radiance 1.17.0

IQR-V4 for Qwen3.8-27B:
- 15 recipes, data/recipes/q38-27b-iq2r-v4 .. q38-27b-iq8r-v4 (2.5 to 8 bits a weight), docs/IQR.md
  "IQR-V4". On the quantisation board's private split every entry has 2-19% less KL than its V3 twin
  of the same size (10-19% from 2.5 to 5.4 bits); IQ4R-L-V4 is 24% below the official FP8 checkpoint
  at 55% of its size, and IQ2R-L-V4 (2.8 bpw) is below the MXFP4 checkpoint. Containers with the
  DFlash2 drafter and the vision tower: huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4, served by
  deploy/compose/qwen3.8-27b-iqr-v4.yaml (IQR_V4 names the size)
- GPTQ runs in act order inside the column trellis (tcq_order=1); the head-fed projections
  (attn_output, ssm_out) take a bf16 scale a (row, 128) block from five bits up; widths from
  measured prices
- A vocabulary-weighted lm_head: four width classes of the computed trellis (output.k<B>), the
  tokens carrying the probability on the widest, decoded in one launch by logits_gemm_vocab with
  16-bit head activations; 0.62 ms at one token on a TP2 rank against the int8 head's 1.02 ms.
  tools/vhead.py and data/vhead/ build the class split from the bf16 checkpoint; libquant reads the
  head's input Hessian for every class
- At IQ6R-L and up, the int8 lm_head is GPTQ'd against its input Hessian (same bytes, median KL
  -8..-12%)
- embed_lookup_iqr takes u7/u8 tables under a zero point and the 4096-state trellis at 6 and 7 bits
- The whitepaper: radiance.stilldeadco.de/whitepapers/iqr-v4.pdf

Faster IQR kernels:
- The one-token GEMV gives each 16-row weight tile a block whose waves split K (5120 x 6144 at one
  token 42.3 -> 30.0 us), with a biased-int fold, a v_perm activation broadcast and one code stream
  a column
- A 16-token WMMA tile without block barriers serves 2 to 16 tokens (6- and 7-bit codes from one
  token): a 4-bit weight takes 0.52-0.66 of FP8's time from one token to sixteen, 1.15-1.74x V3's
  kernels from four tokens up
- The activation quantisers after the IQR gate_up (gemm_iqr_gated), the delta net's decode conv
  fold (gdn_conv_recurrent_update_had) and the attention gate (gate_had_quant_i8g) are folded into
  their producers, byte for byte the same codes: 128 fewer launches a decode step
- End to end on one R9700 (TP1, no speculation): IQ4R-S-V4 decodes one stream in 24.7 ms against
  the MXFP4 checkpoint's 25.8 at five times lower KL; IQ3R-S-V4 is faster than MXFP4 at 1 to 8
  streams. Prefill stays 8-9% behind MXFP4's 4-bit tile

Quantisation tooling:
- rescale=1 refits each row's scale to its codes after GPTQ; gptqsim measures a tensor's W16A16
  form (tcq_code=mad16); an int8 trunk's calibration Grams can be recorded from the codes its GEMMs
  read (--calib-dir, TP1)
- Fixed: the GPU trellis packs tcq_code=mad16's values two int16 a register

New models (merged):
- Spark 2.5 (spark25: bf16 and rotated-int8 IQ8R checkpoints, tensor parallelism with exact
  collectives, reasoning and tagged tool calls) with its DSpark drafter (exact attention and Markov
  walk ops), docs/SPARK25-IQ8R.md (@gostar)
- Ling-3.0-flash (bailing_hybrid: KDA, dense latent attention with mla_attn_paged, group-limited
  sigmoid routing, the clipped SwiGLU and its MTP layer as a serial drafter), its w4a8 recipes and
  compose files for four and two cards (@keptn42)
- Gemma 4 12B (gemma4_unified, served by the gemma4 plugins): its picture and audio embedders, a
  picture's placeholders read both ways on the sliding layers as the model was trained (the
  scheduler ends no prefill chunk inside such a run; RadBatch::n_bidi), windowed attention at
  head_dim 512, the assistant head as MTP drafter at one, two and four ranks, suppress_tokens from
  generation_config, bf16 and i8g compose files (@keptn42)

Merged:
- The prefill KV split sized by the live KV length rather than the model's max_ctx, recorded passes
  keyed by their split geometry, and --gpu-memory-mib, the inverse of --gpu-headroom-mib (@gostar)
- Possessive quantifiers in tokenizer patterns where the greedy reading provably matches the same
  (Ling-3.0's), and the Grafana dashboard's first screen of totals (@keptn42)
- The dashboard's history line (decode, prefill and TTFT over finished requests, kept in the
  browser, JSON export), session extremes that age and reset on a restart, card-count changes, an
  Advanced tab for the poll intervals, each request's prefill time from admission in /stats
  (prefill_s), and the page's JavaScript run by tests/js (@Memoria)
