Archived
Merge main into clef-flash-arch-plugin
This commit is contained in:
commit
d24cf32a13
114 files changed
+26614
-621
No files matched your search
@@ -167,6 +167,11 @@ static const Flag g_flags[] = {
|
||||
" one, for each of --max-num-seqs, within an eighth of host\n"
|
||||
" memory. N fixes the total; 0 keeps none" },
|
||||
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
|
||||
{ "--prefix-resume", "MODE", "where a prefix hit resumes: exact (default) only where\n"
|
||||
" an idle server's cold prefill of the prompt starts a\n"
|
||||
" chunk, so the hit answers bit-identically to a cold run;\n"
|
||||
" nearest at the deepest snapshot, up to a chunk less to\n"
|
||||
" re-prefill" },
|
||||
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
|
||||
"(default), tip-only, keep-all" },
|
||||
|
||||
@@ -298,6 +303,18 @@ static const Flag g_flags[] = {
|
||||
" mixed steps and draft-head passes, and write the counts to FILE as\n"
|
||||
" JSON every 30 s and at shutdown. From the routing histograms the core\n"
|
||||
" already copies back: no device work, no synchronisation" },
|
||||
{ "--expert-profile", "FILE", "rank the expert plane by this radiance-expert-stats JSON's `decode`\n"
|
||||
" counts instead of the container's activation profile, which is\n"
|
||||
" prefill-heavy: decode-hot experts differ. The planner keeps the\n"
|
||||
" hottest resident; --expert-pin-top makes a chosen slice unmovable" },
|
||||
{ "--expert-pin-top", "F", "pin the hottest fraction F of the routed experts (0 < F <= 1) by\n"
|
||||
" --expert-profile's share: heat never demotes them, so the decode-hot\n"
|
||||
" set stays resident while the rest streams. 0 is off" },
|
||||
{ "--draft-expert-placement", "PLACEMENT", "where a draft head's (MTP/DSpark) routed experts live.\n"
|
||||
" `host` pins them in the host pool before any strategy runs, read in\n"
|
||||
" place like a pooled expert: the drafter's experts fit beside a trunk\n"
|
||||
" that already fills the card, instead of the strategy having to make\n"
|
||||
" room on the card. `auto` (the default) leaves them to the strategy" },
|
||||
{ "--live", nullptr, "the live view: cards, throughput, draft acceptance, the expert plane.\n"
|
||||
" Redirected it prints one greppable key=value line instead" },
|
||||
{ "-v", nullptr, "verbose" },
|
||||
@@ -670,6 +687,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
}
|
||||
else if (S("--no-prefix-cache")) c->prefix_cache = false;
|
||||
else if (S("--prefix-resume")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "exact")) c->prefix_exact = true;
|
||||
else if (!std::strcmp(v, "nearest")) c->prefix_exact = false;
|
||||
else {
|
||||
RAD_ERR("--prefix-resume '%s' is not one of exact, nearest", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--checkpoint-policy")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Validated, so an unknown name does not silently fall back to the default. */
|
||||
@@ -914,6 +940,27 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true;
|
||||
else if (S("--profile-ops")) c->profile_ops = true;
|
||||
else if (S("--expert-stats")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_stats = v; }
|
||||
else if (S("--expert-profile")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_profile = v; c->expert_profile_given = true; }
|
||||
else if (S("--expert-pin-top")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
char* e = nullptr;
|
||||
const double d = strtod(v, &e);
|
||||
if (e == v || *e != '\0' || d < 0.0 || d > 1.0) {
|
||||
RAD_ERR("--expert-pin-top: '%s' is not a fraction in [0, 1]", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->expert_pin_top = (float)d;
|
||||
c->expert_pin_top_given = true;
|
||||
}
|
||||
else if (S("--draft-expert-placement")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (std::strcmp(v, "auto") != 0 && std::strcmp(v, "host") != 0) {
|
||||
RAD_ERR("--draft-expert-placement: '%s' is not auto or host", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->draft_expert_placement = v;
|
||||
c->draft_expert_placement_given = true;
|
||||
}
|
||||
else if (S("--live")) c->live_view = true;
|
||||
else {
|
||||
RAD_ERR("unknown option '%s'", a.c_str());
|
||||
@@ -1149,6 +1196,8 @@ const ShowRow kShow[] = {
|
||||
return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } },
|
||||
{ "--no-prefix-cache", [](const Config& c) {
|
||||
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
|
||||
{ "--prefix-resume", [](const Config& c) {
|
||||
return std::string(c.prefix_exact ? "exact" : "nearest"); } },
|
||||
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
|
||||
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
|
||||
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
|
||||
@@ -1235,6 +1284,9 @@ const ShowRow kShow[] = {
|
||||
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
|
||||
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
|
||||
{ "--expert-stats", [](const Config& c) { return or_none(c.expert_stats, "off"); } },
|
||||
{ "--expert-profile", [](const Config& c) { return or_none(c.expert_profile, "off"); } },
|
||||
{ "--expert-pin-top", [](const Config& c) { return fmt("%.4g", c.expert_pin_top); } },
|
||||
{ "--draft-expert-placement", [](const Config& c) { return c.draft_expert_placement; } },
|
||||
{ "--live", [](const Config& c) { return onoff(c.live_view); } },
|
||||
{ "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } },
|
||||
{ "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } },
|
||||
|
||||
@@ -109,6 +109,7 @@ struct HostFacts {
|
||||
std::string io_uring; /* available | refused (why) | unknown */
|
||||
std::string cpu_governor, cpu_epp, cpu_driver;
|
||||
std::string runtime; /* the device runtime's version, "" for none */
|
||||
std::string media; /* "libavformat <v>" / "absent (built without libav*)" */
|
||||
};
|
||||
|
||||
struct Facts {
|
||||
|
||||
@@ -89,6 +89,8 @@ std::string host_lines(const HostFacts& h, const RunFacts& r) {
|
||||
o += fmt(" runtime %s | backend %s\n",
|
||||
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
|
||||
r.host_backend ? "host (CPU)" : "device");
|
||||
if (!h.media.empty())
|
||||
o += fmt(" media decoders %s\n", h.media.c_str());
|
||||
return o;
|
||||
}
|
||||
|
||||
@@ -224,6 +226,7 @@ std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Deci
|
||||
host["cpu_epp"] = h.cpu_epp;
|
||||
host["cpu_driver"] = h.cpu_driver;
|
||||
host["runtime"] = h.runtime;
|
||||
host["media"] = h.media;
|
||||
J cards = J::array();
|
||||
for (const CardFacts& c : f.cards) {
|
||||
J e;
|
||||
|
||||
+2
-2
@@ -1818,8 +1818,8 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
ranks_[0]->tierx.report_pass(jobs, ok, rad_mono_ns());
|
||||
/* Rebind every entry that came back, not only the leading run: the tiers already
|
||||
* marked each resident at its new blocks. */
|
||||
const std::vector<int32_t>& cg = pc.cached_groups();
|
||||
* marked each resident at its new blocks. A job's blocks are one per entry slot. */
|
||||
const std::vector<int32_t>& cg = pc.entry_groups();
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!ok[i]) { res = RestoreResult::Cut; continue; }
|
||||
|
||||
@@ -241,6 +241,9 @@ private:
|
||||
std::vector<TableCopy> table_copies_;
|
||||
std::vector<void*> card_copies_;
|
||||
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. */
|
||||
std::vector<RadFileProfile> expert_profile_;
|
||||
int load_weights();
|
||||
int configure_kv();
|
||||
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
|
||||
|
||||
+68
-9
@@ -37,6 +37,7 @@
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <numeric>
|
||||
#include <sstream>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
@@ -1652,16 +1653,21 @@ int Engine::plan() {
|
||||
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
|
||||
/* The KV tiers' copy staging, built by TierExec::device_init on the first copy out.
|
||||
* The cached groups are settled later, so every paged group is counted (an upper
|
||||
* bound). */
|
||||
* bound), each with the blocks an entry at the lcm of their block sizes holds
|
||||
* (PrefixCache::entry_groups). */
|
||||
if (cfg_.prefix_cache_mib > 0) {
|
||||
int64_t entry = 0, bs = 0;
|
||||
int ng = 0;
|
||||
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
|
||||
const KVGroupPlan* p = probe.plan((int32_t)g);
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0) continue;
|
||||
entry += p->bytes_per_block;
|
||||
bs = bs > 0 ? std::min<int64_t>(bs, p->block_size) : p->block_size;
|
||||
++ng;
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
|
||||
bs = bs > 0 ? std::lcm<int64_t>(bs, p->block_size) : p->block_size;
|
||||
}
|
||||
for (size_t g = 0; g < r->program.kv_groups.size() && bs > 0; ++g) {
|
||||
const KVGroupPlan* p = probe.plan((int32_t)g);
|
||||
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
|
||||
entry += p->bytes_per_block * (bs / p->block_size);
|
||||
ng += (int)(bs / p->block_size);
|
||||
}
|
||||
const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs));
|
||||
f.staging += tier;
|
||||
@@ -1695,6 +1701,39 @@ int Engine::plan() {
|
||||
for (VramFacts& f : facts) f.held_out = cvec_bytes;
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host, ck_store + host_arenas));
|
||||
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
|
||||
* the strategy runs, so they 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. */
|
||||
if (cfg_.draft_expert_placement == "host") {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t draft_max = 0;
|
||||
for (const WeightFootprint& wf : wfs) draft_max = std::max(draft_max, wf.draft_experts);
|
||||
if (draft_max == 0 && cfg_.draft_expert_placement_given) {
|
||||
RAD_ERR("--draft-expert-placement host: this model declares no draft head with "
|
||||
"routed experts");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (draft_max > 0) {
|
||||
/* The pool 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;
|
||||
cfg_.host_pool_mib += add;
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * MiB;
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor_draft_hosted(
|
||||
wfs[i], std::max<int64_t>(room - align_up(wfs[i].draft_experts, MiB), 0));
|
||||
facts[i].experts = std::max<int64_t>(wfs[i].experts - wfs[i].draft_experts, 0);
|
||||
}
|
||||
RAD_INFO("placement: --draft-expert-placement host pins %s of drafter experts a "
|
||||
"rank in the host pool; --host-pool-mib grows by %lld to hold them, and "
|
||||
"the card places only the trunk's experts",
|
||||
humanb(draft_max).c_str(), (long long)add);
|
||||
}
|
||||
}
|
||||
/* The n-gram table was counted off the card; on it, every rank holds the whole table. */
|
||||
if (cfg_.ngram_resolved == TablePlacement::Vram)
|
||||
for (VramFacts& f : facts) f.statics += ngram_bytes;
|
||||
@@ -1843,6 +1882,20 @@ 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. */
|
||||
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;
|
||||
}
|
||||
if (!expert_profile_.empty()) {
|
||||
in.profile = expert_profile_.data();
|
||||
in.n_profile = (int64_t)expert_profile_.size();
|
||||
}
|
||||
}
|
||||
in.container = file_ != nullptr;
|
||||
in.host_backend = device_is_host();
|
||||
Planner planner(in);
|
||||
@@ -1864,7 +1917,8 @@ int Engine::plan() {
|
||||
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
|
||||
r->plan.forced_host_used > 0
|
||||
? fmt("the host pool holds the %s the placement flags put there (the token "
|
||||
"embedding, the encoder towers) beside the weights placed in it",
|
||||
"embedding, the encoder towers, the drafter's experts) beside the "
|
||||
"weights placed in it",
|
||||
humanb(r->plan.forced_host_used).c_str())
|
||||
: std::string());
|
||||
}
|
||||
@@ -3184,8 +3238,11 @@ int Engine::configure_kv() {
|
||||
shard_off[i] = slot;
|
||||
slot += ranks_[i]->kv.checkpoint_bytes();
|
||||
}
|
||||
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
|
||||
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
|
||||
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both. */
|
||||
bool linear = false;
|
||||
for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful();
|
||||
const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state"
|
||||
: linear ? "linear-state + sliding-window" : "sliding-window";
|
||||
const bool sized_auto = cfg_.checkpoint_slots < 0;
|
||||
if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what));
|
||||
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
|
||||
@@ -3235,7 +3292,9 @@ int Engine::configure_kv() {
|
||||
* sessions view reads. The flags gate only the mover, below. */
|
||||
{
|
||||
const bool tier_asked = cfg_.prefix_cache_mib > 0;
|
||||
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
|
||||
/* An entry's blocks, one group per block: a cached group whose blocks are shorter than
|
||||
* the entry appears once for each of its blocks (PrefixCache::entry_groups). */
|
||||
const std::vector<int32_t>& cg = ranks_[0]->prefix.entry_groups();
|
||||
/* One slot holds the whole engine's entry: the groups every rank holds alike
|
||||
* (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own
|
||||
* window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
#include "engine_priv.h"
|
||||
#include "device/device.h"
|
||||
#include "mm/media.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
@@ -37,6 +38,7 @@ diag::Facts Engine::hardware_facts(bool serving) const {
|
||||
if (r->device == id.device) mine.push_back(id.bdf);
|
||||
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
|
||||
f.host.runtime = runtime_version_;
|
||||
f.host.media = mm::decoder_version();
|
||||
if (probed_) {
|
||||
f.host.memlock_soft = memlock_soft_;
|
||||
f.host.io_uring = io_uring_;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* checkpoint.cpp -- see checkpoint.h. */
|
||||
#include "checkpoint.h"
|
||||
#include "ggml_planes.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
@@ -2499,6 +2500,26 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
if (dt == RAD_DT_INVALID) {
|
||||
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. */
|
||||
bool one_type = true;
|
||||
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
|
||||
RadEncoding enc;
|
||||
if (!one_type) {
|
||||
out->why = "its GGUF pieces are of different block types";
|
||||
} else if (ggml_plane_encoding(p0.ggml, &enc)) {
|
||||
if (out->pieces.size() > 1 && (d != 0 || out->rank < 2)) {
|
||||
out->why = "its GGUF pieces are joined along a column, across their blocks";
|
||||
} else {
|
||||
out->imported = true;
|
||||
out->ggml_blocks = true;
|
||||
out->enc = enc;
|
||||
out->why = std::string("it is a GGUF ") + gguf_dtype(p0.ggml)->name +
|
||||
" tensor, which rad-convert imports as its planes -- serve the "
|
||||
"container it writes";
|
||||
}
|
||||
}
|
||||
} else if (!same) {
|
||||
out->why = "its pieces are stored in different dtypes";
|
||||
} else if (p0.pbits) {
|
||||
@@ -3395,6 +3416,31 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (w.ggml_blocks) {
|
||||
/* GGUF blocks, split one row at a time into every plane's row: a call pays the whole row
|
||||
* for the one plane it keeps, and rad-convert asks plane by plane. */
|
||||
int64_t at[RAD_ENC_MAX_PLANES + 1] = { 0 };
|
||||
for (int i = 0; i < w.enc.n_planes; ++i) {
|
||||
int64_t qr = 0, qc = 0;
|
||||
rad_enc_plane_dims(&w.enc.plane[i], 1, w.cols, &qr, &qc);
|
||||
at[i + 1] = at[i] + rad_enc_row_bytes(w.enc.plane[i].dtype, qc);
|
||||
}
|
||||
std::vector<uint8_t> split((size_t)at[w.enc.n_planes]);
|
||||
uint8_t* row[RAD_ENC_MAX_PLANES] = { nullptr };
|
||||
for (int i = 0; i < w.enc.n_planes; ++i) row[i] = split.data() + at[i];
|
||||
int64_t base = 0;
|
||||
for (const SrcTensor* piece : w.pieces) {
|
||||
const int64_t prows = piece->numel() / w.cols, rb = piece->bytes / prows;
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + prows); ++r) {
|
||||
ggml_plane_row(piece->ggml, (const uint8_t*)piece->data + (r - base) * rb, w.cols,
|
||||
row);
|
||||
std::memcpy(o, row[k], (size_t)(at[k + 1] - at[k]));
|
||||
o += at[k + 1] - at[k];
|
||||
}
|
||||
base += prows;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == 0) {
|
||||
/* Codes: the pieces joined, bytes as stored. Sub-byte codes (MXFP4) join along rows of even
|
||||
* width, so every run is byte-aligned. */
|
||||
|
||||
@@ -282,6 +282,9 @@ struct CkptWeight {
|
||||
* from `pq_meta`. */
|
||||
bool paro = false;
|
||||
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale, pq_meta;
|
||||
/* GGUF Q8_0, Q4_K or Q6_K blocks (also `imported`): ckpt_plane_rows splits each row's blocks
|
||||
* into the planes of `enc` (ggml_planes.h), and ckpt_rows_f32 dequantises them. */
|
||||
bool ggml_blocks = false;
|
||||
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
|
||||
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
|
||||
* (the values change), so a recipe rule stores it. */
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
/* ggml_planes.h -- llama.cpp's Q8_0, Q4_K and Q6_K blocks as the affine planes libquant/lq_ggml.cpp
|
||||
* writes them, for reading a GGUF without a recipe. The core cannot call libquant, so this is the
|
||||
* reader's copy; quant_ggml_test holds the two to the same encoding, and checkpoint_test decodes
|
||||
* the planes against the block definition.
|
||||
*
|
||||
* The planes are bit for bit what lq_ggml's unpack_<type> writes from the same blocks (its header
|
||||
* lists them), so a container holds the same numbers whichever way a GGUF reached it. The blocks
|
||||
* are read as raw bytes at their GGUF offsets, so no struct layout is assumed, and gguf_dtype gives
|
||||
* their size.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_encoding.h"
|
||||
#include "../text/gguf.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace ggml_planes {
|
||||
|
||||
constexpr int kQK8_0 = 32, kQK_K = 256;
|
||||
|
||||
/* Writes a plane row front to back, `bits` per element, lowest bits first (rad_encoding.h's bit
|
||||
* stream). 32 bits go out at a time and the tail on flush(), so each byte is stored exactly once
|
||||
* and never read back; this does not rely on the row arriving zeroed. */
|
||||
class Bits {
|
||||
public:
|
||||
explicit Bits(uint8_t* row) : p_(row) {}
|
||||
void put(uint32_t v, int bits) {
|
||||
acc_ |= (uint64_t)(v & ((1u << bits) - 1u)) << n_;
|
||||
n_ += bits;
|
||||
if (n_ >= 32) {
|
||||
p_[0] = (uint8_t)acc_;
|
||||
p_[1] = (uint8_t)(acc_ >> 8);
|
||||
p_[2] = (uint8_t)(acc_ >> 16);
|
||||
p_[3] = (uint8_t)(acc_ >> 24);
|
||||
p_ += 4;
|
||||
acc_ >>= 32;
|
||||
n_ -= 32;
|
||||
}
|
||||
}
|
||||
void flush() {
|
||||
for (; n_ > 0; n_ -= 8, acc_ >>= 8) *p_++ = (uint8_t)acc_;
|
||||
n_ = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
uint8_t* p_;
|
||||
uint64_t acc_ = 0;
|
||||
int n_ = 0;
|
||||
};
|
||||
|
||||
/* Element i of a 16-bit plane row: an f16 super-scale's two bytes as the block holds them. */
|
||||
inline void copy16(uint8_t* row, int64_t i, const uint8_t* half) {
|
||||
row[2 * i] = half[0];
|
||||
row[2 * i + 1] = half[1];
|
||||
}
|
||||
|
||||
/* Two 4-bit codes per byte, element 2k low; q[] holds a block's codes in value order. */
|
||||
inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
|
||||
for (int k = 0; k < n / 2; ++k)
|
||||
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. */
|
||||
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);
|
||||
}
|
||||
|
||||
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
|
||||
if (j < 4) {
|
||||
*d = q[j] & 63u;
|
||||
*m = q[j + 4] & 63u;
|
||||
} else {
|
||||
*d = (q[j + 4] & 0xFu) | ((uint32_t)(q[j - 4] >> 6) << 4);
|
||||
*m = (uint32_t)(q[j + 4] >> 4) | ((uint32_t)(q[j] >> 6) << 4);
|
||||
}
|
||||
}
|
||||
|
||||
/* block_q8_0: d f16 @0, qs i8[32] @2. */
|
||||
inline void split_q8_0(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
|
||||
for (int64_t i = 0; i < nb; ++i) {
|
||||
const uint8_t* b = blocks + bb * i;
|
||||
std::memcpy(row[0] + kQK8_0 * i, b + 2, kQK8_0);
|
||||
copy16(row[1], i, b);
|
||||
}
|
||||
}
|
||||
|
||||
/* block_q4_K: d f16 @0, dmin f16 @2, scales u8[12] @4, qs u8[128] @16. */
|
||||
inline void split_q4_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
|
||||
Bits s(row[1]), m(row[3]);
|
||||
uint8_t q[kQK_K];
|
||||
for (int64_t i = 0; i < nb; ++i) {
|
||||
const uint8_t* b = blocks + bb * i;
|
||||
for (int k = 0; k < kQK_K; ++k) q[k] = (uint8_t)k_low4(b + 16, k);
|
||||
put_nibbles(row[0] + (kQK_K / 2) * i, q, kQK_K);
|
||||
for (int j = 0; j < kQK_K / 32; ++j) {
|
||||
uint32_t sc, mn;
|
||||
k4_scale_min(j, b + 4, &sc, &mn);
|
||||
s.put(sc, 6);
|
||||
m.put(mn, 6);
|
||||
}
|
||||
copy16(row[2], i, b);
|
||||
copy16(row[4], i, b + 2);
|
||||
}
|
||||
s.flush();
|
||||
m.flush();
|
||||
}
|
||||
|
||||
/* block_q6_K: ql u8[128] @0, qh u8[64] @128, scales i8[16] @192, d f16 @208. In each 128 values,
|
||||
* quarter t of 32 takes its low four bits from ql[64n + l (+32 for odd t)] (the high nibble for
|
||||
* t >= 2) and its top two from bits 2t of qh[32n + l]. */
|
||||
inline void split_q6_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
|
||||
Bits c(row[0]);
|
||||
for (int64_t i = 0; i < nb; ++i) {
|
||||
const uint8_t* b = blocks + bb * i;
|
||||
const uint8_t *ql = b, *qh = b + 128;
|
||||
for (int k = 0; k < kQK_K; ++k) {
|
||||
const int n = k / 128, t = (k % 128) / 32, l = k % 32;
|
||||
const uint8_t lo = ql[64 * n + l + 32 * (t & 1)];
|
||||
const uint32_t q = (uint32_t)(t < 2 ? lo & 15 : lo >> 4) |
|
||||
(uint32_t)((qh[32 * n + l] >> (2 * t)) & 3) << 4;
|
||||
c.put(q - 32u, 6);
|
||||
}
|
||||
std::memcpy(row[1] + (kQK_K / 16) * i, b + 192, kQK_K / 16);
|
||||
copy16(row[2], i, b + 208);
|
||||
}
|
||||
c.flush();
|
||||
}
|
||||
|
||||
/* A plane as lq_ggml's encoding_of lists it: one row high, `block` values wide. */
|
||||
struct Plane {
|
||||
const char* role;
|
||||
uint32_t dtype;
|
||||
int64_t block;
|
||||
};
|
||||
|
||||
/* A block type this header splits: ggml's type number, its planes in encoding order (the rest
|
||||
* empty), and the split of a row's `nb` blocks of `bb` bytes into one row of each. */
|
||||
struct Type {
|
||||
uint32_t ggml;
|
||||
Plane planes[RAD_ENC_MAX_PLANES];
|
||||
void (*split)(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row);
|
||||
};
|
||||
|
||||
inline constexpr Type kTypes[] = {
|
||||
{ 8, { { "codes", RAD_I8, 1 }, { "scale", RAD_F16, 32 } }, split_q8_0 },
|
||||
{ 12,
|
||||
{ { "codes", RAD_U4, 1 }, { "scale", RAD_U6, 32 }, { "scale.1", RAD_F16, 256 },
|
||||
{ "min", RAD_U6, 32 }, { "min.1", RAD_F16, 256 } },
|
||||
split_q4_K },
|
||||
{ 14, { { "codes", RAD_I6, 1 }, { "scale", RAD_I8, 16 }, { "scale.1", RAD_F16, 256 } },
|
||||
split_q6_K },
|
||||
};
|
||||
|
||||
inline const Type* type_of(uint32_t ggml_type) {
|
||||
for (const Type& t : kTypes)
|
||||
if (t.ggml == ggml_type) return &t;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} /* namespace ggml_planes */
|
||||
|
||||
/* The encoding a GGUF block type is read as, plane for plane as lq_ggml's encoding_of lists it.
|
||||
* False for a type this header does not split. */
|
||||
inline bool ggml_plane_encoding(uint32_t ggml_type, RadEncoding* e) {
|
||||
const ggml_planes::Type* t = ggml_planes::type_of(ggml_type);
|
||||
if (!t) return false;
|
||||
rad_enc_clear(e);
|
||||
rad_enc_copy_str(e->scheme, "affine");
|
||||
for (const ggml_planes::Plane& p : t->planes) {
|
||||
if (!p.role) break;
|
||||
rad_enc_add_plane(e, p.role, p.dtype, 1, p.block);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* One row of `cols` values held as GGUF blocks, split into one row of every plane of
|
||||
* ggml_plane_encoding's encoding: plane i's row goes to row[i], sized rad_enc_plane_dims and
|
||||
* rad_enc_row_bytes give for a one-row weight. `cols` is a whole number of blocks, and the type one
|
||||
* ggml_plane_encoding accepts. */
|
||||
inline void ggml_plane_row(uint32_t ggml_type, const uint8_t* blocks, int64_t cols,
|
||||
uint8_t* const* row) {
|
||||
const GgufDtype& gd = *gguf_dtype(ggml_type);
|
||||
ggml_planes::type_of(ggml_type)->split(blocks, cols / gd.blck, gd.block_bytes, row);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -98,6 +98,10 @@ struct VideoRefMedia {
|
||||
std::vector<float> enc_samples;
|
||||
int64_t enc_n = 0;
|
||||
int32_t enc_channels = 0;
|
||||
/* A keyframe of a latent-upscaled request again at the small size, prepared as at the full
|
||||
* one: the steps before the upscale pin it on their own grid. Empty otherwise. */
|
||||
std::vector<float> small_pixels;
|
||||
int32_t small_h = 0, small_w = 0;
|
||||
};
|
||||
|
||||
struct VideoRequest {
|
||||
|
||||
+44
-16
@@ -391,6 +391,7 @@ int VideoDriver::plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::s
|
||||
};
|
||||
j.ref_tab.clear();
|
||||
j.enc_q.clear();
|
||||
j.enc_pre = 0;
|
||||
if (r.refs.empty()) return RAD_OK;
|
||||
if (!pack_ || !enc_geom_)
|
||||
return no("this model conditions on no reference media");
|
||||
@@ -466,6 +467,7 @@ int VideoDriver::plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::s
|
||||
}
|
||||
j.ref_tab[1] = (int32_t)keys.size() / 3;
|
||||
j.ref_tab.insert(j.ref_tab.end(), keys.begin(), keys.end());
|
||||
j.enc_pre = j.enc_q.size();
|
||||
/* The prompt's vision pads: each picture's tokens, which ComfyUI modulates as video. */
|
||||
const size_t at = j.ref_tab.size();
|
||||
j.ref_tab.push_back(0);
|
||||
@@ -510,6 +512,33 @@ int VideoDriver::lay_out(const RadVideoGeom& g, const std::vector<int32_t>& tab,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* An upscaled request's keyframes, pinned on the grid its steps run on: encoded at the small size
|
||||
* before the prompt, then at the full size into the same slots once the upscale is done. */
|
||||
int VideoDriver::plan_small_keys(Job& j, const VideoRequest& r, std::string* why) const {
|
||||
const RadVideoGenDecl& d = decl_;
|
||||
std::vector<Job::EncItem> q;
|
||||
int32_t eg[kEncGeomCap];
|
||||
for (const Job::EncItem& it : j.enc_q) {
|
||||
if (it.kind != RAD_ENC_KEYFRAME) continue;
|
||||
const VideoRefMedia& m = r.refs[(size_t)it.ref];
|
||||
const int64_t in[4] = { m.enc_frames, m.small_h, m.small_w, 3 };
|
||||
if (m.small_pixels.size() != (size_t)m.enc_frames * m.small_h * m.small_w * 3 ||
|
||||
d.enc_ratio < 1 || m.small_h % d.enc_ratio || m.small_w % d.enc_ratio ||
|
||||
m.small_h / d.enc_ratio != j.geom_small.lat_h ||
|
||||
m.small_w / d.enc_ratio != j.geom_small.lat_w ||
|
||||
enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, kEncGeomCap) < 0) {
|
||||
if (why) *why = "'" + m.name + "' has no picture at the latent upscale's small size "
|
||||
"the model's encoder takes";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
q.push_back({ it.kind, it.slot, it.ref, true });
|
||||
}
|
||||
j.enc_pre = q.size();
|
||||
q.insert(q.end(), j.enc_q.begin(), j.enc_q.end());
|
||||
j.enc_q = std::move(q);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the
|
||||
* upscale's split and what its ticket says it makes. Run at submit, and again for a request whose
|
||||
* length the model predicts once its VCOND pass has written the prediction. */
|
||||
@@ -544,14 +573,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_
|
||||
RAD_TRY(plan_refs(j, r, s.frames, why));
|
||||
j.pack = Pack{};
|
||||
j.pack_small = Pack{};
|
||||
if (!j.ref_tab.empty()) {
|
||||
/* A keyframe is pinned on the video's grid, which an upscale's small steps are not on. */
|
||||
if (r.upscale > 1.0 && j.ref_tab[1] > 0)
|
||||
return no("a keyframe pins a frame of the video at its size, and latent_upscale "
|
||||
"denoises a smaller one first: send the keyframe request without "
|
||||
"latent_upscale");
|
||||
RAD_TRY(lay_out(j.geom, j.ref_tab, &j.pack, why));
|
||||
}
|
||||
if (!j.ref_tab.empty()) RAD_TRY(lay_out(j.geom, j.ref_tab, &j.pack, why));
|
||||
/* The schedule follows the upscale's split, which needs the small size first. */
|
||||
const bool upscaling = r.upscale > 1.0;
|
||||
const bool own_refine = upscaling && d.n_refine_rungs > 0;
|
||||
@@ -610,6 +632,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_
|
||||
if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns)
|
||||
return no("the model could not lay the small size out");
|
||||
if (!j.ref_tab.empty()) RAD_TRY(lay_out(j.geom_small, j.ref_tab, &j.pack_small, why));
|
||||
if (!j.ref_tab.empty() && j.ref_tab[1] > 0) RAD_TRY(plan_small_keys(j, r, why));
|
||||
j.split = evals - refine;
|
||||
j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0);
|
||||
r.ticket->small_width = sw;
|
||||
@@ -935,18 +958,20 @@ const RadBatch* VideoDriver::next(int step) {
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (!j.admitted || j.failed || j.cond_done) continue;
|
||||
if (j.enc_next < j.enc_q.size()) return build_encode(j, step);
|
||||
if (j.enc_next < j.enc_pre) return build_encode(j, step);
|
||||
}
|
||||
/* 3. A prompt. */
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
|
||||
}
|
||||
/* 4. The oldest lane's next step, or its upscale once its small steps are done. */
|
||||
/* 4. The oldest lane's next step, or its upscale once its small steps are done, and after it
|
||||
* the keyframes again at the full size. */
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue;
|
||||
if (small_now(j) && j.step == j.split) return build_upscale(j, step);
|
||||
if (!small_now(j) && j.enc_next < j.enc_q.size()) return build_encode(j, step);
|
||||
return build_step(j, step);
|
||||
}
|
||||
return nullptr;
|
||||
@@ -1189,9 +1214,12 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
|
||||
const Job::EncItem& it = j.enc_q[j.enc_next];
|
||||
const VideoRefMedia& m = j.req->refs[(size_t)it.ref];
|
||||
const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO;
|
||||
/* A keyframe at an upscale's small size is the media's second picture. */
|
||||
const std::vector<float>& pix = it.small ? m.small_pixels : m.enc_pixels;
|
||||
const int32_t eh = it.small ? m.small_h : m.enc_h, ew = it.small ? m.small_w : m.enc_w;
|
||||
int32_t* gd = hptr<int32_t>(R_ENCG);
|
||||
const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : m.enc_h,
|
||||
audio ? 0 : m.enc_w, audio ? m.enc_channels : 3 };
|
||||
const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : eh, audio ? 0 : ew,
|
||||
audio ? m.enc_channels : 3 };
|
||||
const int64_t ng = enc_geom_(audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE, in, gd,
|
||||
kEncGeomCap);
|
||||
int64_t stage_frames = 0, stage_samples = 0;
|
||||
@@ -1208,14 +1236,14 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
|
||||
std::memcpy(sm + c * stage_samples, m.enc_samples.data() + c * n, (size_t)n * 4);
|
||||
reg_[R_ENCSM].used = stage_samples * ch * 4;
|
||||
} else {
|
||||
const int64_t nf = m.enc_frames, area = (int64_t)m.enc_h * m.enc_w * 3;
|
||||
const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3;
|
||||
stage_frames = ng > 23 ? gd[23] : 0;
|
||||
if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
|
||||
fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass");
|
||||
return nullptr;
|
||||
}
|
||||
float* px = hptr<float>(R_ENCPX);
|
||||
std::memcpy(px, m.enc_pixels.data(), (size_t)(nf * area) * 4);
|
||||
std::memcpy(px, pix.data(), (size_t)(nf * area) * 4);
|
||||
for (int64_t f = nf; f < stage_frames; ++f)
|
||||
std::memcpy(px + f * area, px + (nf - 1) * area, (size_t)area * 4);
|
||||
reg_[R_ENCPX].used = stage_frames * area * 4;
|
||||
@@ -1238,8 +1266,8 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
|
||||
} else {
|
||||
V.enc_pixels = dptr<float>(ri, R_ENCPX);
|
||||
V.enc_frames = (int32_t)stage_frames;
|
||||
V.enc_height = m.enc_h;
|
||||
V.enc_width = m.enc_w;
|
||||
V.enc_height = eh;
|
||||
V.enc_width = ew;
|
||||
}
|
||||
}
|
||||
const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE;
|
||||
|
||||
+11
-6
@@ -16,9 +16,10 @@
|
||||
* 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the
|
||||
* video and audio VAE latents are in the lane's slots before its prompt runs.
|
||||
* 3. VCOND of an admitted request, so its steps can follow the current request's without a gap.
|
||||
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
|
||||
* Requests are denoised one after another, not in turns: a pass is one request's whole
|
||||
* sequence, so taking turns would only delay the first.
|
||||
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done,
|
||||
* then its keyframes' VENCODEs at the full size (an upscaled request's keyframes are encoded
|
||||
* at the small size in 2). Requests are denoised one after another, not in turns: a pass is
|
||||
* one request's whole sequence, so taking turns would only delay the first.
|
||||
*/
|
||||
#pragma once
|
||||
#include "video.h"
|
||||
@@ -86,12 +87,15 @@ private:
|
||||
std::vector<float> pos; /* [3, rows] */
|
||||
/* References and keyframes: their table (RadVideoGenBatch::ref_tab), the step's packed
|
||||
* sequence at the full size and at an upscale's small one (rows 0 without references),
|
||||
* and the encode passes, one a media in order, `enc_next` the next to run. */
|
||||
* and the encode passes, one a media in order, `enc_next` the next to run. The first
|
||||
* `enc_pre` run before the prompt; the rest, an upscaled request's keyframes at the full
|
||||
* size, run into the same slots once the upscale is done. */
|
||||
std::vector<int32_t> ref_tab;
|
||||
Pack pack, pack_small;
|
||||
struct EncItem { int32_t kind, slot, ref; }; /* RAD_ENC_*, its number, its req->refs */
|
||||
/* RAD_ENC_*, its number, its req->refs, and whether it is the media's small_pixels. */
|
||||
struct EncItem { int32_t kind, slot, ref; bool small = false; };
|
||||
std::vector<EncItem> enc_q;
|
||||
size_t enc_next = 0;
|
||||
size_t enc_next = 0, enc_pre = 0;
|
||||
/* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and
|
||||
* positions, the factor the network is told, and whether the upscale has run. */
|
||||
int32_t split = 0;
|
||||
@@ -143,6 +147,7 @@ private:
|
||||
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
|
||||
int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why);
|
||||
int plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::string* why) const;
|
||||
int plan_small_keys(Job& j, const VideoRequest& r, std::string* why) const;
|
||||
int lay_out(const RadVideoGeom& g, const std::vector<int32_t>& tab, Pack* out,
|
||||
std::string* why) const;
|
||||
int32_t predicted_chunks(double log_seconds, std::string* note) const;
|
||||
|
||||
+4
-4
@@ -270,12 +270,12 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
checkpoint_bytes_ = 0;
|
||||
window_ck_bytes_ = 0;
|
||||
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). */
|
||||
bool has_state = false;
|
||||
for (const auto& p : plans_) has_state = has_state || p.stateful();
|
||||
/* 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. */
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
!p.runtime_win && !groups[i].drafter;
|
||||
if (p.win_snap && !p.zero && p.n_layers > 0)
|
||||
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
|
||||
|
||||
+3
-4
@@ -121,10 +121,9 @@ struct KVGroupPlan {
|
||||
return runtime_tokens > 0 && block_size > 0
|
||||
? (runtime_tokens + block_size - 1) / block_size : 0;
|
||||
}
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
|
||||
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
|
||||
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
|
||||
* snapshot would be read. */
|
||||
/* 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. */
|
||||
bool win_snap = false;
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ struct TierJob {
|
||||
};
|
||||
Kind kind = Kind::WriteBack;
|
||||
BlockHash key;
|
||||
/* Per cached group, in PrefixCache::cached_groups() order: the blocks to read for a
|
||||
/* One per entry block, in PrefixCache::entry_groups() order: the blocks to read for a
|
||||
* write-back, or the blocks the engine allocated for a promotion. */
|
||||
std::vector<int32_t> blocks;
|
||||
int32_t host_slot = -1;
|
||||
|
||||
+74
-58
@@ -5,6 +5,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <numeric>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace rad {
|
||||
@@ -144,6 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
block_size_ = 0;
|
||||
interval_ = 0;
|
||||
groups_.clear();
|
||||
per_.clear();
|
||||
entry_groups_.clear();
|
||||
map_.clear(); lru_.clear();
|
||||
ck_by_prefix_.clear(); ck_by_session_.clear();
|
||||
/* set_policy() may override this afterwards. */
|
||||
@@ -156,12 +159,17 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Granularity is the first full-attention group's block size, since that is what a hit
|
||||
* reuses. Paged groups with another block size are not cached and are named in the report. */
|
||||
/* 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. */
|
||||
for (const auto& p : kv->plans()) {
|
||||
if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size;
|
||||
if (p.stateful()) has_linear_ = true;
|
||||
if (p.paged() && p.kind != RAD_KV_WINDOW && p.block_size > 0)
|
||||
block_size_ = block_size_ > 0 ? std::lcm(block_size_, p.block_size) : p.block_size;
|
||||
}
|
||||
/* With only windowed groups, nothing is indexed and a hit is a window snapshot alone, keyed
|
||||
* on the chain at the first group's block. */
|
||||
if (block_size_ == 0) {
|
||||
for (const auto& p : kv->plans()) if (p.paged()) { block_size_ = p.block_size; break; }
|
||||
}
|
||||
@@ -170,20 +178,25 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
RAD_WARN("%s", report_.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
std::string skipped;
|
||||
std::string skipped, split;
|
||||
for (const auto& p : kv->plans()) {
|
||||
if (!p.paged()) continue;
|
||||
/* A window group is not prefix-cached. Its blocks below the window are recycled, adopt()
|
||||
* would overfill a table capped at window_blocks, and a hit does not set first_block_pos.
|
||||
* A drafter or windowed layer's cache then starts where the hit ended. */
|
||||
* A checkpoint slot can carry a trunk's window instead (KVManager::has_window_snapshot);
|
||||
* a drafter or a windowed layer without one starts its cache where the hit ended. */
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
skipped += fmt(" group '%s' is windowed (%lld blocks): not cached\n",
|
||||
p.name.c_str(), (long long)p.window_blocks);
|
||||
skipped += fmt(" group '%s' is windowed (%lld blocks): not cached%s\n",
|
||||
p.name.c_str(), (long long)p.window_blocks,
|
||||
p.win_snap ? "; a checkpoint slot carries its window" : "");
|
||||
continue;
|
||||
}
|
||||
if (p.block_size == block_size_) groups_.push_back(p.index);
|
||||
else skipped += fmt(" group '%s' block %lld != cache granularity %lld: not cached\n",
|
||||
p.name.c_str(), (long long)p.block_size, (long long)block_size_);
|
||||
groups_.push_back(p.index);
|
||||
per_.push_back((int32_t)(block_size_ / p.block_size));
|
||||
for (int64_t k = 0; k < block_size_ / p.block_size; ++k) entry_groups_.push_back(p.index);
|
||||
if (p.block_size != block_size_)
|
||||
split += fmt(" group '%s' block %lld: %lld blocks an entry\n", p.name.c_str(),
|
||||
(long long)p.block_size, (long long)(block_size_ / p.block_size));
|
||||
}
|
||||
|
||||
/* An entry can be demoted only when the host tier can hold every group in it. A streamed
|
||||
@@ -209,8 +222,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
/* A checkpoint is found by the chained hash at its position, which exists only on
|
||||
* block boundaries, so an interval off the block grid would never hit. */
|
||||
RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, "
|
||||
"rounded up to the chunk quantum), which is not a multiple of the attention "
|
||||
"block size %lld, so no checkpoint would ever hit (spec §7.3)",
|
||||
"rounded up to the chunk quantum), which is not a multiple of the cache's "
|
||||
"%lld-token entry, so no checkpoint would ever hit (spec §7.3)",
|
||||
(long long)interval_, (long long)cfg.checkpoint_interval,
|
||||
(long long)block_size_);
|
||||
return RAD_E_INVAL;
|
||||
@@ -218,13 +231,14 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
}
|
||||
|
||||
enabled_ = true;
|
||||
report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
|
||||
report_ = fmt("prefix cache: %zu paged group(s) in %lld-token entries; checkpoints "
|
||||
"every %lld tokens (%lld slots of %s a rank, pinned host memory), retention "
|
||||
"'%s'\n",
|
||||
groups_.size(), (long long)block_size_,
|
||||
(long long)(has_linear_ ? interval_ : 0),
|
||||
(long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(),
|
||||
policy_->name());
|
||||
report_ += split;
|
||||
report_ += skipped;
|
||||
if (!demotable_) {
|
||||
/* Stated whether or not a host tier is configured. */
|
||||
@@ -306,7 +320,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
if (departed && matched > 0 && map_.find(hs[(size_t)matched - 1])->second.n_children >= 2)
|
||||
hit.branch_at = (int32_t)(matched * block_size_);
|
||||
|
||||
/* Back a full hit off by one block so one token remains to compute a logit from. */
|
||||
/* Back a full hit off by one entry so one token remains to compute a logit from. */
|
||||
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
|
||||
|
||||
auto deepest = [&](int64_t limit) { return deepest_ckpt(hs, limit); };
|
||||
@@ -336,8 +350,9 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
if (blocks_out)
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
const Entry& e = map_.find(hs[(size_t)b])->second;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
(*blocks_out)[g].push_back(e.blocks[g]);
|
||||
for (size_t k = 0, g = 0; g < groups_.size(); ++g)
|
||||
for (int32_t j = 0; j < per_[g]; ++j, ++k)
|
||||
(*blocks_out)[g].push_back(e.blocks[k]);
|
||||
}
|
||||
/* A hit is a use for the tiers' idle clock too; otherwise a prefix hit every turn, or one just
|
||||
* promoted for this lookup, would look idle since its publish. */
|
||||
@@ -368,6 +383,23 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
return hit;
|
||||
}
|
||||
|
||||
bool PrefixCache::retain_entry(const std::vector<std::vector<int32_t>>& bt, int64_t b,
|
||||
std::vector<int32_t>* out) {
|
||||
out->assign(entry_groups_.size(), -1);
|
||||
size_t k = 0;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
for (int32_t j = 0; j < per_[g]; ++j, ++k) {
|
||||
const int32_t blk = bt[g][(size_t)(b * per_[g] + j)];
|
||||
if (kv_->retain_block(groups_[g], blk) >= 0) { (*out)[k] = blk; continue; }
|
||||
/* Unwind exactly what was retained: anything else leaks a block or frees one under a
|
||||
* live sequence. */
|
||||
for (size_t i = 0; i < k; ++i) kv_->release_block(entry_groups_[i], (*out)[i]);
|
||||
out->clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int PrefixCache::insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
@@ -379,7 +411,8 @@ int PrefixCache::insert(uint64_t session,
|
||||
|
||||
const int64_t n_full = n_tokens / block_size_;
|
||||
if (n_full <= 0) return RAD_OK;
|
||||
for (const auto& bt : blocks) if ((int64_t)bt.size() < n_full) return RAD_E_INVAL;
|
||||
for (size_t g = 0; g < blocks.size(); ++g)
|
||||
if ((int64_t)blocks[g].size() < n_full * per_[g]) return RAD_E_INVAL;
|
||||
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
const uint64_t now = rad_mono_ns();
|
||||
@@ -397,17 +430,8 @@ int PrefixCache::insert(uint64_t session,
|
||||
* tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left
|
||||
* alone. */
|
||||
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
|
||||
std::vector<int32_t> mine(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
for (; held < groups_.size(); ++held) {
|
||||
const int32_t blk = blocks[held][(size_t)b];
|
||||
if (kv_->retain_block(groups_[held], blk) < 0) break;
|
||||
mine[held] = blk;
|
||||
}
|
||||
if (held != groups_.size()) {
|
||||
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], mine[g]);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
std::vector<int32_t> mine;
|
||||
if (!retain_entry(blocks, b, &mine)) return RAD_E_STATE;
|
||||
Entry& e = it->second;
|
||||
e.blocks = std::move(mine);
|
||||
e.used_ns = now;
|
||||
@@ -419,19 +443,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
}
|
||||
|
||||
Entry e;
|
||||
e.blocks.assign(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
for (; held < groups_.size(); ++held) {
|
||||
int32_t blk = blocks[held][(size_t)b];
|
||||
if (kv_->retain_block(groups_[held], blk) < 0) break;
|
||||
e.blocks[held] = blk;
|
||||
}
|
||||
if (held != groups_.size()) {
|
||||
/* Unwind exactly what was retained: anything else leaks a block or frees one under a
|
||||
* live sequence. */
|
||||
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!retain_entry(blocks, b, &e.blocks)) return RAD_E_STATE;
|
||||
e.tokens.assign(tokens.begin() + b * block_size_,
|
||||
tokens.begin() + (b + 1) * block_size_);
|
||||
e.used_ns = now;
|
||||
@@ -534,18 +546,20 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
int64_t PrefixCache::restore_room() const {
|
||||
if (!kv_ || groups_.empty()) return 0;
|
||||
int64_t room = INT64_MAX;
|
||||
for (int32_t g : groups_) room = std::min(room, kv_->total_blocks(g) - kv_->held_blocks(g));
|
||||
for (size_t i = 0; i < groups_.size(); ++i)
|
||||
room = std::min(room, (kv_->total_blocks(groups_[i]) - kv_->held_blocks(groups_[i])) /
|
||||
std::max<int32_t>(per_[i], 1));
|
||||
return std::max<int64_t>(0, room);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::trim_for(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm, int64_t n_blocks) {
|
||||
const std::vector<MMContentKey>& mm, int64_t n_entries) {
|
||||
/* Without a host tier a trim erases, and making room for a restore must lose nothing. */
|
||||
if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0;
|
||||
if (!enabled_ || n_entries <= 0 || !tiers_ || !tiers_->host_on()) return 0;
|
||||
const std::vector<BlockHash> hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_);
|
||||
std::unordered_set<BlockHash, BlockHashHash> spare(hs.begin(), hs.end());
|
||||
for (const auto& h : held_) spare.insert(h.first);
|
||||
return trim_sparing(n_blocks, &spare);
|
||||
return trim_sparing(n_entries, &spare);
|
||||
}
|
||||
|
||||
void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
@@ -563,14 +577,15 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) return RAD_E_NOTFOUND;
|
||||
if (blocks.size() != groups_.size()) return RAD_E_SHAPE;
|
||||
if (blocks.size() != entry_groups_.size()) return RAD_E_SHAPE;
|
||||
for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL;
|
||||
/* The reservation's reference becomes the cache's: KVManager::reserve_block left each block at
|
||||
* refcount one with no sequence attached, and the cache's release path frees it from now on.
|
||||
* No extra retain. */
|
||||
Entry& e = it->second;
|
||||
e.blocks = blocks;
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
|
||||
for (size_t k = 0; k < entry_groups_.size(); ++k)
|
||||
kv_->cache_reserved_block(entry_groups_[k], blocks[k]);
|
||||
if (!e.in_lru) {
|
||||
/* A restore is a use: a request is about to hit it. */
|
||||
e.used_ns = rad_mono_ns();
|
||||
@@ -582,8 +597,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
}
|
||||
|
||||
bool PrefixCache::shared_with_live(const Entry& e) const {
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true;
|
||||
for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k)
|
||||
if (kv_->block_refcount(entry_groups_[k], e.blocks[k]) > 1) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -595,7 +610,8 @@ bool PrefixCache::same_tokens(const Entry& e, const int32_t* src) const {
|
||||
}
|
||||
|
||||
void PrefixCache::release_blocks(const Entry& e) {
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]);
|
||||
for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k)
|
||||
kv_->release_block(entry_groups_[k], e.blocks[k]);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
@@ -634,16 +650,16 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::trim(int64_t n_blocks) { return trim_sparing(n_blocks, nullptr); }
|
||||
int64_t PrefixCache::trim(int64_t n_entries) { return trim_sparing(n_entries, nullptr); }
|
||||
|
||||
int64_t PrefixCache::trim_sparing(int64_t n_blocks,
|
||||
int64_t PrefixCache::trim_sparing(int64_t n_entries,
|
||||
const std::unordered_set<BlockHash, BlockHashHash>* spare) {
|
||||
/* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */
|
||||
const bool keep = tiers_ && tiers_->host_on();
|
||||
const uint64_t now = rad_mono_ns();
|
||||
int64_t done = 0;
|
||||
auto it = lru_.begin();
|
||||
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0;
|
||||
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_entries && seen > 0;
|
||||
--seen) {
|
||||
const BlockHash h = *it;
|
||||
auto m = map_.find(h);
|
||||
@@ -714,11 +730,11 @@ int64_t PrefixCache::drop_clean() {
|
||||
}
|
||||
|
||||
/* The KV manager tracks how many cache-held blocks are at refcount one. One group only: the paged
|
||||
* groups share a token axis and an entry is one block in each, so summing groups would multiply
|
||||
* the answer. Off-device entries hold no blocks and count for nothing. */
|
||||
* groups share a token axis and an entry is blocks_per_entry() blocks in each, so summing groups
|
||||
* would multiply the answer. Off-device entries hold no blocks and count for nothing. */
|
||||
int64_t PrefixCache::unshared_tokens() const {
|
||||
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
|
||||
return kv_->cache_only_blocks(groups_[0]) * block_size_;
|
||||
if (!kv_ || groups_.empty() || block_size_ <= 0 || per_.empty() || per_[0] <= 0) return 0;
|
||||
return kv_->cache_only_blocks(groups_[0]) * (block_size_ / per_[0]);
|
||||
}
|
||||
|
||||
void PrefixCache::clear() {
|
||||
@@ -1035,7 +1051,7 @@ int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t
|
||||
/* A kept token keeps its whole block: the block holding it is what the next turn hits. */
|
||||
const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_;
|
||||
int64_t entry_bytes = 0;
|
||||
for (int32_t g : groups_) {
|
||||
for (int32_t g : entry_groups_) {
|
||||
const KVGroupPlan* p = kv_->plan(g);
|
||||
if (p) entry_bytes += p->bytes_per_block;
|
||||
}
|
||||
|
||||
+44
-18
@@ -23,6 +23,12 @@
|
||||
* interval (next_checkpoint_after()), so a checkpoint is always written, at the cost of an
|
||||
* occasional short chunk.
|
||||
*
|
||||
* Block sizes: an entry covers block_size() tokens, the lcm of the cached groups' block sizes, and
|
||||
* holds block_size() / B blocks of a group whose blocks are B tokens. A model whose layers keep KV
|
||||
* at different strides (a compressed group at one row per r tokens beside one per token) is cached
|
||||
* in every group; a hit is then a multiple of every group's block. The chunk quantum is a multiple
|
||||
* of every paged group's block (core/sched/geometry.cpp), so checkpoints land on entries.
|
||||
*
|
||||
* Sizing: the cache holds a KV reference on every block it indexes, so pool demand scales with
|
||||
* live sessions, not running requests. Hit rate falls off a cliff with pool utilisation: intact
|
||||
* below about 75%, half gone by about 81%, and zero once the sessions no longer fit, because each
|
||||
@@ -207,6 +213,8 @@ public:
|
||||
* make reserve_checkpoint refuse every checkpoint and lookups search the wrong stride. */
|
||||
int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval);
|
||||
bool enabled() const { return enabled_; }
|
||||
/* Tokens one entry covers: the lcm of the cached groups' block sizes. Hits, publishes and
|
||||
* checkpoint keys are whole entries. */
|
||||
int64_t block_size() const { return block_size_; }
|
||||
int64_t checkpoint_interval() const { return interval_; }
|
||||
const std::vector<int32_t>& cached_groups() const { return groups_; }
|
||||
@@ -214,6 +222,13 @@ public:
|
||||
* rows are addressed by the sequence's block ids, so entries stay in VRAM and are evicted
|
||||
* whole (docs/KV-STREAMING.md §4.1). */
|
||||
bool demotable() const { return demotable_; }
|
||||
/* Blocks of cached_groups()[i] in one entry: block_size() over that group's block size. */
|
||||
int64_t blocks_per_entry(size_t i) const { return i < per_.size() ? per_[i] : 0; }
|
||||
/* The group of each block an entry holds, in the order of its block list (Entry::blocks,
|
||||
* TierJob::blocks, rebind): cached_groups()[i] repeated blocks_per_entry(i) times. The idle
|
||||
* tiers move an entry as these blocks, one per slot. Equal to cached_groups() when every
|
||||
* cached group has the same block size. */
|
||||
const std::vector<int32_t>& entry_groups() const { return entry_groups_; }
|
||||
std::string report() const;
|
||||
|
||||
/* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
|
||||
@@ -222,12 +237,12 @@ public:
|
||||
const CheckpointPolicy& policy() const { return *policy_; }
|
||||
|
||||
/* ---------------- full attention ---------------- */
|
||||
/* Longest cached prefix, in whole blocks, plus the checkpoint that covers the linear state
|
||||
/* Longest cached prefix, in whole entries, plus the checkpoint that covers the linear state
|
||||
* for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in
|
||||
* cached_groups() order, ready for KVManager::adopt().
|
||||
* cached_groups() order, ready for KVManager::adopt(): blocks_per_entry(i) of them an entry.
|
||||
*
|
||||
* Never returns the whole prompt: one token must remain to compute a logit from, so a full
|
||||
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`,
|
||||
* hit is backed off by one entry. `cap`, when given, ends the hit early (HitCap). `session`,
|
||||
* when not 0, is the request being admitted: it takes over the snapshots on the chain it hit
|
||||
* (take_over). */
|
||||
CacheHit lookup(const std::vector<int32_t>& tokens,
|
||||
@@ -235,7 +250,7 @@ public:
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
|
||||
const HitCap* cap = nullptr, uint64_t session = 0) const;
|
||||
|
||||
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
|
||||
/* Publish the whole entries a sequence just filled. `blocks[i]` is the block table of
|
||||
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
|
||||
int insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
@@ -249,11 +264,12 @@ public:
|
||||
* idle tiers on, an entry whose host copy has landed moves to the host tier instead of being
|
||||
* forgotten; only one with no host copy is lost. */
|
||||
int64_t evict_lru(int64_t n_entries);
|
||||
/* Free up to `n_blocks` pool blocks for the scheduler's reserve without losing anything a
|
||||
* later turn could reuse. One oldest-first walk that skips entries a live sequence also holds
|
||||
* and, with the tiers on, entries whose host copy has not landed yet. Pressure that cannot
|
||||
* wait goes to evict_lru. Returns how many blocks went back. */
|
||||
int64_t trim(int64_t n_blocks);
|
||||
/* Give back up to `n_entries` entries' blocks for the scheduler's reserve without losing
|
||||
* anything a later turn could reuse. One oldest-first walk that skips entries a live sequence
|
||||
* also holds and, with the tiers on, entries whose host copy has not landed yet. Pressure
|
||||
* that cannot wait goes to evict_lru. Returns how many entries went: each gave back
|
||||
* blocks_per_entry(i) blocks of cached group i. */
|
||||
int64_t trim(int64_t n_entries);
|
||||
/* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
|
||||
* reading it. Used when the memory has a better use (the expert slab's loan). Entries still
|
||||
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
|
||||
@@ -288,23 +304,25 @@ public:
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t fit = INT64_MAX, bool* cut = nullptr) const;
|
||||
/* Entries a restore can place now: free blocks against the carve, the least over the cached
|
||||
* groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */
|
||||
/* Entries a restore can place now: free blocks against the carve over the blocks an entry
|
||||
* takes in the group, the least over the cached groups. Lent blocks count, since
|
||||
* KVManager::reserve_blocks recalls the loan for them. */
|
||||
int64_t restore_room() const;
|
||||
/* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks
|
||||
* would only have to come back too) and every chain a waiting request holds (hold()), whose
|
||||
* next attempt would restore it again. Only entries whose host copy has landed leave VRAM,
|
||||
* so nothing is lost; with no host tier it takes nothing. */
|
||||
* so nothing is lost; with no host tier it takes nothing. In entries, as trim(). */
|
||||
int64_t trim_for(const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks);
|
||||
int64_t n_entries);
|
||||
|
||||
/* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry
|
||||
* owns none, and its recorded ids now belong to other sequences. Installed as
|
||||
* IdleTiers::set_drop_sink. */
|
||||
void drop_offdevice(const BlockHash& key);
|
||||
|
||||
/* A restore finished and the entry's blocks now live at these ids. The restore's raw
|
||||
* reservations (KVManager::reserve_block) become cache-held references. */
|
||||
/* A restore finished and the entry's blocks now live at these ids, one per entry_groups()
|
||||
* slot. The restore's raw reservations (KVManager::reserve_block) become cache-held
|
||||
* references. */
|
||||
int rebind(const BlockHash& key, const std::vector<int32_t>& blocks);
|
||||
|
||||
|
||||
@@ -404,7 +422,8 @@ public:
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::vector<int32_t> blocks; /* one per cached group, in groups_ order */
|
||||
/* 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 */
|
||||
/* 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. */
|
||||
@@ -438,14 +457,19 @@ private:
|
||||
int64_t n_blocks) const;
|
||||
void touch(const BlockHash& h, uint64_t now_ns) const;
|
||||
/* trim(), leaving the entries in `spare` (when given) where they are. */
|
||||
int64_t trim_sparing(int64_t n_blocks,
|
||||
int64_t trim_sparing(int64_t n_entries,
|
||||
const std::unordered_set<BlockHash, BlockHashHash>* spare);
|
||||
/* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */
|
||||
bool shared_with_live(const Entry& e) const;
|
||||
/* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */
|
||||
bool same_tokens(const Entry& e, const int32_t* src) const;
|
||||
/* Gives the entry's block in every group back to the KV manager. */
|
||||
/* Gives the entry's blocks in every group back to the KV manager. */
|
||||
void release_blocks(const Entry& e);
|
||||
/* Takes the cache's reference on the blocks of entry `b` of a sequence's tables `bt` (one per
|
||||
* cached group) into `out`, entry_groups_ order; on a refusal releases exactly what it took
|
||||
* and returns false. */
|
||||
bool retain_entry(const std::vector<std::vector<int32_t>>& bt, int64_t b,
|
||||
std::vector<int32_t>* out);
|
||||
/* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
|
||||
* caller. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
@@ -474,6 +498,8 @@ private:
|
||||
int64_t interval_ = 0;
|
||||
std::vector<int32_t> groups_; /* paged groups this cache indexes */
|
||||
bool demotable_ = false; /* the host tier can hold every group in an entry */
|
||||
std::vector<int32_t> per_; /* blocks of groups_[i] an entry holds */
|
||||
std::vector<int32_t> entry_groups_; /* the group of each of an entry's blocks */
|
||||
bool has_linear_ = false;
|
||||
|
||||
mutable std::unordered_map<BlockHash, Entry, BlockHashHash> map_;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef RAD_HAVE_FFMPEG
|
||||
@@ -26,6 +27,8 @@ namespace mm {
|
||||
|
||||
bool decoder_available() { return false; }
|
||||
|
||||
std::string decoder_version() { return "absent (built without libav*)"; }
|
||||
|
||||
static int no_decoder(std::string* why) {
|
||||
if (why) *why = "this build has no media decoder: it was configured without libavformat / "
|
||||
"libavcodec / libswscale (RAD_WITH_FFMPEG)";
|
||||
@@ -57,6 +60,14 @@ int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
|
||||
|
||||
bool decoder_available() { return true; }
|
||||
|
||||
std::string decoder_version() {
|
||||
const unsigned v = avformat_version();
|
||||
char b[48];
|
||||
std::snprintf(b, sizeof(b), "libavformat %u.%u.%u", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v),
|
||||
AV_VERSION_MICRO(v));
|
||||
return b;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* The only demuxers a request may reach. A format that can name another file (a playlist, a
|
||||
|
||||
@@ -36,6 +36,11 @@ 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. */
|
||||
std::string decoder_version();
|
||||
|
||||
/* The first frame of an image (or of anything with a video stream). Refuses a source over
|
||||
* `max_pixels`, which bounds what a request can make the server allocate before any resize. */
|
||||
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
|
||||
|
||||
+7
-1
@@ -22,6 +22,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
tier_.assign(n, Tier::VRAM);
|
||||
busy_.assign(n, 0u);
|
||||
movable_.assign(n, 0u);
|
||||
pinned_.assign(n, 0u);
|
||||
layer_of_.assign(n, -1);
|
||||
bytes_.assign(n, 0);
|
||||
ever_.assign(n, 0u);
|
||||
@@ -61,6 +62,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
layer_of_[u] = mu.layer;
|
||||
bytes_[u] = mu.bytes;
|
||||
movable_[u] = mu.movable ? 1u : 0u;
|
||||
pinned_[u] = mu.pinned ? 1u : 0u;
|
||||
if (mu.movable) ++movable;
|
||||
if (mu.layer < 0) {
|
||||
if (mu.movable) other[(size_t)n_layer_].push_back((int32_t)u);
|
||||
@@ -280,7 +282,9 @@ void HeatEngine::set_busy(int32_t unit, bool busy) {
|
||||
void HeatEngine::set_place(int32_t unit) {
|
||||
const size_t u = (size_t)unit, p = (size_t)pos_[u];
|
||||
const bool vram = tier_[u] == Tier::VRAM;
|
||||
rank_as_[p] = (!movable_[u] || busy_[u]) ? 0u : vram ? 2u : 1u;
|
||||
/* A pinned resident is never a candidate to leave the card: it ranks as off-device only, so a
|
||||
* promotion can still target it but a demotion cannot. */
|
||||
rank_as_[p] = (!movable_[u] || busy_[u] || (pinned_[u] && vram)) ? 0u : vram ? 2u : 1u;
|
||||
routed_as_[p] = vram ? 2u : 1u;
|
||||
miss_bytes_[p] = vram ? 0 : bytes_[u];
|
||||
}
|
||||
@@ -330,6 +334,8 @@ bool HeatEngine::pick(Swap* out) const {
|
||||
const int32_t rc = l >= 0 ? res_count_[(size_t)l] : 0;
|
||||
const float h = heat_[(size_t)pos_[i]];
|
||||
if (tier_[i] == Tier::VRAM) {
|
||||
/* A pinned resident never leaves the card, whatever its heat. */
|
||||
if (pinned_[i]) continue;
|
||||
/* Colder wins; on a tie, take from the layer holding the most resident units. */
|
||||
if (cold[c] < 0 || h < cold_h[c] || (h == cold_h[c] && rc > cold_res[c])) {
|
||||
cold[c] = (int32_t)i; cold_h[c] = h; cold_res[c] = rc;
|
||||
|
||||
@@ -210,6 +210,9 @@ private:
|
||||
std::vector<Tier> tier_;
|
||||
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. */
|
||||
std::vector<uint8_t> pinned_;
|
||||
std::vector<int32_t> layer_of_;
|
||||
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
|
||||
std::vector<uint8_t> ever_;
|
||||
|
||||
+138
-6
@@ -12,6 +12,7 @@
|
||||
#include "planner.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -103,6 +104,21 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
/* A draft head's routed experts, pinned in the host pool before any strategy runs, leave the trunk
|
||||
* the whole of `host_room`. The card then holds only the trunk's floor against that room. The
|
||||
* drafter's units share the trunk's slab classes, so the spare the trunk's floor already reserves
|
||||
* covers them; with no trunk experts the drafter is the whole plane and pinning it leaves the card
|
||||
* nothing to hold. */
|
||||
int64_t expert_vram_floor_draft_hosted(const WeightFootprint& wf, int64_t host_room) {
|
||||
if (wf.draft_experts <= 0) return expert_vram_floor(wf, host_room);
|
||||
const int64_t trunk = wf.experts - wf.draft_experts;
|
||||
if (trunk <= 0) return 0;
|
||||
WeightFootprint t = wf;
|
||||
t.experts = trunk;
|
||||
t.draft_experts = 0;
|
||||
return expert_vram_floor(t, host_room);
|
||||
}
|
||||
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
if (p.vram_budget == pool_bytes) return RAD_OK;
|
||||
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
|
||||
@@ -226,6 +242,14 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
layer_experts[mu.layer] += b;
|
||||
out->expert_unit_max = std::max(out->expert_unit_max, b);
|
||||
expert_strides.insert(b);
|
||||
/* A draft head's routed experts: layers at meta.n_layers and above, and only when the
|
||||
* program declares a drafter. The trunk's own layers stay in the elastic plane a
|
||||
* strategy places; --draft-expert-placement host takes this part out of it. */
|
||||
if (prog.drafter.kind != RAD_DRAFT_NONE && prog.meta.n_layers > 0 &&
|
||||
mu.layer >= (int32_t)prog.meta.n_layers) {
|
||||
out->draft_experts += b;
|
||||
out->draft_unit_max = std::max(out->draft_unit_max, b);
|
||||
}
|
||||
}
|
||||
else out->statics += b;
|
||||
if (mu.layer >= 0 && !mu.mapped) out->layer_unit_max = std::max(out->layer_unit_max, b);
|
||||
@@ -667,7 +691,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
Cost k;
|
||||
for (int32_t ui : order) {
|
||||
MoveUnit& mu = p->units[(size_t)ui];
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL) continue;
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL || mu.preplaced()) continue;
|
||||
mu.tier = Tier::VRAM;
|
||||
mu.site = Site::Device;
|
||||
mu.reason = "fits in vram";
|
||||
@@ -679,7 +703,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
|
||||
for (int32_t ui : order) {
|
||||
MoveUnit& mu = p->units[(size_t)ui];
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL) continue;
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL || mu.preplaced()) continue;
|
||||
if (k.residents < cap && k.used + mu.slot_bytes <= room) {
|
||||
k.used += mu.slot_bytes;
|
||||
++k.residents;
|
||||
@@ -1027,6 +1051,100 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --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. */
|
||||
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) {
|
||||
if (cfg.draft_expert_placement_given) {
|
||||
RAD_ERR("placement: --draft-expert-placement host: this model declares no draft head");
|
||||
p->notes.push_back("--draft-expert-placement host: no draft head to place");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
const int32_t trunk = (int32_t)prog.meta.n_layers;
|
||||
auto draft = [&](const MoveUnit& mu) {
|
||||
return mu.expert >= 0 && mu.layer >= trunk && mu.tier != Tier::Mapped && !mu.host_forced;
|
||||
};
|
||||
int64_t need = 0, n = 0, widest = 0;
|
||||
for (const MoveUnit& mu : p->units)
|
||||
if (draft(mu)) { need += mu.slot_bytes; widest = std::max(widest, mu.slot_bytes); ++n; }
|
||||
if (!n) {
|
||||
RAD_ERR("placement: --draft-expert-placement host: the draft head declares no routed "
|
||||
"experts");
|
||||
p->notes.push_back("--draft-expert-placement host: no drafter experts to place");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (need > p->host_budget) {
|
||||
RAD_ERR("placement: --draft-expert-placement host: the drafter's experts need %s of the "
|
||||
"pinned host pool and %s of it is left%s", humanb(need).c_str(),
|
||||
humanb(p->host_budget).c_str(),
|
||||
p->file_stage_reserve ? " after the file tier's staging" : "");
|
||||
p->notes.push_back(fmt("--draft-expert-placement host: the drafter's experts (%s) do not "
|
||||
"fit the host pool", humanb(need).c_str()));
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
for (MoveUnit& mu : p->units) {
|
||||
if (!draft(mu)) continue;
|
||||
p->host_budget -= mu.slot_bytes;
|
||||
p->draft_host_bytes += mu.slot_bytes;
|
||||
mu.tier = Tier::HostPinned;
|
||||
mu.site = Site::DeviceZeroCopy;
|
||||
mu.movable = false;
|
||||
mu.host_forced = true;
|
||||
mu.reason = "--draft-expert-placement host; read over the link in place";
|
||||
}
|
||||
RAD_INFO("placement: the drafter's experts, %lld units (%s, widest %s), in the pinned host "
|
||||
"pool, read in place (--draft-expert-placement host)", (long long)n,
|
||||
humanb(need).c_str(), humanb(widest).c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --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
|
||||
* 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. */
|
||||
void Planner::pin_hot(const Config& cfg, Plan* p) const {
|
||||
if (cfg.expert_pin_top <= 0.0f) return;
|
||||
std::vector<float> shares;
|
||||
for (const MoveUnit& mu : p->units)
|
||||
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. */
|
||||
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
|
||||
: shares[shares.size() - hot] - 1.0f;
|
||||
p->pin_threshold = threshold;
|
||||
p->profile_units = (int64_t)shares.size();
|
||||
int64_t pinned = 0, left = 0;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
if (mu.expert < 0 || mu.tier == Tier::Mapped || mu.host_forced) continue;
|
||||
if (mu.profile_share <= threshold) continue;
|
||||
if (mu.tier != Tier::VRAM) { ++left; continue; }
|
||||
mu.pinned = true;
|
||||
mu.movable = false;
|
||||
++pinned;
|
||||
}
|
||||
p->pinned_units = pinned;
|
||||
RAD_INFO("placement: --expert-pin-top %.4g pins %lld of %lld routed experts resident (share "
|
||||
"above %.4g); %lld of the hot set had no VRAM slot and stay where the strategy put "
|
||||
"them", (double)cfg.expert_pin_top, (long long)pinned, (long long)shares.size(),
|
||||
(double)threshold, (long long)left);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ plan */
|
||||
int Planner::plan(Plan* out) {
|
||||
if (!out || !in_.program || !in_.config) return RAD_E_INVAL;
|
||||
@@ -1055,6 +1173,13 @@ int Planner::plan(Plan* out) {
|
||||
pin_mapped(prog, 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. */
|
||||
int hrc = pin_embedding(prog, cfg, out);
|
||||
const int trc = pin_towers(cfg, out);
|
||||
if (hrc >= 0) hrc = trc;
|
||||
if (hrc >= 0) hrc = pin_draft_experts(prog, cfg, out);
|
||||
|
||||
/* Charge the file tier's staging pool (RAD_PLACE_FILE_STAGE_SLOTS) before anything is placed
|
||||
* in the host pool, or the fill could exhaust it and the mover refuse the plan. Sized from the
|
||||
* widest class carrying a layer unit, the only kind either offload strategy spills; this
|
||||
@@ -1087,14 +1212,14 @@ int Planner::plan(Plan* out) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 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;
|
||||
/* 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);
|
||||
/* After the strategy: it has put the hot set in VRAM, and pinning marks those resident. */
|
||||
pin_hot(cfg, out);
|
||||
finish(prog, out);
|
||||
return hrc < 0 ? hrc : rc;
|
||||
}
|
||||
@@ -1222,6 +1347,13 @@ std::string Plan::report(const Program& prog) const {
|
||||
if (tower_host_bytes)
|
||||
s += fmt(" encoder tower %12s %12s (--vision-tower-placement ram, pinned, read in place)\n",
|
||||
"-", humanb(tower_host_bytes).c_str());
|
||||
if (draft_host_bytes)
|
||||
s += fmt(" drafter %12s %12s (--draft-expert-placement host, pinned, read in place)\n",
|
||||
"-", humanb(draft_host_bytes).c_str());
|
||||
if (pinned_units)
|
||||
s += fmt(" pinned hot %12s %12lld (--expert-pin-top: resident, heat never demotes them, "
|
||||
"share above %.4g of %lld)\n", "-", (long long)pinned_units, (double)pin_threshold,
|
||||
(long long)profile_units);
|
||||
if (ngram_copy_bytes)
|
||||
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n",
|
||||
"-", humanb(ngram_copy_bytes).c_str(),
|
||||
|
||||
+22
-2
@@ -79,8 +79,9 @@ struct MoveUnit {
|
||||
Site site = Site::Device;
|
||||
int32_t slab_slot = -1;
|
||||
bool movable = false; /* may the heat engine relocate it after load */
|
||||
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's
|
||||
* or the encoder tower's */
|
||||
bool pinned = false; /* a decode-hot resident --expert-pin-top kept: heat never demotes it */
|
||||
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's,
|
||||
* the encoder tower's or the draft head's experts' */
|
||||
|
||||
/* Placed before any strategy runs, so every assignment pass skips it and no VRAM total counts
|
||||
* it: the mapped tier, --embedding-placement ram and --vision-tower-placement ram. */
|
||||
@@ -227,7 +228,14 @@ public:
|
||||
* both flags' weight bytes, as the tier totals count them; the pooled figures exclude it. */
|
||||
int64_t embedding_host_bytes = 0;
|
||||
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. */
|
||||
int64_t pinned_units = 0;
|
||||
int64_t profile_units = 0;
|
||||
float pin_threshold = 0.0f;
|
||||
/* --ngram-placement ram: RAM for the n-gram tables the load phase copies out of the mapping.
|
||||
* Every pool still sees them on the mapped tier. `ngram_copy_card` selects pinned memory a
|
||||
* device kernel reads over the link; otherwise locked memory the host gather reads. */
|
||||
@@ -314,6 +322,8 @@ private:
|
||||
void pin_mapped(const Program& prog, Plan* p);
|
||||
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
|
||||
int pin_towers(const Config& cfg, Plan* p) const;
|
||||
int pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const;
|
||||
void pin_hot(const Config& cfg, Plan* p) const;
|
||||
void build_classes(Plan* p);
|
||||
void rank_units(Plan* p, std::vector<int32_t>* order) const;
|
||||
int assign(Plan* p);
|
||||
@@ -349,6 +359,11 @@ struct WeightFootprint {
|
||||
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
|
||||
int64_t expert_unit_max = 0; /* the largest expert unit's slot */
|
||||
/* A draft head's routed experts (layers at meta.n_layers and above, when the program has a
|
||||
* drafter): the part of `experts` a host-pinned --draft-expert-placement takes out of the host
|
||||
* pool's room for the trunk, and the largest such unit. */
|
||||
int64_t draft_experts = 0;
|
||||
int64_t draft_unit_max = 0;
|
||||
/* Upper bound on an expert-tiered plan's spare slab: per expert slab class, the shadow slots,
|
||||
* staging ring and tail pad (Planner::assign_expert_tiered). Same weight budget as residents. */
|
||||
int64_t expert_spare = 0;
|
||||
@@ -400,6 +415,11 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
* the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* The same floor once --draft-expert-placement host has taken the drafter's experts out of the
|
||||
* plane the strategy places: the trunk's floor against the whole host room. The drafter's units
|
||||
* share the trunk's slab classes, so no spare is added. With no drafter it is expert_vram_floor. */
|
||||
int64_t expert_vram_floor_draft_hosted(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* Checks that the plan and this rank's weights pool used the same split: Plan::vram_budget must
|
||||
* equal the pool Pools::configure allocated, or the slab and the pool disagree silently. Returns
|
||||
* RAD_E_STATE, logging the rank and both sizes, when they differ. */
|
||||
|
||||
@@ -479,4 +479,70 @@ void ExpertStats::stop() {
|
||||
|
||||
ExpertStats::~ExpertStats() { stop(); }
|
||||
|
||||
/* ------------------------------------------------------------------ --expert-profile */
|
||||
|
||||
int xs_profile_load(const std::string& path, std::vector<RadFileProfile>* out, int32_t* n_trunk) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
out->clear();
|
||||
if (n_trunk) *n_trunk = -1;
|
||||
FILE* f = std::fopen(path.c_str(), "r");
|
||||
if (!f) {
|
||||
RAD_ERR("--expert-profile: cannot read %s: %s", path.c_str(), std::strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
std::string text;
|
||||
char buf[1 << 16];
|
||||
while (const size_t n = std::fread(buf, 1, sizeof buf, f)) text.append(buf, n);
|
||||
const bool bad = std::ferror(f) != 0;
|
||||
std::fclose(f);
|
||||
if (bad) {
|
||||
RAD_ERR("--expert-profile: reading %s failed", path.c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
nlohmann::json j;
|
||||
try { j = nlohmann::json::parse(text); }
|
||||
catch (const nlohmann::json::exception& e) {
|
||||
RAD_ERR("--expert-profile: %s is not JSON: %s", path.c_str(), e.what());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!j.is_object() || j.value("format", "") != "radiance-expert-stats/1" ||
|
||||
!j.contains("counts") || !j["counts"].contains("decode") ||
|
||||
!j["counts"]["decode"].is_array()) {
|
||||
RAD_ERR("--expert-profile: %s is not a radiance-expert-stats/1 file with decode counts",
|
||||
path.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (n_trunk && j.contains("n_trunk_layers") && j["n_trunk_layers"].is_number_integer())
|
||||
*n_trunk = j["n_trunk_layers"].get<int32_t>();
|
||||
const auto& rows = j["counts"]["decode"];
|
||||
int64_t kept = 0;
|
||||
for (size_t l = 0; l < rows.size(); ++l) {
|
||||
if (!rows[l].is_array()) continue;
|
||||
uint64_t sum = 0;
|
||||
for (const auto& c : rows[l])
|
||||
if (c.is_number_unsigned() || c.is_number_integer())
|
||||
sum += c.get<uint64_t>();
|
||||
if (sum == 0) continue;
|
||||
for (size_t e = 0; e < rows[l].size(); ++e) {
|
||||
const auto& c = rows[l][e];
|
||||
if (!(c.is_number_unsigned() || c.is_number_integer())) continue;
|
||||
const uint64_t n = c.get<uint64_t>();
|
||||
if (n == 0) continue;
|
||||
RadFileProfile p{};
|
||||
p.layer = (int32_t)l;
|
||||
p.expert = (int32_t)e;
|
||||
p.share = (float)((double)n / (double)sum);
|
||||
out->push_back(p);
|
||||
++kept;
|
||||
}
|
||||
}
|
||||
if (kept == 0)
|
||||
RAD_WARN("--expert-profile: %s has no decode selections; the planner ranks from the "
|
||||
"container's profile", path.c_str());
|
||||
else
|
||||
RAD_INFO("--expert-profile: %lld decode-hot entries over %zu layers from %s",
|
||||
(long long)kept, rows.size(), path.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -210,4 +210,11 @@ private:
|
||||
std::mutex file_mu_; /* one write at a time */
|
||||
};
|
||||
|
||||
/* --expert-profile FILE: the planner's ranking, from a radiance-expert-stats JSON's `decode`
|
||||
* counts. One entry per (layer, expert) with a positive count, its share that count over the
|
||||
* layer's decode selections, so a layer's hottest expert ranks above another layer's merely busy
|
||||
* one. `n_trunk` is the file's trunk layer count, or -1 where it names none. Returns RAD_E_IO on a
|
||||
* missing or unreadable file and RAD_E_INVAL on one that is not this format. */
|
||||
int xs_profile_load(const std::string& path, std::vector<RadFileProfile>* out, int32_t* n_trunk);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -907,6 +907,14 @@ 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). */
|
||||
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. */
|
||||
std::string checkpoint_policy = "geometric-backoff";
|
||||
@@ -1079,6 +1087,21 @@ struct Config {
|
||||
/* --expert-stats FILE: count the routed experts every layer selects, by step kind, and write
|
||||
* the counts to FILE as JSON every 30 s and at shutdown (place/xstats.h). Empty is off. */
|
||||
std::string expert_stats;
|
||||
/* --expert-profile FILE: a radiance-expert-stats JSON (place/xstats.h) whose `decode` counts
|
||||
* rank the expert plane, instead of the container's activation profile. Empty serves the
|
||||
* container's profile. */
|
||||
std::string expert_profile;
|
||||
bool expert_profile_given = false;
|
||||
/* --expert-pin-top F: pin the hottest F of the routed experts (0 < F <= 1) by the profile's
|
||||
* 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. */
|
||||
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. */
|
||||
bool live_view = false;
|
||||
|
||||
|
||||
@@ -87,11 +87,20 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
verify_ = std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
|
||||
verify_rep_ = verify_ && !leader_ && rep_bytes_ > 0;
|
||||
|
||||
/* A group whose blocks are shorter than an entry is listed once per block it holds there. */
|
||||
size_t n_groups = 0;
|
||||
for (size_t i = 0; i < gi_.size(); ++i) {
|
||||
bool seen = false;
|
||||
for (size_t j = 0; j < i && !seen; ++j) seen = gi_[j].g == gi_[i].g;
|
||||
if (!seen) ++n_groups;
|
||||
}
|
||||
const std::string blocks =
|
||||
n_groups != gi_.size() ? fmt(" in %zu blocks", gi_.size()) : std::string();
|
||||
char buf[400];
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s, batches of %d through "
|
||||
"gather_rows/scatter_rows at u8",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(),
|
||||
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s%s, batches of %d "
|
||||
"through gather_rows/scatter_rows at u8",
|
||||
n_groups, humanb(entry_bytes_).c_str(), blocks.c_str(),
|
||||
rep_bytes_ > 0 ? " (" : "",
|
||||
rep_bytes_ > 0 ? humanb(rep_bytes_).c_str() : "",
|
||||
rep_bytes_ > 0 ? " of it replicated on every rank and held once a slot)" : "",
|
||||
@@ -143,7 +152,8 @@ int TierExec::slot_layout(const std::vector<const KVManager*>& ranks,
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
L.rep_bytes += p0->bytes_per_block;
|
||||
L.replicated.push_back(p0->name);
|
||||
if (std::find(L.replicated.begin(), L.replicated.end(), p0->name) == L.replicated.end())
|
||||
L.replicated.push_back(p0->name);
|
||||
}
|
||||
int64_t slot = L.rep_bytes;
|
||||
for (size_t i = 0; i < ranks.size(); ++i) {
|
||||
|
||||
@@ -46,8 +46,9 @@ namespace rad {
|
||||
class TierExec {
|
||||
public:
|
||||
~TierExec();
|
||||
/* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the
|
||||
* order of the entry's `blocks` vector. The staging layout is derived from them here only.
|
||||
/* `groups` is PrefixCache::entry_groups(): the group of each block an entry holds, in the
|
||||
* order of the entry's `blocks` vector (a group with blocks shorter than the entry is listed
|
||||
* once per block). The staging layout is derived from them here only.
|
||||
* `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and
|
||||
* `max_chain` the longest restore chain; the index buffers are sized from the last two. */
|
||||
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
|
||||
|
||||
+37
-15
@@ -391,7 +391,10 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
* by a repetition count (upstream's cap of 2000 rejects ordinary schemas such as
|
||||
* `maxLength: 8000`). It is linear in the count, and nothing after the parse is worse than
|
||||
* linear in the rules; the mask plan gives every link past the longest token one class. So
|
||||
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`. */
|
||||
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`.
|
||||
*
|
||||
* S'(x) depends only on S and x, so the links are shared: every bounded repetition of the same
|
||||
* operand points into one chain (rep_links_), and S{0,2000} after S{0,4000} builds nothing. */
|
||||
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
|
||||
const bool no_max = max_times == UINT64_MAX;
|
||||
if (last_sym_start == rule.size())
|
||||
@@ -407,17 +410,30 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
|
||||
/* A refusal names the repetition the client wrote. */
|
||||
try {
|
||||
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
|
||||
|
||||
/* A bounded repetition's chain of links for this operand, shared with every earlier
|
||||
* bounded repetition of it; only the links it lacks are built. */
|
||||
std::vector<uint32_t>* links = nullptr;
|
||||
uint64_t n_new = n_opt;
|
||||
if (!no_max && n_opt > 0) {
|
||||
std::vector<std::pair<uint32_t, uint32_t>> key;
|
||||
key.reserve(prev_rule.size());
|
||||
for (const auto& e : prev_rule) key.emplace_back((uint32_t)e.type, e.value);
|
||||
links = &rep_links_[std::move(key)];
|
||||
n_new = n_opt > links->size() ? n_opt - links->size() : 0;
|
||||
}
|
||||
|
||||
/* Charge the copies up front: the operand once per required count beyond the first,
|
||||
* and once per optional rule plus its reference, ALT and END. Counts reach 2^64 - 2,
|
||||
* so overflow saturates and is refused before the loops run. Each generated rule's
|
||||
* name and slot are charged again in generate_symbol_id. */
|
||||
* and once per optional rule built plus its reference, ALT and END. Counts reach
|
||||
* 2^64 - 2, so overflow saturates and is refused before the loops run. Each generated
|
||||
* rule's name and slot are charged again in generate_symbol_id. */
|
||||
{
|
||||
const uint64_t w = prev_rule.size();
|
||||
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
|
||||
uint64_t req = 0, opt = 0, copies = 0, bytes = 0;
|
||||
const bool wraps =
|
||||
__builtin_mul_overflow(min_times > 1 ? min_times - 1 : 0, w, &req) ||
|
||||
__builtin_mul_overflow(n_rest, w + 3, &opt) ||
|
||||
__builtin_mul_overflow(n_new, w + 3, &opt) ||
|
||||
__builtin_add_overflow(req, opt, &copies) ||
|
||||
__builtin_mul_overflow(copies, (uint64_t)sizeof(GbnfElement), &bytes);
|
||||
charge(wraps ? UINT64_MAX : bytes);
|
||||
@@ -430,21 +446,26 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
|
||||
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
|
||||
}
|
||||
|
||||
uint32_t last_rec_rule_id = 0;
|
||||
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
|
||||
|
||||
GbnfRule rec_rule(prev_rule);
|
||||
for (uint64_t i = 0; i < n_opt; i++) {
|
||||
rec_rule.resize(prev_rule.size());
|
||||
if (no_max) {
|
||||
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
|
||||
if (i > 0 || no_max)
|
||||
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
|
||||
rec_rule.push_back({ GRE_RULE_REF, rec_rule_id });
|
||||
rec_rule.push_back({ GRE_ALT, 0 });
|
||||
rec_rule.push_back({ GRE_END, 0 });
|
||||
add_rule(rec_rule_id, rec_rule);
|
||||
last_rec_rule_id = rec_rule_id;
|
||||
rule.push_back({ GRE_RULE_REF, rec_rule_id });
|
||||
} else if (n_opt > 0) {
|
||||
while (links->size() < n_opt) {
|
||||
rec_rule.resize(prev_rule.size());
|
||||
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
|
||||
if (!links->empty()) rec_rule.push_back({ GRE_RULE_REF, links->back() });
|
||||
rec_rule.push_back({ GRE_ALT, 0 });
|
||||
rec_rule.push_back({ GRE_END, 0 });
|
||||
add_rule(rec_rule_id, rec_rule);
|
||||
links->push_back(rec_rule_id);
|
||||
}
|
||||
rule.push_back({ GRE_RULE_REF, (*links)[n_opt - 1] });
|
||||
}
|
||||
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
|
||||
} catch (const std::runtime_error& ex) {
|
||||
throw std::runtime_error("the repetition {" + std::to_string(min_times) + "," +
|
||||
(no_max ? std::string() : std::to_string(max_times)) + "}: " +
|
||||
@@ -580,6 +601,7 @@ const char* GbnfParser::parse_rule(const char* src) {
|
||||
int GbnfParser::parse(const char* src, std::string* err) {
|
||||
if (!src) return RAD_E_INVAL;
|
||||
budget_used_ = 0;
|
||||
rep_links_.clear();
|
||||
depth_ = 0;
|
||||
try {
|
||||
const char* pos = parse_space(src, true);
|
||||
|
||||
@@ -146,6 +146,13 @@ private:
|
||||
uint32_t depth_ = 0;
|
||||
void charge(uint64_t bytes);
|
||||
|
||||
/* The optional links of bounded repetitions, keyed by the repeated operand's elements:
|
||||
* links[k - 1] is S'(k) ::= S S'(k-1) |, so every S{m,n} over the same S shares one chain and
|
||||
* builds only the links past the longest it has (handle_repetitions). A JSON schema's
|
||||
* `maxLength` bounds all repeat `char`, so a schema with many of them costs its longest bound
|
||||
* once instead of the sum of them. */
|
||||
std::map<std::vector<std::pair<uint32_t, uint32_t>>, std::vector<uint32_t>> rep_links_;
|
||||
|
||||
uint32_t get_symbol_id(const char* src, size_t len);
|
||||
uint32_t generate_symbol_id(const std::string& base);
|
||||
void add_rule(uint32_t id, const GbnfRule& rule);
|
||||
|
||||
+43
-2
@@ -143,15 +143,49 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* checkpoints land wherever a step ends (§7.3). */
|
||||
g.min_max_tok = g.quantum;
|
||||
|
||||
*out = g;
|
||||
|
||||
if (cfg.max_tok < g.min_max_tok) {
|
||||
*out = g;
|
||||
RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least "
|
||||
"%lld, so a chunk can end on a linear-state boundary: %s",
|
||||
(long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* 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
|
||||
* interval costs only retention. */
|
||||
const int64_t I0 = g.checkpoint_interval;
|
||||
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
|
||||
const int64_t budget_chunk = cfg.max_tok / g.quantum * g.quantum;
|
||||
g.exact = cfg.prefix_exact && cfg.prefix_cache;
|
||||
if (g.exact && splits && I0 > budget_chunk && I0 % budget_chunk != 0) {
|
||||
g.checkpoint_interval = align_up(I0, budget_chunk);
|
||||
RAD_WARN("--checkpoint-interval %lld resolves to %lld: --prefix-resume exact needs it a "
|
||||
"multiple of the %lld-token prefill chunk (--max-num-batched-tokens %lld) so "
|
||||
"every checkpoint is where a cold prefill's chunk ends; give a multiple of %lld, "
|
||||
"or --prefix-resume nearest to keep %lld", (long long)cfg.checkpoint_interval,
|
||||
(long long)g.checkpoint_interval, (long long)budget_chunk, (long long)cfg.max_tok,
|
||||
(long long)budget_chunk, (long long)I0);
|
||||
}
|
||||
if (g.exact) {
|
||||
const int64_t I = g.checkpoint_interval;
|
||||
if (splits && I <= budget_chunk) {
|
||||
const int64_t h = g.span > 1 ? std::max<int64_t>(1, std::min(g.span, cfg.max_tok / I))
|
||||
: 1;
|
||||
g.grid = h * I;
|
||||
g.grid_origin = h > 1 ? I : 0;
|
||||
} else {
|
||||
g.grid = budget_chunk;
|
||||
g.grid_origin = 0;
|
||||
}
|
||||
}
|
||||
|
||||
*out = g;
|
||||
|
||||
/* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
|
||||
* when the interval is below --max-num-batched-tokens, raising the budget does not change the
|
||||
* chunk; the log line makes that visible. tip-only window snapshots do not
|
||||
@@ -167,6 +201,13 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
eff >= cfg.max_tok ? ""
|
||||
: g.span > 1 ? " (the checkpoint interval times the span, not the budget)"
|
||||
: " (the checkpoint interval, not the budget)");
|
||||
if (g.exact)
|
||||
RAD_INFO("prefix resume: exact -- a hit resumes only where an idle server's cold prefill "
|
||||
"of the same prompt starts a chunk (every %lld tokens%s) and a prompt's tail "
|
||||
"snapshot is taken where its last chunk starts, so the hit recomputes the cold "
|
||||
"run's own chunks and answers bit-identically; a turn re-prefills up to one chunk "
|
||||
"more than --prefix-resume nearest", (long long)g.grid,
|
||||
g.grid_origin > 0 ? fmt(" from %lld", (long long)g.grid_origin).c_str() : "");
|
||||
if (cfg.prefill_span > 1) {
|
||||
/* What the span does here, said once: the intervals the budget holds can be fewer than
|
||||
* the flag asks for, and a model without an interval grid spans nothing. */
|
||||
|
||||
@@ -60,7 +60,29 @@ struct ChunkGeometry {
|
||||
* tip-only, which keeps the tail alone and so splits no chunk at the interval. */
|
||||
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. */
|
||||
bool exact = false;
|
||||
int64_t grid = 0;
|
||||
int64_t grid_origin = 0;
|
||||
|
||||
bool checkpoints() const { return checkpoint_interval > 0; }
|
||||
|
||||
/* The deepest grid position at or below `pos`; `pos` itself when not exact. */
|
||||
int64_t grid_floor(int64_t pos) const {
|
||||
if (pos <= 0) return 0;
|
||||
if (!exact || grid <= 0) return pos;
|
||||
if (pos < grid_origin) return 0;
|
||||
return grid_origin + (pos - grid_origin) / grid * grid;
|
||||
}
|
||||
bool on_grid(int64_t pos) const { return grid_floor(pos) == pos; }
|
||||
};
|
||||
|
||||
/* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration
|
||||
|
||||
@@ -172,7 +172,7 @@ 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. `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;
|
||||
@@ -187,10 +187,12 @@ struct IPrefixCache {
|
||||
/* Release the least recently used entries and their KV references. The scheduler tries this
|
||||
* before preempting a running request. */
|
||||
virtual int64_t evict(int64_t n_entries) = 0;
|
||||
/* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike
|
||||
/* Free up to `n_entries` for the reserve without losing anything a later turn needs. Unlike
|
||||
* evict(), it skips entries a live sequence still holds (no block would be freed) and entries
|
||||
* whose only copy is in VRAM. Returns the number of blocks freed. */
|
||||
virtual int64_t trim(int64_t n_blocks) = 0;
|
||||
* whose only copy is in VRAM. An entry is one block in each cached group, or more in a group
|
||||
* whose blocks are shorter than the entry (PrefixCache::blocks_per_entry). Returns the number
|
||||
* of entries freed. */
|
||||
virtual int64_t trim(int64_t n_entries) = 0;
|
||||
|
||||
/* Drop every entry in every tier. Implementations with idle tiers must override this: there,
|
||||
* evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */
|
||||
|
||||
+96
-19
@@ -10,6 +10,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <numeric>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -97,9 +98,9 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
if (kv->block_tokens((int32_t)i) <= 0) continue;
|
||||
++n_paged;
|
||||
const auto& cg = pc->cached_groups();
|
||||
/* Snapshots are taken only where the trunk has a window to snapshot too
|
||||
* (ChunkGeometry::window_ckpt); without them no drafter window rides in one. */
|
||||
if (cfg.prefix_cache && geo_.window_ckpt && kv->window_snapshot((int32_t)i) &&
|
||||
/* Snapshots are taken only on a checkpoint grid (ChunkGeometry::checkpoints()), the
|
||||
* window's alone or beside linear state; without one no window rides in a slot. */
|
||||
if (cfg.prefix_cache && geo_.checkpoints() && kv->window_snapshot((int32_t)i) &&
|
||||
std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end())
|
||||
++n_snap;
|
||||
}
|
||||
@@ -110,19 +111,27 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
}
|
||||
/* The trunk's share: a paged group a trunk layer reads (a bound layer below the trunk's layer
|
||||
* count; a drafter borrows from base_layer up) that the cache does not index. Recomputing the
|
||||
* tail cannot repair that hole; see scheduler.h. */
|
||||
* tail cannot repair that hole; see scheduler.h. A windowed group is restored by a hit that
|
||||
* resumes at a window snapshot (a checkpoint slot carries the trunk's window, with or without
|
||||
* linear state beside it); any other such group refuses every hit. */
|
||||
hit_holes_trunk_ = false;
|
||||
hit_needs_window_ = false;
|
||||
for (size_t i = 0; i < prog.kv_groups.size(); ++i) {
|
||||
if (kv->block_tokens((int32_t)i) <= 0) continue;
|
||||
bool trunk = false;
|
||||
for (int l : prog.kv_groups[i].layers) if (l < prog.meta.n_layers) { trunk = true; break; }
|
||||
if (!trunk) continue;
|
||||
const std::vector<int32_t>& cg = pc->cached_groups();
|
||||
if (std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) { hit_holes_trunk_ = true; break; }
|
||||
if (std::find(cg.begin(), cg.end(), (int32_t)i) != cg.end()) continue;
|
||||
if (prog.kv_groups[i].decl.kind == RAD_KV_WINDOW) hit_needs_window_ = true;
|
||||
else hit_holes_trunk_ = true;
|
||||
}
|
||||
if (hit_holes_trunk_ && cfg.prefix_cache)
|
||||
RAD_INFO("prefix cache: a trunk layer's paged group is neither prefix-cached nor carried "
|
||||
"by a checkpoint slot -- a hit re-prefills");
|
||||
else if (hit_needs_window_ && cfg.prefix_cache)
|
||||
RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit "
|
||||
"resumes from a window snapshot (a checkpoint slot) or re-prefills");
|
||||
"resumes from a window snapshot (a checkpoint slot)");
|
||||
if (cfg.prefill_interleave > 0)
|
||||
RAD_INFO("scheduler: --prefill-interleave %lld: after a prefill chunk that leaves its "
|
||||
"prompt unfinished while other sequences decode, the next %lld steps carry "
|
||||
@@ -470,14 +479,26 @@ void Scheduler::trim_prefix_cache() {
|
||||
if (!pc_ || !cfg_.prefix_cache) return;
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
if (cg.empty()) return;
|
||||
const int32_t g = cg[0];
|
||||
const int64_t total = kv_->total_blocks(g);
|
||||
if (total <= 0) return;
|
||||
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
|
||||
/* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded by
|
||||
* the live mark, so a pool that returned its unused top would read as nearly full and the
|
||||
* trim would drain the cache for room the pool can grow back into. */
|
||||
const int64_t short_by = reserve - (total - kv_->held_blocks(g));
|
||||
/* 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. */
|
||||
int64_t entry = 0;
|
||||
for (int32_t g : cg) {
|
||||
const int64_t bs = kvgeom_.g[(size_t)g].block_size;
|
||||
if (bs > 0) entry = entry > 0 ? std::lcm(entry, bs) : bs;
|
||||
}
|
||||
int64_t short_by = 0;
|
||||
for (int32_t g : cg) {
|
||||
const int64_t total = kv_->total_blocks(g), bs = kvgeom_.g[(size_t)g].block_size;
|
||||
if (total <= 0 || bs <= 0) continue;
|
||||
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
|
||||
/* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded
|
||||
* by the live mark, so a pool that returned its unused top would read as nearly full and
|
||||
* the trim would drain the cache for room the pool can grow back into. */
|
||||
const int64_t blocks = reserve - (total - kv_->held_blocks(g));
|
||||
const int64_t per = std::max<int64_t>(entry / bs, 1);
|
||||
if (blocks > 0) short_by = std::max(short_by, (blocks + per - 1) / per);
|
||||
}
|
||||
if (short_by > 0) (void)pc_->trim(short_by);
|
||||
}
|
||||
|
||||
@@ -850,7 +871,38 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
|
||||
int64_t want = remaining < budget ? remaining : budget;
|
||||
|
||||
if (geo_.checkpoints()) {
|
||||
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. */
|
||||
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;
|
||||
int64_t far = next;
|
||||
if (geo_.span > 1 && span_now_ && n_computed >= I && n_computed % I == 0)
|
||||
far = n_computed + geo_.span * I;
|
||||
if (n_computed + want > far)
|
||||
want = far - n_computed;
|
||||
else if (n_computed + want > next && n_computed + want < n_target)
|
||||
want = (n_computed + want) / I * I - n_computed;
|
||||
const int64_t tail = tail_checkpoint(n_target);
|
||||
if (tail > n_computed && n_computed + want >= tail) {
|
||||
want = tail - n_computed;
|
||||
if (checkpoint_pos) *checkpoint_pos = tail;
|
||||
} 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. */
|
||||
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()) {
|
||||
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) {
|
||||
@@ -934,6 +986,16 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
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. */
|
||||
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
|
||||
@@ -1136,6 +1198,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
if (reuse > last) reuse = last;
|
||||
if (reuse < 0) reuse = 0;
|
||||
|
||||
/* --prefix-resume exact: resume only on the grid an idle cold prefill chunks this prompt
|
||||
* on (ChunkGeometry::grid), so the tokens recomputed below are cut into the cold run's own
|
||||
* chunks. A snapshot is already on it (plan_chunk writes none off it, but for a request's
|
||||
* own Request::checkpoint_at); a hit at a block (no snapshot needed) steps back to it. */
|
||||
if (geo_.exact && reuse > 0 &&
|
||||
!(geo_.checkpoints() && h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens)) {
|
||||
const int32_t g = (int32_t)geo_.grid_floor(reuse);
|
||||
if (g < reuse)
|
||||
RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at %lld, on the "
|
||||
"%lld-token chunk grid (--prefix-resume exact)", (unsigned long long)r.id,
|
||||
(long long)reuse, (long long)g, (long long)geo_.grid);
|
||||
reuse = g;
|
||||
}
|
||||
|
||||
/* A hit on a hybrid model needs a checkpoint. The adopted blocks cover the paged
|
||||
* attention groups, but nothing covers a recurrent group, whose state lives in a
|
||||
* per-sequence slot; skipping tokens also requires restoring that state (`ckpt_src`,
|
||||
@@ -1158,9 +1234,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
(unsigned long long)r.id, (long long)h.n_attn_tokens, (long long)reuse);
|
||||
}
|
||||
/* A window snapshot covers the trunk's windowed groups at the checkpoint only. The lookup
|
||||
* clamped the hit to it (a window counts as state there), so a hit with a slot is exactly
|
||||
* at a snapshot; one without is no hit. */
|
||||
const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 &&
|
||||
* clamped the hit to it (a window counts as state there, and linear state beside it
|
||||
* resumes there too), so a hit with a slot is exactly at a snapshot; one without is no
|
||||
* hit. */
|
||||
const bool win_hit = geo_.checkpoints() && kv_->has_window_snapshot() && reuse > 0 &&
|
||||
h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens;
|
||||
|
||||
/* Windowed-group clamp: the trunk's own KV includes a paged group the cache does not
|
||||
@@ -1173,7 +1250,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
*
|
||||
* 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. */
|
||||
if (reuse > 0 && hit_holes_trunk_ && !win_hit) {
|
||||
if (reuse > 0 && (hit_holes_trunk_ || (hit_needs_window_ && !win_hit))) {
|
||||
reuse = 0;
|
||||
s.hit_cut = SchedReq::HitCut::Window;
|
||||
RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not "
|
||||
|
||||
@@ -491,12 +491,16 @@ private:
|
||||
* place. */
|
||||
bool hit_holes_draft_ = true;
|
||||
/* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
|
||||
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
|
||||
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
|
||||
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index and
|
||||
* no checkpoint slot carries? Unlike a drafter hole, recomputing the tail cannot repair it;
|
||||
* every hit is refused (admit_one). */
|
||||
bool hit_holes_trunk_ = false;
|
||||
/* The end-of-generation ids, sorted and unique (set_eog), and a lookup in them. */
|
||||
std::vector<int32_t> eog_;
|
||||
bool is_eog(int32_t id) const;
|
||||
/* A windowed trunk group, which the cache does not index: a hit stands only where it resumes
|
||||
* at a window snapshot (IKVManager::has_window_snapshot), which restores the window. */
|
||||
bool hit_needs_window_ = false;
|
||||
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
|
||||
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
|
||||
* not declare one, in which case admission and commit are exactly as before. A sequence with
|
||||
|
||||
+19
-1
@@ -38,7 +38,8 @@
|
||||
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
|
||||
* `upscale_refine_steps` (the model's default when absent; abi/rad_builder.h, RadVideoGenDecl).
|
||||
* The video object of an upscaled video says how it was made: the factor, the refine steps and the
|
||||
* small size (`upscale_from`).
|
||||
* small size (`upscale_from`). Keyframes ride it: each is prepared at both sizes and pinned at the
|
||||
* one the steps run at.
|
||||
*
|
||||
* The prompt is the model's template with `{prompt}` filled; the template is tokenised with its
|
||||
* special tokens and the prompt without, so a caller cannot write control tokens into it.
|
||||
@@ -742,6 +743,23 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
&canvas[i], &why) < 0)
|
||||
return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why);
|
||||
pixels(m, { canvas[i] });
|
||||
/* A latent upscale's first steps pin it at their own size, prepared the same way. */
|
||||
if (r->upscale > 1.0) {
|
||||
RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */
|
||||
geo.size_multiple = info.size_multiple;
|
||||
int32_t sw = 0, sh = 0;
|
||||
gen::video_small_size(geo, r->width, r->height, r->upscale, &sw, &sh);
|
||||
mm::Frame small;
|
||||
if (deps_.mm->encoder_image_canvas((const uint8_t*)m.data.data(), m.data.size(),
|
||||
sw, sh,
|
||||
m.kind == gen::VideoRefMedia::LAST_FRAME ||
|
||||
first_center,
|
||||
&small, &why) < 0)
|
||||
return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why);
|
||||
m.small_h = small.h;
|
||||
m.small_w = small.w;
|
||||
m.small_pixels.assign(small.rgb.begin(), small.rgb.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -320,6 +320,12 @@ int parse_tokenizer_json(const char* path, VocabBuild& out);
|
||||
/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
|
||||
int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
|
||||
|
||||
/* Read a standalone chat template file into out.chat_template, trailing newlines stripped.
|
||||
* A release that ships no template (DeepSeek's does not) needs one from elsewhere; the caller
|
||||
* passes the file. An unreadable or empty file is an error, never a silent skip. Returns
|
||||
* RAD_OK, or RAD_E_IO when the file cannot be read. */
|
||||
int read_chat_template_path(const char* path, VocabBuild& out);
|
||||
|
||||
/* Build a VocabBuild from a GGUF's tokenizer.ggml.* metadata.
|
||||
*
|
||||
* GGUF has no declared chain, only `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
|
||||
|
||||
@@ -638,6 +638,27 @@ void read_config(const std::string& dir, VocabBuild& out) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int read_chat_template_path(const char* path, VocabBuild& out) {
|
||||
if (!path) return RAD_E_INVAL;
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
RAD_ERR("tokenizer: cannot read chat template %s", path);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
std::ostringstream ss;
|
||||
ss << f.rdbuf();
|
||||
std::string t = ss.str();
|
||||
while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back();
|
||||
if (t.empty()) {
|
||||
RAD_ERR("tokenizer: chat template %s is empty", path);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
RAD_INFO("tokenizer: chat template from %s (%zu bytes), overriding the checkpoint's",
|
||||
path, t.size());
|
||||
out.chat_template = std::move(t);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== parse_tokenizer_json */
|
||||
|
||||
namespace {
|
||||
|
||||
Reference in new issue
Block a user