Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+2
View File
@@ -123,6 +123,7 @@ public:
int op_declared (const char* op) const;
int decl_name_map(const RadNameMap* m);
int declare_logits(rad_buf b);
int declare_scores(rad_buf hidden, rad_weight table);
int declare_pooled(rad_buf b);
int declare_plugin_words(int64_t max_words);
int declare_drafter(const RadDrafterDecl* d);
@@ -131,6 +132,7 @@ public:
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo);
int drafter_short_block(int64_t block);
int drafter_tree(rad_buf parents);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
+83 -5
View File
@@ -1134,6 +1134,30 @@ int Builder::decl_name_map(const RadNameMap* m) {
/* The buffer the core samples from. A second call is refused rather than winning: a target and
* its drafter declaring into one builder (spec §10) both have logits, and keeping the second would
* sample the draft distribution. The drafter's logits are reached through its scope. */
int Builder::declare_scores(rad_buf hidden, rad_weight table) {
if (finished_) { err(RAD_E_STATE, "declare_scores after declare finished"); return RAD_E_STATE; }
if (hidden == RAD_NULL_HANDLE || (size_t)hidden >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_scores: %u is not a declared buffer", (unsigned)hidden);
return RAD_E_INVAL;
}
if (table == RAD_NULL_HANDLE || (size_t)table >= prog_.weights.size()) {
err(RAD_E_INVAL, "declare_scores: %u is not a declared weight", (unsigned)table);
return RAD_E_INVAL;
}
const RadBufDecl& h = prog_.buffers[hidden].decl;
const auto& w = prog_.weights[table];
if (h.dtype != RAD_BF16 || h.rank != 2 || w.decl.dtype != RAD_BF16 || w.decl.rank != 2 ||
w.decl.shape[1] != h.shape[1]) {
err(RAD_E_INVAL, "declare_scores: the hidden rows ('%s') and the table ('%s') must be bf16 "
"[rows, n_embd] and [n_vocab, n_embd]", prog_.buffers[hidden].name.c_str(),
w.name.c_str());
return RAD_E_INVAL;
}
prog_.score_hidden = hidden;
prog_.score_table = table;
return RAD_OK;
}
int Builder::declare_logits(rad_buf b) {
if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; }
if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
@@ -1943,7 +1967,10 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
int64_t block = d->block;
if (d->kind == RAD_DRAFT_BLOCK) {
if (block == 0) block = (int64_t)d->depth + 1;
if (block < 2 || block < (int64_t)d->depth || block > (int64_t)d->depth + 1) {
/* A tree's (rad_drafter_tree) node count is not its block's draft count: more nodes
* than draft positions (a wider tree) or fewer (a block longer than the tree is deep on
* most steps). Checked at finish, once the tree is or is not declared. */
if (block < 2) {
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs "
"over the last %d rows of the block, so the block is either %d rows "
"(the anchor predicts nothing) or %d (it does).",
@@ -2077,17 +2104,48 @@ int Builder::drafter_short_block(int64_t block) {
}
const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1;
const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */
if (block >= full || block - lead < 1) {
/* A tree (rad_drafter_tree, declared first) grows a tree of its own over the shorter pass, up
* to block - 1 nodes whatever its own node count, so it needs only two rows. */
if (prog_.drafter_tree ? (block < 2 || block >= full) : (block >= full || block - lead < 1)) {
err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter "
"than the drafter's own (%lld) and still propose a token (more than %lld "
"rows).", prog_.drafter_name.c_str(), (long long)block, (long long)full,
(long long)lead);
"than the drafter's own (%lld) and still propose a token (%s %lld rows).",
prog_.drafter_name.c_str(), (long long)block, (long long)full,
prog_.drafter_tree ? "at least" : "more than",
(long long)(prog_.drafter_tree ? 2 : lead));
return RAD_E_INVAL;
}
prog_.drafter_short_block = block;
return RAD_OK;
}
/* A block drafter whose proposal is a tree (rad_builder.h). */
int Builder::drafter_tree(rad_buf parents) {
if (finished_) {
err(RAD_E_STATE, "drafter_tree after declare finished");
return RAD_E_STATE;
}
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
err(RAD_E_STATE, "drafter_tree: %s. Only a BLOCK drafter's one pass proposes every node at "
"once; declare it with rad_declare_drafter first.",
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
: "the declared drafter is a SERIAL head");
return RAD_E_STATE;
}
if (parents == RAD_NULL_HANDLE || (size_t)parents >= prog_.buffers.size()) {
err(RAD_E_INVAL, "drafter_tree '%s': parents buffer %u is not a declared buffer",
prog_.drafter_name.c_str(), (unsigned)parents);
return RAD_E_INVAL;
}
if (prog_.buffers[parents].decl.dtype != RAD_I32) {
err(RAD_E_DTYPE, "drafter_tree '%s': parents buffer '%s' is not i32",
prog_.drafter_name.c_str(), prog_.buffers[parents].name.c_str());
return RAD_E_DTYPE;
}
prog_.drafter_tree = true;
prog_.drafter_parents = parents;
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -2442,6 +2500,16 @@ int Builder::finish() {
w.source.c_str(), rad_dtype_name(w.decl.dtype));
}
if (prog_.drafter.kind == RAD_DRAFT_BLOCK && !prog_.drafter_tree &&
(prog_.drafter.block < prog_.drafter.depth ||
prog_.drafter.block > (int64_t)prog_.drafter.depth + 1))
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs over the "
"last %d rows of the block, so the block is either %d rows (the anchor "
"predicts nothing) or %d (it does); only a tree (rad_drafter_tree) "
"proposes a node count other than its block's drafts.",
prog_.drafter_name.c_str(), (long long)prog_.drafter.block, prog_.drafter.depth,
prog_.drafter.depth, prog_.drafter.depth + 1, prog_.drafter.depth);
if (instances_) finish_instances();
fill_tune_instances();
finish_weight_uses();
@@ -2599,6 +2667,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) {
return B(b)->declare_logits(logits);
}
int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_scores(hidden, table);
}
int rad_declare_pooled(RadBuilder* b, rad_buf pooled) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_pooled(pooled);
@@ -2630,6 +2703,11 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
}
int rad_drafter_tree(RadBuilder* b, rad_buf parents) {
if (!b) return RAD_E_INVAL;
return B(b)->drafter_tree(parents);
}
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
+4 -1
View File
@@ -19,6 +19,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <atomic>
#include <climits>
#include <unordered_map>
#include <cstring>
@@ -650,7 +651,9 @@ std::string dump_graph_json(const Program& p) {
j["geometry"] = o.base.str();
j["ranged"] = o.ranged_key;
if (!o.ranged_key.empty()) { j["range_lo"] = o.range_lo; j["range_hi"] = o.range_hi; }
j["issued"] = o.issued;
/* Read through an atomic_ref: the step path stores this flag from the engine thread
* (Ctx::flush_issued); a plain read here would race it. */
j["issued"] = std::atomic_ref<const bool>(o.issued).load(std::memory_order_relaxed);
j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op));
json ws = json::array();
+7 -3
View File
@@ -175,8 +175,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
/* An imported quantisation is served by the family's quantised plugin (startup.h). A plugin
* that declines imports (rad_arch_serves_imports) is left out of the family here: neither
* counted as a second quantised plugin nor picked as the only one. */
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
* counted as a second quantised plugin nor picked as the only one. Block-scaled fp8 reads
* stock weight by weight, so a family with no plugin claiming it is served the same way: the
* plugin declares each weight at the encoding it finds (Qwen3.8-Flash-Next-FP8: fp8 routed
* experts beside bf16 linears, served by qwen4exp_fp8). */
const bool stock = quant == "fp8_e4m3";
if ((imported || stock) && !arch_id.empty() && out->arch_plugin.empty()) {
std::vector<const Plugin*> fam, quantised;
for (const Plugin& p : r.plugins())
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) {
@@ -198,7 +202,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
out->arch_version = pick->version;
out->arch_id = pick->arch_id;
out->arch_quant = pick->arch_quant;
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
RAD_INFO("quantisation '%s' is read weight by weight; '%s' serves it as %s",
quant.c_str(), pick->name.c_str(),
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
}
+3 -2
View File
@@ -68,8 +68,9 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
* plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of
* both counts. `out->arch_quant` is the chosen descriptor, which a container
* converted from it records. */
* both counts. Block-scaled fp8 (`fp8_e4m3`) that no plugin of the family claims is served the
* same way, since its weights read stock. `out->arch_quant` is the chosen descriptor, which a
* container converted from it records. */
int rad_tools_load_plugins(const std::string& radiance_home,
const std::vector<std::string>& hierarchy,
const std::string& arch_id,
+37 -9
View File
@@ -110,7 +110,10 @@ static const Flag g_flags[] = {
" host memory at load, pinned for the cards to read\n"
" (locked, where only a host kernel reads it); disk reads\n"
" its rows from the container on the host. auto takes the\n"
" first of the three that holds it" },
" first of the three that holds it. ram=DIR makes the\n"
" pinned copy a file in DIR (a tmpfs) mapped shared, so\n"
" two engines on separate cards hold one table: the\n"
" first fills it, the last to exit deletes it" },
{ "--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" },
@@ -180,8 +183,9 @@ static const Flag g_flags[] = {
" with no draft head is unaffected -- auto resolves to 0." },
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
"from N decoding sequences on (0 never, the default): the\n"
"long block pays at one sequence, the short one at many" },
"from N decoding sequences on (0 never): the long block pays\n"
"at one sequence, the short one at many. auto (the default):\n"
"never for a chain, from 2 for a tree drafter" },
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter or DFlash2's walk\n"
" samples each proposal from its own shortlist and the sampler\n"
" couples the target's draw to it: more accepted drafts on sampled\n"
@@ -585,10 +589,20 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
std::string share_dir;
if (!emb && !std::strncmp(v, "ram=", 4)) {
share_dir = v + 4;
if (share_dir.empty()) {
RAD_ERR("--ngram-placement ram= needs a directory: ram=DIR, the tmpfs that "
"holds the shared table");
return RAD_E_INVAL;
}
p = TablePlacement::Ram;
} else if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram, ram=DIR or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
if (!emb) c->ngram_share_dir = share_dir;
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
@@ -727,7 +741,11 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--draft-short-from")) { if (!num(0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL; }
else if (S("--draft-short-from")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->draft_short_from = -1;
else if (!parse_int(a.c_str(), v, 0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL;
}
else if (S("--draft-coupling")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "off")) c->draft_coupling = false;
@@ -751,7 +769,14 @@ int config_parse(int argc, char** argv, Config* c) {
}
else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; }
else if (S("--port")) { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; }
else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; }
else if (S("--api-key")) {
if (!(v = need(i))) return RAD_E_INVAL;
/* An empty key is no key: --api-key "" or --api-key "$UNSET_VAR" must not start a
* server that looks guarded and answers everything keyless. */
if (!*v) { RAD_ERR("--api-key takes a non-empty key; an empty value guards nothing");
return RAD_E_INVAL; }
c->api_key = v;
}
else if (S("--served-model-name")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; }
@@ -1166,7 +1191,9 @@ const ShowRow kShow[] = {
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--ngram-placement", [](const Config& c) {
std::string v = table_placement_name(c.ngram_placement);
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-mib", [](const Config& c) {
@@ -1202,7 +1229,8 @@ const ShowRow kShow[] = {
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--draft-short-from", [](const Config& c) {
return c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
return c.draft_short_from < 0 ? std::string("auto")
: c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
{ "--host", [](const Config& c) { return c.host; } },
+103 -26
View File
@@ -3644,6 +3644,43 @@ void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
return p;
}
/* Locks [p, p + len) in pieces of at most kPinPiece for every card, each mapped on the cards at
* its host address. On failure sets the device error for `who` (asked for `bytes`), unlocks what
* was locked and returns false; the mapping stays the caller's to unmap. */
bool lock_pieces(char* p, int64_t len, int64_t bytes, std::vector<hsa_agent_t>& cards,
const char* who) {
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
int done = 0;
for (; done < pieces; ++done) {
const int64_t off = (int64_t)done * kPinPiece;
const int64_t n = std::min(kPinPiece, len - off);
void* on_card = nullptr;
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
(int)cards.size(), G().host_fine, 0,
&on_card);
if (st != HSA_STATUS_SUCCESS) {
device_set_error("%s(%s): locking piece %d of %d (%s at +%s): %s", who,
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
humanb(off).c_str(), hsa_why(st));
break;
}
if (on_card != p + off) {
++done;
device_set_error("%s(%s): piece %d of %d is mapped on the cards at %p, not "
"at its host address %p, so the pieces are not one range there, "
"although the kernel driver reports the SVM API that maps a lock in "
"place",
who, humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
break;
}
}
if (done < pieces) {
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
return false;
}
return true;
}
void* pin_pieces(int64_t bytes) {
std::vector<hsa_agent_t> cards;
for (const Dev& d : G().dev) cards.push_back(d.agent);
@@ -3672,33 +3709,61 @@ void* pin_pieces(int64_t bytes) {
}
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
int done = 0;
for (; done < pieces; ++done) {
const int64_t off = (int64_t)done * kPinPiece;
const int64_t n = std::min(kPinPiece, len - off);
void* on_card = nullptr;
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
(int)cards.size(), G().host_fine, 0,
&on_card);
if (st != HSA_STATUS_SUCCESS) {
device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s",
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
humanb(off).c_str(), hsa_why(st));
break;
}
if (on_card != p + off) {
++done;
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
"at its host address %p, so the pieces are not one range there, "
"although the kernel driver reports the SVM API that maps a lock in "
"place",
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
break;
}
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
::munmap(p, (size_t)len);
return nullptr;
}
if (done < pieces) {
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
std::lock_guard<std::mutex> lk(g_pinned_mu);
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
return p;
}
/* pin_pieces over a shared file mapping instead of private anonymous memory: the pages are the
* file's (a tmpfs file other processes map too) and the lock takes them in place. The file maps
* onto a 2 MiB boundary inside a reservation made with one alignment extra, then the ends are
* trimmed. MADV_HUGEPAGE is advised but shmem follows shmem_enabled, not it. A tmpfs page is
* swappable until the lock pins it, so MLOCK_ONFAULT keeps the pages in memory meanwhile; a
* refusal (the memlock limit) costs only that. */
void* pin_pieces_file(int64_t bytes, int fd, int64_t foff) {
std::vector<hsa_agent_t> cards;
for (const Dev& d : G().dev) cards.push_back(d.agent);
if (!svm_in_place()) {
device_set_error("rad_dev_map_file(%s): a file range is pinned in place only through the "
"kernel driver's SVM API, which this host lacks, so ram=DIR needs it",
humanb(bytes).c_str());
return nullptr;
}
const int64_t align = RAD_ALIGN_POOL;
const int64_t len = align_up(bytes, 4096);
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (m == MAP_FAILED) {
device_set_error("rad_dev_map_file(%s): mmap: %s", humanb(bytes).c_str(),
std::strerror(errno));
return nullptr;
}
const uintptr_t lo = (uintptr_t)m;
const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1);
if (::mmap((void*)at, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd,
(off_t)foff) == MAP_FAILED) {
device_set_error("rad_dev_map_file(%s): mmap of the file at +%s: %s", humanb(bytes).c_str(),
humanb(foff).c_str(), std::strerror(errno));
::munmap(m, (size_t)(len + align));
return nullptr;
}
if (at > lo) ::munmap(m, at - lo);
if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at);
char* const p = (char*)at;
if (len >= ((int64_t)2 << 20)) (void)::madvise(p, (size_t)len, MADV_HUGEPAGE);
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
if (::mlock2(p, (size_t)len, MLOCK_ONFAULT) != 0)
RAD_WARN("device: the shared file range %p (%s) could not be locked against swap (mlock2: "
"%s)", (void*)p, humanb(len).c_str(), std::strerror(errno));
prefer_numa_node(p, len, current_card_numa_node());
if (!lock_pieces(p, len, bytes, cards, "rad_dev_map_file")) {
::munmap(p, (size_t)len);
return nullptr;
}
@@ -3762,6 +3827,17 @@ void* a_alloc(int64_t bytes, int kind) {
return p;
}
void* a_map_file(int fd, int64_t foff, int64_t bytes) {
if (fd < 0 || foff < 0 || bytes <= 0) {
device_set_error("rad_dev_map_file(%d, %lld, %lld): a file, a non-negative offset and a "
"positive size are needed", fd, (long long)foff, (long long)bytes);
return nullptr;
}
void* p = pin_pieces_file(bytes, fd, foff);
note_alloc(p, bytes, RAD_MEM_HOST_MAPPED);
return p;
}
/* Every free invalidates locate()'s cache first. */
void (*g_hip_free)(void*, int) = nullptr;
void a_free(void* p, int kind) {
@@ -3842,6 +3918,7 @@ const DeviceBackend* aql_backend_if_present(void) {
g_hip_host_ptr = hip->host_ptr;
g_hip_device_ptr = hip->device_ptr;
g_aql.alloc = a_alloc;
g_aql.map_file = a_map_file;
g_aql.free = a_free;
g_aql.host_ptr = a_host_ptr;
g_aql.device_ptr = a_device_ptr;
+11
View File
@@ -135,6 +135,14 @@ extern "C" int64_t rad_xp_behind(int device);
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
extern "C" void rad_dev_free_uncached(void* p);
/* [foff, foff + bytes) of the open file `fd`, mapped MAP_SHARED and pinned for every card as a
* RAD_MEM_HOST_MAPPED allocation is: one range at the same address on host and cards. For a table
* that engines on separate cards share through a tmpfs file (format/table_share.h). `foff` is a
* multiple of 2 MiB and the file holds the whole range. Freed with rad_dev_free(p,
* RAD_MEM_HOST_MAPPED), which unpins and unmaps and leaves the file alone. Null with the reason in
* rad_dev_last_error() on a backend without it or a failure. */
extern "C" void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes);
/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
* host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
* the device runs it back to back however long the host took to submit it. For timing a batch of
@@ -339,6 +347,9 @@ struct DeviceBackend {
/* ---- rad_event_dma; null on a backend with no DMA queue. */
int (*event_dma)(RadEvent e, RadStream s, uint32_t** word);
/* ---- see rad_dev_map_file. Null on a backend with no pinned host memory to map a file into. */
void* (*map_file)(int fd, int64_t foff, int64_t bytes);
};
+14
View File
@@ -648,6 +648,20 @@ void* rad_dev_alloc_uncached(int64_t bytes) {
if (const auto f = dev()->alloc_uncached) return f(bytes);
return nullptr;
}
void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
const auto f = dev()->map_file;
if (!f) {
rad::device_set_error("rad_dev_map_file: the %s backend has no pinned host memory to map a "
"file into", dev()->name);
return nullptr;
}
void* p = f(fd, foff, bytes);
if (p) {
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
}
return p;
}
void rad_dev_free_uncached(void* p) {
if (const auto f = dev()->free_uncached) f(p);
}
+184 -56
View File
@@ -110,6 +110,8 @@ Engine::~Engine() {
table_copies_.clear();
for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED);
card_copies_.clear();
for (TableShare& t : table_shares_) table_share_close(&t);
table_shares_.clear();
rad_tools_registry().close();
}
@@ -554,6 +556,14 @@ int Engine::step_loop() {
pipelining_ = !cfg_.kld() && !embedding_ &&
(serial_drafting() || block_drafting() || cfg_.n_spec <= 0);
early_ids_ = !cfg_.kld() && !embedding_;
/* A tree's acceptance moves K and V on the card behind the step issued ahead. The KL mode
* drafts nothing and an embedding model declares no drafter, so no server reaches this today;
* it keeps a tree from running unverified should another path turn pipelining off. */
if (tree_ && !pipelining_) {
RAD_ERR("speculation: drafter '%s' proposes trees, which are verified only on steps issued "
"ahead, and this server issues none; ask the plugin for a chain", drafter_.name);
return fail_loop(RAD_E_UNSUPPORTED);
}
const bool t_on = (int)log_level() >= (int)Log::Debug;
/* The next step's forward pass when already issued behind the previous step, before its
* readback (Scheduler::step_next). */
@@ -789,46 +799,11 @@ int Engine::step_loop() {
return fail_loop(st);
}
/* Snapshot after the step that produced the state: the chunker ended this chunk at the
* checkpoint position, so copy 0 holds exactly that state. The copy to the host slot is
* issued before collect_step's readback and before any step issued ahead, which orders the
* next write of the state after it. Under the scheduler's lock, as the restore. */
bool any_save = false;
for (const StepEntry& e : plan.e)
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; }
if (any_save) {
const int ss = sched_.locked([&]() -> int {
for (const StepEntry& e : plan.e) {
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
/* The window behind the checkpoint position. The chunk ending there still
* holds it, so a miss is a broken invariant; skipping would commit a slot
* holding another sequence's pages. */
if (ranks_[0]->kv.has_window_snapshot() &&
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
&ckpt_win_)) {
RAD_ERR("sequence %llu: the window behind checkpoint %d is not held",
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
return RAD_E_STATE;
}
for (auto& rk : ranks_) {
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
(int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(),
&ckpt_win_);
if (s < 0) {
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
"%d: %s", rk->index, (unsigned long long)e.seq,
(int)e.ckpt_slot, rad_strerror(s));
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
return s;
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
}
return RAD_OK;
});
/* Snapshot after the step that produced the state (save_checkpoints). Where a block
* drafter's window rides in the snapshot, its context pass must store the step's rows
* first, so the card's driver saves right behind that pass instead. */
if (!(block_drafting() && drafter_snap_)) {
const int ss = save_checkpoints();
if (ss < 0) return fail_loop(ss);
}
@@ -903,6 +878,7 @@ int Engine::step_loop() {
res.lp = so.lp.data();
res.first_row = so.first_row.data();
}
res.path = so.path.empty() ? nullptr : so.path.data();
st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
@@ -1165,6 +1141,57 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
return RAD_OK;
}
/* Snapshot after the step that produced the state. Linear state is what the chunk's last token
* leaves, so the chunker ended the chunk at the checkpoint and copy 0 holds exactly that state; a
* window snapshot is the window's rows behind the checkpoint, which may lie inside the chunk
* (plan_chunk) and are still held when it ends. The copy to the host slot is issued before
* collect_step's readback and before any step issued ahead, which orders the next write of the
* state after it. Under the scheduler's lock, as the restore. A block drafter's window in the
* snapshot (drafter_snap_) is saved behind the drafter's context pass (issue_block_drafter),
* which writes only the drafter's groups. */
int Engine::save_checkpoints() {
const StepPlan& plan = sched_.plan();
bool any_save = false;
for (const StepEntry& e : plan.e)
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; }
if (any_save) {
const int ss = sched_.locked([&]() -> int {
for (const StepEntry& e : plan.e) {
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
/* The window behind the checkpoint position. This step's chunk reaches it, and
* a window slides only from a step's first query, so a miss is a broken
* invariant; skipping would commit a slot holding another sequence's pages. */
if (ranks_[0]->kv.has_window_snapshot() &&
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
&ckpt_win_)) {
RAD_ERR("sequence %llu: the window behind checkpoint %d is not held",
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
return RAD_E_STATE;
}
for (auto& rk : ranks_) {
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
(int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(),
&ckpt_win_);
if (s < 0) {
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
"%d: %s", rk->index, (unsigned long long)e.seq,
(int)e.ckpt_slot, rad_strerror(s));
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
return s;
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
}
return RAD_OK;
});
if (ss < 0) return ss;
}
return RAD_OK;
}
/* Scored rows (Request::token_scores): the logits row at a scored prompt's last position, copied
* to the host before the sampler can rewrite it in place. stage_scored_rows picks the rows while
* every rank is parked; issue_scored_rows copies one row per rank stream ahead of its sampler;
@@ -1172,6 +1199,8 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
* row is copied (512 KB at a 128K vocabulary), which is cheaper than one copy per id. */
int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) {
score_rows_.clear();
score_only_ = false;
score_ids_.clear();
if (embedding_) return RAD_OK;
for (size_t i = 0; i < plan.e.size(); ++i) {
const Request* r = plan.e[i].req;
@@ -1180,16 +1209,35 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) {
}
if (score_rows_.empty()) return RAD_OK;
const int64_t n = (int64_t)score_rows_.size();
/* A scored step reads back the hidden rows and the candidates' table rows instead of whole
* logits rows (BatchBuilder set the flag on the same facts). */
const RadBatch* b0 = sched_.batch_for(0);
score_only_ = b0 && b0->score_only;
if (score_only_) {
const Program& p = ranks_[0]->program;
score_embd_ = p.buffers[p.score_hidden].decl.shape[1];
for (const auto& sr : score_rows_)
for (int32_t t : sr.second->tokens) score_ids_.push_back(t);
std::sort(score_ids_.begin(), score_ids_.end());
score_ids_.erase(std::unique(score_ids_.begin(), score_ids_.end()), score_ids_.end());
}
for (auto& rk : ranks_) {
if (n <= rk->score_rows_cap) continue;
const int64_t width = rk->sampler.config().n_vocab_local;
/* In floats: n logits rows, or the bf16 hidden and table rows of a scored step. */
int64_t rows = n;
if (score_only_) {
const int64_t need = ((n + (int64_t)score_ids_.size()) * score_embd_ + 1) / 2;
rows = std::max(rows, (need + width - 1) / width);
}
if (rows <= rk->score_rows_cap) continue;
if (ranks_.size() > 1) RAD_TRY(rad_dev_set(rk->device));
if (rk->score_host) rad_dev_free(rk->score_host, RAD_MEM_HOST_PINNED);
const int64_t width = rk->sampler.config().n_vocab_local;
rk->score_host = static_cast<float*>(
rad_dev_alloc(n * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED));
rk->score_rows_cap = rk->score_host ? n : 0;
rad_dev_alloc(rows * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED));
rk->score_rows_cap = rk->score_host ? rows : 0;
if (!rk->score_host) {
RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)n);
RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)rows);
return RAD_E_NOMEM;
}
}
@@ -1199,8 +1247,27 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) {
int Engine::issue_scored_rows(Rank& r) {
const int64_t width = r.sampler.config().n_vocab_local;
const char* logits = static_cast<const char*>(r.ctx.buf_ptr(r.program.logits_buf));
char* const logits = static_cast<char*>(r.ctx.buf_ptr(r.program.logits_buf));
if (!logits || !r.score_host) return RAD_E_STATE;
if (score_only_) {
/* The plugin left the hidden rows and ran no lm_head: read back each scored row's hidden
* state and the table rows its candidates name, then zero the logits rows the sampler is
* about to read, so the token it draws (and the caller discards) is drawn from defined
* values. One rank (BatchBuilder). */
const int64_t rb = score_embd_ * (int64_t)sizeof(uint16_t);
const char* hid = static_cast<const char*>(r.ctx.buf_ptr(r.program.score_hidden));
const char* tab = static_cast<const char*>(r.ctx.weight_ptr(r.program.score_table));
if (!hid || !tab) return RAD_E_STATE;
char* host = reinterpret_cast<char*>(r.score_host);
const int64_t n = (int64_t)score_rows_.size();
for (int64_t k = 0; k < n; ++k)
RAD_TRY(rad_memcpy_async(host + k * rb, hid + (int64_t)score_rows_[(size_t)k].first * rb,
rb, r.ctx.stream()));
for (size_t j = 0; j < score_ids_.size(); ++j)
RAD_TRY(rad_memcpy_async(host + (n + (int64_t)j) * rb, tab + (int64_t)score_ids_[j] * rb,
rb, r.ctx.stream()));
return rad_memset_async(logits, 0, n * width * (int64_t)sizeof(float), r.ctx.stream());
}
for (size_t k = 0; k < score_rows_.size(); ++k)
RAD_TRY(rad_memcpy_async(r.score_host + (int64_t)k * width,
logits + (int64_t)score_rows_[k].first * width * 4,
@@ -1208,6 +1275,18 @@ int Engine::issue_scored_rows(Rank& r) {
return RAD_OK;
}
/* A scored step's logits: the dot product of a row's hidden state with each candidate's table row,
* bf16 operands widened exactly and summed in f64, then rounded once to f32. */
static float score_dot(const uint16_t* h, const uint16_t* w, int64_t n) {
double acc = 0.0;
for (int64_t i = 0; i < n; ++i) {
const float a = __builtin_bit_cast(float, (uint32_t)h[i] << 16);
const float b = __builtin_bit_cast(float, (uint32_t)w[i] << 16);
acc += (double)a * (double)b;
}
return (float)acc;
}
int Engine::collect_scored_rows() {
if (score_rows_.empty()) return RAD_OK;
/* collect_step's wait fences rank 0's stream; every other rank's copies are fenced here. */
@@ -1216,6 +1295,23 @@ int Engine::collect_scored_rows() {
RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream()));
}
if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device));
if (score_only_) {
const uint16_t* host = reinterpret_cast<const uint16_t*>(ranks_[0]->score_host);
const int64_t n = (int64_t)score_rows_.size();
for (int64_t k = 0; k < n; ++k) {
TokenScores& ts = *score_rows_[(size_t)k].second;
ts.logits.assign(ts.tokens.size(), 0.0f);
for (size_t j = 0; j < ts.tokens.size(); ++j) {
const auto it = std::lower_bound(score_ids_.begin(), score_ids_.end(), ts.tokens[j]);
const int64_t c = it - score_ids_.begin();
ts.logits[j] = score_dot(host + k * score_embd_, host + (n + c) * score_embd_,
score_embd_);
}
}
score_rows_.clear();
score_only_ = false;
return RAD_OK;
}
for (size_t k = 0; k < score_rows_.size(); ++k) {
TokenScores& ts = *score_rows_[k].second;
ts.logits.assign(ts.tokens.size(), 0.0f);
@@ -1236,10 +1332,11 @@ int Engine::collect_scored_rows() {
/* One sampled row's logprobs into the step's table, sized on first use. A non-finite row
* (RAD_E_INVAL) is left at token -1, and the scheduler fails only that request. A row outside the
* step, or never staged for logprobs, is an engine error. */
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token, int32_t at) {
if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
TokenLogprobs& lp = so.lp[(size_t)row];
if (at < 0) at = row;
if (row < 0 || row >= so.n_rows || at >= so.n_rows) return RAD_E_STATE;
TokenLogprobs& lp = so.lp[(size_t)at];
const int s = ranks_[0]->sampler.logprobs_for(row, token, &lp);
if (s == RAD_E_INVAL) { lp = TokenLogprobs{}; return RAD_OK; }
return s;
@@ -1253,6 +1350,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.accepted.assign(plan.e.size(), 0);
so.eos.assign(plan.e.size(), 0);
so.lp.clear();
so.path.clear();
if (so.n_rows <= 0) return RAD_OK;
so.rows.resize((size_t)so.n_rows);
@@ -1303,7 +1401,16 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
if (!e.req) continue;
int32_t out[RAD_SCHED_MAX_SPEC + 1] = { 0 };
int32_t acc = 0;
RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out, &acc));
/* A tree step verifies every proposal as a tree (a chain one as the chain-shaped
* tree), as the card's acceptance does; `path` names the accepted nodes. */
int32_t path[RAD_SCHED_MAX_SPEC] = { 0 };
const bool tree = plan.spec_is_tree;
if (tree)
RAD_TRY(accept_tree(e.draft, e.draft_parent, e.n_spec,
&so.rows[(size_t)so.first_row[i]], out, path, &acc));
else
RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out,
&acc));
/* Truncated at the first end-of-generation token, so `accepted` and `token` (which
* drive the KV rollback, the conv cursor and the emitted text) say how far the step
@@ -1314,11 +1421,19 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.accepted[i] = acc;
so.token[i] = out[acc];
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
if (tree) {
if (so.path.empty()) so.path.assign(plan.e.size() * RAD_SCHED_MAX_SPEC, 0);
for (int32_t t = 0; t < acc; ++t) so.path[i * RAD_SCHED_MAX_SPEC + t] = path[t];
}
/* Each emitted token's logprobs come from its own row, the distribution it was drawn
* from. */
* from: on a tree, the row of the node it follows. They are filed as the entry's j-th
* emitted token (StepResult::lp), whichever row they came from. */
if (e.req && e.req->sp.n_probs >= 0)
for (int32_t j = 0; j <= acc; ++j)
RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
for (int32_t j = 0; j <= acc; ++j) {
const int32_t from = tree && j > 0 ? path[j - 1] : j;
RAD_TRY(row_logprobs(so, so.first_row[i] + from, out[j],
so.first_row[i] + j));
}
/* Advance the grammar over every emitted token, accepted drafts included, up to the
* truncated `acc`, so it sees exactly what the client sees. */
if (e.req)
@@ -2275,8 +2390,8 @@ int Engine::run_server() {
s.experts.n_experts = n_expert;
s.experts.tier.assign((size_t)n_layer * (size_t)n_expert, (uint8_t)Tier::VRAM);
/* The live tier when the heat engine runs, else the plan's (where a unit started).
* HeatEngine::tier is a plain vector written by the dispatch thread at step
* boundaries, so a racing read sees either side of a single store. */
* tier_published is the HTTP-readable mirror HeatEngine::set_tier keeps; reading
* the dispatch thread's own tier_ here would be a data race. */
const HeatEngine& heat = ranks_[0]->heat;
const bool live_tier = heat.enabled();
s.experts.heat_enabled = live_tier;
@@ -2285,7 +2400,7 @@ int Engine::run_server() {
for (size_t u = 0; u < p.units.size(); ++u) {
const MoveUnit& mu = p.units[u];
if (mu.expert < 0 || mu.layer < 0) continue;
const Tier t = live_tier ? heat.tier((int32_t)u) : mu.tier;
const Tier t = live_tier ? heat.tier_published((int32_t)u) : mu.tier;
s.experts.tier[(size_t)mu.layer * (size_t)n_expert + (size_t)mu.expert]
= (uint8_t)t;
/* Count residency over units, not plane cells: the plane is a rectangle a
@@ -2352,6 +2467,12 @@ int Engine::run_server() {
s.link.h2d_bytes = s.link.d2h_bytes = s.link.ssd_reads = 0;
s.link.ssd_bytes = s.link.prefetched = s.link.prefetch_bytes = 0;
s.link.stream_bytes = s.link.staged_bytes = 0;
s.link.kv_stream_bytes = 0;
s.link.kv_streaming = cfg_.kv_resident > 0; /* zeroed here if the arch refused it */
/* The ring's depth, not the flag: KVStreamStats::resident_blocks sums the device pool
* of every group that really runs a window under its context, so this is zero when
* --kv-resident was asked for and nothing streams anyway. */
s.link.kv_stream_active = ranks_[0]->kv.stream_stats().resident_blocks > 0;
for (const auto& rk : ranks_) {
const MoverStats rms = rk->mover.stats();
s.link.h2d_bytes += (int64_t)rms.h2d_bytes;
@@ -2363,6 +2484,13 @@ int Engine::run_server() {
s.link.staged_bytes += (int64_t)rms.staged_bytes;
if (rk->heat.enabled()) s.link.stream_bytes += (int64_t)rk->heat.stats().stream_bytes;
}
/* KV streaming: only rank 0's resolve counters are read -- every rank sees the same
* misses by design -- so the figure takes the world factor to reach all cards, the
* way the summed move rows sit there. The counters ride the step's ctl read; nothing
* here costs a step. */
if (s.link.kv_streaming)
s.link.kv_stream_bytes =
(int64_t)ranks_[0]->kv.stream_stats().bytes_in * (int64_t)ranks_.size();
}
};
+44 -5
View File
@@ -33,6 +33,7 @@
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include "format/table_share.h"
#include "lora/adapter.h"
#include "lora/slots.h"
@@ -230,7 +231,7 @@ private:
int64_t host_late);
/* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
* shared by every rank. Locked for the host gather, or pinned for a device kernel to read
* over the link (`card`). */
* over the link (`card`); with ram=DIR the pinned copy is a file other engines map too. */
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
std::string* why);
/* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
@@ -240,6 +241,9 @@ private:
* the ranks that read them are gone. */
std::vector<TableCopy> table_copies_;
std::vector<void*> card_copies_;
/* The files behind the card copies made under --ngram-placement ram=DIR. Closed after the
* copies are freed, because the holder that leaves last deletes the file. */
std::vector<TableShare> table_shares_;
std::vector<std::pair<const void*, void*>> table_copy_of_;
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
* rank's planner in place of the container's activation profile. */
@@ -268,6 +272,9 @@ private:
/* The ids' copy recorded tok_end_ ahead of the drafter's passes: collect_step waits for
* it alone, and the step loop for step_end_ after the commit. */
bool early = false;
/* [n_seq][RAD_SCHED_MAX_SPEC] on a tree step (StepPlan::spec_is_tree): each entry's
* accepted nodes in commit order (accept_tree's path). Empty on a chain step. */
std::vector<int32_t> path;
};
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
@@ -308,6 +315,12 @@ private:
* Written by the scheduler thread while the ranks are parked, read by them during the step,
* consumed by collect_step. */
std::vector<std::pair<int32_t, TokenScores*>> score_rows_;
/* A scored step (RadBatch::score_only): the plugin ran no lm_head, and the candidates' logits
* come from the hidden rows and the head table's rows at `score_ids_` (every scored row's
* candidates, sorted and unique), both read back into `score_host`. */
bool score_only_ = false;
std::vector<int32_t> score_ids_;
int64_t score_embd_ = 0;
int stage_scored_rows(const StepPlan& plan, const StepOut& so);
int issue_scored_rows(Rank& r);
int collect_scored_rows();
@@ -341,7 +354,9 @@ private:
* records tok_end_, so the wait for the ids skips the passes (StepOut::early). */
int collect_issue(StepOut& so, bool fence = false);
int collect_step(const RadBatch* b, StepOut& so);
int row_logprobs(StepOut& so, int32_t row, int32_t token);
/* `row`'s logprobs for `token`, filed at `at` (default `row`): a tree verify emits a token from
* its parent node's row but files it as the entry's j-th emitted token. */
int row_logprobs(StepOut& so, int32_t row, int32_t token, int32_t at = -1);
/* The step's end on the card: after its last draft pass and the host readbacks, before the
* step issued ahead. The engine waits on this event, not the stream, so the card runs the
* next step while the host commits this one. */
@@ -375,10 +390,12 @@ private:
* string because RadDrafterDecl::name points into the Program. */
RadDrafterDecl drafter_{};
std::string drafter_name_;
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or
* --draft-short-from is 0. */
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or will not
* run it (--draft-short-from 0, or auto for a chain). */
int64_t drafter_short_ = 0;
bool short_on_ = false; /* the short block runs now (block_shape) */
/* --draft-short-from resolved at bring-up (auto: 0 for a chain, 2 for a tree). */
int64_t short_from_ = 0;
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
@@ -475,11 +492,33 @@ private:
* both behind the step before its readback and finish_block_drafter publishes the proposals
* after the commit, so the step can be issued ahead. */
bool block_drafting() const;
/* RadBuildCtx::draft_tree for every declare: decided once in declare() from the plugin's probe
* (RadArchProbe::tree_pays). */
bool draft_tree_ = false;
int block_pass(const RadBatch* db, const char* what, int step);
/* A program's block drafter rides its window in the window snapshot: it stores its context
* in the context pass right behind the trunk step, and the snapshot is saved after that. Only
* where the trunk's window is snapshotted at all (window_snapshots): a full-attention trunk
* takes no snapshot for a drafter's window alone. */
bool drafter_window_snap(const Program& p) const {
return cfg_.n_spec > 0 && p.drafter.kind == RAD_DRAFT_BLOCK && p.drafter.depth > 0 &&
window_snapshots(p, cfg_);
}
/* The drafter's window rides in the window snapshot (KVManager::drafter_window_snapshot), so
* the checkpoint save waits for its context pass (save_checkpoints). */
bool drafter_snap_ = false;
int save_checkpoints();
/* A tree drafter (rad_drafter_tree), driven on the card only: ADV_BTAKE takes its parents,
* ADV_COMPACT moves the accepted path's K and V after the acceptance, and ADV_CTXTREE stages
* the context pass by that path. */
bool tree_ = false;
rad_buf tree_parents_ = 0;
int tree_compact(int rows);
int issue_block_drafter(int step, StepOut& so);
int finish_block_drafter(const StepOut& so);
/* The block and proposal count this step's query pass runs at: the drafter's own, or its short
* block once --draft-short-from sequences decode, back to its own only two below. */
* block once --draft-short-from sequences decode, back to its own two below or at one sequence
* (Scheduler::short_block_on). */
void block_shape(int* block, int* steps);
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
* in the query pass's order, and how many there are (0 when no query pass ran). */
+206 -45
View File
@@ -19,6 +19,7 @@
#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"
@@ -399,15 +400,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());
@@ -419,16 +464,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;
@@ -564,8 +610,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;
@@ -640,7 +721,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 "
@@ -896,6 +977,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. */
@@ -1125,6 +1207,22 @@ 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);
/* 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) {
@@ -1364,7 +1462,14 @@ int Engine::declare() {
drafter_name_ = p0.drafter_name;
drafter_.name = drafter_name_.c_str();
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0
/* 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 "
@@ -1374,14 +1479,23 @@ int Engine::declare() {
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_)
if (drafter_short_ && tree_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), %lld token(s)", (long long)cfg_.draft_short_from,
"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 (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. */
@@ -1610,6 +1724,7 @@ 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();
@@ -1702,9 +1817,9 @@ int Engine::plan() {
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 are not part of the elastic plane the card must hold and the
* pool must have room for them on top of the trunk's spill. Growing the pool here, before
* the split, is what lets a drafter fit beside a trunk that already fills the card. */
* 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;
@@ -1715,10 +1830,9 @@ int Engine::plan() {
return RAD_E_INVAL;
}
if (draft_max > 0) {
/* The pool must hold the drafter on top of the trunk's own spill, so it grows by
* the drafter's bytes and the floor is recomputed against that larger room with
* the drafter taken out of the plane the card places. */
const int64_t add = (align_up(draft_max, MiB) + MiB - 1) / MiB;
/* 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;
@@ -1797,6 +1911,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);
@@ -1882,14 +1997,22 @@ 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:
* decode-hot experts differ, and the pin below keeps them resident. Loaded once, before
* any rank plans, so every rank ranks the same way. */
/* --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();
@@ -3087,22 +3210,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;
@@ -3122,19 +3273,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;
}
@@ -3167,7 +3318,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. */
@@ -3238,7 +3391,8 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both. */
/* 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"
@@ -3265,7 +3419,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());
+88 -7
View File
@@ -175,6 +175,14 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
: rk.ctx.buf_ptr(rk.tok_buf));
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
? drafter_.proposal_pitch : 1;
/* A tree drafter's parents, at the proposal's pitch (rad_drafter_tree). */
if (tree_ && mode == ADV_BTAKE) {
a.par = static_cast<const int32_t*>(rk.ctx.buf_ptr(tree_parents_));
if (!a.par) {
RAD_ERR("drafter '%s': rank %zu has no parents buffer", drafter_.name, i);
return RAD_E_STATE;
}
}
} else {
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
}
@@ -188,6 +196,49 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
return RAD_OK;
}
/* ADV_COMPACT on every rank, against the scheduler's latest build (the tree step just accepted):
* the accepted paths' K and V into place in every paged group. Each rank's pools are its own. */
int Engine::tree_compact(int rows) {
for (size_t i = 0; i < ranks_.size(); ++i) {
Rank& rk = *ranks_[i];
AdvanceArgs a = sched_.advance_args((int)i);
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
a.mode = 0;
a.st = rk.step_slots;
const Program& p = rk.program;
for (size_t g = 1; g < p.kv_groups.size() && (int)g < a.n_groups; ++g) {
const int kind = p.kv_groups[g].decl.kind;
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) continue;
const KVPoolBinding* b = rk.ctx.kv_binding((uint32_t)g);
if (!b || !b->base || b->rank != 4) continue; /* a zero group on this rank */
const int bits = rad_dtype_bits(b->dtype);
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
int32_t layers = 0;
for (int32_t s : b->layer_slot) layers += s >= 0;
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
return RAD_E_UNSUPPORTED;
}
if (a.n_pool >= kAdvMaxPools) {
RAD_ERR("speculation: more than %d paged KV groups for a tree's acceptance",
(int)kAdvMaxPools);
return RAD_E_UNSUPPORTED;
}
AdvPool& q = a.pool[a.n_pool++];
q.base = static_cast<char*>(b->base);
q.layer_stride = b->layer_stride;
q.n_layers = layers;
q.n_head = (int32_t)b->shape[1];
q.row_bytes = (int32_t)row;
q.grp = (int32_t)g;
}
RAD_TRY(step_compact(a, rk.ctx.stream()));
}
return RAD_OK;
}
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
* history pass and every round, then the final proposal into the slots and their readback.
@@ -496,9 +547,13 @@ void Engine::block_shape(int* block, int* steps) {
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
* proposals are for, mostly repeats (Scheduler::short_block_on). */
if (drafter_short_ <= 0) return;
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from);
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), short_from_);
if (short_on_) {
*steps -= *block - (int)drafter_short_;
/* A tree (rad_drafter_tree) grows a tree of its own over the shorter pass, at most its
* draft positions of nodes (DFlash2 attends across its block, so the short pass is not the
* full pass's prefix); the verify takes that many. */
if (tree_) *steps = std::min(*steps, (int)drafter_short_ - 1);
else *steps -= *block - (int)drafter_short_;
*block = (int)drafter_short_;
}
}
@@ -508,6 +563,9 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
if (!block_drafting()) return RAD_OK;
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
/* A tree's accepted path into place in the trunk's cache, against the same build (the step
* just accepted), before any later pass reads it. */
if (tree_) RAD_TRY(tree_compact(-1));
/* The sampled ids before either pass, as the serial driver reads them. */
RAD_TRY(collect_issue(so, /*fence=*/true));
@@ -518,15 +576,25 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
block_shape(&block, &steps);
block_steps_ = steps;
block_row_.resize((size_t)cfg_.max_seqs);
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
/* The head reads the block's draft rows. A tree (rad_drafter_tree; DFlash2's convention, the
* anchor predicts nothing) reads all block - 1 of them whatever its node count. */
const int head = tree_ ? block - 1 : steps;
const int n = sched_.block_begin(block, head, (int)drafter_.window, drafter_.mask_token,
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
/* --draft-coupling: the draws before the query pass reads them (stage_couple_draws). */
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(block_row_.data(), n));
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
* drafter will need, and skipping would leave a permanent hole in its cache. */
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
* drafter will need, and skipping would leave a permanent hole in its cache. A tree verify's
* context rows store only the accepted path, at its committed positions (ADV_CTXTREE). */
if (const RadBatch* cb = sched_.block_context(step)) {
if (tree_) RAD_TRY(advance_all(ADV_CTXTREE, 0, false));
RAD_TRY(block_pass(cb, "context", step));
}
/* A snapshot carrying the drafter's window is saved now, with the step's context rows stored
* and before the query pass and the step issued ahead (save_checkpoints). */
if (drafter_snap_) RAD_TRY(save_checkpoints());
if (n <= 0) return RAD_OK;
const RadBatch* qb = sched_.block_query(step);
if (!qb) return RAD_OK;
@@ -581,12 +649,25 @@ int Engine::finish_block_drafter(const StepOut& so) {
for (int j = 0; j < steps; ++j)
draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j];
}
/* -v: what each block pass proposed, a line a sequence, so two runs can be compared draft by
* draft where acceptance alone cannot tell them apart (a drafter whose context is wrong still
* drafts, and its rejected drafts change no token). */
const bool show = (int)log_level() >= (int)Log::Debug;
for (int i = 0; i < block_rows_; ++i) {
const int32_t* d = &draft_out_[(size_t)i * (size_t)steps];
if (show) {
std::string t;
for (int j = 0; j < steps; ++j) t += fmt(" %d", (int)d[j]);
RAD_DEBUG("drafter '%s': sequence %llu proposes%s", drafter_.name,
(unsigned long long)block_row_[(size_t)i].seq, t.c_str());
}
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. A
* tree's parents come from the same slot, as ADV_BTAKE took them. */
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
const uint64_t seq = block_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)steps], steps);
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
const int rc = sched_.set_draft(seq, d, steps, tree_ ? S.par : nullptr);
if (mtp_couple_)
RAD_TRY(bind_couple(seq, i, steps, rc == RAD_OK, block_row_[(size_t)i].card));
}
+39 -12
View File
@@ -237,8 +237,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
RadModelMeta& m = out->m;
/* Nomic BERT states its geometry with n_layer, n_embd, n_head, n_inner, n_positions and
* moe_top_k. They are fallbacks in the same chain, so a config carrying both spellings keeps
* the HuggingFace one and every existing checkpoint reads byte for byte as before. */
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
* reads the HuggingFace one. */
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
m.n_embd = gi("hidden_size", gi("n_embd", 0));
m.n_head = gi("num_attention_heads", gi("n_head", 0));
@@ -274,18 +274,21 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4): the
* quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from
* bf16 releases.
* bf16 releases. transformers' fine-grained FP8 states no fmt (Qwen3.8-Flash-Next-FP8's config)
* and is always E4M3, so a bare "fp8" is "fp8_e4m3", as a release that states it is.
*
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is the bf16 release that
* arch/gemma4_bf16 serves as compressed-tensors, which is what rad-convert's
* `--set quantization_config.quant_method=compressed-tensors` said by hand. Its per-layer
* embeddings or shared KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape
* and refuses those two keys, so the bare (gemma4, "") descriptor must not win. */
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is a bf16 release that
* arch/gemma4_bf16 serves under "compressed-tensors", so it needs no
* `--set quantization_config.quant_method=compressed-tensors`. Its per-layer embeddings or shared
* KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape and refuses those two
* keys, so the bare (gemma4, "") descriptor must not win. */
std::string quant_descriptor(const MetaOwn& m) {
std::string q;
if (const char* qm = m.get("quantization_config.quant_method")) {
q = qm;
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
const char* fm = m.get("quantization_config.fmt");
if (!fm && q == "fp8") fm = "e4m3";
if (fm) { q += "_"; q += fm; }
return q;
}
if (m.arch == "gemma4") {
@@ -2401,6 +2404,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
* RAD_MAP_COPY alternatives, first present wins (a tied lm_head is output.weight when
* shipped, else the embedding). */
const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
/* Pieces whose scale is one `X.weight_scale` their shards share (below). */
bool shard_scaled = false;
for (const Src1& s1 : srcs) {
const SrcTensor* st = ck.find(s1.name);
/* An FP8 weight's scale plane: `X.weight_scale_inv` (block-scaled releases) or
@@ -2410,6 +2415,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
const SrcTensor* sc = st ? ck.find(std::string(s1.name) + "_scale_inv") : nullptr;
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2))
sc = ck.find(std::string(s1.name) + "_scale");
/* A table split into shards, `X.shard_<i>.weight`, under one scale for all of them,
* `X.weight_scale` (Qwen3.8-Flash-Next-FP8's n-gram table). */
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2)) {
const std::string n = s1.name;
const size_t at = n.rfind(".shard_");
const size_t end = n.size() >= 7 ? n.size() - 7 : 0;
if (at != std::string::npos && end > at + 7 && n.compare(end, 7, ".weight") == 0 &&
std::all_of(n.begin() + (long)at + 7, n.begin() + (long)end,
[](char c) { return c >= '0' && c <= '9'; }))
if ((sc = ck.find(n.substr(0, at) + ".weight_scale"))) shard_scaled = true;
}
/* A weight shipped in an imported form is read through that form's views. */
{
const SrcTensor *ic = nullptr, *is = nullptr;
@@ -2501,8 +2517,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
* along rows, so each row of the weight is one source row of blocks; the loader still
* refuses them, since the blocks interleave what the planes hold apart. */
* along rows, so each row of the weight is one source row of blocks. rad-convert imports
* them; the loader refuses them, since the blocks interleave what the planes hold apart. */
bool one_type = true;
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
RadEncoding enc;
@@ -2693,7 +2709,18 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
bad = true;
out->why = "its FP8 pieces are joined along a column, across their scale planes";
}
if (!bad) {
/* Shards under the one scale they share are one tensor with one scale, byte for byte:
* `fp8_e4m3*<s>[*x*]`. */
bool one_scale = !bad && shard_scaled && n_one == (int)out->pieces.size();
for (size_t k = 1; one_scale && k < out->scales.size(); ++k)
one_scale = out->scales[k] == out->scales[0];
if (one_scale) {
out->trivial = out->why.empty();
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, 0, 0);
} else if (!bad) {
out->trivial = out->why.empty() && n_one == 0;
/* A per-tensor scale is written once a row (ckpt_plane_rows). */
if (n_one) {
+2 -2
View File
@@ -63,13 +63,13 @@ inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
}
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. */
inline uint32_t k_low4(const uint8_t* qs, int v) {
const uint8_t q = qs[32 * (v / 64) + v % 32];
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
}
/* Q4_K: the 6-bit scale and min of sub-block j, as llama.cpp's get_scale_min_k4 unpacks them. */
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
if (j < 4) {
*d = q[j] & 63u;
+15 -10
View File
@@ -14,6 +14,20 @@
namespace rad {
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
const int64_t probe = std::min<int64_t>(n, 4096);
bool 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";
return RAD_E_IO;
}
return RAD_OK;
}
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
@@ -45,16 +59,7 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
return RAD_E_IO;
}
const int64_t probe = std::min<int64_t>(n, 4096);
bool 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";
return RAD_E_IO;
}
return RAD_OK;
return table_copy_check(src, n, buf, why);
}
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
+5
View File
@@ -32,6 +32,11 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* dst, std::string* why);
/* The check table_copy_fill ends with, on its own: samples of [buf, buf + n) against [src, src + n)
* (the first and last 4 KiB and 64 spread between). RAD_OK, or RAD_E_IO with `why`. For a copy
* another process filled. */
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why);
/* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c);
+261
View File
@@ -0,0 +1,261 @@
/* table_share.cpp -- see table_share.h. */
#include "table_share.h"
#include "../rad_internal.h"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace {
constexpr char kMagic[8] = { 'R', 'A', 'D', 'N', 'G', 'R', 'M', '1' };
constexpr uint32_t kVersion = 1;
constexpr int64_t kHuge = (int64_t)2 << 20;
/* A leaving holder tries for LOCK_EX for about a second (table_share_close). */
constexpr int kLeaveTries = 10;
constexpr unsigned kLeaveWaitUs = 100 * 1000;
/* All integers host-endian: the file lives in a tmpfs, so it never leaves the machine. */
struct Header {
char magic[8];
uint32_t version;
uint32_t ready;
uint64_t bytes;
uint64_t filler_pid; /* for whoever reads the file by hand; nothing depends on it */
char id[24]; /* the 16 hex digits and a NUL */
};
static_assert(sizeof(Header) <= 4096, "the header must fit the first page");
enum class Seen { Fresh, Partial, Ready, Foreign };
std::string errno_text() { return std::strerror(errno); }
/* What the open data file holds. A fresh file and a half-filled one have a zero header; a header
* that is not this protocol's or not for this table is Foreign. */
Seen classify(int fd, const std::string& id, int64_t n, std::string* why) {
struct stat st{};
if (::fstat(fd, &st) != 0) {
*why = fmt("fstat: %s", errno_text().c_str());
return Seen::Foreign;
}
if (st.st_size == 0) return Seen::Fresh;
Header h{};
const ssize_t got = ::pread(fd, &h, sizeof h, 0);
if (got != (ssize_t)sizeof h) {
*why = fmt("its header is %lld bytes short", (long long)(sizeof h - (got < 0 ? 0 : got)));
return Seen::Foreign;
}
Header zero{};
if (std::memcmp(&h, &zero, sizeof h) == 0) return Seen::Partial;
if (std::memcmp(h.magic, kMagic, sizeof kMagic) != 0 || h.version != kVersion) {
*why = "it is not a table file of this version";
return Seen::Foreign;
}
if (h.bytes != (uint64_t)n || std::strncmp(h.id, id.c_str(), sizeof h.id) != 0) {
*why = fmt("it holds %s of table '%.16s', not %s of '%s'", humanb((int64_t)h.bytes).c_str(),
h.id, humanb(n).c_str(), id.c_str());
return Seen::Foreign;
}
if (!h.ready) return Seen::Partial;
if (st.st_size != table_share_file_bytes(n)) {
*why = fmt("it is marked ready but is %lld bytes long, not %lld", (long long)st.st_size,
(long long)table_share_file_bytes(n));
return Seen::Foreign;
}
return Seen::Ready;
}
std::string file_path(const std::string& dir, const std::string& id) {
const bool slash = !dir.empty() && dir.back() == '/';
return dir + (slash ? "" : "/") + "ngram-" + id + ".tab";
}
void fail(TableShare* s) {
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) ::close(s->fd);
*s = TableShare{};
}
} /* namespace */
int64_t table_share_file_bytes(int64_t n) {
return kTableShareHeader + ((n + kHuge - 1) & ~(kHuge - 1));
}
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n) {
char real[PATH_MAX];
const std::string path = ::realpath(container_path.c_str(), real) ? std::string(real)
: container_path;
struct stat st{};
if (::stat(path.c_str(), &st) != 0) return std::string();
uint64_t h = 1469598103934665603ull;
auto feed = [&](const void* p, size_t len) {
const unsigned char* b = static_cast<const unsigned char*>(p);
for (size_t i = 0; i < len; ++i) h = (h ^ b[i]) * 1099511628211ull;
};
const int64_t parts[] = { (int64_t)st.st_size, (int64_t)st.st_mtim.tv_sec,
(int64_t)st.st_mtim.tv_nsec, foff, n };
feed(path.data(), path.size());
feed(parts, sizeof parts);
return fmt("%016llx", (unsigned long long)h);
}
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why) {
if (!out || !why || dir.empty() || id.empty() || n <= 0) return RAD_E_INVAL;
*out = TableShare{};
out->path = file_path(dir, id);
out->lock_path = out->path + ".lock";
/* A holder that left last deletes the file while we open it: its unlink comes with LOCK_EX, so
* once we hold LOCK_SH the link count says whether the file is still the one in the directory. */
for (;;) {
out->fd = ::open(out->path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->fd < 0) {
*why = fmt("opening %s: %s", out->path.c_str(), errno_text().c_str());
*out = TableShare{};
return RAD_E_IO;
}
if (::flock(out->fd, LOCK_SH) != 0) {
*why = fmt("locking %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
struct stat st{};
if (::fstat(out->fd, &st) != 0) {
*why = fmt("fstat %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (st.st_nlink > 0) {
struct statfs fs{};
if (::fstatfs(out->fd, &fs) == 0 && (long)fs.f_type != 0x01021994L &&
(long)fs.f_type != 0x858458f6L)
RAD_WARN("n-gram table share: %s is not on a tmpfs or ramfs, so the table is "
"written to its disk and held in the page cache", dir.c_str());
break;
}
::close(out->fd);
}
std::string seen_why;
Seen seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
out->ready = true;
return RAD_OK;
}
out->lock_fd = ::open(out->lock_path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->lock_fd < 0) {
*why = fmt("opening %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (::flock(out->lock_fd, LOCK_EX) != 0) {
*why = fmt("locking %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
/* The holder we waited for may have finished. */
seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
::close(out->lock_fd);
out->lock_fd = -1;
out->ready = true;
return RAD_OK;
}
if (::ftruncate(out->fd, table_share_file_bytes(n)) != 0) {
*why = fmt("sizing %s to %s: %s", out->path.c_str(),
humanb(table_share_file_bytes(n)).c_str(), errno_text().c_str());
fail(out);
return RAD_E_NOMEM;
}
out->filler = true;
return RAD_OK;
}
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why) {
if (!s || !why || s->fd < 0 || !s->filler || id.size() >= sizeof(Header::id))
return RAD_E_INVAL;
Header h{};
std::memcpy(h.magic, kMagic, sizeof kMagic);
h.version = kVersion;
h.ready = 1;
h.bytes = (uint64_t)n;
h.filler_pid = (uint64_t)::getpid();
std::memcpy(h.id, id.c_str(), id.size());
if (::pwrite(s->fd, &h, sizeof h, 0) != (ssize_t)sizeof h) {
*why = fmt("writing the header of %s: %s", s->path.c_str(), errno_text().c_str());
return RAD_E_IO;
}
if (s->lock_fd >= 0) {
::close(s->lock_fd);
s->lock_fd = -1;
}
s->ready = true;
return RAD_OK;
}
void table_share_close(TableShare* s) {
if (!s) return;
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) {
/* Engines stopped together (a compose recreate) leave together: one that tries while the
* other still holds LOCK_SH, unpinning the table, is not the last, and the other may be
* killed at the stop timeout before its own try, which leaves the table in the tmpfs. So
* this holder lets go of LOCK_SH and tries for a while. It holds no lock from here on
* until LOCK_EX is granted; a conversion would not keep it either, since a refused one
* has already dropped LOCK_SH (flock(2): not atomic). LOCK_EX may then come on a file
* another holder already deleted, with a new engine's file at its name, so only the file
* the name still points to is deleted. The lock file goes first: nobody gets past
* LOCK_SH on this file to use it, while a file made anew at the name the moment this one
* is gone could already have a filler on it. */
(void)::flock(s->fd, LOCK_UN);
for (int i = 0; i < kLeaveTries; ++i) {
if (::flock(s->fd, LOCK_EX | LOCK_NB) == 0) {
struct stat mine{}, named{};
if (::fstat(s->fd, &mine) == 0 && ::stat(s->path.c_str(), &named) == 0 &&
mine.st_dev == named.st_dev && mine.st_ino == named.st_ino) {
::unlink(s->lock_path.c_str());
::unlink(s->path.c_str());
}
break;
}
if (errno != EWOULDBLOCK && errno != EINTR) break;
if (i + 1 < kLeaveTries) ::usleep(kLeaveWaitUs);
}
::close(s->fd);
}
*s = TableShare{};
}
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n) {
if (dir.empty() || id.empty() || n <= 0) return false;
const int fd = ::open(file_path(dir, id).c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
std::string why;
const bool ready = classify(fd, id, n, &why) == Seen::Ready;
::close(fd);
return ready;
}
} /* namespace rad */
+69
View File
@@ -0,0 +1,69 @@
/* table_share.h -- an n-gram table as a file in a tmpfs that engines on separate cards share
* (--ngram-placement ram=DIR). Each engine maps the file MAP_SHARED and pins it for its own cards,
* so the host holds one copy however many engines read it. This is the file protocol only; the
* mapping and the pinning are the device layer's (rad_dev_map_file).
*
* The file is `DIR/ngram-<id>.tab`: a header in its first 2 MiB, the table from kTableShareHeader
* on, so the table keeps the 2 MiB alignment the pinned ranges want. The id names the container
* and the table's place in it, so a file never serves another model.
*
* Every holder keeps LOCK_SH on the data file for its life, which counts the readers. The first
* engine to find the file unready takes the fill lock (LOCK_EX on `<file>.lock`, a file of its
* own so that a later engine arriving while the table is read never waits behind the readers),
* fills the table and marks it ready; an engine arriving meanwhile waits on the fill lock and then
* finds it ready. The holder that gets LOCK_EX on the data file when it leaves is the last, and
* deletes the file and the lock file; one that leaves while another still holds LOCK_SH waits a
* moment for it, since engines stopped together leave together. A holder that died took its locks
* with it: a half-filled file is filled again, a ready one is reused after the same sample check
* as a fresh copy. */
#pragma once
#include <cstdint>
#include <string>
namespace rad {
/* The table's offset in the file. */
constexpr int64_t kTableShareHeader = (int64_t)2 << 20;
/* The file's length for an n-byte table: the header, then the table rounded up to 2 MiB. */
int64_t table_share_file_bytes(int64_t n);
/* The smallest table worth a shared file. A file costs the header and the table's rounding to
* 2 MiB, up to 4 MiB beside the table, and a tmpfs entry that outlives a crash; a weight of a few
* bytes the gather reads beside the table (its one-element scale) would cost more that way than as
* a private copy in every engine. From 16 headers on the file's overhead is under an eighth of the
* table; a smaller one takes the private pinned copy. */
constexpr int64_t kTableShareMin = 16 * kTableShareHeader;
struct TableShare {
int fd = -1; /* the data file, LOCK_SH held until table_share_close */
int lock_fd = -1; /* the fill lock, held while `filler` and not yet marked ready */
std::string path, lock_path;
bool ready = false; /* the table in the file is complete */
bool filler = false; /* this holder fills it, then calls table_share_mark_ready */
};
/* FNV-1a 64 over the container's real path, size and mtime (to the nanosecond), the table's file
* offset and its length, as 16 hex digits; empty if the container cannot be stat'ed. */
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n);
/* Open or create DIR/ngram-<id>.tab for an n-byte table and take part in the protocol: afterwards
* `out->ready` (map it and check samples) or `out->filler` (map it, fill [kTableShareHeader, +n),
* mark it ready). RAD_E_INVAL if a file of that name does not hold a table of this id and length
* (another program's, or another version's; never overwritten, since a live engine may map it),
* RAD_E_IO if the directory or file cannot be used. `why` carries the reason. */
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why);
/* The filler's table is complete: write the header, release the fill lock. */
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why);
/* Leave. The last holder deletes the file and its lock file; while another still holds the file,
* this waits up to about a second for it to leave first. Safe on a TableShare never opened. */
void table_share_close(TableShare* s);
/* Whether DIR/ngram-<id>.tab is a complete table of n bytes now, read from its header without
* taking part: for the placement decision, which must know before anything is pinned. */
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n);
} /* namespace rad */
+2 -2
View File
@@ -186,8 +186,8 @@ void KVStreamStore::release(MemAllocator& host_alloc) {
KVStreamStats KVStreamStore::stats(const std::vector<KVGroupPlan>& plans) const {
KVStreamStats st;
st.misses = misses_;
st.bytes_in = bytes_in_;
st.misses = (int64_t)misses_.load(std::memory_order_relaxed);
st.bytes_in = (int64_t)bytes_in_.load(std::memory_order_relaxed);
for (const auto& p : plans)
if (p.streamed()) st.resident_blocks += p.pool_blocks();
return st;
+8 -5
View File
@@ -9,6 +9,7 @@
#pragma once
#include "mem/pools.h"
#include <atomic>
#include <cstdint>
#include <vector>
@@ -85,17 +86,19 @@ public:
KVStreamStats stats(const std::vector<KVGroupPlan>& plans) const;
/* Charged by the engine, which reads the resolve's counters where a step has drained. */
/* Charged by the engine, which reads the resolve's counters where a step has drained. Atomic
* (relaxed): stats() is also read by the dashboard's snapshot on an HTTP thread while a step
* may be in flight; only the values carry meaning, not their order. */
void note_traffic(int64_t misses, int64_t bytes) {
if (misses > 0) misses_ += (uint64_t)misses;
if (bytes > 0) bytes_in_ += (uint64_t)bytes;
if (misses > 0) misses_.fetch_add((uint64_t)misses, std::memory_order_relaxed);
if (bytes > 0) bytes_in_.fetch_add((uint64_t)bytes, std::memory_order_relaxed);
}
private:
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
std::vector<Map> maps_; /* set_map(), by group handle */
uint64_t misses_ = 0; /* note_traffic() */
uint64_t bytes_in_ = 0;
std::atomic<uint64_t> misses_{0}; /* note_traffic() */
std::atomic<uint64_t> bytes_in_{0};
};
} /* namespace rad */
+37 -3
View File
@@ -272,11 +272,15 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
/* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). A
* trunk's window rides in the slot whether or not linear state is beside it: a hit resumes at
* a snapshot either way, and without the window there it could not resume at all. */
* a snapshot either way, and without the window there it could not resume at all. A drafter's
* window rides there only on a model without linear state (set_drafter_window_snapshot). */
bool has_state = false;
for (const auto& p : plans_) has_state = has_state || p.stateful();
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
!p.runtime_win && !groups[i].drafter;
p.drafter = groups[i].drafter;
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && !p.runtime_win &&
(!groups[i].drafter || (snap_drafter_ && !has_state));
if (p.win_snap && !p.zero && p.n_layers > 0)
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
}
@@ -984,6 +988,36 @@ bool KVManager::can_ever_fit(int64_t n_tokens) const {
return true;
}
/* Read-only counterpart of ensure(): can `seq` grow to n_tokens without taking blocks from
* another sequence? Used by the scheduler's preempted-prefill admission gate, which must not
* reserve anything or it would perturb the very pool it is trying to protect. */
bool KVManager::can_grow(uint64_t id, int64_t n_tokens) const {
const Seq* s = find(id);
if (!s) return false;
if (n_tokens <= s->n_tokens) return true;
for (size_t g = 0; g < plans_.size(); ++g) {
const auto& p = plans_[g];
if (p.paged()) {
const int64_t first = s->first_block_pos[g] / p.block_size;
const int64_t want = ceil_div(n_tokens, p.block_size) - first;
int64_t need = want - (int64_t)s->blocks[g].size();
if (need < 0) need = 0;
/* ensure() takes one copy-on-write block for a partially filled block; include it
* here so the gate does not admit a sequence that then has to steal from another. */
if (s->n_tokens > 0 && s->n_tokens % p.block_size != 0) {
const int64_t bi = s->n_tokens / p.block_size - first;
if (bi >= 0 && bi < (int64_t)s->blocks[g].size() &&
refcount_[g][(size_t)s->blocks[g][(size_t)bi]] > 1)
++need;
}
if (need > available_blocks((int32_t)g)) return false;
} else if (p.stateful() && s->state[g] < 0) {
if (free_states_[g].empty()) return false;
}
}
return true;
}
/* ------------------------------------------------------------------ sequences */
KVManager::Seq* KVManager::find(uint64_t s) {
+23 -4
View File
@@ -122,9 +122,12 @@ struct KVGroupPlan {
? (runtime_tokens + block_size - 1) / block_size : 0;
}
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot), after any
* linear state. Set for a trunk group; a drafter's window is recomputed by draft refill, so
* its snapshot would not be read. */
* linear state. Set for a trunk group, and for a drafter's group on a model without linear
* state where the engine saves the snapshot behind the drafter's context pass
* (set_drafter_window_snapshot). Elsewhere a drafter's window is recomputed by draft refill,
* so its snapshot would not be read. */
bool win_snap = false;
bool drafter = false; /* a drafter's group (KVGroupInfo::drafter) */
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
/* Paged groups: blocks the device pool backs, fewer than `n_blocks` when the group streams
@@ -230,6 +233,17 @@ public:
* is sized and capped from these two alone (core/mem/vram_budget.cpp); VRAM above the ceiling
* would never be addressed. carve() spends the pool it is given. */
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
/* Whether a drafter's WINDOW group rides in the window snapshot too (KVGroupPlan::win_snap).
* The engine sets it, before plan_groups, where the drafter stores its context right behind
* the trunk step and the snapshot is saved after that (a block drafter on the card's driver);
* a snapshot taken before would hold the window without the step's rows. Kept across
* forget(). */
void set_drafter_window_snapshot(bool on) { snap_drafter_ = on; }
/* Some drafter group rides in the window snapshot (after plan_groups). */
bool drafter_window_snapshot() const {
for (const auto& p : plans_) if (p.win_snap && p.drafter) return true;
return false;
}
int64_t ceiling(int64_t ctx) const;
/* The context-independent part of every ceiling: recurrent and conv state for max_seqs
* sequences, plus alignment padding. Set by plan_groups(). */
@@ -437,6 +451,12 @@ public:
* the request is failed rather than deadlocking the engine (spec §17). */
bool can_ever_fit(int64_t n_tokens) const;
/* Whether `seq` can grow to `n_tokens` without taking blocks from another sequence. */
bool can_grow(uint64_t seq, int64_t n_tokens) const;
/* Blocks a paged group can still hand out, including the lendable part. */
int64_t available_blocks(int32_t group) const;
/* ---------------- the loan ----------------
*
* The paged groups lend unheld blocks to the expert slab in place. The carve fixes and backs
@@ -668,6 +688,7 @@ private:
int64_t max_seqs_ = 0;
int64_t max_ctx_ = 0;
int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */
bool snap_drafter_ = false; /* set_drafter_window_snapshot */
/* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
@@ -707,8 +728,6 @@ private:
std::vector<int64_t> bucket_blocks_; /* per group: blocks one held_hist_ bucket covers */
std::vector<std::vector<int32_t>> held_hist_; /* per group, per bucket: held blocks */
int64_t available_blocks(int32_t g) const;
/* The buffer this group wants in hand, in blocks. See buffer_bytes(). */
int64_t buf_blocks(size_t i) const;
/* One past the highest held block, rounded up to a bucket. */
int64_t held_top(size_t i) const;
+36 -6
View File
@@ -77,7 +77,13 @@ void GeometricBackoff::select(const std::vector<int64_t>& pos, std::vector<int64
void KeepTipOnly::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
keep->clear();
if (!pos.empty()) keep->push_back(pos.back());
if (pos.empty()) return;
const int64_t tip = pos.back();
if (floor_ > 0) {
const auto it = std::upper_bound(pos.begin(), pos.end(), tip - floor_);
if (it != pos.begin()) keep->push_back(*(it - 1));
}
keep->push_back(tip);
}
void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
@@ -122,8 +128,7 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma
int64_t share_bytes, int64_t room_bytes) {
CheckpointSlots c;
c.per_seq = policy.held(ctx, interval) + 1;
const int64_t seqs = std::max<int64_t>(max_seqs, 1);
c.want = seqs > INT64_MAX / c.per_seq ? INT64_MAX : seqs * c.per_seq;
c.want = checkpoint_slots_want(policy, max_seqs, ctx, interval);
if (slot_bytes <= 0) return c;
const int64_t share = std::max<int64_t>(share_bytes, 0) / slot_bytes;
const int64_t room = std::max<int64_t>(room_bytes, 0) / slot_bytes;
@@ -136,6 +141,24 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma
return c;
}
int64_t checkpoint_slots_want(const CheckpointPolicy& policy, int64_t max_seqs, int64_t ctx,
int64_t interval) {
const int64_t per = policy.held(ctx, interval) + 1;
const int64_t seqs = std::max<int64_t>(max_seqs, 1);
return seqs > INT64_MAX / per ? INT64_MAX : seqs * per;
}
int64_t host_reserve_for_floor(int64_t need_bytes, int64_t room_bytes, int64_t margin_bytes) {
if (need_bytes <= 0 || margin_bytes <= 0 || room_bytes >= need_bytes) return margin_bytes;
/* Whole MiB, the unit --host-headroom-mib takes, and the shortfall rounding up: the reserve
* gives back at least what the floor asked for, so the store is never a byte short of it. */
const int64_t mib = (int64_t)1 << 20;
const int64_t shortfall = (need_bytes - room_bytes + mib - 1) / mib;
const int64_t margin = margin_bytes / mib;
const int64_t keep = margin - shortfall;
return std::min(margin, std::max(kHostReserveFloor / mib, keep)) * mib;
}
/* ------------------------------------------------------------------ configure */
int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) {
@@ -151,6 +174,7 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
ck_by_prefix_.clear(); ck_by_session_.clear();
/* set_policy() may override this afterwards. */
policy_ = make_checkpoint_policy(cfg.checkpoint_policy, checkpoint_interval);
policy_->set_floor(drafter_floor_);
report_.clear();
if (!kv) return RAD_E_INVAL;
@@ -160,9 +184,9 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
}
/* Every paged group but a windowed one is cached. An entry covers the lcm of their block
* sizes, and holds that over a group's block size of the group's blocks: a hit then ends on
* a block of every group, which adopt() needs. The chunk quantum is a multiple of every paged
* group's block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */
* sizes and holds lcm / B blocks of a group with B-token blocks, so a hit ends on a block of
* every group, which adopt() needs. The chunk quantum is a multiple of every paged group's
* block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */
for (const auto& p : kv->plans()) {
if (p.stateful()) has_linear_ = true;
if (p.paged() && p.kind != RAD_KV_WINDOW && p.block_size > 0)
@@ -250,6 +274,12 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
void PrefixCache::set_policy(std::unique_ptr<CheckpointPolicy> p) {
if (p) policy_ = std::move(p);
if (policy_) policy_->set_floor(drafter_floor_);
}
void PrefixCache::set_drafter_floor(int64_t tokens) {
drafter_floor_ = tokens > 0 ? tokens : 0;
if (policy_) policy_->set_floor(drafter_floor_);
}
std::string PrefixCache::report() const { return report_; }
+37 -3
View File
@@ -127,6 +127,10 @@ public:
* of the store. The base applies select() to its own output one checkpoint at a time, which
* is cheap only for a policy that keeps few. */
virtual int64_t held(int64_t ctx, int64_t interval) const;
/* Tokens before the tip a hit must be able to end at: a drafter whose KV the cache does not
* hold recomputes that much of the prompt's tail (Scheduler::init, HitCap). 0: none. A policy
* that would otherwise keep nothing that deep keeps one snapshot there. */
virtual void set_floor(int64_t) {}
};
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
@@ -146,12 +150,18 @@ private:
int64_t interval_;
};
/* The two ends of the trade, for comparison. */
/* The two ends of the trade, for comparison. tip-only under a drafter floor also keeps the deepest
* snapshot at or below tip - floor: without it a refill-capped hit finds nothing to end on, keeps
* the whole hit, and the request decodes with no drafts (8 sessions of 22k tokens: 5 ran
* unspeculated, decode 424-521 t/s against 738-754 under geometric backoff). */
class KeepTipOnly final : public CheckpointPolicy {
public:
const char* name() const override { return "tip-only"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t, int64_t) const override { return 1; }
int64_t held(int64_t, int64_t) const override { return floor_ > 0 ? 2 : 1; }
void set_floor(int64_t tokens) override { floor_ = tokens > 0 ? tokens : 0; }
private:
int64_t floor_ = 0;
};
class KeepAll final : public CheckpointPolicy {
public:
@@ -174,6 +184,9 @@ std::unique_ptr<CheckpointPolicy> make_checkpoint_policy(const std::string& name
* the room is a hard bound. */
constexpr int64_t kCheckpointSlotsFloor = 8;
/* The least --host-headroom-mib is reduced to for a store's floor (host_reserve_for_floor). */
constexpr int64_t kHostReserveFloor = (int64_t)1 << 30;
struct CheckpointSlots {
int64_t per_seq = 0; /* snapshots a sequence is given */
int64_t want = 0; /* --max-num-seqs x per_seq */
@@ -181,10 +194,28 @@ struct CheckpointSlots {
enum class Bound { Want, Share, Room } bound = Bound::Want;
};
/* What --checkpoint-slots auto wants before any byte budget applies: the policy's hold for one
* --max-model-len session plus one for its running turn, for each of --max-num-seqs. */
int64_t checkpoint_slots_want(const CheckpointPolicy& policy, int64_t max_seqs, int64_t ctx,
int64_t interval);
CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs,
int64_t ctx, int64_t interval, int64_t slot_bytes,
int64_t share_bytes, int64_t room_bytes);
/* The reserve to charge a store whose floor `need_bytes` must fit. `room_bytes` is what the host
* can pin with `margin_bytes` (--host-headroom-mib) held free; it is what the engine measures, not
* what a model or a KV encoding is assumed to cost.
*
* The reserve is a courtesy to the system -- the process's unpooled allocations, the load's
* staging windows, the page cache -- and a store that turns prefix reuse on or off outranks it: a
* store too small for one snapshot re-prefills the whole conversation on every turn, while the
* reserve it displaced is memory the host would merely have kept. So the reserve gives back
* exactly the shortfall, never below kHostReserveFloor, and never above the margin asked for.
* It answers `margin_bytes` unchanged whenever the floor already fits, so a host with room to
* spare never sees the reserve move. */
int64_t host_reserve_for_floor(int64_t need_bytes, int64_t room_bytes, int64_t margin_bytes);
/* ------------------------------------------------------------------ a release */
/* What PrefixCache::release_session took out and what it left. Blocks are left for three
* reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the
@@ -234,6 +265,8 @@ public:
/* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
* tests). Call after configure(), which would undo it. */
void set_policy(std::unique_ptr<CheckpointPolicy> p);
/* The drafter's refill window (CheckpointPolicy::set_floor), held across set_policy. */
void set_drafter_floor(int64_t tokens);
const CheckpointPolicy& policy() const { return *policy_; }
/* ---------------- full attention ---------------- */
@@ -424,7 +457,7 @@ private:
struct Entry {
/* blocks_per_entry(i) per cached group, in groups_ order: entry_groups_[k] owns blocks[k] */
std::vector<int32_t> blocks;
std::vector<int32_t> tokens; /* the block's token ids, compared on hit */
std::vector<int32_t> tokens; /* the entry's token ids, compared on hit */
/* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
* off-device entry owns no block, so eviction must not reach it. */
bool in_lru = false;
@@ -530,6 +563,7 @@ private:
}
mutable uint64_t clock_ = 0;
std::unique_ptr<CheckpointPolicy> policy_;
int64_t drafter_floor_ = 0;
mutable Stats stats_;
std::string report_;
};
+3 -3
View File
@@ -36,9 +36,9 @@ struct FrameRGBA {
/* Whether this build has a decoder. */
bool decoder_available();
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)"
* when it is not: one string for the startup report and /diagnostics, so a media 500 can be
* read off the report instead of bisected. */
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)" when it
* is not: one string for the startup report and /diagnostics, so a build that refuses every media
* part shows it there. */
std::string decoder_version();
/* The first frame of an image (or of anything with a video stream). Refuses a source over
+4 -1
View File
@@ -16,10 +16,11 @@ constexpr int32_t kBlock = 64;
int HeatEngine::init(const Plan& plan, const HeatParams& params) {
params_ = params;
stats_ = HeatStats{};
stats_.reset();
const size_t n = plan.units.size();
tier_.assign(n, Tier::VRAM);
tier_pub_.assign(n);
busy_.assign(n, 0u);
movable_.assign(n, 0u);
pinned_.assign(n, 0u);
@@ -59,6 +60,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
for (size_t u = 0; u < n; ++u) {
const MoveUnit& mu = plan.units[u];
tier_[u] = mu.tier;
tier_pub_.set(u, (uint8_t)mu.tier);
layer_of_[u] = mu.layer;
bytes_[u] = mu.bytes;
movable_[u] = mu.movable ? 1u : 0u;
@@ -259,6 +261,7 @@ void HeatEngine::set_tier(int32_t unit, Tier t) {
else if (was != Tier::VRAM && t == Tier::VRAM) ++res_count_[(size_t)l];
}
tier_[(size_t)unit] = t;
tier_pub_.set((size_t)unit, (uint8_t)t);
set_place(unit);
end_invalidate(unit);
+112 -4
View File
@@ -31,6 +31,8 @@
#include "planner.h"
#include <string>
#include <atomic>
#include <memory>
#include <vector>
namespace rad {
@@ -111,6 +113,100 @@ struct HeatStats {
uint64_t routed = 0, routed_resident = 0, stream_bytes = 0;
};
/* The live twin of HeatStats: every counter an atomic, so the HTTP thread's /stats and LiveView
* reads are relaxed loads beside the dispatch thread's writes rather than a data race. Written
* as plain counters are (++ and +=), read through snapshot(). See MoverCounters, same reasoning.
*/
struct HeatCounters {
std::atomic<uint64_t> dispatches{0};
std::atomic<uint64_t> proposed{0}, promotions{0}, demotions{0};
std::atomic<uint64_t> refused{0}, no_candidate{0};
std::atomic<uint64_t> distinct_promoted{0}, readmits{0};
std::atomic<uint64_t> routed{0}, routed_resident{0}, stream_bytes{0};
/* HeatEngine is copyable — place_test snapshots engines — so its counters must copy too.
* A copy takes the current values: relaxed loads into the copy's own atomics. */
HeatCounters() = default;
HeatCounters(const HeatCounters& o) { *this = o; }
HeatCounters& operator=(const HeatCounters& o) {
dispatches.store(o.dispatches.load(std::memory_order_relaxed), std::memory_order_relaxed);
proposed.store(o.proposed.load(std::memory_order_relaxed), std::memory_order_relaxed);
promotions.store(o.promotions.load(std::memory_order_relaxed), std::memory_order_relaxed);
demotions.store(o.demotions.load(std::memory_order_relaxed), std::memory_order_relaxed);
refused.store(o.refused.load(std::memory_order_relaxed), std::memory_order_relaxed);
no_candidate.store(o.no_candidate.load(std::memory_order_relaxed),
std::memory_order_relaxed);
distinct_promoted.store(o.distinct_promoted.load(std::memory_order_relaxed),
std::memory_order_relaxed);
readmits.store(o.readmits.load(std::memory_order_relaxed), std::memory_order_relaxed);
routed.store(o.routed.load(std::memory_order_relaxed), std::memory_order_relaxed);
routed_resident.store(o.routed_resident.load(std::memory_order_relaxed),
std::memory_order_relaxed);
stream_bytes.store(o.stream_bytes.load(std::memory_order_relaxed),
std::memory_order_relaxed);
return *this;
}
void reset() {
/* Field by field: atomics are not copy-assignable. */
dispatches.store(0, std::memory_order_relaxed);
proposed.store(0, std::memory_order_relaxed);
promotions.store(0, std::memory_order_relaxed);
demotions.store(0, std::memory_order_relaxed);
refused.store(0, std::memory_order_relaxed);
no_candidate.store(0, std::memory_order_relaxed);
distinct_promoted.store(0, std::memory_order_relaxed);
readmits.store(0, std::memory_order_relaxed);
routed.store(0, std::memory_order_relaxed);
routed_resident.store(0, std::memory_order_relaxed);
stream_bytes.store(0, std::memory_order_relaxed);
}
HeatStats snapshot() const {
HeatStats s;
s.dispatches = dispatches.load(std::memory_order_relaxed);
s.proposed = proposed.load(std::memory_order_relaxed);
s.promotions = promotions.load(std::memory_order_relaxed);
s.demotions = demotions.load(std::memory_order_relaxed);
s.refused = refused.load(std::memory_order_relaxed);
s.no_candidate = no_candidate.load(std::memory_order_relaxed);
s.distinct_promoted = distinct_promoted.load(std::memory_order_relaxed);
s.readmits = readmits.load(std::memory_order_relaxed);
s.routed = routed.load(std::memory_order_relaxed);
s.routed_resident = routed_resident.load(std::memory_order_relaxed);
s.stream_bytes = stream_bytes.load(std::memory_order_relaxed);
return s;
}
};
/* The per-unit tier mirror HeatEngine keeps for the HTTP thread: one relaxed atomic byte per
* unit, written by set_tier and read by tier_published. A type of its own because it must be
* copyable — HeatEngine is copyable, and a copy takes the tier values into an array of its
* own — which a bare unique_ptr of atomics is not. */
struct TierMirror {
std::unique_ptr<std::atomic<uint8_t>[]> a;
size_t n = 0;
void assign(size_t m) {
n = m;
a.reset(m ? new std::atomic<uint8_t>[m] : nullptr);
}
void set(size_t i, uint8_t v) const { a[i].store(v, std::memory_order_relaxed); }
uint8_t get(size_t i) const { return a[i].load(std::memory_order_relaxed); }
TierMirror() = default;
TierMirror(const TierMirror& o) {
assign(o.n);
for (size_t i = 0; i < n; ++i) set(i, o.get(i));
}
TierMirror& operator=(const TierMirror& o) {
if (this == &o) return *this;
assign(o.n);
for (size_t i = 0; i < n; ++i) set(i, o.get(i));
return *this;
}
};
class HeatEngine {
public:
/* Binds to the plan. A static plan is a mode, not a failure: init returns RAD_OK and
@@ -145,6 +241,12 @@ public:
void set_tier(int32_t unit, Tier t);
void set_busy(int32_t unit, bool busy);
Tier tier(int32_t unit) const { return tier_[(size_t)unit]; }
/* The tier as the HTTP thread may safely read it: set_tier mirrors every change into a
* relaxed atomic, and /stats and LiveView read the mirror. tier_ itself belongs to the
* dispatch thread; reading it from another thread mid-step is a data race. */
Tier tier_published(int32_t unit) const {
return (Tier)tier_pub_.get((size_t)unit);
}
bool busy(int32_t unit) const { return busy_[(size_t)unit] != 0; }
/* The best swap available, or false when the guards refuse. */
@@ -165,7 +267,9 @@ public:
const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1;
return l >= 0 && (size_t)l < res_count_.size() ? res_count_[(size_t)l] : 0;
}
const HeatStats& stats() const { return stats_; }
/* A snapshot by value: the counters are atomics read while the dispatch thread writes them.
* Engine-internal decisions must use the individual counters (`warm`), not a snapshot. */
HeatStats stats() const { return stats_.snapshot(); }
/* Exit banner, ending with the per-layer resident counts, which show whether every layer kept
* its share of slots. */
@@ -175,7 +279,7 @@ private:
HeatParams params_;
bool enabled_ = false;
int32_t n_layer_ = 0;
HeatStats stats_;
HeatCounters stats_;
/* Heat by position, not by unit. Each layer owns a run of positions whose front is indexed by
* expert: expert e of layer l is at slot_lo_[l] + e, whether or not the plan has a unit for it
@@ -208,10 +312,14 @@ private:
/* Unit bytes from the plan, so a miss is priced where it is detected. */
std::vector<int64_t> bytes_;
std::vector<Tier> tier_;
/* Per unit, the tier as a relaxed atomic mirror, for the HTTP thread's reads (tier_published
* reads, set_tier and init write). Sized with tier_; element type uint8_t to keep the read
* lock-free and the mirror one byte per unit. */
TierMirror tier_pub_;
std::vector<uint8_t> busy_;
std::vector<uint8_t> movable_;
/* --expert-pin-top: a decode-hot resident the planner marked unmovable is never a demotion
* candidate, even where a later pass made its unit movable again. */
/* --expert-pin-top: a decode-hot resident the planner pinned is never a demotion candidate,
* even where a later pass made its unit movable again. */
std::vector<uint8_t> pinned_;
std::vector<int32_t> layer_of_;
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
+1 -1
View File
@@ -111,7 +111,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
plan_ = &plan;
cfg_ = cfg;
budget_ = budget;
stats_ = MoverStats{};
stats_.reset();
if (!budget_)
RAD_WARN("mover: no Pools given; allocating the slab and host pool directly (test only)");
+90 -2
View File
@@ -349,6 +349,93 @@ struct MoverStats {
uint64_t file_read_ns = 0, file_wait_ns = 0;
};
/* The live twin of MoverStats: every counter an atomic. The mover writes these through the
* step on its rank thread while the HTTP thread reads them for /stats and LiveView, and reading
* a plain field another thread writes is a data race (UB). Relaxed atomics give exactly the
* "either side of a store" telemetry promises, at no cost on the writer. snapshot() loads them
* all into a plain MoverStats; same reasoning that made flex_used_ atomic, for the same reader.
*/
struct MoverCounters {
std::atomic<uint64_t> dispatches{0};
std::atomic<uint64_t> promotions{0}, demotions{0};
std::atomic<uint64_t> h2d_bytes{0}, d2h_bytes{0};
std::atomic<uint64_t> prefetched{0}, prefetch_bytes{0};
std::atomic<uint64_t> no_record{0}, starved_slab{0}, starved_pool{0};
std::atomic<uint64_t> quarantined{0};
std::atomic<uint64_t> dropped{0};
std::atomic<uint64_t> donated{0}, relocated{0}, stranded{0};
std::atomic<uint64_t> ssd_reads{0}, ssd_bytes{0};
std::atomic<uint64_t> stage_layers{0}, staged_units{0}, staged_bytes{0}, stage_overflow{0};
std::atomic<uint64_t> stage_copies{0};
std::atomic<uint64_t> file_layers{0}, file_units{0}, file_bytes{0}, file_preads{0};
std::atomic<uint64_t> file_read_ns{0}, file_wait_ns{0};
void reset() {
/* Field by field: atomics are not copy-assignable. */
dispatches.store(0, std::memory_order_relaxed);
promotions.store(0, std::memory_order_relaxed);
demotions.store(0, std::memory_order_relaxed);
h2d_bytes.store(0, std::memory_order_relaxed);
d2h_bytes.store(0, std::memory_order_relaxed);
prefetched.store(0, std::memory_order_relaxed);
prefetch_bytes.store(0, std::memory_order_relaxed);
no_record.store(0, std::memory_order_relaxed);
starved_slab.store(0, std::memory_order_relaxed);
starved_pool.store(0, std::memory_order_relaxed);
quarantined.store(0, std::memory_order_relaxed);
dropped.store(0, std::memory_order_relaxed);
donated.store(0, std::memory_order_relaxed);
relocated.store(0, std::memory_order_relaxed);
stranded.store(0, std::memory_order_relaxed);
ssd_reads.store(0, std::memory_order_relaxed);
ssd_bytes.store(0, std::memory_order_relaxed);
stage_layers.store(0, std::memory_order_relaxed);
staged_units.store(0, std::memory_order_relaxed);
staged_bytes.store(0, std::memory_order_relaxed);
stage_overflow.store(0, std::memory_order_relaxed);
stage_copies.store(0, std::memory_order_relaxed);
file_layers.store(0, std::memory_order_relaxed);
file_units.store(0, std::memory_order_relaxed);
file_bytes.store(0, std::memory_order_relaxed);
file_preads.store(0, std::memory_order_relaxed);
file_read_ns.store(0, std::memory_order_relaxed);
file_wait_ns.store(0, std::memory_order_relaxed);
}
MoverStats snapshot() const {
MoverStats s;
s.dispatches = dispatches.load(std::memory_order_relaxed);
s.promotions = promotions.load(std::memory_order_relaxed);
s.demotions = demotions.load(std::memory_order_relaxed);
s.h2d_bytes = h2d_bytes.load(std::memory_order_relaxed);
s.d2h_bytes = d2h_bytes.load(std::memory_order_relaxed);
s.prefetched = prefetched.load(std::memory_order_relaxed);
s.prefetch_bytes = prefetch_bytes.load(std::memory_order_relaxed);
s.no_record = no_record.load(std::memory_order_relaxed);
s.starved_slab = starved_slab.load(std::memory_order_relaxed);
s.starved_pool = starved_pool.load(std::memory_order_relaxed);
s.quarantined = quarantined.load(std::memory_order_relaxed);
s.dropped = dropped.load(std::memory_order_relaxed);
s.donated = donated.load(std::memory_order_relaxed);
s.relocated = relocated.load(std::memory_order_relaxed);
s.stranded = stranded.load(std::memory_order_relaxed);
s.ssd_reads = ssd_reads.load(std::memory_order_relaxed);
s.ssd_bytes = ssd_bytes.load(std::memory_order_relaxed);
s.stage_layers = stage_layers.load(std::memory_order_relaxed);
s.staged_units = staged_units.load(std::memory_order_relaxed);
s.staged_bytes = staged_bytes.load(std::memory_order_relaxed);
s.stage_overflow = stage_overflow.load(std::memory_order_relaxed);
s.stage_copies = stage_copies.load(std::memory_order_relaxed);
s.file_layers = file_layers.load(std::memory_order_relaxed);
s.file_units = file_units.load(std::memory_order_relaxed);
s.file_bytes = file_bytes.load(std::memory_order_relaxed);
s.file_preads = file_preads.load(std::memory_order_relaxed);
s.file_read_ns = file_read_ns.load(std::memory_order_relaxed);
s.file_wait_ns = file_wait_ns.load(std::memory_order_relaxed);
return s;
}
};
/* ------------------------------------------------------------------ the mover */
class Mover {
public:
@@ -543,7 +630,8 @@ public:
}
int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; }
const MoverStats& stats() const { return stats_; }
/* A snapshot by value: the counters are atomics read while the rank thread writes them. */
MoverStats stats() const { return stats_.snapshot(); }
std::string report() const;
private:
@@ -624,7 +712,7 @@ private:
const Plan* plan_ = nullptr;
MoverConfig cfg_;
Residency res_;
MoverStats stats_;
MoverCounters stats_;
Pools* budget_ = nullptr;
/* True only when this object called the allocator itself (the test path). A Pool
* reservation belongs to the Pool; freeing it here would be a double free. */
+9 -14
View File
@@ -1053,10 +1053,9 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
/* --draft-expert-placement host: a draft head's routed experts (layers at meta.n_layers and above,
* and only when the program declares a drafter) go to the pinned host pool before any strategy
* runs. The card reads them in place at the DeviceZeroCopy site, the same way it reads a pooled
* expert, so a drafter's experts fit beside a trunk that already fills the card instead of the
* strategy having to make room for them on it. They are not movable: heat never promotes a draft
* expert onto the card and into the trunk's slab. */
* runs. The card reads them in place at the DeviceZeroCopy site, as it reads a pooled expert, so
* a drafter's experts fit beside a trunk that already fills the card. They are not movable: heat
* never promotes a draft expert onto the card and into the trunk's slab. */
int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const {
if (cfg.draft_expert_placement != "host") return RAD_OK;
if (prog.drafter.kind == RAD_DRAFT_NONE || prog.meta.n_layers == 0) {
@@ -1107,12 +1106,12 @@ int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p)
/* --expert-pin-top F: the hottest fraction of the routed experts, ranked by the profile the planner
* was given (the container's, or --expert-profile's decode counts), stay resident. They are marked
* unmovable, so the heat engine never demotes them and the decode-hot set stops paying the host
* unmovable, so the heat engine never demotes them and the decode-hot set never pays the host
* pool's PCIe read. The cut keeps the hottest ceil(F * n), and a tie at the cut stays movable: the
* threshold is the share just below the hot set, and only a share strictly above it pins. Runs
* after the strategy, which has already put the hot set in VRAM; a hot unit the strategy had to
* leave on the host is left there and counted, since pinning it would need VRAM the card does not
* have. */
* leave on the host stays there and is counted, since pinning it would need VRAM the card does
* not have. */
void Planner::pin_hot(const Config& cfg, Plan* p) const {
if (cfg.expert_pin_top <= 0.0f) return;
std::vector<float> shares;
@@ -1120,9 +1119,7 @@ void Planner::pin_hot(const Config& cfg, Plan* p) const {
if (mu.expert >= 0 && mu.tier != Tier::Mapped) shares.push_back(mu.profile_share);
if (shares.empty()) return;
std::sort(shares.begin(), shares.end());
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. A tie at
* the cut stays movable: the threshold is the share just below the hot set, and only a share
* strictly above it pins. */
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. */
const double keep = (double)cfg.expert_pin_top * (double)shares.size();
const size_t hot = keep <= 0.0 ? 0 : std::min(shares.size(), (size_t)std::ceil(keep));
const float threshold = hot == 0 ? shares.back() + 1.0f
@@ -1174,7 +1171,8 @@ int Planner::plan(Plan* out) {
build_classes(out);
/* After build_classes: a unit's slot_bytes is its class's stride, and the pins below charge
* the host pool that. Before it the charge would be zero and the pool would not hold them. */
* the host pool that. Before it the charge would be zero and the pool would not hold them.
* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
@@ -1212,9 +1210,6 @@ int Planner::plan(Plan* out) {
}
}
/* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. The pins ran above,
* once slot_bytes was known. */
int rc = assign(out);
enforce_op_site_agreement(prog, out);
schedule_prefetch(out);
+2 -3
View File
@@ -230,9 +230,8 @@ public:
int64_t tower_host_bytes = 0;
int64_t draft_host_bytes = 0;
int64_t forced_host_used = 0;
/* --expert-profile and --expert-pin-top: the profile's units the planner pinned resident and the
* share threshold it derived from the fraction. Reported so the window can see what the decode
* set costs the card. */
/* --expert-profile and --expert-pin-top: the units the planner pinned resident, the profiled
* units, and the share threshold it derived from the fraction (Plan::report). */
int64_t pinned_units = 0;
int64_t profile_units = 0;
float pin_threshold = 0.0f;
+31 -13
View File
@@ -367,6 +367,10 @@ public:
* encoder-only or embedding-only plugin does; the engine refuses to serve such a program at
* startup. */
rad_buf logits_buf = 0;
/* Scored steps (rad_declare_scores): the final-normed hidden rows and the bf16 head table.
* Zero when the plugin declared none. */
rad_buf score_hidden = 0;
rad_weight score_table = 0;
/* The step's pooled vectors (rad_declare_pooled): set only by an embedding program, which has
* no logits buffer. */
rad_buf pooled_buf = 0;
@@ -403,6 +407,10 @@ public:
int32_t drafter_pos_offset = 0;
/* A block drafter's shorter block (rad_drafter_short_block), 0 when it serves only its own. */
int64_t drafter_short_block = 0;
/* A block drafter that proposes a tree (rad_drafter_tree): `drafter_parents` holds each
* proposal's parent node, at the proposal's pitch. False and 0 for a chain drafter. */
bool drafter_tree = false;
rad_buf drafter_parents = 0;
/* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every
* text-only program, and every deployment with RadBuildCtx::max_enc_patches 0.
@@ -711,6 +719,9 @@ struct Request {
* (SchedReq owns this Request, so it outlives it) and is written alongside n_draft. Null when
* n_draft is 0. */
const int32_t* draft = nullptr;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent): draft[j]'s parent node,
* 0 the bonus token. Null for a chain. The sampler reads each row's ancestors from it. */
const int32_t* draft_parent = nullptr;
int32_t n_accepted = 0; /* from the previous verify */
/* Whether this request may be speculated on. Written by the engine after every step, read by
@@ -867,6 +878,9 @@ struct Config {
TablePlacement embedding_placement = TablePlacement::Ram;
bool embedding_placement_given = false;
TablePlacement ngram_placement = TablePlacement::Auto;
/* --ngram-placement ram=DIR: the pinned n-gram copy is the file DIR/ngram-<id>.tab (a tmpfs),
* mapped shared, so engines on separate cards hold one table. Empty: a private copy. */
std::string ngram_share_dir;
TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk;
/* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
@@ -907,13 +921,15 @@ struct Config {
* store is opened (checkpoint_slots_auto in core/mem/prefix.h). */
int64_t checkpoint_slots = -1;
bool prefix_cache = true;
/* --prefix-resume exact|nearest. Exact (the default) resumes a prefix hit only on the grid an
* idle server's cold prefill chunks the same prompt on (ChunkGeometry::grid), and takes a
* prompt's tail snapshot where its last chunk starts: the hit recomputes the cold run's own
* chunks, so its output is the cold run's bit for bit, where a kernel rounds a row differently
* at another chunk length. Nearest resumes at the deepest snapshot or block, a prompt's tail
* snapshot at its last quantum boundary: up to a chunk less re-prefilled a turn, and a hit that
* can differ from a cold run in the last bits (a near-tie in greedy text). */
/* --prefix-resume exact|nearest.
* - exact (the default): a prefix hit resumes only on the grid an idle server's cold prefill
* chunks the same prompt on (ChunkGeometry::grid), and a prompt's tail snapshot is taken
* where its last chunk starts. The hit recomputes the cold run's own chunks, so its output
* is the cold run's bit for bit even where a kernel rounds a row differently at another
* chunk length.
* - nearest: a hit resumes at the deepest snapshot or block, and a prompt's tail snapshot is
* at its last quantum boundary. Up to a chunk less is re-prefilled a turn, and a hit can
* differ from a cold run in the last bits (a near-tie in greedy text). */
bool prefix_exact = true;
/* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
* core/mem/prefix.h ships the two extremes so they can be compared. */
@@ -953,8 +969,10 @@ struct Config {
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
/* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in
* the step just run; 0 never. Ignored without a drafter that declares one. */
int64_t draft_short_from = 0; /* --draft-short-from */
* the step just run; 0 never. -1, auto: never for a chain, and from two for a tree
* (rad_drafter_tree), whose nodes are verify rows every drafting sequence pays for. Ignored
* without a drafter that declares a short block. */
int64_t draft_short_from = -1; /* --draft-short-from */
/* --draft-coupling off|on: a linear serial drafter (or DFlash2's block walk) samples its
* proposals and the sampler applies the maximal coupling at the verify
@@ -1096,10 +1114,10 @@ struct Config {
* share, keeping them resident: heat never demotes them. 0 is off. */
float expert_pin_top = 0.0f;
bool expert_pin_top_given = false;
/* --draft-expert-placement auto|host: a draft head's (MTP/DSpark) routed experts are pinned in
* the host pool before any strategy runs, streamed in place like a pooled expert. `auto` (the
* default) leaves them to the strategy. `host` is what lets a drafter's experts fit beside a
* trunk that already fills the card. */
/* --draft-expert-placement auto|host. `host` pins a draft head's (MTP/DSpark) routed experts
* in the host pool before any strategy runs, read in place like a pooled expert, so they fit
* beside a trunk that already fills the card. `auto` (the default) leaves them to the
* strategy. */
std::string draft_expert_placement = "auto";
bool draft_expert_placement_given = false;
/* --live: the live view (spec §16). Off by default like everything else in that section. */
+6
View File
@@ -29,6 +29,12 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...)
* the first. */
uint64_t log_last_line_ns();
/* A copy safe to interpolate into a log line: every byte below 0x20 but '\t', and DEL, becomes
* '?'. Client-controlled text reaches the log — session labels, echoed request fields — and an
* unfiltered newline forges a line while an ESC sequence drives the terminal that reads it.
* Multi-byte UTF-8 is left alone; only control bytes are replaced. */
std::string log_sanitize(const std::string& s);
/* Rank tags on log lines. Per-rank components (pools, planner, mover, sampler) print the same
* line once per rank, so under TP each line needs its rank. LogRank sets the tag as a scope
* because the printers are several layers down, where threading a rank argument through every
+5 -3
View File
@@ -929,7 +929,7 @@ int Ctx::lane_join(int from, int to) {
* field added to RadBatch changes its size: decide whether the key must read it, then update the
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
* (below). */
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 400,
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408,
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80,
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
@@ -957,7 +957,7 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
mix((uint64_t)b->n_checkpoints); mix((uint64_t)b->n_seq_decode);
mix((uint64_t)b->n_tok_decode); mix((uint64_t)b->max_q_len_decode);
mix((uint64_t)b->max_q_len_prefill); mix((uint64_t)b->n_draft_out); mix((uint64_t)b->n_ahead);
mix((uint64_t)b->rope_mixed); ptr(b->rope_pos);
mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); mix((uint64_t)b->score_only);
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
@@ -1396,7 +1396,9 @@ void Ctx::flush_issued() {
for (size_t r = 0; r < unflushed_.size(); ++r) {
const uint32_t i = unflushed_[r];
if (i < plans_.size() && i < program_->ops.size() && plans_[i].issued)
program_->ops[i].issued = true;
/* /graph reads this same bool from the HTTP thread: an atomic_ref store keeps that
* pair a relaxed exchange rather than a data race (ctx.h OpInfo::issued). */
std::atomic_ref<bool>(program_->ops[i].issued).store(true, std::memory_order_relaxed);
else
unflushed_[w++] = i;
}
+3 -1
View File
@@ -80,7 +80,9 @@ struct OpPlan {
* leave out. */
int32_t n_opd_schema = -1;
int32_t n_opd_required = -1;
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump);
the step path and the HTTP graph dump meet on it through
std::atomic_ref (Ctx::flush_issued, rad_graph.cpp) */
/* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows
* (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share
* the link and give way to it while it runs (Ctx::issue_body). */
+30
View File
@@ -38,6 +38,36 @@ namespace rad {
int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
int32_t* out, int32_t* n_accepted);
/* The same rule over a tree (rad_drafter_tree). Node 0 is the verify's first row (the bonus token
* it starts from); node j, 1 <= j <= n_draft, is draft[j - 1], verified at row j, and its parent
* is node parent[j - 1] (< j), or node j - 1 when `parent` is null (a chain). `target[r]` is the
* target's token after node r's row.
*
* From node 0, take the lowest-numbered child whose token is the target's at the current node,
* while there is one. Writes the walk's nodes to path[0..n_accepted) and the emitted tokens to
* out[0..n_accepted]: out[t] is the target's token at path[t - 1] (node 0 for t = 0), which equals
* the accepted draft there, and out[n_accepted] is the bonus. The card's acceptance
* (sched/advance_impl.h, ADV_ACCEPT) walks the same way. */
inline int accept_tree(const int32_t* draft, const int32_t* parent, int n_draft,
const int32_t* target, int32_t* out, int32_t* path, int32_t* n_accepted) {
if (!draft || !target || !out || !path || !n_accepted || n_draft < 0) return RAD_E_INVAL;
int32_t cur = 0, acc = 0;
for (;;) {
int32_t nxt = -1;
for (int32_t j = cur + 1; j <= n_draft; ++j) {
int32_t p = parent ? parent[j - 1] : j - 1;
if (p < 0 || p >= j) p = j - 1; /* as the builder and ADV_TRUNK read it */
if (p == cur && draft[j - 1] == target[cur]) { nxt = j; break; }
}
if (nxt < 0) break;
path[acc++] = nxt;
cur = nxt;
}
for (int32_t t = 0; t <= acc; ++t) out[t] = target[t == 0 ? 0 : path[t - 1]];
*n_accepted = acc;
return RAD_OK;
}
/* Where a verify step's emission ends: at the first end-of-generation token among `out`'s
* n_accepted + 1 tokens (accept_greedy's output), which is emitted, or after all of them. Returns
* the number of accepted drafts to commit, at most `n_accepted`. A drafter that predicts the stop
+49 -11
View File
@@ -3,6 +3,7 @@
*/
#include "sampler.h"
#include "gbnf.h"
#include "../sched/draft.h" /* RAD_SCHED_MAX_SPEC */
#include <algorithm>
#include <chrono>
@@ -618,8 +619,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
}
/* A constraining grammar does not rule out speculation: build_step masks draft position i
* against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
* refused. */
* against the state after drafts 0..i-1 (on a tree, after row i's ancestors) and then rewinds.
* Only a backend that cannot rewind is refused. */
bool Sampler::allows_speculation(uint64_t req_id) const {
auto it = seqs_.find(req_id);
if (it == seqs_.end() || !it->second.grammar) return true;
@@ -729,7 +730,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
* `dead` is not a failure: a draft the grammar forbids will be rejected at verification
* and every later position discarded, so masking stops for the rest of the window. */
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
const bool walk = gr && n_pos > 1;
/* A tree (rad_drafter_tree) is walked per row instead: row k's prefix is its ancestors,
* not drafts 0..k-1, so each row pushes the committed state, advances over its own path,
* is masked, and rolls back. A refused ancestor kills that row only: verification never
* reaches it, while a sibling's path may still be admissible. */
const int32_t* tpar = r->draft_parent;
const bool walk = gr && n_pos > 1 && !tpar;
const bool walk_tree = gr && n_pos > 1 && tpar;
if (walk) gr->push_state();
bool dead = false;
@@ -746,10 +753,38 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
st->think.push(sp.reasoning, r->output[st->think_seen]);
think = st->think;
}
const ReasoningCount think0 = think;
for (int k = 0; k < n_pos; ++k) {
/* Row k's drafts before it: 0..k-1 on a chain, its ancestors (root first) on a tree. */
int32_t anc[RAD_SCHED_MAX_SPEC];
int32_t dk = 0;
if (tpar) {
int32_t chain[RAD_SCHED_MAX_SPEC];
for (int32_t j = k; j > 0 && dk < RAD_SCHED_MAX_SPEC;) {
chain[dk++] = j;
int32_t pj = tpar[j - 1];
j = (pj < 0 || pj >= j) ? j - 1 : pj;
}
for (int32_t t = 0; t < dk; ++t) anc[t] = r->draft[chain[dk - 1 - t] - 1];
} else {
for (; dk < k; ++dk) anc[dk] = r->draft[dk];
}
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
bool row_dead = false; /* a tree row whose path the grammar refuses */
bool pushed = false;
if (walk_tree && dk > 0) {
RAD_TRY(gr->push_state());
pushed = true;
for (int32_t t = 0; t < dk && !row_dead; ++t)
row_dead = gr->accept_token(anc[t]) < 0;
}
if (budget && tpar) {
think = think0;
for (int32_t t = 0; t < dk; ++t) think.push(sp.reasoning, anc[t]);
} else if (budget && k > 0) {
think.push(sp.reasoning, r->draft[k - 1]);
}
const int64_t row = n_seq_++;
/* Row k verifies draft k against the state its round left. A row with no bound state
* (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify
@@ -781,8 +816,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
p.seed = sp.seed;
/* Output position: draft position k is token n_out + k, so its draw is the same with
* or without speculation. */
p.pos = (uint64_t)(n_out + k);
* or without speculation. On a tree it is the row's depth: siblings share a prefix
* length, hence a coordinate, hence the target's draw there. */
p.pos = (uint64_t)(n_out + dk);
p.temp = sp.temp;
p.top_p = sp.top_p;
@@ -857,14 +893,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
* this span, so the reference's update order holds at a verify: position k sees the
* drafts before it, as the processor would after emitting them. */
if (pen || dry || ngram) {
const int64_t len = n_total + k;
const int64_t len = n_total + dk;
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
int32_t* h = hist_stage_ + row * cfg_.max_hist;
for (int64_t i = 0; i < take; ++i) {
const int64_t src = len - take + i;
h[i] = src < n_prompt ? r->prompt[(size_t)src]
: src < n_total ? r->output[(size_t)(src - n_prompt)]
: r->draft[src - n_total];
: anc[src - n_total];
}
p.hist_len = (int32_t)take;
if (pen) p.flags |= RAD_SP_PENALTY;
@@ -874,7 +910,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
}
if (gr && !dead && gr->constrains()) {
if (gr && !dead && !row_dead && gr->constrains()) {
uint32_t* dst = mask_stage_ + row * mask_words_;
int s;
/* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
@@ -914,8 +950,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
}
if (s < 0 && k > 0) {
/* At a draft position this only means a draft is wrong; verification
* rejects at or before here, so stop masking the rest of the window. */
dead = true;
* rejects at or before here, so stop masking the rest of the window. On a
* tree only this row's path is wrong; its siblings are masked on. */
if (!tpar) dead = true;
} else if (s < 0) {
/* A dead grammar fails its request, not the step: an error status would stop
* the step loop for every client. The row stays unmasked and the engine
@@ -939,6 +976,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
}
}
}
if (pushed) RAD_TRY(gr->rollback()); /* back to the committed state for the next row */
if (budget && think.inside() && think.body >= sp.thinking_budget)
force_close(p, row, sp.reasoning.close);
+2 -1
View File
@@ -167,7 +167,8 @@ public:
/* False only for a constraining grammar whose backend cannot snapshot its state. Masking a
* draft window walks the grammar over the drafts and rewinds, which needs
* push_state/rollback; without it the request decodes one token at a time. */
* push_state/rollback (a tree's rows each walk their own ancestors); without it the request
* decodes one token at a time. */
bool allows_speculation(uint64_t req_id) const;
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
* whose backend cannot rewind starts to constrain (on a commit). */
+20
View File
@@ -23,4 +23,24 @@ int step_advance(const AdvanceArgs& a, RadStream s) {
#endif
}
int step_compact(const AdvanceArgs& a, RadStream s) {
if (a.n_seq <= 0 || a.n_pool <= 0) return RAD_OK;
if (device_is_host()) {
RAD_TRY(rad_stream_sync(s));
const int items = adv_compact_items(a);
for (int i = 0; i < a.n_seq; ++i)
for (int w = 0; w < items; ++w) {
int p = 0, l = 0, h = 0;
if (adv_compact_item(a, w, &p, &l, &h)) adv_compact(a, i, p, l, h, 0, 1);
}
return RAD_OK;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
return rad_step_compact_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
#else
(void)s;
return RAD_E_UNSUPPORTED;
#endif
}
} /* namespace rad */
+53 -1
View File
@@ -35,7 +35,20 @@ struct StepSlot {
int32_t acc; /* drafts the last verify step accepted */
/* The next verify step's input tokens: the bonus token, then the draft head's proposals. */
int32_t tok[1 + RAD_SCHED_MAX_SPEC];
int32_t pad[3];
/* A tree drafter's proposal (rad_drafter_tree): par[j] is the parent of node j + 1, a node
* index in [0, j], where node 0 is the bonus token tok[0] and node j + 1 is tok[j + 1].
* `ntree` is the number of nodes it describes, written by ADV_BTAKE from the drafter's
* parents plane; 0 means tok[1..] is a chain. */
int32_t par[RAD_SCHED_MAX_SPEC];
int32_t ntree;
/* The last verify's accepted root path: path[t] is the node committed (t + 1)-th, so the
* committed tokens are tok[path[0]], tok[path[1]], ... and the step's anchor sits at
* ctx - 1 - npath. ADV_COMPACT moves those nodes' K and V from where the verify stored them
* (its row index) to where they belong (their depth), and ADV_CTXTREE positions the
* drafter's context rows by it. 0 after a chain verify, which needs neither. */
int32_t npath;
int32_t path[RAD_SCHED_MAX_SPEC];
int32_t pad[2];
};
enum AdvMode : int32_t {
@@ -47,6 +60,26 @@ enum AdvMode : int32_t {
/* A block drafter (RAD_DRAFT_BLOCK) on the card: */
ADV_BLOCK = 6, /* before the query pass: the anchor at the committed end, then the masks */
ADV_BTAKE = 7, /* after it: its `round` proposals into the state, behind the bonus token */
/* A tree drafter (rad_drafter_tree), whose verify rows are a tree rather than a chain: */
ADV_CTXTREE = 8, /* before the context pass: the accepted path's rows at their depth, the
* rejected rows stored nowhere */
};
/* The most paged KV groups one ADV_COMPACT moves (the trunk's sliding and global groups and a
* drafter's own, with room). */
enum { kAdvMaxPools = 6 };
/* One paged group's cache on one rank, as ADV_COMPACT addresses it: `n_layers` caches of
* [n_blocks, n_head, block_size, row_bytes] bytes, `layer_stride` apart from `base`
* (core/runtime/kvbind.cpp composes that shape). `grp` indexes the batch's AdvGroup array, whose
* block table maps a position to a block. */
struct AdvPool {
char* base;
int64_t layer_stride;
int32_t n_layers;
int32_t n_head;
int32_t row_bytes;
int32_t grp;
};
/* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab,
@@ -112,12 +145,31 @@ struct AdvanceArgs {
* position of those rows, 0 or 1 past the committed position. Zero for every other head. */
int32_t shared_kv = 0;
int32_t rot_shift = 0;
/* A tree drafter (rad_drafter_tree). ADV_BTAKE: the proposal's parents plane, row i's from
* i * src_pitch as the tokens are; null for a chain drafter. */
const int32_t* par = nullptr;
/* ADV_TRUNK: RadBatch::spec_parent [n_tok] in the slab, or -1 when the build stages none.
* A tree row's entry is its parent's row within the sequence's block (-1 for the bonus
* token); every other row's is -2, an ordinary causal row. */
int64_t parent_off = -1;
/* ADV_COMPACT: every paged group's cache on this rank. */
AdvPool pool[kAdvMaxPools] = {};
int32_t n_pool = 0;
};
/* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */
int step_advance(const AdvanceArgs& a, RadStream s);
/* ADV_COMPACT, after ADV_ACCEPT on a tree verify and before anything reads the trunk's cache: for
* every row whose StepSlot holds an accepted path, move the K and V each path node's verify row
* stored (at the anchor's position + its row index) to its committed position (+ its depth), in
* every pool of `a`, every layer and every head. A separate kernel from the advance because it
* moves bytes across the whole cache rather than patching a row's few integers. */
int step_compact(const AdvanceArgs& a, RadStream s);
} /* namespace rad */
/* The launcher in advance.hip: one kernel onto `stream` through hipLaunchKernel. */
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream);
/* And ADV_COMPACT's. */
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream);
+43
View File
@@ -59,8 +59,51 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr
}
}
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
* split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every
* block waiting for the kernels before it and counting itself in after its moves. */
constexpr int kCompactThreads = 64;
__device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) {
int p = 0, l = 0, h = 0;
if (!rad::adv_compact_item(a, (int)blockIdx.x, &p, &l, &h)) return;
rad::adv_compact(a, (int)blockIdx.y, p, l, h, (int)threadIdx.x, kCompactThreads);
}
__global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::AdvanceArgs a) {
step_compact_body(a);
}
__global__ __launch_bounds__(kCompactThreads) void r4dchain_step_compact(rad::AdvanceArgs a) {
const ChainRec* r = chain_rec();
if (r) {
if (threadIdx.x == 0)
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
__builtin_amdgcn_s_sleep(1);
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
}
step_compact_body(a);
if (r) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__syncthreads();
if (threadIdx.x == 0)
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
}
} // namespace
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
const int items = rad::adv_compact_items(*args);
if (items <= 0) return 0;
if (!rad_dev_chain_enabled())
hipLaunchKernelGGL(rad_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
else
hipLaunchKernelGGL(r4dchain_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads);
+171 -13
View File
@@ -28,6 +28,20 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
return lo < a.n_eog && a.eog[lo] == t;
}
/* Group `e`'s slot for position `p` of batch row `i`, or -1 past its block table. A runtime
* window's position at or past ring_pos is in its ring (see adv_groups). */
RAD_ADV_FN int32_t adv_slot(const AdvanceArgs& a, const AdvGroup& e, int i, int32_t p) {
const int32_t first = adv_i32(a, e.first_off)[i];
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t bi = (p - first) / e.block_size;
if (e.ring && e.ring_blocks > 0 && adv_i32(a, e.tlen_off)[i] > 0) {
const int32_t rpos = adv_i32(a, e.rpos_off)[i];
if (p >= rpos) bi = rpos / e.block_size + ((p - rpos) / e.block_size) % e.ring_blocks;
}
return (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
}
/* Every group's slots for the row's `n` positions (from the positions just written) and its
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
* tables for the furthest reachable position, so only a row whose output is unused hits this.
@@ -43,16 +57,18 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
* off the table once the ring wraps.
*
* `len`, when given, is the length's count from `base` in place of `n` (ADV_HIST: rows that
* repeat a position must not lengthen the context). */
* repeat a position must not lengthen the context). `at`, when given, is where each row stores its
* K and V instead of its position: a tree verify's rows rotate at their depth but store at their
* row index, since siblings share a depth (ADV_TRUNK), and a context row the tree rejected stores
* nowhere (-1, ADV_CTXTREE). */
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n,
int32_t len = -1) {
int32_t len = -1, const int32_t* at = nullptr) {
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
const int32_t* pos = adv_i32(a, a.pos_off);
for (int g = 0; g < a.n_groups; ++g) {
const AdvGroup& e = G[g];
const int32_t first = adv_i32(a, e.first_off)[i];
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
const bool ring = e.ring && tlen > 0;
int64_t used = (int64_t)base + (len >= 0 ? len : n) - first;
@@ -62,20 +78,22 @@ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base,
}
adv_i32(a, e.used_off)[i] = (int32_t)used;
if (!e.paged) continue;
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t* slot = adv_i32(a, e.slot_off);
for (int32_t j = 0; j < n; ++j) {
const int32_t p = pos[k + j];
int32_t bi = (p - first) / e.block_size;
if (ring && p >= rpos && e.ring_blocks > 0)
bi = rpos / e.block_size +
((p - rpos) / e.block_size) % e.ring_blocks;
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
const int32_t p = at ? at[j] : pos[k + j];
slot[k + j] = p >= 0 ? adv_slot(a, e, i, p) : -1;
}
}
}
/* A tree's node depths from its parents: node 0 (the bonus token) at 0, node j + 1 one below
* par[j]. A parent outside [0, j] is a drafter bug; it is read as the previous node, so the row
* still stores and rotates somewhere sane, and the verify rejects whatever it proposed. */
RAD_ADV_FN int32_t adv_parent(const StepSlot& S, int32_t j) {
const int32_t p = S.par[j - 1];
return (p < 0 || p >= j) ? j - 1 : p;
}
/* Writes a row's position and moves its rotary components by the same amount. A row whose
* position does not change keeps the host's components. */
RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
@@ -108,10 +126,39 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
switch (a.mode) {
case ADV_ACCEPT: {
const int32_t* y = a.src + rout;
/* A tree verify, which the trunk's spec_parent row says (its first entry is -1, the root,
* whoever staged it: ADV_TRUNK for a card row, the builder for a host row): accept_tree's
* rule. From the bonus token, follow the first child (lowest node index) whose token is
* the target's pick at its parent's row, as long as one is; then the same
* end-of-generation cut over the tokens that walk emits. */
const int32_t* tp = a.parent_off >= 0 ? adv_i32(a, a.parent_off) + rtok : nullptr;
if (tp && aux > 0 && tp[0] == -1) {
const int32_t* d = tok + rtok; /* node j's token is d[j], 1 <= j <= aux */
const int32_t a0 = rtok - k; /* parents count rows from the sequence's first */
int32_t cur = 0, acc = 0;
for (;;) {
int32_t nxt = -1;
for (int32_t j = cur + 1; j <= aux; ++j)
if (tp[j] - a0 == cur && d[j] == y[cur]) { nxt = j; break; }
if (nxt < 0) break;
S.path[acc++] = nxt;
cur = nxt;
}
for (int32_t t = 0; t <= acc; ++t)
if (adv_is_eog(a, y[t == 0 ? 0 : S.path[t - 1]])) { acc = t; break; }
const int32_t head = ctx[i] + (rtok - k) + acc;
S.acc = acc;
S.head = head;
S.ctx = head + 1;
S.n_acc = acc + 1;
S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]];
S.npath = acc;
return;
}
/* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
* while it equals the target's pick at its position, and the run stops at an
* end-of-generation token, not after it. */
const int32_t* y = a.src + rout;
const int32_t* d = tok + rtok + 1;
int32_t acc = 0;
while (acc < aux && d[acc] == y[acc]) ++acc;
@@ -123,16 +170,64 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
S.ctx = head + 1;
S.n_acc = acc + 1;
S.tok[0] = y[acc];
S.npath = 0;
return;
}
case ADV_TRUNK: {
const int32_t base = S.ctx;
if (a.parent_off >= 0) {
int32_t* par = adv_i32(a, a.parent_off);
/* A row verifying fewer nodes than the drafter proposed (a window cut it) verifies
* their prefix, which is a tree too: every parent precedes its child. */
if (n > 1 && S.ntree >= n - 1) {
/* A tree: node j stores its K and V at base + j (siblings share a depth, so the
* position cannot address them) and rotates at base + its depth, the position the
* token would have if its path were committed. Attention reads spec_parent to see
* only a row's own ancestors inside the block. */
int32_t dep[1 + RAD_SCHED_MAX_SPEC], at[1 + RAD_SCHED_MAX_SPEC];
for (int32_t j = 0; j < n; ++j) {
const int32_t p = j == 0 ? -1 : adv_parent(S, j);
dep[j] = j == 0 ? 0 : dep[p] + 1;
tok[k + j] = S.tok[j];
par[k + j] = p;
adv_pos(a, pos, k + j, base + dep[j]);
at[j] = base + j;
}
ctx[i] = base;
adv_i32(a, a.acc_off)[i] = S.n_acc;
adv_groups(a, i, k, base, n, -1, at);
return;
}
for (int32_t j = 0; j < n; ++j) par[k + j] = -2;
}
for (int32_t j = 0; j < n; ++j) { tok[k + j] = S.tok[j]; adv_pos(a, pos, k + j, base + j); }
ctx[i] = base;
adv_i32(a, a.acc_off)[i] = S.n_acc;
adv_groups(a, i, k, base, n);
return;
}
case ADV_CTXTREE: {
/* The drafter's context pass over a tree verify's rows (one per node, in node order, as
* the trunk tapped them), a card row only where the host marked the step's entry as one.
* Only the accepted path is context: path node t's row writes at the anchor + t + 1,
* rotated there, which is where its token now sits, and every rejected node's row stores
* nowhere. Run after ADV_ACCEPT, which wrote the path, and before ADV_BTAKE. A chain
* verify's path is its first `acc` rows (npath 0). */
const int32_t base = S.head - S.acc;
int32_t at[1 + RAD_SCHED_MAX_SPEC];
at[0] = base;
adv_pos(a, pos, k, base);
for (int32_t j = 1; j < n; ++j) { at[j] = -1; adv_pos(a, pos, k + j, base); }
for (int32_t t = 0; t < S.acc; ++t) {
const int32_t r = t < S.npath ? S.path[t] : t + 1;
if (r < 1 || r >= n) continue;
at[r] = base + t + 1;
adv_pos(a, pos, k + r, base + t + 1);
}
ctx[i] = base;
adv_groups(a, i, k, base, n, -1, at);
return;
}
case ADV_HIST: {
if (a.shared_kv) {
/* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
@@ -205,13 +300,76 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
return;
}
case ADV_BTAKE:
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. */
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. A tree
* drafter's parents come with the tokens, at the same pitch. */
for (int32_t j = 0; j < a.round; ++j)
S.tok[1 + j] = a.src[(int64_t)i * a.src_pitch + j];
if (a.par) {
for (int32_t j = 0; j < a.round; ++j) S.par[j] = a.par[(int64_t)i * a.src_pitch + j];
S.ntree = a.round;
} else {
S.ntree = 0;
}
return;
default:
return;
}
}
/* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at
* base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its
* child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads:
* a destination base + t + 1 is either the node's own place or a place a node already moved out
* of. Each caller keeps one chunk set across every t, so its reads and writes stay in order. */
RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, int c0, int cstep) {
/* Only a row that sampled in this step: ADV_ACCEPT just wrote its slot. Any other row's slot
* may hold a path from an earlier request that used the same slot. */
const int32_t* rows = adv_i32(a, a.row_off);
if (rows[2 * a.row_pitch + i] < 0) return;
const StepSlot& S = a.st[adv_i32(a, a.sid_off)[i]];
const int32_t np = S.npath < S.acc ? S.npath : S.acc;
if (np <= 0) return;
const AdvPool& P = a.pool[p];
if (!P.base || l >= P.n_layers || h >= P.n_head) return;
const AdvGroup& e = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off)[P.grp];
if (!e.paged) return;
const int32_t base = S.head - S.acc;
const int32_t bs = e.block_size;
char* lay = P.base + (int64_t)l * P.layer_stride;
const int32_t chunks = P.row_bytes / 16;
for (int32_t t = 0; t < np; ++t) {
const int32_t src = base + S.path[t], dst = base + t + 1;
if (src == dst) continue;
const int32_t ss = adv_slot(a, e, i, src), ds = adv_slot(a, e, i, dst);
if (ss < 0 || ds < 0) continue;
const uint32_t* from = reinterpret_cast<const uint32_t*>(
lay + (((int64_t)(ss / bs) * P.n_head + h) * bs + ss % bs) * P.row_bytes);
uint32_t* to = reinterpret_cast<uint32_t*>(
lay + (((int64_t)(ds / bs) * P.n_head + h) * bs + ds % bs) * P.row_bytes);
for (int32_t c = c0; c < chunks; c += cstep) {
const uint32_t v0 = from[4 * c], v1 = from[4 * c + 1], v2 = from[4 * c + 2],
v3 = from[4 * c + 3];
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
}
}
}
/* The (pool, layer, head) of ADV_COMPACT's work item `w`, counting every pool's layers x heads in
* order; false past the last. */
RAD_ADV_FN bool adv_compact_item(const AdvanceArgs& a, int w, int* p, int* l, int* h) {
for (int q = 0; q < a.n_pool; ++q) {
const int n = a.pool[q].n_layers * a.pool[q].n_head;
if (w < n) { *p = q; *l = w / a.pool[q].n_head; *h = w % a.pool[q].n_head; return true; }
w -= n;
}
return false;
}
RAD_ADV_FN int adv_compact_items(const AdvanceArgs& a) {
int n = 0;
for (int q = 0; q < a.n_pool; ++q) n += a.pool[q].n_layers * a.pool[q].n_head;
return n;
}
} /* namespace rad */
+45 -10
View File
@@ -866,14 +866,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(long long)max_seqs_, (long long)max_tok_);
return nullptr;
}
if (plan.spec_is_tree) {
/* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
* and positions are not written. Filling in the linear-chain answer would verify a tree
* against the wrong causal mask. */
RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
return nullptr;
}
Set& s = set_;
const int64_t n_seq = (int64_t)plan.e.size();
@@ -963,6 +955,29 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
s.h_pos[k + j] = e.ctx_len + j;
}
/* A tree verify (RadBatch::spec_parent): every verify block of a tree step is staged as
* a tree, a chain proposal (prompt lookup) as the tree whose node j hangs off j - 1, so
* the card's acceptance and the host's agree on every row. Node j stores its K and V at
* its row's position (the slots below are unchanged) and rotates at the anchor + its
* depth. A parent is named by its row within the sequence's rows (from cu_seqlens), the
* index an attention kernel has. A card row is restaged by ADV_TRUNK from its StepSlot. */
if (plan.spec_is_tree) {
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_parent[k + j] = -2;
if (e.produces_token && !e.is_prefill && e.n_spec > 0 &&
e.n_spec < e.n_tokens && e.n_spec <= RAD_SCHED_MAX_SPEC) {
const int32_t a0 = e.n_tokens - 1 - e.n_spec; /* the anchor's row */
int32_t dep[1 + RAD_SCHED_MAX_SPEC];
dep[0] = 0;
s.h_parent[k + a0] = -1;
for (int32_t j = 1; j <= e.n_spec; ++j) {
int32_t p = e.draft_parent ? e.draft_parent[j - 1] : j - 1;
if (p < 0 || p >= j) p = j - 1;
dep[j] = dep[p] + 1;
s.h_parent[k + a0 + j] = a0 + p;
s.h_pos[k + a0 + j] = e.ctx_len + a0 + dep[j];
}
}
}
/* Every row of a sequence runs with its request's adapter (RadBatch::lora_slot), fixed at
* admission; a placeholder row with no request is a base row. */
if (lora_on_) {
@@ -979,7 +994,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
for (int32_t j = 0; j < e.n_tokens; ++j) {
int32_t v[3];
const int64_t p = (int64_t)e.ctx_len + j;
/* h_pos, not ctx_len + j: a tree verify's rows rotate at their depth. */
const int64_t p = (int64_t)s.h_pos[k + j];
if (rl) rl->at(p, v);
else v[0] = v[1] = v[2] = (int32_t)p;
s.h_rope[k + j] = v[0];
@@ -1155,6 +1171,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
mm_ev_live_ = true;
}
/* A scored step (RadBatch::score_only): every sampled row is a scored request's first row, on
* one rank, in a program that told the core where its hidden rows and head table are. */
int32_t score_only = 0;
if (n_out > 0 && n_dout == 0 && !plan.draft_pass && ranks_.size() == 1 &&
prog_->score_hidden != RAD_NULL_HANDLE && prog_->score_table != RAD_NULL_HANDLE) {
score_only = 1;
for (const StepEntry& e : plan.e) {
if (!e.produces_token) continue;
if (!e.req || !e.req->token_scores || !e.req->output.empty() || e.n_spec > 0) {
score_only = 0;
break;
}
}
}
/* ---------------------------------------------------------- the batch, one per rank */
for (size_t r = 0; r < ranks_.size(); ++r) {
void* const base = s.dev[r];
@@ -1170,6 +1201,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.seq_ids = on_rank(base, b0, s.d_sid);
B.n_out = n_out;
B.out_ids = n_out ? on_rank(base, b0, s.d_out) : nullptr;
B.score_only = score_only;
B.n_draft_out = n_dout;
B.draft_out_ids = n_dout ? on_rank(base, b0, s.d_dout) : nullptr;
B.q_lens = on_rank(base, b0, s.d_q);
@@ -1188,7 +1220,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
* without drafts may follow one that had drafts, and the linear kernels need its accepted
* count instead of their absent-operand default of 1. */
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */
/* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */
B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr;
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
B.rope_mixed = rope_mixed;
B.n_mm_rows = n_mm;
@@ -1232,6 +1265,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
++ring_.live;
last_n_seq_ = n_seq;
last_n_tok_ = n_tok;
last_tree_ = plan.spec_is_tree;
ring_.head = off + used;
out_last_ = out_next_;
out_next_ = (out_next_ + 1) % kOut;
@@ -1263,6 +1297,7 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
a.cu_off = off(s.d_cu);
a.q_off = off(s.d_q);
a.row_off = off(s.d_rows);
a.parent_off = last_tree_ ? off(s.d_parent) : -1;
a.row_pitch = (int32_t)max_seqs_;
a.grp_off = off(s.d_grp);
if (mm_on_) {
+5
View File
@@ -41,6 +41,10 @@ struct StepEntry {
int32_t ckpt_restore = -1;
const int32_t* draft = nullptr; /* the drafter's proposal, appended after the committed tail */
int32_t n_draft = 0;
/* A tree drafter's proposal (rad_drafter_tree): draft_parent[j] is the parent of draft[j] as a
* node index (0 the anchor, j + 1 draft[j]). Null for a chain. Read only on a tree step
* (StepPlan::spec_is_tree), where a null one is staged as the chain. */
const int32_t* draft_parent = nullptr;
/* First logits row, written into `out_ids`, that this entry reads, or -1 for the default
* rule. The MTP history pass uses it to gather the 1 + n_spec trunk rows of a verifying
* sequence; the DFlash2 query pass uses it to name the mask rows of its own block. Which
@@ -319,6 +323,7 @@ private:
int64_t pay_words_ = 0; /* payload build_groups wrote, in int32 words */
void forget_tables();
int64_t last_n_seq_ = 0;
bool last_tree_ = false; /* the last build staged spec_parent (advance_args' parent_off) */
int64_t derived_bytes_ = 0;
std::vector<Derived> derived_;
+34 -20
View File
@@ -38,6 +38,30 @@ int64_t prefill_shared_tok(const Config& cfg) {
return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
}
/* What a prefix hit restores beside the cached blocks: linear state, or a trunk's sliding window.
* Only the trunk's window makes a model take window snapshots; a block drafter's rides in them
* where they exist (KVManager::set_drafter_window_snapshot) and is recomputed by draft refill
* where they do not. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt length, which no
* slot could describe, so it is sized for the context plus a ring and is never checkpointed. */
static void restored_state(const Program& prog, bool* linear, bool* window) {
*linear = *window = false;
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind != RAD_KV_FULL && kg.decl.kind != RAD_KV_WINDOW &&
kg.decl.kind != RAD_KV_RING)
*linear = true;
else if (kg.decl.kind == RAD_KV_WINDOW && kg.block_size > 0 && !kg.layers.empty() &&
!kg.drafter)
*window = true;
}
}
bool window_snapshots(const Program& prog, const Config& cfg) {
bool linear = false, window = false;
restored_state(prog, &linear, &window);
return !linear && window && cfg.prefix_cache && cfg.checkpoint_interval > 0;
}
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
if (!out) return RAD_E_INVAL;
ChunkGeometry g;
@@ -46,22 +70,12 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
/* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
* served by a different kernel may differ (§7.2). */
bool has_linear = false, has_window = false;
restored_state(prog, &has_linear, &has_window);
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) {
if (kg.block_size > 0) {
g.attn_block = lcm64(g.attn_block, kg.block_size);
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
* length, which no slot could describe, so it is sized for the context plus a ring
* and is never checkpointed. */
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
has_window = true;
}
} else {
has_linear = true;
if ((kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) && kg.block_size > 0) {
g.attn_block = lcm64(g.attn_block, kg.block_size);
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
}
}
@@ -152,11 +166,11 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
}
/* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A
* prefill alone in its step takes the budget, rounded down to the quantum, and stops at every
* interval boundary it reaches where chunks split at the interval (linear state, or periodic
* window snapshots); a span carries h intervals from the second one on. An interval past the
* budget must then be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the grid every cold run cuts: rounded up, as the quantum rounds it, since a longer
* prefill alone in its step takes the budget, rounded down to the quantum. Where chunks split
* at the interval (linear state, or periodic window snapshots) it stops at every interval
* boundary it reaches, and a span carries h intervals from the second one on. An interval past
* the budget must be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the cold run's grid; it is rounded up, as the quantum rounds it, since a longer
* interval costs only retention. */
const int64_t I0 = g.checkpoint_interval;
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
+13 -8
View File
@@ -61,14 +61,14 @@ struct ChunkGeometry {
bool window_periodic = false;
/* --prefix-resume exact (Config::prefix_exact): a prefix hit resumes only where a cold prefill
* of the same prompt starts a chunk, so the tokens a hit recomputes are cut into the chunks a
* cold run cuts them into. A kernel may round a row differently at another chunk length (a
* split-K count chosen from M, a small-M path); computed in the same chunks, the hit's output
* is the cold run's, bit for bit, on an idle server. The grid is where an idle server's prefill
* chunks start: 0, then grid_origin + k * grid. `grid` is the checkpoint interval where chunks
* split at it and it fits the budget, times the span from the second interval on (origin = the
* interval), and otherwise --max-num-batched-tokens rounded down to the quantum (the interval
* is then rounded up to a multiple of it). Zero when not exact. */
* of the same prompt starts a chunk, so the tokens it recomputes are cut into the cold run's
* chunks. A kernel may round a row differently at another chunk length (a split-K count chosen
* from M, a small-M path); in the same chunks, on an idle server, the hit's output is the cold
* run's bit for bit. The grid is where an idle server's prefill chunks start: 0, then
* grid_origin + k * grid. Where chunks split at the interval and it fits the budget, `grid` is
* the interval times the span the budget holds, from grid_origin = the interval when that span
* is over 1. Otherwise `grid` is --max-num-batched-tokens rounded down to the quantum, and the
* interval is rounded up to a multiple of it. Zero when not exact. */
bool exact = false;
int64_t grid = 0;
int64_t grid_origin = 0;
@@ -91,6 +91,11 @@ struct ChunkGeometry {
* (RadBuildCtx::max_mixed_tok) and the scheduler plans by it, so the two agree. */
int64_t prefill_shared_tok(const Config& cfg);
/* ChunkGeometry::window_ckpt from the program and the configuration alone, without resolving or
* reporting the geometry: a trunk's sliding window, no linear state, a prefix cache and an
* interval. Bring-up asks it before the geometry is resolved (Engine::drafter_window_snap). */
bool window_snapshots(const Program& prog, const Config& cfg);
/* Resolve the geometry from the declared program and the operator's budgets.
*
* Returns RAD_E_INVAL when cfg.max_tok is too small (the required number is in
+15 -1
View File
@@ -79,6 +79,13 @@ struct IKVManager {
* instead of deadlocking the engine (spec §17). */
virtual bool can_ever_fit(int64_t n_tokens) const = 0;
/* Whether `seq` can be grown to `n_tokens` without taking blocks from another sequence. */
virtual bool can_grow(uint64_t seq, int64_t n_tokens) const = 0;
/* How many blocks a paged group can still hand out, including those lent to the expert slab
* and recallable on demand. */
virtual int64_t available_blocks(int32_t group) const = 0;
virtual const std::vector<int32_t>& block_table(uint64_t seq, int32_t group) const = 0;
virtual int32_t state_slot(uint64_t seq, int32_t group) const = 0;
@@ -172,10 +179,14 @@ struct IPrefixCache {
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
* `blocks_out` receives block ids per cached group, in cached_groups() order, for
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not
* null, ends the hit early (HitCap, core/mem/prefix.h). */
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const = 0;
virtual const std::vector<int32_t>& cached_groups() const = 0;
/* The drafter's refill window (Scheduler::init): retention keeps a snapshot that deep below a
* session's tip, so a refill-capped hit has one to end on (PrefixCache::set_drafter_floor). */
virtual void set_drafter_floor(int64_t) {}
/* Publish what this sequence computed so a later request sharing the prefix can adopt it.
* `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
@@ -331,6 +342,7 @@ struct KVBinding final : IKVManager {
}
int preempt(uint64_t s) override { return m->preempt(s); }
bool can_ever_fit(int64_t n) const override { return m->can_ever_fit(n); }
bool can_grow(uint64_t s, int64_t n) const override { return m->can_grow(s, n); }
const std::vector<int32_t>& block_table(uint64_t s, int32_t g) const override {
return m->block_table(s, g);
}
@@ -340,6 +352,7 @@ struct KVBinding final : IKVManager {
}
int64_t state_index_width(int32_t g) const override { return m->state_index_width(g); }
int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); }
int64_t available_blocks(int32_t g) const override { return m->available_blocks(g); }
int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); }
int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); }
int64_t held_top_blocks(int32_t g) const override { return m->held_top_blocks(g); }
@@ -472,6 +485,7 @@ struct PCBinding final : IPrefixCache {
}
void release(const Request& r) override { m->release(r.id); }
const std::vector<int32_t>& cached_groups() const override { return m->cached_groups(); }
void set_drafter_floor(int64_t tokens) override { m->set_drafter_floor(tokens); }
/* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
* prompt alone would stop hitting at the first assistant token. */
+161 -43
View File
@@ -146,7 +146,10 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
"drafter's window is recomputed", (long long)draft_refill_);
}
if (pc) pc->set_drafter_floor(draft_refill_);
/* A tree drafter (rad_drafter_tree): every trunk step verifies its proposals as trees. */
tree_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter_tree;
serial_shared_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_SERIAL &&
prog.drafter_shared_kv;
serial_rot_shift_ = serial_shared_ ? prog.drafter_pos_offset : 0;
@@ -260,6 +263,17 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
/* An embedding input runs in one step or not at all (Request::embed); one longer than a step
* could never be admitted. */
if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
/* Every prompt id, tokenised or client-supplied, names a real vocabulary row: an id past the
* embedding table is refused at admission, never staged into a pass. Raw id arrays reach here
* straight from the request body, and an op failing mid-step is a device fault (spec §17) —
* the whole engine would die for one bad number. Same bound as the scored-prompt check below.
*/
for (int32_t t : r->prompt)
if (t < 0 || t >= prog_->meta.n_vocab) {
RAD_WARN("request %llu refused: prompt token id %d is outside the vocabulary [0, %lld)",
(unsigned long long)r->id, t, (long long)prog_->meta.n_vocab);
return RAD_E_INVAL;
}
/* Nor could a prompt the KV pool cannot hold even alone: admission takes only what the pool
* holds, so it would wait at the head of the queue, and everything behind it, forever. The
* prompt is the least a request needs: its first token comes from the prefill's last row.
@@ -363,12 +377,18 @@ bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const {
return false;
}
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
if (it == by_id_.end()) return RAD_E_NOTFOUND;
SchedReq& s = *reqs_[(size_t)it->second];
if (n < 0) return RAD_E_INVAL;
/* A tree's parents travel with its tokens; a prefix of a tree is a tree (every parent
* precedes its child), so the caps below keep them valid. */
s.draft_tree = parents != nullptr;
if (parents)
for (int i = 0; i < n && i < RAD_SCHED_MAX_SPEC; ++i) s.draft_par[i] = parents[i];
s.req->draft_parent = parents ? s.draft_par : nullptr;
/* The step issued ahead already verifies these: it was planned with the drafter's count and
* the card has the tokens. The host copy is what its commit emits accepted tokens from, so it
@@ -479,9 +499,9 @@ void Scheduler::trim_prefix_cache() {
if (!pc_ || !cfg_.prefix_cache) return;
const std::vector<int32_t>& cg = pc_->cached_groups();
if (cg.empty()) return;
/* An entry covers the lcm of the cached groups' blocks and holds that over a group's block of
* its blocks (PrefixCache::blocks_per_entry); the trim asks for entries, as many as the group
* furthest short needs. */
/* An entry covers the lcm of the cached groups' block sizes and holds lcm / B blocks of a
* group with B-token blocks (PrefixCache::blocks_per_entry). The trim asks for entries, as
* many as the group furthest short needs. */
int64_t entry = 0;
for (int32_t g : cg) {
const int64_t bs = kvgeom_.g[(size_t)g].block_size;
@@ -874,10 +894,10 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
if (geo_.checkpoints() && geo_.exact) {
/* --prefix-resume exact: checkpoints only where an idle cold prefill of this prompt starts
* a chunk (ChunkGeometry::grid), so a hit that resumes at one recomputes the cold run's
* own chunks. Splits as below at the interval and a span's end; the tail snapshot is at
* the start of the prompt's last chunk (tail_checkpoint), a boundary an idle chunk already
* ends on, so it costs a copy and no step. A step that shares the budget (another
* request, decode rows) may straddle it, and is split there. */
* own chunks. Splits at the interval and a span's end as nearest does (below). The tail
* snapshot is at the start of the prompt's last chunk (tail_checkpoint), a boundary an
* idle chunk already ends on, so it costs a copy and no step. A step that shares the
* budget (another request, decode rows) may straddle it, and is split there. */
const int64_t I = geo_.checkpoint_interval;
const bool periodic = !geo_.window_ckpt || geo_.window_periodic;
const int64_t next = periodic ? ((n_computed / I) + 1) * I : INT64_MAX;
@@ -895,28 +915,27 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
} else if (periodic && (n_computed + want) % I == 0 && geo_.on_grid(n_computed + want)) {
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
}
/* A request's own checkpoint (Request::checkpoint_at) as below, wherever it falls: the
* head the request shares with others resumes there by design. */
/* A request's own checkpoint (Request::checkpoint_at), wherever it falls, as nearest
* takes it: the head the request shares with others resumes there by design. */
const int64_t keep = keep_at / geo_.quantum * geo_.quantum;
if (keep > n_computed && keep <= n_computed + want && keep <= n_target) {
want = keep - n_computed;
if (checkpoint_pos) *checkpoint_pos = keep;
}
} else if (geo_.checkpoints()) {
/* --prefix-resume nearest, or no prefix cache: interval checkpoints, and a tail snapshot
* as deep in the prompt as the rules below allow. */
const int64_t I = geo_.checkpoint_interval;
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
if (geo_.window_ckpt && !geo_.window_periodic) {
/* An explicit tail-only policy should not pay for intermediate
* window copies or chunk splits just to retire those snapshots. */
next = INT64_MAX;
} else if (geo_.window_ckpt) {
/* A tail-only window snapshot is unreachable after a prompt edit.
* Keep interval checkpoints too; the ordinary retention policy bounds
* their storage. Preserve the tail before the template's changed suffix,
* even when the prompt ends exactly on an interval boundary. */
const int64_t tail = tail_checkpoint(n_target);
if (tail > n_computed) next = std::min(next, tail);
}
/* Otherwise a window keeps interval snapshots too (a tail-only one is unreachable after a
* prompt edit; the ordinary retention policy bounds their storage), each splitting the
* prefill at its boundary. The tail's is taken inside the chunk that carries it
* (wtail below), so it splits nothing. */
/* A span (ChunkGeometry::span) starts only on an interval boundary past the first
* interval, and its chunk is the span's intervals in a row, each the piece a span of 1
* makes a chunk of its own. Not from a prompt's start: the first interval may be served on
@@ -930,16 +949,26 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
want = far - n_computed;
else if (n_computed + want > next && n_computed + want < n_target)
want = (n_computed + want) / I * I - n_computed;
if ((geo_.window_ckpt && n_computed + want == next) ||
(!geo_.window_ckpt && (n_computed + want) % I == 0)) {
/* A window snapshot at the prompt's tail, a block short of its end (the next turn's
* rendering may differ there), even where the prompt ends on an interval boundary. The
* window's rows behind it are still held when the chunk ends (a window slides from a
* step's first query, KVManager::recycle_window), so it is taken inside whichever chunk
* carries that position, and the prompt is not split there: no extra step. It wins over
* an interval snapshot at the same chunk's end, which lies past it. */
const int64_t wtail = geo_.window_ckpt ? tail_checkpoint(n_target) : -1;
if (wtail > n_computed && wtail <= n_computed + want) {
if (checkpoint_pos) *checkpoint_pos = wtail;
} else if ((geo_.window_ckpt && n_computed + want == next) ||
(!geo_.window_ckpt && (n_computed + want) % I == 0)) {
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
} else if (n_computed + want == n_target) {
/* Also one at the prompt's tail. The next turn resumes from the deepest snapshot
* under its hit, which on the interval alone can be nearly an interval short of this
* prompt's end, re-prefilled every turn. The final chunk splits at the last quantum
* boundary, and the remainder (under a quantum) runs as the next step's chunk
* (tail_checkpoint decides when that is worth it). */
const int64_t tail = tail_checkpoint(n_target);
* prompt's end, re-prefilled every turn. Linear state is what the chunk's last token
* leaves, so the final chunk splits at the last quantum boundary and the remainder
* (under a quantum) runs as the next step's chunk (tail_checkpoint decides when that
* is worth it). A window's tail snapshot is taken above, inside its chunk. */
const int64_t tail = geo_.window_ckpt ? -1 : tail_checkpoint(n_target);
if (tail > n_computed) {
want = tail - n_computed;
if (checkpoint_pos) *checkpoint_pos = tail;
@@ -974,36 +1003,46 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
}
if (aligned < end) {
want = aligned - n_computed;
if (checkpoint_pos) *checkpoint_pos = -1;
/* A checkpoint at the old end goes with it (the chunk that reaches it takes it); a
* window's tail snapshot the trimmed chunk still carries stays, or the next chunk
* would start past it and the prompt take none. */
if (checkpoint_pos && *checkpoint_pos > aligned) *checkpoint_pos = -1;
}
}
return want;
}
/* The tail checkpoint of a `target`-token prompt, or -1: its last quantum boundary, only past the
* first interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
* interval over the interval checkpoint below it, which pays for the extra step. */
/* The tail checkpoint of a `target`-token prompt, or -1. Under --prefix-resume exact, where its
* last chunk starts (below). Under nearest, its last quantum boundary, only past the first
* interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
* interval over the interval checkpoint below it, which pays for the extra step; a window
* snapshot follows its own rule (below). */
int64_t Scheduler::tail_checkpoint(int64_t target) const {
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
if (I <= 0 || Q <= 0) return -1;
if (geo_.exact) {
/* --prefix-resume exact: where the prompt's last chunk starts on the resume grid, so an
* exact repeat re-prefills that chunk as the cold run did, and an appended turn that chunk
* and what it added. A window snapshot keeps its margin below (next comment): the grid
* point under the end less a block. Past the first interval, as below. */
* and what it added. A window snapshot keeps nearest's margin (next comment): the grid
* point under the end less a block. From the first interval on, as nearest's linear-state
* rule (a window's lower floor, kWindowSnapshotMin, is nearest's only). */
const int64_t margin = geo_.window_ckpt ? std::max<int64_t>(Q, 16) : 1;
const int64_t t = geo_.grid_floor(target - margin);
if (geo_.window_ckpt) return t >= I ? t : -1;
return t > I ? t : -1;
}
const int64_t tail = target / Q * Q;
/* A window snapshot is taken at the tail of any prompt of an interval or more, a block short
* of the end: the next turn re-renders the last few tokens (the generation prompt is replaced
* by the reply), and a snapshot past where the two renderings diverge is unreachable. Prompts
* that left fewer than ~8 tokens in their last block always missed. */
/* A window snapshot is taken at the tail of a prompt, a block short of its end: the next turn
* re-renders the last few tokens (the generation prompt is replaced by the reply), and a
* snapshot past where the two renderings diverge is unreachable. Prompts that left fewer than
* ~8 tokens in their last block always missed. It is taken where that position is at least
* kWindowSnapshotMin, or an interval where that is lower: from a 528-token prompt at a quantum
* of 16. The snapshot is the only way a hit resumes on a model whose windowed layers the cache
* does not index, so the floor is low: copying the window out and back costs a few
* milliseconds, recomputing the prompt a prefill. */
if (geo_.window_ckpt) {
const int64_t t = (target - std::max<int64_t>(Q, 16)) / Q * Q;
return t >= I ? t : -1;
return t >= std::min<int64_t>(I, kWindowSnapshotMin) ? t : -1;
}
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
}
@@ -1126,6 +1165,12 @@ void Scheduler::preempt_back() {
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
Request& r = *s.req;
/* A REQUEST THAT WAS PREEMPTED WAITS FOR ROOM FOR THE WHOLE RECOMPUTE, plus one block of
* headroom for every sequence already running. Admitting it on a shortfall is what turns
* preemption into a loop: it prefills a chunk, the pool refuses the next step, it is taken
* back to zero, and the same chunk is attempted again. */
if (r.state == ReqState::Preempted && !preempted_can_prefill(s)) return kAdmitWait;
if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
/* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The
@@ -1248,8 +1293,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* tenant wrote, so the model would attend to the previous request's KV. Zero the reuse
* and re-prefill unless a window snapshot covers it.
*
* A drafter's own group (bound at base_layer and above) is not this clamp's business:
* draft refill caps the hit so the recompute covers the drafter's window. */
* A drafter's own group (bound at base_layer and above) is not this clamp's business: it
* rides in the window snapshot where the engine puts it there
* (IKVManager::window_snapshot), and otherwise draft refill caps the hit so the recompute
* covers the drafter's window. */
if (reuse > 0 && (hit_holes_trunk_ || (hit_needs_window_ && !win_hit))) {
reuse = 0;
s.hit_cut = SchedReq::HitCut::Window;
@@ -1392,6 +1439,42 @@ void Scheduler::undo_hit(SchedReq& s) {
s.hit_attn = 0;
}
/* Whether a preempted request can be admitted without becoming the next victim. The first
* requirement is the whole recompute's blocks; the second is one block per running sequence for
* the step after this one. Without that headroom, a decode step takes the block this prefill
* just reserved, the pool refuses the next chunk, and preempt_back() puts it back to zero again. */
bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
const Request& r = *s.req;
const int64_t target = s.seq_len();
for (size_t g = 0; g < kvgeom_.g.size(); ++g) {
const KVGeom::G& gg = kvgeom_.g[g];
if (!gg.paged) continue;
int64_t need = (target + gg.block_size - 1) / gg.block_size -
(int64_t)kv_->block_table(r.id, (int32_t)g).size();
if (need < 0) need = 0;
for (int32_t slot : running_) {
const SchedReq& rs = *reqs_[(size_t)slot];
if (!rs.req) continue;
const int64_t next = rs.req->n_computed + 1;
const int64_t rows = (next + gg.block_size - 1) / gg.block_size;
const int64_t extra = rows - (int64_t)kv_->block_table(rs.req->id, (int32_t)g).size();
need += 1; /* the step after this one keeps its block */
if (extra > 0) need += extra; /* and the block its next token already needs */
}
if (need > kv_->available_blocks((int32_t)g)) return false;
}
/* Stateful groups: the recompute needs its state slots back, and every running sequence must
* keep the slot it already holds. */
if (!kv_->can_grow(r.id, target)) return false;
for (int32_t slot : running_) {
const SchedReq& rs = *reqs_[(size_t)slot];
if (rs.req && !kv_->can_grow(rs.req->id, rs.req->n_computed + 1)) return false;
}
return true;
}
/* ------------------------------------------------------------------ the step */
const RadBatch* Scheduler::step() {
std::lock_guard<std::mutex> lk(mu_);
@@ -1407,6 +1490,7 @@ const RadBatch* Scheduler::step() {
if (pc_) pc_->begin_step();
plan_.reset();
plan_.spec_is_tree = tree_;
step_prefill_tok_ = 0;
step_decode_tok_ = 0;
@@ -1623,14 +1707,17 @@ const RadBatch* Scheduler::step() {
e.n_draft = s.n_draft;
e.is_prefill = prefill;
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
/* A tree drafter's parents, unless prompt lookup replaced its proposal with a chain. */
e.draft_parent = (!prefill && s.draft_tree && !e.ngram) ? s.draft_par : nullptr;
r.draft_parent = e.n_spec ? e.draft_parent : nullptr;
e.produces_token = (r.n_computed + want >= target);
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
* sequence after this, and restoring it again on a later chunk would rewind it. */
e.ckpt_restore = s.ckpt_src;
s.ckpt_src = -1;
/* The checkpoint is the state after the chunk's last token, which the split put at the
* interval boundary. */
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(want - 1));
/* The checkpoint is the state after the chunk's token at `ckpt`: its last, where the split
* put the interval boundary there, or inside it for a window snapshot (plan_chunk). */
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
s.entry = (int32_t)plan_.e.size();
s.sched_tokens = (int32_t)want;
plan_.e.push_back(e);
@@ -1679,6 +1766,7 @@ const RadBatch* Scheduler::step() {
? share_tok : 0;
admit_full_ = 0;
const int as = admit_one(s, budget, areserve);
if (as == kAdmitWait) { ++at; continue; }
if (as < 0) break; /* head of line: do not admit behind it */
if (admit_full_ > s.sched_tokens && capped_at < 0) {
capped_at = (int32_t)plan_.e.size();
@@ -1698,6 +1786,7 @@ const RadBatch* Scheduler::step() {
* preemption may still carry a drafter's proposal. */
r.n_draft = 0;
r.draft = nullptr;
r.draft_parent = nullptr;
e.n_accepted = 1; /* one-based; a prefill rolls nothing back */
e.conv_cursor = s.conv_cursor;
e.draft = s.draft;
@@ -1708,7 +1797,8 @@ const RadBatch* Scheduler::step() {
* restoring again on a later chunk would rewind the recurrence to the hit. */
e.ckpt_restore = s.ckpt_src;
s.ckpt_src = -1;
if (s.pending_ckpt > 0) reserve_ckpt(e, r, s.pending_ckpt, s.sched_tokens - 1);
if (s.pending_ckpt > 0)
reserve_ckpt(e, r, s.pending_ckpt, (int32_t)(s.pending_ckpt - r.n_computed - 1));
s.entry = (int32_t)plan_.e.size();
plan_.e.push_back(e);
plan_.n_tok += s.sched_tokens;
@@ -1748,7 +1838,7 @@ const RadBatch* Scheduler::step() {
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
e.n_tokens = (int32_t)grown;
e.produces_token = (r.n_computed + grown >= s.seq_len());
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(grown - 1));
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
s.sched_tokens = (int32_t)grown;
plan_.n_tok += grown - had;
budget -= grown - had;
@@ -2003,6 +2093,7 @@ const RadBatch* Scheduler::step_next_locked() {
if (ends_every_request()) return nullptr;
plan_next_.reset();
plan_next_.spec_is_tree = tree_;
for (const StepEntry& e : plan_.e) {
if (e.slot < 0 || (size_t)e.slot >= reqs_.size()) return nullptr;
SchedReq& s = *reqs_[(size_t)e.slot];
@@ -2012,6 +2103,12 @@ const RadBatch* Scheduler::step_next_locked() {
* that cannot rewind decides at commit whether the next step may speculate; one that can,
* or no grammar, keeps its answer. */
if (!e.produces_token || !r.speculation_fixed) return nullptr;
/* A SCORED row (Request::token_scores, a /v1/systemone question) that the step in flight
* brings to max_tokens gets no step issued ahead: it would run a whole forward pass for a
* request that finishes at the commit, and max_tokens=1 pays a decode step after its
* prefill. Scored rows only -- every other decode keeps the step of overlap it had. */
if (r.token_scores && r.max_tokens > 0 &&
(int64_t)r.output.size() + 1 >= r.max_tokens) return nullptr;
/* The furthest context the row can reach: every position this step verifies committed,
* counted from the last commit rather than this step's own bound (which would add a
@@ -2034,6 +2131,8 @@ const RadBatch* Scheduler::step_next_locked() {
n.n_accepted = 1; /* the card's: StepSlot::n_acc */
n.conv_cursor = s.conv_cursor;
n.draft = s.draft; /* published before this step commits (set_draft) */
/* And the tree drafter's parents, which the card verifies by (ADV_BTAKE took them). */
n.draft_parent = tree_ ? s.draft_par : nullptr;
n.n_draft = d;
n.is_prefill = false;
n.produces_token = true;
@@ -2080,7 +2179,11 @@ void Scheduler::promote_next() {
s.entry_next = -1;
s.draft_next = 0;
s.sched_tokens = plan_.e[i].n_tokens;
if (s.req) { s.req->n_draft = plan_.e[i].n_spec; s.req->draft = s.draft; }
if (s.req) {
s.req->n_draft = plan_.e[i].n_spec;
s.req->draft = s.draft;
s.req->draft_parent = tree_ && plan_.e[i].n_spec ? s.draft_par : nullptr;
}
}
++m_.steps_decode;
/* A step issued ahead during a hold is one of its decode-only steps. */
@@ -2241,7 +2344,12 @@ int Scheduler::commit(StepResult& res) {
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
};
for (int32_t j = 0; j < a; ++j) emit(s.draft[j], j);
/* On a tree step the accepted drafts are the path's nodes, in path order. */
const int32_t* path = res.path ? res.path + (size_t)i * RAD_SCHED_MAX_SPEC : nullptr;
for (int32_t j = 0; j < a; ++j) {
const int32_t d = path ? path[j] - 1 : j;
emit(d >= 0 && d < e.n_spec ? s.draft[d] : s.draft[j], j);
}
if (res.token) emit(res.token[i], a);
r.n_computed = valid;
step_decode_tok_ += 1 + a;
@@ -2692,6 +2800,7 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
d.card = e.card;
d.ctx_len = e.ctx_len;
d.n_tokens = e.n_tokens;
d.n_spec = e.produces_token && !e.is_prefill ? e.n_spec : 0;
/* Every entry of the trunk step gets a row, in order, running or not: the context pass's
* row i must be the trunk's row i, so leaving out a sequence the commit just finished
@@ -2811,6 +2920,15 @@ const RadBatch* Scheduler::block_context(int step) {
/* The context pass reads tapped hidden states, not token ids: nothing to shift and no
* draft. */
e.produces_token = false;
/* A tree verify's rows are restaged on the card from its accepted path (ADV_CTXTREE):
* only that path is context, each node at its committed position. Not a placeholder,
* whose blocks may already be free. */
if (tree_ && d.dev && !d.mirror && d.n_spec > 0 && d.n_tokens == 1 + d.n_spec) {
e.dev = true;
e.dev_tok = (int32_t)block_plan_.n_tok;
e.dev_out = -1;
e.dev_aux = 0;
}
block_plan_.e.push_back(e);
block_plan_.n_tok += e.n_tokens;
}
+30 -5
View File
@@ -46,6 +46,10 @@ struct SchedReq {
int32_t draft[RAD_SCHED_MAX_SPEC] = {};
int32_t n_draft = 0;
int32_t conv_cursor = 0;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent), valid while `draft_tree`;
* a chain proposal (prompt lookup, or a chain drafter) clears it. */
int32_t draft_par[RAD_SCHED_MAX_SPEC] = {};
bool draft_tree = false;
/* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
* K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
@@ -140,6 +144,9 @@ public:
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
const int32_t* first_row = nullptr; /* [n_seq] */
/* A tree step's accepted nodes, [n_seq][RAD_SCHED_MAX_SPEC]: entry i's t-th accepted
* draft is draft[path[i][t] - 1]. Null on a chain step, where it is draft[t]. */
const int32_t* path = nullptr;
};
/* What commit left a sequence at: its committed length and whether it is still Running.
@@ -262,7 +269,8 @@ public:
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
int set_draft(uint64_t id, const int32_t* tokens, int n);
/* `parents`: a tree drafter's (rad_drafter_tree), node j + 1's parent node, null for a chain. */
int set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents = nullptr);
/* ---------------------------------------------------------- media the encoder owes
* A request carrying media is admitted only once every item is encoded; until then it keeps
@@ -400,11 +408,14 @@ public:
* block drafter's block length is chosen by. Read before block_begin(). */
int decoded_seqs() const;
/* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it
* ran it last step and this step's decoded_seqs(): on from `from`, off again only at two
* below, so a load wavering at the threshold does not switch the pass shape every step. */
* ran it last step and this step's decoded_seqs(): on from `from`, and off again two below or
* at one sequence below `from`, where the long block pays. Two below keeps a load wavering at
* a threshold of 3 or more from switching the pass shape every step. From 2 there is no such
* margin: a load between one and two sequences switches every step (block_shape reads it per
* step), and the one sequence left after an overlap runs the long block again. */
static bool short_block_on(bool was_on, int64_t decoded, int64_t from) {
if (decoded >= from) return true;
if (decoded + 2 <= from) return false;
if (decoded <= 1 || decoded + 2 <= from) return false;
return was_on;
}
const RadBatch* block_context(int step);
@@ -425,11 +436,15 @@ public:
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* plan_chunk's tail-checkpoint rule (see the definition). */
/* plan_chunk's tail-checkpoint rule for each --prefix-resume mode (see the definition). */
int64_t tail_checkpoint(int64_t target) const;
/* The least recompute a snapshot at a shared head (CacheHit::branch_at) must save each later
* request for the chunk split that takes it. */
static constexpr int64_t kSharedHeadMin = 256;
/* The lowest position tail_checkpoint takes a window snapshot at (ChunkGeometry::window_ckpt),
* or the interval where that is lower. A prompt reaches it at kWindowSnapshotMin +
* max(quantum, 16) tokens: 528 at a quantum of 16. */
static constexpr int64_t kWindowSnapshotMin = 512;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
@@ -520,6 +535,8 @@ private:
* at the committed position (advance.h). False and 0 for every other drafter. */
bool serial_shared_ = false;
int32_t serial_rot_shift_ = 0;
/* A tree drafter (rad_drafter_tree): every trunk plan is StepPlan::spec_is_tree. */
bool tree_ = false;
BatchBuilder builder_;
DraftController draft_;
@@ -662,6 +679,7 @@ private:
int32_t card = -1;
int32_t ctx_len = 0;
int32_t n_tokens = 0;
int32_t n_spec = 0; /* the trunk entry's drafts: a tree verify when > 0 */
int64_t base_pos = 0; /* the anchor's position: the sequence's next one */
bool can_draft = false;
/* On the card: the anchor's position is the card's, and `base_pos` the furthest it can
@@ -746,12 +764,19 @@ private:
/* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */
const Request* live_req(int32_t slot, uint64_t id) const;
void preempt_back();
/* A preempted request waits until the pool can hold its WHOLE remaining recompute plus one
* block of headroom for every running sequence; otherwise admitting it now just gets it
* preempted again next step and the prefill loops. */
bool preempted_can_prefill(const SchedReq& s) const;
/* Give blocks back from the prefix cache until the pool has headroom again. */
void trim_prefix_cache();
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
* it. `reserve`: tokens of the step to leave for the requests queued behind this one
* (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
/* Positive sentinel from admit_one: the request waits (its context is still being read off
* disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */
static constexpr int kAdmitWait = 1;
/* The queue positions one step's admission took, kept to reuse the allocation. */
std::vector<size_t> took_;
/* A step's prefill entries while step() moves its decode entries first; reserved at init,
+3 -1
View File
@@ -506,7 +506,9 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
return error_response(err_not_implemented(
"the server was not given a diagnostics provider; this build has no engine attached"),
req.peer);
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
/* A cross-origin browser is not a loopback client even when its own machine serves
* this port: the drive-by that guard exists to refuse. */
ApiError e;
e.status = 403;
e.type = "permission_error";
+100 -36
View File
@@ -13,6 +13,7 @@
* collapsing while the pooled acceptance rate stays plausible.
*/
#include "server.h"
#include "oai.h"
#include "rad_internal.h"
@@ -57,8 +58,10 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
if (req.method == "POST") {
/* The default applies to every client's requests that name no choice, so a server
* started without --api-key takes the change from a loopback client only, as it does a
* runtime adapter load. */
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
* runtime adapter load. A browser page on another origin does not qualify even when the
* victim's own browser makes it loopback: that is the drive-by this guard must refuse.
*/
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
ApiError e;
e.status = 403;
e.type = "permission_error";
@@ -67,12 +70,12 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
"elsewhere";
return error_response(e, req.peer);
}
json body;
try {
body = json::parse(req.body.empty() ? "{}" : req.body);
} catch (const std::exception& e) {
return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer);
}
bool over = false, deep = false;
json body = parse_json_bounded(req.body.empty() ? "{}" : req.body, 0, &over, &deep);
if (body.is_discarded()) return error_response(err_bad("body", "not JSON"), req.peer);
if (over || deep)
return error_response(err_bad("body", "expected {\"enabled\": true|false} and "
"nothing deeper than that"), req.peer);
const auto it = body.find("enabled");
if (it == body.end() || !it->is_boolean())
return error_response(err_bad("enabled", "a boolean is required"), req.peer);
@@ -462,6 +465,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
l["prefetch_bytes"] = s.link.prefetch_bytes;
l["staged_bytes"] = s.link.staged_bytes;
l["stream_bytes"] = s.link.stream_bytes;
l["kv_stream_bytes"] = s.link.kv_stream_bytes;
l["kv_streaming"] = s.link.kv_streaming;
l["kv_stream_active"] = s.link.kv_stream_active;
o["link"] = std::move(l);
}
if (s.passes.present) {
@@ -1182,7 +1188,7 @@ nav button.on { color:var(--fg); background:var(--track); }
otherwise have had, and a percentage of the paged pool's token capacity says nothing
about it: it is a preemption signal, so it is kept, underneath, where it reads as one. -->
<div class="cell"><div class="n" id="m-kv">–<u></u></div>
<span class="cap">kv cache in vram</span>
<span class="cap" id="m-kvcap">kv cache in vram</span>
<span class="det" id="m-kvdet"></span>
<svg viewBox="0 0 200 22" preserveAspectRatio="none"><path/></svg></div>
<div class="cell"><div class="n" id="m-accept">–<u>%</u></div>
@@ -1353,7 +1359,7 @@ nav button.on { color:var(--fg); background:var(--track); }
<span class="cap">conversations can resume</span>
<span class="det" id="s-livedet"></span></div>
<div class="cell"><div class="n" id="s-vram">–<u>tok</u></div>
<span class="cap">context in vram</span>
<span class="cap" id="s-vramcap">context in vram</span>
<span class="det" id="s-vramdet"></span></div>
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
<span class="cap">moved to host ram</span>
@@ -1638,6 +1644,9 @@ const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll;
const RECENT_PREFILL = 10; /* 5 s */
const extAt = {}, winAt = {};
let lastActiveC = 0;
/* Whether the server streams its KV (--kv-resident). Settled at bringup, so it cannot change under
* a running page: the cells that name a memory tier read it instead of guessing. */
let kvStreamOn = false;
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
* `highest` from extAt. */
function noteSample(key, c, value, cap, win) {
@@ -1867,7 +1876,7 @@ const linkSegs = segs("linkbar", "linkrows");
* own mapping, read in place -- so it is the one that is not a grey. */
const TIER_INK = ["#f5f5f5", "#9a9a9a", "#5e5e5e", "#2b2b2b", "#3f6fa8"];
const INK_AR = "#60a5fa", INK_UP = "#4ade80", INK_DOWN = "#fbbf24", INK_SSD = "#a78bfa";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf", INK_KV = "#fb923c";
/* The plane is painted as raw pixels, so the same inks are wanted as RGB triples. Parsed from
* TIER_INK rather than written out a second time: two lists of five colours is one list that
* will drift, and the drift is a legend that names the wrong band of the picture. */
@@ -2243,7 +2252,13 @@ function update(s, dt) {
* wrong headline: the drafter's own window group is sized one block-run per slot and therefore
* sits at 100% for the whole life of the server, so a headline reading the max reads 100% on a
* server using 4% of its cache. */
const kvFrac = s.kv_tokens_total > 0 ? s.kv_tokens_used / s.kv_tokens_total : 0;
/* ONE UNIT FOR ONE METER. The figure is bytes -- every group's, which is the only unit groups
* can be summed in -- and the bar used to be TOKENS, the binding group's. Groups hold different
* bytes per token, so the two were answering at different rates: the figure reached its total
* while the bar was half full and then the figure stood still while the bar went on climbing.
* A streamed group's host mirror, whose pages arrive in their own order, made the gap wide
* enough to read as a bug, and it was one. Both are bytes now, and the percentage is the bar. */
const kvFrac = s.kv_bytes_total > 0 ? (s.kv_bytes_used || 0) / s.kv_bytes_total : 0;
/* HELD, NOT READ. A finished turn's blocks stay held by the prefix cache so the next turn can
* reuse them, and they occupy the card for exactly as long as they are held -- so they belong
* in this figure. What leaves it is a block that reached the free list, which is where an
@@ -2255,14 +2270,31 @@ function update(s, dt) {
* holds, in place, so what it keeps for itself is below what the carve gave it -- and the gap is
* the expert plane's "Borrowed VRAM". The line says both numbers rather than one, because
* "of 3.1 GiB" alone would read as a smaller budget. */
const kvGave = (s.kv_bytes_carved || 0) - s.kv_bytes_total;
/* TWO LINES, because the slot is two lines and a third is clipped rather than drawn. The share
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
the line that says how much context the bytes are actually holding. */
const kvGave = (s.kv_bytes_carved || 0) - (s.kv_bytes_total || 0);
/* KV STREAMING CHANGES WHAT THESE BYTES ARE -- but only where it is switched on in fact, not
* where it was asked for: --kv-resident is a preference (zeroed when the architecture refuses
* it, and a no-op at or above the group's context), while kv_stream_active says a group really
* keeps a resident window under its context. Without it every block the cache holds is on the
* card, so "of <total>" is VRAM and the carve is its ceiling. With it the card holds only the
* ring and every other block's K/V sits in a pinned host mirror: the figure above is the
* mirror, which is the whole context and therefore larger than the carve -- printing the carve
* beside it as a "max", or below as "can grow to", put a smaller number next to the larger one,
* and the pool read full the moment the mirror did. The line names the tier instead, and the
* ring keeps its own figure. */
const kvStream = !!(s.link && s.link.kv_stream_active);
/* THE TIER THE NUMBER IS IN, spelled. A streamed group's held context lives in the host mirror,
* so the same figure is "in ram" on this card; without streaming every block is on the card and
* it stays "in vram". The sessions view asks the same question of the same pool and renames its
* cell from the flag this poll settles. `kvStream` is the ring's actual state, not the switch. */
kvStreamOn = kvStream;
$("m-kvcap").textContent = kvStream ? "kv cache in ram" : "kv cache in vram";
$("m-kvdet").textContent = s.kv_bytes_total > 0
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
? (kvStream
? "of " + hb(s.kv_bytes_total) + " in host mirror · " + cnt3(s.kv_tokens_used) + " tok"
+ " · " + hb(s.kv_bytes_carved || 0) + " VRAM ring"
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : ""))
: "";
const aw = accWindow(s);
const awR = aw ? aw.ratio : null;
@@ -2298,29 +2330,31 @@ function update(s, dt) {
/* ONE MERGED FIGURE. The pool is carved into groups by state kind -- paged attention, the
* linear state, the drafter's own window -- and which of them a token landed in is an
* implementation detail of the carve, not a question anybody watching a server is asking. */
/* THE BAR IS THE BYTES BECAUSE THE PANEL IS ABOUT THE CARD, and it is filled from every group
* -- the recurrent ones included -- while the token figure beside it is the binding paged
* group's alone. They are not a unit conversion of each other and the panel says both.
*
* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The bytes are apportioned by the token split rather than
* measured, because the cache counts in blocks of the shared token axis and the bytes are
* every group's -- the ratio is what is being drawn, and it is exact in the unit it is taken
* in. */
/* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The share comes from the tokens (which blocks a running request
* reads versus which only the cache keeps is a fact about blocks) and is then spent in BYTES,
* the unit the figure and the percentage beside it are in, so the three cannot disagree. */
const kvCached = Math.min(s.kv_tokens_cached || 0, s.kv_tokens_used || 0);
const kvLive = Math.max(0, (s.kv_tokens_used || 0) - kvCached);
const kvCachedShare = (s.kv_tokens_used || 0) > 0 ? kvCached / s.kv_tokens_used : 0;
mKv.v.textContent = hbOf(s.kv_bytes_used, s.kv_bytes_total, " / ") + " · " + pct(kvFrac);
setSplit(mKv, kvLive, kvCached, s.kv_tokens_total || 0);
/* The two shares are FRACTIONS OF THE FILL, not of the track: spent as widths against a total
* of 1 they would draw a full bar for a pool holding 29 KiB. */
setSplit(mKv, (1 - kvCachedShare) * kvFrac, kvCachedShare * kvFrac, 1);
/* The segments named by what reclaiming them would cost, since a dimmer bar is not
self-explanatory. The split is by who references the blocks: the first part is context a
request on the card is reading, the second context nothing reads and the next eviction frees. */
mKvSub.textContent = s.kv_tokens_used > 0
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
: "";
mKvMax.textContent = s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "";
mKvMax.textContent = kvStream
? (s.kv_tokens_max > 0
? "a miss streams the missing blocks from the mirror into the ring"
: "")
: (s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "");
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
@@ -2498,6 +2532,8 @@ function update(s, dt) {
const pre = (f) => lk[f] || 0;
const dP = (f) => prev.link[f] == null ? 0 : Math.max(0, (pre(f) - prev.link[f]) / dt);
const ar = d("ar_bytes"), dn = d("d2h_bytes"), sd = d("ssd_bytes"), st = d("stream_bytes");
/* Null-safe until a server reports it: an older one, or the switch off, reads as zero. */
const kv = lk.kv_streaming ? dP("kv_stream_bytes") : 0;
const pf = dP("staged_bytes") + dP("prefetch_bytes");
const up = Math.max(0, d("h2d_bytes") - pf);
const pfAll = pre("staged_bytes") + pre("prefetch_bytes");
@@ -2508,7 +2544,7 @@ function update(s, dt) {
* proportion then falls back to the CUMULATIVE bytes, which is the same question asked over
* the whole run, and the panel says out loud which of the two it is showing. The rates stay
* in the rows either way: they are never wrong, only sometimes zero. */
const live = ar + up + pf + dn + sd + st > 0;
const live = ar + up + pf + dn + sd + st + kv > 0;
const w = (now, all) => live ? now : all;
linkSegs([
{ name: "All-reduce", ink: INK_AR, w: w(ar, lk.ar_bytes),
@@ -2531,6 +2567,16 @@ function update(s, dt) {
a: rate(sd), b: hb(lk.ssd_bytes) },
{ name: "Expert streaming", ink: INK_STREAM, w: w(st, lk.stream_bytes),
a: rate(st), b: hb(lk.stream_bytes) },
/* KV STREAMING, --kv-resident (core/kvstream): each step's resolve copies the blocks a
* streamed group missed from the pinned host mirror into the VRAM ring. The row rides the
* switch, not the traffic: a server that took --kv-resident but never streams -- a pipeline
* that never enters the streaming path -- is exactly what a zero row with the switch on
* says, and that is a question worth answering at a glance. The bytes are rank 0's resolve
* counters times the world: the ranks see the same misses through maps brought up
* identically, so each card's link carries one rank's figure. */
...(lk.kv_streaming ? [{ name: "KV streaming", ink: INK_KV,
w: w(kv, pre("kv_stream_bytes")),
a: rate(kv), b: hb(pre("kv_stream_bytes")) }] : []),
]);
/* THE HEADLINE IS THE PCIe TOTAL, which is the all-reduce plus the moves. The SSD tier is
* left out of it on purpose: those bytes come off a disk into host memory and only the ones
@@ -2540,8 +2586,12 @@ function update(s, dt) {
* EXPERT STREAMING IS IN IT. A routed expert that was not resident is read by the MoE GEMM
* where it lies, which for every tier above VRAM means crossing the link on the critical
* path of the step. It is not a move and not a collective, and it is the traffic a promotion
* is spent to remove -- so the two belong on one axis. */
const lr = rates(ar + up + pf + dn + st);
* is spent to remove -- so the two belong on one axis.
*
* KV STREAMING IS IN IT WHILE THE SWITCH IS ON. Its resolve copies cross the same PCIe the
* movers use, already summed over the cards; with the switch off the term is zero and the
* headline reads as it did without the counter. */
const lr = rates(ar + up + pf + dn + st + kv);
$("lnk_n").firstChild.nodeValue = lr.n;
$("lnk_n").querySelector("u").textContent = lr.u;
/* WHAT IS SUMMED AND WHAT IS NOT. The move and stream rows are every card's added up,
@@ -3462,6 +3512,9 @@ async function loadSessions() {
/* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can
serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A
tier that is off has no cell. */
/* A streamed server holds that context in its host mirror, not on the card, so the cell says
* where the tokens are; the flag comes from the stats poll (kvStreamOn). */
$("s-vramcap").textContent = kvStreamOn ? "context in ram" : "context in vram";
$("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0);
$("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : "";
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) {
@@ -3619,6 +3672,17 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) {
/* No caching: the page must match the binary's /stats shape, and a stale copy shows only
* blank panels. */
r.set_header("Cache-Control", "no-store");
/* The page is fixed markup that talks only to its own origin, and CSP is how that promise
* becomes enforceable: even a future markup bug could not phone an injected payload's
* findings home, and could not reach the key beyond this origin. script/style 'unsafe-inline'
* is the cost of shipping as one compiled-in literal with its own <style> and <script>;
* frame-ancestors keeps a hostile page from framing the Model view and clickjacking its
* guardrail toggle. */
r.set_header("Content-Security-Policy",
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
"connect-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; "
"form-action 'none'");
r.set_header("X-Frame-Options", "DENY");
return r;
}
+41 -5
View File
@@ -433,6 +433,14 @@ static std::string lower_ascii(std::string s) {
return s;
}
bool HttpRequest::is_cross_origin() const {
const std::string origin = header("Origin");
if (origin.empty()) return false;
const size_t at = origin.find("://");
const std::string auth = at == std::string::npos ? origin : origin.substr(at + 3);
return lower_ascii(auth) != lower_ascii(header("Host"));
}
/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
* OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.<key>`, beside
* `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
@@ -486,6 +494,11 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
/* Every response, refusals and preflights included: no browser may second-guess the type.
* The JSON routes answer only the dashboard's own fetch, and a body sniffed as HTML would
* otherwise execute where it was only meant to be read. */
svr.set_default_headers({{"X-Content-Type-Options", "nosniff"}});
/* An exception escaping a handler would close the connection with no body; answer 500 with
* an error object instead. */
svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
@@ -494,7 +507,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
try { std::rethrow_exception(ep); }
catch (const std::exception& e) { what = e.what(); }
catch (...) {}
RAD_ERR("server: %s", what.c_str());
/* e.what() can carry request text (a path, a header): keep it off the log as an
* escape-sequence vector. */
RAD_ERR("server: %s", log_sanitize(what).c_str());
res.status = 500;
res.set_content(error_body(req.path, 500, "internal_server_error", what),
"application/json");
@@ -534,10 +549,17 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
/* The probe paths and the dashboard page are exempt. A load balancer cannot send a
* bearer token, and a browser opening the page cannot send a header; the page holds no
* data and sends the key on every data fetch. Everything else is guarded, including
* /tokenize, which vLLM leaves open (it only guards /v1). */
* /tokenize, which vLLM leaves open (it only guards /v1).
*
* The exemption follows the methods those paths actually answer — reads, plus the POST
* /ping of the health-check convention — so it cannot ride a method the router might
* one day put behind one of these paths. */
const std::string& p = hreq.path;
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
p != "/dashboard") {
const std::string& m = hreq.method;
const bool reads = m == "GET" || m == "HEAD";
const bool probe = p == "/health" || p == "/v1/health" || p == "/" || p == "/dashboard";
const bool exempt = (reads && (probe || p == "/ping")) || (p == "/ping" && m == "POST");
if (!api_key.empty() && !exempt) {
if (!key_ok(hreq)) {
/* Logged in Server::error_response's format; the gate answers before the router. */
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
@@ -582,8 +604,22 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
hres.set_chunked_content_provider(
st->content_type,
[st](size_t /*offset*/, httplib::DataSink& sink) -> bool {
/* In the vendored 0.46 an exception escaping the provider unwinds the task queue
* and aborts the process (upstream's 0.54.0 serve_guarded fixed exactly this);
* until the lift moves, a throwing next() ends this response, not the server. */
std::string chunk;
bool more = st->next(chunk);
bool more = true;
try {
more = st->next(chunk);
} catch (const std::exception& e) {
RAD_ERR("server: stream provider threw: %s", log_sanitize(e.what()).c_str());
sink.done();
return true;
} catch (...) {
RAD_ERR("server: stream provider threw a non-standard exception");
sink.done();
return true;
}
if (!chunk.empty()) {
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
}
+5
View File
@@ -52,6 +52,11 @@ struct HttpRequest {
bool peer_gone() const { return closed && closed(); }
/* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
bool peer_is_loopback() const;
/* True when the request comes from a browser on another origin: an `Origin` header whose
* authority differs from `Host`. Scripts send no Origin, so this never fires for curl or an
* SDK. Through a proxy that rewrites Host, every browser reads as cross-origin — which is
* exactly the case the "loopback-only" guards must not wave through. */
bool is_cross_origin() const;
};
struct HttpResponse {
+26 -6
View File
@@ -92,10 +92,13 @@ json form_value(const std::string& key, const std::string& v) {
if (v == "true" || v == "1") return json(true);
if (v == "false" || v == "0") return json(false);
}
/* `loras` as JSON text, or one adapter's name. */
/* `loras` as JSON text, or one adapter's name. Bounded like a request body: a form field
* under the body cap can be brackets alone, and the deep tree's teardown would take the
* process with it. Over-deep or over-budget reads as plain text, as a discarded parse did. */
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
json j = json::parse(v, nullptr, false);
if (!j.is_discarded()) return j;
bool over = false, deep = false;
json j = parse_json_bounded(v, 0, &over, &deep);
if (!j.is_discarded() && !over && !deep) return j;
}
return json(v);
}
@@ -623,7 +626,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
src_px = std::move(src.rgba);
}
auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int {
auto render = [&](const std::string& prompt, const char* field, gen::Branch* out,
ApiError* err) -> int {
/* A prompt spelling the media marker would be scanned for pictures this request never
* uploaded, and the scan would walk off the item list: refuse the text, as the chat and
* embeddings paths refuse marker text (oai.cpp). */
if (prompt.find(RAD_MEDIA_MARKER) != std::string::npos) {
*err = err_bad(field, std::string("contains \"") + RAD_MEDIA_MARKER +
"\": it names a picture this request did not upload");
return RAD_E_INVAL;
}
std::string text = r.background == "transparent" && !info.tmpl_transparent.empty()
? replace_all(info.tmpl_transparent, "{prompt}", prompt)
: prompt;
@@ -651,6 +663,14 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
}
if (at == std::string::npos) break;
if (mi >= items.size()) {
/* Unreachable for any request: the prompt text is refused above, so only a model
* template that spells the marker past its pictures could reach it. Belt for the
* day one does. */
*err = err_internal("the render template spells the media marker more times "
"than the request has pictures");
return RAD_E_STATE;
}
mm::Placed pl;
pl.item = items[mi++];
pl.tok = (int32_t)out->tokens.size();
@@ -716,8 +736,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
};
{
ApiError err;
if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, &g->neg, &err) < 0)
if (render(r.prompt, "prompt", &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, "negative_prompt", &g->neg, &err) < 0)
return error_response(err, req.peer);
}
+6 -3
View File
@@ -260,15 +260,18 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
o += " readmit=" + std::to_string(s.experts.readmits);
}
}
/* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
* of these lines can be differenced into rates. */
/* Link traffic by consumer (collective, mover, MoE GEMM streaming, KV streaming), cumulative
* so a `| tee` of these lines can be differenced into rates. */
if (s.link.present &&
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes ||
s.link.kv_streaming)) {
o += " link ar=" + std::to_string(s.link.ar_bytes);
o += " h2d=" + std::to_string(s.link.h2d_bytes);
o += " d2h=" + std::to_string(s.link.d2h_bytes);
if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes);
if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes);
/* Printed at zero when the switch is on: the zero is the measurement. */
if (s.link.kv_streaming) o += " kv=" + std::to_string(s.link.kv_stream_bytes);
}
o += "\n";
return o;
+20 -5
View File
@@ -95,11 +95,12 @@ struct ExpertPlane {
/* Interconnect traffic by consumer.
*
* Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
* on one clock, so rates from two polls compare directly: is the link busy because the model is
* wide or because placement is thrashing?
* Four things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid), and --kv-resident's per-step
* resolve, which copies the blocks a streamed KV group missed from its host mirror into the VRAM
* ring (core/kvstream). All are cumulative byte counts on one clock, so rates from two polls
* compare directly: is the link busy because the model is wide or because placement is thrashing?
*
* `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
* mover's measured copy sizes.
@@ -117,6 +118,20 @@ struct LinkStat {
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
* Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
int64_t staged_bytes = 0;
/* KV streaming (--kv-resident): the bytes the resolves copied from the host mirror into the
* ring. Rank 0's counters -- the ranks resolve the same block ids through maps brought up
* identically, so one rank's answer is every rank's (see Engine::stream_probe_take) -- times
* the world, to sit on every card's link like the move rows. `kv_streaming` says the switch
* was asked for; a renderer then shows the row at zero included, because a zero with the
* switch on is the answer to "does this model's pipeline ever stream?".
*
* `kv_stream_active` is the DIFFERENT question: whether a group's device pool really is a
* resident window under its context. The switch is a preference -- it is zeroed when the
* architecture refuses it, and --kv-resident at or above the group's context leaves a plain
* resident pool -- so text that names a memory tier must read this, never the flag. */
int64_t kv_stream_bytes = 0;
bool kv_streaming = false;
bool kv_stream_active = false;
};
/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
+22 -10
View File
@@ -163,7 +163,11 @@ std::string ApiError::dump() const {
if (n_ctx >= 0) e["n_ctx"] = n_ctx;
json o;
o["error"] = e;
return o.dump();
/* A message can carry raw request text (a URL-decoded label, an echoed field name): dump
* must survive invalid UTF-8 by replacing it rather than throwing and turning a 404 into
* a 500. The JSON parsers refuse invalid UTF-8 in bodies, but URL-decoded params do not
* pass through one. */
return o.dump(-1, ' ', false, json::error_handler_t::replace);
}
ApiError err_bad(const std::string& param, const std::string& why) {
@@ -431,13 +435,16 @@ std::string str_or(const json& o, const char* k, const std::string& def = std::s
}
/* A conversation's label for /sessions: at most 128 bytes, cut at a UTF-8 character boundary
* because the label is serialised into JSON. */
* because the label is serialised into JSON. Control bytes are dropped at the door: the label
* is logged on release and shown on the dashboard, and an embedded ESC sequence would drive
* whatever terminal renders it. */
std::string session_label_of(const std::string& s) {
std::string t = log_sanitize(s);
constexpr size_t kMax = 128;
if (s.size() <= kMax) return s;
if (t.size() <= kMax) return t;
size_t cut = kMax;
while (cut > 0 && ((unsigned char)s[cut] & 0xC0) == 0x80) --cut;
return s.substr(0, cut);
while (cut > 0 && ((unsigned char)t[cut] & 0xC0) == 0x80) --cut;
return t.substr(0, cut);
}
/* One field under several spellings (OpenAI's, vLLM's, llama.cpp's), read as a number (double)
@@ -1053,8 +1060,11 @@ void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
if (lim.reasoning_effort_map.empty()) return;
auto it = opt->template_kwargs.find("reasoning_effort");
if (it == opt->template_kwargs.end()) return;
const json v = json::parse(it->second, nullptr, false);
if (!v.is_string()) return;
/* The kwarg is client text re-parsed as JSON: bound it like a body, a string of brackets
* would overflow this worker's stack when the tree comes down. */
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
if (over || deep || !v.is_string()) return;
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
if (m == lim.reasoning_effort_map.end()) return;
if (m->second == "none" || m->second == "minimal") {
@@ -1071,9 +1081,11 @@ ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, in
* variable was in the render. The set is more actionable than the template's traceback. */
auto it = opt.template_kwargs.find("reasoning_effort");
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
const json v = json::parse(it->second, nullptr, false);
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
const std::vector<std::string>& set = lim.reasoning_efforts;
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
if (!over && !deep && v.is_string() &&
std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
std::string list;
for (size_t i = 0; i < set.size(); ++i)
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
@@ -3782,7 +3794,7 @@ std::string anthropic_error_body(const ApiError& e) {
json o;
o["type"] = "error";
o["error"] = json{ { "type", anthropic_error_type(e.status) }, { "message", e.message } };
return o.dump();
return o.dump(-1, ' ', false, json::error_handler_t::replace); /* see ApiError::dump */
}
AnthropicStream::AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser)
+7 -2
View File
@@ -38,6 +38,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "mm/processor.h"
#include "mm/resample.h"
@@ -658,8 +659,12 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
auto handle = [&](const std::string& msg, bool binary) {
if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
/* Bounded like a request body: 2 MiB of brackets is a legal WebSocket frame, and the
* recursive teardown of a deep tree would take the whole process down with it. */
bool over = false, deep = false;
const ojson j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string())
return error("invalid_request_error", "invalid_json",
"a client event is a JSON object with a string `type`", "", nullptr);
const std::string type = j["type"].get<std::string>();
+21 -10
View File
@@ -406,13 +406,15 @@ static std::string from_peer(const std::string& peer) {
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
metrics_.observe_http(e.status);
/* Log every refusal with status, type, message and peer: 4xx at info (the client's doing),
* 5xx as a warning (ours). */
* 5xx as a warning (ours). The message can echo request text (a URL-decoded label, a field
* name), so the log copy is control-byte-clean; the wire copy keeps the bytes. */
const std::string msg = log_sanitize(e.message), typ = log_sanitize(e.type);
if (e.status >= 500)
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
else
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
HttpResponse r = HttpResponse::json_body(
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
@@ -1791,6 +1793,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
}
@@ -1969,6 +1972,7 @@ HttpResponse Server::handle_mica(const HttpRequest& req) {
if (mica_answers(r, dist, &answers, &err) < 0) return error_response(err, req.peer);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", input_tokens }, { "output_tokens", 0 } } } }));
}
@@ -2056,6 +2060,7 @@ HttpResponse Server::handle_clef(const HttpRequest& req) {
release(1);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", (int64_t)r.tokens.size() }, { "output_tokens", 0 } } } }));
}
@@ -2150,7 +2155,8 @@ HttpResponse Server::handle_laya(const HttpRequest& req) {
retire(gens);
release(n);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{ { "answers", std::move(answers) },
return HttpResponse::json_body(200, json_dump(json{ { "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", laya_usage(r) } }));
}
@@ -2206,7 +2212,6 @@ HttpResponse Server::handle_loras(const HttpRequest& req) {
}
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
using json = nlohmann::json;
auto fail = [&](int status, const char* type, const std::string& msg) {
ApiError e;
e.status = status;
@@ -2217,12 +2222,18 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
if (!opt_.lora_load || !opt_.lora_unload)
return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or "
"--max-loras)");
if (opt_.api_key.empty() && !req.peer_is_loopback())
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin()))
/* A cross-origin browser counts as neither loopback nor local: the victim's own browser
* is loopback to this port, and that is exactly how a hostile page would reach here. */
return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a "
"server started without --api-key takes it only from a "
"loopback client");
const json j = json::parse(req.body, nullptr, false);
if (j.is_discarded() || !j.is_object() || !j.contains("lora_name") || !j["lora_name"].is_string())
/* Bounded like a generation body: this parses client text the same way, and a deep bracket
* nest would overflow this worker's stack when the tree is torn down. */
bool over = false, deep = false;
const json j = parse_json_bounded(req.body, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("lora_name") ||
!j["lora_name"].is_string())
return fail(400, "invalid_request_error", "the body must be a JSON object with lora_name");
const std::string name = j["lora_name"].get<std::string>();
if (name.empty() || name == opt_.model_id)
+4 -3
View File
@@ -149,9 +149,10 @@ struct ServerOptions {
* a string rendered once: the dump includes `OpInfo::issued`, which a pre-first-step snapshot
* would report as false for every op, hiding dead declarations.
*
* Regenerating reads the Program on the HTTP thread while the step path writes that field. It
* is a monotonic false -> true bool, so at worst a mid-step fetch shows an op unissued one step
* early. Registry::select is called with record = false and mutates nothing else. */
* Regenerating reads the Program on the HTTP thread while the step path writes that field;
* both sides go through std::atomic_ref (Ctx::flush_issued, rad_graph.cpp), so the pairing is
* a relaxed exchange rather than a data race. Registry::select is called with record = false
* and mutates nothing else. */
std::function<std::string()> graph_json;
/* The startup report as JSON (core/diag/diag.h): options in force, the machine as it is now
* (the provider may reuse a reading for a second), and what on it costs speed. Without an API
+7 -2
View File
@@ -27,6 +27,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "text_split.h"
#include "gen/audio.h"
@@ -279,8 +280,12 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
"session.close");
return false;
}
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
/* Bounded like a request body: a deep bracket nest is a legal frame, and tearing its
* tree down recurses once per level. */
bool over = false, deep = false;
const json j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string()) {
error("a client message is a JSON object with a string `type`");
return false;
}
+2 -3
View File
@@ -24,6 +24,8 @@ struct ChatTemplate::Impl {
bool add_bos = false, add_eos = false;
};
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
* about parser generation, which the render's failure is not. */
static std::string template_words(const char* what) {
static const char kWrap[] = "Unable to generate parser for this template. Automatic parser "
"generation failed: ";
@@ -190,9 +192,6 @@ static bool lead_system(const ojson& messages, ojson* out) {
return true;
}
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
* about parser generation, which the render's failure is not. */
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
ChatPrompt* out) const {
if (!ready()) {
+9
View File
@@ -68,6 +68,15 @@ LogRank::~LogRank() { g_log_rank = prev_; }
static std::atomic<uint64_t> g_last_line_ns{0};
uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); }
std::string log_sanitize(const std::string& s) {
std::string out = s;
for (char& c : out) {
const unsigned char b = (unsigned char)c;
if ((b < 0x20 && b != '\t') || b == 0x7f) c = '?';
}
return out;
}
void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
const char* base = std::strrchr(file, '/');
base = base ? base + 1 : file;