- From PR #390: the file tier reads a routed layer with its own router's counts and waits for its
  deposits; the stop-string hold-back keeps back only a tail that can still become a stop string
  (before, every delta waited up to the longest stop's length); the sampler's planes are sized by
  the step's token bound, the n-gram ban runs beside a drafter, and a top-1 row issues no candidate
  cut (@Code000)
- The n-gram reader refills its reads as they land, and a decode gather waits on the other rank's
  read of a row instead of reading it again (#369, @pokesjw)
- libr3d's GEMM structs value-initialised so the tape audit sees no padding (@RikshaDriver)

Added:
- --ngram-placement disk=DIR: the n-gram table read from its own file, DIR/ngram-<id>.bin, filled
  from the container at the first start, on a faster or separate drive (#130)

Fixed:
- input_reference's H.264 round trip runs on libopenh264, which the image carries, at a quantiser
  held at the crf (a side under 16 padded and cut back); a build with no H.264 encoder answers 501
  (#163)
- kvtier: at most 1024 session rows under one shared first block; with one shared prompt the list
  grew a row a request and prefill fell from 9k to 2.5k tok/s after 500K requests (#375)
- Speculative steps on an architecture with no pass-key callback keep their recorded passes under
  the live-KV prefill split

Plugin ABI 35:
- RadArgs::kv_used_max_h and wgp_count, RadBatch::kv_used_max_h and positions_h, the optional
  rad_arch_pass_key export and RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT; RadEncoderDecl::bidirectional
  and RadBatch's n_bidi runs. The layout fingerprint table is regenerated; out-of-tree plugins
  rebuild against 35

Thanks to @gostar, @keptn42, @Memoria, @Code000, @pokesjw and @RikshaDriver.
This commit is contained in:
Deadcode committed 2026-11-04 18:56:58 +01:00
1 parent 3af8065cc6
commit 19d4e8fe0e
102 files changed
+9794 -692

No files matched your search

+17 -4
View File
@@ -645,7 +645,7 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
std::string share_dir;
std::string share_dir, disk_dir;
if (!emb && !std::strncmp(v, "ram=", 4)) {
share_dir = v + 4;
if (share_dir.empty()) {
@@ -654,11 +654,23 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
p = TablePlacement::Ram;
} else if (!emb && !std::strncmp(v, "disk=", 5)) {
disk_dir = v + 5;
if (disk_dir.empty()) {
RAD_ERR("--ngram-placement disk= needs a directory: disk=DIR, where the table "
"is read from its own file");
return RAD_E_INVAL;
}
p = TablePlacement::Disk;
} else if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram, ram=DIR or disk, not '%s'", a.c_str(), v);
RAD_ERR("%s takes auto, vram, ram, ram=DIR, disk or disk=DIR, not '%s'", a.c_str(),
v);
return RAD_E_INVAL;
}
if (!emb) c->ngram_share_dir = share_dir;
if (!emb) {
c->ngram_share_dir = share_dir;
c->ngram_disk_dir = disk_dir;
}
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
@@ -1354,7 +1366,8 @@ const ShowRow kShow[] = {
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) {
std::string v = table_placement_name(c.ngram_placement);
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } },
const std::string& dir = c.ngram_share_dir.empty() ? c.ngram_disk_dir : c.ngram_share_dir;
return dir.empty() ? v : v + "=" + dir; } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-mib", [](const Config& c) {
+13 -3
View File
@@ -42,6 +42,7 @@
#include <utility>
#include <vector>
#include <thread>
#include <sys/mman.h>
#include <unistd.h>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
@@ -318,6 +319,8 @@ Engine::~Engine() {
ranks_.clear();
for (TableCopy& c : table_copies_) table_copy_free(&c);
table_copies_.clear();
for (TableCopy& c : table_files_) ::munmap(c.base, c.bytes);
table_files_.clear();
for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED);
card_copies_.clear();
for (TableShare& t : table_shares_) table_share_close(&t);
@@ -374,6 +377,10 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
}
sc.max_seqs = cfg_.max_seqs;
sc.max_spec = cfg_.n_spec;
/* The real step bound, not the sizing declare's level: the sampler's planes must be the same
* buffers in every declare of the program (plan_level compares them), and a step can sample
* no more rows than the real bound lets it carry tokens. */
sc.max_tok = cfg_.max_tok;
sc.rank = rank;
sc.world_size = cfg_.tp;
sc.draft_coupling = cfg_.draft_coupling;
@@ -381,11 +388,14 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
/* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
* same chain against its own buffer. PERSIST, since the step loop copies it back after the
* step, when a transient's storage may belong to another buffer. */
* step, when a transient's storage may belong to another buffer. One id per sampler row,
* capped as the rows are (SamplerConfig::max_tok). */
RadBufDecl d{};
d.dtype = RAD_I32;
d.rank = 1;
d.shape[0] = cfg_.max_seqs * (cfg_.n_spec > 0 ? cfg_.n_spec + 1 : 1);
if (cfg_.max_tok > 0)
d.shape[0] = std::min<int64_t>(d.shape[0], std::max<int64_t>(cfg_.max_tok, cfg_.max_seqs));
d.kind = RAD_BUF_PERSIST;
tok = rad_decl_buffer(b, "sampler.tokens", &d);
return tok ? RAD_OK : RAD_E_STATE;
@@ -3482,8 +3492,8 @@ int Engine::run_server() {
in.decoder_max_area = pg.vgen_str.decoder_max_area;
if (in.image_cond && in.image_crf > 0 && !mm::h264_roundtrip_available())
RAD_WARN("video: '%s' prepares a first frame with an H.264 round trip at crf %d, which "
"needs libx264; this build's libavcodec has none, so input_reference is "
"refused", in.name.c_str(), (int)in.image_crf);
"needs an H.264 encoder and decoder; this build's libavcodec lacks one, so "
"input_reference is refused", in.name.c_str(), (int)in.image_crf);
in.max_lanes = vd.max_lanes;
in.max_ref_images = vd.max_ref_images;
in.max_ref_videos = vd.max_ref_videos;
+5
View File
@@ -255,6 +255,11 @@ private:
* copies are freed, because the holder that leaves last deletes the file. */
std::vector<TableShare> table_shares_;
std::vector<std::pair<const void*, void*>> table_copy_of_;
/* --ngram-placement disk=DIR: the table's own file, mapped read-only in place of the
* container's range (table_file_map); unmapped in ~Engine. */
std::vector<TableCopy> table_files_;
std::vector<const void*> table_file_src_; /* the container address each of table_files_ replaces */
int table_file_map(const uint8_t* src, int64_t n, int64_t foff, void** out, std::string* why);
/* --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_;
+58 -4
View File
@@ -482,6 +482,35 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
return RAD_OK;
}
/* --ngram-placement disk=DIR: the container's [src, src + n) at file offset `foff` read from its own
* file, DIR/ngram-<id>.bin (the table's bytes and nothing else, the id table_share_id's: the
* container's path, size and mtime and the table's place in it). The first start fills it from the
* container through a temporary name and renames it, so a file under the real name is complete; a
* later start checks samples of it against the container. Mapped read-only in place of the
* container's range, which is all the disk gather needs: it finds the file behind the mapping and
* reads it directly (libavx avx_ngram.cpp, table_file). */
int Engine::table_file_map(const uint8_t* src, int64_t n, int64_t foff, void** out,
std::string* why) {
const auto t0 = std::chrono::steady_clock::now();
const std::string id = table_share_id(file_->path(), foff, n);
if (id.empty()) {
*why = fmt("the container %s cannot be stat'ed, which names the table's file", file_->path());
return RAD_E_IO;
}
const std::string& dir = cfg_.ngram_disk_dir;
const std::string path = dir + (dir.back() == '/' ? "" : "/") + "ngram-" + id + ".bin";
TableCopy c;
bool filled = false;
const int rc = table_file_open(*file_, src, n, foff, path, &c, &filled, why);
if (rc != RAD_OK) return rc;
table_files_.push_back(c);
RAD_INFO("placement: n-gram table read from %s (%s%s, %.1f s)", path.c_str(), humanb(n).c_str(),
filled ? ", filled from the container" : "",
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
*out = c.base;
return RAD_OK;
}
/* When --ngram-placement auto chose a pinned copy for a card and it could not be made, move the
* gather to the host. Every rank's n-gram weights take the host site, in both the WeightInfo
* Ctx::init reads and the plan, so the gather and its scale move together; a copy already
@@ -3056,6 +3085,26 @@ int Engine::load_weights() {
"rows are read from the container%s", into, why.c_str(),
card ? " by the host gather" : ""));
}
/* --ngram-placement disk=DIR: the table's own file instead of the container. */
if (cfg_.ngram_resolved == TablePlacement::Disk && !cfg_.ngram_disk_dir.empty() &&
is_ngram_table(r->program, (rad_weight)i) && n >= kTableShareMin) {
void* m = nullptr;
for (size_t k = 0; k < table_files_.size() && !m; ++k)
if (table_file_src_[k] == w.host_ptr) m = table_files_[k].base;
std::string why;
if (!m) {
const int fs = table_file_map((const uint8_t*)w.ptr, n, (int64_t)p0.offset,
&m, &why);
if (fs != RAD_OK) {
RAD_ERR("--ngram-placement disk=%s: '%s': %s",
cfg_.ngram_disk_dir.c_str(), w.name.c_str(), why.c_str());
return fs;
}
table_file_src_.push_back(w.host_ptr);
}
w.ptr = m;
w.host_ptr = m;
}
/* No readahead on a mapped weight: a host kernel gathers a few rows from a table
* too large to be resident, so the default 128 KiB readahead would read 32 pages
* for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the
@@ -3913,10 +3962,15 @@ int Engine::start() {
},
&r->ctx));
if (r->fstager.enabled() && r->index == 0)
RAD_INFO("file stager: %zu routed layers hold experts read from the container; each "
"pass reads a layer's (up to %s) into one of two VRAM buffers before its "
"first expert op, so every step is paced by the drive",
r->fstager.n_layers(), humanb(r->plan.file_layer_max).c_str());
RAD_INFO("file stager: it covers %zu routed layers (a pool-cached unit of one may "
"be read from the container); each pass reads a layer's (up to %s) into one "
"of two VRAM buffers before its first expert op, so every step is paced by the drive%s",
r->fstager.n_layers(), humanb(r->plan.file_layer_max).c_str(),
r->fstager.whole_rows() > 0
? fmt("; a pass of %lld tokens or more reads its layers whole, each "
"while the card computes the one before",
(long long)r->fstager.whole_rows()).c_str()
: "");
if (r->stager.enabled() && r->fstager.enabled()) {
r->stagers.set(&r->stager, &r->fstager);
r->ctx.set_stager(&r->stagers);
+66
View File
@@ -3,7 +3,10 @@
#include "../rad_internal.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <atomic>
@@ -91,6 +94,69 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t
return RAD_OK;
}
int table_file_open(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
const std::string& path, TableCopy* out, bool* filled, std::string* why) {
if (!out || !filled || !why || !src || n <= 0 || path.empty()) return RAD_E_INVAL;
*out = TableCopy{};
*filled = false;
struct stat st;
if (::stat(path.c_str(), &st) != 0 || st.st_size != n) {
const std::string tmp = path + ".part";
const int fd = ::open(tmp.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
*why = fmt("creating %s: %s", tmp.c_str(), std::strerror(errno));
return RAD_E_IO;
}
void* m = MAP_FAILED;
if (::ftruncate(fd, (off_t)n) == 0)
m = ::mmap(nullptr, (size_t)n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) {
*why = fmt("sizing %s to %s: %s", tmp.c_str(), humanb(n).c_str(), std::strerror(errno));
::close(fd);
::unlink(tmp.c_str());
return RAD_E_IO;
}
int rc = table_copy_fill(file, src, n, foff, static_cast<uint8_t*>(m), why);
if (rc == RAD_OK && (::msync(m, (size_t)n, MS_SYNC) != 0 || ::fsync(fd) != 0)) {
*why = fmt("writing %s: %s", tmp.c_str(), std::strerror(errno));
rc = RAD_E_IO;
}
::munmap(m, (size_t)n);
::close(fd);
if (rc == RAD_OK && ::rename(tmp.c_str(), path.c_str()) != 0) {
*why = fmt("renaming %s: %s", tmp.c_str(), std::strerror(errno));
rc = RAD_E_IO;
}
if (rc != RAD_OK) {
::unlink(tmp.c_str());
return rc;
}
*filled = true;
}
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
*why = fmt("opening %s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
void* m = ::mmap(nullptr, (size_t)n, PROT_READ, MAP_SHARED, fd, 0);
::close(fd);
if (m == MAP_FAILED) {
*why = fmt("mapping %s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
if (!*filled) {
const int rc = table_copy_check(src, n, static_cast<const uint8_t*>(m), why);
if (rc != RAD_OK) {
::munmap(m, (size_t)n);
*why = fmt("%s does not match the container (%s); remove it and it is filled again",
path.c_str(), why->c_str());
return rc;
}
}
*out = TableCopy{ m, (size_t)n };
return RAD_OK;
}
void table_copy_free(TableCopy* c) {
if (!c || !c->base) return;
::munlock(c->base, c->bytes);
+8
View File
@@ -37,6 +37,14 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
* another process filled. */
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why);
/* --ngram-placement disk=DIR: [src, src + n) read from its own file `path` (the table's bytes and
* nothing else), mapped read-only in `out` (`bytes` = n). A missing file, or one of another size, is
* filled from the container under `path`.part and renamed, so a file under `path` is complete
* (`*filled` true); an existing one is checked as table_copy_check checks. The disk gather finds the
* file behind the mapping and reads it directly. Release with munmap(out->base, out->bytes). */
int table_file_open(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
const std::string& path, TableCopy* out, bool* filled, std::string* why);
/* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c);
+21 -2
View File
@@ -536,7 +536,10 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
static bool chain_extends(const std::vector<BlockHash>& shorter,
const std::vector<BlockHash>& longer) {
if (shorter.size() > longer.size()) return false;
for (size_t i = 0; i < shorter.size(); ++i) if (shorter[i] != longer[i]) return false;
/* Hashes are chained, so the last block decides; it is compared first, and a chain that
* diverges anywhere rejects in one compare. */
if (!shorter.empty() && shorter.back() != longer[shorter.size() - 1]) return false;
for (size_t i = 0; i + 1 < shorter.size(); ++i) if (shorter[i] != longer[i]) return false;
return true;
}
@@ -546,7 +549,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
std::lock_guard lk(mu_);
/* A session is a leaf of the prefix trie. Each turn arrives under a new request id, so the
* candidates are the sessions sharing this root (a handful at most):
* candidates are the sessions sharing this root (at most kRootSessions):
*
* - a chain this one extends is no longer a leaf and is absorbed;
* - a chain that extends this one means this is not a leaf either (a preempted request
@@ -590,6 +593,22 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
s.chain = chain;
s.label = std::move(kept_label);
at_root.push_back(id);
/* Rows under one root are pruned only when the root block goes, and a prompt every request
* shares (a decision model's instructions) never goes: the list grew by a row a request and
* each insert walked it under the lock the engine threads take (#375: prefill from 9k to
* 2.5k tok/s after 500K requests). Past kRootSessions the least recently used row is
* dropped; a row is bookkeeping, so its blocks stay cached. */
if (at_root.size() > kRootSessions) {
uint64_t oldest = 0, oldest_ns = ~uint64_t{0};
for (uint64_t sid : at_root) {
auto it = sessions_.find(sid);
if (it != sessions_.end() && it->second.last_used_ns < oldest_ns) {
oldest_ns = it->second.last_used_ns;
oldest = sid;
}
}
if (oldest) drop_session(oldest);
}
}
void IdleTiers::drop_session(uint64_t id) {
+3
View File
@@ -404,6 +404,9 @@ private:
* freed, so ticks do not spin on the queue. */
bool wb_stuck_ = false;
std::unordered_map<uint64_t, Session> sessions_;
/* Rows kept under one root (sessions sharing a first block); past it the least recently used
* goes (note_session). */
static constexpr size_t kRootSessions = 1024;
/* Sessions by first block. A chain is reachable only from position zero, so once its first
* block goes (forget(), or a drop here via drop_rooted) its rows go too; this keeps the table
* bounded. Sessions sharing a system prompt share a root, hence a list. */
+61 -18
View File
@@ -702,21 +702,41 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
return RAD_OK;
}
namespace {
/* The H.264 encoder the round trip uses: libx264, the reference's, else libopenh264 (the published
* image carries libopenh264 and no libx264). Not any H.264 encoder: the hardware ones need a device
* context this path does not set up. */
const AVCodec* h264_encoder() {
for (const char* name : { "libx264", "libopenh264" })
if (const AVCodec* c = avcodec_find_encoder_by_name(name)) return c;
return nullptr;
}
} /* namespace */
bool h264_roundtrip_available() {
return avcodec_find_encoder_by_name("libx264") && avcodec_find_decoder(AV_CODEC_ID_H264);
return h264_encoder() && avcodec_find_decoder(AV_CODEC_ID_H264);
}
/* PyAV's single-frame round trip: VideoFrame.from_ndarray(rgb24).reformat("yuv420p") (plain
* SWS_BILINEAR, BT.601 coefficients, limited-range output), libx264 with the given crf, then the
* decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. */
* decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. Without libx264, libopenh264 takes
* the frame at a quantiser held at the crf, about the compression libx264's crf gives a single intra
* frame, so the first frame is close to the reference's but not exact. libopenh264 takes no side
* under 16, so a smaller picture is encoded with its last row and column repeated out to 16 and
* the decoded frame cut back. */
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
std::string w;
if (!why) why = &w;
const int W = in.w & ~1, H = in.h & ~1;
if (W <= 0 || H <= 0) { *why = "the picture is smaller than 2x2"; return RAD_E_INVAL; }
const AVCodec* enc = avcodec_find_encoder_by_name("libx264");
const AVCodec* enc = h264_encoder();
const AVCodec* dcd = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!enc || !dcd) { *why = "this libavcodec has no libx264 encoder or H.264 decoder"; return RAD_E_UNSUPPORTED; }
if (!enc) { *why = "this libavcodec has no H.264 encoder"; return RAD_E_UNSUPPORTED; }
if (!dcd) { *why = "this libavcodec has no H.264 decoder"; return RAD_E_UNSUPPORTED; }
const bool x264 = !std::strcmp(enc->name, "libx264");
const int EW = x264 ? W : std::max(W, 16), EH = x264 ? H : std::max(H, 16);
AVCodecContext* ec = avcodec_alloc_context3(enc);
AVCodecContext* dc = avcodec_alloc_context3(dcd);
AVFrame* yuv = av_frame_alloc();
@@ -733,8 +753,8 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
*why = "out of memory";
st = RAD_E_NOMEM;
} else {
ec->width = W;
ec->height = H;
ec->width = EW;
ec->height = EH;
ec->pix_fmt = AV_PIX_FMT_YUV420P;
ec->time_base = AVRational{ 1, 1 };
ec->framerate = AVRational{ 1, 1 };
@@ -742,19 +762,26 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
* that many slices, which shapes the bitstream. */
ec->thread_count = 0;
ec->thread_type = FF_THREAD_SLICE;
av_opt_set(ec->priv_data, "preset", "veryfast", 0);
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0);
if (x264) {
av_opt_set(ec->priv_data, "preset", "veryfast", 0);
av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0);
} else {
/* libopenh264's rate control held between qmin and qmax: its "off" mode encodes at the
* layer quantiser FFmpeg leaves at the library's default and ignores both. */
ec->qmin = ec->qmax = std::clamp(crf, 1, 51);
av_opt_set(ec->priv_data, "rc_mode", "quality", 0);
}
int e = avcodec_open2(ec, enc, nullptr);
if (e < 0) fail("opening libx264", e);
if (e < 0) fail(x264 ? "opening libx264" : "opening the H.264 encoder", e);
if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e);
if (st == RAD_OK) {
yuv->format = AV_PIX_FMT_YUV420P;
yuv->width = W;
yuv->height = H;
yuv->width = EW;
yuv->height = EH;
if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e);
}
if (st == RAD_OK) {
sws = sws_getContext(W, H, AV_PIX_FMT_RGB24, W, H, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
sws = sws_getContext(EW, EH, AV_PIX_FMT_RGB24, EW, EH, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
nullptr, nullptr, nullptr);
if (!sws) fail("no RGB to yuv420p conversion", 0);
}
@@ -765,14 +792,17 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
if (!rgb) fail("out of memory", AVERROR(ENOMEM));
else {
rgb->format = AV_PIX_FMT_RGB24;
rgb->width = W;
rgb->height = H;
rgb->width = EW;
rgb->height = EH;
if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e);
else {
for (int y = 0; y < H; ++y)
std::memcpy(rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0],
in.rgb.data() + (size_t)y * in.w * 3, (size_t)W * 3);
if (sws_scale(sws, rgb->data, rgb->linesize, 0, H, yuv->data, yuv->linesize) != H)
for (int y = 0; y < EH; ++y) {
uint8_t* row = rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0];
std::memcpy(row, in.rgb.data() + (size_t)std::min(y, H - 1) * in.w * 3,
(size_t)W * 3);
for (int x = W; x < EW; ++x) std::memcpy(row + x * 3, row + (W - 1) * 3, 3);
}
if (sws_scale(sws, rgb->data, rgb->linesize, 0, EH, yuv->data, yuv->linesize) != EH)
fail("colour conversion failed", 0);
}
av_frame_free(&rgb);
@@ -795,6 +825,19 @@ int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) {
st = to_rgb(dec, &back, out, why);
sws_freeContext(back);
got = st == RAD_OK;
if (got && (out->w != W || out->h != H)) {
if (out->w < W || out->h < H) {
fail("the round trip decoded to a smaller frame", 0);
got = false;
} else {
for (int y = 0; y < H; ++y)
std::memmove(out->rgb.data() + (size_t)y * W * 3,
out->rgb.data() + (size_t)y * out->w * 3, (size_t)W * 3);
out->rgb.resize((size_t)W * H * 3);
out->w = W;
out->h = H;
}
}
}
av_frame_unref(dec);
}
+2 -2
View File
@@ -90,9 +90,9 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
/* `in` encoded as a one-frame H.264 stream at constant quality `crf` (libx264, preset veryfast,
* yuv420p) and decoded back, as a video model's reference pipeline does to a conditioning
* picture so it carries the compression of the footage the model was trained on. An odd width
* or height loses its last column or row first. Needs libx264. */
* or height loses its last column or row first. Needs an H.264 encoder: libx264, else libopenh264. */
int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why);
/* Whether this build can run h264_roundtrip: its libavcodec has libx264. */
/* Whether this build can run h264_roundtrip: its libavcodec has an H.264 encoder and decoder. */
bool h264_roundtrip_available();
} /* namespace mm */
+221 -137
View File
@@ -334,6 +334,22 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
std::memset(calm_, 0, 8 << 20);
}
/* ---- the file tier's cache cycle (stage_file_units) -------------------------------------
*
* The stager covers the plan's file-tier units from the start; it may cover more
* (cover_file_units). Each layer's file-tier bytes start as the plan's, which the plan sized
* the stager's buffers for. */
file_ok_.assign(plan.units.size(), 0);
layer_file_.assign((size_t)std::max(n_layers_, 1), 0);
file_cap_ = file_buf_bytes_;
for (size_t u = 0; u < plan.units.size(); ++u) {
const MoveUnit& mu = plan.units[u];
if (mu.tier != Tier::SSD || mu.access != RAD_ACCESS_CONDITIONAL) continue;
file_ok_[u] = 1;
if (mu.layer >= 0) layer_file_[(size_t)mu.layer] += align_up(mu.bytes, RAD_ALIGN_UNIT);
}
victims_.assign(plan.classes.size(), VictimRank{});
/* ---- streams, events, move records ------------------------------------------------------ */
RAD_TRY(rad_stream_create(&mover_, /*high_priority=*/0));
/* Every event here is local: they order the mover's queue against this card's compute queue
@@ -664,18 +680,6 @@ int64_t Mover::stage_need(const std::vector<int32_t>& units, int64_t* largest) c
/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */
namespace {
/* One weight's bytes: where they are in the container and where they go. */
struct FileExt {
int64_t foff = 0, bytes = 0;
char* dst = nullptr;
/* Into a hot-cache slot rather than the layer buffer: counted as
* ssd_promoted_bytes, and the copy leaves the unit resident. */
bool hot = false;
/* Into a host pool slot rather than the layer buffer: counted as
* ssd_deposit_bytes, and the copy leaves the unit resident in RAM. */
bool deposit = false;
};
/* The largest gap a run reads through instead of starting another pread. A routed layer's
* weights sit together in the container, each on RAD_ALIGN_UNIT, so a gap between two file-tier
* weights is either alignment padding (cheaper to read than a second pread) or units on another
@@ -685,36 +689,125 @@ constexpr int64_t kReadThrough = (int64_t)256 << 10;
} /* namespace */
bool Mover::on_file_tier(const std::vector<int32_t>& units) const {
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) continue;
const UnitState& us = unit_[(size_t)u];
if (us.tier == Tier::SSD && us.slab_slot < 0 && us.klass >= 0) return true;
}
return false;
}
bool Mover::routes_any(const std::vector<int32_t>& units, const int32_t* ecnt,
int32_t n_expert) const {
if (!plan_ || !ecnt) return !units.empty();
for (int32_t u : units) {
if (u < 0 || (size_t)u >= plan_->units.size()) continue;
const int32_t e = plan_->units[(size_t)u].expert;
if (e < 0 || e >= n_expert || ecnt[e] != 0) return true;
}
return false;
}
void Mover::cover_file_units(const std::vector<int32_t>& more) {
/* A unit whose container bytes are not its kernel's layout cannot be read back. */
for (int32_t u : more)
if (u >= 0 && (size_t)u < file_ok_.size() && plan_->units[(size_t)u].file_direct)
file_ok_[(size_t)u] = 1;
}
/* A full pool's relabel victim for a deposit of class `klass`: its coldest pooled unit that the
* file stager reads back (Mover::file_ok_), with nothing in flight, outside the `protect` layers,
* and whose layer's file-tier part still fits the stager's buffer with it. -1 when none, or when
* that unit is not colder than `below` (the unit being read): trading a pooled unit for a colder
* one would only make the next step read the warmer one from the drive.
*
* The protected layers are the one being read and any whose ops are about to be issued: a
* relabelled unit's weights are published at the zero region at once, so taking one of theirs
* would hand the next GEMM zeros for a routed expert. Every other layer is safe: one already
* issued this pass read the pool slot, which the quarantine keeps until those kernels are done,
* and a later one is read back by its own trigger, since the stager covers the unit. The
* routing counts protect nothing here: they are the counts of the layer being read, and indexing
* them by another layer's expert number protected a random set while a whole-layer read (no
* counts) protected nothing at all.
*
* The cap keeps every read of a layer within the stager's buffer: the plan sized it for the
* largest layer's file-tier part, and a relabel adds to its victim's. */
int32_t Mover::pick_victim(int32_t klass, const int32_t* protect, int n_protect, float below) {
if (klass < 0 || (size_t)klass >= victims_.size() || !heat_) return -1;
VictimRank& vr = victims_[(size_t)klass];
if (vr.at != dispatch_) {
vr.at = dispatch_;
vr.by_heat.clear();
for (int32_t v = 0; v < (int32_t)unit_.size(); ++v) {
const UnitState& vs = unit_[(size_t)v];
if (vs.klass != klass || vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0 || !file_ok_[(size_t)v])
continue;
vr.by_heat.push_back({ heat_->heat(v), v });
}
/* Hottest first; on equal heat the higher unit first, so the back is the coldest and,
* among equally cold ones, the lowest: the unit a scan keeping its first strict minimum
* would pick. */
std::sort(vr.by_heat.begin(), vr.by_heat.end(),
[](const std::pair<float, int32_t>& a, const std::pair<float, int32_t>& b) {
return a.first != b.first ? a.first > b.first : a.second > b.second;
});
}
for (size_t k = vr.by_heat.size(); k-- > 0;) {
const int32_t v = vr.by_heat[k].second;
if (v < 0) continue;
const UnitState& vs = unit_[(size_t)v];
/* Within a dispatch a unit leaves the pool only by a relabel, so one that is not there any
* more is gone for the rest of it. A copy in flight or a protected layer only waits. */
if (vs.klass != klass || vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0) {
vr.by_heat[k].second = -1;
continue;
}
if (copying_[(size_t)v]) continue;
const int32_t layer = plan_->units[(size_t)v].layer;
bool held = layer < 0 || (size_t)layer >= layer_file_.size();
for (int p = 0; p < n_protect && !held; ++p) held = protect[p] >= 0 && protect[p] == layer;
if (held) continue;
if (layer_file_[(size_t)layer] + align_up(vs.bytes, RAD_ALIGN_UNIT) > file_cap_) continue;
/* Every candidate further in is at least as warm. */
if (!(vr.by_heat[k].first < below)) return -1;
vr.by_heat[k].second = -1;
while (!vr.by_heat.empty() && vr.by_heat.back().second < 0) vr.by_heat.pop_back();
return v;
}
return -1;
}
int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
RadEvent after, RadEvent done, std::vector<int32_t>* staged,
std::vector<int32_t>* skipped, const int32_t* ecnt,
int32_t n_expert, std::vector<int32_t>* promoted) {
if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL;
staged->clear();
if (skipped) skipped->clear();
if (promoted) promoted->clear();
RadEvent after, RadEvent done, FileRead* rd, const int32_t* ecnt,
int32_t n_expert, const int32_t* protect, int n_protect) {
if (!plan_ || !dst || !rd || !done) return RAD_E_INVAL;
if (!file_.ok() || !windows_ || n_windows_ <= 0) return RAD_E_STATE;
/* The layout in `dst`, unit by unit in the order given, and every weight's extent. */
std::vector<FileExt> ext;
std::vector<int64_t> at;
std::vector<char*> pbases; /* hot-cache units' slot bases, in promoted order */
int64_t off = 0, hot_bytes = 0;
/* The layout in `dst`, unit by unit in the order given after what earlier calls for the
* layer packed, and every weight's extent. */
fext_.clear();
fat_.clear();
fbase_.clear();
frec_.clear();
const size_t staged0 = rd->staged.size(), skipped0 = rd->skipped.size(),
promoted0 = rd->promoted.size();
const int64_t used0 = rd->used;
int64_t off = rd->used, hot_bytes = 0;
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::SSD || us.slab_slot >= 0 || us.klass < 0) continue;
/* Routing-aware reads: the layer's router has run by the time the stager triggers
* (the trigger is the layer's first expert op), so `ecnt` holds this pass's counts.
* An expert counted zero has no sorted rows, so no GEMM run names it and nothing
* reads its weights: leave its bytes on the drive. The dummy publication below
* keeps every table entry valid for the pass. */
if (ecnt && skipped) {
const MoveUnit& mu = plan_->units[(size_t)u];
if (mu.expert >= 0 && mu.expert < n_expert && ecnt[mu.expert] == 0) {
skipped->push_back(u);
continue;
}
const MoveUnit& mu = plan_->units[(size_t)u];
/* Routing-aware reads: `ecnt` holds the counts of the rows about to run, taken at the
* layer's trigger behind its router. An expert counted zero has no sorted rows, so no
* GEMM run names it and nothing reads its weights: leave its bytes on the drive. The
* dummy publication below keeps every table entry valid for the pass. */
if (ecnt && mu.expert >= 0 && mu.expert < n_expert && ecnt[mu.expert] == 0) {
rd->skipped.push_back(u);
continue;
}
/* The hot VRAM cache: heat past the admission bar and a free
* budgeted slot, and this pass's read lands in the slot and stays there. The read is
@@ -722,7 +815,7 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
* bookkeeping (the container is ground truth), so a mistake costs one future
* re-read. No free slot, no heat, or no move record: the buffer path below, as
* before. */
if (promoted && plan_->dynamic && heat_ && heat_->admit_hot(u) && !unit_in_flight(u)) {
if (plan_->dynamic && heat_ && heat_->admit_hot(u) && !unit_in_flight(u)) {
ClassPools& cp = pools_[(size_t)us.klass];
const int rec = free_move_record();
int64_t slot = -1;
@@ -730,7 +823,6 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
else slot = cp.slab.take_where([&](int64_t s) { return s < cp.n_fixed; });
if (slot >= 0 && record_gate() < 0) { cp.slab.add_free(slot); slot = -1; }
if (slot >= 0) {
const MoveUnit& mu = plan_->units[(size_t)u];
char* const base = cp.slot_ptr(slot);
Move& m = moves_[(size_t)rec];
m.state = Move::State::Copying;
@@ -746,74 +838,58 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
base + mu.offset[k], true });
fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
base + mu.offset[k], true, false });
}
promoted->push_back(u);
pbases.push_back(base);
rd->promoted.push_back(u);
fbase_.push_back(base);
frec_.push_back((int32_t)rec);
hot_bytes += us.bytes;
continue;
}
}
/* A free pool slot and this read deposits the unit into the pool -- the O_DIRECT
* read's destination IS the slot, and the unit becomes a pool unit: the GEMM reads it
/* A free pool slot and this read deposits the unit into the pool: its window's copy list
* carries it into the slot, and the unit becomes a pool unit -- the GEMM reads it
* zero-copy this step, heat promotes it at PCIe speed, and its demotion is a copyless
* drop. The pool is ALL cache: no free slot and the coldest idle pool unit -- native
* or deposited, the container is ground truth for both -- relabels back to the file
* tier, copyless. Its slot feeds a future deposit after the
* coldest idle pool unit -- native or deposited, the container is ground truth for both --
* relabels back to the file tier, copyless. Its slot feeds a future deposit after the
* quarantine; this read takes the buffer path. */
if (promoted && plan_->dynamic && heat_ && !unit_in_flight(u)) {
* drop. The pool is all cache: with no free slot, its coldest unit the stager covers is
* relabelled back to the file tier, copyless (the container holds every unit's bytes),
* provided it is colder than this one (pick_victim). The slot it gives up feeds a later
* deposit after the quarantine; this read takes the buffer path. */
if (plan_->dynamic && heat_ && !unit_in_flight(u)) {
ClassPools& cp = pools_[(size_t)us.klass];
const int rec = free_move_record();
int64_t g = -1;
if (rec < 0) ++stats_.no_record;
else if (record_gate() >= 0) g = cp.pool.take();
if (g < 0 && heat_) {
/* The pool is full. Eviction is a copyless relabel: the
* container holds every unit's bytes, so the victim loses nothing but its slot --
* it becomes a file-tier unit whose next read deposits again. The victim is the
* coldest idle unit of the class, however it got there: the cache adapts to the
* workload, not to where a unit started. The freed slot feeds a future deposit
* after the quarantine; this read takes the buffer path. */
int32_t victim = -1;
float best = 0;
for (int32_t v = 0; v < (int32_t)unit_.size(); ++v) {
UnitState& vs = unit_[(size_t)v];
if (vs.klass != us.klass ||
vs.tier != Tier::HostPinned || vs.pool_slot < 0 ||
vs.slab_slot >= 0 || copying_[(size_t)v] || unit_in_flight(v))
continue;
const MoveUnit& mv = plan_->units[(size_t)v];
if (mv.expert >= 0 && mv.expert < n_expert && ecnt && ecnt[mv.expert] > 0)
continue; /* routed this pass: still wanted */
const float h = heat_->heat(v);
if (victim < 0 || h < best) { victim = v; best = h; }
}
if (g < 0 && rec >= 0) {
/* The deposit's own record is still free (nothing uses it this read), so the
* relabel may take the same one. */
const int r2 = free_move_record();
const int32_t victim =
r2 >= 0 ? pick_victim(us.klass, protect, n_protect, heat_->heat(u)) : -1;
if (victim >= 0) {
const int r2 = free_move_record();
if (r2 >= 0) {
UnitState& vs = unit_[(size_t)victim];
const MoveUnit& mv = plan_->units[(size_t)victim];
Move& m2 = moves_[(size_t)r2];
m2.state = Move::State::Published; /* nothing to copy: the drive has it */
m2.kind = Move::Kind::Evict;
m2.unit = victim;
m2.slab_slot = -1;
m2.pool_slot = vs.pool_slot;
for (size_t k = 0; k < mv.weights.size(); ++k)
res_.publish(mv.weights[k], calm_);
vs.tier = Tier::SSD;
vs.site = Site::DeviceStaged;
vs.pool_slot = -1;
heat_->set_tier(victim, Tier::SSD);
++stats_.pool_evictions;
}
UnitState& vs = unit_[(size_t)victim];
const MoveUnit& mv = plan_->units[(size_t)victim];
Move& m2 = moves_[(size_t)r2];
m2.state = Move::State::Published; /* nothing to copy: the drive has it */
m2.kind = Move::Kind::Evict;
m2.unit = victim;
m2.slab_slot = -1;
m2.pool_slot = vs.pool_slot;
for (size_t k = 0; k < mv.weights.size(); ++k)
res_.publish(mv.weights[k], calm_);
vs.tier = Tier::SSD;
vs.site = Site::DeviceStaged;
vs.pool_slot = -1;
layer_file_[(size_t)mv.layer] += align_up(vs.bytes, RAD_ALIGN_UNIT);
heat_->set_tier(victim, Tier::SSD);
/* No pool slot to promote from until a read deposits it again, which makes
* it movable once more; its layer's trigger reads it meanwhile. */
heat_->set_movable(victim, false);
++stats_.pool_evictions;
}
}
if (g >= 0) {
const MoveUnit& mu = plan_->units[(size_t)u];
Move& m = moves_[(size_t)rec];
m.state = Move::State::Copying;
m.kind = Move::Kind::Deposit;
@@ -824,20 +900,23 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
us.pool_slot = g;
us.tier = Tier::HostPinned;
us.site = Site::DeviceZeroCopy;
if (mu.layer >= 0 && (size_t)mu.layer < layer_file_.size())
layer_file_[(size_t)mu.layer] -= align_up(us.bytes, RAD_ALIGN_UNIT);
heat_->set_tier(u, Tier::HostPinned);
heat_->set_movable(u, true); /* the slot makes it a PCIe-speed promotion candidate */
heat_->set_busy(u, true);
++stats_.ssd_deposits;
char* const slot = (char*)cp.pool_base + g * cp.stride;
for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
(char*)cp.pool_base + g * cp.stride + mu.offset[k],
false, true });
fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
slot + mu.offset[k], false, true });
}
for (size_t k = 0; k < mu.weights.size(); ++k)
res_.publish(mu.weights[k],
(char*)cp.pool_dev + g * cp.stride + mu.offset[k]);
frec_.push_back((int32_t)rec);
continue;
}
}
@@ -847,42 +926,58 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
"the plan sized for the largest one", humanb(cap).c_str());
return RAD_E_SCRATCH;
}
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t k = 0; k < mu.weights.size(); ++k) {
const WeightInfo& w = prog_->weights[mu.weights[k]];
if (w.stored_bytes <= 0) continue; /* nothing to read, and nothing to place */
ext.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes, dst + off + mu.offset[k] });
fext_.push_back(FileExt{ (int64_t)w.file_offset, w.stored_bytes,
dst + off + mu.offset[k], false, false });
}
staged->push_back(u);
at.push_back(off);
rd->staged.push_back(u);
fat_.push_back(off);
off += need;
}
/* Skipped units' table entries must not name their stale addresses either: point them
* into the layer buffer, whose base is a valid allocation no zero-count expert reads
* through (a dead row would read row 0 of a real expert's region and discard it). The
* caller nulls them again with the staged units. Published even when EVERY unit of the
* layer was skipped -- a decode step can route nothing to a layer -- because the kernels
* still issue the layer's table and a null entry fails the step. */
if (skipped) {
for (int32_t u : *skipped) {
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], calm_);
stats_.ssd_skipped_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
stats_.ssd_skipped_units += (uint64_t)skipped->size();
rd->used = off;
/* Publish before the reads: nothing resolves these addresses until the caller's layer op,
* which waits on `done` first. Skipped units' entries must not name stale addresses either:
* they point at the zero region, which no zero-count expert reads through (a dead row reads
* zeros and discards them). Published even when EVERY unit of the layer was skipped -- a
* decode step can route nothing to a layer -- because the kernels still issue the layer's
* table and a null entry fails the step. The caller nulls them again with the staged units.
* Hot-cache units publish at their slots and stay published: nothing unstages them, and
* retire() finishes their admission when the copies land. */
for (size_t k = skipped0; k < rd->skipped.size(); ++k) {
const int32_t u = rd->skipped[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j) res_.publish(mu.weights[j], calm_);
stats_.ssd_skipped_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
if (ext.empty()) return RAD_OK;
stats_.ssd_skipped_units += (uint64_t)(rd->skipped.size() - skipped0);
for (size_t k = staged0; k < rd->staged.size(); ++k) {
const int32_t u = rd->staged[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], dst + fat_[k - staged0] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
for (size_t k = promoted0; k < rd->promoted.size(); ++k) {
const int32_t u = rd->promoted[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], fbase_[k - promoted0] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
if (fext_.empty()) return RAD_OK;
/* Container order, so a window is one long run of the drive rather than a seek per weight. */
std::stable_sort(ext.begin(), ext.end(),
std::stable_sort(fext_.begin(), fext_.end(),
[](const FileExt& a, const FileExt& b) { return a.foff < b.foff; });
/* The dashboard's SSD panel and /stats ssd_reads read these: the file tier's container
* reads are the expert SSD traffic the metric names. The scheduled prefetch path counted
* its own link reads here; the file stager's were invisible, so the panels showed zero
* however much the drive streamed. */
stats_.ssd_reads += (uint64_t)ext.size();
for (const FileExt& e : ext) {
stats_.ssd_reads += (uint64_t)fext_.size();
for (const FileExt& e : fext_) {
stats_.ssd_bytes += (uint64_t)e.bytes;
/* The copies below move the same bytes from the windows to their destination, which
* crosses the link either way: into the layer buffer when the unit is discarded at the
@@ -902,8 +997,8 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
std::vector<Seg> segs;
std::vector<Cp> cps;
size_t i = 0;
int64_t piece = 0; /* bytes of ext[i] already placed */
while (i < ext.size()) {
int64_t piece = 0; /* bytes of fext_[i] already placed */
while (i < fext_.size()) {
const int w = win_next_;
win_next_ = (win_next_ + 1) % n_windows_;
char* win = windows_ + (int64_t)w * W;
@@ -921,8 +1016,8 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
* cannot finish across this window and the next. */
segs.clear();
cps.clear();
while (i < ext.size()) {
const FileExt& e = ext[i];
while (i < fext_.size()) {
const FileExt& e = fext_[i];
const int64_t fo = e.foff + piece, left = e.bytes - piece;
int64_t wo;
if (!segs.empty() && fo >= segs.back().fs && fo <= segs.back().fe + kReadThrough) {
@@ -958,26 +1053,14 @@ int Mover::stage_file_units(const std::vector<int32_t>& units, char* dst, int64_
win_rec_[(size_t)w] = 1;
}
RAD_TRY(rad_event_record(done, mover_));
/* The hot-cache admissions and deposits are copies like the staged units': their records
* land behind them, so retire() finishes a move when its bytes are in its slot. */
for (int32_t rec : frec_) RAD_TRY(rad_event_record(moves_[(size_t)rec].ev, mover_));
rd->copied = true;
for (size_t k = 0; k < staged->size(); ++k) {
const int32_t u = (*staged)[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], dst + at[k] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
/* Hot-cache units publish at their slots and stay published: nothing unstages them, and
* retire() finishes their admission when the copies land. */
for (size_t k = 0; k < pbases.size(); ++k) {
const int32_t u = (*promoted)[k];
const MoveUnit& mu = plan_->units[(size_t)u];
for (size_t j = 0; j < mu.weights.size(); ++j)
res_.publish(mu.weights[j], pbases[k] + mu.offset[j]);
stats_.ssd_read_bytes += (uint64_t)unit_[(size_t)u].bytes;
}
++stats_.ssd_layers;
stats_.ssd_units += (uint64_t)(staged->size() + pbases.size());
stats_.h2d_bytes += (uint64_t)(off + hot_bytes);
stats_.ssd_units += (uint64_t)((rd->staged.size() - staged0) + (rd->promoted.size() - promoted0));
stats_.h2d_bytes += (uint64_t)(off - used0 + hot_bytes);
return RAD_OK;
}
@@ -1809,6 +1892,7 @@ int Mover::retire(HeatEngine* heat) {
break;
case Move::Kind::Release:
case Move::Kind::Drop:
case Move::Kind::Evict: /* published at issue, never Copying */
break;
}
/* Safe without synchronisation: both copies of the bytes are valid now (see
+75 -16
View File
@@ -366,8 +366,9 @@ struct MoverStats {
uint64_t ssd_layers = 0, ssd_units = 0, ssd_read_bytes = 0, ssd_preads = 0;
uint64_t ssd_read_ns = 0, ssd_wait_ns = 0;
/* Routing-aware reads: units of experts whose routing count was zero at the layer's
* trigger, not read (their weights are re-published to the layer buffer as a dummy
* address for the pass, and nulled again with the staged units). */
* trigger, not read (their weights are published at the zero region for the pass, and
* nulled again with the staged units). Counted per read: a later slice of the layer's rows
* that reads some of them counts the rest again. */
uint64_t ssd_skipped_units = 0, ssd_skipped_bytes = 0;
};
@@ -604,28 +605,58 @@ public:
* and published there; afterwards unstage_units publishes them as null again. The plan
* charges the two buffers to the weights pool (Plan::file_stage_vram).
*
* stage_file_units reads every file-tier unit of `units` into `dst`, packed at RAD_ALIGN_UNIT
* in the order given, through the pinned read windows: container-order
* runs, each window draining to `dst` on the mover's stream while the next
* fills, behind `after` (if set), with `done` recorded last. Published
* settled. RAD_E_SCRATCH if the units exceed `cap`. The reads block this
* thread.
* stage_file_units reads the file-tier units of `units` into `dst`, packed at RAD_ALIGN_UNIT
* in the order given from `rd->used` on, through the pinned read windows:
* container-order runs, each window drained to its destinations by one
* copy list on the mover's stream while the next fills, behind `after` (if
* set), with `done` recorded last. Published settled, so the compute
* stream must wait on `done` before an op reads any of them; `rd->copied`
* says whether there is anything to wait for (a hot-cache admission or a
* pool deposit is a copy like a staged unit's). RAD_E_SCRATCH if the units
* exceed `cap`. The reads block this thread. Appends to `rd`, so a second
* call for another slice of the layer's rows adds what the first left out.
*
* Routing-aware reads: with `ecnt` (host, `n_expert` entries, the layer's per-expert routing
* counts for the rows about to run), a unit whose expert is counted zero is not read: it goes
* to `rd->skipped`, its weights are published at the zero region (valid memory a no-run
* expert never reads through), and the caller nulls it again with the staged units. Null
* `ecnt` reads every file-tier unit given.
*
* A read that finds the pool full relabels its coldest unit back to the file tier (see the
* definition). Units of the `protect` layers (plan layer numbers; the one being read and any
* whose ops are about to be issued) are never taken, whatever their counts.
*
* Routing-aware reads: with `ecnt` (host, `n_expert` entries, the layer's per-expert
* routing counts for the current pass), a unit whose expert is counted zero is not read:
* it goes to `skipped`, its weights are published at `dst` (a dummy address inside the
* layer buffer, valid memory a no-run expert never reads through), and the caller nulls
* it again with the staged units. Null `ecnt` reads the whole layer.
* file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */
struct FileRead {
std::vector<int32_t> staged; /* read into the layer buffer; nulled at release */
std::vector<int32_t> skipped; /* counted zero; published at the zero region */
std::vector<int32_t> promoted; /* read into hot-cache slots; they keep that address */
int64_t used = 0; /* bytes of the buffer the staged units take */
bool copied = false; /* `done` is behind copies an op will read */
void clear() {
staged.clear(); skipped.clear(); promoted.clear();
used = 0;
copied = false;
}
};
int stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
RadEvent after, RadEvent done, std::vector<int32_t>* staged,
std::vector<int32_t>* skipped = nullptr,
RadEvent after, RadEvent done, FileRead* rd,
const int32_t* ecnt = nullptr, int32_t n_expert = 0,
std::vector<int32_t>* promoted = nullptr);
const int32_t* protect = nullptr, int n_protect = 0);
char* file_buffer(int i) const {
return (file_vram_ && (i == 0 || i == 1)) ? file_vram_ + i * file_buf_bytes_ : nullptr;
}
int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; }
/* Whether any of `units` is on the file tier now (no slab slot, no pool slot): a layer with
* none has nothing to read, and its trigger skips the read and the drain it would cost. */
bool on_file_tier(const std::vector<int32_t>& units) const;
/* Whether `ecnt` (as stage_file_units takes it) routes any of `units`. */
bool routes_any(const std::vector<int32_t>& units, const int32_t* ecnt, int32_t n_expert) const;
/* The units the file stager reads back when they are on the file tier: every routed unit the
* plan put there, plus `more` (pooled and resident ones it also covers). Only a covered unit
* may be relabelled back to the file tier to make room for a deposit, since nothing else
* would ever read it again. Called once, at the stager's bring-up. */
void cover_file_units(const std::vector<int32_t>& more);
/* A snapshot by value: the counters are atomics read while the rank thread writes them. */
MoverStats stats() const { return stats_.snapshot(); }
@@ -779,6 +810,34 @@ private:
int win_next_ = 0;
std::vector<RadEvent> win_ev_;
std::vector<uint8_t> win_rec_;
/* stage_file_units' working lists, kept so a read allocates nothing once warm. A FileExt is
* one weight's bytes: where they are in the container and where they go -- the layer
* buffer, a hot-cache slot (`hot`, counted as ssd_promoted_bytes) or a pool slot
* (`deposit`, counted as ssd_deposit_bytes). */
struct FileExt {
int64_t foff = 0, bytes = 0;
char* dst = nullptr;
bool hot = false;
bool deposit = false;
};
std::vector<FileExt> fext_;
std::vector<int64_t> fat_; /* the staged units' buffer offsets */
std::vector<char*> fbase_; /* the hot-cache units' slot bases */
std::vector<int32_t> frec_; /* move records whose copies this read issues */
/* The file tier's cache cycle. `file_ok_`: by unit, the file stager reads it back when it is
* on the file tier (cover_file_units). `layer_file_`: by plan layer, the bytes of its units
* that are on the file tier or in the hot VRAM cache (which hands them back to the file tier
* when evicted), at the stager's packing; a relabel keeps it within `file_cap_`, the stager's
* buffer, so any read of a layer fits. */
std::vector<uint8_t> file_ok_;
std::vector<int64_t> layer_file_;
int64_t file_cap_ = 0;
/* A full pool's relabel candidates per class, ranked once per dispatch like donors_: every
* covered pooled unit, hottest first, so the coldest is at the back. Heat does not change
* within a dispatch, so this picks what a scan of every unit at each read would. */
struct VictimRank { int at = -1; std::vector<std::pair<float, int32_t>> by_heat; };
std::vector<VictimRank> victims_;
int32_t pick_victim(int32_t klass, const int32_t* protect, int n_protect, float below);
/* The lead gate's ring: one event a dispatch, and a host wait on the one from
* max_lead_dispatches ago. */
+134 -52
View File
@@ -380,7 +380,7 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
if (!mover) return RAD_OK;
/* Routing-aware reads. The source may still decline per layer (a layer that has not
* reported this pass is read whole). */
* reported yet is read whole). */
routes_ = routes;
routes_ud_ = routes_ud;
scratch_ = nullptr;
@@ -391,12 +391,38 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
RAD_MEM_HOST_PINNED);
if (!scratch_) { scratch_n_ = 0; routes_ = nullptr; }
}
/* A pass's rows each route n_expert_used of the model's n_expert experts, so a pass of
* kWholeRows * n_expert / n_expert_used rows routes kWholeRows to an expert on average, on
* every rank: an expert-parallel rank holds fewer experts and gets their share of the rows. */
whole_rows_ = routes_ && prog.meta.n_expert_used > 0
? (kWholeRows * prog.meta.n_expert + prog.meta.n_expert_used - 1) /
prog.meta.n_expert_used
: 0;
whole_ = false;
/* A unit declared and never read has no op span and is left out. */
size_t c = 0;
layers_ = routed_layers(plan, [](const MoveUnit& mu) {
/* The plan's file-tier units, and under a dynamic plan every movable routed unit of a class
* that has some: a deposit can relabel those to the file tier (see stager.h, "which units").
* A unit declared and never read has no op span and is left out. */
auto on_file = [](const MoveUnit& mu) {
return mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL;
}, &c);
};
std::vector<uint8_t> file_class(plan.classes.size(), 0);
for (const MoveUnit& mu : plan.units)
if (on_file(mu) && mu.slab_class >= 0 && (size_t)mu.slab_class < file_class.size())
file_class[(size_t)mu.slab_class] = 1;
auto may_be = [&](const MoveUnit& mu) {
return on_file(mu) ||
(plan.dynamic && mu.access == RAD_ACCESS_CONDITIONAL && mu.movable &&
mu.expert >= 0 && mu.slab_class >= 0 && (size_t)mu.slab_class < file_class.size() &&
file_class[(size_t)mu.slab_class]);
};
size_t c = 0;
layers_ = routed_layers(plan, may_be, &c);
bool wide = !layers_.empty();
if (c > 0) {
wide = false;
layers_ = routed_layers(plan, on_file, &c);
}
if (layers_.empty()) return RAD_OK;
/* A layer's copies stay published until the next one starts, so interleaved layers would need
* a third buffer for the read-ahead; with no fallback address, such a plan is refused. */
@@ -423,6 +449,13 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover,
if ((size_t)layers_[i].first_op < first_of_.size())
first_of_[(size_t)layers_[i].first_op] = (int32_t)i;
mover_ = mover;
if (wide) {
std::vector<int32_t> more;
for (const Layer& L : layers_)
for (int32_t u : L.units)
if (!on_file(plan.units[(size_t)u])) more.push_back(u);
mover_->cover_file_units(more);
}
for (int b = 0; b < 2; ++b)
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
layers_.clear();
@@ -441,6 +474,7 @@ bool FileStager::begin_pass(const RadBatch* b) {
first_op_ = true;
pass_kind_ = b->draft_pass;
last_issued_ = -1;
whole_ = whole_rows_ > 0 && b->n_tok >= whole_rows_;
return true;
}
@@ -449,46 +483,101 @@ bool FileStager::will_issue(int32_t li) const {
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
}
int FileStager::start(int32_t li, RadStream s) {
bool FileStager::counted(int32_t li) const {
if (!routes_ || whole_) return false;
int64_t n = 0;
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n);
return dev && n > 0 && n <= scratch_n_;
}
/* Called only at the layer's trigger or a repeat of it, so the router of the rows about to run
* has been issued on `s` ahead of the copy. The drain costs far less than the read it decides. */
int FileStager::counts(int32_t li, RadStream s, const int32_t** ecnt, int32_t* n_expert) {
*ecnt = nullptr;
*n_expert = 0;
if (!routes_) return RAD_OK;
int64_t n = 0;
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n);
if (!dev || n <= 0 || n > scratch_n_) return RAD_OK;
RAD_TRY(rad_memcpy_async(scratch_, dev, (size_t)n * sizeof(int32_t), s));
RAD_TRY(rad_stream_sync(s));
*ecnt = scratch_;
*n_expert = (int32_t)n;
return RAD_OK;
}
/* Read layer `li` into its buffer: with this pass's counts when the source has them (only at the
* layer's trigger), whole otherwise. A layer with nothing on the file tier now is not held. */
int FileStager::start(int32_t li, RadStream s, bool* resync) {
const int b = li & 1;
if (holds_[b] >= 0) return RAD_E_STATE; /* released before the next read, by construction */
/* Routing-aware reads: the trigger (this call) runs at the layer's first expert op,
* after the layer's router on the same stream, so this pass's counts are ordered
* before the copy. The stream sync costs far less than a gigabyte-scale layer read;
* a source that declines (no report yet this pass) reads the whole layer. */
const Layer& L = layers_[(size_t)li];
if (!mover_->on_file_tier(L.units)) return RAD_OK;
const int32_t* ecnt = nullptr;
int32_t n_expert = 0;
if (routes_) {
int64_t n = 0;
const int32_t* dev = routes_(routes_ud_, layers_[(size_t)li].layer, &n);
if (dev && n > 0 && n <= scratch_n_ &&
rad_memcpy_async(scratch_, dev, (size_t)n * sizeof(int32_t), s) >= 0 &&
rad_stream_sync(s) >= 0) {
ecnt = scratch_;
n_expert = (int32_t)n;
}
}
const int rc = mover_->stage_file_units(layers_[(size_t)li].units, buf_[b], cap_,
free_rec_[b] ? free_[b] : nullptr, done_[b],
&staged_[b], &skipped_[b], ecnt, n_expert,
&promoted_[b]);
if (rc < 0) return rc;
if (!staged_[b].empty() || !promoted_[b].empty()) holds_[b] = li;
if (counted(li)) RAD_TRY(counts(li, s, &ecnt, &n_expert));
/* The layer read, the one held in the other buffer, and the one whose ops are being issued
* (cur_: it may hold nothing on the file tier, and so be held by neither): their pooled units
* must keep their addresses. */
const int32_t protect[3] = { L.layer, holds_[b ^ 1] >= 0 ? layers_[(size_t)holds_[b ^ 1]].layer
: -1,
cur_ >= 0 ? layers_[(size_t)cur_].layer : -1 };
rd_[b].clear();
holds_[b] = li;
*resync = true;
RAD_TRY(mover_->stage_file_units(L.units, buf_[b], cap_, free_rec_[b] ? free_[b] : nullptr,
done_[b], &rd_[b], ecnt, n_expert, protect, 3));
pending_[b] = rd_[b].copied;
return RAD_OK;
}
/* Another slice of the current layer's rows: its router has rewritten the counts, and an expert
* the earlier slices did not route is read now. The buffer is the layer's, and the new units are
* packed after the ones already there, so nothing is waited on before the copies. */
int FileStager::top_up(int32_t li, RadStream s, bool* resync) {
const int b = li & 1;
if (holds_[b] != li || rd_[b].skipped.empty()) return RAD_OK;
const int32_t* ecnt = nullptr;
int32_t n_expert = 0;
RAD_TRY(counts(li, s, &ecnt, &n_expert));
/* The earlier slices were read with counts, so the source has them; were it to decline,
* everything left is read. A slice that routes nothing new changes nothing. */
if (!mover_->routes_any(rd_[b].skipped, ecnt, n_expert)) return RAD_OK;
again_.swap(rd_[b].skipped);
rd_[b].skipped.clear();
rd_[b].copied = false;
const int32_t protect[3] = { layers_[(size_t)li].layer,
holds_[b ^ 1] >= 0 ? layers_[(size_t)holds_[b ^ 1]].layer : -1,
cur_ >= 0 ? layers_[(size_t)cur_].layer : -1 };
*resync = true;
const int rc = mover_->stage_file_units(again_, buf_[b], cap_, nullptr, done_[b], &rd_[b],
ecnt, n_expert, protect, 3);
again_.clear();
RAD_TRY(rc);
if (rd_[b].copied) pending_[b] = true;
return wait(b, s);
}
int FileStager::wait(int32_t b, RadStream s) {
if (!pending_[b]) return RAD_OK;
RAD_TRY(rad_event_wait(s, done_[b]));
pending_[b] = false;
++waits_;
return RAD_OK;
}
int FileStager::finish(int32_t b, RadStream s) {
/* A read the pass never reached (a read-ahead past where it ended) still deposited into the
* pool or admitted into the hot cache, whose publications outlive it: order the stream behind
* those copies before anything later can read them. */
RAD_TRY(wait(b, s));
RAD_TRY(rad_event_record(free_[b], s));
free_rec_[b] = true;
mover_->unstage_units(staged_[b]);
staged_[b].clear();
if (!skipped_[b].empty()) {
mover_->unstage_units(skipped_[b]); /* the dummy publications go to null too */
skipped_[b].clear();
}
/* Hot-cache units are NOT unstaged: their publications name their slots, which outlive
* the buffer. The layer's copies into them landed before its ops ran (the done_ wait). */
promoted_[b].clear();
mover_->unstage_units(rd_[b].staged);
/* The skipped units' dummy publications go to null too. Hot-cache units are not unstaged:
* their publications name their slots, which outlive the buffer. */
mover_->unstage_units(rd_[b].skipped);
rd_[b].clear();
holds_[b] = -1;
return RAD_OK;
}
@@ -497,41 +586,34 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
*resync = false;
if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
/* Read the pass's first routed layer at its first op of any kind. */
/* Read the pass's first routed layer at its first op of any kind, when it is read whole. */
if (first_op_) {
first_op_ = false;
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
[](const Layer& L, int32_t op) { return L.first_op < op; });
if (it != layers_.end()) {
const int32_t li = (int32_t)(it - layers_.begin());
if (will_issue(li)) {
RAD_TRY(start(li, s));
*resync = true;
}
if (will_issue(li) && !counted(li)) RAD_TRY(start(li, s, resync));
}
}
if ((size_t)h >= first_of_.size()) return RAD_OK;
const int32_t li = first_of_[(size_t)h];
if (li < 0 || li == cur_) return RAD_OK;
if (li < 0) return RAD_OK;
if (li == cur_) return top_up(li, s, resync);
/* Entering layer `li`: the layer before is behind every op issued so far on this stream. */
for (int b = 0; b < 2; ++b)
if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; }
/* A layer the read-ahead skipped (the learned bound said the pass ends before it) is read
* here rather than issued without addresses. */
if (holds_[li & 1] != li) {
RAD_TRY(start(li, s));
*resync = true;
}
if (holds_[li & 1] == li) RAD_TRY(rad_event_wait(s, done_[li & 1]));
/* Read here unless read ahead: a counted layer always, a whole one the read-ahead skipped
* (the learned bound said the pass ends before it). */
if (holds_[li & 1] != li) RAD_TRY(start(li, s, resync));
RAD_TRY(wait(li & 1, s));
cur_ = li;
const int32_t next = li + 1;
if ((size_t)next < layers_.size() && will_issue(next)) {
RAD_TRY(start(next, s));
*resync = true;
}
if ((size_t)next < layers_.size() && will_issue(next) && !counted(next))
RAD_TRY(start(next, s, resync));
return RAD_OK;
}
+82 -28
View File
@@ -214,47 +214,92 @@ private:
* GEMM is handed every expert's pointer at issue. So on every pass, decode included, each routed
* layer's file-tier units are read into one of the mover's two file buffers before the layer's
* first expert op and published there, then published as null when the next routed layer starts.
* The router's picks are not known on the host without a round trip, so the layer's whole
* file-tier part is read; decode is then paced by the drive, which is the trade the flag makes.
*
* the pass's first op read the first routed layer the pass issues
* a layer's first op release the layer before (record its buffer free on the stream, publish
* null), wait on this layer's copies, and read the next layer into the
* buffer just released -- its copies queue behind that free event
* ---- which experts -------------------------------------------------------------------------------
*
* Only the experts the layer's rows route to are read. Their counts are known only once the
* layer's router has run, so a layer is read at its own trigger, its first expert op: the counts
* are copied back behind the router on the same stream (one drain of the stream), and a unit
* counted zero is published at the mover's zero region instead of being read. The read cannot
* start earlier: counts taken before the router are another layer's, or the last pass's, and a
* truly routed expert they count zero would be computed from zeros. The card waits for every
* read either way, so reading at the trigger costs what reading the next layer ahead behind the
* same drain did.
*
* A layer the count source cannot give counts for (the first pass, before any report) is read
* whole, and since that read needs no counts it goes ahead of time as before: at the pass's
* first op for the first routed layer, at a layer's trigger for the next one, into the buffer
* just released.
*
* So is every layer of a pass large enough that its rows route nearly every expert, kWholeRows
* rows an expert on average by the model's expert count and top-k (whole_rows()). An exact read
* takes the same bytes there, and each layer costs the card's work plus the drive's, since the
* card idles behind the drain while the drive reads. A whole read needs no counts, so nothing
* drains the stream, and the drive reads the next layer while the card computes the one before.
* At 64 rows an expert, one routed an eighth as often as the average is left out of about one
* pass in 3000, and read for nothing then. Smaller passes skip enough to pay for the drain: at
* decode nearly every file-tier expert.
*
* the pass's first op read the first routed layer the pass issues, if it is read whole
* a layer's first op release the layer before (record its buffer free on the stream,
* publish null), read this layer unless read ahead, wait on its
* copies, and read the next layer ahead if it is read whole -- its
* copies queue behind the free event of the buffer it takes
* a repeat of that op another slice of rows: read what its counts route that the earlier
* slices' did not, and wait on those copies
* the pass's end release whatever is still held
*
* A layer is released when the next one starts, not at its own last op: a routed block that slices
* a large step into passes of `rows` tokens issues its expert ops once per slice, so a release at
* the last op would leave the next slice reading null. Repeats of the current layer's first op do
* nothing.
* the last op would leave the next slice reading null. Each slice routes its own rows, which is
* why a repeat reads again.
*
* The read blocks the issuing thread while the card runs what was issued before it. A layer's
* file-tier part is gigabytes against milliseconds of compute, so the step is drive-bound either
* way; a reader thread would gain little and add a second writer of the residency table.
* Every read that issued a copy is waited on, a hot-cache admission's or a pool deposit's as much
* as a staged unit's: all are published settled, so the wait is the only thing between the GEMM
* and the slot's previous bytes.
*
* The read blocks the issuing thread while the card runs what was issued before it; a reader
* thread would gain little and add a second writer of the residency table.
*
* A layer is read ahead only when the pass will issue it (a bound learned per draft_pass from the
* last pass of that kind), so a trunk pass does not read the MTP head's layer. */
* last pass of that kind), so a trunk pass does not read the MTP head's layer.
*
* ---- which units -------------------------------------------------------------------------------
*
* Under a dynamic plan the pool is a cache of the file tier: a deposit may relabel a pooled unit
* back to the file tier (Mover::stage_file_units). A pooled unit the plan put in the pool is then
* on the file tier too, so the stager covers every movable routed unit of a class with file-tier
* units, not only the plan's file-tier ones, and tells the mover so (Mover::cover_file_units); a
* trigger whose layer has nothing on the file tier skips the read and its drain. Where covering
* them would interleave two layers' spans, only the plan's file-tier units are covered, and the
* mover relabels none of the others. */
class FileStager final : public OpStager {
public:
~FileStager() override;
/* Routing-aware reads: the engine binds a source of the layer's per-expert routing
* counts for the current pass (the router reports them to the Ctx before the layer's
* first expert op, which is the stager's trigger). Returns the device pointer of
* `n_expert` i32 counts, or null when the layer has not reported this pass — the
* caller then reads the whole layer. Null `routes` reads whole layers. */
/* Routing-aware reads: the engine binds a source of a layer's per-expert routing counts
* (Ctx::route_counts_device). It returns the device pointer of `n_expert` i32 counts that the
* layer's router rewrites every pass before the layer's first expert op, which is the
* stager's trigger, or null when it has none (the layer has not reported yet) -- the stager
* then reads the whole layer. Null `routes` reads whole layers. */
using RouteCounts = const int32_t* (*)(void* ud, int32_t layer, int64_t* n_expert);
/* Binds the routed layers with file-tier units and the ops that read them, over the mover's
* two file buffers. Leaves enabled() false when no routed unit is on the file tier. Refuses a
* plan whose routed layers are read by interleaved ops, since a file-tier unit has no other
* address to fall back on. */
* plan whose routed file-tier layers are read by interleaved ops, since a file-tier unit has
* no other address to fall back on. */
int init(const Program& prog, const Plan& plan, Mover* mover,
RouteCounts routes = nullptr, void* routes_ud = nullptr);
bool enabled() const { return !layers_.empty(); }
size_t n_layers() const { return layers_.size(); }
int64_t buffer_bytes() const { return cap_; }
/* Stream waits on the stager's copies so far, one per read that issued any. Tests read it. */
int64_t waits() const { return waits_; }
/* The smallest pass, in tokens, whose layers are read whole and ahead (see "which experts"),
* or 0 when every pass is read exactly (no routing source, or the model's top-k unknown). */
int64_t whole_rows() const { return whole_rows_; }
static constexpr int64_t kWholeRows = 64;
bool begin_pass(const RadBatch* b) override;
int before_op(rad_op h, RadStream s, bool* resync) override;
@@ -262,7 +307,8 @@ public:
private:
using Layer = StagedLayer;
std::vector<Layer> layers_; /* the routed layers with file-tier units, in first-op order */
int64_t waits_ = 0;
std::vector<Layer> layers_; /* the routed layers the stager covers, in first-op order */
std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */
Mover* mover_ = nullptr;
@@ -272,16 +318,15 @@ private:
void* routes_ud_ = nullptr;
int32_t* scratch_ = nullptr; /* pinned, for the trigger's blocking counts copy */
int64_t scratch_n_ = 0;
std::vector<int32_t> skipped_[2]; /* per buffer: units not read, nulled at release */
/* Per buffer: units the stager read into hot-cache slots. Unlike the
* staged ones they keep their publications when the buffer is released — the slot is
* their address from here on, until heat evicts one. */
std::vector<int32_t> promoted_[2];
/* Per buffer: what its layer's reads staged (nulled at release), skipped (likewise) and read
* into hot-cache slots (whose publications outlive the buffer -- the slot is their address
* until heat evicts one). */
Mover::FileRead rd_[2];
std::vector<int32_t> again_; /* a repeat's candidates: the layer's skipped units */
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
RadEvent free_[2] = { nullptr, nullptr }; /* behind the ops that read a buffer's layer */
bool free_rec_[2] = { false, false };
std::vector<int32_t> staged_[2];
int start(int32_t li, RadStream s);
bool pending_[2] = { false, false }; /* copies no stream has waited on yet */
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
int32_t cur_ = -1; /* the layer whose ops are being issued */
@@ -290,9 +335,18 @@ private:
int32_t pass_kind_ = 0;
int32_t last_issued_ = -1;
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
int64_t whole_rows_ = 0;
bool whole_ = false; /* this pass reads every layer whole (whole_rows) */
bool will_issue(int32_t li) const;
int start(int32_t li);
/* Whether layer `li` is read with counts, at its own trigger; otherwise it is read whole,
* and may be read ahead. */
bool counted(int32_t li) const;
/* The counts of the rows about to run, copied back behind the router on `s`, or null. */
int counts(int32_t li, RadStream s, const int32_t** ecnt, int32_t* n_expert);
int start(int32_t li, RadStream s, bool* resync);
int top_up(int32_t li, RadStream s, bool* resync);
int wait(int32_t b, RadStream s);
int finish(int32_t b, RadStream s);
};
+4
View File
@@ -905,6 +905,10 @@ struct Config {
/* --ngram-placement ram=DIR: the pinned n-gram copy is the file DIR/ngram-<id>.tab (a tmpfs),
* mapped shared, so engines on separate cards hold one table. Empty: a private copy. */
std::string ngram_share_dir;
/* --ngram-placement disk=DIR: the table is read from its own file, DIR/ngram-<id>.bin, filled
* from the container at the first start, instead of from the container (a faster drive than
* the model's). Empty: from the container. */
std::string ngram_disk_dir;
TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk;
/* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
+28 -12
View File
@@ -782,13 +782,30 @@ const int32_t* Ctx::route_counts_device(int layer, int64_t* n_expert) const {
if (n_expert) *n_expert = 0;
if (layer < 0 || (size_t)layer >= route_.size()) return nullptr;
const RouteSlot& s = route_[(size_t)layer];
/* No step gate: route_report lands at the END of the block's passes (heat consumes it a
* step later), but the reported buffer is the block's own ecnt, whose CONTENT the router
* kernel rewrote this pass -- and the file stager's trigger runs after that router on the
* same stream, so a stream-ordered copy reads this pass's counts. The counts are indexed
* by the rank's local expert slot (the kernel subtracts expert_base), which is also what
* the mover's units carry. */
/* No step gate: route_report lands at the END of the block's passes, so at the file stager's
* trigger (the layer's first expert op) the pointer is the one the last pass reported. That
* is right only for a buffer whose address is the same in this pass: the block's own counts
* buffer, which its router rewrites every pass -- and the trigger runs after that router on
* the same stream, so a stream-ordered copy reads the counts of the rows about to run. The
* counts are indexed by the rank's local expert slot (the kernel subtracts expert_base),
* which is also what the mover's units carry. */
if (!s.routing.expert_count || s.reported < 0) return nullptr;
/* A transient buffer is at another offset at another arena level, and liveness lets a
* later buffer share its bytes, since no declared op reads the counts (the report is a
* handoff, not an op): the bytes under the last pass's pointer may be anything. A whole read
* is slow but right; counts read there could name a routed expert zero and leave it
* unread. Every architecture here declares the counts RAD_BUF_PERSIST. */
const char* p = (const char*)s.routing.expert_count;
const char* base = (const char*)arena_.base();
if (base && program_ && p >= base + program_->arena_fixed_bytes && p < base + arena_.bytes()) {
if (!route_transient_noted_) {
route_transient_noted_ = true;
RAD_WARN("rank %d: layer %d reports its routing counts in a transient buffer, so the "
"file stager reads its routed experts whole; declare the counts "
"RAD_BUF_PERSIST", rank_, layer);
}
return nullptr;
}
if (n_expert) *n_expert = s.routing.n_expert ? s.routing.n_expert : route_n_expert_;
return s.routing.expert_count;
}
@@ -961,12 +978,11 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
* issue the scatter only when they have some (and the second attention over a run read both
* ways, n_bidi, only on such a pass). */
if (b->enc || b->n_mm_rows > 0 || b->n_bidi > 0) return 0;
/* Legacy architecture plugins have no pass-key callback. Only refuse them when the resolved
* program contains a launcher explicitly marked as using live prefill splits, and this batch
* can issue a prefill, mixed, speculative-verify or draft query through it. */
if (!arch_pass_key_ &&
(b->phase == RAD_PHASE_PREFILL || b->phase == RAD_PHASE_MIXED || b->draft_pass != 0 ||
b->n_spec > 0)) {
/* A plugin with no pass-key callback cannot key a launch that splits its KV by the live
* context, so a prefill or mixed pass of a program holding such a launcher is not recorded.
* Its decode, verify and draft passes are: their launches get the keyed context bound in
* place of the live maximum (Ctx::issue_body). */
if (!arch_pass_key_ && (b->phase == RAD_PHASE_PREFILL || b->phase == RAD_PHASE_MIXED)) {
for (const IssuePlan& ip : issue_table_)
if (ip.row && ip.row->info &&
(ip.row->info->capabilities & RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT))
+7 -4
View File
@@ -332,10 +332,11 @@ public:
/* Called by the drain, so the ring knows which banks are still unread. */
void mark_credited(int layer, int bank);
const RadRouting* last_routing(int layer) const;
/* The device pointer of `layer`'s expert counts for the current step, with `n_expert` set,
* or null when the layer has not reported this step (a routing-aware file stager then
* reads the layer whole). The pointer is stream-ordered behind the router: a copy on the
* compute stream at the stager's trigger sees this pass's counts. */
/* The device pointer of the buffer `layer`'s router writes its expert counts to, as the
* layer last reported it, with `n_expert` set; null when the layer has not reported yet, or
* when the buffer is a transient one (a routing-aware file stager then reads the layer
* whole). The router rewrites it every pass before the layer's first expert op, so a copy on
* the compute stream at the stager's trigger sees the counts of the rows about to run. */
const int32_t* route_counts_device(int layer, int64_t* n_expert) const;
/* ---------------------------------------------------------- the placement seam */
@@ -778,6 +779,8 @@ private:
std::vector<RouteSlot> route_;
int64_t route_n_expert_ = 0;
/* route_counts_device has said once that a layer's counts are a transient buffer. */
mutable bool route_transient_noted_ = false;
/* A bank is one step's histograms for every layer: [kRouteBanks][n_layer][n_expert] in pinned
* host memory. A report copies a layer's counts into its row of the card-side
* [n_layer][n_expert] (an on-card copy that orders nothing else); the end of the pass copies
+10
View File
@@ -916,6 +916,16 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* entry per schema operand, the trailing optional ones the issue left out null. */
ip.args.n_t = std::max(n_opd, (int)p.n_opd_schema);
ip.args.kv_used_max_h = issue_kv_used_max_h(batch_, t, ip.args.n_t);
/* A plugin with no pass-key callback has its decode, verify and draft passes recorded
* (pass_key), and a played pass keeps the arguments it was recorded with, so a launch there
* must not read a bound the key does not: it gets the step's context bound plus its longest
* query, both keyed, which crosses a bucket every 1024 tokens or more (batch.cpp) instead of
* moving with every token. Its prefill and mixed passes are never recorded and keep the
* exact maximum. */
if (ip.args.kv_used_max_h > 0 && !arch_pass_key_ && batch_ &&
batch_->phase != RAD_PHASE_PREFILL && batch_->phase != RAD_PHASE_MIXED)
ip.args.kv_used_max_h = (int32_t)std::min<int64_t>(
INT32_MAX, (int64_t)batch_->max_ctx_len + batch_->max_q_len);
p.issued = true;
++n_issues_;
+36 -20
View File
@@ -119,8 +119,13 @@ static RadOperand opd_none() {
static int64_t rows_for(const SamplerConfig& c) {
/* One row per sampled position: a verify samples n_spec+1 positions per sequence, each with
* its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). */
return c.max_seqs * (int64_t)(c.max_spec + 1);
* its own RNG coordinate. Sized for the worst step, as the arena is (spec §3.1). A step
* carries at most max_tok tokens and samples at most one row per token, so a deep drafter
* at the default 256 sequences no longer sizes every plane for 256 * (depth + 1) rows; a
* drafter's greedy pass stages one row per drafting sequence, so never below max_seqs. */
const int64_t want = c.max_seqs * (int64_t)(c.max_spec + 1);
if (c.max_tok <= 0) return want;
return std::min(want, std::max(c.max_tok, c.max_seqs));
}
/* ================================================================== declare */
@@ -331,8 +336,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
RAD_TRY(stage_alloc());
declared_ = true;
RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows, %lld mask words "
RAD_INFO("sampler: %lld-token vocabulary (%lld this rank), %lld rows%s, %lld mask words "
"(%s per row)", (long long)cfg_.n_vocab, (long long)nv, (long long)rows,
rows < cfg_.max_seqs * (int64_t)(cfg_.max_spec + 1) ? " (the step's token bound)" : "",
(long long)mask_words_, humanb(mask_words_ * 4).c_str());
return RAD_OK;
}
@@ -1068,13 +1074,11 @@ int Sampler::build_greedy(int64_t n) {
any_ngram_wl_ = false;
any_couple_ = false;
cur_stage_ = greedy_stage_;
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from
* the staging, and a stale pair from an earlier request's build must not issue the ban over
* history that was not staged this step. The exemption plane needs no clear: `run` uploads
* it only beside an issued ban, every row that runs the ban has its words rewritten in full
* by the build that staged the pair (build_step), and rows below a zeroed pair are skipped
* by the op before they read a word. */
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
/* Nothing a step's build staged is written here: a drafter's pass is built right after the
* step's chain was issued, whose uploads read the pinned staging only when the stream reaches
* them, behind the step's forward. So the n-gram pairs stay as the step staged them and the
* ban is gated on any_ngram_, which this clears; before, the pairs were zeroed here and a
* banning step with drafter passes uploaded the zeros, so the ban never ran on the card. */
if (greedy_ready_) return RAD_OK;
for (int64_t i = 0; i < cap; ++i) {
DeviceSampleParams& p = greedy_stage_[i];
@@ -1097,27 +1101,32 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
const RadStream s = rad_stream(c);
bool any_mask = false, any_greedy = false, any_chain = false;
bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false;
bool any_penalty = false, any_dry = false, any_xtc = false;
bool any_topp = false, any_minp = false, any_typ = false, any_temp = false;
for (int64_t i = 0; i < n_seq_; ++i) {
const DeviceSampleParams& p = cur_stage_[i];
any_mask |= (p.flags & RAD_SP_MASK) != 0;
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
any_dry |= (p.flags & RAD_SP_DRY) != 0;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
/* The pair plane is read directly, not through cur_stage_: it is per-step staging the
* LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair),
* so it agrees with cur_stage_ by builder contract. A new builder must keep that
* contract: stage the pair with the params, zero it with the greedy ones. */
any_ngram |= ngram_stage_[2 * i] > 0;
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
else {
any_chain = true;
/* sample_temp leaves a row at temperature <= 0 or exactly 1 as it is */
any_temp |= p.temp > 0.0f && p.temp != 1.0f;
any_topp |= p.top_p < 1.0f;
any_minp |= p.min_p > 0.0f;
any_typ |= p.typical_p < 1.0f;
/* The cuts only remove candidates, and a top-1 row has one: a greedy row over a split
* vocabulary or asking for logprobs, and every row of a drafter's greedy pass. Every
* implementation keeps it (top-p and min-p keep the best, typical keeps a lone
* candidate, XTC needs two above its threshold), so such a row issues none of them;
* nor does a top_p or typical_p outside (0, 1), which every kernel skips. A drafter's
* greedy pass under a split vocabulary, whose rows are zeroed, issued top-p and
* typical every round: two launches with a max and a sum over the candidate width a
* row, for nothing. */
if (p.top_k != 1) {
any_topp |= p.top_p > 0.0f && p.top_p < 1.0f;
any_minp |= p.min_p > 0.0f;
any_typ |= p.typical_p > 0.0f && p.typical_p < 1.0f;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
}
}
}
@@ -1129,6 +1138,13 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
return RAD_E_STATE;
}
/* The ban runs only for a build_step build in which some row's staged history holds a whole
* n-gram (any_ngram_; build_greedy clears it). A shorter one bans nothing, however the op is
* implemented, so neither the op nor its planes are issued for it. The pair plane is not
* scanned for a row with a positive n: a drafter's greedy build leaves it as the step staged
* it (see build_greedy). */
const bool any_ngram = any_ngram_;
/* Async copies on the compute stream, only of what some row reads. The mask is 19 KiB per
* constrained sequence at a 151K vocab, which keeps a host-side grammar affordable
* (spec §13). */
+12 -2
View File
@@ -106,6 +106,12 @@ struct SamplerConfig {
int64_t max_seqs = 0; /* the largest number of sequences one step may carry */
int64_t max_hist = 2048; /* the penalty window bound; a longer request is truncated */
int max_spec = 0;
/* The step's token bound (--max-num-batched-tokens), 0 for none. A step samples one row per
* token it verifies or completes, and the model's logits rows are capped here too
* (rad_arch.h, max_logit_rows), so rows past it could never be staged; the planes are sized
* for min(max_seqs * (max_spec + 1), max(max_tok, max_seqs)). Never below max_seqs: a drafter
* pass stages one greedy row per sequence it drafts for (build_greedy). */
int64_t max_tok = 0;
int rank = 0;
int world_size = 1;
/* This rank's first vocabulary row. sample_topk adds it to the candidate ids it packs into
@@ -218,6 +224,9 @@ public:
* meaningful only where the row carries RAD_SP_MASK. */
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
int64_t mask_words() const { return mask_words_; }
/* Staged row `row`'s n-gram ban pair {n, window}, as the last build_step staged it: a greedy
* build leaves it, since that step's upload may not have read it yet. */
const int32_t* staged_ngram(int64_t row) const { return ngram_stage_ + 2 * row; }
/* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries
* none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */
const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; }
@@ -344,8 +353,9 @@ private:
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
* passed to sample_dry. */
bool any_brk_ = false;
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use,
* so this only decides whether that plane is uploaded and the op issued. */
/* Whether any row this step runs the n-gram ban over a history at least its n-gram long; a
* shorter one bans nothing. Its history is the plane the penalties use, so this only decides
* whether that plane is uploaded and the op issued. Cleared by build_greedy. */
bool any_ngram_ = false;
/* Whether any banned row this step whitelists a column of this rank's shard; only then is
* the exemption plane uploaded and passed to sample_ngram_ban. */
+55 -3
View File
@@ -666,6 +666,57 @@ static std::vector<LogprobEntry> kept_logprobs(const std::vector<LogprobEntry>&
return std::vector<LogprobEntry>(lp.begin(), lp.begin() + (long)lp_before_cut(lp, 0, cut));
}
/* How many trailing bytes of a running choice's text are held back for its stop strings: the
* longest tail that is a proper prefix of one of them (core/text's Detokenizer holds back the
* same in what it has not returned). Every byte before that tail is final. A stop string that
* began there would already be complete in `text`, and pump() would have cut it, or it can no
* longer be completed, since the text only grows at its end. So this holds back exactly what
* pump() may yet cut, for any decoder: one that leaves stop strings to the server (iface.h), and
* core/text's, which cannot see a stop the server's scan can find in the U+FFFD it returned for
* a byte that was not UTF-8. A blanket (longest stop - 1) bytes, which this replaced, delayed
* every delta, the first one included, by up to a 4 KiB stop's worth of text.
*
* Run on every drain of every running choice, so its cost is bounded three ways:
*
* - Only the bytes not yet on the wire (`emitted` on) can be held back, and the tail never
* starts before them: a tail that began earlier would have been a longer one at the drain
* that sent those bytes. So the tails looked at are the ones in what the drain adds to what
* it held back, however long the stop strings are.
* - A tail is compared only where it starts with a byte some stop string starts with.
* - The comparisons share a budget (kStopTailBudget: a stop string looked at costs one, and
* each byte compared one more). A client sets its stop strings (64 of up to 4 KiB) and
* steers the text, and text that keeps almost matching long stop strings would cost a drain
* up to 4095 tails times 64 strings times their length. Past the budget the whole unsent
* window, up to the longest stop less a byte, is held back: more than the tail, never less,
* so nothing of a stop string is sent, and as late as the blanket hold-back this replaced.
* The next drain tries again. */
constexpr size_t kStopTailBudget = size_t(1) << 14;
static size_t stop_prefix_tail(std::string_view text, size_t emitted,
const std::vector<std::string>& stops, size_t maxstop) {
const size_t unsent = text.size() > emitted ? text.size() - emitted : 0;
const size_t limit = std::min(unsent, maxstop > 0 ? maxstop - 1 : 0);
bool starts[256] = {};
for (const std::string& s : stops)
if (s.size() > 1) starts[(unsigned char)s[0]] = true;
size_t budget = kStopTailBudget;
for (size_t n = limit; n > 0; --n) {
const char* tail = text.data() + text.size() - n;
if (!starts[(unsigned char)*tail]) continue;
for (const std::string& s : stops) {
if (budget == 0) return limit;
--budget;
if (s.size() <= n || s[0] != *tail) continue;
size_t i = 1; /* s[0] is known to match */
while (i < n && s[i] == tail[i]) ++i;
if (i == n) return n;
if (budget < i) return limit;
budget -= i;
}
}
return 0;
}
bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
bool progress = false;
SinkToken buf[128];
@@ -1228,15 +1279,16 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
}
}
if (g.delta && g.sink->n_produced() > 0) out += g.delta->started();
/* While the choice runs, hold back the longest stop string minus one byte, or the
* start of a stop sequence would already be on the wire when it is recognised.
/* While the choice runs, hold back a tail that may still become a stop string
* (stop_prefix_tail), or its start would already be on the wire when it is
* recognised.
*
* Only while running: a closed choice has no more bytes coming, so its whole text is
* the answer, including a trailing `\` or partial `\uXXXX` the escape rule would
* otherwise hold back. */
size_t safe = g.text.size();
if (!g.closed) {
if (maxstop > 1) safe = safe > maxstop - 1 ? safe - (maxstop - 1) : 0;
if (maxstop > 1) safe -= stop_prefix_tail(g.text, g.emitted, st->r.stop, maxstop);
safe = json_stable_prefix(std::string_view(g.text.data(), safe));
if (safe <= g.emitted) continue;
}
+2 -1
View File
@@ -887,7 +887,8 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
const int e = mm::h264_roundtrip(f, info.image_crf, &rt, &why);
if (e < 0) {
ApiError err = err_bad("input_reference", "the picture could not be prepared: " + why);
if (e != RAD_E_INVAL) { err.status = 503; err.type = "server_error"; }
/* A build without an H.264 codec cannot prepare one at all: 501, not a transient 503. */
if (e != RAD_E_INVAL) { err.status = e == RAD_E_UNSUPPORTED ? 501 : 503; err.type = "server_error"; }
return error_response(err, req.peer);
}
f = std::move(rt);