Archived
Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port
Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
mtp_couple_propose.
Also ignores /baseline-models/ (local model copies).
Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
45f3b510c7
365 files changed
+56942
-6331
No files matched your search
@@ -23,6 +23,11 @@ list(APPEND RAD_CORE_SRC ${_top})
|
||||
add_library(rad_core STATIC ${RAD_CORE_SRC})
|
||||
target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads)
|
||||
target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}")
|
||||
if(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK)
|
||||
# Scheduler is embedded in Engine and its test-only callback changes its class layout.
|
||||
# Propagate the definition to every consumer to keep all translation units ABI-consistent.
|
||||
target_compile_definitions(rad_core PUBLIC RAD_ENABLE_KV_ROLLBACK_TEST_HOOK=1)
|
||||
endif()
|
||||
target_include_directories(rad_core PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
${CMAKE_SOURCE_DIR}/abi
|
||||
|
||||
@@ -137,6 +137,7 @@ public:
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
int declare_audio_generator(const RadAudioGenDecl* d);
|
||||
int declare_video_generator(const RadVideoGenDecl* d);
|
||||
int declare_shape_generator(const RadShapeGenDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
/* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the
|
||||
|
||||
+137
-12
@@ -1201,6 +1201,11 @@ int Builder::declare_logits(rad_buf b) {
|
||||
prog_.vgen_str.name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_logits: this program already declared the shape generator '%s'",
|
||||
prog_.sgen_name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
prog_.logits_buf = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1241,6 +1246,11 @@ int Builder::declare_pooled(rad_buf b) {
|
||||
prog_.vgen_str.name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_pooled: this program already declared the shape generator '%s'",
|
||||
prog_.sgen_name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const RadBufDecl& d = prog_.buffers[b].decl;
|
||||
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
|
||||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
|
||||
@@ -1329,6 +1339,11 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
(int)d->one_grid);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->bidirectional != 0 && (d->bidirectional != 1 || audio)) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': bidirectional %d -- 0, or 1 for a picture and video "
|
||||
"encoder", nm, (int)d->bidirectional);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
slot = *d;
|
||||
slot_name = nm;
|
||||
slot.name = nullptr; /* the plugin's storage; the name is the copy */
|
||||
@@ -1348,12 +1363,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
|
||||
prog_.is_audio_generator() || prog_.is_video_generator()) {
|
||||
prog_.is_audio_generator() || prog_.is_video_generator() || prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
|
||||
"generates text, embeds, makes images, audio or video -- one of the five",
|
||||
nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
|
||||
"generates text, embeds, makes images, audio, video or shapes -- one of "
|
||||
"the six", nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
|
||||
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
|
||||
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
|
||||
: prog_.is_audio_generator() ? "an audio generator"
|
||||
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
|
||||
@@ -1505,13 +1521,14 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
|
||||
prog_.generator.layout != 0 || prog_.is_video_generator()) {
|
||||
prog_.generator.layout != 0 || prog_.is_video_generator() || prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a "
|
||||
"program generates text, embeds, makes images, audio or video -- one of "
|
||||
"the five", nm,
|
||||
"program generates text, embeds, makes images, audio, video or shapes -- "
|
||||
"one of the six", nm,
|
||||
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
|
||||
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
|
||||
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
|
||||
: prog_.generator.layout != 0 ? "an image generator"
|
||||
: prog_.is_video_generator() ? "a video generator" : "a shape generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!d->tmpl && !d->tmpl_plain) {
|
||||
@@ -1682,13 +1699,14 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
|
||||
prog_.generator.layout != 0 || prog_.is_audio_generator()) {
|
||||
prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a "
|
||||
"program generates text, embeds, makes images, audio or video -- one of "
|
||||
"the five", nm,
|
||||
"program generates text, embeds, makes images, audio, video or shapes -- "
|
||||
"one of the six", nm,
|
||||
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
|
||||
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
|
||||
: prog_.generator.layout != 0 ? "an image generator" : "an audio generator");
|
||||
: prog_.generator.layout != 0 ? "an image generator"
|
||||
: prog_.is_audio_generator() ? "an audio generator" : "a shape generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) {
|
||||
@@ -1903,6 +1921,108 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The shape generator (rad_declare_shape_generator). Checked here rather than at the first request:
|
||||
* the picture's geometry, the sampler, the grid and the field's buffer, which the core reads back
|
||||
* after every query pass. */
|
||||
int Builder::declare_shape_generator(const RadShapeGenDecl* d) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "declare_shape_generator after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!d) { err(RAD_E_INVAL, "declare_shape_generator: null declaration"); return RAD_E_INVAL; }
|
||||
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
|
||||
if (prog_.is_shape_generator()) {
|
||||
err(RAD_E_STATE, "declare_shape_generator: '%s' was already declared; '%s' is a second one",
|
||||
prog_.sgen_name.c_str(), nm);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE ||
|
||||
prog_.generator.layout != 0 || prog_.is_audio_generator() || prog_.is_video_generator()) {
|
||||
err(RAD_E_STATE, "declare_shape_generator '%s': this program already declared %s; a "
|
||||
"program generates text, embeds, makes images, audio, video or shapes -- "
|
||||
"one of the six", nm,
|
||||
prog_.logits_buf != RAD_NULL_HANDLE ? "logits"
|
||||
: prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output"
|
||||
: prog_.generator.layout != 0 ? "an image generator"
|
||||
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (d->canvas < 1 || d->canvas > 4096 || !(d->border_ratio >= 0.0 && d->border_ratio < 1.0) ||
|
||||
d->enc_patch < 1 || d->enc_size < d->enc_patch || d->enc_size > 4096 ||
|
||||
d->enc_size % d->enc_patch != 0) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': the picture is out of range (canvas %lld, "
|
||||
"border %g, encoder %lld in patches of %lld): the canvas 1..4096, the "
|
||||
"border in [0, 1), the encoder's side 1..4096 and a whole number of "
|
||||
"patches", nm, (long long)d->canvas, d->border_ratio,
|
||||
(long long)d->enc_size, (long long)d->enc_patch);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!std::isfinite(d->pix_mean[c]) || !(d->pix_std[c] > 0.0) ||
|
||||
!std::isfinite(d->pix_std[c])) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': channel %d's mean %g and deviation %g "
|
||||
"must be finite and the deviation positive", nm, c, d->pix_mean[c],
|
||||
d->pix_std[c]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->latent_rows < 1 || d->latent_channels < 1 || d->step_rows < 2 * d->latent_rows) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': a latent of %lld rows of %lld channels "
|
||||
"and a step of %lld rows; a step holds both branches' latents", nm,
|
||||
(long long)d->latent_rows, (long long)d->latent_channels, (long long)d->step_rows);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->default_steps < 2 || d->max_steps < d->default_steps || d->max_steps > 1000 ||
|
||||
!(d->default_guidance >= 0.0) || !std::isfinite(d->default_guidance)) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': the sampler is out of range (%lld steps "
|
||||
"by default, %lld at most, guidance %g): at least 2 grid points, at most "
|
||||
"1000, the guidance finite and not negative", nm,
|
||||
(long long)d->default_steps, (long long)d->max_steps, d->default_guidance);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!(d->bounds > 0.0) || !std::isfinite(d->bounds) || !std::isfinite(d->level) ||
|
||||
d->min_resolution < 2 || d->default_resolution < d->min_resolution ||
|
||||
d->max_resolution < d->default_resolution || d->max_resolution > 2048) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': the field is out of range (bounds %g, "
|
||||
"level %g, resolution %lld in %lld..%lld): the bounds positive, the level "
|
||||
"finite, the resolutions in order from 2 to 2048", nm, d->bounds,
|
||||
d->level, (long long)d->default_resolution, (long long)d->min_resolution,
|
||||
(long long)d->max_resolution);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->max_lanes < 1 || d->max_query < 1) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': %lld lanes and %lld points a query pass; "
|
||||
"both at least 1", nm, (long long)d->max_lanes, (long long)d->max_query);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t n_patch = (d->enc_size / d->enc_patch) * (d->enc_size / d->enc_patch);
|
||||
const int64_t rows = std::max({ d->step_rows, d->max_query, n_patch, d->latent_rows });
|
||||
if (prog_.ctx.max_tok < rows) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': a pass carries %lld rows and this one's "
|
||||
"largest is %lld", nm, (long long)prog_.ctx.max_tok, (long long)rows);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const rad_buf h = d->field_out;
|
||||
if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out %u is not a declared buffer", nm,
|
||||
(unsigned)h);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const RadBufDecl& ob = prog_.buffers[h].decl;
|
||||
if (ob.dtype != RAD_F32 || ob.domain != RAD_DOMAIN_DEVICE ||
|
||||
decl_numel(ob.rank, ob.shape) < d->max_query) {
|
||||
err(RAD_E_INVAL, "declare_shape_generator '%s': field_out '%s' must be a device f32 "
|
||||
"buffer of at least %lld elements", nm, prog_.buffers[h].name.c_str(),
|
||||
(long long)d->max_query);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.sgen_name = nm;
|
||||
prog_.shape_gen = *d;
|
||||
/* As for the other generators: the Program is moved after declare; the name lives in
|
||||
* sgen_name. */
|
||||
prog_.shape_gen.name = nullptr;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Validates the draft head at declare rather than at the first draft pass, where a bad decl would
|
||||
* only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized
|
||||
* its buffers with. */
|
||||
@@ -2745,6 +2865,11 @@ int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) {
|
||||
return B(b)->declare_video_generator(d);
|
||||
}
|
||||
|
||||
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_shape_generator(d);
|
||||
}
|
||||
|
||||
void rad_note(RadBuilder* b, const char* f, ...) {
|
||||
if (!b) return;
|
||||
va_list ap;
|
||||
|
||||
+58
-12
@@ -76,8 +76,10 @@ static const Flag g_flags[] = {
|
||||
"(default) leaves decode rows and new requests their room,\n"
|
||||
"off takes the whole step, N holds the chunk to N tokens" },
|
||||
{ "--prefill-interleave", "N", "decode-only steps after each prefill chunk while other\n"
|
||||
"sequences decode, at most 64; 0 (default) lets every step\n"
|
||||
"carry a chunk" },
|
||||
"sequences decode, at most 64; auto fits them in a quarter\n"
|
||||
"of the chunk step's time, auto:SHARE in SHARE of it (0-4];\n"
|
||||
"0 lets every step carry a chunk; served default auto:1\n"
|
||||
"(0 under --deterministic, KL mode, generators)" },
|
||||
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
|
||||
"recompute gate before reclaiming cache blocks and\n"
|
||||
"preempting the lowest-priority running request; 0\n"
|
||||
@@ -87,7 +89,10 @@ static const Flag g_flags[] = {
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--gpu-memory-mib", "N", "VRAM claimed on every card; the rest is left unclaimed.\n"
|
||||
"Not with --gpu-headroom-mib" },
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96).\n"
|
||||
"Not with --gpu-memory-mib" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
|
||||
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
|
||||
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
|
||||
@@ -568,7 +573,22 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0;
|
||||
else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--prefill-interleave")) { if (!num(0, 64, &c->prefill_interleave)) return RAD_E_INVAL; }
|
||||
else if (S("--prefill-interleave")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->prefill_interleave_set = true;
|
||||
if (!std::strcmp(v, "auto")) { c->prefill_interleave = -1; c->prefill_interleave_share = 0.25; }
|
||||
else if (!std::strncmp(v, "auto:", 5)) {
|
||||
/* auto:SHARE -- decode-only steps for up to SHARE x a chunk step's time, 0 < SHARE <= 4 */
|
||||
char* e = nullptr;
|
||||
const double sh = std::strtod(v + 5, &e);
|
||||
if (e == v + 5 || *e || !(sh > 0.0 && sh <= 4.0)) {
|
||||
RAD_ERR("--prefill-interleave %s: auto:SHARE takes a share in (0, 4]", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->prefill_interleave = -1; c->prefill_interleave_share = sh;
|
||||
}
|
||||
else if (!parse_int(a.c_str(), v, 0, 64, &c->prefill_interleave)) return RAD_E_INVAL;
|
||||
}
|
||||
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
|
||||
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
|
||||
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
|
||||
@@ -587,14 +607,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
* old launch lines at the flags that move the split. */
|
||||
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
|
||||
RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
|
||||
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
|
||||
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay "
|
||||
"on the card", a.c_str());
|
||||
"the model needs. --gpu-headroom-mib or --gpu-memory-mib take card space away, "
|
||||
"--max-model-len and --max-num-seqs bound the cache, and --host-pool-mib "
|
||||
"decides which experts stay on the card", a.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */
|
||||
else if (S("--gpu-headroom-mib") || S("--gpu-headroom"))
|
||||
{ if (!num(0, INT64_MAX, &c->gpu_headroom_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--gpu-memory-mib")) { if (!num(1, INT64_MAX, &c->gpu_memory_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--host-headroom-mib")) { if (!num(0, INT64_MAX, &c->host_headroom_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--kv-cache-dtype")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
@@ -641,7 +662,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()) {
|
||||
@@ -650,11 +671,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;
|
||||
}
|
||||
@@ -1130,6 +1163,14 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* --gpu-memory-mib claims the card; --gpu-headroom-mib leaves it unclaimed. The alias
|
||||
* --gpu-headroom is recorded as --gpu-headroom-mib, so it is covered. */
|
||||
if (c->given.count("--gpu-memory-mib") && c->given.count("--gpu-headroom-mib")) {
|
||||
RAD_ERR("--gpu-memory-mib claims the card and --gpu-headroom-mib leaves it unclaimed; "
|
||||
"give one");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Prompt lookup alone: the window is its K, stated once. */
|
||||
if (c->spec_ngram_min > c->spec_ngram_max) {
|
||||
RAD_ERR("--spec-ngram-min %d is longer than --spec-ngram-max %d", c->spec_ngram_min,
|
||||
@@ -1322,12 +1363,16 @@ const ShowRow kShow[] = {
|
||||
return c.busy_prefill_chunk < 0 ? std::string("auto")
|
||||
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
|
||||
{ "--prefill-interleave", [](const Config& c) {
|
||||
return c.prefill_interleave > 0 ? num(c.prefill_interleave) : std::string("off"); } },
|
||||
return c.prefill_interleave > 0 ? num(c.prefill_interleave)
|
||||
: c.prefill_interleave < 0 ? "auto:" + std::to_string(c.prefill_interleave_share)
|
||||
: std::string("off"); } },
|
||||
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
|
||||
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
|
||||
{ "--max-model-len", [](const Config& c) {
|
||||
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
|
||||
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
|
||||
{ "--gpu-memory-mib", [](const Config& c) {
|
||||
return c.gpu_memory_mib ? num(c.gpu_memory_mib) : std::string("0 (use --gpu-headroom-mib)"); } },
|
||||
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
|
||||
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
|
||||
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
|
||||
@@ -1340,7 +1385,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) {
|
||||
|
||||
+61
-16
@@ -589,7 +589,7 @@ KernelRec* kernel_for(const void* stub, int ord, std::string* why) {
|
||||
struct Stream {
|
||||
uint64_t magic = kStreamMagic;
|
||||
int ord = 0;
|
||||
uint32_t id = 0; /* index into g_queue_by_id, never reused */
|
||||
uint32_t id = 0; /* queue_of's key, never reused (see there) */
|
||||
hsa_agent_t agent{};
|
||||
hsa_queue_t* q = nullptr;
|
||||
uint64_t mask = 0;
|
||||
@@ -623,12 +623,27 @@ struct Stream {
|
||||
void unlock() { busy.store(false, std::memory_order_release); }
|
||||
};
|
||||
|
||||
/* Every queue this process has made, by an id that is never reused, so "packet i of queue n"
|
||||
* stays meaningful after the queue is destroyed. A destroyed queue's entry is null; everything
|
||||
* it held has been consumed. */
|
||||
/* Every live queue, by an id that is never reused, so "packet i of queue n" stays meaningful after
|
||||
* the queue is destroyed: queue_of answers null for a destroyed queue's id, and everything it held
|
||||
* has been consumed. At most kMaxQueues are live at once; a destroyed queue's slot is taken again
|
||||
* under a new generation, id = generation * kMaxQueues + slot, so a stale id never names the
|
||||
* slot's next queue. */
|
||||
constexpr uint32_t kMaxQueues = 1024;
|
||||
std::atomic<hsa_queue_t*> g_queue_by_id[kMaxQueues];
|
||||
std::atomic<uint32_t> g_next_queue_id{0};
|
||||
std::atomic<uint32_t> g_queue_id_at[kMaxQueues]; /* the id holding each slot now */
|
||||
std::mutex g_queue_slot_mu;
|
||||
std::vector<uint32_t> g_queue_free; /* destroyed queues' slots */
|
||||
uint32_t g_queue_next_slot = 0;
|
||||
uint32_t g_queue_gen[kMaxQueues];
|
||||
|
||||
/* The queue an id names, or null once it is destroyed. The slot's id is stored before its queue
|
||||
* (release), so a queue read here that belongs to a later generation is seen with that
|
||||
* generation's id and refused. */
|
||||
inline hsa_queue_t* queue_of(uint32_t id) {
|
||||
const uint32_t slot = id % kMaxQueues;
|
||||
hsa_queue_t* q = g_queue_by_id[slot].load(std::memory_order_acquire);
|
||||
return g_queue_id_at[slot].load(std::memory_order_acquire) == id ? q : nullptr;
|
||||
}
|
||||
|
||||
inline Stream* ours(const void* s) {
|
||||
if ((uintptr_t)s < 4096) return nullptr;
|
||||
@@ -1127,6 +1142,9 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
|
||||
if (!gx || !gy || !gz) return RAD_OK;
|
||||
if (gx > UINT32_MAX || gy > UINT32_MAX || gz > UINT32_MAX) return RAD_E_INVAL;
|
||||
if ((uint64_t)k->group_size + shm > 65536) return RAD_E_INVAL;
|
||||
/* The packet's fields are 16 bits wide and the card runs at most 1024 work-items a group;
|
||||
* HIP refuses a larger block, and so does this. */
|
||||
if ((uint64_t)b.x * b.y * b.z > 1024) return RAD_E_INVAL;
|
||||
|
||||
alignas(64) unsigned char ka[kKargMax];
|
||||
const uint32_t n = (k->kernarg_size + 15u) & ~15u;
|
||||
@@ -1562,6 +1580,7 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) !=
|
||||
HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) {
|
||||
if (ka) hsa_amd_memory_pool_free(ka); /* allocated, then refused access */
|
||||
hsa_queue_destroy(s->q);
|
||||
device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s",
|
||||
d.host_kargs ? "pinned host memory" : "VRAM the host can write");
|
||||
@@ -1582,17 +1601,28 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
s->bounce = static_cast<char*>(bb);
|
||||
note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1);
|
||||
note_alloc(bb, kBounceBytes, -1);
|
||||
s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed);
|
||||
if (s->id >= kMaxQueues) {
|
||||
uint32_t slot = kMaxQueues;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
|
||||
if (!g_queue_free.empty()) {
|
||||
slot = g_queue_free.back();
|
||||
g_queue_free.pop_back();
|
||||
} else if (g_queue_next_slot < kMaxQueues) {
|
||||
slot = g_queue_next_slot++;
|
||||
}
|
||||
if (slot < kMaxQueues) s->id = g_queue_gen[slot]++ * kMaxQueues + slot;
|
||||
}
|
||||
if (slot >= kMaxQueues) {
|
||||
note_free(bb);
|
||||
note_free(ka);
|
||||
hsa_amd_memory_pool_free(bb);
|
||||
hsa_amd_memory_pool_free(ka);
|
||||
hsa_queue_destroy(s->q);
|
||||
device_set_error("rad_stream_create: more than %u streams in one process", kMaxQueues);
|
||||
device_set_error("rad_stream_create: more than %u streams live at once", kMaxQueues);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
g_queue_by_id[s->id].store(s->q, std::memory_order_release);
|
||||
g_queue_id_at[slot].store(s->id, std::memory_order_release);
|
||||
g_queue_by_id[slot].store(s->q, std::memory_order_release);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
G().streams.push_back(s.get());
|
||||
@@ -1604,14 +1634,24 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
void a_stream_destroy(RadStream rs) {
|
||||
Stream* s = ours(rs);
|
||||
if (!s) return;
|
||||
(void)stream_drain(s);
|
||||
/* Undrained (a closed gate, a fault), the queue may still be read by the card, and so may its
|
||||
* kernel argument ring: both are left allocated rather than freed under it. */
|
||||
if (const int rc = stream_drain(s); rc < 0) {
|
||||
RAD_WARN("device: a stream was destroyed with work it could not drain (%s); its queue and "
|
||||
"argument ring stay allocated", rad_strerror(rc));
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(G().streams_mu);
|
||||
auto& v = G().streams;
|
||||
for (size_t i = 0; i < v.size(); ++i) if (v[i] == s) { v.erase(v.begin() + (long)i); break; }
|
||||
}
|
||||
g_queue_by_id[s->id].store(nullptr, std::memory_order_release);
|
||||
g_queue_by_id[s->id % kMaxQueues].store(nullptr, std::memory_order_release);
|
||||
hsa_queue_destroy(s->q);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_queue_slot_mu);
|
||||
g_queue_free.push_back(s->id % kMaxQueues);
|
||||
}
|
||||
note_free(s->karg);
|
||||
note_free(s->bounce);
|
||||
hsa_amd_memory_pool_free(s->karg);
|
||||
@@ -1676,7 +1716,7 @@ bool xp_list_finished(int ord, uint32_t k);
|
||||
bool reusable(const Sig* g) {
|
||||
if (g->stamped || hsa_signal_load_relaxed(g->h) != 0) return false;
|
||||
for (const auto& w : g->waiters) {
|
||||
hsa_queue_t* q = g_queue_by_id[w.first].load(std::memory_order_acquire);
|
||||
hsa_queue_t* q = queue_of(w.first);
|
||||
if (q && hsa_queue_load_read_index_relaxed(q) <= w.second) return false;
|
||||
}
|
||||
const int32_t xd = g->xp_dev.load(std::memory_order_acquire);
|
||||
@@ -1902,7 +1942,7 @@ std::vector<Tape*> g_tape_retired;
|
||||
* kReserveMargin past it has launched, which proves it as in reserve(). */
|
||||
bool tape_idle(const Tape* t) {
|
||||
for (const auto& l : t->last) {
|
||||
hsa_queue_t* q = g_queue_by_id[l.first].load(std::memory_order_acquire);
|
||||
hsa_queue_t* q = queue_of(l.first);
|
||||
if (q && hsa_queue_load_read_index_scacquire(q) < l.second + kReserveMargin) return false;
|
||||
}
|
||||
return true;
|
||||
@@ -2574,6 +2614,7 @@ struct DmaQueue {
|
||||
* a queue while the engine runs on, and a ring the host thinks full would wait forever. */
|
||||
volatile uint32_t* fin = nullptr;
|
||||
uint32_t lists = 0; /* lists handed over; list k ends at ends[k % kDmaEnds] */
|
||||
uint64_t seen = 0; /* the most the room check has known read, under the lock */
|
||||
std::unique_ptr<uint64_t[]> ends;
|
||||
};
|
||||
constexpr uint32_t kDmaEnds = 4096;
|
||||
@@ -2818,22 +2859,26 @@ inline uint64_t dma_read(const DmaQueue* q) {
|
||||
uint64_t r = *q->rptr;
|
||||
if (q->fin) {
|
||||
const uint32_t k = *q->fin;
|
||||
if (k) r = std::max(r, q->ends[k % kDmaEnds]);
|
||||
/* ends[k % kDmaEnds] is list k's only while fewer than kDmaEnds lists are behind it. */
|
||||
if (k && q->lists - k < kDmaEnds) r = std::max(r, q->ends[k % kDmaEnds]);
|
||||
}
|
||||
return r;
|
||||
return std::max(r, q->seen);
|
||||
}
|
||||
|
||||
/* Writes `n` dwords to the ring; queue lock held. A packet never straddles the ring end: the tail
|
||||
* is padded with single-dword NOPs. The ring holds a few hundred layers' lists, so waiting for
|
||||
* room means the host is that far ahead of a stalled engine. */
|
||||
int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) {
|
||||
/* What was once known read stays read: a list number whose ends slot a later list has taken
|
||||
* cannot be used any more, and the read pointer alone may be behind it. */
|
||||
q->seen = dma_read(q);
|
||||
const uint64_t cap = kDmaRingBytes / 4;
|
||||
uint64_t at = (q->w / 4) & (cap - 1);
|
||||
const uint64_t pad = at + n > cap ? cap - at : 0;
|
||||
const uint64_t need = (pad + n) * 4;
|
||||
if (q->w + need - dma_read(q) > kDmaRingBytes) {
|
||||
Stall st("a full DMA ring");
|
||||
while (q->w + need - dma_read(q) > kDmaRingBytes) {
|
||||
while (q->w + need - (q->seen = dma_read(q)) > kDmaRingBytes) {
|
||||
if (G().faulted.load(std::memory_order_relaxed)) {
|
||||
device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full");
|
||||
return RAD_E_DEVICE;
|
||||
|
||||
@@ -406,7 +406,8 @@ int64_t dev_stuck_ms();
|
||||
constexpr int kTapeOverlapRun = 6;
|
||||
|
||||
/* ------------------------------------------------------------------ the allocation ledger
|
||||
* What rad_dev_alloc has handed out since process start, by RAD_MEM_* kind. It does not see a
|
||||
* By RAD_MEM_* kind: the bytes rad_dev_alloc has handed out and rad_dev_free has not taken back,
|
||||
* and the number of allocations since process start. It does not see a
|
||||
* kernel plugin that calls hipMalloc directly; see the ledger in dispatch.cpp. */
|
||||
void rad_dev_alloc_totals(int kind, int64_t* bytes, int64_t* count);
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <cstdint>
|
||||
@@ -172,6 +173,26 @@ struct Ledger {
|
||||
std::atomic<int64_t> count{0};
|
||||
};
|
||||
Ledger g_ledger[4]; /* indexed by RAD_MEM_*; rad_dev_alloc bounds the kind */
|
||||
/* Each live allocation's size, so rad_dev_free (which has none) takes it back off the ledger's
|
||||
* bytes: pinned ranges are freed and taken again during bring-up, and the pin-cap check reads the
|
||||
* ledger as what the process holds. Allocations are rare, never per step. */
|
||||
struct LiveAlloc { int64_t bytes; int kind; };
|
||||
std::mutex g_ledger_mu;
|
||||
std::unordered_map<void*, LiveAlloc> g_ledger_live;
|
||||
|
||||
void ledger_add(void* p, int64_t bytes, int kind) {
|
||||
g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
g_ledger_live[p] = LiveAlloc{ bytes, kind };
|
||||
}
|
||||
void ledger_drop(void* p) {
|
||||
if (!p) return;
|
||||
std::lock_guard<std::mutex> lk(g_ledger_mu);
|
||||
const auto it = g_ledger_live.find(p);
|
||||
if (it == g_ledger_live.end()) return;
|
||||
g_ledger[it->second.kind].bytes.fetch_sub(it->second.bytes, std::memory_order_relaxed);
|
||||
g_ledger_live.erase(it);
|
||||
}
|
||||
|
||||
/* Live event handles, counted here so the number is backend-independent; the only place an
|
||||
* event leaked at teardown shows. */
|
||||
@@ -450,7 +471,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
thread_local int64_t t_device_ordinal = 0;
|
||||
void* p = dev()->alloc(bytes, kind);
|
||||
if (p && kind >= 0 && kind < (int)std::size(rad::g_ledger)) {
|
||||
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
rad::ledger_add(p, bytes, kind);
|
||||
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
|
||||
const int64_t floor_ = rad::trace_floor();
|
||||
@@ -476,8 +497,7 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
return p;
|
||||
}
|
||||
void rad_dev_free(void* p, int kind) {
|
||||
/* The ledger counts allocations, not live bytes: rad_dev_free has no size. The engine frees
|
||||
* only at teardown, so the two agree while running. */
|
||||
rad::ledger_drop(p);
|
||||
dev()->free(p, kind);
|
||||
}
|
||||
void* rad_dev_host_ptr(void* p) { return dev()->host_ptr(p); }
|
||||
@@ -694,7 +714,7 @@ void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
}
|
||||
void* p = f(fd, foff, bytes);
|
||||
if (p) {
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
rad::ledger_add(p, bytes, RAD_MEM_HOST_MAPPED);
|
||||
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
return p;
|
||||
|
||||
+28
-3
@@ -20,6 +20,7 @@
|
||||
#include <condition_variable>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
@@ -723,6 +724,21 @@ constexpr int64_t kVmemGranule = RAD_ALIGN_POOL;
|
||||
|
||||
int64_t h_vmem_granularity(void) { return kVmemGranule; }
|
||||
|
||||
/* Each reservation's card, recorded at reserve: the thread that later commits into a pool, or
|
||||
* releases it at teardown, may have selected another card, and the pages count against the card
|
||||
* the range was reserved for (as the AQL backend's VRes does). Keyed by base. */
|
||||
struct VRange { char* end; int device; };
|
||||
std::mutex g_vres_mu;
|
||||
std::map<const char*, VRange> g_vres;
|
||||
|
||||
int vmem_device_of(const void* addr) {
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
auto it = g_vres.upper_bound((const char*)addr);
|
||||
if (it == g_vres.begin()) return t_device;
|
||||
--it;
|
||||
return (const char*)addr < it->second.end ? it->second.device : t_device;
|
||||
}
|
||||
|
||||
void* h_vmem_reserve(int64_t bytes, int64_t align) {
|
||||
if (bytes <= 0) return nullptr;
|
||||
if (align < kVmemGranule) align = kVmemGranule;
|
||||
@@ -740,11 +756,20 @@ void* h_vmem_reserve(int64_t bytes, int64_t align) {
|
||||
if (head) ::munmap(raw, head);
|
||||
const size_t tail = raw_len - head - (size_t)bytes;
|
||||
if (tail) ::munmap(base + bytes, tail);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vres[base] = VRange{ base + bytes, t_device };
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
void h_vmem_release(void* base, int64_t bytes) {
|
||||
if (base && bytes > 0) ::munmap(base, (size_t)bytes);
|
||||
if (!base || bytes <= 0) return;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_vres_mu);
|
||||
g_vres.erase((const char*)base);
|
||||
}
|
||||
::munmap(base, (size_t)bytes);
|
||||
}
|
||||
|
||||
int h_vmem_commit(void* addr, int64_t bytes) {
|
||||
@@ -755,7 +780,7 @@ int h_vmem_commit(void* addr, int64_t bytes) {
|
||||
device_set_error("vmem_commit(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
g_used[t_device].fetch_add(bytes, std::memory_order_relaxed);
|
||||
g_used[vmem_device_of(addr)].fetch_add(bytes, std::memory_order_relaxed);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -769,7 +794,7 @@ int h_vmem_decommit(void* addr, int64_t bytes) {
|
||||
device_set_error("vmem_decommit(%p, %lld): mmap failed", addr, (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g_used[t_device].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
g_used[vmem_device_of(addr)].fetch_sub(bytes, std::memory_order_relaxed);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+315
-7
@@ -6,6 +6,7 @@
|
||||
#include "gen/driver.h"
|
||||
#include "gen/audio_driver.h"
|
||||
#include "gen/video_driver.h"
|
||||
#include "gen/shape_driver.h"
|
||||
#include "kld.h"
|
||||
#include "mm/processor.h"
|
||||
#include "mm/media.h"
|
||||
@@ -41,10 +42,220 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
#include <string>
|
||||
#endif
|
||||
|
||||
namespace rad {
|
||||
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
namespace {
|
||||
struct KVRollbackTestEvidence {
|
||||
bool waiting_for_greedy = false;
|
||||
std::string report_path;
|
||||
uint64_t seq = 0;
|
||||
int step = -1;
|
||||
int proposals = 0;
|
||||
int accepted = -1;
|
||||
int32_t group = -1;
|
||||
int64_t prefix_before = 0;
|
||||
int64_t rollback_tokens_before = 0;
|
||||
int64_t rollback_to_tokens = 0;
|
||||
int64_t prefix_after_rollback = -1;
|
||||
int64_t first_block_pos = 0;
|
||||
int64_t block_size = 0;
|
||||
int64_t n_layers = 0;
|
||||
int64_t bytes_per_layer = 0;
|
||||
std::vector<int32_t> logical_blocks;
|
||||
std::vector<int32_t> physical_slots;
|
||||
std::vector<uint8_t> before;
|
||||
uint64_t after_hash = 0;
|
||||
bool bytes_equal = false;
|
||||
bool mapping_equal = false;
|
||||
bool negative_control_detected = false;
|
||||
};
|
||||
|
||||
uint64_t kv_test_hash(const std::vector<uint8_t>& bytes) {
|
||||
uint64_t h = 14695981039346656037ull;
|
||||
for (uint8_t b : bytes) h = (h ^ b) * 1099511628211ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
bool kv_test_bytes_equal(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
|
||||
return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
|
||||
}
|
||||
|
||||
template<class RankT>
|
||||
bool kv_test_snapshot(RankT& rank, uint64_t seq, int32_t group, int64_t prefix_tokens,
|
||||
int64_t* first_block_pos, std::vector<int32_t>* logical,
|
||||
std::vector<int32_t>* physical, std::vector<uint8_t>* bytes) {
|
||||
const KVGroupPlan* p = rank.kv.plan(group);
|
||||
if (!p || p->zero || !p->paged() || p->kind != RAD_KV_FULL || p->streamed() ||
|
||||
p->n_layers <= 0 || p->block_size <= 0 || !p->base) return false;
|
||||
const auto& table = rank.kv.block_table(seq, group);
|
||||
const int64_t first_pos = rank.kv.first_block_pos(seq, group);
|
||||
if (first_pos < 0 || prefix_tokens < first_pos) return false;
|
||||
const int64_t complete = (prefix_tokens - first_pos) / p->block_size;
|
||||
if (complete <= 0 || complete > (int64_t)table.size()) return false;
|
||||
if (first_block_pos) *first_block_pos = first_pos;
|
||||
/* Snapshot every complete block in the retained pre-verify prefix. The trailing partial
|
||||
* block is omitted because accepted verify tokens may legitimately fill its unused slots. */
|
||||
const int64_t nblocks = complete;
|
||||
const int64_t layer_bytes = p->layer_bytes_per_block();
|
||||
const int64_t block_bytes = p->n_layers * layer_bytes;
|
||||
if (nblocks <= 0 || layer_bytes <= 0 || p->bytes_per_block != block_bytes) return false;
|
||||
if (rad_dev_set(rank.device) < 0 || rad_stream_sync(rank.ctx.stream()) < 0) return false;
|
||||
logical->clear();
|
||||
physical->clear();
|
||||
logical->reserve((size_t)nblocks);
|
||||
physical->reserve((size_t)nblocks);
|
||||
bytes->resize((size_t)nblocks * (size_t)block_bytes);
|
||||
for (int64_t b = 0; b < nblocks; ++b) {
|
||||
const int32_t id = table[(size_t)b];
|
||||
if (id < 0 || id >= p->pool_blocks()) return false;
|
||||
logical->push_back((int32_t)(first_pos / p->block_size + b));
|
||||
physical->push_back(id);
|
||||
for (int64_t layer = 0; layer < p->n_layers; ++layer) {
|
||||
const auto* src = static_cast<const uint8_t*>(p->base) +
|
||||
layer * p->layer_stride() + (int64_t)id * layer_bytes;
|
||||
auto* dst = bytes->data() + b * block_bytes + layer * layer_bytes;
|
||||
if (rad_memcpy_async(dst, src, layer_bytes, rank.ctx.stream()) < 0) return false;
|
||||
}
|
||||
}
|
||||
return rad_stream_sync(rank.ctx.stream()) >= 0;
|
||||
}
|
||||
|
||||
void kv_test_write_report(const KVRollbackTestEvidence& e, bool greedy, int greedy_token,
|
||||
int64_t tokens_at_greedy) {
|
||||
if (e.report_path.empty()) return;
|
||||
std::ofstream f(e.report_path, std::ios::trunc);
|
||||
if (!f) return;
|
||||
f << "{\"partial_rejection_observed\":true,\"step\":" << e.step
|
||||
<< ",\"sequence\":" << e.seq << ",\"proposals\":" << e.proposals
|
||||
<< ",\"accepted\":" << e.accepted << ",\"group\":" << e.group
|
||||
<< ",\"prefix_tokens_before_verify\":" << e.prefix_before
|
||||
<< ",\"rollback_tokens_before\":" << e.rollback_tokens_before
|
||||
<< ",\"rollback_to_tokens\":" << e.rollback_to_tokens
|
||||
<< ",\"prefix_tokens_after\":" << e.prefix_after_rollback
|
||||
<< ",\"first_block_pos\":" << e.first_block_pos
|
||||
<< ",\"block_size\":" << e.block_size << ",\"layers\":" << e.n_layers
|
||||
<< ",\"bytes_per_layer\":" << e.bytes_per_layer << ",\"logical_blocks\":[";
|
||||
for (size_t i = 0; i < e.logical_blocks.size(); ++i) f << (i ? "," : "") << e.logical_blocks[i];
|
||||
f << "],\"physical_slots\":[";
|
||||
for (size_t i = 0; i < e.physical_slots.size(); ++i) f << (i ? "," : "") << e.physical_slots[i];
|
||||
f << "],\"committed_prefix_bytes\":" << e.before.size()
|
||||
<< ",\"before_hash\":" << kv_test_hash(e.before)
|
||||
<< ",\"after_hash\":" << e.after_hash
|
||||
<< ",\"bytes_equal\":" << (e.bytes_equal ? "true" : "false")
|
||||
<< ",\"mapping_equal\":" << (e.mapping_equal ? "true" : "false")
|
||||
<< ",\"negative_control_detected\":" << (e.negative_control_detected ? "true" : "false")
|
||||
<< ",\"next_greedy_decode_observed\":" << (greedy ? "true" : "false")
|
||||
<< ",\"tokens_at_next_greedy_decode\":" << (greedy ? tokens_at_greedy : -1)
|
||||
<< ",\"next_greedy_token\":" << (greedy ? greedy_token : -1) << "}\n";
|
||||
}
|
||||
|
||||
KVRollbackTestEvidence& kv_test_evidence() {
|
||||
static KVRollbackTestEvidence e;
|
||||
return e;
|
||||
}
|
||||
|
||||
template<class Output, class Ranks>
|
||||
void kv_test_before_commit(const StepPlan& plan, const Output& so, int step, Ranks& ranks) {
|
||||
auto& e = kv_test_evidence();
|
||||
if (!e.waiting_for_greedy && !e.report_path.empty() && e.accepted < 0) {
|
||||
for (size_t i = 0; i < plan.e.size(); ++i) {
|
||||
const StepEntry& entry = plan.e[i];
|
||||
if (entry.seq == e.seq && step == e.step && entry.n_spec == e.proposals &&
|
||||
(so.accepted[i] <= 0 || so.accepted[i] >= e.proposals)) {
|
||||
e = KVRollbackTestEvidence{};
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!e.waiting_for_greedy) return;
|
||||
for (size_t i = 0; i < plan.e.size(); ++i) {
|
||||
const StepEntry& entry = plan.e[i];
|
||||
if (entry.seq == e.seq && entry.req && entry.req->sp.greedy() &&
|
||||
so.first_row[i] >= 0) {
|
||||
kv_test_write_report(e, true, so.token[i], ranks[0]->kv.seq_tokens(e.seq));
|
||||
e.waiting_for_greedy = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<class Ranks>
|
||||
void kv_test_prepare(const StepPlan& plan, int step, Ranks& ranks) {
|
||||
auto& e = kv_test_evidence();
|
||||
if (!e.report_path.empty() || e.waiting_for_greedy) return;
|
||||
const char* path = std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT");
|
||||
if (!path || !*path) return;
|
||||
for (const StepEntry& entry : plan.e) {
|
||||
if (!entry.req || entry.n_spec != 7) continue;
|
||||
const int64_t prefix = entry.ctx_len;
|
||||
for (int32_t g = 0; g < ranks[0]->kv.n_groups(); ++g) {
|
||||
const KVGroupPlan* p = ranks[0]->kv.plan(g);
|
||||
if (!p || p->kind != RAD_KV_FULL || p->zero || p->streamed() ||
|
||||
prefix < p->block_size) continue;
|
||||
KVRollbackTestEvidence candidate;
|
||||
candidate.report_path = path;
|
||||
candidate.seq = entry.seq;
|
||||
candidate.step = step;
|
||||
candidate.proposals = entry.n_spec;
|
||||
candidate.group = g;
|
||||
candidate.prefix_before = prefix;
|
||||
candidate.block_size = p->block_size;
|
||||
candidate.n_layers = p->n_layers;
|
||||
candidate.bytes_per_layer = p->layer_bytes_per_block();
|
||||
if (!kv_test_snapshot(*ranks[0], entry.seq, g, prefix, &candidate.first_block_pos,
|
||||
&candidate.logical_blocks, &candidate.physical_slots,
|
||||
&candidate.before)) continue;
|
||||
e = std::move(candidate);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<class RankT>
|
||||
void kv_test_rollback(uint64_t seq, int proposals, int accepted, int64_t valid,
|
||||
bool before, RankT& rank) {
|
||||
auto& e = kv_test_evidence();
|
||||
if (e.report_path.empty() || e.waiting_for_greedy || seq != e.seq ||
|
||||
proposals != e.proposals || proposals != 7 || accepted <= 0 || accepted >= proposals)
|
||||
return;
|
||||
if (before) {
|
||||
e.accepted = accepted;
|
||||
e.rollback_tokens_before = rank.kv.seq_tokens(seq);
|
||||
e.rollback_to_tokens = valid;
|
||||
return;
|
||||
}
|
||||
std::vector<int32_t> logical, physical;
|
||||
std::vector<uint8_t> after;
|
||||
int64_t first_block_pos = -1;
|
||||
const bool copied = kv_test_snapshot(rank, seq, e.group, std::min(e.prefix_before, valid),
|
||||
&first_block_pos, &logical, &physical, &after);
|
||||
bool mapping_equal = copied && first_block_pos == e.first_block_pos &&
|
||||
logical == e.logical_blocks && physical == e.physical_slots;
|
||||
const bool bytes_equal = copied && kv_test_bytes_equal(after, e.before);
|
||||
e.after_hash = copied ? kv_test_hash(after) : 0;
|
||||
e.bytes_equal = bytes_equal;
|
||||
std::vector<uint8_t> mutated = e.before;
|
||||
if (!mutated.empty()) mutated[0] ^= 1;
|
||||
e.negative_control_detected = !mutated.empty() && !kv_test_bytes_equal(e.before, mutated);
|
||||
const int64_t after_tokens = rank.kv.seq_tokens(seq);
|
||||
mapping_equal = mapping_equal && after_tokens == e.rollback_to_tokens;
|
||||
e.mapping_equal = mapping_equal;
|
||||
e.prefix_after_rollback = after_tokens;
|
||||
kv_test_write_report(e, false, -1, -1);
|
||||
e.waiting_for_greedy = true;
|
||||
(void)valid; // rollback's requested length is emitted by the manager as after_tokens
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
/* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */
|
||||
Engine::Engine(Config cfg)
|
||||
: cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
|
||||
@@ -108,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);
|
||||
@@ -164,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;
|
||||
@@ -171,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;
|
||||
@@ -506,6 +726,9 @@ int Engine::issue_ahead(const RadBatch** out) {
|
||||
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
|
||||
const RadBatch* nb = sched_.step_next();
|
||||
if (!nb) return RAD_OK;
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
kv_test_prepare(sched_.plan(), nb->step, ranks_);
|
||||
#endif
|
||||
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
|
||||
* and drafts. */
|
||||
RAD_TRY(advance_all(ADV_TRUNK, 0, false));
|
||||
@@ -567,6 +790,15 @@ int Engine::step_loop() {
|
||||
return fail_loop(RAD_E_UNSUPPORTED);
|
||||
}
|
||||
const bool t_on = (int)log_level() >= (int)Log::Debug;
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
if (std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT")) {
|
||||
sched_.set_kv_rollback_test_hook([this](uint64_t seq, int proposals, int accepted,
|
||||
int64_t valid, bool before) {
|
||||
if (!ranks_.empty()) kv_test_rollback(seq, proposals, accepted, valid, before,
|
||||
*ranks_[0]);
|
||||
});
|
||||
}
|
||||
#endif
|
||||
/* The next step's forward pass when already issued behind the previous step, before its
|
||||
* readback (Scheduler::step_next). */
|
||||
const RadBatch* ahead = nullptr;
|
||||
@@ -620,6 +852,9 @@ int Engine::step_loop() {
|
||||
* produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
|
||||
* chunk produces no row). */
|
||||
const StepPlan& plan = sched_.plan();
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
kv_test_prepare(plan, b->step, ranks_);
|
||||
#endif
|
||||
/* One entry per request; Sampler::build_step expands each into 1 + n_draft rows itself
|
||||
* (giving each position its RNG coordinate), so one push per row would stage (1+n)^2 rows.
|
||||
* `first_row` indexes sampled tokens, so it counts rows. */
|
||||
@@ -883,6 +1118,9 @@ int Engine::step_loop() {
|
||||
res.first_row = so.first_row.data();
|
||||
}
|
||||
res.path = so.path.empty() ? nullptr : so.path.data();
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
kv_test_before_commit(plan, so, b->step, ranks_);
|
||||
#endif
|
||||
st = sched_.commit(res);
|
||||
if (t_on) phase_mark(PH_COMMIT);
|
||||
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
|
||||
@@ -1809,17 +2047,20 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
|
||||
const bool audio_gen = ranks_[0]->program.is_audio_generator();
|
||||
const bool video_gen = ranks_[0]->program.is_video_generator();
|
||||
const bool shape_gen = ranks_[0]->program.is_shape_generator();
|
||||
const bool generator = ranks_[0]->program.is_pass_driven();
|
||||
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) {
|
||||
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output "
|
||||
"(rad_declare_pooled) and no generator (rad_declare_generator, "
|
||||
"rad_declare_audio_generator, rad_declare_video_generator), so a step produces "
|
||||
"rad_declare_audio_generator, rad_declare_video_generator, "
|
||||
"rad_declare_shape_generator), so a step produces "
|
||||
"nothing anyone can read. An encoder-only plugin cannot serve.",
|
||||
plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (generator) {
|
||||
const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images";
|
||||
const char* const what = audio_gen ? "audio" : video_gen ? "video"
|
||||
: shape_gen ? "shapes" : "images";
|
||||
if (cfg_.kld() || cfg_.n_spec > 0) {
|
||||
RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to "
|
||||
"work on", plugins_.arch_plugin.c_str(), what);
|
||||
@@ -1828,6 +2069,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
for (size_t i = 1; i < ranks_.size(); ++i)
|
||||
if (ranks_[i]->program.is_audio_generator() != audio_gen ||
|
||||
ranks_[i]->program.is_video_generator() != video_gen ||
|
||||
ranks_[i]->program.is_shape_generator() != shape_gen ||
|
||||
!ranks_[i]->program.is_pass_driven()) {
|
||||
RAD_ERR("rank %zu declared a different generator from rank 0's", i);
|
||||
return RAD_E_STATE;
|
||||
@@ -1838,6 +2080,8 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
"after them"
|
||||
: video_gen
|
||||
? "a video generator: a prompt is read by its own request's steps and keeps no KV"
|
||||
: shape_gen
|
||||
? "a shape generator: a picture is read by its own request's steps and keeps no KV"
|
||||
: "an image generator: a conditioning is read by its own request's images and by "
|
||||
"nothing after them";
|
||||
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
|
||||
@@ -1994,7 +2238,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(),
|
||||
rank_stream_views_[r].data() });
|
||||
}
|
||||
if (video_gen) {
|
||||
if (shape_gen) {
|
||||
/* As for the image generator below. */
|
||||
std::vector<gen::ShapeDriver::RankIO> gio;
|
||||
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
|
||||
auto d = std::make_unique<gen::ShapeDriver>();
|
||||
RAD_TRY(d->init(ranks_[0]->program, gio));
|
||||
shp_gen_ = d.get();
|
||||
gen_ = std::move(d);
|
||||
RAD_TRY(rad_dev_set(ranks_[0]->device));
|
||||
} else if (video_gen) {
|
||||
/* As for the image generator below; the plugin lays out each request's rows. */
|
||||
std::vector<gen::VideoDriver::RankIO> gio;
|
||||
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
|
||||
@@ -2596,6 +2849,7 @@ int Engine::run_server() {
|
||||
o.image_model = img_gen_ != nullptr;
|
||||
o.audio_model = aud_gen_ != nullptr;
|
||||
o.video_model = vid_gen_ != nullptr;
|
||||
o.shape_model = shp_gen_ != nullptr;
|
||||
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
|
||||
/* clef's learned scalars, which the server applies to what the head returns (server/clef.h);
|
||||
* rad-convert writes them beside decision.type. */
|
||||
@@ -2792,6 +3046,18 @@ int Engine::run_server() {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens;
|
||||
} else if (vc.family == mm::Family::Radio) {
|
||||
/* NVIDIA's processor sizes a picture and a video frame by patch budgets
|
||||
* (min_num_patches..max_num_patches, video_target_num_patches), not pixel bands. */
|
||||
if (cfg_.image_min_pixels || cfg_.image_max_pixels || cfg_.image_tokens ||
|
||||
cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_max_frame_tokens) {
|
||||
RAD_ERR("media: this model's processor sizes images and video frames by its patch "
|
||||
"budgets (min_num_patches, max_num_patches, video_target_num_patches), so "
|
||||
"--image-min/max-pixels, --image-tokens, --video-min/max-pixels and "
|
||||
"--video-max-frame-tokens do nothing on it");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames;
|
||||
} else {
|
||||
if (cfg_.image_tokens) {
|
||||
RAD_ERR("media: --image-tokens is a token budget, and this model's processor "
|
||||
@@ -2892,6 +3158,16 @@ int Engine::run_server() {
|
||||
ranks_[0]->program.encoder_name.c_str(), mm_proc->config().image_soft_tokens,
|
||||
mm_proc->config().video_soft_tokens, mm_proc->config().fps,
|
||||
mm_proc->config().max_frames, (long long)encd.max_patches);
|
||||
else if (mm_proc->config().family == mm::Family::Radio)
|
||||
RAD_INFO("media: %s%s through '%s'; an image becomes one tile of %d..%d patches "
|
||||
"(a quarter as many tokens), a video frame about %d patches, %d frames a "
|
||||
"tubelet at %.3g frames a second, at most %d frames, no pruning; %lld "
|
||||
"patches a pass", o.allow_image ? "images" : "",
|
||||
o.allow_video ? " and video" : "", ranks_[0]->program.encoder_name.c_str(),
|
||||
mm_proc->config().radio_min_patches, mm_proc->config().radio_max_patches,
|
||||
mm_proc->config().radio_video_patches, mm_proc->config().radio_tubelet,
|
||||
mm_proc->config().fps, mm_proc->config().max_frames,
|
||||
(long long)encd.max_patches);
|
||||
else
|
||||
RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld "
|
||||
"patches a pass), a video to %lld pixels over all its frames",
|
||||
@@ -2961,7 +3237,13 @@ int Engine::run_server() {
|
||||
return rc;
|
||||
}
|
||||
o.allow_audio = true;
|
||||
if (mm::decoder_available())
|
||||
if (mm::decoder_available() && ac.family == mm::AudioFamily::Gemma4Unified)
|
||||
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, a token is a frame of %d "
|
||||
"samples (%d ms); %lld frames a pass",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
(double)mm_proc->audio_config().max_samples / (double)ac.rate, ac.frame_length,
|
||||
ac.frame_length * 1000 / ac.rate, (long long)aend.max_patches);
|
||||
else if (mm::decoder_available())
|
||||
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, "
|
||||
"%d frames a token; %lld frames a pass",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
@@ -3159,6 +3441,29 @@ int Engine::run_server() {
|
||||
|
||||
/* A video generator's endpoints: the driver's queue and the declared prompt, sizes and
|
||||
* lengths. */
|
||||
struct ShapeBridge final : server::IShapeGen {
|
||||
gen::ShapeDriver* drv = nullptr;
|
||||
const gen::ShapeGenInfo& info() const override { return drv->info(); }
|
||||
int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) override {
|
||||
return drv->submit(std::move(r), why);
|
||||
}
|
||||
int64_t queued() const override { return drv->queued(); }
|
||||
int64_t running() const override { return drv->running(); }
|
||||
} shape_bridge;
|
||||
if (shp_gen_) {
|
||||
shape_bridge.drv = shp_gen_;
|
||||
d.shapes = &shape_bridge;
|
||||
const gen::ShapeGenInfo& in = shp_gen_->info();
|
||||
if (cfg_.served_model_name.empty() && !in.name.empty()) {
|
||||
o.model_id = in.name;
|
||||
decide("--served-model-name", o.model_id, "a shape generator: its own name");
|
||||
}
|
||||
RAD_INFO("shape: '%s', a %lldx%lld picture to a field sampled at %lld cells a side by "
|
||||
"default (%lld..%lld), %lld steps by default at guidance %g",
|
||||
in.name.c_str(), (long long)in.canvas, (long long)in.canvas,
|
||||
(long long)in.default_resolution, (long long)in.min_resolution,
|
||||
(long long)in.max_resolution, (long long)in.default_steps, in.default_guidance);
|
||||
}
|
||||
struct VideoBridge final : server::IVideoGen {
|
||||
gen::VideoDriver* drv = nullptr;
|
||||
server::VideoGenInfo inf;
|
||||
@@ -3209,8 +3514,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;
|
||||
@@ -3308,6 +3613,9 @@ int Engine::run_server() {
|
||||
else if (vid_gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)",
|
||||
o.host.c_str(), o.port, keyed);
|
||||
else if (shp_gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/generate, /send and /status/{uid}; completions and "
|
||||
"chat are 501%s)", o.host.c_str(), o.port, keyed);
|
||||
else if (gen_)
|
||||
RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are "
|
||||
"501%s)", o.host.c_str(), o.port,
|
||||
|
||||
+13
-5
@@ -50,7 +50,7 @@ namespace rad {
|
||||
|
||||
class Kld;
|
||||
class StallWatch;
|
||||
namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; }
|
||||
namespace gen { class Driver; class AudioDriver; class VideoDriver; class ShapeDriver; struct IPassDriver; }
|
||||
namespace server { class Sink; }
|
||||
struct TierPump;
|
||||
struct TierJob;
|
||||
@@ -169,6 +169,7 @@ private:
|
||||
std::vector<const char*> meta_kv_kp_, meta_kv_vp_;
|
||||
|
||||
void (*arch_step_)(RadCtx*, const RadBatch*) = nullptr;
|
||||
uint64_t (*arch_pass_key_)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
|
||||
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
@@ -254,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_;
|
||||
@@ -431,14 +437,16 @@ private:
|
||||
int collect_pooled_issue(const RadBatch* b, StepOut& so);
|
||||
int collect_pooled(const RadBatch* b, StepOut& so);
|
||||
/* A generator (rad_declare_generator, rad_declare_audio_generator,
|
||||
* rad_declare_video_generator): the driver that turns requests into passes and the loop that
|
||||
* runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other
|
||||
* program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the
|
||||
* endpoints; one of them is set when `gen_` is. */
|
||||
* rad_declare_video_generator, rad_declare_shape_generator): the driver that turns requests
|
||||
* into passes and the loop that runs them, replacing the scheduler and step loop
|
||||
* (engine_gen.cpp). Null for every other program. `img_gen_`, `aud_gen_`, `vid_gen_` and
|
||||
* `shp_gen_` are the same driver by its kind, for the endpoints; one of them is set when
|
||||
* `gen_` is. */
|
||||
std::unique_ptr<gen::IPassDriver> gen_;
|
||||
gen::Driver* img_gen_ = nullptr;
|
||||
gen::AudioDriver* aud_gen_ = nullptr;
|
||||
gen::VideoDriver* vid_gen_ = nullptr;
|
||||
gen::ShapeDriver* shp_gen_ = nullptr;
|
||||
int gen_loop();
|
||||
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
|
||||
* before the step or pass that first reads them. */
|
||||
|
||||
+114
-7
@@ -11,6 +11,7 @@
|
||||
#include "gen/driver.h"
|
||||
#include "gen/audio_driver.h"
|
||||
#include "gen/video_driver.h"
|
||||
#include "gen/shape_driver.h"
|
||||
|
||||
#include "build/startup.h"
|
||||
#include "build/rad_build.h"
|
||||
@@ -481,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
|
||||
@@ -967,6 +997,7 @@ int Engine::load_plugins() {
|
||||
|
||||
const Plugin* ap = rad_tools_registry().plugin(plugins_.arch_plugin);
|
||||
arch_step_ = ap ? ap->arch_step : nullptr;
|
||||
arch_pass_key_ = ap ? ap->arch_pass_key : nullptr;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1000,6 +1031,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
* fast row (RadBuildCtx::plain_norm). */
|
||||
bc.plain_norm = std::strcmp(device_backend_name(), "sycl") == 0 ? 1 : 0;
|
||||
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
|
||||
bc.expert_file_tier = cfg_.weights_disk_tier ? 1 : 0;
|
||||
bc.scope = "";
|
||||
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
|
||||
bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0;
|
||||
@@ -1113,6 +1145,25 @@ int Engine::declare() {
|
||||
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
|
||||
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
|
||||
cfg_.prefix_cache = false;
|
||||
} else if (pb.gen_rows > 0 && pb.gen_shape) {
|
||||
if (!cfg_.given.count("--max-num-batched-tokens")) {
|
||||
cfg_.max_tok = pb.gen_rows;
|
||||
decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok),
|
||||
"a shape generator: a denoising step's two branches or a query pass's "
|
||||
"points, whichever is more");
|
||||
}
|
||||
if (!cfg_.given.count("--max-num-seqs")) {
|
||||
cfg_.max_seqs = 1;
|
||||
decide("--max-num-seqs", "1", "a shape generator: a pass is one request's");
|
||||
}
|
||||
if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) {
|
||||
cfg_.max_ctx = pb.gen_rows;
|
||||
decide("--max-model-len", std::to_string(cfg_.max_ctx),
|
||||
"a shape generator: a pass's rows");
|
||||
}
|
||||
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
|
||||
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
|
||||
cfg_.prefix_cache = false;
|
||||
} else if (pb.gen_rows > 0 && pb.gen_video) {
|
||||
if (!cfg_.given.count("--max-num-batched-tokens")) {
|
||||
cfg_.max_tok = pb.gen_rows;
|
||||
@@ -1302,6 +1353,27 @@ int Engine::declare() {
|
||||
: "the model carries no vision tower");
|
||||
}
|
||||
|
||||
/* --prefill-interleave not given: auto:1, decode-only steps for as long as a chunk step took,
|
||||
* so decoders keep about half their rate while prompts prefill (measured on Flash-Next: 8
|
||||
* decoders beside a 64K prefill, 12 -> 41 tokens/s each). Not where the schedule must not
|
||||
* follow timing (--deterministic) or nothing decodes beside a prefill (a generator's passes,
|
||||
* KL mode's scoring); an explicit N or auto[:SHARE] is kept as given. */
|
||||
if (!cfg_.prefill_interleave_set) {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
|
||||
const char* none = pb.gen_rows > 0 ? "a generator: its passes carry no decode rows"
|
||||
: cfg_.kld() ? "KL mode scores documents and decodes nothing" : nullptr;
|
||||
if (none || cfg_.deterministic) {
|
||||
decide("--prefill-interleave", "0", none ? none : "--deterministic keeps a "
|
||||
"timing-independent schedule (--prefill-interleave N or auto overrides it)");
|
||||
} else {
|
||||
cfg_.prefill_interleave = -1;
|
||||
cfg_.prefill_interleave_share = 1.0;
|
||||
decide("--prefill-interleave", "auto:1", "decode-only steps for as long as a chunk "
|
||||
"step took while prompts prefill beside decoding sequences");
|
||||
}
|
||||
}
|
||||
|
||||
/* Control vectors are resolved before any rank declares, because the plugin reads the
|
||||
* direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it
|
||||
* nothing is looked for and the graph declares no projection op. With it, a plugin that does
|
||||
@@ -1827,6 +1899,7 @@ int Engine::plan() {
|
||||
f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program)
|
||||
: r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program)
|
||||
: r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program)
|
||||
: r->program.is_shape_generator() ? gen::ShapeDriver::device_bytes(r->program)
|
||||
: BatchBuilder::device_bytes(r->program, cfg_, kg);
|
||||
if (f.staging < 0) return RAD_E_INVAL;
|
||||
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
|
||||
@@ -3052,6 +3125,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
|
||||
@@ -3871,6 +3964,7 @@ int Engine::start() {
|
||||
/* Null for all-in-VRAM: the mover never runs and lookup uses WeightInfo::ptr. */
|
||||
d.residency = r->plan.strategy == Strategy::AllVram ? nullptr : r->mover.residency();
|
||||
d.arch_step = arch_step_;
|
||||
d.arch_pass_key = arch_pass_key_;
|
||||
d.profile_ops = cfg_.profile_ops;
|
||||
bind_kv_pools(r->program, [&](int32_t g) { return r->kv.plan(g); }, &d.kv);
|
||||
d.registry = &rad_tools_registry();
|
||||
@@ -3916,10 +4010,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);
|
||||
@@ -4138,10 +4237,16 @@ int Engine::start() {
|
||||
: fmt("%s --gpu-headroom-mib", humanb(want).c_str());
|
||||
if (room < allowance) {
|
||||
const int64_t raise_mib = (allowance - room + MiB - 1) / MiB;
|
||||
const int64_t need_head = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib;
|
||||
const std::string fix = cfg_.gpu_memory_mib > 0
|
||||
? fmt("Set --gpu-memory-mib to at most %lld: what is left here falls with it one "
|
||||
"for one.",
|
||||
(long long)(props.vram_bytes / MiB - need_head))
|
||||
: fmt("Set --gpu-headroom-mib to at least %lld: what is left here rises with it "
|
||||
"one for one.", (long long)need_head);
|
||||
RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first "
|
||||
"launch to load its code object and size its scratch in -- under the %s this "
|
||||
"engine allows for its own. %s Set --gpu-headroom-mib to at least %lld: what "
|
||||
"is left here rises with it one for one.",
|
||||
"engine allows for its own. %s %s",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(),
|
||||
got < want
|
||||
@@ -4149,7 +4254,7 @@ int Engine::start() {
|
||||
"another process on it or an allocation the budget does not "
|
||||
"count.", humanb(want - got).c_str()).c_str()
|
||||
: "",
|
||||
(long long)(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib));
|
||||
fix.c_str());
|
||||
} else if (got < want) {
|
||||
RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after "
|
||||
"the budget read the card, by another process on it or an allocation the "
|
||||
@@ -4211,6 +4316,8 @@ int Engine::load_vocab() {
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), vs.h, vb));
|
||||
} else if (meta_textless(rad_meta_gets(&meta_, "radiance.text", nullptr))) {
|
||||
vocab_textless(vb);
|
||||
} else if (ckpt_->is_gguf()) {
|
||||
/* GGUF names its pre-tokeniser; the chain is reconstructed from the name or refused (a
|
||||
* container converted with --tokenizer bakes in the declared one). */
|
||||
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for
|
||||
* images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained
|
||||
* before the next.
|
||||
* images, audio_driver.h for audio, video_driver.h for video, shape_driver.h for shapes) run on the
|
||||
* ranks like token steps, one at a time, each drained before the next.
|
||||
*
|
||||
* Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next
|
||||
* pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of
|
||||
@@ -29,6 +29,12 @@ static const char* pass_name(int gen) {
|
||||
case RAD_GEN_PASS_ADECODE: return "adecode";
|
||||
case RAD_GEN_PASS_VDECODE: return "vdecode";
|
||||
case RAD_GEN_PASS_VUPSCALE: return "vupscale";
|
||||
case RAD_GEN_PASS_VENCODE: return "vencode";
|
||||
case RAD_GEN_PASS_AENCODE: return "aencode";
|
||||
case RAD_GEN_PASS_SCOND: return "scond";
|
||||
case RAD_GEN_PASS_SSTEP: return "sstep";
|
||||
case RAD_GEN_PASS_SLATENT: return "slatent";
|
||||
case RAD_GEN_PASS_SQUERY: return "squery";
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
+223
-30
@@ -13,6 +13,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <map>
|
||||
|
||||
namespace rad {
|
||||
@@ -54,8 +55,9 @@ void MetaOwn::finish() {
|
||||
* since the plugin only sees RadModelMeta, whose typed fields size everything at declare.
|
||||
*
|
||||
* A text-only model puts its dimensions at the top level; a multimodal one nests them under
|
||||
* `text_config` beside `vision_config`. Every key is flattened into the free-form list by dotted
|
||||
* path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds
|
||||
* `text_config` beside `vision_config` (NVIDIA's omni wrappers: `llm_config`). Every key is
|
||||
* flattened into the free-form list by dotted path, and typed fields are read from
|
||||
* `text_config.X`, then `llm_config.X`, falling back to `X`, so a plugin finds
|
||||
* `vision_config.depth` under that name either way.
|
||||
*/
|
||||
/* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a
|
||||
@@ -95,10 +97,20 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
|
||||
else if (v.is_string()) out->kv(key, v.get<std::string>());
|
||||
else if (v.is_array()) {
|
||||
/* An array of scalars becomes a space-separated string (mrope_section "11 11 10",
|
||||
* layer_types "linear_attention full_attention ..."), nested arrays row-major.
|
||||
* Arrays of objects are skipped. */
|
||||
* layer_types "linear_attention full_attention ..."), nested arrays row-major. An
|
||||
* array of objects is flattened element by element under its index (Nemotron-H
|
||||
* Puzzle's per-layer `block_configs.1.n_routed_experts`); other mixed arrays are
|
||||
* skipped. */
|
||||
std::string s;
|
||||
if (join_scalars(v, &s)) out->kv(key, s);
|
||||
if (join_scalars(v, &s)) {
|
||||
out->kv(key, s);
|
||||
} else {
|
||||
bool objects = !v.empty();
|
||||
for (const auto& e : v) objects = objects && e.is_object();
|
||||
if (objects)
|
||||
for (size_t i = 0; i < v.size(); ++i)
|
||||
flatten_json(v[i], key + "." + std::to_string(i), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,31 +208,38 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
|
||||
flatten_json(j, "", out);
|
||||
|
||||
/* Alias text_config.X to a bare X where no bare X exists, so plugins read the same free-form
|
||||
* keys (e.g. `partial_rotary_factor`) with or without a vision tower. A bare key wins where
|
||||
* both exist. */
|
||||
/* Alias text_config.X (or llm_config.X) to a bare X where no bare X exists, so plugins read
|
||||
* the same free-form keys (e.g. `partial_rotary_factor`) with or without a vision tower. A
|
||||
* bare key wins where both exist. */
|
||||
{
|
||||
const size_t n = out->keys.size();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const std::string& k = out->keys[i];
|
||||
if (k.rfind("text_config.", 0) != 0) continue;
|
||||
const std::string bare = k.substr(12);
|
||||
bool have = false;
|
||||
for (size_t j2 = 0; j2 < n; ++j2) if (out->keys[j2] == bare) { have = true; break; }
|
||||
if (!have) out->kv(bare, out->vals[i]);
|
||||
for (const char* pre : { "text_config.", "llm_config." }) {
|
||||
const size_t len = std::strlen(pre);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const std::string& k = out->keys[i];
|
||||
if (k.rfind(pre, 0) != 0) continue;
|
||||
const std::string bare = k.substr(len);
|
||||
bool have = false;
|
||||
for (size_t j2 = 0; j2 < out->keys.size(); ++j2)
|
||||
if (out->keys[j2] == bare) { have = true; break; }
|
||||
if (!have) out->kv(bare, out->vals[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto gs = [&](const char* k) -> const char* { return out->get(k); };
|
||||
/* text_config first, then the top level. */
|
||||
auto gi = [&](const char* k, int64_t dflt) -> int64_t {
|
||||
/* text_config first, then llm_config, then the top level. */
|
||||
auto nested = [&](const char* k) -> const char* {
|
||||
const char* v = gs((std::string("text_config.") + k).c_str());
|
||||
if (!v) v = gs(k);
|
||||
if (!v) v = gs((std::string("llm_config.") + k).c_str());
|
||||
return v ? v : gs(k);
|
||||
};
|
||||
auto gi = [&](const char* k, int64_t dflt) -> int64_t {
|
||||
const char* v = nested(k);
|
||||
return v ? strtoll(v, nullptr, 10) : dflt;
|
||||
};
|
||||
auto gf = [&](const char* k, double dflt) -> double {
|
||||
const char* v = gs((std::string("text_config.") + k).c_str());
|
||||
if (!v) v = gs(k);
|
||||
const char* v = nested(k);
|
||||
return v ? strtod(v, nullptr) : dflt;
|
||||
};
|
||||
|
||||
@@ -232,6 +251,11 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
/* LFM2-VL names the wrapper, not the text model; one plugin serves LFM2 with or without
|
||||
* its tower. `model_type` stays in the free-form keys. */
|
||||
if (out->arch == "lfm2vl") out->arch = "lfm2";
|
||||
/* Gemma 4 12B (`gemma4_unified`): its text model is Gemma 4's, served by the gemma4
|
||||
* plugins; `model_type` tells them apart. */
|
||||
if (out->arch == "gemma4unified") out->arch = "gemma4";
|
||||
/* Nemotron-H Omni wraps a Nemotron-H Puzzle text model (`llm_config`) the same way. */
|
||||
if (out->arch == "nemotronhomni") out->arch = "nemotronh";
|
||||
}
|
||||
if (const char* nm = gs("_name_or_path")) out->name = nm;
|
||||
|
||||
@@ -240,6 +264,15 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
|
||||
* reads the HuggingFace one. */
|
||||
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
|
||||
/* Nemotron-H Puzzle states no count: HF derives it from the per-layer list. */
|
||||
if (m.n_layers == 0)
|
||||
if (const char* types = nested("layers_block_type"))
|
||||
for (const char* p = types; *p;) {
|
||||
while (*p == ' ') ++p;
|
||||
if (!*p) break;
|
||||
++m.n_layers;
|
||||
while (*p && *p != ' ') ++p;
|
||||
}
|
||||
m.n_embd = gi("hidden_size", gi("n_embd", 0));
|
||||
m.n_head = gi("num_attention_heads", gi("n_head", 0));
|
||||
m.n_head_kv = gi("num_key_value_heads", m.n_head);
|
||||
@@ -688,6 +721,124 @@ int Checkpoint::open_diffusers() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* config.yaml's maps of scalars as dotted keys, a list's items space-separated, booleans as 1 and
|
||||
* 0 and a trailing comment dropped: the subset Hunyuan3D-2's configs are written in. Anything else
|
||||
* (a multi-line value, a list of maps) is refused, not guessed at. */
|
||||
static int meta_from_yaml(const std::string& path, MetaOwn* out) {
|
||||
std::ifstream f(path);
|
||||
if (!f) {
|
||||
RAD_ERR("%s: cannot read", path.c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
std::vector<std::pair<size_t, std::string>> stack; /* indentation, key */
|
||||
std::string line;
|
||||
int ln = 0;
|
||||
auto trim = [](std::string s) {
|
||||
const size_t a = s.find_first_not_of(" \t\r"), b = s.find_last_not_of(" \t\r");
|
||||
return a == std::string::npos ? std::string() : s.substr(a, b - a + 1);
|
||||
};
|
||||
while (std::getline(f, line)) {
|
||||
++ln;
|
||||
if (const size_t h = line.find(" #"); h != std::string::npos) line.resize(h);
|
||||
const std::string body = trim(line);
|
||||
if (body.empty() || body[0] == '#') continue;
|
||||
const size_t ind = line.find_first_not_of(' ');
|
||||
const size_t colon = body.find(':');
|
||||
if (colon == std::string::npos || body[0] == '-') {
|
||||
RAD_ERR("%s:%d: not a `key: value` line of the YAML this importer reads", path.c_str(), ln);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
while (!stack.empty() && stack.back().first >= ind) stack.pop_back();
|
||||
const std::string key = trim(body.substr(0, colon));
|
||||
std::string val = trim(body.substr(colon + 1));
|
||||
std::string full;
|
||||
for (const auto& s : stack) full += s.second + ".";
|
||||
full += key;
|
||||
if (val.empty()) {
|
||||
stack.emplace_back(ind, key);
|
||||
continue;
|
||||
}
|
||||
if (val.front() == '[') {
|
||||
if (val.back() != ']') {
|
||||
RAD_ERR("%s:%d: a list must close on its line", path.c_str(), ln);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
std::string items;
|
||||
for (char& ch : val) if (ch == '[' || ch == ']' || ch == ',') ch = ' ';
|
||||
std::istringstream is(val);
|
||||
for (std::string it; is >> it;) items += (items.empty() ? "" : " ") + it;
|
||||
val = items;
|
||||
} else if (val == "True" || val == "true") {
|
||||
val = "1";
|
||||
} else if (val == "False" || val == "false") {
|
||||
val = "0";
|
||||
} else if (val.size() >= 2 && (val.front() == '"' || val.front() == '\'') &&
|
||||
val.back() == val.front()) {
|
||||
val = val.substr(1, val.size() - 2);
|
||||
}
|
||||
out->set(full, val);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A Hunyuan3D-2 shape model (tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 and its kin): a folder of
|
||||
* config.yaml and one safetensors holding three networks under `model.` (the DiT),
|
||||
* `conditioner.` (DINOv2's image encoder) and `vae.` (the shape VAE), the names kept. config.yaml's
|
||||
* keys go into the metadata by dotted path (model.params.hidden_size, vae.params.scale_factor,
|
||||
* conditioner.params.main_image_encoder.kwargs.config.num_hidden_layers, ...). The architecture
|
||||
* is `hunyuan3d2`, and the model reads no text (`radiance.text` none). */
|
||||
int Checkpoint::open_hy3d(const std::string& weights) {
|
||||
kind_ = SafeT;
|
||||
RAD_TRY(add_shard(weights));
|
||||
RAD_TRY(meta_from_yaml(dir_ + "/config.yaml", &meta_));
|
||||
meta_.arch = "hunyuan3d2";
|
||||
meta_.set("radiance.text", "none");
|
||||
/* The typed dimensions are the denoiser's: its blocks, width and heads, read off its tensors;
|
||||
* the vocabulary is the one token of a model that reads no text, and the context a step's
|
||||
* rows (both branches of the 1370 conditioning rows and the latent). */
|
||||
{
|
||||
RadModelMeta& m = meta_.m;
|
||||
const SrcTensor* lat = find("model.latent_in.weight");
|
||||
const SrcTensor* mlp = find("model.double_blocks.0.img_mlp.0.weight");
|
||||
const SrcTensor* qn = find("model.double_blocks.0.img_attn.norm.query_norm.scale");
|
||||
const SrcTensor* vae = find("vae.post_kl.weight");
|
||||
int64_t layers = 0;
|
||||
while (find("model.double_blocks." + std::to_string(layers) + ".img_mod.lin.weight"))
|
||||
++layers;
|
||||
for (int64_t s = 0; find("model.single_blocks." + std::to_string(s) + ".linear1.weight"); ++s)
|
||||
++layers;
|
||||
if (!lat || lat->shape.size() != 2 || !mlp || mlp->shape.size() != 2 || !qn ||
|
||||
qn->shape.size() != 1 || qn->shape[0] <= 0 || !vae || !layers) {
|
||||
RAD_ERR("%s: Hunyuan3D-2's DiT or shape VAE is incomplete", weights.c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
m.n_layers = layers;
|
||||
m.n_embd = lat->shape[0];
|
||||
m.head_dim = qn->shape[0];
|
||||
m.n_head = m.n_head_kv = m.n_embd / m.head_dim;
|
||||
m.n_ff = mlp->shape[0];
|
||||
m.n_vocab = 1;
|
||||
m.n_ctx_train = 2 * (1370 + 3072);
|
||||
m.rms_eps = 1e-6f;
|
||||
m.rope_theta = 10000.0f;
|
||||
m.rope_scale = 1.0f;
|
||||
}
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Whether `file` is a Hunyuan3D-2 shape checkpoint: its DiT and image encoder by name. */
|
||||
static bool hy3d_weights(const std::string& file) {
|
||||
SafeTensorsFile probe;
|
||||
if (probe.open(file) != RAD_OK) return false;
|
||||
bool dit = false, enc = false;
|
||||
for (const auto& t : probe.tensors()) {
|
||||
dit = dit || t.name == "model.latent_in.weight";
|
||||
enc = enc || t.name.rfind("conditioner.main_image_encoder.", 0) == 0;
|
||||
}
|
||||
return dit && enc;
|
||||
}
|
||||
|
||||
/* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its
|
||||
* finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding
|
||||
*
|
||||
@@ -887,6 +1038,16 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) ||
|
||||
path_exists(dir_ + "/modular_model_index.json")))
|
||||
return open_diffusers();
|
||||
/* A Hunyuan3D-2 shape model: config.yaml beside its one safetensors (the fp16 one when the
|
||||
* folder holds both). */
|
||||
if (!is_index && path_exists(dir_ + "/config.yaml")) {
|
||||
std::string w = path;
|
||||
if (!is_file)
|
||||
for (const char* f : { "/model.fp16.safetensors", "/model.safetensors" })
|
||||
if (path_exists(dir_ + f)) { w = dir_ + f; break; }
|
||||
if (w != path || is_file)
|
||||
if (hy3d_weights(w)) return open_hy3d(w);
|
||||
}
|
||||
if (is_file) {
|
||||
shards.push_back(path);
|
||||
/* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune
|
||||
@@ -1274,16 +1435,17 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
const Import im = imports_at(name); /* a drafter's own form under its prefix */
|
||||
/* CtFp8 has no imported form: its FP8 weights read stock (ckpt_resolve). */
|
||||
if (import_ == Import::None || import_ == Import::CtFp8) return RAD_E_NOTFOUND;
|
||||
if (im == Import::None || im == Import::CtFp8) return RAD_E_NOTFOUND;
|
||||
if (auto hit = imported_.find(name); hit != imported_.end()) {
|
||||
*codes = hit->second.first;
|
||||
*scale = hit->second.second;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::ParoI5 || import_ == Import::ParoI4) {
|
||||
const bool i5 = import_ == Import::ParoI5;
|
||||
if (im == Import::ParoI5 || im == Import::ParoI4) {
|
||||
const bool i5 = im == Import::ParoI5;
|
||||
/* Paro int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and
|
||||
* X.qzeros/.qzeros_hi (zero points). The view describes the logical [N, K] u5 matrix;
|
||||
* ckpt_plane_rows re-lays the planes row by row. */
|
||||
@@ -1323,13 +1485,13 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::QuarkMx || import_ == Import::ParoMx || import_ == Import::ParoM2) {
|
||||
if (im == Import::QuarkMx || im == Import::ParoMx || im == Import::ParoM2) {
|
||||
/* Quark's MXFP4 is `fp4_e2m1*e8m0[1x32]` as stored: two codes per byte (element 2j in the
|
||||
* low nibble), one biased exponent per 32 of K. The view only renames dtypes and the
|
||||
* logical width. Excluded layers are plain tensors. ParoQuant's M2XFP4 grid carries one
|
||||
* more plane (`weight_meta`, [N, K/32] u8) that is handed to the weight through
|
||||
* import_meta: its bytes are the encoding's third plane as they ship. */
|
||||
const bool m2 = import_ == Import::ParoM2;
|
||||
const bool m2 = im == Import::ParoM2;
|
||||
const SrcTensor* w = find(name);
|
||||
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
|
||||
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
|
||||
@@ -1356,7 +1518,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::CtInt4) {
|
||||
if (im == Import::CtInt4) {
|
||||
/* CT-INT4: `X.weight` ships as X.weight_packed (i32 [N, K/8], eight codes per word from the
|
||||
* low bits, each the signed code plus 8) and X.weight_scale ([N, K/group]), and when
|
||||
* asymmetric X.weight_zero_point (see SrcTensor::ct_zero). compressed-tensors dequantises
|
||||
@@ -1427,7 +1589,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::ModelOpt) {
|
||||
if (im == Import::ModelOpt) {
|
||||
/* ModelOpt's NVFP4: `X.weight` U8 [N, K/2] (two e2m1 codes a byte, the even k in the low
|
||||
* nibble), `X.weight_scale` e4m3 [N, K/16] and `X.weight_scale_2` f32, one per tensor.
|
||||
* ModelOpt dequantises
|
||||
@@ -1483,7 +1645,7 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::Nvfp4) {
|
||||
if (im == Import::Nvfp4) {
|
||||
/* NVFP4 (compressed-tensors' nvfp4-pack-quantized): `X.weight_packed` U8 [N, K/2], two
|
||||
* e2m1 codes per byte with the even k in the low nibble; `X.weight_scale` e4m3 [N, K/16];
|
||||
* `X.weight_global_scale` f32, one per tensor. The global scale is a divisor: the value is
|
||||
@@ -1661,6 +1823,36 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
|
||||
std::unordered_map<std::string, std::string> owner;
|
||||
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
|
||||
/* The drafter's own quantisation. One is read: ModelOpt's NVFP4 in groups of 16 (LiLiCorr
|
||||
* ships `modelopt_fp4` / `W4A16_NVFP4`: NVFP4 weights, bf16 activations, which a recipe rule
|
||||
* decodes like the target's NVFP4). Its names take that form (imports_at); anything else
|
||||
* quantised is refused by name rather than read as plain tensors. */
|
||||
const std::string dq = prefix + "quantization_config.";
|
||||
auto qd = [&](const char* k) {
|
||||
const char* v = meta_.get(dq + k);
|
||||
return v ? std::string(v) : std::string();
|
||||
};
|
||||
const std::string qm = qd("quant_method");
|
||||
if (!qm.empty()) {
|
||||
const std::string qa = qd("quant_algo"), gs = qd("group_size");
|
||||
const bool modelopt = qm == "modelopt" || qm == "modelopt_fp4";
|
||||
if (!modelopt || (qa != "NVFP4" && qa != "W4A16_NVFP4") || (!gs.empty() && gs != "16")) {
|
||||
RAD_ERR("drafter %s: quantization_config %s / %s (group %s) is not one this reads; "
|
||||
"ModelOpt's NVFP4 in groups of 16 is", dir.c_str(), qm.c_str(), qa.c_str(),
|
||||
gs.empty() ? "unstated" : gs.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (import_ != Import::None && import_ != Import::ModelOpt) {
|
||||
RAD_ERR("drafter %s: an NVFP4 drafter beside a target imported in another form is not "
|
||||
"read", dir.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
draft_import_ = Import::ModelOpt;
|
||||
draft_prefix_ = prefix;
|
||||
/* As the target's: the tool's config is provenance, not a served format. */
|
||||
for (std::string& k : meta_.keys)
|
||||
if (k.rfind(dq, 0) == 0) k = prefix + "imported_" + k.substr(prefix.size());
|
||||
}
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -2580,8 +2772,9 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
"rad-convert imports with its scales rounded to bf16 -- serve the "
|
||||
"container it writes";
|
||||
}
|
||||
} else if (dt == RAD_FP4E2M1 && scaled && (ck.imports() == Checkpoint::Import::Nvfp4 ||
|
||||
ck.imports() == Checkpoint::Import::ModelOpt)) {
|
||||
} else if (dt == RAD_FP4E2M1 && scaled &&
|
||||
(ck.imports_at(p0.name) == Checkpoint::Import::Nvfp4 ||
|
||||
ck.imports_at(p0.name) == Checkpoint::Import::ModelOpt)) {
|
||||
/* NVFP4 as import_piece reads it: e2m1 codes beside the f32 scale the e4m3 one and the
|
||||
* second level make, one per 16 of K, each piece with its own second level. Not trivial
|
||||
* (the scale is derived), so the loader refuses it and rad-convert decodes it for a
|
||||
|
||||
@@ -187,6 +187,12 @@ public:
|
||||
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoM2, ParoI5, ParoI4, Nvfp4, CtFp8,
|
||||
ModelOpt };
|
||||
Import imports() const { return import_; }
|
||||
/* The form `name` is read in: a drafter merged by add_draft ships its own quantisation (a
|
||||
* ModelOpt NVFP4 drafter beside a bf16 target), so names under its prefix take that one. */
|
||||
Import imports_at(const std::string& name) const {
|
||||
return draft_import_ != Import::None && name.rfind(draft_prefix_, 0) == 0 ? draft_import_
|
||||
: import_;
|
||||
}
|
||||
const std::string& import_refusal() const { return import_why_; }
|
||||
|
||||
/* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed
|
||||
@@ -209,6 +215,7 @@ private:
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_diffusers();
|
||||
int open_sgm();
|
||||
int open_hy3d(const std::string& weights);
|
||||
int add_companions();
|
||||
int add_torch_files();
|
||||
int open_gguf(const std::string& path);
|
||||
@@ -230,6 +237,9 @@ private:
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
std::string import_why_;
|
||||
/* add_draft's drafter, when it ships a quantisation of its own: the form and the prefix. */
|
||||
Import draft_import_ = Import::None;
|
||||
std::string draft_prefix_;
|
||||
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
|
||||
bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */
|
||||
/* import_piece's answers by name, so a weight resolved twice reuses its views. */
|
||||
|
||||
@@ -56,6 +56,9 @@ struct Cursor {
|
||||
case GT_ARR: {
|
||||
uint32_t et = 0; uint64_t n = 0;
|
||||
if (!get(&et) || !get(&n)) return false;
|
||||
/* An array of arrays is refused, as the GGUF reader refuses it: each level costs a
|
||||
* file 12 bytes and this walker a stack frame. */
|
||||
if (et == GT_ARR) { ok = false; return false; }
|
||||
for (uint64_t i = 0; i < n && ok; ++i) if (!skip_value(et)) return false;
|
||||
return ok;
|
||||
}
|
||||
|
||||
+55
-16
@@ -48,7 +48,7 @@ void RadFile::close() {
|
||||
|
||||
int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
|
||||
if (fd_ < 0) { RAD_ERR("read_at on a closed container"); return RAD_E_STATE; }
|
||||
if (off < 0 || bytes < 0 || off + bytes > size_) {
|
||||
if (off < 0 || bytes < 0 || off > size_ || bytes > size_ - off) {
|
||||
RAD_ERR("read_at [%lld, %lld) is outside the %lld-byte container",
|
||||
(long long)off, (long long)(off + bytes), (long long)size_);
|
||||
return RAD_E_FORMAT;
|
||||
@@ -210,6 +210,21 @@ int RadFile::validate() {
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
|
||||
/* The tables are read in place through typed pointers, so each must sit on its element's
|
||||
* alignment (the writer places every one 8-aligned), as the vocab section's arrays must. */
|
||||
auto aligned = [&](uint64_t off, uint64_t count, size_t align, const char* what) {
|
||||
if (count == 0 || off % align == 0) return true;
|
||||
RAD_ERR("%s: %s starts at %llu, which is not %zu-aligned", path_.c_str(), what,
|
||||
(unsigned long long)off, align);
|
||||
return false;
|
||||
};
|
||||
if (!aligned(hdr_->meta_off, hdr_->meta_count, alignof(RadFileKV), "the metadata table") ||
|
||||
!aligned(hdr_->dir_off, hdr_->dir_count, alignof(RadFileEntry), "the weight directory") ||
|
||||
!aligned(hdr_->plane_off, hdr_->plane_count, alignof(RadFilePlane), "the plane table") ||
|
||||
!aligned(hdr_->enc_off, hdr_->enc_count, alignof(RadEncoding), "the encoding table") ||
|
||||
!aligned(hdr_->prof_off, hdr_->prof_count, alignof(RadFileProfile), "the expert profile"))
|
||||
return RAD_E_FORMAT;
|
||||
|
||||
meta_ = (const RadFileKV*)(base_ + hdr_->meta_off);
|
||||
dir_ = (const RadFileEntry*)(base_ + hdr_->dir_off);
|
||||
planes_ = (const RadFilePlane*)(base_ + hdr_->plane_off);
|
||||
@@ -335,18 +350,21 @@ int RadFile::validate() {
|
||||
}
|
||||
const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff);
|
||||
/* Offset 0 means an optional array is absent (scores are unigram-only; types default to
|
||||
* normal). Nothing real lives at file offset 0. */
|
||||
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) {
|
||||
return bytes == 0 || off == 0 ||
|
||||
(off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
|
||||
off % align == 0);
|
||||
* normal). Nothing real lives at file offset 0. Token texts, merges and steps are not
|
||||
* optional: the writer places each one its count says exists, and a reader handed a
|
||||
* count with no array would read the file header in its place. */
|
||||
auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align, bool optional) {
|
||||
if (bytes == 0) return true;
|
||||
if (off == 0) return optional;
|
||||
return off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) &&
|
||||
off % align == 0;
|
||||
};
|
||||
const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps;
|
||||
if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff)) ||
|
||||
!arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float)) ||
|
||||
!arr_ok(v->tok_type_off, nt, 1) ||
|
||||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) ||
|
||||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) {
|
||||
if (!arr_ok(v->tok_text_off, nt * sizeof(rad_stroff), alignof(rad_stroff), false) ||
|
||||
!arr_ok(v->tok_score_off, nt * sizeof(float), alignof(float), true) ||
|
||||
!arr_ok(v->tok_type_off, nt, 1, true) ||
|
||||
!arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t), false) ||
|
||||
!arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep), false)) {
|
||||
RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its "
|
||||
"element",
|
||||
path_.c_str(), what);
|
||||
@@ -458,7 +476,17 @@ int RadFile::index_experts() {
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
const uint64_t ebase = dir_[j].offset;
|
||||
if (e_id == 1) g.stride = ebase - g.base;
|
||||
if (e_id == 1) {
|
||||
/* Expert 1 defines the stride, so the arithmetic test below cannot check it: it
|
||||
* must step forward by at least one whole unit, or experts overlap (or wrap). */
|
||||
if (ebase < g.base || ebase - g.base < g.unit_bytes) {
|
||||
RAD_ERR("%s: layer %d expert 1 starts at %llu, inside or before expert 0's "
|
||||
"%llu bytes at %llu", path_.c_str(), layer, (unsigned long long)ebase,
|
||||
(unsigned long long)g.unit_bytes, (unsigned long long)g.base);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
g.stride = ebase - g.base;
|
||||
}
|
||||
if (ebase != g.base + (uint64_t)e_id * g.stride) {
|
||||
RAD_ERR("%s: layer %d expert %d starts at %llu, but base + %d*%llu is %llu -- the "
|
||||
"layer has no fixed stride and cannot be addressed by arithmetic",
|
||||
@@ -565,8 +593,16 @@ void RadWriter::abort() {
|
||||
/* The file is the caller's container: restore its header (a no-op unless finish_append()
|
||||
* failed in that write) and truncate the tail. */
|
||||
if (fd_out_ >= 0) {
|
||||
(void)!::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0);
|
||||
(void)!::ftruncate(fd_out_, (off_t)old_size_);
|
||||
/* A failed restore leaves a file that is neither the old container nor the new one,
|
||||
* and the caller has only been told that the write failed. */
|
||||
const bool hdr_ok = ::pwrite(fd_out_, &old_hdr_, sizeof old_hdr_, 0) ==
|
||||
(ssize_t)sizeof old_hdr_;
|
||||
const bool cut_ok = ::ftruncate(fd_out_, (off_t)old_size_) == 0;
|
||||
if (!hdr_ok || !cut_ok)
|
||||
RAD_ERR("%s: the append was undone only in part (%s) -- the container is damaged; "
|
||||
"restore it from a copy", path_.c_str(),
|
||||
!hdr_ok ? "its header could not be rewritten"
|
||||
: "its tail could not be cut back");
|
||||
::close(fd_out_);
|
||||
}
|
||||
if (fd_spill_ >= 0) ::close(fd_spill_);
|
||||
@@ -1009,8 +1045,11 @@ int RadWriter::set_vocab_section(const void* blob, int64_t bytes) {
|
||||
!fits(h->tok_score_off, h->tok_score_off ? (uint64_t)h->n_tokens * sizeof(float) : 0) ||
|
||||
!fits(h->tok_type_off, h->tok_type_off ? h->n_tokens : 0) ||
|
||||
!fits(h->merge_off, (uint64_t)h->n_merges * 2 * sizeof(uint32_t)) ||
|
||||
!fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep))) {
|
||||
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes. Its offsets must be "
|
||||
!fits(h->step_off, (uint64_t)h->n_steps * sizeof(RadVocabStep)) ||
|
||||
(h->n_tokens && !h->tok_text_off) || (h->n_merges && !h->merge_off) ||
|
||||
(h->n_steps && !h->step_off)) {
|
||||
RAD_ERR("the vocab section's arrays do not fit inside its %lld bytes, or one its count "
|
||||
"names is absent. Its offsets must be "
|
||||
"SECTION-RELATIVE -- serialise with a section_file_off of 0 and let finish() "
|
||||
"rebase them.", (long long)bytes);
|
||||
return RAD_E_INVAL;
|
||||
|
||||
@@ -295,7 +295,13 @@ int SafeTensorsFile::open(const std::string& path) {
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
|
||||
index_.emplace(t.name, tensors_.size());
|
||||
/* A JSON object's keys are unique; a header naming one tensor twice has two answers to
|
||||
* find() and is refused rather than resolved to the first. */
|
||||
if (!index_.emplace(t.name, tensors_.size()).second) {
|
||||
RAD_ERR("%s: the header names '%s' twice", path.c_str(), name.c_str());
|
||||
close();
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
tensors_.push_back(std::move(t));
|
||||
|
||||
if (!sc.eat(',')) break;
|
||||
|
||||
+27
-5
@@ -155,6 +155,20 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
}
|
||||
}
|
||||
|
||||
/* The view's rectangles come from plugin-stated spans and parts, sum-checked only. A single
|
||||
* selected plane takes them as its own rectangles below, with no enc_plane_rect to bound
|
||||
* them, so every one is held to the entry here. */
|
||||
for (int g = 0; !whole && g < w.n_part_spans; ++g)
|
||||
if (w.part_lo[g] < 0 || w.part_lo[g] > w.part_hi[g] || w.part_hi[g] > w.part_total[g])
|
||||
return refuse(fmt("part %d's span [%lld, %lld) is outside its %lld", g,
|
||||
(long long)w.part_lo[g], (long long)w.part_hi[g],
|
||||
(long long)w.part_total[g]));
|
||||
for (const VRect& q : view)
|
||||
if (q.r0 < 0 || q.r0 > q.r1 || q.r1 > VR || q.c0 < 0 || q.c0 > q.c1 || q.c1 > VC)
|
||||
return refuse(fmt("the slice [%lld, %lld) x [%lld, %lld) is outside the entry's "
|
||||
"%lld x %lld", (long long)q.r0, (long long)q.r1, (long long)q.c0,
|
||||
(long long)q.c1, (long long)VR, (long long)VC));
|
||||
|
||||
for (int k = 0; k < w.n_sel; ++k) {
|
||||
const RadEncPlane& p = enc.plane[w.sel[k]];
|
||||
PlaneShare& s = out[k];
|
||||
@@ -186,7 +200,10 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
return refuse(fmt("columns [%lld, %lld) of the %s '%s' plane do not fall on whole "
|
||||
"bytes", (long long)pq.col0, (long long)(pq.col0 + pq.cols),
|
||||
rad_dtype_name(p.dtype), p.role));
|
||||
if (!s.rects.empty() && pq.cols != s.cols)
|
||||
/* A vector's stacked parts lie end to end as one row, so they may differ in width (a
|
||||
* Mamba convolution's bias is [x | B | C]); a matrix's parts stack as rows. */
|
||||
const bool vec = rank == 1 && pq.rows == 1;
|
||||
if (!vec && !s.rects.empty() && pq.cols != s.cols)
|
||||
return refuse("the share's parts differ in width");
|
||||
PlaneShare::Rect r;
|
||||
r.row0 = pq.row0;
|
||||
@@ -194,11 +211,16 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
r.byte0 = pq.col0 * bits / 8;
|
||||
r.bytes = rad_enc_row_bytes(p.dtype, pq.cols);
|
||||
s.rects.push_back(r);
|
||||
s.rows += pq.rows;
|
||||
s.cols = pq.cols;
|
||||
if (vec) {
|
||||
s.rows = 1;
|
||||
s.cols += pq.cols;
|
||||
} else {
|
||||
s.rows += pq.rows;
|
||||
s.cols = pq.cols;
|
||||
}
|
||||
}
|
||||
/* A vector's stacked parts come out as one piece a part, each a row of the share; laid
|
||||
* end to end they are the declared vector, so only the element count has to agree. */
|
||||
/* Laid end to end, a vector's parts are the declared vector, so only the element count
|
||||
* has to agree. */
|
||||
const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k]
|
||||
: s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k];
|
||||
if (!fits)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -175,10 +175,15 @@ int TuneCache::load(const std::string& home, const std::string& machine) {
|
||||
continue;
|
||||
}
|
||||
if (tok[0] == "machine") {
|
||||
if (tok.size() >= 2 && std::string(tok[1]) != machine)
|
||||
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- the rows may not "
|
||||
"describe this card", path.c_str(), (int)tok[1].size(), tok[1].data(),
|
||||
machine.c_str());
|
||||
/* A cache from another card is wrong, not just slow (tunecache.h): a file renamed or
|
||||
* copied to this machine's name is refused, as another format version is. */
|
||||
if (tok.size() >= 2 && std::string(tok[1]) != machine) {
|
||||
RAD_WARN("%s: measured on '%.*s' but this machine is '%s' -- ignoring the cache",
|
||||
path.c_str(), (int)tok[1].size(), tok[1].data(), machine.c_str());
|
||||
std::free(line);
|
||||
::fclose(f);
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (tok.size() < 5) { ++bad; continue; }
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
/* shape.cpp -- the shape generator's host geometry (shape.h): the picture, the sampler's grid, the
|
||||
* field's levels, marching cubes and the mesh's files; and the ticket a caller waits on. */
|
||||
#include "shape.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace gen {
|
||||
|
||||
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name) {
|
||||
ShapeGenInfo g;
|
||||
g.name = name;
|
||||
g.canvas = d.canvas;
|
||||
g.enc_size = d.enc_size;
|
||||
g.enc_patch = d.enc_patch;
|
||||
g.border_ratio = d.border_ratio;
|
||||
for (int c = 0; c < 3; ++c) { g.pix_mean[c] = d.pix_mean[c]; g.pix_std[c] = d.pix_std[c]; }
|
||||
g.default_steps = d.default_steps;
|
||||
g.max_steps = d.max_steps;
|
||||
g.default_guidance = d.default_guidance;
|
||||
g.bounds = d.bounds;
|
||||
g.level = d.level;
|
||||
g.default_resolution = d.default_resolution;
|
||||
g.min_resolution = d.min_resolution;
|
||||
g.max_resolution = d.max_resolution;
|
||||
g.max_lanes = d.max_lanes;
|
||||
return g;
|
||||
}
|
||||
|
||||
/* ================================================================== the picture */
|
||||
namespace {
|
||||
|
||||
/* An 8-bit image, `ch` channels interleaved. */
|
||||
struct Img {
|
||||
int32_t w = 0, h = 0, ch = 0;
|
||||
std::vector<uint8_t> px;
|
||||
uint8_t* at(int32_t y, int32_t x) { return px.data() + ((size_t)y * w + x) * ch; }
|
||||
const uint8_t* at(int32_t y, int32_t x) const { return px.data() + ((size_t)y * w + x) * ch; }
|
||||
};
|
||||
|
||||
/* OpenCV's saturate_cast<uchar> of a float: round half to even, clipped. */
|
||||
inline uint8_t sat_u8(float v) {
|
||||
const float r = std::nearbyint(v);
|
||||
return (uint8_t)(r < 0.0f ? 0.0f : r > 255.0f ? 255.0f : r);
|
||||
}
|
||||
|
||||
/* cv::resize's INTER_AREA when it shrinks both sides: computeResizeAreaTab's weights, a row's
|
||||
* horizontal sums, then the weighted rows, in float. */
|
||||
struct AreaTap { int32_t di, si; float alpha; };
|
||||
std::vector<AreaTap> area_tab(int32_t ssize, int32_t dsize, double scale) {
|
||||
std::vector<AreaTap> tab;
|
||||
for (int32_t dx = 0; dx < dsize; ++dx) {
|
||||
const double fsx1 = dx * scale, fsx2 = fsx1 + scale;
|
||||
const double cell = std::min(scale, ssize - fsx1);
|
||||
int32_t sx1 = (int32_t)std::ceil(fsx1), sx2 = (int32_t)std::floor(fsx2);
|
||||
sx2 = std::min(sx2, ssize - 1);
|
||||
sx1 = std::min(sx1, sx2);
|
||||
if (sx1 - fsx1 > 1e-3) tab.push_back({ dx, sx1 - 1, (float)((sx1 - fsx1) / cell) });
|
||||
for (int32_t sx = sx1; sx < sx2; ++sx) tab.push_back({ dx, sx, (float)(1.0 / cell) });
|
||||
if (fsx2 - sx2 > 1e-3)
|
||||
tab.push_back({ dx, sx2, (float)(std::min(std::min(fsx2 - sx2, 1.0), cell) / cell) });
|
||||
}
|
||||
return tab;
|
||||
}
|
||||
|
||||
void resize_area_down(const Img& s, int32_t dw, int32_t dh, Img* d) {
|
||||
const double sx = (double)s.w / dw, sy = (double)s.h / dh;
|
||||
const std::vector<AreaTap> xt = area_tab(s.w, dw, sx), yt = area_tab(s.h, dh, sy);
|
||||
const int32_t ch = s.ch;
|
||||
std::vector<float> row((size_t)dw * ch), acc((size_t)dw * ch);
|
||||
d->w = dw; d->h = dh; d->ch = ch;
|
||||
d->px.assign((size_t)dw * dh * ch, 0);
|
||||
size_t k = 0;
|
||||
for (int32_t dy = 0; dy < dh; ++dy) {
|
||||
std::fill(acc.begin(), acc.end(), 0.0f);
|
||||
for (; k < yt.size() && yt[k].di == dy; ++k) {
|
||||
std::fill(row.begin(), row.end(), 0.0f);
|
||||
const uint8_t* src = s.at(yt[k].si, 0);
|
||||
for (const AreaTap& t : xt)
|
||||
for (int32_t c = 0; c < ch; ++c)
|
||||
row[(size_t)t.di * ch + c] += src[(size_t)t.si * ch + c] * t.alpha;
|
||||
for (size_t i = 0; i < acc.size(); ++i) acc[i] += row[i] * yt[k].alpha;
|
||||
}
|
||||
uint8_t* dst = d->at(dy, 0);
|
||||
for (size_t i = 0; i < acc.size(); ++i) dst[i] = sat_u8(acc[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* cv::resize's fixed-point separable filter for 8-bit images: each tap's float coefficient
|
||||
* rounded to 11 bits, the horizontal sums in int, the vertical sum shifted back by 22 with
|
||||
* rounding. `taps` coefficients a destination pixel, first at source index ofs[d] (indices
|
||||
* clamped to the image, OpenCV's BORDER_REPLICATE). */
|
||||
struct Taps {
|
||||
int32_t ksize = 0;
|
||||
std::vector<int32_t> ofs;
|
||||
std::vector<int16_t> c;
|
||||
};
|
||||
|
||||
Taps taps_linear_area(int32_t ssize, int32_t dsize) {
|
||||
/* INTER_AREA when it does not shrink both sides: linear taps in OpenCV's area mode. */
|
||||
const double scale = (double)ssize / dsize, inv = (double)dsize / ssize;
|
||||
Taps t;
|
||||
t.ksize = 2;
|
||||
for (int32_t dx = 0; dx < dsize; ++dx) {
|
||||
const int32_t sx = (int32_t)std::floor(dx * scale);
|
||||
float fx = (float)((dx + 1) - (sx + 1) * inv);
|
||||
fx = fx <= 0 ? 0.0f : fx - std::floor(fx);
|
||||
t.ofs.push_back(sx);
|
||||
t.c.push_back((int16_t)std::nearbyint((1.0f - fx) * 2048.0f));
|
||||
t.c.push_back((int16_t)std::nearbyint(fx * 2048.0f));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
Taps taps_cubic(int32_t ssize, int32_t dsize) {
|
||||
const double scale = (double)ssize / dsize;
|
||||
const float A = -0.75f;
|
||||
Taps t;
|
||||
t.ksize = 4;
|
||||
for (int32_t dx = 0; dx < dsize; ++dx) {
|
||||
float fx = (float)((dx + 0.5) * scale - 0.5);
|
||||
const int32_t sx = (int32_t)std::floor(fx);
|
||||
fx -= sx;
|
||||
float w[4];
|
||||
w[0] = ((A * (fx + 1) - 5 * A) * (fx + 1) + 8 * A) * (fx + 1) - 4 * A;
|
||||
w[1] = ((A + 2) * fx - (A + 3)) * fx * fx + 1;
|
||||
w[2] = ((A + 2) * (1 - fx) - (A + 3)) * (1 - fx) * (1 - fx) + 1;
|
||||
w[3] = 1.0f - w[0] - w[1] - w[2];
|
||||
t.ofs.push_back(sx - 1);
|
||||
for (float v : w) t.c.push_back((int16_t)std::nearbyint(v * 2048.0f));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
void resize_fixed(const Img& s, const Taps& tx, const Taps& ty, int32_t dw, int32_t dh, Img* d) {
|
||||
const int32_t ch = s.ch;
|
||||
/* Every source row through the horizontal taps, then each destination row from its rows. */
|
||||
std::vector<int32_t> hrow((size_t)s.h * dw * ch);
|
||||
for (int32_t y = 0; y < s.h; ++y)
|
||||
for (int32_t dx = 0; dx < dw; ++dx)
|
||||
for (int32_t c = 0; c < ch; ++c) {
|
||||
int32_t sum = 0;
|
||||
for (int32_t k = 0; k < tx.ksize; ++k) {
|
||||
const int32_t sx = std::clamp(tx.ofs[(size_t)dx] + k, 0, s.w - 1);
|
||||
sum += s.at(y, sx)[c] * tx.c[(size_t)dx * tx.ksize + k];
|
||||
}
|
||||
hrow[((size_t)y * dw + dx) * ch + c] = sum;
|
||||
}
|
||||
d->w = dw; d->h = dh; d->ch = ch;
|
||||
d->px.assign((size_t)dw * dh * ch, 0);
|
||||
for (int32_t dy = 0; dy < dh; ++dy)
|
||||
for (int32_t i = 0; i < dw * ch; ++i) {
|
||||
int64_t v = 0;
|
||||
for (int32_t k = 0; k < ty.ksize; ++k) {
|
||||
const int32_t sy = std::clamp(ty.ofs[(size_t)dy] + k, 0, s.h - 1);
|
||||
v += (int64_t)hrow[(size_t)sy * dw * ch + i] * ty.c[(size_t)dy * ty.ksize + k];
|
||||
}
|
||||
const int64_t r = (v + (1 << 21)) >> 22;
|
||||
d->px[(size_t)dy * dw * ch + i] = (uint8_t)std::clamp<int64_t>(r, 0, 255);
|
||||
}
|
||||
}
|
||||
|
||||
/* cv2.resize(src, (dw, dh), INTER_AREA). */
|
||||
void resize_area(const Img& s, int32_t dw, int32_t dh, Img* d) {
|
||||
if (dw == s.w && dh == s.h) { *d = s; return; }
|
||||
if (s.w >= dw && s.h >= dh) { resize_area_down(s, dw, dh, d); return; }
|
||||
resize_fixed(s, taps_linear_area(s.w, dw), taps_linear_area(s.h, dh), dw, dh, d);
|
||||
}
|
||||
|
||||
/* cv2.resize(src, (dw, dh), INTER_CUBIC). */
|
||||
void resize_cubic(const Img& s, int32_t dw, int32_t dh, Img* d) {
|
||||
if (dw == s.w && dh == s.h) { *d = s; return; }
|
||||
resize_fixed(s, taps_cubic(s.w, dw), taps_cubic(s.h, dh), dw, dh, d);
|
||||
}
|
||||
|
||||
/* torchvision's antialiased bilinear resize along one axis (align_corners false): the triangle
|
||||
* filter around each output's centre, widened by the scale when shrinking, normalised over the
|
||||
* taps inside the image. */
|
||||
struct AaTaps { std::vector<int32_t> lo; std::vector<std::vector<float>> w; };
|
||||
AaTaps aa_taps(int32_t in, int32_t out) {
|
||||
const double scale = (double)in / out;
|
||||
const double support = scale >= 1.0 ? scale : 1.0;
|
||||
const double inv = scale >= 1.0 ? 1.0 / scale : 1.0;
|
||||
AaTaps t;
|
||||
for (int32_t i = 0; i < out; ++i) {
|
||||
const double center = scale * (i + 0.5);
|
||||
const int32_t lo = std::max((int32_t)(center - support + 0.5), 0);
|
||||
const int32_t hi = std::min((int32_t)(center + support + 0.5), in);
|
||||
std::vector<float> w;
|
||||
double total = 0.0;
|
||||
for (int32_t j = lo; j < hi; ++j) {
|
||||
const double x = std::fabs((j - center + 0.5) * inv);
|
||||
const double v = x < 1.0 ? 1.0 - x : 0.0;
|
||||
w.push_back((float)v);
|
||||
total += v;
|
||||
}
|
||||
if (total > 0.0) for (float& v : w) v = (float)(v / total);
|
||||
t.lo.push_back(lo);
|
||||
t.w.push_back(std::move(w));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
|
||||
std::string* why) {
|
||||
auto no = [&](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
const int32_t H = rgba.h, W = rgba.w;
|
||||
if (H < 1 || W < 1 || rgba.rgba.size() != (size_t)H * W * 4) return no("the picture is empty");
|
||||
/* ---- ImageProcessorV2.recenter: the alpha's bounding box on a square of the longer side */
|
||||
int32_t y0 = H, y1 = -1, x0 = W, x1 = -1;
|
||||
for (int32_t y = 0; y < H; ++y)
|
||||
for (int32_t x = 0; x < W; ++x)
|
||||
if (rgba.rgba[((size_t)y * W + x) * 4 + 3]) {
|
||||
y0 = std::min(y0, y); y1 = std::max(y1, y);
|
||||
x0 = std::min(x0, x); x1 = std::max(x1, x);
|
||||
}
|
||||
if (y1 < 0) return no("the picture is fully transparent: nothing to make a shape of");
|
||||
const int32_t h = y1 - y0, w = x1 - x0;
|
||||
if (h == 0 || w == 0)
|
||||
return no("the picture's opaque part is a single row or column: nothing to make a shape "
|
||||
"of");
|
||||
const int32_t size = std::max(H, W);
|
||||
const int32_t desired = (int32_t)(size * (1.0 - g.border_ratio));
|
||||
const double scale = (double)desired / std::max(h, w);
|
||||
const int32_t h2 = (int32_t)(h * scale), w2 = (int32_t)(w * scale);
|
||||
if (h2 < 1 || w2 < 1)
|
||||
return no("the picture's opaque part is too thin to scale onto the canvas");
|
||||
Img crop;
|
||||
crop.w = w; crop.h = h; crop.ch = 4;
|
||||
crop.px.resize((size_t)w * h * 4);
|
||||
for (int32_t y = 0; y < h; ++y)
|
||||
std::memcpy(crop.at(y, 0), rgba.rgba.data() + ((size_t)(y0 + y) * W + x0) * 4,
|
||||
(size_t)w * 4);
|
||||
Img fit;
|
||||
resize_area(crop, w2, h2, &fit);
|
||||
const int32_t oy = (size - h2) / 2, ox = (size - w2) / 2;
|
||||
/* Flattened onto white in float, then truncated to 8 bits, as numpy's astype does. */
|
||||
Img sq;
|
||||
sq.w = size; sq.h = size; sq.ch = 3;
|
||||
sq.px.assign((size_t)size * size * 3, 255);
|
||||
for (int32_t y = 0; y < h2; ++y)
|
||||
for (int32_t x = 0; x < w2; ++x) {
|
||||
const uint8_t* p = fit.at(y, x);
|
||||
const float a = (float)p[3] / 255.0f;
|
||||
uint8_t* q = sq.at(oy + y, ox + x);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const float v = (float)p[c] * a + 255.0f * (1.0f - a);
|
||||
q[c] = (uint8_t)std::clamp(v, 0.0f, 255.0f);
|
||||
}
|
||||
}
|
||||
/* ---- the canvas, INTER_CUBIC */
|
||||
const int32_t C = (int32_t)g.canvas;
|
||||
Img can;
|
||||
resize_cubic(sq, C, C, &can);
|
||||
/* ---- the encoder's transform: 0..1, bilinear (antialiased) to enc_size, normalised */
|
||||
const int32_t E = (int32_t)g.enc_size, P = (int32_t)g.enc_patch, G = E / P;
|
||||
const AaTaps ta = aa_taps(C, E);
|
||||
std::vector<float> hor((size_t)C * E * 3), img((size_t)E * E * 3);
|
||||
for (int32_t y = 0; y < C; ++y)
|
||||
for (int32_t x = 0; x < E; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float s = 0.0f;
|
||||
const std::vector<float>& wt = ta.w[(size_t)x];
|
||||
for (size_t k = 0; k < wt.size(); ++k)
|
||||
s += wt[k] * ((float)can.at(y, ta.lo[(size_t)x] + (int32_t)k)[c] / 255.0f);
|
||||
hor[((size_t)y * E + x) * 3 + c] = s;
|
||||
}
|
||||
for (int32_t y = 0; y < E; ++y)
|
||||
for (int32_t x = 0; x < E; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float s = 0.0f;
|
||||
const std::vector<float>& wt = ta.w[(size_t)y];
|
||||
for (size_t k = 0; k < wt.size(); ++k)
|
||||
s += wt[k] * hor[(((size_t)ta.lo[(size_t)y] + k) * E + x) * 3 + c];
|
||||
img[((size_t)y * E + x) * 3 + c] =
|
||||
(float)((s - g.pix_mean[c]) / g.pix_std[c]);
|
||||
}
|
||||
/* ---- patches, row-major; a patch's values (channel, row, column) */
|
||||
const int64_t pd = 3 * (int64_t)P * P;
|
||||
patches->assign((size_t)G * G * pd, 0.0f);
|
||||
for (int32_t py = 0; py < G; ++py)
|
||||
for (int32_t px = 0; px < G; ++px) {
|
||||
float* o = patches->data() + ((size_t)py * G + px) * pd;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
for (int32_t i = 0; i < P; ++i)
|
||||
for (int32_t j = 0; j < P; ++j)
|
||||
o[((size_t)c * P + i) * P + j] =
|
||||
img[(((size_t)py * P + i) * E + px * P + j) * 3 + c];
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the sampler and the grid */
|
||||
std::vector<float> shape_sigmas(int32_t steps) {
|
||||
std::vector<float> s;
|
||||
if (steps < 2) return s;
|
||||
const double step = 1.0 / (steps - 1);
|
||||
for (int32_t i = 0; i < steps; ++i) s.push_back(i == steps - 1 ? 1.0f : (float)(i * step));
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<int32_t> shape_levels(int32_t resolution) {
|
||||
std::vector<int32_t> r;
|
||||
if (resolution < 63) r.push_back(resolution);
|
||||
for (int32_t v = resolution; v >= 63; v /= 2) r.push_back(v);
|
||||
std::reverse(r.begin(), r.end());
|
||||
return r;
|
||||
}
|
||||
|
||||
std::vector<float> shape_axis(double bounds, int32_t r) {
|
||||
std::vector<float> a((size_t)r + 1);
|
||||
const double step = 2.0 * bounds / r;
|
||||
for (int32_t i = 0; i <= r; ++i) a[(size_t)i] = (float)(i * step + -bounds);
|
||||
a[(size_t)r] = (float)bounds;
|
||||
return a;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */
|
||||
void dilate(std::vector<uint8_t>& m, int64_t n) {
|
||||
std::vector<uint8_t> t(m.size());
|
||||
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int64_t stride) {
|
||||
for (int64_t p = 0; p < (int64_t)src.size(); ++p) {
|
||||
const int64_t c = (p / stride) % n;
|
||||
uint8_t v = src[(size_t)p];
|
||||
if (c > 0) v |= src[(size_t)(p - stride)];
|
||||
if (c + 1 < n) v |= src[(size_t)(p + stride)];
|
||||
dst[(size_t)p] = v;
|
||||
}
|
||||
};
|
||||
pass(m, t, 1);
|
||||
pass(t, m, n);
|
||||
pass(m, t, n * n);
|
||||
m.swap(t);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
|
||||
double level, bool last) {
|
||||
const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1;
|
||||
std::vector<uint8_t> near((size_t)(np * np * np), 0);
|
||||
auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); };
|
||||
const float lv = (float)level;
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k) {
|
||||
const int64_t p = (i * np + j) * np + k;
|
||||
const float raw = prev[(size_t)p];
|
||||
if (std::isnan(raw)) continue;
|
||||
const float v = raw - lv;
|
||||
const int s = sgn(v);
|
||||
bool cross = std::fabs(v) < 0.95f;
|
||||
const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k },
|
||||
{ i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } };
|
||||
for (int q = 0; q < 6 && !cross; ++q) {
|
||||
const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2];
|
||||
/* Outside the grid the reference replicates the border, and a neighbour not
|
||||
* sampled stands in as the point itself: neither crosses. */
|
||||
if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue;
|
||||
const float u = prev[(size_t)((a * np + b) * np + c)];
|
||||
if (std::isnan(u)) continue;
|
||||
cross = sgn(u - lv) != s;
|
||||
}
|
||||
near[(size_t)p] = cross;
|
||||
}
|
||||
if (!last) dilate(near, np);
|
||||
std::vector<uint8_t> mark((size_t)(n * n * n), 0);
|
||||
auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; };
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k)
|
||||
if (near[(size_t)((i * np + j) * np + k)])
|
||||
mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1;
|
||||
dilate(mark, n);
|
||||
if (last) dilate(mark, n);
|
||||
std::vector<uint32_t> pts;
|
||||
for (int64_t p = 0; p < (int64_t)mark.size(); ++p)
|
||||
if (mark[(size_t)p]) pts.push_back((uint32_t)p);
|
||||
return pts;
|
||||
}
|
||||
|
||||
/* ================================================================== marching cubes */
|
||||
namespace {
|
||||
|
||||
/* Corner c of a cube is at (c & 1, c >> 1 & 1, c >> 2 & 1) along the grid's (i, j, k). Edge e is
|
||||
* along axis e / 4 from corner kEdge[e][0] to kEdge[e][1]. */
|
||||
struct McTables {
|
||||
int32_t edge[12][2];
|
||||
/* Each case's triangles as edge triples, -1 ended. */
|
||||
int8_t tri[256][31];
|
||||
};
|
||||
|
||||
McTables build_tables() {
|
||||
McTables T{};
|
||||
int ne = 0;
|
||||
for (int a = 0; a < 3; ++a)
|
||||
for (int c = 0; c < 8; ++c)
|
||||
if (!(c >> a & 1)) { T.edge[ne][0] = c; T.edge[ne][1] = c | (1 << a); ++ne; }
|
||||
auto edge_of = [&](int c0, int c1) {
|
||||
for (int e = 0; e < 12; ++e)
|
||||
if ((T.edge[e][0] == c0 && T.edge[e][1] == c1) ||
|
||||
(T.edge[e][0] == c1 && T.edge[e][1] == c0))
|
||||
return e;
|
||||
return -1;
|
||||
};
|
||||
auto pos = [](int c, double* p) { p[0] = c & 1; p[1] = c >> 1 & 1; p[2] = c >> 2 & 1; };
|
||||
for (int m = 0; m < 256; ++m) {
|
||||
for (int i = 0; i < 31; ++i) T.tri[m][i] = -1;
|
||||
if (m == 0 || m == 255) continue;
|
||||
auto in = [&](int c) { return (m >> c & 1) != 0; };
|
||||
/* Each face's segments between its crossing edges. A face with all four edges crossing
|
||||
* (its inside corners diagonal) separates the inside corners, the rule both cubes that
|
||||
* share the face apply, so the surface has no cracks. */
|
||||
std::vector<std::array<int, 2>> seg;
|
||||
for (int a = 0; a < 3; ++a)
|
||||
for (int s = 0; s < 2; ++s) {
|
||||
const int u = (a + 1) % 3, v = (a + 2) % 3;
|
||||
const int base = s << a;
|
||||
const int cyc[4] = { base, base | (1 << u), base | (1 << u) | (1 << v),
|
||||
base | (1 << v) };
|
||||
int fe[4];
|
||||
bool cr[4];
|
||||
int ncr = 0;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
fe[q] = edge_of(cyc[q], cyc[(q + 1) % 4]);
|
||||
cr[q] = in(cyc[q]) != in(cyc[(q + 1) % 4]);
|
||||
ncr += cr[q];
|
||||
}
|
||||
if (ncr == 2) {
|
||||
int a0 = -1, a1 = -1;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
if (!cr[q]) continue;
|
||||
if (a0 < 0) a0 = fe[q]; else a1 = fe[q];
|
||||
}
|
||||
seg.push_back({ a0, a1 });
|
||||
} else if (ncr == 4) {
|
||||
for (int q = 0; q < 4; ++q)
|
||||
if (in(cyc[q])) seg.push_back({ fe[(q + 3) % 4], fe[q] });
|
||||
}
|
||||
}
|
||||
/* The segments close into loops; each crossing edge is in exactly two. */
|
||||
std::vector<bool> used(seg.size(), false);
|
||||
int nt = 0;
|
||||
for (size_t s0 = 0; s0 < seg.size(); ++s0) {
|
||||
if (used[s0]) continue;
|
||||
std::vector<int> loop = { seg[s0][0], seg[s0][1] };
|
||||
used[s0] = true;
|
||||
for (bool grew = true; grew;) {
|
||||
grew = false;
|
||||
for (size_t q = 0; q < seg.size(); ++q) {
|
||||
if (used[q]) continue;
|
||||
const int tail = loop.back();
|
||||
int nx = -1;
|
||||
if (seg[q][0] == tail) nx = seg[q][1];
|
||||
else if (seg[q][1] == tail) nx = seg[q][0];
|
||||
if (nx < 0) continue;
|
||||
used[q] = true;
|
||||
grew = true;
|
||||
if (nx != loop.front()) loop.push_back(nx);
|
||||
}
|
||||
}
|
||||
/* Orientation: the loop's normal (Newell's, over the edges' midpoints) points from the
|
||||
* inside corners to the outside ones. */
|
||||
double nrm[3] = { 0, 0, 0 }, out[3] = { 0, 0, 0 };
|
||||
std::vector<std::array<double, 3>> mid;
|
||||
for (int e : loop) {
|
||||
double p0[3], p1[3];
|
||||
pos(T.edge[e][0], p0);
|
||||
pos(T.edge[e][1], p1);
|
||||
mid.push_back({ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2 });
|
||||
const double sg = in(T.edge[e][0]) ? 1.0 : -1.0;
|
||||
for (int d = 0; d < 3; ++d) out[d] += sg * (p1[d] - p0[d]);
|
||||
}
|
||||
for (size_t q = 0; q < mid.size(); ++q) {
|
||||
const auto& c = mid[q];
|
||||
const auto& d = mid[(q + 1) % mid.size()];
|
||||
nrm[0] += (c[1] - d[1]) * (c[2] + d[2]);
|
||||
nrm[1] += (c[2] - d[2]) * (c[0] + d[0]);
|
||||
nrm[2] += (c[0] - d[0]) * (c[1] + d[1]);
|
||||
}
|
||||
if (nrm[0] * out[0] + nrm[1] * out[1] + nrm[2] * out[2] < 0)
|
||||
std::reverse(loop.begin(), loop.end());
|
||||
for (size_t q = 1; q + 1 < loop.size() && nt < 10; ++q) {
|
||||
T.tri[m][3 * nt] = (int8_t)loop[0];
|
||||
T.tri[m][3 * nt + 1] = (int8_t)loop[q];
|
||||
T.tri[m][3 * nt + 2] = (int8_t)loop[q + 1];
|
||||
++nt;
|
||||
}
|
||||
}
|
||||
}
|
||||
return T;
|
||||
}
|
||||
|
||||
const McTables& tables() {
|
||||
static const McTables t = build_tables();
|
||||
return t;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
|
||||
ShapeMesh* out) {
|
||||
out->v.clear();
|
||||
out->f.clear();
|
||||
const McTables& T = tables();
|
||||
const int64_t n = (int64_t)r + 1, nn = n * n;
|
||||
const float lv = (float)level;
|
||||
const double sc = 2.0 * bounds / (double)n;
|
||||
/* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the
|
||||
* y and z edges of planes i and i + 1. */
|
||||
std::vector<int32_t> ex((size_t)nn), ey[2], ez[2];
|
||||
for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); }
|
||||
auto value = [&](int64_t i, int64_t j, int64_t k) {
|
||||
return field[(size_t)((i * n + j) * n + k)];
|
||||
};
|
||||
for (int64_t i = 0; i + 1 < n; ++i) {
|
||||
std::fill(ex.begin(), ex.end(), -1);
|
||||
if (i > 0) {
|
||||
std::swap(ey[0], ey[1]);
|
||||
std::swap(ez[0], ez[1]);
|
||||
std::fill(ey[1].begin(), ey[1].end(), -1);
|
||||
std::fill(ez[1].begin(), ez[1].end(), -1);
|
||||
}
|
||||
for (int64_t j = 0; j + 1 < n; ++j)
|
||||
for (int64_t k = 0; k + 1 < n; ++k) {
|
||||
float v[8];
|
||||
bool skip = false;
|
||||
int m = 0;
|
||||
for (int c = 0; c < 8 && !skip; ++c) {
|
||||
v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
|
||||
if (std::isnan(v[c])) skip = true;
|
||||
else if (v[c] > lv) m |= 1 << c;
|
||||
}
|
||||
if (skip || m == 0 || m == 255) continue;
|
||||
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
|
||||
const int e = T.tri[m][t];
|
||||
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
|
||||
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
|
||||
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
|
||||
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
|
||||
: &ez[bi][(size_t)((j + bj) * n + k)];
|
||||
if (*slot < 0) {
|
||||
const float t0 = v[c0], t1 = v[c1];
|
||||
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
|
||||
float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
|
||||
g[a] += f;
|
||||
*slot = (int32_t)(out->v.size() / 3);
|
||||
for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds));
|
||||
}
|
||||
out->f.push_back((uint32_t)*slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== files */
|
||||
namespace {
|
||||
|
||||
void put(std::string& s, const void* p, size_t n) { s.append((const char*)p, n); }
|
||||
template <class T> void put_v(std::string& s, T v) { put(s, &v, sizeof v); }
|
||||
|
||||
/* Area-weighted vertex normals, unit length (zero for a vertex of only degenerate faces). */
|
||||
std::vector<float> vertex_normals(const ShapeMesh& m) {
|
||||
std::vector<float> nrm(m.v.size(), 0.0f);
|
||||
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
|
||||
const float* a = &m.v[(size_t)m.f[t] * 3];
|
||||
const float* b = &m.v[(size_t)m.f[t + 1] * 3];
|
||||
const float* c = &m.v[(size_t)m.f[t + 2] * 3];
|
||||
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
|
||||
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
|
||||
const float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
|
||||
u[0] * w[1] - u[1] * w[0] };
|
||||
for (int q = 0; q < 3; ++q)
|
||||
for (int d = 0; d < 3; ++d) nrm[(size_t)m.f[t + q] * 3 + d] += x[d];
|
||||
}
|
||||
for (size_t i = 0; i + 2 < nrm.size(); i += 3) {
|
||||
const float l =
|
||||
std::sqrt(nrm[i] * nrm[i] + nrm[i + 1] * nrm[i + 1] + nrm[i + 2] * nrm[i + 2]);
|
||||
if (l > 0.0f) for (int d = 0; d < 3; ++d) nrm[i + d] /= l;
|
||||
}
|
||||
return nrm;
|
||||
}
|
||||
|
||||
std::string glb(const ShapeMesh& m) {
|
||||
const size_t nv = m.v.size() / 3, ni = m.f.size();
|
||||
const std::vector<float> nrm = vertex_normals(m);
|
||||
float lo[3] = { INFINITY, INFINITY, INFINITY }, hi[3] = { -INFINITY, -INFINITY, -INFINITY };
|
||||
for (size_t i = 0; i < nv; ++i)
|
||||
for (int d = 0; d < 3; ++d) {
|
||||
lo[d] = std::min(lo[d], m.v[i * 3 + d]);
|
||||
hi[d] = std::max(hi[d], m.v[i * 3 + d]);
|
||||
}
|
||||
const size_t vb = nv * 12, ib = ni * 4;
|
||||
std::string bin;
|
||||
put(bin, m.v.data(), vb);
|
||||
put(bin, nrm.data(), vb);
|
||||
put(bin, m.f.data(), ib);
|
||||
while (bin.size() % 4) bin.push_back('\0');
|
||||
using nlohmann::json;
|
||||
json j;
|
||||
j["asset"] = { { "version", "2.0" }, { "generator", "radiance" } };
|
||||
j["scene"] = 0;
|
||||
j["scenes"] = json::array({ { { "nodes", json::array({ 0 }) } } });
|
||||
j["nodes"] = json::array({ { { "mesh", 0 } } });
|
||||
const json prim = { { "attributes", { { "POSITION", 0 }, { "NORMAL", 1 } } },
|
||||
{ "indices", 2 }, { "mode", 4 } };
|
||||
j["meshes"] = json::array({ { { "primitives", json::array({ prim }) } } });
|
||||
j["buffers"] = json::array({ { { "byteLength", bin.size() } } });
|
||||
j["bufferViews"] = json::array({
|
||||
{ { "buffer", 0 }, { "byteOffset", 0 }, { "byteLength", vb }, { "target", 34962 } },
|
||||
{ { "buffer", 0 }, { "byteOffset", vb }, { "byteLength", vb }, { "target", 34962 } },
|
||||
{ { "buffer", 0 }, { "byteOffset", 2 * vb }, { "byteLength", ib }, { "target", 34963 } } });
|
||||
j["accessors"] = json::array({
|
||||
{ { "bufferView", 0 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" },
|
||||
{ "min", { lo[0], lo[1], lo[2] } }, { "max", { hi[0], hi[1], hi[2] } } },
|
||||
{ { "bufferView", 1 }, { "componentType", 5126 }, { "count", nv }, { "type", "VEC3" } },
|
||||
{ { "bufferView", 2 }, { "componentType", 5125 }, { "count", ni },
|
||||
{ "type", "SCALAR" } } });
|
||||
std::string js = j.dump();
|
||||
while (js.size() % 4) js.push_back(' ');
|
||||
std::string out;
|
||||
put_v<uint32_t>(out, 0x46546C67u); /* "glTF" */
|
||||
put_v<uint32_t>(out, 2);
|
||||
put_v<uint32_t>(out, (uint32_t)(12 + 8 + js.size() + 8 + bin.size()));
|
||||
put_v<uint32_t>(out, (uint32_t)js.size());
|
||||
put_v<uint32_t>(out, 0x4E4F534Au); /* "JSON" */
|
||||
out += js;
|
||||
put_v<uint32_t>(out, (uint32_t)bin.size());
|
||||
put_v<uint32_t>(out, 0x004E4942u); /* "BIN\0" */
|
||||
out += bin;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string obj(const ShapeMesh& m) {
|
||||
std::string s;
|
||||
char line[128];
|
||||
for (size_t i = 0; i + 2 < m.v.size(); i += 3) {
|
||||
const int n = std::snprintf(line, sizeof line, "v %.9g %.9g %.9g\n", (double)m.v[i],
|
||||
(double)m.v[i + 1], (double)m.v[i + 2]);
|
||||
s.append(line, (size_t)n);
|
||||
}
|
||||
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
|
||||
const int n = std::snprintf(line, sizeof line, "f %u %u %u\n", m.f[t] + 1, m.f[t + 1] + 1,
|
||||
m.f[t + 2] + 1);
|
||||
s.append(line, (size_t)n);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string ply(const ShapeMesh& m) {
|
||||
const size_t nv = m.v.size() / 3, nf = m.f.size() / 3;
|
||||
std::string s = "ply\nformat binary_little_endian 1.0\nelement vertex " + std::to_string(nv) +
|
||||
"\nproperty float x\nproperty float y\nproperty float z\nelement face " +
|
||||
std::to_string(nf) + "\nproperty list uchar int vertex_indices\nend_header\n";
|
||||
put(s, m.v.data(), m.v.size() * 4);
|
||||
for (size_t t = 0; t < nf; ++t) {
|
||||
put_v<uint8_t>(s, 3);
|
||||
for (int q = 0; q < 3; ++q) put_v<int32_t>(s, (int32_t)m.f[t * 3 + q]);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string stl(const ShapeMesh& m) {
|
||||
std::string s(80, '\0');
|
||||
std::memcpy(&s[0], "radiance", 8);
|
||||
const size_t nf = m.f.size() / 3;
|
||||
put_v<uint32_t>(s, (uint32_t)nf);
|
||||
for (size_t t = 0; t < nf; ++t) {
|
||||
const float* a = &m.v[(size_t)m.f[t * 3] * 3];
|
||||
const float* b = &m.v[(size_t)m.f[t * 3 + 1] * 3];
|
||||
const float* c = &m.v[(size_t)m.f[t * 3 + 2] * 3];
|
||||
const float u[3] = { b[0] - a[0], b[1] - a[1], b[2] - a[2] };
|
||||
const float w[3] = { c[0] - a[0], c[1] - a[1], c[2] - a[2] };
|
||||
float x[3] = { u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2],
|
||||
u[0] * w[1] - u[1] * w[0] };
|
||||
const float l = std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
|
||||
if (l > 0.0f) for (float& q : x) q /= l;
|
||||
put(s, x, 12);
|
||||
put(s, a, 12);
|
||||
put(s, b, 12);
|
||||
put(s, c, 12);
|
||||
put_v<uint16_t>(s, 0);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
|
||||
std::string* mime, std::string* why) {
|
||||
if (format == "glb") { *bytes = glb(m); *mime = "model/gltf-binary"; return RAD_OK; }
|
||||
if (format == "obj") { *bytes = obj(m); *mime = "model/obj"; return RAD_OK; }
|
||||
if (format == "ply") { *bytes = ply(m); *mime = "application/x-ply"; return RAD_OK; }
|
||||
if (format == "stl") { *bytes = stl(m); *mime = "model/stl"; return RAD_OK; }
|
||||
if (why) *why = "type '" + format + "' is not one this server writes: glb, obj, ply or stl";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ================================================================== the ticket */
|
||||
void ShapeTicket::progress(int32_t steps_done, int32_t points_done) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
steps_done_ = steps_done;
|
||||
points_done_ = points_done;
|
||||
}
|
||||
|
||||
void ShapeTicket::set_field(std::vector<float>&& field, int32_t r) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
field_ = std::move(field);
|
||||
r_ = r;
|
||||
}
|
||||
|
||||
void ShapeTicket::finish(int status, const std::string& why) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (done_) return;
|
||||
done_ = true;
|
||||
status_ = status;
|
||||
why_ = why;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
bool ShapeTicket::wait(int ms) {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return done_; });
|
||||
return done_;
|
||||
}
|
||||
|
||||
bool ShapeTicket::finished() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return done_;
|
||||
}
|
||||
|
||||
int ShapeTicket::status() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return status_;
|
||||
}
|
||||
|
||||
std::string ShapeTicket::why() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return why_;
|
||||
}
|
||||
|
||||
std::vector<float> ShapeTicket::take_field(int32_t* r) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (r) *r = r_;
|
||||
return std::move(field_);
|
||||
}
|
||||
|
||||
void ShapeTicket::progress_of(int32_t* steps_done, int32_t* points_done) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (steps_done) *steps_done = steps_done_;
|
||||
if (points_done) *points_done = points_done_;
|
||||
}
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,137 @@
|
||||
/* shape.h -- shape generation: the request, the channel its field comes back on, and the host
|
||||
* geometry around the model's passes.
|
||||
*
|
||||
* A shape generator (abi/rad_builder.h, rad_declare_shape_generator) makes a 3-D shape from one
|
||||
* picture: it denoises a latent, then decodes it into an occupancy field that is sampled on a
|
||||
* grid. core/gen/shape_driver.h turns a request into those passes; this is what a caller hands it
|
||||
* (the picture already prepared, shape_picture), what it hands back (progress as the steps and
|
||||
* the grid's levels run, then the finest grid), and the geometry both sides share: the sampler's
|
||||
* sigmas, the grid's levels and the points each level queries, and the mesh made of the grid
|
||||
* (shape_mesh) with its file formats.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "mm/media.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace gen {
|
||||
|
||||
/* What the driver knows of the declaration, for the server and the geometry below. */
|
||||
struct ShapeGenInfo {
|
||||
std::string name;
|
||||
int64_t canvas = 0, enc_size = 0, enc_patch = 0;
|
||||
double border_ratio = 0.0;
|
||||
double pix_mean[3] = {}, pix_std[3] = {};
|
||||
int64_t default_steps = 0, max_steps = 0;
|
||||
double default_guidance = 0.0;
|
||||
double bounds = 1.0, level = 0.0;
|
||||
int64_t default_resolution = 0, min_resolution = 0, max_resolution = 0;
|
||||
int64_t max_lanes = 1;
|
||||
};
|
||||
ShapeGenInfo shape_info(const RadShapeGenDecl& d, const std::string& name);
|
||||
|
||||
/* The picture as an SCOND pass carries it (RadShapeGenDecl, "The picture"): `rgba` decoded with
|
||||
* its alpha, out as f32 [(enc_size / enc_patch)^2, 3 enc_patch^2]. Refuses a picture whose alpha
|
||||
* leaves nothing, or a bounding box of one row or column, as the reference does. */
|
||||
int shape_picture(const ShapeGenInfo& g, const mm::FrameRGBA& rgba, std::vector<float>* patches,
|
||||
std::string* why);
|
||||
|
||||
/* The sampler's grid points: numpy's linspace(0, 1, steps) taken to f32. An evaluation at each
|
||||
* but the last steps to the next. */
|
||||
std::vector<float> shape_sigmas(int32_t steps);
|
||||
|
||||
/* The grid's levels, coarsest first: `resolution` halved while it stays at least 63, then
|
||||
* reversed (one level when it is below 63). */
|
||||
std::vector<int32_t> shape_levels(int32_t resolution);
|
||||
|
||||
/* One axis of a level's grid: numpy's linspace(-bounds, bounds, r + 1) in f32. */
|
||||
std::vector<float> shape_axis(double bounds, int32_t r);
|
||||
|
||||
/* The grid points of level `r` (index (i, j, k) at (i (r+1) + j) (r+1) + k) to query, given the
|
||||
* coarser level's field `prev` at resolution `rp` (NaN where it was not sampled): the coarse
|
||||
* points whose sign against `level` differs from a neighbour's, or whose value is within 0.95 of
|
||||
* zero, dilated once unless this is the last level, put at their places on this grid and dilated
|
||||
* twice there (once when the coarse set was). As FlashVDM's hierarchical decoding. */
|
||||
std::vector<uint32_t> shape_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
|
||||
double level, bool last);
|
||||
|
||||
/* A triangle mesh: positions xyz, and faces as three vertex indices, counter-clockwise seen from
|
||||
* outside the shape. */
|
||||
struct ShapeMesh {
|
||||
std::vector<float> v;
|
||||
std::vector<uint32_t> f;
|
||||
};
|
||||
|
||||
/* Marching cubes over `field` ((r+1)^3 values, the layout above) at `level`, inside above it. A
|
||||
* cube with a corner not sampled (NaN) makes nothing. Vertices sit on the grid's edges where the
|
||||
* linear interpolation of their ends crosses the level, one vertex an edge, and grid index g goes
|
||||
* to g 2 bounds / (r + 1) - bounds (RadShapeGenDecl, "The field"). */
|
||||
void shape_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
|
||||
ShapeMesh* out);
|
||||
|
||||
/* The mesh as a file: "glb" (positions, smooth normals and indices), "obj", "ply" (binary) or
|
||||
* "stl" (binary). The content type goes to `mime`. Refuses another format by name. */
|
||||
int shape_export(const ShapeMesh& m, const std::string& format, std::string* bytes,
|
||||
std::string* mime, std::string* why);
|
||||
|
||||
/* ================================================================== the request */
|
||||
class ShapeTicket {
|
||||
public:
|
||||
/* driver side */
|
||||
void progress(int32_t steps_done, int32_t points_done);
|
||||
/* The finest grid, at resolution `r`, and the end. */
|
||||
void finish(int status, const std::string& why = std::string());
|
||||
void set_field(std::vector<float>&& field, int32_t r);
|
||||
|
||||
/* caller side: waits at most `ms` milliseconds for the end; true once it came. */
|
||||
bool wait(int ms);
|
||||
bool finished() const;
|
||||
int status() const;
|
||||
std::string why() const;
|
||||
/* The field, once finished with RAD_OK; moved out. */
|
||||
std::vector<float> take_field(int32_t* r);
|
||||
void progress_of(int32_t* steps_done, int32_t* points_done) const;
|
||||
|
||||
std::atomic<bool> cancel{false};
|
||||
|
||||
/* Written by the driver at submit: the evaluations, the resolution and the guidance. */
|
||||
int32_t steps = 0, resolution = 0;
|
||||
double guidance = 0.0;
|
||||
/* Usage, written by the driver before finish(): the points the decoder was queried at, and
|
||||
* per-phase times. */
|
||||
int64_t points = 0;
|
||||
int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
bool done_ = false;
|
||||
int status_ = RAD_OK;
|
||||
std::string why_;
|
||||
int32_t steps_done_ = 0, points_done_ = 0;
|
||||
std::vector<float> field_;
|
||||
int32_t r_ = 0;
|
||||
};
|
||||
|
||||
struct ShapeRequest {
|
||||
/* The picture, prepared (shape_picture). */
|
||||
std::vector<float> patches;
|
||||
int32_t steps = 0; /* sigma grid points; 0: the model's default */
|
||||
double guidance = NAN; /* NaN: the model's default */
|
||||
int32_t resolution = 0; /* the finest grid's cells a side; 0: the model's default */
|
||||
bool dense = false; /* sample every point of the finest grid, no coarser levels */
|
||||
uint64_t seed = 0;
|
||||
std::shared_ptr<ShapeTicket> ticket;
|
||||
};
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,436 @@
|
||||
/* shape_driver.cpp -- the shape generator's pass driver (shape_driver.h). */
|
||||
#include "shape_driver.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace gen {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
/* Region offsets and sizes, in the enum's order (shape_driver.h), and the total; shared by the
|
||||
* allocation and the VRAM budget. */
|
||||
int64_t carve(const RadShapeGenDecl& d, int64_t (*bytes)[2], int n) {
|
||||
const int64_t side = d.enc_size / d.enc_patch;
|
||||
const int64_t want[] = {
|
||||
side * side * 3 * d.enc_patch * d.enc_patch * 4, /* R_PATCH: f32 */
|
||||
2 * 4, /* R_SIGMA */
|
||||
2 * 4, /* R_SNEXT */
|
||||
2 * 4, /* R_CFG */
|
||||
2 * 4, /* R_PAIR */
|
||||
2 * 4, /* R_LANES */
|
||||
2 * 4, /* R_FLAGS */
|
||||
2 * 2 * 4, /* R_SEED */
|
||||
3 * 4, /* R_LATCU */
|
||||
d.max_query * 3 * 4, /* R_QUERY: f32 */
|
||||
2 * 4, /* R_QCU */
|
||||
};
|
||||
int64_t off = 0;
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r];
|
||||
off = align_up(off + want[r], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int64_t ShapeDriver::device_bytes(const Program& prog) {
|
||||
if (!prog.is_shape_generator()) return 0;
|
||||
int64_t b[R_N][2];
|
||||
return carve(prog.shape_gen, b, R_N);
|
||||
}
|
||||
|
||||
int ShapeDriver::init(const Program& prog, const std::vector<RankIO>& ranks) {
|
||||
fini();
|
||||
if (!prog.is_shape_generator()) return RAD_E_STATE;
|
||||
decl_ = prog.shape_gen;
|
||||
info_ = shape_info(decl_, prog.sgen_name);
|
||||
ranks_ = ranks;
|
||||
n_patch_ = (decl_.enc_size / decl_.enc_patch) * (decl_.enc_size / decl_.enc_patch);
|
||||
patch_dim_ = 3 * decl_.enc_patch * decl_.enc_patch;
|
||||
int64_t b[R_N][2];
|
||||
bytes_ = carve(decl_, b, R_N);
|
||||
for (int r = 0; r < R_N; ++r) {
|
||||
reg_[r].off = b[r][0];
|
||||
reg_[r].bytes = b[r][1];
|
||||
reg_[r].used = 0;
|
||||
}
|
||||
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
|
||||
field_host_ = static_cast<float*>(rad_dev_alloc(decl_.max_query * 4, RAD_MEM_HOST_PINNED));
|
||||
if (!host_ || !field_host_) {
|
||||
RAD_ERR("shape generator: no pinned host memory for the pass staging and the field "
|
||||
"(%lld + %lld bytes)", (long long)bytes_, (long long)(decl_.max_query * 4));
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
std::memset(host_, 0, (size_t)bytes_);
|
||||
dev_.assign(ranks_.size(), nullptr);
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RAD_TRY(rad_dev_set(ranks_[r].device));
|
||||
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
|
||||
if (!dev_[r]) {
|
||||
RAD_ERR("shape generator: rank %zu has no room for the pass staging (%lld bytes)", r,
|
||||
(long long)bytes_);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
}
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
|
||||
out_.assign(ranks_.size(), RadBatch{});
|
||||
sout_.assign(ranks_.size(), RadShapeGenBatch{});
|
||||
free_lanes_.clear();
|
||||
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void ShapeDriver::fini() {
|
||||
for (size_t r = 0; r < dev_.size(); ++r)
|
||||
if (dev_[r]) {
|
||||
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
|
||||
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
|
||||
}
|
||||
dev_.clear();
|
||||
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
|
||||
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
|
||||
if (field_host_) rad_dev_free(field_host_, RAD_MEM_HOST_PINNED);
|
||||
host_ = nullptr;
|
||||
field_host_ = nullptr;
|
||||
}
|
||||
|
||||
/* ================================================================== requests */
|
||||
int ShapeDriver::submit(std::unique_ptr<ShapeRequest> r, std::string* why) {
|
||||
if (!r || !r->ticket) return RAD_E_INVAL;
|
||||
const RadShapeGenDecl& d = decl_;
|
||||
auto no = [&](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
if ((int64_t)r->patches.size() != n_patch_ * patch_dim_)
|
||||
return no("the picture is not prepared for this model's image encoder");
|
||||
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
|
||||
if (steps < 2 || steps > d.max_steps)
|
||||
return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) +
|
||||
" (sigma grid points, the last one the clean shape)");
|
||||
const double cfg = std::isnan(r->guidance) ? d.default_guidance : r->guidance;
|
||||
if (!(cfg >= 0.0) || !std::isfinite(cfg))
|
||||
return no("guidance_scale must be finite and not negative");
|
||||
const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)d.default_resolution;
|
||||
if (res < d.min_resolution || res > d.max_resolution)
|
||||
return no("octree_resolution must be " + std::to_string(d.min_resolution) + ".." +
|
||||
std::to_string(d.max_resolution));
|
||||
|
||||
auto j = std::make_unique<Job>();
|
||||
j->sigmas = shape_sigmas(steps);
|
||||
j->evals = steps - 1;
|
||||
j->cfg = (float)cfg;
|
||||
j->levels = r->dense ? std::vector<int32_t>{ res } : shape_levels(res);
|
||||
ShapeTicket& t = *r->ticket;
|
||||
t.steps = j->evals;
|
||||
t.resolution = res;
|
||||
t.guidance = cfg;
|
||||
t.t_submit_ns = (int64_t)rad_mono_ns();
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (closed_) {
|
||||
if (why) *why = closed_why_;
|
||||
return closed_status_;
|
||||
}
|
||||
j->id = next_id_++;
|
||||
j->req = std::move(r);
|
||||
jobs_.push_back(std::move(j));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void ShapeDriver::shutdown(const char* why, int status) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
closed_ = true;
|
||||
closed_why_ = why ? why : "the engine stopped";
|
||||
closed_status_ = status;
|
||||
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
|
||||
}
|
||||
|
||||
int64_t ShapeDriver::queued() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
int64_t n = 0;
|
||||
for (const auto& j : jobs_) if (!j->admitted) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
int64_t ShapeDriver::running() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
int64_t n = 0;
|
||||
for (const auto& j : jobs_) if (j->admitted) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
ShapeDriver::Job* ShapeDriver::job_locked(uint64_t id) {
|
||||
for (auto& j : jobs_) if (j->id == id) return j.get();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void ShapeDriver::release_locked(Job& j) {
|
||||
if (j.lane >= 0) {
|
||||
free_lanes_.push_back(j.lane);
|
||||
j.lane = -1;
|
||||
}
|
||||
}
|
||||
|
||||
void ShapeDriver::fail_locked(Job& j, int status, const std::string& why) {
|
||||
j.failed = true;
|
||||
j.req->ticket->finish(status, why);
|
||||
}
|
||||
|
||||
/* In arrival order: a request needs only a lane. */
|
||||
void ShapeDriver::admit_locked() {
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (j.admitted || j.failed) continue;
|
||||
if (free_lanes_.empty()) break;
|
||||
j.lane = free_lanes_.back();
|
||||
free_lanes_.pop_back();
|
||||
j.admitted = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* A level of the grid begins: its field unsampled, its points `pts` (every point when `all`). */
|
||||
void ShapeDriver::start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all) {
|
||||
const int32_t r = j.levels[level];
|
||||
const int64_t n = (int64_t)r + 1;
|
||||
j.level = level;
|
||||
j.field.assign((size_t)(n * n * n), NAN);
|
||||
j.axis = shape_axis(decl_.bounds, r);
|
||||
j.all = all;
|
||||
j.pts = std::move(pts);
|
||||
j.n_pts = all ? n * n * n : (int64_t)j.pts.size();
|
||||
j.next = 0;
|
||||
}
|
||||
|
||||
/* ================================================================== staging */
|
||||
int ShapeDriver::upload() {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r)
|
||||
for (int g = 0; g < R_N; ++g) {
|
||||
if (reg_[g].used <= 0) continue;
|
||||
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
|
||||
reg_[g].used, ranks_[r].stream));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void ShapeDriver::stage_common(const Job& j) {
|
||||
const int32_t lanes[2] = { j.lane, j.lane };
|
||||
const int32_t cu[3] = { 0, (int32_t)decl_.latent_rows, (int32_t)(2 * decl_.latent_rows) };
|
||||
std::memcpy(hptr<int32_t>(R_LANES), lanes, sizeof lanes);
|
||||
std::memcpy(hptr<int32_t>(R_LATCU), cu, sizeof cu);
|
||||
reg_[R_LANES].used = sizeof lanes;
|
||||
reg_[R_LATCU].used = sizeof cu;
|
||||
}
|
||||
|
||||
void ShapeDriver::base_batches(const Job& j, int64_t n_tok, int kind, int step) {
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RadBatch& B = out_[r];
|
||||
RadShapeGenBatch& S = sout_[r];
|
||||
const int ri = (int)r;
|
||||
B = RadBatch{};
|
||||
B.step = step;
|
||||
B.phase = RAD_PHASE_PREFILL;
|
||||
B.n_tok = n_tok;
|
||||
B.n_seq = 1;
|
||||
B.max_q_len = (int32_t)n_tok;
|
||||
B.max_q_len_prefill = (int32_t)n_tok;
|
||||
B.gen = kind;
|
||||
S = RadShapeGenBatch{};
|
||||
S.lane = j.lane;
|
||||
S.patches = dptr<float>(ri, R_PATCH);
|
||||
S.step = j.step;
|
||||
S.n_steps = j.evals;
|
||||
S.sigma = dptr<float>(ri, R_SIGMA);
|
||||
S.sigma_next = dptr<float>(ri, R_SNEXT);
|
||||
S.cfg = dptr<float>(ri, R_CFG);
|
||||
S.pair = dptr<int32_t>(ri, R_PAIR);
|
||||
S.lanes = dptr<int32_t>(ri, R_LANES);
|
||||
S.flags = dptr<int32_t>(ri, R_FLAGS);
|
||||
S.seed = dptr<uint32_t>(ri, R_SEED);
|
||||
S.lat_cu = dptr<int32_t>(ri, R_LATCU);
|
||||
S.query = dptr<float>(ri, R_QUERY);
|
||||
S.query_cu = dptr<int32_t>(ri, R_QCU);
|
||||
B.sgen_b = &S;
|
||||
}
|
||||
pass_.kind = kind;
|
||||
pass_.job = j.id;
|
||||
}
|
||||
|
||||
/* ================================================================== the passes */
|
||||
const RadBatch* ShapeDriver::next(int step) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
pass_ = Pass{};
|
||||
rb_.clear();
|
||||
if (closed_) return nullptr;
|
||||
/* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe
|
||||
* because next() runs between passes, with nothing in flight. */
|
||||
for (auto it = jobs_.begin(); it != jobs_.end();) {
|
||||
Job& j = **it;
|
||||
const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire);
|
||||
if (!(j.failed || cancelled || j.finished)) { ++it; continue; }
|
||||
if (cancelled && !j.failed && !j.finished)
|
||||
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
|
||||
release_locked(j);
|
||||
it = jobs_.erase(it);
|
||||
}
|
||||
admit_locked();
|
||||
|
||||
/* 1. The decoding of a denoised lane: its latent, then its grid. */
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (!j.admitted || j.failed || !j.cond_done || j.step < j.evals) continue;
|
||||
return j.latent_done ? build_query(j, step) : build_latent(j, step);
|
||||
}
|
||||
/* 2. A picture. */
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
|
||||
}
|
||||
/* 3. The oldest lane's next step. */
|
||||
for (auto& jp : jobs_) {
|
||||
Job& j = *jp;
|
||||
if (j.admitted && !j.failed && j.cond_done && j.step < j.evals) return build_step(j, step);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const RadBatch* ShapeDriver::batch_for(int rank) const {
|
||||
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
|
||||
return &out_[(size_t)rank];
|
||||
}
|
||||
|
||||
const RadBatch* ShapeDriver::build_cond(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
std::memcpy(hptr<float>(R_PATCH), j.req->patches.data(), j.req->patches.size() * 4);
|
||||
reg_[R_PATCH].used = (int64_t)j.req->patches.size() * 4;
|
||||
stage_common(j);
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, n_patch_, RAD_GEN_PASS_SCOND, step);
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
/* The two entries of the step: the picture's latent guided against the unconditioned one, which
|
||||
* reads the same lane and moves nothing. */
|
||||
const RadBatch* ShapeDriver::build_step(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
const float s = j.sigmas[(size_t)j.step], sn = j.sigmas[(size_t)j.step + 1];
|
||||
const float sig[2] = { s, s }, nxt[2] = { sn, sn }, cfg[2] = { j.cfg, 1.0f };
|
||||
const int32_t pair[2] = { 1, -2 };
|
||||
const int32_t flags[2] = { j.step == 0 ? (int32_t)RAD_GEN_F_FIRST : 0, 0 };
|
||||
const uint32_t lo = (uint32_t)j.req->seed, hi = (uint32_t)(j.req->seed >> 32);
|
||||
const uint32_t seed[4] = { lo, hi, lo, hi };
|
||||
auto stage = [&](int r, const void* p, int64_t n) {
|
||||
std::memcpy(host_ + reg_[r].off, p, (size_t)n);
|
||||
reg_[r].used = n;
|
||||
};
|
||||
stage(R_SIGMA, sig, sizeof sig);
|
||||
stage(R_SNEXT, nxt, sizeof nxt);
|
||||
stage(R_CFG, cfg, sizeof cfg);
|
||||
stage(R_PAIR, pair, sizeof pair);
|
||||
stage(R_FLAGS, flags, sizeof flags);
|
||||
stage(R_SEED, seed, sizeof seed);
|
||||
stage_common(j);
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, decl_.step_rows, RAD_GEN_PASS_SSTEP, step);
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
const RadBatch* ShapeDriver::build_latent(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
stage_common(j);
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, decl_.latent_rows, RAD_GEN_PASS_SLATENT, step);
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
/* The level's next run of points, at most max_query, as x, y, z. */
|
||||
const RadBatch* ShapeDriver::build_query(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
const int64_t n = std::min<int64_t>(decl_.max_query, j.n_pts - j.next);
|
||||
const int64_t side = (int64_t)j.levels[j.level] + 1;
|
||||
float* q = hptr<float>(R_QUERY);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t p = j.all ? j.next + i : (int64_t)j.pts[(size_t)(j.next + i)];
|
||||
q[3 * i] = j.axis[(size_t)(p / (side * side))];
|
||||
q[3 * i + 1] = j.axis[(size_t)(p / side % side)];
|
||||
q[3 * i + 2] = j.axis[(size_t)(p % side)];
|
||||
}
|
||||
reg_[R_QUERY].used = n * 3 * 4;
|
||||
const int32_t qcu[2] = { 0, (int32_t)n };
|
||||
std::memcpy(hptr<int32_t>(R_QCU), qcu, sizeof qcu);
|
||||
reg_[R_QCU].used = sizeof qcu;
|
||||
stage_common(j);
|
||||
if (upload() < 0) return nullptr;
|
||||
base_batches(j, n, RAD_GEN_PASS_SQUERY, step);
|
||||
for (auto& S : sout_) S.n_query = n;
|
||||
pass_.n_query = n;
|
||||
rb_.assign(1, Readback{ decl_.field_out, n * 4, field_host_ });
|
||||
return &out_[0];
|
||||
}
|
||||
|
||||
int ShapeDriver::done() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
const int64_t now = (int64_t)rad_mono_ns();
|
||||
Job* j = job_locked(pass_.job);
|
||||
switch (j ? pass_.kind : 0) {
|
||||
case RAD_GEN_PASS_SCOND:
|
||||
j->cond_done = true;
|
||||
j->req->ticket->t_cond_ns = now;
|
||||
/* The patches are on the card for good; the request keeps no copy. */
|
||||
std::vector<float>().swap(j->req->patches);
|
||||
break;
|
||||
case RAD_GEN_PASS_SSTEP:
|
||||
++j->step;
|
||||
j->req->ticket->progress(j->step, 0);
|
||||
if (j->step >= j->evals) j->req->ticket->t_denoised_ns = now;
|
||||
break;
|
||||
case RAD_GEN_PASS_SLATENT:
|
||||
j->latent_done = true;
|
||||
start_level(*j, 0, {}, true);
|
||||
break;
|
||||
case RAD_GEN_PASS_SQUERY: {
|
||||
const int64_t n = pass_.n_query;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t p = j->all ? j->next + i : (int64_t)j->pts[(size_t)(j->next + i)];
|
||||
j->field[(size_t)p] = field_host_[i];
|
||||
}
|
||||
j->next += n;
|
||||
j->points += n;
|
||||
j->req->ticket->progress(j->step, (int32_t)std::min<int64_t>(j->points, INT32_MAX));
|
||||
if (j->next < j->n_pts) break;
|
||||
/* The level is complete: the next one's points, or the end (also when no point of this
|
||||
* level is near the surface, which leaves the finer levels nothing to sample). */
|
||||
if (j->level + 1 < j->levels.size()) {
|
||||
const int32_t rp = j->levels[j->level], r = j->levels[j->level + 1];
|
||||
const bool last = j->level + 2 == j->levels.size();
|
||||
std::vector<uint32_t> pts = shape_refine(j->field, rp, r, decl_.level, last);
|
||||
if (!pts.empty()) {
|
||||
start_level(*j, j->level + 1, std::move(pts), false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
ShapeTicket& t = *j->req->ticket;
|
||||
t.points = j->points;
|
||||
t.t_done_ns = now;
|
||||
t.set_field(std::move(j->field), j->levels[j->level]);
|
||||
j->finished = true;
|
||||
t.finish(RAD_OK);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
pass_ = Pass{};
|
||||
rb_.clear();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,141 @@
|
||||
/* shape_driver.h -- the shape generator's pass driver (shape.h; abi/rad_builder.h's
|
||||
* RadShapeGenDecl describes the passes).
|
||||
*
|
||||
* Driven by the engine thread like the other drivers (pass.h): `next()` picks and stages a pass,
|
||||
* `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads
|
||||
* through `submit()` and leave through their ShapeTicket.
|
||||
*
|
||||
* A request holds a lane from admission to its last query. Its picture is prepared and its
|
||||
* schedule fixed at submit; between passes the driver only stages, except when a level of the
|
||||
* grid is complete, when it works out the points of the next (shape_refine).
|
||||
*
|
||||
* Pass priority, one pass at a time:
|
||||
*
|
||||
* 1. SLATENT, then the SQUERY passes level by level, of a lane whose denoising is done: they
|
||||
* finish a request and free its lane.
|
||||
* 2. SCOND of an admitted request, so its steps can follow the current request's without a gap.
|
||||
* 3. SSTEP of the oldest lane with steps left. Requests are denoised one after another, not in
|
||||
* turns: a pass is one request's, so taking turns would only delay the first.
|
||||
*/
|
||||
#pragma once
|
||||
#include "shape.h"
|
||||
#include "pass.h"
|
||||
#include "device/device.h"
|
||||
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
|
||||
namespace rad {
|
||||
namespace gen {
|
||||
|
||||
class ShapeDriver final : public IPassDriver {
|
||||
public:
|
||||
struct RankIO {
|
||||
int device = 0;
|
||||
RadStream stream = nullptr;
|
||||
};
|
||||
|
||||
int init(const Program& prog, const std::vector<RankIO>& ranks);
|
||||
void fini();
|
||||
~ShapeDriver() override { fini(); }
|
||||
|
||||
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
|
||||
static int64_t device_bytes(const Program& prog);
|
||||
|
||||
/* ---------------------------------------------------------- HTTP threads */
|
||||
/* Queue a request, refused at once with `why` when it can never run. */
|
||||
int submit(std::unique_ptr<ShapeRequest> r, std::string* why);
|
||||
const ShapeGenInfo& info() const { return info_; }
|
||||
void shutdown(const char* why, int status) override;
|
||||
|
||||
/* ---------------------------------------------------------- the engine thread */
|
||||
const RadBatch* next(int step) override;
|
||||
const RadBatch* batch_for(int rank) const override;
|
||||
const std::vector<Readback>& readbacks() const override { return rb_; }
|
||||
int done() override;
|
||||
|
||||
int64_t queued() const override;
|
||||
int64_t running() const override;
|
||||
|
||||
private:
|
||||
struct Job {
|
||||
uint64_t id = 0;
|
||||
std::unique_ptr<ShapeRequest> req;
|
||||
std::vector<float> sigmas; /* the request's grid points */
|
||||
float cfg = 0.0f;
|
||||
int32_t evals = 0; /* steps the request takes: grid points less one */
|
||||
int32_t lane = -1;
|
||||
bool admitted = false;
|
||||
bool cond_done = false;
|
||||
int32_t step = 0; /* steps done */
|
||||
bool latent_done = false;
|
||||
/* The grid: its levels, the one being sampled, its field (NaN where not sampled) and
|
||||
* the points it samples, all of them when `all` (the coarsest level, and dense
|
||||
* sampling); `next` is the first not yet queried. */
|
||||
std::vector<int32_t> levels;
|
||||
size_t level = 0;
|
||||
std::vector<float> field;
|
||||
std::vector<float> axis;
|
||||
std::vector<uint32_t> pts;
|
||||
bool all = false;
|
||||
int64_t n_pts = 0, next = 0;
|
||||
int64_t points = 0; /* every level's, for the usage */
|
||||
bool failed = false;
|
||||
bool finished = false;
|
||||
};
|
||||
struct Pass {
|
||||
int kind = 0;
|
||||
uint64_t job = 0;
|
||||
int64_t n_query = 0;
|
||||
};
|
||||
struct Region { int64_t off = 0, bytes = 0, used = 0; };
|
||||
enum { R_PATCH, R_SIGMA, R_SNEXT, R_CFG, R_PAIR, R_LANES, R_FLAGS, R_SEED, R_LATCU, R_QUERY,
|
||||
R_QCU, R_N };
|
||||
|
||||
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
template <class T> T* dptr(int rank, int r) const {
|
||||
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
|
||||
}
|
||||
int upload();
|
||||
/* What every pass carries: the lane twice (the step's two entries) and the latents' bounds. */
|
||||
void stage_common(const Job& j);
|
||||
void base_batches(const Job& j, int64_t n_tok, int kind, int step);
|
||||
void start_level(Job& j, size_t level, std::vector<uint32_t>&& pts, bool all);
|
||||
|
||||
void admit_locked();
|
||||
void release_locked(Job& j);
|
||||
void fail_locked(Job& j, int status, const std::string& why);
|
||||
Job* job_locked(uint64_t id);
|
||||
|
||||
const RadBatch* build_cond(Job& j, int step);
|
||||
const RadBatch* build_step(Job& j, int step);
|
||||
const RadBatch* build_latent(Job& j, int step);
|
||||
const RadBatch* build_query(Job& j, int step);
|
||||
|
||||
RadShapeGenDecl decl_{};
|
||||
ShapeGenInfo info_;
|
||||
int64_t n_patch_ = 0, patch_dim_ = 0;
|
||||
std::vector<RankIO> ranks_;
|
||||
|
||||
char* host_ = nullptr; /* pinned, same layout as each slab */
|
||||
int64_t bytes_ = 0;
|
||||
std::vector<void*> dev_;
|
||||
Region reg_[R_N];
|
||||
float* field_host_ = nullptr;
|
||||
std::vector<Readback> rb_;
|
||||
|
||||
std::vector<RadBatch> out_; /* one per rank */
|
||||
std::vector<RadShapeGenBatch> sout_;
|
||||
Pass pass_;
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
|
||||
std::vector<int32_t> free_lanes_;
|
||||
uint64_t next_id_ = 1;
|
||||
bool closed_ = false;
|
||||
std::string closed_why_;
|
||||
int closed_status_ = RAD_E_STATE;
|
||||
};
|
||||
|
||||
} /* namespace gen */
|
||||
} /* namespace rad */
|
||||
@@ -198,6 +198,9 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
|
||||
int64_t (*bytes)[2], int n) {
|
||||
/* A guided model's VCOND carries the negative prompt after the positive. */
|
||||
const int64_t prompts = d.guidance ? 2 : 1;
|
||||
/* A schedule's steps: a request's, at most max_steps, plus the refinement rungs an upscaling
|
||||
* request appends after them (video_schedule). */
|
||||
const int64_t sched_cap = (int64_t)d.max_steps + std::max<int32_t>(d.n_refine_rungs, 0);
|
||||
const int64_t want[] = {
|
||||
prompts * d.max_text * 4, /* R_TOK */
|
||||
prompts * d.max_text * 4, /* R_POS */
|
||||
@@ -205,8 +208,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
|
||||
3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */
|
||||
RAD_VGEOM_N * 4, /* R_GEOM */
|
||||
16 * 4, /* R_SCHED */
|
||||
d.max_steps * 4, /* R_TV */
|
||||
d.max_steps * 4, /* R_TA */
|
||||
sched_cap * 4, /* R_TV */
|
||||
sched_cap * 4, /* R_TA */
|
||||
4 * 4, /* R_SEED */
|
||||
4, /* R_LANE */
|
||||
4, /* R_FIRST */
|
||||
@@ -1008,6 +1011,11 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
|
||||
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
|
||||
reg_[R_IMG].used = (int64_t)img.size() * 2;
|
||||
}
|
||||
if ((int64_t)j.sched.steps * 4 > reg_[R_TV].bytes) {
|
||||
fail_locked(j, RAD_E_STATE, "the schedule's " + std::to_string(j.sched.steps) +
|
||||
" steps are more than the timestep regions hold");
|
||||
return nullptr;
|
||||
}
|
||||
float* tv = hptr<float>(R_TV);
|
||||
float* ta = hptr<float>(R_TA);
|
||||
for (int32_t i = 0; i < j.sched.steps; ++i) {
|
||||
@@ -1238,7 +1246,7 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
|
||||
} else {
|
||||
const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3;
|
||||
stage_frames = ng > 23 ? gd[23] : 0;
|
||||
if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
|
||||
if (nf < 1 || stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
|
||||
fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
+31
-1
@@ -39,6 +39,7 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
|
||||
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
|
||||
if (ngram_window >= 0) base.ngram_window = ngram_window;
|
||||
if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist;
|
||||
if (!suppress.empty()) base.suppress_tokens = suppress;
|
||||
return base;
|
||||
}
|
||||
|
||||
@@ -156,6 +157,23 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
|
||||
out->ngram_whitelist.push_back((int)id);
|
||||
}
|
||||
}
|
||||
|
||||
/* transformers' suppress_tokens, a JSON array of ids. Dropped entry by entry like the
|
||||
* whitelist above. */
|
||||
it = j.find("suppress_tokens");
|
||||
if (it != j.end() && !it->is_array()) {
|
||||
RAD_WARN("%s states suppress_tokens that is not an array; ignoring it", src);
|
||||
} else if (it != j.end()) {
|
||||
for (const auto& v : *it) {
|
||||
const int64_t id = v.is_number_integer() ? v.get<int64_t>() : -1;
|
||||
if (id < 0 || id > INT32_MAX) {
|
||||
RAD_WARN("%s states a suppress_tokens entry outside [0, %d]; ignoring it",
|
||||
src, INT32_MAX);
|
||||
continue;
|
||||
}
|
||||
out->suppress.push_back((int)id);
|
||||
}
|
||||
}
|
||||
return out->any();
|
||||
}
|
||||
|
||||
@@ -175,7 +193,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
nlohmann::json j = nlohmann::json::object();
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
|
||||
"no_repeat_ngram_size", "no_repeat_ngram_window_size",
|
||||
"no_repeat_ngram_whitelist" };
|
||||
"no_repeat_ngram_whitelist", "suppress_tokens" };
|
||||
for (const char* k : kFields) {
|
||||
const char* v = get(k);
|
||||
if (!v || !*v) continue;
|
||||
@@ -195,6 +213,18 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (std::strcmp(k, "suppress_tokens") == 0) {
|
||||
/* An array of scalars is flattened to a space-separated string (flatten_json). */
|
||||
nlohmann::json ids = nlohmann::json::array();
|
||||
char* p = const_cast<char*>(v);
|
||||
for (char* e = nullptr;; p = e) {
|
||||
const long long id = std::strtoll(p, &e, 10);
|
||||
if (e == p) break;
|
||||
ids.push_back(id);
|
||||
}
|
||||
j[k] = std::move(ids);
|
||||
continue;
|
||||
}
|
||||
char* end = nullptr;
|
||||
const double d = std::strtod(v, &end);
|
||||
if (end == v) {
|
||||
|
||||
+4
-1
@@ -33,10 +33,13 @@ struct GenSampling {
|
||||
* has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a
|
||||
* JSON array of ids. Empty means not stated. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
/* transformers' suppress_tokens: ids never sampled. Empty means not stated. */
|
||||
std::vector<int32_t> suppress;
|
||||
|
||||
bool any() const {
|
||||
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
|
||||
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty();
|
||||
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty() ||
|
||||
!suppress.empty();
|
||||
}
|
||||
|
||||
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
|
||||
|
||||
+14
-10
@@ -381,12 +381,16 @@ int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
|
||||
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
if (counted) {
|
||||
const int64_t was = q.window_blocks * q.bytes_per_block;
|
||||
/* The plan counted this group's snapshot section, so both totals carry `was`.
|
||||
* Saturating hides an accounting bug; surface it in debug builds. */
|
||||
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was &&
|
||||
"runtime window: snapshot byte totals below the section being removed");
|
||||
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
|
||||
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
|
||||
/* The plan counted this group's snapshot section, so both totals carry `was`; less
|
||||
* is an accounting bug, and the pool would be sized from a wrong total. */
|
||||
if (window_ck_bytes_ < was || checkpoint_bytes_ < was) {
|
||||
RAD_ERR("kv group %d: runtime window: the snapshot byte totals (%lld, %lld) are "
|
||||
"below the %lld-byte section being removed", (int)g,
|
||||
(long long)window_ck_bytes_, (long long)checkpoint_bytes_, (long long)was);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
window_ck_bytes_ -= was;
|
||||
checkpoint_bytes_ -= was;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -520,8 +524,8 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
" vram_kv %10s\n"
|
||||
" short by %10s\n"
|
||||
"Lower --max-num-seqs, or give the cache more of the card: a smaller "
|
||||
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
|
||||
"them for you (spec §6).",
|
||||
"--gpu-headroom-mib, a larger --gpu-memory-mib, or a larger --host-pool-mib. The "
|
||||
"engine will not shrink one of them for you (spec §6).",
|
||||
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -550,8 +554,8 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
}
|
||||
if (p.n_blocks <= 0) {
|
||||
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
|
||||
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or "
|
||||
"lower --max-num-seqs.",
|
||||
"linear/conv costs of %s. Raise --host-pool-mib or --gpu-memory-mib, or lower "
|
||||
"--gpu-headroom-mib or --max-num-seqs.",
|
||||
p.name.c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
|
||||
+21
-2
@@ -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) {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -76,6 +76,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
if (f.unified) b.host_pinned = std::max(b.host_pinned, f.host_pinned);
|
||||
}
|
||||
if (!b.unified) b.host_pinned = 0;
|
||||
/* --gpu-memory-mib is the inverse of --gpu-headroom-mib: N + headroom = the card, in MiB.
|
||||
* Convert once the smallest rank capacity is known. A device that reports no capacity has
|
||||
* nothing to claim, so the flag does not apply. */
|
||||
if (b.capacity > 0 && cfg.gpu_memory_mib > 0) {
|
||||
const int64_t cap_mib = b.capacity / kMiB;
|
||||
if (cfg.gpu_memory_mib > cap_mib) {
|
||||
b.report = fmt("--gpu-memory-mib %lld is above this card's %lld MiB",
|
||||
(long long)cfg.gpu_memory_mib, (long long)cap_mib);
|
||||
if (log) RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
cfg.gpu_headroom_mib = cap_mib - cfg.gpu_memory_mib;
|
||||
cfg.given["--gpu-headroom-mib"] = "derived from --gpu-memory-mib";
|
||||
}
|
||||
b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB;
|
||||
int64_t host_reserve = 0;
|
||||
for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve);
|
||||
@@ -116,6 +131,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.queues + b.prefetch + b.host_pinned);
|
||||
|
||||
if (b.claimable < 0) {
|
||||
const char* how = cfg.gpu_memory_mib > 0
|
||||
? "Raise --gpu-memory-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n"
|
||||
: "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n";
|
||||
b.report = fmt(
|
||||
"VRAM does not cover the fixed costs before a single pool is sized:\n"
|
||||
" card total %10s\n"
|
||||
@@ -128,12 +148,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" expert prefetch %10s (its ring of expert units and buffers)\n"
|
||||
" ------------------------------\n"
|
||||
" short by %10s\n"
|
||||
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n",
|
||||
"%s",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str());
|
||||
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str(), how);
|
||||
if (log) RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_NOMEM;
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
* loaded code. The only observed term, printed on its own line so a
|
||||
* desktop on the card shows up there instead of shrinking a pool.
|
||||
* --gpu-headroom-mib what the operator leaves alone (default 96 MiB).
|
||||
* --gpu-memory-mib the inverse: claim this much of the card; headroom is the rest.
|
||||
* Not with --gpu-headroom-mib.
|
||||
* arena activation arena plus scratch, from arena_plan_bytes() on the buffer
|
||||
* plan, the same call that later allocates it.
|
||||
*
|
||||
@@ -32,9 +34,9 @@
|
||||
* KVManager::ceiling; the experts at the whole plane) and one side's excess goes to the other.
|
||||
*
|
||||
* No flag states a pool size: unbudgeted VRAM is unusable, and on a model whose experts do not
|
||||
* fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib,
|
||||
* --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which experts must stay on
|
||||
* the card).
|
||||
* fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib
|
||||
* or --gpu-memory-mib, --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which
|
||||
* experts must stay on the card).
|
||||
*
|
||||
* The host backend uses half the machine's memory as its capacity (host_vram_bytes) and splits it
|
||||
* like a card; its weights pool holds what a host kernel cannot read where the container stores it
|
||||
|
||||
+10
-1
@@ -31,7 +31,16 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s;
|
||||
for (int64_t k = 0; k < count; ++k) {
|
||||
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
|
||||
const int64_t within = first + k - patch_at(s);
|
||||
int64_t within = first + k - patch_at(s);
|
||||
if (within < seg_prefix) {
|
||||
/* A row the tower fills itself: row -1, the column naming which. */
|
||||
planes[k] = -1;
|
||||
planes[count + k] = (int32_t)within;
|
||||
planes[2 * count + k] = seg_h(s);
|
||||
planes[3 * count + k] = seg_w(s);
|
||||
continue;
|
||||
}
|
||||
within -= seg_prefix;
|
||||
const int64_t bw = seg_w(s) / merge;
|
||||
int64_t row, col;
|
||||
if (patch_raster) {
|
||||
|
||||
+61
-18
@@ -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
@@ -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 */
|
||||
|
||||
+432
-7
@@ -244,10 +244,74 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (mt && !std::strcmp(mt, "gemma4_vision")) {
|
||||
/* NVIDIA's Nemotron-H Omni states its tile budget in the processor configs (preprocessor and
|
||||
* processor_config's image_processor carry the same keys) and its token ids in config.json,
|
||||
* except <img> and </img>, which the vocabulary names (Processor::init). */
|
||||
if (mt && !std::strcmp(mt, "radio")) {
|
||||
family = Family::Radio;
|
||||
auto geti = [&](const char* k, int64_t dflt) {
|
||||
const std::string a = std::string("processor.image_processor.") + k;
|
||||
const std::string b = std::string("preprocessor.") + k;
|
||||
return rad_meta_geti(&m, a.c_str(), rad_meta_geti(&m, b.c_str(), dflt));
|
||||
};
|
||||
patch = (int32_t)geti("patch_size", rad_meta_geti(&m, "vision_config.patch_size", 0));
|
||||
const double ratio = rad_meta_getf(&m, "downsample_ratio", 0.0);
|
||||
merge = ratio > 0.0 ? (int32_t)std::lround(1.0 / ratio) : 0;
|
||||
temporal = 1;
|
||||
radio_tubelet = (int32_t)rad_meta_geti(
|
||||
&m, "processor.video_temporal_patch_dim",
|
||||
rad_meta_geti(&m, "video_temporal_patch_size",
|
||||
rad_meta_geti(&m, "vision_config.video_temporal_patch_size", 0)));
|
||||
radio_prefix = (int32_t)(rad_meta_geti(&m, "vision_config.num_cls_tokens", 0) +
|
||||
rad_meta_geti(&m, "vision_config.num_registers", 0));
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "img_context_token_id", -1);
|
||||
if (patch <= 0 || merge <= 0 || radio_tubelet <= 0 || radio_prefix <= 0 || tok_image < 0) {
|
||||
if (why) *why = "the container states no Nemotron-H Omni processor geometry "
|
||||
"(vision_config.patch_size, downsample_ratio, video_temporal_patch_size, "
|
||||
"num_cls_tokens + num_registers, img_context_token_id)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
radio_min_patches = (int32_t)geti("min_num_patches", 1024);
|
||||
radio_max_patches = (int32_t)geti("max_num_patches", 13312);
|
||||
radio_max_len = (int32_t)geti("max_model_len", 16384);
|
||||
radio_video_patches = (int32_t)geti("video_target_num_patches", 1024);
|
||||
if (!read_triple(m, "processor.image_processor.norm_mean", mean) &&
|
||||
!read_triple(m, "preprocessor.norm_mean", mean))
|
||||
read_triple(m, "norm_mean", mean);
|
||||
if (!read_triple(m, "processor.image_processor.norm_std", stdv) &&
|
||||
!read_triple(m, "preprocessor.norm_std", stdv))
|
||||
read_triple(m, "norm_std", stdv);
|
||||
/* The model card's serving default: 2 frames a second, at most 128 (64 tubelets). */
|
||||
fps = 2.0;
|
||||
min_frames = radio_tubelet;
|
||||
max_frames = 128;
|
||||
max_frame_rows = 0;
|
||||
/* The pixel bands only have to be consistent for check(); the tile rule sizes by patches. */
|
||||
const int64_t p2 = (int64_t)patch * patch;
|
||||
image_min_pixels = (int64_t)radio_min_patches * p2;
|
||||
image_max_pixels = std::max<int64_t>(image_min_pixels, (int64_t)radio_max_patches * p2);
|
||||
video_min_pixels = video_max_pixels = (int64_t)radio_video_patches * p2;
|
||||
std::string bad;
|
||||
if (radio_min_patches <= 0 || radio_video_patches <= 0 || radio_max_len <= 0)
|
||||
bad = "min_num_patches, video_target_num_patches and max_model_len must be positive";
|
||||
if (bad.empty() && check(&bad) < 0) bad = "the container's Nemotron-H Omni processor "
|
||||
"configuration is inconsistent: " + bad;
|
||||
if (!bad.empty()) {
|
||||
if (why) *why = bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Gemma 4 12B ("unified") has no tower: its embedder takes a whole 48 x 48 pooling window as
|
||||
* one patch, so a patch is a row (merge 1), and its values are u / 255. The sizes are the
|
||||
* same: a window is 48 pixels a side either way. */
|
||||
const bool unified = mt && !std::strcmp(mt, "gemma4_unified_vision");
|
||||
if (mt && (!std::strcmp(mt, "gemma4_vision") || unified)) {
|
||||
family = Family::Gemma4;
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
|
||||
unit_pixels = unified;
|
||||
patch = (int32_t)rad_meta_geti(&m, unified ? "vision_config.model_patch_size"
|
||||
: "vision_config.patch_size", 0);
|
||||
merge = unified ? 1 : (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
|
||||
temporal = 1;
|
||||
if (patch <= 0 || merge <= 0) {
|
||||
if (why) *why = "the container states no vision tower geometry (vision_config."
|
||||
@@ -267,7 +331,8 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
image_soft_tokens = (int32_t)rad_meta_geti(
|
||||
&m, "processor.image_processor.max_soft_tokens",
|
||||
rad_meta_geti(&m, "vision_soft_tokens_per_image",
|
||||
rad_meta_geti(&m, "vision_config.default_output_length", 280)));
|
||||
rad_meta_geti(&m, "vision_config.default_output_length",
|
||||
rad_meta_geti(&m, "vision_config.num_soft_tokens", 280))));
|
||||
video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens",
|
||||
70);
|
||||
fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0);
|
||||
@@ -970,6 +1035,134 @@ void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
resize_bicubic_impl(in, w, h, out, true);
|
||||
}
|
||||
|
||||
/* Python's round(): the nearest integer, a tie to the even one. The default floating-point
|
||||
* environment rounds that way, which nearbyint follows. */
|
||||
static inline int64_t py_round(double x) { return (int64_t)std::nearbyint(x); }
|
||||
|
||||
void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp) {
|
||||
const int64_t div = c.merge, lo = c.radio_min_patches;
|
||||
const int64_t hi = c.radio_max_patches > 0 ? c.radio_max_patches : INT64_MAX;
|
||||
const int64_t budget = std::max<int64_t>((int64_t)(c.radio_max_len - 4) * div * div, lo);
|
||||
const int64_t avail = std::max<int64_t>(std::min<int64_t>(budget, hi), lo);
|
||||
/* round(x + 0.5): x + 1 rounded down for a fraction, and for a whole x, x or x + 1 by parity
|
||||
* (Python's tie to even), which the reference's comment does not say but its code does. */
|
||||
const int64_t ch = py_round((double)h / (double)c.patch + 0.5);
|
||||
const int64_t cw = py_round((double)w / (double)c.patch + 0.5);
|
||||
const double factor = std::min(std::sqrt((double)avail / (double)(ch * cw)), 1.0);
|
||||
int64_t th = (int64_t)std::floor(factor * (double)ch);
|
||||
int64_t tw = (int64_t)std::floor(factor * (double)cw);
|
||||
if (avail > lo && th * tw < lo) {
|
||||
const double up = std::sqrt((double)lo / (double)(th * tw));
|
||||
th = (int64_t)std::ceil(up * (double)th);
|
||||
tw = (int64_t)std::ceil(up * (double)tw);
|
||||
}
|
||||
if (const int64_t r = th % div) th = (th + div - r) * tw <= avail ? th + div - r
|
||||
: std::max(div, th - r);
|
||||
if (const int64_t r = tw % div) tw = th * (tw + div - r) <= avail ? tw + div - r
|
||||
: std::max(div, tw - r);
|
||||
*wp = (int32_t)tw;
|
||||
*hp = (int32_t)th;
|
||||
}
|
||||
|
||||
void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp) {
|
||||
const int64_t div = c.merge, target = c.radio_video_patches;
|
||||
const double aspect = (double)w / (double)std::max<int64_t>(h, 1);
|
||||
int64_t ph = std::max<int64_t>(py_round(std::sqrt((double)target / aspect)), 1);
|
||||
int64_t pw = std::max<int64_t>(py_round(std::sqrt((double)target * aspect)), 1);
|
||||
if (div > 1) {
|
||||
const int64_t rh = ph % div, rw = pw % div;
|
||||
const int64_t phu = ph + (rh ? div - rh : 0), pwu = pw + (rw ? div - rw : 0);
|
||||
if (phu * pwu <= target) {
|
||||
ph = phu;
|
||||
pw = pwu;
|
||||
} else {
|
||||
ph = std::max(div, ph - rh);
|
||||
pw = std::max(div, pw - rw);
|
||||
}
|
||||
}
|
||||
*wp = (int32_t)pw;
|
||||
*hp = (int32_t)ph;
|
||||
}
|
||||
|
||||
/* ATen's antialiased bicubic (Keys, a = -0.5) on float, one axis: output i reads inputs
|
||||
* [lo, lo + n) at the filter's normalised weights, the support widened by the scale when
|
||||
* shrinking. */
|
||||
namespace {
|
||||
struct AaTaps { std::vector<int32_t> lo, n; std::vector<float> w; int32_t width = 0; };
|
||||
inline float aa_cubic(float x) {
|
||||
const float a = -0.5f;
|
||||
x = std::fabs(x);
|
||||
if (x < 1.0f) return ((a + 2.0f) * x - (a + 3.0f)) * x * x + 1.0f;
|
||||
if (x < 2.0f) return ((a * x - 5.0f * a) * x + 8.0f * a) * x - 4.0f * a;
|
||||
return 0.0f;
|
||||
}
|
||||
AaTaps aa_taps_f32(int32_t in, int32_t out) {
|
||||
AaTaps t;
|
||||
const float scale = (float)in / (float)out;
|
||||
const float support = scale >= 1.0f ? 2.0f * scale : 2.0f;
|
||||
const float inv = scale >= 1.0f ? 1.0f / scale : 1.0f;
|
||||
t.width = (int32_t)std::ceil(support) * 2 + 1;
|
||||
t.lo.resize((size_t)out);
|
||||
t.n.resize((size_t)out);
|
||||
t.w.assign((size_t)out * t.width, 0.0f);
|
||||
for (int32_t i = 0; i < out; ++i) {
|
||||
const float center = scale * ((float)i + 0.5f);
|
||||
const int32_t lo = std::max((int32_t)(center - support + 0.5f), 0);
|
||||
const int32_t n = std::min((int32_t)(center + support + 0.5f), in) - lo;
|
||||
float* w = &t.w[(size_t)i * t.width];
|
||||
float total = 0.0f;
|
||||
for (int32_t j = 0; j < n && j < t.width; ++j) {
|
||||
w[j] = aa_cubic(((float)(j + lo) - center + 0.5f) * inv);
|
||||
total += w[j];
|
||||
}
|
||||
for (int32_t j = 0; j < n && j < t.width; ++j) w[j] = total != 0.0f ? w[j] / total : 0.0f;
|
||||
t.lo[(size_t)i] = lo;
|
||||
t.n[(size_t)i] = std::min(n, t.width);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector<float>* out) {
|
||||
std::vector<float> src((size_t)in.w * in.h * 3);
|
||||
for (size_t i = 0; i < src.size(); ++i) src[i] = (float)in.rgb[i];
|
||||
/* Width first, then height; a side that keeps its size is skipped (its taps are the identity). */
|
||||
std::vector<float> mid;
|
||||
const std::vector<float>* cur = &src;
|
||||
int32_t cw = in.w;
|
||||
if (w != in.w) {
|
||||
const AaTaps t = aa_taps_f32(in.w, w);
|
||||
mid.assign((size_t)w * in.h * 3, 0.0f);
|
||||
for (int32_t y = 0; y < in.h; ++y)
|
||||
for (int32_t x = 0; x < w; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float acc = 0.0f;
|
||||
const float* wt = &t.w[(size_t)x * t.width];
|
||||
for (int32_t j = 0; j < t.n[(size_t)x]; ++j)
|
||||
acc += src[((size_t)y * in.w + t.lo[(size_t)x] + j) * 3 + c] * wt[j];
|
||||
mid[((size_t)y * w + x) * 3 + c] = acc;
|
||||
}
|
||||
cur = ∣
|
||||
cw = w;
|
||||
}
|
||||
if (h != in.h) {
|
||||
const AaTaps t = aa_taps_f32(in.h, h);
|
||||
out->assign((size_t)cw * h * 3, 0.0f);
|
||||
for (int32_t y = 0; y < h; ++y) {
|
||||
const float* wt = &t.w[(size_t)y * t.width];
|
||||
for (int32_t x = 0; x < cw; ++x)
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float acc = 0.0f;
|
||||
for (int32_t j = 0; j < t.n[(size_t)y]; ++j)
|
||||
acc += (*cur)[((size_t)(t.lo[(size_t)y] + j) * cw + x) * 3 + c] * wt[j];
|
||||
(*out)[((size_t)y * cw + x) * 3 + c] = acc;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
*out = *cur;
|
||||
}
|
||||
|
||||
void cap_area(const Frame& in, int64_t max_pixels, Frame* out) {
|
||||
if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; }
|
||||
const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h));
|
||||
@@ -1071,7 +1264,8 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
|
||||
* processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for
|
||||
* pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and
|
||||
* EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One
|
||||
* frame per segment. */
|
||||
* frame per segment. With `unit_pixels` (the 12B, merge 1: a row is one 48 x 48 window) the value
|
||||
* is p itself, rounded to bf16. */
|
||||
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, bool video,
|
||||
Item* it) {
|
||||
const int P = c.patch, M = c.merge;
|
||||
@@ -1080,7 +1274,7 @@ void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& fra
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = video ? (float)((double)v * (1.0 / 255.0))
|
||||
: (float)v * (float)(1.0 / 255.0);
|
||||
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
|
||||
lut[v] = rad_f32_to_bf16(c.unit_pixels ? p : 2.0f * (p - 0.5f));
|
||||
}
|
||||
const int64_t dim = it->patch_dim;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
@@ -1100,6 +1294,55 @@ void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& fra
|
||||
}
|
||||
}
|
||||
|
||||
/* Radio's patch rows (Family::Radio), segment by segment: `n_prefix` zero rows, then the patches
|
||||
* in merge-block order. A row is [the tubelet's frames (frame, channel, y, x) | the picture's
|
||||
* (channel, y, x)]: a picture fills the second part, a video tubelet the first, the rest zero.
|
||||
* Each value is (u / 255 - mean) / std in f32 on the resized float pixels, rounded to bf16, as the
|
||||
* reference processor's tensor ops and the model's cast to bf16 give it. `frames` holds
|
||||
* grid_t * tubelet frames of [grid_h * patch, grid_w * patch, 3] floats for a video, one for a
|
||||
* picture. */
|
||||
void patchify_radio(const VisionConfig& c, const std::vector<const std::vector<float>*>& frames,
|
||||
bool video, Item* it) {
|
||||
const int P = c.patch, M = c.merge, T = c.radio_tubelet;
|
||||
const int gh = it->grid_h, gw = it->grid_w, W = gw * P;
|
||||
const int64_t dim = it->patch_dim, pp = 3LL * P * P;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
uint16_t* dst = it->pixels.data();
|
||||
auto norm = [&](float u, int ch) {
|
||||
return rad_f32_to_bf16((u / 255.0f - c.mean[ch]) / c.stdv[ch]);
|
||||
};
|
||||
for (int g = 0; g < it->grid_t; ++g) {
|
||||
dst += (size_t)it->seg_prefix * dim;
|
||||
for (int bh = 0; bh < gh / M; ++bh)
|
||||
for (int bw = 0; bw < gw / M; ++bw)
|
||||
for (int mh = 0; mh < M; ++mh)
|
||||
for (int mw = 0; mw < M; ++mw) {
|
||||
const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P;
|
||||
const int nf = video ? T : 1;
|
||||
uint16_t* o = dst + (video ? 0 : (int64_t)T * pp);
|
||||
for (int t = 0; t < nf; ++t) {
|
||||
const std::vector<float>& f = *frames[(size_t)(g * nf + t)];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int y = 0; y < P; ++y)
|
||||
for (int x = 0; x < P; ++x)
|
||||
*o++ = norm(f[((size_t)(py0 + y) * W + px0 + x) * 3 + ch], ch);
|
||||
}
|
||||
dst += dim;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Radio's item geometry: finish_item's, with the prefix rows counted in the patches. */
|
||||
void finish_item_radio(const VisionConfig& c, Item* it) {
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->seg_prefix = c.radio_prefix;
|
||||
it->rows_h = it->grid_h / c.merge;
|
||||
it->rows_w = it->grid_w / c.merge;
|
||||
it->seg_rows = it->rows_h * it->rows_w;
|
||||
it->n_seg = it->grid_t;
|
||||
it->n_patch = (int64_t)it->grid_t * (c.radio_prefix + (int64_t)it->grid_h * it->grid_w);
|
||||
}
|
||||
|
||||
void finish_item(const VisionConfig& c, Item* it) {
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w;
|
||||
@@ -1153,6 +1396,26 @@ int Processor::init(const VisionConfig& cfg,
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (cfg.family == Family::Radio) {
|
||||
/* The markers around a run are vocabulary words, not config ids. A tile is one segment of
|
||||
* one pass with its prefix rows, so the picture budget is lowered to what a pass holds;
|
||||
* a video frame's target must fit as it is. */
|
||||
if (!token_id) return RAD_E_INVAL;
|
||||
cfg_.tok_start = token_id("<img>");
|
||||
cfg_.tok_end = token_id("</img>");
|
||||
if (cfg_.tok_start < 0 || cfg_.tok_end < 0) return RAD_E_NOTFOUND;
|
||||
const int64_t cap = cfg.max_patches - cfg.radio_prefix;
|
||||
if (cap < cfg.radio_min_patches || cap < cfg.radio_video_patches) return RAD_E_INVAL;
|
||||
if (cfg_.radio_max_patches > cap) cfg_.radio_max_patches = (int32_t)cap;
|
||||
/* A video's budget: max_frames frames in tubelets, each its prefix plus the frame target
|
||||
* (the video tile never exceeds it). */
|
||||
if (cfg_.max_video_patches <= 0)
|
||||
cfg_.max_video_patches = (int64_t)((cfg.max_frames + cfg.radio_tubelet - 1) /
|
||||
cfg.radio_tubelet) *
|
||||
(cfg.radio_prefix + cfg.radio_video_patches);
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (cfg.family == Family::Glm5Next) {
|
||||
/* A token is merge^2 patches and an image is one segment of one pass, so the budget is
|
||||
* lowered to what a pass holds. */
|
||||
@@ -1712,6 +1975,99 @@ int Processor::image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::st
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* NVIDIA's Nemotron-H Omni image processor: one tile, sized by radio_size, resized with torch's
|
||||
* antialiased bicubic on float pixels (none when the size already fits). */
|
||||
int Processor::image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
int32_t wp = 0, hp = 0;
|
||||
radio_size(f.w, f.h, c, &wp, &hp);
|
||||
std::vector<float> px;
|
||||
resize_bicubic_aa_f32(f, wp * c.patch, hp * c.patch, &px);
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = hp;
|
||||
it->grid_w = wp;
|
||||
it->rope_1d = true;
|
||||
finish_item_radio(c, it.get());
|
||||
if (it->n_patch > c.max_patches) {
|
||||
if (why) *why = "the image resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
patchify_radio(c, { &px }, false, it.get());
|
||||
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Its video path: every frame at the video tile (radio_video_size of the first), `tubelet`
|
||||
* frames a segment (the last repeated to fill one), each run labelled as the reference processor
|
||||
* labels a tubelet -- "Frame i sampled at T seconds and frame i+1 sampled at T' seconds: ", T the
|
||||
* frame's source index times int(1000 / fps) ms -- the runs joined by a newline. No pruning (EVS):
|
||||
* every tubelet keeps all its rows. */
|
||||
int Processor::video_radio(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
int32_t wp = 0, hp = 0;
|
||||
radio_video_size(v.frames[0].w, v.frames[0].h, c, &wp, &hp);
|
||||
const int32_t T = c.radio_tubelet;
|
||||
const int64_t nf = (int64_t)v.frames.size();
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Video;
|
||||
it->grid_t = (int32_t)((nf + T - 1) / T);
|
||||
it->grid_h = hp;
|
||||
it->grid_w = wp;
|
||||
it->rope_1d = true;
|
||||
finish_item_radio(c, it.get());
|
||||
if (c.radio_prefix + (int64_t)hp * wp > c.max_patches) {
|
||||
if (why) *why = "a video frame resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (it->n_patch > c.max_video_patches) {
|
||||
if (why) *why = "the video is over the server's patch budget for one video";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<std::vector<float>> resized((size_t)nf);
|
||||
for (int64_t i = 0; i < nf; ++i)
|
||||
resize_bicubic_aa_f32(v.frames[(size_t)i], wp * c.patch, hp * c.patch, &resized[(size_t)i]);
|
||||
std::vector<const std::vector<float>*> frames;
|
||||
for (int64_t i = 0; i < (int64_t)it->grid_t * T; ++i)
|
||||
frames.push_back(&resized[(size_t)std::min(i, nf - 1)]);
|
||||
patchify_radio(c, frames, true, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
const int64_t frame_ms = v.info.fps > 0.0 ? (int64_t)(1000.0 / v.info.fps) : 0;
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
std::string label = g > 0 ? "\n" : "";
|
||||
for (int32_t j = 0; j < T; ++j) {
|
||||
const int64_t fi = (int64_t)g * T + j;
|
||||
if (fi >= nf) break;
|
||||
char part[96];
|
||||
if (frame_ms > 0)
|
||||
std::snprintf(part, sizeof part, "%s%s %lld sampled at %.2f seconds",
|
||||
j ? " and " : "", j ? "frame" : "Frame", (long long)(fi + 1),
|
||||
(double)(v.index[(size_t)fi] * frame_ms) / 1000.0);
|
||||
else
|
||||
std::snprintf(part, sizeof part, "%s%s %lld", j ? " and " : "",
|
||||
j ? "frame" : "Frame", (long long)(fi + 1));
|
||||
label += part;
|
||||
}
|
||||
label += ": ";
|
||||
const std::vector<int32_t> tt = encode_text_ ? encode_text_(label) : std::vector<int32_t>{};
|
||||
if (tt.empty()) {
|
||||
if (why) *why = "the tokenizer produced nothing for a video frame label";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
it->expand.insert(it->expand.end(), tt.begin(), tt.end());
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back((int32_t)it->expand.size());
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
|
||||
it->expand.push_back(c.tok_end);
|
||||
}
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
@@ -1723,6 +2079,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
if (c.family == Family::Pixtral) return image_pixtral(f, out, why);
|
||||
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
|
||||
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
|
||||
if (c.family == Family::Radio) return image_radio(f, out, why);
|
||||
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
|
||||
@@ -1816,6 +2173,7 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::str
|
||||
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
|
||||
if (c.family == Family::Radio) return video_radio(v, out, why);
|
||||
if (c.family == Family::Glm5Next || c.family == Family::Pixtral) {
|
||||
if (why) *why = "this model's processor takes pictures, not video";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -2131,12 +2489,40 @@ static int qwen3asr_from_meta(const RadModelMeta& m, AudioConfig* c, std::string
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Gemma4UnifiedAudioFeatureExtractor's framing (Gemma 4 12B): processor_config.json's
|
||||
* `feature_extractor` and the clip cap `audio_seq_length` (in frames). The frame's width is what the
|
||||
* embedder takes, so it stands in `n_mels` as a mel spectrum's bins do. */
|
||||
static int unified_from_meta(const RadModelMeta& m, AudioConfig* c, std::string* why) {
|
||||
c->family = AudioFamily::Gemma4Unified;
|
||||
c->rate = (int32_t)rad_meta_geti(&m, "processor.feature_extractor.sampling_rate", 16000);
|
||||
c->frame_length = (int32_t)rad_meta_geti(
|
||||
&m, "processor.feature_extractor.audio_samples_per_token",
|
||||
rad_meta_geti(&m, "audio_config.audio_samples_per_token",
|
||||
rad_meta_geti(&m, "audio_config.audio_embed_dim", 0)));
|
||||
c->hop = c->frame_length;
|
||||
c->n_mels = c->frame_length;
|
||||
c->max_samples = rad_meta_geti(&m, "processor.audio_seq_length", 750) * c->frame_length;
|
||||
c->tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
|
||||
c->tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
|
||||
c->tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id",
|
||||
rad_meta_geti(&m, "eoa_token_index", -1));
|
||||
if (c->rate <= 0 || c->frame_length <= 0 || c->max_samples <= 0 || c->tok_audio < 0 ||
|
||||
c->tok_start < 0 || c->tok_end < 0) {
|
||||
if (why) *why = "the container's audio framing is incomplete (sampling_rate, "
|
||||
"audio_samples_per_token, audio_seq_length, audio_token_id, boa_token_id, "
|
||||
"eoa_token_id)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
|
||||
if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why);
|
||||
if (mt && !std::strcmp(mt, "gemma4_unified_audio")) return unified_from_meta(m, this, why);
|
||||
if (!mt || std::strcmp(mt, "gemma4_audio")) {
|
||||
if (why) *why = "the container states no audio tower this processor knows (audio_config."
|
||||
"model_type gemma4_audio or qwen3_asr_encoder)";
|
||||
"model_type gemma4_audio, gemma4_unified_audio or qwen3_asr_encoder)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* preprocessor_config.json's keys (`preprocessor.`), else processor_config.json's
|
||||
@@ -2273,6 +2659,12 @@ int Processor::init_audio(const AudioConfig& cfg, std::string* why) {
|
||||
return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) +
|
||||
" frames) is not whole rows of " +
|
||||
std::to_string(cfg.merge) + " frames");
|
||||
/* The 12B's frames are samples: no window, no FFT, no mel bank. */
|
||||
if (cfg.family == AudioFamily::Gemma4Unified) {
|
||||
acfg_ = cfg;
|
||||
audio_on_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
const bool qwen = cfg.family == AudioFamily::Qwen3ASR;
|
||||
/* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */
|
||||
if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0))
|
||||
@@ -2481,11 +2873,44 @@ int Processor::audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The 12B's clip (AudioFamily::Gemma4Unified): ceil(n / frame_length) frames of samples, the last
|
||||
* zero-padded, each sample rounded to bf16 as the reference casts the frames for its embedder; one
|
||||
* frame a placeholder. The reference cuts nothing; a clip past `max_samples` is cut there. */
|
||||
int Processor::audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
const AudioConfig& c = acfg_;
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t fl = c.frame_length, rows = (n + fl - 1) / fl;
|
||||
if (rows * c.merge > c.max_frames) {
|
||||
if (why) *why = "the clip is more frames than one audio encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Audio;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)rows;
|
||||
it->grid_w = 1;
|
||||
it->patch_dim = fl;
|
||||
it->n_patch = rows;
|
||||
it->valid = (int32_t)rows;
|
||||
it->rows_h = (int32_t)rows;
|
||||
it->rows_w = 1;
|
||||
it->seg_rows = (int32_t)rows;
|
||||
it->n_seg = rows > 0 ? 1 : 0;
|
||||
it->pixels.assign((size_t)(rows * fl), 0);
|
||||
for (int64_t i = 0; i < n; ++i) it->pixels[(size_t)i] = rad_f32_to_bf16(samples[(size_t)i]);
|
||||
one_run(it.get(), c.tok_start, rows, c.tok_audio, c.tok_end);
|
||||
if (rows == 0) it->encoded = true;
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
const AudioConfig& c = acfg_;
|
||||
if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why);
|
||||
if (c.family == AudioFamily::Gemma4Unified) return audio_unified(samples, out, why);
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t real = c.real_frames(n);
|
||||
const int64_t rows = (real + c.merge - 1) / c.merge;
|
||||
|
||||
+49
-5
@@ -50,6 +50,8 @@ enum class Kind { Image, Video, Audio };
|
||||
* channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is
|
||||
* frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment
|
||||
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
|
||||
* Gemma 4 12B ("unified", no tower) is the same with a whole pooling window as one
|
||||
* patch (patch = 48, merge 1) and its values u / 255 (`unit_pixels`).
|
||||
* Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole --
|
||||
* sides multiples of patch * merge, pixels within the budget's band -- and one past it
|
||||
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
|
||||
@@ -79,8 +81,19 @@ enum class Kind { Image, Video, Audio };
|
||||
* Pixtral Nemotron 3.5's noncausal Mistral3 wrapper: longest-edge resize, then ceil each side
|
||||
* to patch * merge; PIL bicubic and CLIP normalization. Raster (channel, y, x) patches;
|
||||
* image placeholders per merged grid row, each followed by IMG_BREAK (last: IMG_END).
|
||||
* Every token has ordinary 1-D positions, and separators retain their token embedding. */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral };
|
||||
* Every token has ordinary 1-D positions, and separators retain their token embedding.
|
||||
* Radio NVIDIA's Nemotron-H Omni with C-RADIO: a picture becomes one tile whose patch grid
|
||||
* falls between min_num_patches and max_num_patches, aspect ratio kept and both sides
|
||||
* even (the pixel shuffle's factor), resized with torch's antialiased bicubic on float
|
||||
* pixels; a video frame the same at about video_target_num_patches. Values are
|
||||
* (u / 255 - mean) / std in f32, rounded to bf16. A patch row is the tubelet's frames
|
||||
* (frame, channel, y, x) and then the picture's (channel, y, x), the part not in use
|
||||
* zero, so one embedding GEMM serves both projections. Each segment carries `n_prefix`
|
||||
* zero rows ahead of its patches, which the tower fills with its class and register
|
||||
* tokens. Pictures are spelled <img> placeholders </img>; a video one such run a
|
||||
* tubelet, each after its "Frame i sampled at T seconds and frame i+1 ...: " label,
|
||||
* runs joined by a newline. Tokens at their positions (NoPE). */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio };
|
||||
|
||||
struct VisionConfig {
|
||||
Family family = Family::QwenVL;
|
||||
@@ -88,6 +101,8 @@ struct VisionConfig {
|
||||
/* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140,
|
||||
* 280, 560, 1120, the budgets the model was trained at. */
|
||||
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
|
||||
/* Gemma4: patch values u / 255 rather than 2 * (u / 255) - 1 (the 12B's embedder). */
|
||||
bool unit_pixels = false;
|
||||
int64_t image_min_pixels = 0, image_max_pixels = 0;
|
||||
int64_t video_min_pixels = 0, video_max_pixels = 0;
|
||||
/* Glm5Next: the band an image's canvas falls in, in output rows (tokens). */
|
||||
@@ -104,6 +119,11 @@ struct VisionConfig {
|
||||
/* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */
|
||||
int32_t min_tiles = 0, max_tiles = 0, tile = 0;
|
||||
bool use_thumbnail = false;
|
||||
/* Radio: a picture's patch budget [radio_min_patches, radio_max_patches] (with the global cap
|
||||
* radio_max_len tokens), the per-frame target of a video, the frames a tubelet packs and the
|
||||
* learned rows (class and register tokens) a segment carries ahead of its patches. */
|
||||
int32_t radio_min_patches = 0, radio_max_patches = 0, radio_max_len = 0;
|
||||
int32_t radio_video_patches = 0, radio_tubelet = 0, radio_prefix = 0;
|
||||
double max_pixels_tolerance = 0.0;
|
||||
int64_t max_segment_patches = 0;
|
||||
|
||||
@@ -135,7 +155,11 @@ struct VisionConfig {
|
||||
* engine again after command-line overrides. */
|
||||
int check(std::string* why) const;
|
||||
|
||||
int64_t patch_dim() const { return 3LL * temporal * patch * patch; }
|
||||
int64_t patch_dim() const {
|
||||
/* Radio's row is a tubelet's frames and then the picture's patch (Family::Radio). */
|
||||
if (family == Family::Radio) return 3LL * (1 + radio_tubelet) * patch * patch;
|
||||
return 3LL * temporal * patch * patch;
|
||||
}
|
||||
int32_t factor() const { return patch * merge; }
|
||||
|
||||
/* Read from the container; refuses one with no vision tower. Processor-only keys the
|
||||
@@ -165,6 +189,9 @@ struct ImageMode {
|
||||
* through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor).
|
||||
* The clip's real frames, then zero frames to whole output rows.
|
||||
*
|
||||
* Gemma4Unified Gemma4UnifiedAudioFeatureExtractor (the 12B's): no spectrum; a frame is
|
||||
* `frame_length` samples as they are, the last zero-padded, one frame a row.
|
||||
*
|
||||
* Qwen3ASR Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is
|
||||
* zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at
|
||||
* each end, a periodic Hann window and power spectra, the last frame dropped, so n
|
||||
@@ -176,7 +203,7 @@ struct ImageMode {
|
||||
* padding, and, where that exceeds a whole chunk, frames past it that the encoder
|
||||
* reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which
|
||||
* keeps one chunk's convolution from seeing the next. */
|
||||
enum class AudioFamily { Gemma4, Qwen3ASR };
|
||||
enum class AudioFamily { Gemma4, Qwen3ASR, Gemma4Unified };
|
||||
|
||||
/* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the
|
||||
* checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*`
|
||||
@@ -257,6 +284,10 @@ struct Item {
|
||||
/* Patches are in raster order (row by row), not merge-block order: the coordinate planes
|
||||
* invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */
|
||||
bool patch_raster = false;
|
||||
/* Rows ahead of each segment's patches that the encoder fills itself (Family::Radio: C-RADIO's
|
||||
* class and register tokens): zero pixels, coordinate (-1, k), counted in patch_at and
|
||||
* n_patch but never in a segment's output rows. */
|
||||
int32_t seg_prefix = 0;
|
||||
|
||||
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
|
||||
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
|
||||
@@ -265,7 +296,7 @@ struct Item {
|
||||
bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; }
|
||||
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
|
||||
int64_t patch_at(int32_t s) const {
|
||||
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
|
||||
if (segments.empty()) return (int64_t)s * (seg_prefix + (int64_t)grid_h * grid_w);
|
||||
return s >= n_seg ? n_patch : segments[(size_t)s].patch0;
|
||||
}
|
||||
int64_t row_at(int32_t s) const {
|
||||
@@ -424,6 +455,8 @@ private:
|
||||
std::string* why) const;
|
||||
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_radio(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
|
||||
int32_t tok_thumbnail_ = -1;
|
||||
std::vector<int32_t> tok_tiles_;
|
||||
@@ -434,6 +467,8 @@ private:
|
||||
bool audio_on_ = false;
|
||||
int audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
std::vector<float> hann_; /* the window, float32 as the reference stores it */
|
||||
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
|
||||
@@ -459,6 +494,15 @@ std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int
|
||||
* within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */
|
||||
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
|
||||
int64_t* oh, int64_t* ow, std::string* why);
|
||||
/* Radio's tile for a picture of w x h pixels (NVIDIA's _compute_target_patches, Python's
|
||||
* round-half-even included) and for a video frame (_compute_target_patches_video), in patches. */
|
||||
void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp);
|
||||
void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp);
|
||||
/* torch's F.interpolate(mode="bicubic", align_corners=False, antialias=True) of packed RGB bytes
|
||||
* taken as float, without rounding or clamping: [h, w, 3] f32 in 0..255 give or take the
|
||||
* filter's overshoot. Separable, width first, as ATen's CPU kernel; a side that keeps its size is
|
||||
* the identity. */
|
||||
void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector<float>* out);
|
||||
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
|
||||
* horizontal pass into an 8-bit intermediate and then a vertical one. */
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
|
||||
|
||||
+221
-137
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
+57
-5
@@ -52,9 +52,10 @@ bool target_covers(const std::string& declared, const char* arch) {
|
||||
}
|
||||
|
||||
/* Two schemas for one op are the same when every positional slot means the same thing: parameter
|
||||
* keys, types and requiredness (what the selector matches on) and operand count, roles and
|
||||
* optionality (arguments are positional). Operand names are for diagnostics only (ABI), so "b"
|
||||
* and "w_gate" in slot 1 agree. */
|
||||
* keys, types, requiredness (what the selector matches on) and roles (the core reads the first
|
||||
* registrant's: a chunk or a capacity named by one plugin applies to every plugin's rows), and
|
||||
* operand count, roles and optionality (arguments are positional). Operand names are for
|
||||
* diagnostics only (ABI), so "b" and "w_gate" in slot 1 agree. */
|
||||
bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff) {
|
||||
if (a.n_params != b.n_params) {
|
||||
*diff = fmt("%d parameters vs %d", a.n_params, b.n_params);
|
||||
@@ -77,6 +78,10 @@ bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* diff)
|
||||
x.required ? "required" : "optional", y.required ? "required" : "optional");
|
||||
return false;
|
||||
}
|
||||
if (x.role != y.role) {
|
||||
*diff = fmt("parameter '%s' has role %d vs %d", or_empty(x.key), x.role, y.role);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (a.n_operands != b.n_operands) {
|
||||
*diff = fmt("%d operands vs %d", a.n_operands, b.n_operands);
|
||||
@@ -212,6 +217,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
p.arch_declare = dl_fn<int (*)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*)>(
|
||||
s.handle, "rad_arch_declare");
|
||||
p.arch_step = dl_fn<void (*)(RadCtx*, const RadBatch*)>(s.handle, "rad_arch_step");
|
||||
p.arch_pass_key = dl_fn<uint64_t (*)(RadCtx*, const RadBatch*, const int32_t*)>(
|
||||
s.handle, "rad_arch_pass_key");
|
||||
if (!id_fn || !p.arch_declare || !p.arch_step) {
|
||||
err_("architecture plugin '%s' is missing rad_arch_id, rad_arch_declare or "
|
||||
"rad_arch_step", p.name.c_str());
|
||||
@@ -291,6 +298,27 @@ int Registry::commit_(Staged& s, int order) {
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The counts are the plugin's word; the tables they index are walked at every
|
||||
* selection and every issue, so a null table or an operand count past what an issue
|
||||
* can carry (MAX_OPERANDS) is refused here, by name, rather than read there. */
|
||||
if (sch->n_params < 0 || (sch->n_params && !sch->params) || sch->n_operands < 0 ||
|
||||
sch->n_operands > MAX_OPERANDS || (sch->n_operands && !sch->operands)) {
|
||||
err_("kernel plugin '%s': op '%s' declares %d parameters and %d operands, a table "
|
||||
"missing, or more operands than an issue carries (%d)", p.name.c_str(),
|
||||
sch->op, sch->n_params, sch->n_operands, MAX_OPERANDS);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int q = 0; q < sch->n_params; ++q) {
|
||||
const RadParamSpec& ps = sch->params[q];
|
||||
if (!ps.key || !ps.key[0] || ps.role < RAD_PROLE_NONE ||
|
||||
ps.role > RAD_PROLE_CAPACITY) {
|
||||
err_("kernel plugin '%s': op '%s' parameter %d has no key or an unknown role "
|
||||
"(%d)", p.name.c_str(), sch->op, q, ps.role);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
std::string diff;
|
||||
auto it = schemas_.find(sch->op);
|
||||
if (it != schemas_.end()) {
|
||||
@@ -338,6 +366,23 @@ int Registry::commit_(Staged& s, int order) {
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The selector reads every constraint of every row at every query, and the tuner every
|
||||
* tunable, so their tables must exist wherever a count says they do. */
|
||||
if (k->n_tunables < 0 || (k->n_tunables && !k->tunables) || k->n_constraints < 0 ||
|
||||
(k->n_constraints && !k->constraints)) {
|
||||
err_("kernel '%s' in plugin '%s' declares %d tunables and %d constraints with a "
|
||||
"missing table", k->name, p.name.c_str(), k->n_tunables, k->n_constraints);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int c = 0; c < k->n_constraints; ++c)
|
||||
if (!k->constraints[c].key || !k->constraints[c].key[0] ||
|
||||
(k->constraints[c].op == RAD_C_IN && !k->constraints[c].sval)) {
|
||||
err_("kernel '%s' in plugin '%s' declares constraint %d with no key, or an IN "
|
||||
"with no set", k->name, p.name.c_str(), c);
|
||||
unstage_(s);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Every tunable axis must carry a default that is one of its own values. Untuned
|
||||
* shapes (no cache, an unmeasured shape, another card's cache) run the defaults, with
|
||||
* no other fallback (spec §15). Checked at load rather than first use so a bad axis
|
||||
@@ -382,8 +427,15 @@ int Registry::commit_(Staged& s, int order) {
|
||||
if (no_device_code_)
|
||||
why = "no card is visible, so this process runs on the host backend and no GPU code "
|
||||
"object runs here";
|
||||
if (n_device > 0 && s.code_to > s.code_from &&
|
||||
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) {
|
||||
/* The code range decides only the per-card test: on the host backend the rows go even when
|
||||
* this dlopen registered no fat binary (no HIP in the build, or the library already
|
||||
* mapped by another registry). */
|
||||
const bool no_code_here =
|
||||
n_device > 0 &&
|
||||
(no_device_code_ ||
|
||||
(s.code_to > s.code_from &&
|
||||
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0));
|
||||
if (no_code_here) {
|
||||
std::vector<std::pair<const RadKernelInfo*, int>> keep;
|
||||
for (const auto& r : staged_rows)
|
||||
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
|
||||
|
||||
@@ -82,6 +82,7 @@ struct Plugin {
|
||||
std::string arch_quant;
|
||||
int (*arch_declare)(RadBuilder*, const RadModelMeta*, const RadBuildCtx*) = nullptr;
|
||||
void (*arch_step)(RadCtx*, const RadBatch*) = nullptr;
|
||||
uint64_t (*arch_pass_key)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
|
||||
/* Optional (rad_builder.h); null means every question answers zero. Asked before declare, so
|
||||
* model facts that are inputs to declaration are still read by the plugin, not the core. */
|
||||
int (*arch_probe)(const RadModelMeta*, RadArchProbe*) = nullptr;
|
||||
|
||||
+30
-2
@@ -17,6 +17,11 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
|
||||
* room for an architecture plugin's private ops without a variable-length array on the hot path.
|
||||
* The plugin loader refuses a schema with more, so no issue carries more. */
|
||||
constexpr int MAX_OPERANDS = 32;
|
||||
|
||||
namespace mm { struct Item; struct PromptMedia; }
|
||||
|
||||
class Registry;
|
||||
@@ -451,9 +456,15 @@ public:
|
||||
std::vector<int64_t> decoder_max_area;
|
||||
} vgen_str;
|
||||
bool is_video_generator() const { return video_gen.max_lanes != 0; }
|
||||
/* The declared shape generator (rad_declare_shape_generator); `max_lanes` 0 when none. Its
|
||||
* name points at `sgen_name`. */
|
||||
RadShapeGenDecl shape_gen{};
|
||||
std::string sgen_name;
|
||||
bool is_shape_generator() const { return shape_gen.max_lanes != 0; }
|
||||
/* Driven by passes, not token steps: any generator. */
|
||||
bool is_pass_driven() const {
|
||||
return is_generator() || is_audio_generator() || is_video_generator();
|
||||
return is_generator() || is_audio_generator() || is_video_generator() ||
|
||||
is_shape_generator();
|
||||
}
|
||||
|
||||
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
|
||||
@@ -671,6 +682,10 @@ struct SamplingParams {
|
||||
* duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the
|
||||
* no-whitelist form. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
/* Token ids this request never samples (generation_config.json's suppress_tokens: Gemma 4's
|
||||
* end-of-image and end-of-audio markers). Global ids, duplicates ignored; empty is off. The
|
||||
* sampler takes them out of the row as it does a grammar's mask. */
|
||||
std::vector<int32_t> suppress_tokens;
|
||||
};
|
||||
|
||||
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
|
||||
@@ -824,7 +839,13 @@ struct Config {
|
||||
* prefill stager arms for. 0 = off: the chunk takes every token the step has left. N > 0: cap
|
||||
* the chunk at N tokens on such a step. See Scheduler::step, docs/GUIDE.md. */
|
||||
int64_t busy_prefill_chunk = -1;
|
||||
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks */
|
||||
double prefill_interleave_share = 0.25; /* --prefill-interleave auto[:SHARE] */
|
||||
/* Whether --prefill-interleave was given. Not given, engine bring-up serves auto:1 (decode-only
|
||||
* steps for as long as a chunk step took) except under --deterministic, in KL mode and for a
|
||||
* generator; the Config default 0 is what a Scheduler built directly (tests) gets. */
|
||||
bool prefill_interleave_set = false;
|
||||
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks;
|
||||
* -1 auto (Scheduler::interleave_steps) */
|
||||
/* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate
|
||||
* before the scheduler evicts cache blocks and preempts a lower-priority running request to
|
||||
* make room for it. 0 = fall back on the next step; default 5000 ms. */
|
||||
@@ -848,6 +869,9 @@ struct Config {
|
||||
int64_t vram_weights_mib = 0;
|
||||
int64_t vram_kv_mib = 0;
|
||||
int64_t gpu_headroom_mib = 96; /* --gpu-headroom-mib, left unclaimed on every card */
|
||||
/* --gpu-memory-mib: claim this much of every card; 0 uses gpu_headroom_mib. Inverse of
|
||||
* headroom: N + headroom = the card, in MiB. Not with --gpu-headroom-mib. */
|
||||
int64_t gpu_memory_mib = 0;
|
||||
/* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head)
|
||||
* descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4
|
||||
* keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant),
|
||||
@@ -887,6 +911,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
|
||||
|
||||
+56
-14
@@ -31,11 +31,15 @@ int Ctx::init(const CtxDesc& d) {
|
||||
registry_ = d.registry;
|
||||
kv_ = d.kv;
|
||||
arch_step_ = d.arch_step;
|
||||
arch_pass_key_ = d.arch_pass_key;
|
||||
profiling_ = d.profile_ops;
|
||||
|
||||
/* The rank owns one device. Set it here so allocation lands on the right card, and again from
|
||||
* the rank thread in bind_thread() because the backend's current device is thread-local. */
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
RadDeviceProps props{};
|
||||
if (rad_dev_props(device_, &props) >= 0 && !props.is_host_backend && props.n_cu > 0)
|
||||
wgp_count_ = props.n_cu;
|
||||
|
||||
if (d.stream) {
|
||||
stream_ = d.stream;
|
||||
@@ -367,6 +371,7 @@ int Ctx::bind_ops() {
|
||||
ip.args.instance = r.instance;
|
||||
ip.args.rank = rank_;
|
||||
ip.args.world_size = world_size_;
|
||||
ip.args.wgp_count = wgp_count_;
|
||||
/* A launch that ends its own link hold gets the hold word as an extra
|
||||
* `link_gate` parameter after the geometry's. */
|
||||
if (r.row->releases_link)
|
||||
@@ -777,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;
|
||||
}
|
||||
@@ -942,23 +964,36 @@ int Ctx::lane_join(int from, int to) {
|
||||
|
||||
/* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A
|
||||
* field added to RadBatch changes its size: decide whether the key must read it, then update the
|
||||
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
|
||||
* (below). */
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408,
|
||||
* size here. The ABI-35 host mirrors are used by issue-time split selection; unsupported dynamic
|
||||
* geometries fail closed via the pass-key contract, while Qwen keys its full-group maximum in the
|
||||
* architecture callback. `agen_b`, `vgen_b` and `sgen_b` are set only on generator passes, which are
|
||||
* never recorded (below). */
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 480,
|
||||
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80,
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 88,
|
||||
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
|
||||
|
||||
uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
/* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows
|
||||
* issue the scatter only when they have some. */
|
||||
if (b->enc || b->n_mm_rows > 0) return 0;
|
||||
* 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;
|
||||
/* 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))
|
||||
return 0;
|
||||
}
|
||||
/* A pass carrying a request's words for the plugin is shaped by them (a head issues per
|
||||
* sequence from their counts), and such a step samples a prompt's first token, which is not
|
||||
* the repeating decode pass. */
|
||||
if (b->n_plugin_words > 0) return 0;
|
||||
/* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key
|
||||
* below reads. */
|
||||
/* A generator pass is shaped by what RadBatch::gen_b, agen_b, vgen_b or sgen_b carries, which
|
||||
* no key below reads. */
|
||||
if (b->gen) return 0;
|
||||
uint64_t h = 0x9e3779b97f4a7c15ull;
|
||||
auto mix = [&](uint64_t v) {
|
||||
@@ -976,6 +1011,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids);
|
||||
ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted);
|
||||
ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids);
|
||||
/* A block drafter's query pass reads it (null on every other pass). */
|
||||
ptr(b->anchor_rows);
|
||||
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
|
||||
* two are different passes. The slots themselves are read on the card. */
|
||||
ptr(b->lora_slot);
|
||||
@@ -989,6 +1026,11 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
/* A streamed group's view by the memory it names, never its address (kvstream_view_key). */
|
||||
mix(kvstream_view_key(k.stream));
|
||||
}
|
||||
if (arch_pass_key_) {
|
||||
const uint64_t geometry = arch_pass_key_(const_cast<Ctx*>(this), b, b->kv_used_max_h);
|
||||
if (!geometry) return 0;
|
||||
mix(geometry);
|
||||
}
|
||||
mix((uint64_t)level_);
|
||||
mix(dense_epoch_);
|
||||
mix(domain_epoch_.load(std::memory_order_relaxed));
|
||||
|
||||
+11
-8
@@ -40,10 +40,6 @@ class Registry;
|
||||
struct XpState;
|
||||
struct XpLayer;
|
||||
|
||||
/* The widest conventional op is gdn_conv_prep at sixteen operands (docs/OPS.md). Thirty-two leaves
|
||||
* room for an architecture plugin's private ops without a variable-length array on the hot path. */
|
||||
constexpr int MAX_OPERANDS = 32;
|
||||
|
||||
typedef void (*ArchStepFn)(RadCtx*, const RadBatch*);
|
||||
|
||||
/* "[shape]/[stride]" of a tensor's live dimensions, for diagnostics. */
|
||||
@@ -196,6 +192,7 @@ struct CtxDesc {
|
||||
RadStream stream = nullptr; /* null: the Ctx creates its own compute stream */
|
||||
ResidencyTable* residency = nullptr; /* null in the all-in-VRAM case */
|
||||
ArchStepFn arch_step = nullptr; /* the architecture plugin's rad_arch_step */
|
||||
uint64_t (*arch_pass_key)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
|
||||
bool profile_ops = false; /* spec §16, and it changes what you measure */
|
||||
/* Whether a repeated pass may be recorded and played back. False for a caller whose pass
|
||||
* issues work the batch does not describe (e.g. a test driving another component through
|
||||
@@ -260,6 +257,7 @@ public:
|
||||
}
|
||||
/* This rank's device ordinal, for the calls that name a card rather than a stream. */
|
||||
int device() const { return device_; }
|
||||
int wgp_count() const { return wgp_count_; }
|
||||
int world_size() const { return world_size_; }
|
||||
RadStream stream() const { return stream_; }
|
||||
Program* program() const { return program_; }
|
||||
@@ -334,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 */
|
||||
@@ -657,6 +656,8 @@ private:
|
||||
bool staging_ = false; /* the stager armed for the pass being issued */
|
||||
int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
|
||||
ArchStepFn arch_step_ = nullptr;
|
||||
uint64_t (*arch_pass_key_)(RadCtx*, const RadBatch*, const int32_t*) = nullptr;
|
||||
int wgp_count_ = 32;
|
||||
|
||||
/* The expert prefetch's state (xp_state.h), null while it is off. */
|
||||
std::unique_ptr<XpState> xp_;
|
||||
@@ -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,6 +10,7 @@
|
||||
* the host. See ctx.h for the cost budget (spec §3.2).
|
||||
*/
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
@@ -62,6 +63,66 @@ std::string tensor_shape_str(const RadTensor& t) {
|
||||
return s + "]";
|
||||
}
|
||||
|
||||
/* A device launch may use a host-side KV bound only when its exact operand maps to the host mirror
|
||||
* of seqused (including a sequence slice), or to the position just after a one-sequence prefill
|
||||
* piece. Never copy seqused back from a device queue here: the AQL upload may still be pending on
|
||||
* another queue. */
|
||||
static bool issue_vector_operand(const RadTensor& t) {
|
||||
return (t.rank == 1 && t.stride[0] == 1) ||
|
||||
(t.rank == 2 && t.shape[1] == 1 && t.stride[0] == 1 && t.stride[1] == 1);
|
||||
}
|
||||
|
||||
static bool issue_host_span_max(const RadTensor& t, const int32_t* device, const int32_t* host,
|
||||
int64_t total, int32_t* out) {
|
||||
if (!t.data || !issue_vector_operand(t) || t.shape[0] <= 0 || !device || !host || total <= 0 || !out)
|
||||
return false;
|
||||
const std::uintptr_t p = reinterpret_cast<std::uintptr_t>(t.data);
|
||||
const std::uintptr_t base = reinterpret_cast<std::uintptr_t>(device);
|
||||
if (p < base) return false;
|
||||
const std::uintptr_t delta = p - base;
|
||||
if (delta % sizeof(int32_t)) return false;
|
||||
const std::uint64_t first = delta / sizeof(int32_t);
|
||||
const std::uint64_t count = (std::uint64_t)t.shape[0];
|
||||
if (first > (std::uint64_t)total || count > (std::uint64_t)total - first) return false;
|
||||
int32_t maximum = host[first];
|
||||
for (std::uint64_t i = 1; i < count; ++i) maximum = std::max(maximum, host[first + i]);
|
||||
*out = maximum;
|
||||
return true;
|
||||
}
|
||||
|
||||
static int32_t issue_kv_used_max_h(const RadBatch* b, const RadTensor* t, int n) {
|
||||
if (!b || !t || b->n_seq <= 0) return -1;
|
||||
bool have = false;
|
||||
int32_t found = -1;
|
||||
auto add = [&](int32_t value) {
|
||||
if (!have) { found = value; have = true; }
|
||||
else if (found != value) return false;
|
||||
return true;
|
||||
};
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!t[i].data || !issue_vector_operand(t[i]) || t[i].shape[0] <= 0) continue;
|
||||
if (b->kv) for (int g = 0; g < b->n_kv_groups; ++g) {
|
||||
if (b->kv_used_max_h && t[i].data == b->kv[g].seqused &&
|
||||
t[i].shape[0] == b->n_seq) {
|
||||
if (!add(b->kv_used_max_h[g])) return -1;
|
||||
continue;
|
||||
}
|
||||
int32_t used = -1;
|
||||
if (issue_host_span_max(t[i], b->kv[g].seqused, b->kv[g].seqused_h,
|
||||
b->n_seq, &used) && !add(used)) return -1;
|
||||
}
|
||||
/* ArPieces' first attention uses positions[R] as its exact KV end: it is the position after
|
||||
* the first query piece. This special operand is one length for one ordinary prefill seq. */
|
||||
if (b->phase == RAD_PHASE_PREFILL && b->n_seq == 1 && b->n_spec == 0 &&
|
||||
b->draft_pass == 0 && t[i].shape[0] == 1) {
|
||||
int32_t used = -1;
|
||||
if (issue_host_span_max(t[i], b->positions, b->positions_h, b->n_tok, &used) &&
|
||||
!add(used)) return -1;
|
||||
}
|
||||
}
|
||||
return have ? found : -1;
|
||||
}
|
||||
|
||||
/* Element offset to byte offset. False when it cannot be expressed: a mid-byte offset into a
|
||||
* packed sub-byte weight (e.g. an odd W4 element), or a plugin-private dtype with no core-known
|
||||
* size. */
|
||||
@@ -854,6 +915,17 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
/* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. There is one
|
||||
* 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_;
|
||||
|
||||
@@ -1280,6 +1352,9 @@ int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer) {
|
||||
}
|
||||
int rad_rank(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->rank() : 0; }
|
||||
int rad_world_size(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->world_size() : 1; }
|
||||
int rad_ctx_wgp_count(RadCtx* c) {
|
||||
return c ? static_cast<rad::Ctx*>(c)->wgp_count() : 32;
|
||||
}
|
||||
RadStream rad_stream(RadCtx* c) { return c ? static_cast<rad::Ctx*>(c)->stream() : nullptr; }
|
||||
|
||||
/* The second lane. `rad_lane` selects the lane subsequent issues launch on; `rad_lane_join`
|
||||
|
||||
+50
-20
@@ -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;
|
||||
}
|
||||
@@ -980,6 +986,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
|
||||
if (budget && think.inside() && think.body >= sp.thinking_budget)
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
if (!sp.suppress_tokens.empty()) suppress(p, row, sp.suppress_tokens);
|
||||
|
||||
if (want_lp) {
|
||||
/* Temperature the candidate value carries: early and late, each counted only
|
||||
@@ -1038,6 +1045,19 @@ void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
p.flags |= RAD_SP_MASK;
|
||||
}
|
||||
|
||||
void Sampler::suppress(DeviceSampleParams& p, int64_t row, const std::vector<int32_t>& ids) {
|
||||
uint32_t* dst = mask_stage_ + row * mask_words_;
|
||||
if (!(p.flags & RAD_SP_MASK)) {
|
||||
std::memset(dst, 0xff, (size_t)mask_words_ * 4);
|
||||
p.mask_row = (int32_t)row;
|
||||
p.flags |= RAD_SP_MASK;
|
||||
}
|
||||
for (int32_t id : ids) {
|
||||
const int64_t at = (int64_t)id - cfg_.vocab_off;
|
||||
if (at >= 0 && at < cfg_.n_vocab_local) dst[at >> 5] &= ~(1u << (uint32_t)(at & 31));
|
||||
}
|
||||
}
|
||||
|
||||
int Sampler::build_greedy(int64_t n) {
|
||||
if (!declared_) return RAD_E_STATE;
|
||||
if (n < 0) return RAD_E_INVAL;
|
||||
@@ -1054,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];
|
||||
@@ -1083,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1115,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). */
|
||||
|
||||
+15
-2
@@ -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]; }
|
||||
@@ -267,6 +276,9 @@ private:
|
||||
* inside the block. A grammar mask on the row wins: the close is forced only where the
|
||||
* grammar admits it, otherwise at a later position. */
|
||||
void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
|
||||
/* Take `ids` out of the row: from the grammar's mask where it has one, from a full row where
|
||||
* not. */
|
||||
void suppress(DeviceSampleParams& p, int64_t row, const std::vector<int32_t>& ids);
|
||||
|
||||
SamplerConfig cfg_{};
|
||||
const VocabView* vocab_ = nullptr;
|
||||
@@ -341,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. */
|
||||
|
||||
@@ -48,7 +48,11 @@ struct StepSlot {
|
||||
* drafter's context rows by it. 0 after a chain verify, which needs neither. */
|
||||
int32_t npath;
|
||||
int32_t path[RAD_SCHED_MAX_SPEC];
|
||||
int32_t pad[2];
|
||||
/* The last verify step's row of its last committed position, in that step's own row order,
|
||||
* which a block drafter's context pass mirrors. ADV_BLOCK hands it to the query pass
|
||||
* (RadBatch::anchor_rows): LiLiCorr's correlator reads the context state there. */
|
||||
int32_t hrow;
|
||||
int32_t pad[1];
|
||||
};
|
||||
|
||||
enum AdvMode : int32_t {
|
||||
@@ -115,6 +119,7 @@ struct AdvanceArgs {
|
||||
int32_t n_groups = 0;
|
||||
char* slab = nullptr; /* this rank's device slab */
|
||||
int64_t tok_off = 0, pos_off = 0, ctx_off = 0, acc_off = 0, out_off = 0;
|
||||
int64_t arow_off = -1; /* [n_seq] ADV_BLOCK: each row's StepSlot::hrow; -1 when not carved */
|
||||
int64_t sid_off = 0, cu_off = 0, q_off = 0;
|
||||
/* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first
|
||||
* verified position; its first sampled row, or -1 for a row that sampled nothing; and one
|
||||
|
||||
@@ -153,6 +153,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
S.ctx = head + 1;
|
||||
S.n_acc = acc + 1;
|
||||
S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]];
|
||||
S.hrow = rtok + (acc == 0 ? 0 : S.path[acc - 1]); /* rows are nodes, in order */
|
||||
S.npath = acc;
|
||||
return;
|
||||
}
|
||||
@@ -167,6 +168,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
const int32_t head = ctx[i] + (rtok - k) + acc;
|
||||
S.acc = acc;
|
||||
S.head = head;
|
||||
S.hrow = rtok + acc;
|
||||
S.ctx = head + 1;
|
||||
S.n_acc = acc + 1;
|
||||
S.tok[0] = y[acc];
|
||||
@@ -296,6 +298,7 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
for (int32_t j = 1; j < n; ++j) tok[k + j] = aux;
|
||||
for (int32_t j = 0; j < n; ++j) adv_pos(a, pos, k + j, base + j);
|
||||
ctx[i] = base;
|
||||
if (a.arow_off >= 0) adv_i32(a, a.arow_off)[i] = S.hrow;
|
||||
adv_groups(a, i, k, base, n);
|
||||
return;
|
||||
}
|
||||
|
||||
+45
-1
@@ -123,6 +123,7 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
/* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */
|
||||
pair(&s.h_rpos, &s.d_rpos, S);
|
||||
pair(&s.h_tlen, &s.d_tlen, S);
|
||||
pair(&s.h_arow, &s.d_arow, S);
|
||||
s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size());
|
||||
s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size());
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
@@ -135,6 +136,7 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
* moves a rotary position off the token index. */
|
||||
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
|
||||
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
|
||||
pair(&s.h_bidi, &s.d_bidi, bidi_on_ ? 4 * T : 0);
|
||||
/* Each row's adapter slot, carved only when the engine serves adapters, so an engine without
|
||||
* them lays the slab out as if the array did not exist. */
|
||||
pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0);
|
||||
@@ -245,6 +247,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
o.kv.assign(ranks_.size(), std::vector<RadKVGroupBatch>(s.groups.size()));
|
||||
o.stream.assign(ranks_.size(), std::vector<RadKVStream>(s.groups.size()));
|
||||
o.batch.assign(ranks_.size(), RadBatch{});
|
||||
o.kv_used_max_h.assign(s.groups.size(), 0);
|
||||
o.seqs.clear();
|
||||
o.seqs.reserve((size_t)max_seqs_); /* a build fills it without allocating */
|
||||
o.has_seqs = false;
|
||||
@@ -480,6 +483,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
});
|
||||
|
||||
mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0;
|
||||
bidi_on_ = prog.encoder.modalities != 0 && prog.encoder.bidirectional != 0;
|
||||
lora_on_ = cfg.lora.enabled();
|
||||
pw_cap_ = prog.plugin_words;
|
||||
return RAD_OK;
|
||||
@@ -725,7 +729,13 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
|
||||
if (has_win) {
|
||||
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
|
||||
/* The ring size sets the group header's geometry, so every sequence in the
|
||||
* group must report the same one. */
|
||||
if (ring_blocks && ring_blocks != (int32_t)win.ring_blocks) {
|
||||
RAD_ERR("kv group %d: sequences report ring sizes of %d and %d blocks",
|
||||
(int)gi, (int)ring_blocks, (int)win.ring_blocks);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
ring_blocks = (int32_t)win.ring_blocks;
|
||||
}
|
||||
bt_len = (int64_t)bt.size();
|
||||
@@ -808,6 +818,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
(int)g.sidx_pitch);
|
||||
}
|
||||
}
|
||||
int32_t group_used = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i)
|
||||
group_used = std::max(group_used, g.h_used[i]);
|
||||
o.kv_used_max_h[gi] = group_used;
|
||||
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
|
||||
if (!L.paged) {
|
||||
stage(g.bt_fix, np, n_seq);
|
||||
@@ -846,6 +860,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
b.block_table = on_rank(base, s.dev[0], g.d_bt);
|
||||
b.block_table_pitch = pitch;
|
||||
b.seqused = on_rank(base, s.dev[0], g.d_used);
|
||||
b.seqused_h = g.h_used;
|
||||
b.state_index = on_rank(base, s.dev[0], g.d_sidx);
|
||||
b.state_index_pitch = g.sidx_pitch;
|
||||
b.block_size = L.block_size;
|
||||
@@ -933,6 +948,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
int64_t n_out = 0, n_dout = 0;
|
||||
int32_t rope_mixed = 0;
|
||||
int64_t n_mm = 0;
|
||||
int64_t n_bidi = 0;
|
||||
bool lora_rows = false;
|
||||
int32_t cvec_rows = 0;
|
||||
int64_t n_pw = 0;
|
||||
@@ -1022,6 +1038,23 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
n_mm += got;
|
||||
}
|
||||
}
|
||||
/* The part of each picture's or video frame's run inside this chunk, read both ways
|
||||
* (RadBatch::n_bidi), on a trunk pass: its rows see the keys up to the run's end, or the
|
||||
* chunk's where a run longer than any step was cut (Scheduler::bidi_fit). */
|
||||
if (bidi_on_ && plan.draft_pass == 0 && shift == 0 && e.req && e.req->media) {
|
||||
const mm::PromptMedia& pm = *e.req->media;
|
||||
const int64_t c0 = e.ctx_len, c1 = c0 + e.n_tokens, T = max_tok_;
|
||||
for (const mm::RopeLayout::Run& run : pm.rope.runs) {
|
||||
const int64_t a = std::max<int64_t>(run.tok, c0);
|
||||
const int64_t b = std::min<int64_t>((int64_t)run.tok + run.n, c1);
|
||||
if (a >= b || pm.items[(size_t)run.item].item->kind == mm::Kind::Audio) continue;
|
||||
s.h_bidi[n_bidi] = (int32_t)b;
|
||||
s.h_bidi[T + n_bidi] = (int32_t)(k + a - c0);
|
||||
s.h_bidi[2 * T + n_bidi] = (int32_t)(b - a);
|
||||
s.h_bidi[3 * T + n_bidi] = (int32_t)i;
|
||||
++n_bidi;
|
||||
}
|
||||
}
|
||||
if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) {
|
||||
/* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the
|
||||
* scheduler chose, the last token of a checkpoint interval (§7.3). */
|
||||
@@ -1075,6 +1108,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
s.h_q[i] = e.n_tokens;
|
||||
s.h_ctx[i] = e.ctx_len;
|
||||
s.h_acc[i] = e.n_accepted;
|
||||
s.h_arow[i] = -1;
|
||||
if (e.is_prefill) { if (e.n_tokens > max_q_pf) max_q_pf = e.n_tokens; }
|
||||
else { if (e.n_tokens > max_q_dec) max_q_dec = e.n_tokens; }
|
||||
}
|
||||
@@ -1205,6 +1239,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.n_seq = n_seq;
|
||||
B.token_ids = on_rank(base, b0, s.d_tok);
|
||||
B.positions = on_rank(base, b0, s.d_pos);
|
||||
B.positions_h = s.h_pos;
|
||||
B.cu_seqlens = on_rank(base, b0, s.d_cu);
|
||||
B.seq_ids = on_rank(base, b0, s.d_sid);
|
||||
B.n_out = n_out;
|
||||
@@ -1220,6 +1255,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.max_q_len_decode = max_q_dec;
|
||||
B.max_q_len_prefill = max_q_pf;
|
||||
B.max_ctx_len = (int32_t)ctx_bound;
|
||||
B.kv_used_max_h = o.kv_used_max_h.data();
|
||||
B.n_kv_groups = (int)o.kv[r].size();
|
||||
B.kv = o.kv[r].data();
|
||||
B.draft_pass = plan.draft_pass;
|
||||
@@ -1230,10 +1266,17 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
|
||||
/* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */
|
||||
B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr;
|
||||
/* Pass 1 is a block drafter's query pass (a serial head has no pass 1). */
|
||||
B.anchor_rows = plan.draft_pass == 1 ? on_rank(base, b0, s.d_arow) : nullptr;
|
||||
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
|
||||
B.rope_mixed = rope_mixed;
|
||||
B.n_mm_rows = n_mm;
|
||||
B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr;
|
||||
B.n_bidi = n_bidi;
|
||||
B.bidi_used = n_bidi ? on_rank(base, b0, s.d_bidi) : nullptr;
|
||||
B.bidi_row = n_bidi ? s.h_bidi + max_tok_ : nullptr;
|
||||
B.bidi_n = n_bidi ? s.h_bidi + 2 * max_tok_ : nullptr;
|
||||
B.bidi_seq = n_bidi ? s.h_bidi + 3 * max_tok_ : nullptr;
|
||||
B.mm_embd = n_mm ? mm_dev_[r] : nullptr;
|
||||
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
|
||||
* runs the same pass as an engine serving no adapters. */
|
||||
@@ -1309,6 +1352,7 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
|
||||
a.ctx_off = off(s.d_ctx);
|
||||
a.acc_off = off(s.d_acc);
|
||||
a.out_off = off(s.d_out);
|
||||
a.arow_off = off(s.d_arow);
|
||||
a.sid_off = off(s.d_sid);
|
||||
a.cu_off = off(s.d_cu);
|
||||
a.q_off = off(s.d_q);
|
||||
|
||||
@@ -220,12 +220,19 @@ private:
|
||||
* runtime window (advance.h). Per sequence because each prompt has its own floor. */
|
||||
int32_t *h_rpos = nullptr, *d_rpos = nullptr;
|
||||
int32_t *h_tlen = nullptr, *d_tlen = nullptr;
|
||||
/* [max_seqs] a block drafter's query pass: each row's last committed row in the context
|
||||
* pass just run (RadBatch::anchor_rows), written on the card by ADV_BLOCK. */
|
||||
int32_t *h_arow = nullptr, *d_arow = nullptr;
|
||||
|
||||
char* h_derived = nullptr; /* derivation staging, byte-addressed */
|
||||
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
|
||||
* mm_rows): carved only when the program declared an encoder, empty otherwise. */
|
||||
int32_t *h_rope = nullptr, *d_rope = nullptr;
|
||||
int32_t *h_mmrow = nullptr, *d_mmrow = nullptr;
|
||||
/* [4][max_tok] the runs read both ways (RadBatch::n_bidi): their key counts (the one plane
|
||||
* the device reads), first rows, rows and sequences; carved only when the program's
|
||||
* encoder asks for them (RadEncoderDecl::bidirectional). */
|
||||
int32_t *h_bidi = nullptr, *d_bidi = nullptr;
|
||||
/* [n_tok] each row's runtime LoRA adapter slot (RadBatch::lora_slot): carved only when the
|
||||
* engine serves adapters, empty otherwise. */
|
||||
int32_t *h_lora = nullptr, *d_lora = nullptr;
|
||||
@@ -265,6 +272,7 @@ private:
|
||||
/* Per rank and group, the RadKVStream a batch names: each rank's own copy, outside the slab. */
|
||||
std::vector<std::vector<RadKVStream>> stream;
|
||||
std::vector<RadBatch> batch;
|
||||
std::vector<int32_t> kv_used_max_h;
|
||||
/* The build's sequences in row order (step_seqs); none for an encoder pass. */
|
||||
std::vector<uint64_t> seqs;
|
||||
bool has_seqs = false;
|
||||
@@ -344,6 +352,7 @@ private:
|
||||
* (see RadBatch::mm_embd). The staging is refilled only after its last upload has run
|
||||
* (`mm_ev_`). */
|
||||
bool mm_on_ = false;
|
||||
bool bidi_on_ = false; /* RadEncoderDecl::bidirectional */
|
||||
/* The engine serves runtime LoRA adapters (Config::lora): the batch carries each row's slot. */
|
||||
bool lora_on_ = false;
|
||||
/* Program::plugin_words: the words a sequence may carry, 0 for none. */
|
||||
|
||||
@@ -9,11 +9,13 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* lcm, with a non-positive side meaning "no constraint yet". */
|
||||
/* lcm, with a non-positive side meaning "no constraint yet". The sides are plugin-declared; an lcm
|
||||
* past int64 saturates, so the quantum check refuses it rather than wrapping to a small one. */
|
||||
static int64_t lcm64(int64_t a, int64_t b) {
|
||||
if (a <= 0) return b;
|
||||
if (b <= 0) return a;
|
||||
return std::lcm(a, b);
|
||||
const int64_t q = a / std::gcd(a, b);
|
||||
return q > INT64_MAX / b ? INT64_MAX : q * b;
|
||||
}
|
||||
|
||||
/* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps
|
||||
|
||||
+160
-28
@@ -138,7 +138,14 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
"prompt unfinished while other sequences decode, the next %lld steps carry "
|
||||
"decode rows only and admit nothing", (long long)cfg.prefill_interleave,
|
||||
(long long)cfg.prefill_interleave);
|
||||
else if (cfg.prefill_interleave < 0)
|
||||
RAD_INFO("scheduler: --prefill-interleave auto: after a prefill chunk that leaves its "
|
||||
"prompt unfinished while other sequences decode, decode-only steps follow for up "
|
||||
"to %.2f of the chunk step's measured time (at most %lld steps)",
|
||||
cfg.prefill_interleave_share, (long long)kInterleaveAutoMax);
|
||||
interleave_left_ = 0;
|
||||
ema_chunk_s_ = 0.0;
|
||||
ema_decode_s_ = 0.0;
|
||||
held_prefill_ = 0;
|
||||
draft_refill_ = 0;
|
||||
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
|
||||
@@ -375,6 +382,11 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.arrived_us = mono_us();
|
||||
s.first_tok_us = 0;
|
||||
s.preempted_us = 0;
|
||||
/* A recycled slot keeps its struct, and the prefill figure is computed from admitted_us
|
||||
* whenever it is non-zero: left standing, it would date this request's first token to the
|
||||
* admission of whichever request held the slot before. The re-admission guard below needs
|
||||
* it zero for the same reason -- a stale stamp would read as an earlier admission. */
|
||||
s.admitted_us = 0;
|
||||
s.slot = slot;
|
||||
s.card = -1;
|
||||
s.running = false;
|
||||
@@ -584,14 +596,11 @@ void Scheduler::trim_prefix_cache() {
|
||||
if (short_by > 0) (void)pc_->trim(short_by);
|
||||
}
|
||||
|
||||
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
|
||||
bool publish, int status, const char* why) {
|
||||
++step_finished_;
|
||||
/* Publish before freeing: this is the only moment the whole prefix is both computed and still
|
||||
* owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled
|
||||
* and failed requests are published too; their prompts were computed, and a client that hangs
|
||||
* up mid-answer is likely to ask for that prefix again. */
|
||||
if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
|
||||
/* What a request computed, into the prefix cache, while it still owns the blocks: at its close,
|
||||
* and at a preemption, whose recompute then adopts its prompt instead of computing it again.
|
||||
* True when published. */
|
||||
bool Scheduler::publish_prefix(SchedReq& s) {
|
||||
if (cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
|
||||
s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) {
|
||||
/* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its
|
||||
* table is a reference plus a ring rather than a prefix from position 0, and the window
|
||||
@@ -613,8 +622,20 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
RAD_DEBUG("prefix cache: request %llu not published: %s",
|
||||
(unsigned long long)s.req->id, rad_strerror(rc));
|
||||
trim_prefix_cache();
|
||||
return rc >= 0;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
|
||||
bool publish, int status, const char* why) {
|
||||
++step_finished_;
|
||||
/* Publish before freeing: this is the only moment the whole prefix is both computed and still
|
||||
* owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled
|
||||
* and failed requests are published too; their prompts were computed, and a client that hangs
|
||||
* up mid-answer is likely to ask for that prefix again. */
|
||||
if (publish) (void)publish_prefix(s);
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
/* Prompt lookup's index is this text's alone. */
|
||||
@@ -901,6 +922,8 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
|
||||
o.slot = s.slot;
|
||||
o.age_s = (double)(now - s.arrived_us) / 1e6;
|
||||
o.ttft_s = s.first_tok_us ? (double)(s.first_tok_us - s.arrived_us) / 1e6 : -1.0;
|
||||
o.prefill_s = (s.first_tok_us && s.admitted_us)
|
||||
? (double)(s.first_tok_us - s.admitted_us) / 1e6 : -1.0;
|
||||
/* Since the first token, not admission, so time spent queued does not read as slow
|
||||
* decode. */
|
||||
const double dec = s.first_tok_us ? (double)(now - s.first_tok_us) / 1e6 : 0.0;
|
||||
@@ -968,7 +991,7 @@ int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
|
||||
* so a chunk clamped to it is already aligned; in the other order a chunk past the checkpoint
|
||||
* would be rounded down and miss the boundary. */
|
||||
int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos, int64_t keep_at) const {
|
||||
int64_t* checkpoint_pos, int64_t keep_at, const Request* r) const {
|
||||
if (checkpoint_pos) *checkpoint_pos = -1;
|
||||
int64_t remaining = n_target - n_computed;
|
||||
if (remaining <= 0 || budget <= 0) return 0;
|
||||
@@ -1093,9 +1116,48 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
if (checkpoint_pos && *checkpoint_pos > aligned) *checkpoint_pos = -1;
|
||||
}
|
||||
}
|
||||
if (r) {
|
||||
const int64_t fit = bidi_fit(*r, n_computed, n_target, want, budget);
|
||||
/* A trimmed chunk keeps a window snapshot it still carries (as above); a grown one drops it. */
|
||||
if (fit != want && checkpoint_pos && (fit > want || *checkpoint_pos > n_computed + fit))
|
||||
*checkpoint_pos = -1;
|
||||
want = fit;
|
||||
}
|
||||
return want;
|
||||
}
|
||||
|
||||
/* A chunk that ended inside a run read both ways would give the run's rows of this chunk keys the
|
||||
* next chunk writes. So it ends before the run, on a quantum (and before every run that lands in,
|
||||
* as a video's frames do); a chunk that starts at or inside the run (nothing fits before it) runs
|
||||
* to the run's end, rounded up to a quantum unless the sequence ends first, past every run that
|
||||
* lands in, or waits for a step that holds that. A run no step holds is cut where the chunk falls,
|
||||
* and its rows see the run up to the cut (RadBatch::bidi_used). */
|
||||
int64_t Scheduler::bidi_fit(const Request& r, int64_t n_computed, int64_t n_target, int64_t want,
|
||||
int64_t budget) const {
|
||||
if (!prog_ || !prog_->encoder.bidirectional || !r.media || want <= 0) return want;
|
||||
const mm::PromptMedia& pm = *r.media;
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
/* The run read both ways that a chunk ending at `end` would cut, or null. */
|
||||
auto cut = [&](int64_t end) -> const mm::RopeLayout::Run* {
|
||||
if (end >= n_target) return nullptr;
|
||||
const mm::RopeLayout::Run* run = pm.rope.run_at(end);
|
||||
if (!run || run->tok == end || pm.items[(size_t)run->item].item->kind == mm::Kind::Audio)
|
||||
return nullptr;
|
||||
return run;
|
||||
};
|
||||
int64_t end = n_computed + want;
|
||||
for (const mm::RopeLayout::Run* run = cut(end); run; run = cut(end)) {
|
||||
const int64_t before = (int64_t)run->tok / Q * Q;
|
||||
if (before <= n_computed) break;
|
||||
end = before;
|
||||
}
|
||||
if (!cut(end)) return end - n_computed;
|
||||
for (const mm::RopeLayout::Run* run = cut(end); run; run = cut(end))
|
||||
end = std::min<int64_t>(n_target, ((int64_t)run->tok + run->n + Q - 1) / Q * Q);
|
||||
if (end - n_computed <= budget) return end - n_computed;
|
||||
return end - n_computed > cfg_.max_tok ? want : 0;
|
||||
}
|
||||
|
||||
/* The tail checkpoint of a `target`-token prompt, or -1. Under --prefix-resume exact, where its
|
||||
* last chunk starts (below). Under nearest, its last quantum boundary, only past the first
|
||||
* interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
|
||||
@@ -1215,14 +1277,44 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
|
||||
return std::min(std::max(cap, Q), budget);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ decode-only steps */
|
||||
/* How many decode-only steps follow a chunk that ran beside decoding sequences
|
||||
* (--prefill-interleave). N as given; under auto, as many as fit in Config::prefill_interleave_share of a chunk
|
||||
* step's measured time at a decode step's, so the prefill gives up at most a fifth of its rate
|
||||
* (a quarter of a chunk step) however many sequences decode, and the decoders get the steps that
|
||||
* share buys: several where decode steps are cheap beside the chunk, none where one costs more
|
||||
* than a quarter of it (they still ride every chunk). One until both costs are measured, which
|
||||
* takes the first decode-only step. Both are wall times read off step_finished, so under auto
|
||||
* which steps carry a chunk follows the device's timing and differs from run to run; a number
|
||||
* schedules the same steps every time. */
|
||||
void Scheduler::step_cost_locked(bool chunk, double seconds) {
|
||||
double& ema = chunk ? ema_chunk_s_ : ema_decode_s_;
|
||||
ema = ema > 0.0 ? ema + kInterleaveEma * (seconds - ema) : seconds;
|
||||
}
|
||||
|
||||
void Scheduler::note_step_cost(bool chunk, double seconds) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (seconds > 0) step_cost_locked(chunk, seconds);
|
||||
}
|
||||
|
||||
int64_t Scheduler::interleave_steps() const {
|
||||
if (cfg_.prefill_interleave >= 0) return cfg_.prefill_interleave;
|
||||
if (ema_chunk_s_ <= 0.0 || ema_decode_s_ <= 0.0) return 1;
|
||||
const double n = cfg_.prefill_interleave_share * ema_chunk_s_ / ema_decode_s_;
|
||||
return n >= (double)kInterleaveAutoMax ? kInterleaveAutoMax : (int64_t)n;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ preemption */
|
||||
void Scheduler::preempt_back() {
|
||||
bool Scheduler::preempt_back() {
|
||||
int32_t slot = running_.back();
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
Request& r = *s.req;
|
||||
|
||||
/* Preemption by recompute: the blocks go back and the request restarts from zero. Its output
|
||||
* is the tail of its token sequence, so it simply re-prefills prompt ++ output. */
|
||||
* is the tail of its token sequence, so it simply re-prefills prompt ++ output. What it computed
|
||||
* is published first: the recompute adopts it from the cache, and under pressure the cache gives
|
||||
* the blocks back (the newest entries last). */
|
||||
const bool published = publish_prefix(s);
|
||||
kv_->preempt(r.id);
|
||||
drop_card(s);
|
||||
r.n_computed = 0;
|
||||
@@ -1242,6 +1334,7 @@ void Scheduler::preempt_back() {
|
||||
running_.pop_back();
|
||||
queue_insert(waiting_, slot); /* original arrival -> the front of its priority class */
|
||||
++m_.preemptions;
|
||||
return published;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ admission */
|
||||
@@ -1319,6 +1412,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
const RestoreResult rr = pc_->restore(r, whole_only);
|
||||
if (rr == RestoreResult::Declined) {
|
||||
s.restore_waited = true;
|
||||
admit_next_step_ = true;
|
||||
RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)",
|
||||
(unsigned long long)r.id, n_deferred_);
|
||||
return RAD_E_FULL;
|
||||
@@ -1471,9 +1565,12 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
* to what really has to run. */
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0)
|
||||
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
|
||||
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
|
||||
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
|
||||
else if (cap < budget && want > 0)
|
||||
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at, &r);
|
||||
}
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
@@ -1522,6 +1619,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
|
||||
if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); }
|
||||
r.state = ReqState::Running;
|
||||
if (!s.admitted_us) s.admitted_us = mono_us(); /* first admission; a re-admit after
|
||||
* preemption keeps the original stamp */
|
||||
s.preempted_us = 0;
|
||||
s.running = true;
|
||||
server::sink_admitted(r.sink);
|
||||
@@ -1552,6 +1651,9 @@ void Scheduler::undo_hit(SchedReq& s) {
|
||||
bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
|
||||
const Request& r = *s.req;
|
||||
const int64_t target = s.seq_len();
|
||||
/* What the recompute adopts from the cache (its own prefix, published at the preemption) needs
|
||||
* no new block. */
|
||||
const int64_t hit = (cfg_.prefix_cache && pc_) ? pc_->lookup(r, nullptr, nullptr).n_attn_tokens : 0;
|
||||
|
||||
for (size_t g = 0; g < kvgeom_.g.size(); ++g) {
|
||||
const KVGeom::G& gg = kvgeom_.g[g];
|
||||
@@ -1559,7 +1661,7 @@ bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
|
||||
* wanted the whole prompt from a pool of none and kept a preempted request out for good. */
|
||||
if (!gg.paged || kv_->total_blocks((int32_t)g) <= 0) continue;
|
||||
int64_t need = (target + gg.block_size - 1) / gg.block_size -
|
||||
(int64_t)kv_->block_table(r.id, (int32_t)g).size();
|
||||
(int64_t)kv_->block_table(r.id, (int32_t)g).size() - hit / gg.block_size;
|
||||
if (need < 0) need = 0;
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& rs = *reqs_[(size_t)slot];
|
||||
@@ -1692,7 +1794,7 @@ const RadBatch* Scheduler::step() {
|
||||
running_.erase(std::find(running_.begin(), running_.end(), victim));
|
||||
running_.push_back(victim);
|
||||
}
|
||||
preempt_back();
|
||||
if (preempt_back()) evict_rounds = 0; /* its blocks stay in the cache: evict them first */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1704,7 +1806,7 @@ const RadBatch* Scheduler::step() {
|
||||
bool any_decoding = false;
|
||||
bool hold_prefill = false;
|
||||
held_prefill_ = 0;
|
||||
if (cfg_.prefill_interleave > 0) {
|
||||
if (cfg_.prefill_interleave != 0) {
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
@@ -1820,10 +1922,13 @@ const RadBatch* Scheduler::step() {
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
|
||||
/*rows_only=*/shares == 0);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0 && capped_at < 0) {
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
|
||||
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
|
||||
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
|
||||
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
|
||||
else if (cap < budget && want > 0 && capped_at < 0) {
|
||||
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
|
||||
r.checkpoint_at);
|
||||
r.checkpoint_at, &r);
|
||||
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
|
||||
}
|
||||
/* A prefill with no room left does not end the walk: it takes nothing this step, but
|
||||
@@ -1910,7 +2015,9 @@ const RadBatch* Scheduler::step() {
|
||||
/* The back of the running set gives its blocks up. When that is this request, the
|
||||
* requests ahead of it hold the pool: it is preempted by recompute and waits for
|
||||
* them, rather than failed. */
|
||||
preempt_back();
|
||||
/* A victim that published keeps its blocks in the cache: eviction gets its rounds
|
||||
* back, so they are reclaimed before anyone else is preempted. */
|
||||
if (preempt_back()) evict_rounds = 0;
|
||||
preempted_here = true;
|
||||
if (last) { yielded = true; break; }
|
||||
}
|
||||
@@ -2001,13 +2108,28 @@ const RadBatch* Scheduler::step() {
|
||||
(int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1
|
||||
? share_tok : 0;
|
||||
admit_full_ = 0;
|
||||
admit_next_step_ = false;
|
||||
const int as = admit_one(s, budget, areserve);
|
||||
if (as == kAdmitWait) { ++at; continue; }
|
||||
/* A preempted request waiting for its whole-recompute gate lets the next one be asked;
|
||||
* an overdue one does not. The room the overdue path made this step is for it, and a
|
||||
* request queued behind it would take that room back: a victim just forced off for it,
|
||||
* its prompt published, needs almost nothing to come back, and under KV pressure the
|
||||
* same victim was forced off and re-admitted 26 times in 16 s while the overdue request
|
||||
* waited. */
|
||||
if (as == kAdmitWait) {
|
||||
if (s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) break;
|
||||
++at;
|
||||
continue;
|
||||
}
|
||||
/* An overdue preempted prefill on an idle engine that still cannot be admitted will
|
||||
* not become admissible by waiting: nothing is running to finish and free the pool.
|
||||
* Fail it (spec §17) and ask the next request, instead of parking the step loop. */
|
||||
if (as < 0 && running_.empty() && s.req && s.req->state == ReqState::Preempted &&
|
||||
preempt_wait_overdue(s)) {
|
||||
* Fail it (spec §17) and ask the next request, instead of parking the step loop. Not
|
||||
* when this step admitted someone ahead of it (the budget or a card went to them) or
|
||||
* the refusal is a restore waiting a step for deferred releases: both clear by the
|
||||
* next step, and failing them lost two of ten preempted requests under KV pressure
|
||||
* once their prompts were published at the preemption (1. 11. 2026). */
|
||||
if (as < 0 && running_.empty() && plan_.e.empty() && !admit_next_step_ && s.req &&
|
||||
s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) {
|
||||
RAD_WARN("request %llu failed: overdue preempted prefill could not be admitted "
|
||||
"with nothing running (%s)",
|
||||
(unsigned long long)s.req->id, rad_strerror(as));
|
||||
@@ -2081,7 +2203,7 @@ const RadBatch* Scheduler::step() {
|
||||
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
|
||||
int64_t ckpt = -1;
|
||||
const int64_t grown = e.ckpt_slot < 0 && limit > had
|
||||
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at)
|
||||
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at, &r)
|
||||
: had;
|
||||
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
|
||||
e.n_tokens = (int32_t)grown;
|
||||
@@ -2135,13 +2257,13 @@ const RadBatch* Scheduler::step() {
|
||||
case RAD_PHASE_MIXED: ++m_.steps_mixed; break;
|
||||
default: ++m_.steps_decode; break;
|
||||
}
|
||||
if (cfg_.prefill_interleave > 0) {
|
||||
if (cfg_.prefill_interleave != 0) {
|
||||
/* Armed only while a prompt continues past this step: after a last chunk nothing is left
|
||||
* to interleave, and holding would only keep the next request out. */
|
||||
bool continues = false;
|
||||
for (const StepEntry& e : plan_.e)
|
||||
if (e.is_prefill && !e.produces_token) continues = true;
|
||||
if (any_pf) interleave_left_ = any_decoding && continues ? cfg_.prefill_interleave : 0;
|
||||
if (any_pf) interleave_left_ = any_decoding && continues ? interleave_steps() : 0;
|
||||
else if (interleave_left_ > 0) --interleave_left_;
|
||||
if (held_prefill_ > 0) ++m_.steps_held;
|
||||
}
|
||||
@@ -2562,7 +2684,14 @@ int Scheduler::commit(StepResult& res) {
|
||||
/* Not while a step issued ahead writes past `valid`; that step's commit rolls back to
|
||||
* the end it reaches. */
|
||||
if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) {
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
if (kv_rollback_test_hook_) kv_rollback_test_hook_(r.id, e.n_spec, a, valid, true);
|
||||
#endif
|
||||
int st = kv_->rollback(r.id, valid);
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
if (st >= 0 && kv_rollback_test_hook_)
|
||||
kv_rollback_test_hook_(r.id, e.n_spec, a, valid, false);
|
||||
#endif
|
||||
if (st < 0) RAD_WARN("kv rollback for request %llu: %s",
|
||||
(unsigned long long)r.id, rad_strerror(st));
|
||||
}
|
||||
@@ -2736,6 +2865,9 @@ void Scheduler::step_finished() {
|
||||
/* The window ages by all elapsed time, idle included; only the busy part is added as time the
|
||||
* tokens took. */
|
||||
const double aged = std::chrono::duration<double>(step_end - last_step_at_).count();
|
||||
/* --prefill-interleave auto's two step costs (interleave_steps). */
|
||||
if (wall > 0 && cfg_.prefill_interleave < 0)
|
||||
step_cost_locked(plan_.phase != RAD_PHASE_DECODE, wall);
|
||||
if (wall > 0) {
|
||||
constexpr double kWindowS = 1.0;
|
||||
const double f = std::exp(-aged / kWindowS);
|
||||
|
||||
+42
-2
@@ -19,6 +19,9 @@
|
||||
#include "ngram.h"
|
||||
|
||||
#include <chrono>
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
#include <functional>
|
||||
#endif
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
@@ -42,6 +45,9 @@ struct SchedReq {
|
||||
/* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
|
||||
int64_t arrived_us = 0;
|
||||
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
|
||||
int64_t admitted_us = 0; /* 0 until the first admission: where the queue ends, so a
|
||||
* prefill rate can divide by the prefill alone. ttft covers
|
||||
* the wait for admission (GUIDE); this excludes it. */
|
||||
int64_t preempted_us = 0; /* when this state became Preempted; 0 otherwise. Bounds the
|
||||
* whole-recompute admission wait (--preempt-wait-ms). */
|
||||
|
||||
@@ -274,6 +280,7 @@ public:
|
||||
int32_t slot = -1;
|
||||
double age_s = 0;
|
||||
double ttft_s = -1; /* negative until the first token */
|
||||
double prefill_s = -1; /* first token minus admission; negative until both */
|
||||
double decode_tps = 0; /* this request's own, since its first token */
|
||||
};
|
||||
/* Oldest first, since the oldest is the one most likely stuck. Returns how many were
|
||||
@@ -463,7 +470,15 @@ public:
|
||||
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
|
||||
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
|
||||
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos, int64_t keep_at = 0) const;
|
||||
int64_t* checkpoint_pos, int64_t keep_at = 0,
|
||||
const Request* r = nullptr) const;
|
||||
/* Visible for tests: `want` tokens of `r` from `n_computed` cut so the chunk ends inside no run
|
||||
* the language model reads both ways (RadEncoderDecl::bidirectional): before the run on a
|
||||
* quantum, or at its end when the chunk starts in it and `budget` holds that, else 0. A run
|
||||
* longer than any step keeps the cut where it falls. `want` unchanged for a program with no
|
||||
* such runs. */
|
||||
int64_t bidi_fit(const Request& r, int64_t n_computed, int64_t n_target, int64_t want,
|
||||
int64_t budget) const;
|
||||
|
||||
/* The smallest step the prefill stager overlaps, in tokens (0 = no stager), set once by the
|
||||
* engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it (busy_cap).
|
||||
@@ -489,8 +504,21 @@ public:
|
||||
* multi-token chunk past the floor would overwrite keys its own earlier rows still read, while
|
||||
* one token a step attends as its decode step did. Otherwise `n_target`. */
|
||||
int64_t chunk_end(const Request& r, int64_t n_target) const;
|
||||
/* --prefill-interleave: the decode-only steps that follow a chunk run beside decoding
|
||||
* sequences. N as configured; under auto, from the measured step costs (see the definition).
|
||||
* Visible for tests, as is note_step_cost, which feeds auto a step's wall time as
|
||||
* step_finished does: `chunk` for a step that carried a prefill chunk, else a decode step. */
|
||||
int64_t interleave_steps() const;
|
||||
void note_step_cost(bool chunk, double seconds);
|
||||
|
||||
private:
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
friend class Engine;
|
||||
/* Test-build-only observer at the concrete rollback operation. */
|
||||
void set_kv_rollback_test_hook(std::function<void(uint64_t, int, int, int64_t, bool)> hook) {
|
||||
kv_rollback_test_hook_ = std::move(hook);
|
||||
}
|
||||
#endif
|
||||
Program* prog_ = nullptr;
|
||||
Config cfg_{};
|
||||
ChunkGeometry geo_{};
|
||||
@@ -503,11 +531,15 @@ private:
|
||||
int64_t span_min_ = 0;
|
||||
/* Set by admit_one when it held the admitted chunk back: what it would have taken. */
|
||||
int64_t admit_full_ = 0;
|
||||
bool admit_next_step_ = false; /* admit_one's refusal is a wait for the next step */
|
||||
/* Whether this step's prefill may span (ChunkGeometry::span): set by step() for the step it
|
||||
* plans, true only for a prefill alone in its step, and read by plan_chunk. True outside a
|
||||
* step, so plan_chunk called directly answers for a span. */
|
||||
bool span_now_ = true;
|
||||
IKVManager* kv_ = nullptr;
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
std::function<void(uint64_t, int, int, int64_t, bool)> kv_rollback_test_hook_;
|
||||
#endif
|
||||
IPrefixCache* pc_ = nullptr;
|
||||
|
||||
/* Does a prefix-cache hit leave a hole in a block drafter's own KV? Only if some paged group
|
||||
@@ -748,6 +780,13 @@ private:
|
||||
* the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
|
||||
int64_t interleave_left_ = 0;
|
||||
int64_t held_prefill_ = 0;
|
||||
/* --prefill-interleave auto: the decode-only steps after a chunk (interleave_steps), sized by
|
||||
* the running means of a step that carried a chunk and of a decode step, in seconds, fed by
|
||||
* step_finished. */
|
||||
static constexpr double kInterleaveEma = 0.25;
|
||||
static constexpr int64_t kInterleaveAutoMax = 64;
|
||||
double ema_chunk_s_ = 0.0, ema_decode_s_ = 0.0;
|
||||
void step_cost_locked(bool chunk, double seconds);
|
||||
/* The throughput window (step_finished): each kind's tokens and the wall time the steps
|
||||
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
|
||||
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
|
||||
@@ -796,7 +835,8 @@ private:
|
||||
const Request* serial_req(const SerialSeq& m) const;
|
||||
/* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */
|
||||
const Request* live_req(int32_t slot, uint64_t id) const;
|
||||
void preempt_back();
|
||||
bool preempt_back(); /* true: the victim published its prefix */
|
||||
bool publish_prefix(SchedReq& s);
|
||||
/* A preempted request waits until the pool can hold its WHOLE remaining recompute, the rest
|
||||
* of every running prefill, and one block of headroom per runner. Admitting it against only
|
||||
* the next token steals the blocks a running prefill still needs and preempt_back() resets
|
||||
|
||||
@@ -311,6 +311,7 @@ public:
|
||||
o.slot = r.slot;
|
||||
o.age_s = r.age_s;
|
||||
o.ttft_s = r.ttft_s;
|
||||
o.prefill_s = r.prefill_s;
|
||||
o.decode_tps = r.decode_tps;
|
||||
out->push_back(std::move(o));
|
||||
}
|
||||
|
||||
@@ -390,7 +390,7 @@ json Server::capabilities() const {
|
||||
caps["reasoning"] = !rerank && deps_.chat && deps_.chat->supports_reasoning();
|
||||
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
|
||||
* whatever its conditioning network's processor would take. */
|
||||
const bool img = opt_.image_model || opt_.video_model;
|
||||
const bool img = opt_.image_model || opt_.video_model || opt_.shape_model;
|
||||
caps["grammar"] = !img && !rerank && deps_.grammar != nullptr;
|
||||
/* Laya runs on the embedding path, but answers /v1/systemone, not /v1/embeddings. */
|
||||
caps["embedding"] = deps_.embed != nullptr && !rerank && opt_.decision_type != "laya";
|
||||
@@ -403,11 +403,13 @@ json Server::capabilities() const {
|
||||
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
|
||||
caps["audio_generation"] = deps_.audio != nullptr;
|
||||
caps["video_generation"] = deps_.videos != nullptr;
|
||||
caps["shape_generation"] = deps_.shapes != nullptr;
|
||||
/* The decision protocol /v1/systemone serves (ServerOptions::decision_type), so a proxy can
|
||||
* route to a decision model without trying a generation; null when it serves none. */
|
||||
caps["decision"] = opt_.decision_type.empty() ? json(nullptr) : json(opt_.decision_type);
|
||||
/* What a video request may carry. */
|
||||
if (deps_.videos) video_caps(caps, deps_.videos);
|
||||
if (deps_.shapes) shape_caps(caps, deps_.shapes);
|
||||
/* The efforts a chat request may send, probed from the template at startup; null when it
|
||||
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
|
||||
+358
-102
@@ -385,6 +385,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
j["slot"] = q.slot;
|
||||
j["age_s"] = q.age_s;
|
||||
if (q.ttft_s >= 0) j["ttft_s"] = q.ttft_s;
|
||||
if (q.prefill_s >= 0) j["prefill_s"] = q.prefill_s;
|
||||
j["tps"] = q.decode_tps;
|
||||
reqs.push_back(std::move(j));
|
||||
}
|
||||
@@ -586,6 +587,18 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
.cap { font-size:10.5px; font-weight:600; letter-spacing:.1em; text-transform:uppercase;
|
||||
color:var(--dim); }
|
||||
.aside { font-family:var(--mono); font-size:11.5px; color:var(--dim); }
|
||||
/* A panel header's left side can hold a title plus a control; the header itself is
|
||||
* space-between, so without this group the control would land in the middle. */
|
||||
.pleft { display:flex; align-items:baseline; gap:9px; }
|
||||
.pbtn { background:none; border:0; padding:0; margin:0; color:var(--faint); cursor:pointer;
|
||||
display:inline-flex; align-items:center; }
|
||||
.pbtn:hover { color:var(--fg); }
|
||||
.pbtn:focus-visible { outline:1px solid var(--edge); outline-offset:3px; }
|
||||
/* The glyph is nudged down 2px so the tray bar's bottom lines up with the bottom of the
|
||||
* caption's letters. align-items:baseline puts the SVG's BOX on the text baseline, but the
|
||||
* baseline sits above the box bottom, so the bar floated ~2px high -- measured in headless
|
||||
* Chrome, not eyeballed. The viewBox-flush geometry alone does not fix this. */
|
||||
#reqjson svg { transform: translateY(2px); }
|
||||
.pbody { padding:14px 16px 16px; }
|
||||
|
||||
/* The control vector's switch: a checkbox row with its explanation under it. The two need a gap
|
||||
@@ -595,6 +608,13 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
.cvrow { display:flex; align-items:center; gap:8px; }
|
||||
#cvnote { margin-top:9px; padding-left:4px; }
|
||||
|
||||
.pollrow { display:flex; align-items:center; gap:10px; font-size:13px; color:var(--fg); }
|
||||
.pollrow + .pollnote { margin-top:6px; }
|
||||
.pollnote { max-width:74ch; }
|
||||
.pollrow input[type=number] { width:11ch; font:400 15px/1.4 var(--mono); color:var(--fg);
|
||||
background:var(--track); border:1px solid var(--edge);
|
||||
border-radius:5px; padding:7px 10px; }
|
||||
|
||||
/* ------------------------------------------------ THE FIRST ROW IS FIXED, THE REST FIT THEIR CONTENT
|
||||
A card whose content changes LENGTH moves every card under it while it is being read, and one
|
||||
card here does that every poll: the list of requests gains and loses rows. So the first row --
|
||||
@@ -734,6 +754,12 @@ th + th, td + td { padding-left:14px; }
|
||||
margin-top:14px; padding-top:12px; border-top:1px solid var(--rule); }
|
||||
#hist .hhead { display:flex; align-items:baseline; gap:10px; margin-bottom:8px; }
|
||||
#hist .hsum { flex:1; font-family:var(--mono); font-size:11px; color:var(--dim); line-height:1.5; }
|
||||
/* Each category is one atomic unit: if it cannot fit on the line it moves whole, rather than
|
||||
* breaking mid-figure and orphaning a unit -- "810" at the end of one line, "ms" on the next.
|
||||
* The separator is its own element with padding because HTML collapses runs of spaces, so
|
||||
* spacing in the string could never have widened the category break. */
|
||||
#hist .hgrp { white-space:nowrap; }
|
||||
#hist .hsep { color:var(--faint); padding:0 9px; }
|
||||
#hist .hbtn { font-family:var(--mono); font-size:10px; color:var(--faint); cursor:pointer;
|
||||
user-select:none; padding:0 4px; }
|
||||
#hist .hbtn:hover { color:var(--bad); }
|
||||
@@ -1167,6 +1193,7 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
<button id="tab-dash" class="on">Dashboard</button>
|
||||
<button id="tab-sess">Sessions</button>
|
||||
<button id="tab-model">Model</button>
|
||||
<button id="tab-adv">Advanced</button>
|
||||
</nav>
|
||||
<input id="key" type="password" placeholder="API key" autocomplete="off" hidden>
|
||||
<span class="ver" id="ver"></span>
|
||||
@@ -1212,7 +1239,17 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
<div class="body">
|
||||
<div class="stack">
|
||||
<section class="panel" id="reqpanel">
|
||||
<div class="phead"><span class="cap">Requests</span>
|
||||
<div class="phead"><span class="pleft"><span class="cap">Requests</span>
|
||||
<button type="button" class="pbtn" id="reqjson"
|
||||
title="Download JSON file" aria-label="Download JSON file">
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true">
|
||||
<!-- The tray bar's stroke bottom lands exactly on the viewBox
|
||||
bottom, so baseline alignment puts the bar on the text
|
||||
baseline. An inset bar floats a hair above the caps. -->
|
||||
<path d="M8 2v9m0 0L4.6 7.6M8 11l3.4-3.4M2.2 15.2h11.6"
|
||||
fill="none" stroke="currentColor" stroke-width="1.6"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg></button></span>
|
||||
<span class="aside" id="reqaside"></span></div>
|
||||
<div class="pbody">
|
||||
<div class="hold">
|
||||
@@ -1224,8 +1261,7 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
</div>
|
||||
<div id="hist">
|
||||
<div class="hhead"><span class="cap">history</span>
|
||||
<span class="hsum" id="hsum"></span>
|
||||
<span class="hbtn" id="hjson" title="copy the stored rows as JSON">json</span>
|
||||
<span class="hsum" id="hsum" title="mean of the per-request figures over all captured rows; each request counts once, so this is not the pooled rate the DECODE tile shows. last 20 and last 5 are the same mean over the most recent 20 and 5 requests. prefill is fresh prompt tokens over the time from admission to first token, so queue wait is not charged to it; on an engine that reports no admission time it falls back to time to first token, which does include queue wait. ttft is the median time to first token, including queue wait."></span>
|
||||
<span class="hbtn" id="hclr" title="clear the stored history">clear</span></div>
|
||||
<div class="hlist">
|
||||
<table>
|
||||
@@ -1359,6 +1395,25 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
|
||||
</div>
|
||||
|
||||
<!-- CHOSEN ONCE AND THEN LEFT ALONE. A view of its own, reached from the header like the others:
|
||||
these settings are not read alongside the figures, and at the foot of the dashboard column
|
||||
they sat under everything a reader scrolls past to get to them. -->
|
||||
<div id="view-adv" hidden>
|
||||
<section class="panel">
|
||||
<div class="phead"><span class="cap">Advanced</span>
|
||||
<span class="aside" id="advsum"></span></div>
|
||||
<div class="pbody">
|
||||
<label class="pollrow" for="pollidle">Idle interval
|
||||
<input id="pollidle" type="number" min="100" max="5000" step="50"> ms</label>
|
||||
<label class="pollrow" style="margin-top:12px" for="pollbusy">Busy interval
|
||||
<input id="pollbusy" type="number" min="100" max="5000" step="50"> ms</label>
|
||||
<div class="aside pollnote">Idle is how often the page fetches when no request is running;
|
||||
busy is how often while one is in flight. Set them equal for a single fixed rate.
|
||||
100–5000 ms each.</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- WHAT HAPPENS IF A STORED CONVERSATION COMES BACK. The strip says how well the cache is
|
||||
serving and where what it holds is; the tables say, a conversation a row, what its next
|
||||
turn reuses and what it prefills. Every figure is tokens or bytes. -->
|
||||
@@ -1477,7 +1532,7 @@ $("key").addEventListener("change", (e) => {
|
||||
* tab is left and re-opened. */
|
||||
loadControlVector();
|
||||
});
|
||||
const HIST = 120; /* 60s of history at the 500ms poll */
|
||||
const HIST_S = 60; /* the sparkline's window in SECONDS: the span it draws and prunes to */
|
||||
|
||||
const el = (t, c, x) => { const e = document.createElement(t);
|
||||
if (c) e.className = c; if (x !== undefined) e.textContent = x;
|
||||
@@ -1594,6 +1649,10 @@ const stepTime = (ms) => !finite(ms) ? { n: DASH, u: "ms" }
|
||||
/* The caption and the unit live in the document beside the cell they label. Holding a second
|
||||
* copy of them here would be holding a copy that can differ. */
|
||||
const METRICS = ["step", "decode", "prefill", "flight", "kv", "accept"];
|
||||
/* One monotonic stamp per poll: every ring is pruned and drawn against it, so a window means
|
||||
* the same span of seconds whatever interval the browser polls at. performance.now() so a wall
|
||||
* clock adjustment cannot stretch or shrink a window. */
|
||||
let nowS = 0;
|
||||
const M = {}, hist = {};
|
||||
for (const k of METRICS) {
|
||||
hist[k] = [];
|
||||
@@ -1608,9 +1667,10 @@ for (const k of METRICS) {
|
||||
* rare spike owns the box and the typical variation is squeezed into a pixel. A spike past the
|
||||
* 95th draws pinned to the top; the number above carries the level and the detail line the
|
||||
* extremes. The stroke is 1.25 units wide, so a one-unit inset keeps it off the edge. */
|
||||
function spark(key, vals) {
|
||||
function spark(key, pts) {
|
||||
const s = M[key], w = 200, h = 22;
|
||||
if (vals.length < 3) { s.line.setAttribute("d", ""); return; }
|
||||
if (pts.length < 3) { s.line.setAttribute("d", ""); return; }
|
||||
const vals = pts.map(p => p.v);
|
||||
const q = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))];
|
||||
const sorted = [...vals].sort((a, b) => a - b);
|
||||
let lo = q(sorted, 0.05), hi = q(sorted, 0.95);
|
||||
@@ -1618,18 +1678,28 @@ function spark(key, vals) {
|
||||
* extremes then serve, so the spikes still show. */
|
||||
if (!(hi > lo)) { lo = sorted[0]; hi = sorted[sorted.length - 1]; }
|
||||
const span = hi - lo;
|
||||
const dx = w / (vals.length - 1);
|
||||
/* X IS TIME, NOT SAMPLE INDEX. Index spacing is only honest while every sample is the same age
|
||||
* apart; once the poll rate varies -- adaptive, or a browser throttling a busy tab -- a busy
|
||||
* stretch of 100 ms samples would be drawn five times wider than the seconds it took. The newest
|
||||
* sample sits on the right edge and the window spans HIST_S back from it, so a stretch gets the
|
||||
* room its seconds deserve and a gap in the samples shows as a gap in the line. */
|
||||
const t1 = pts[pts.length - 1].t;
|
||||
let d = "";
|
||||
for (let i = 0; i < vals.length; i++) {
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
let t = span > Math.abs(hi) * 1e-3 ? (vals[i] - lo) / span : 0.5;
|
||||
if (t < 0) t = 0; else if (t > 1) t = 1;
|
||||
d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," + (h - 1 - (h - 2) * t).toFixed(1);
|
||||
const x = Math.min(w, Math.max(0, w * (1 - (t1 - pts[i].t) / HIST_S)));
|
||||
d += (i ? "L" : "M") + x.toFixed(1) + "," + (h - 1 - (h - 2) * t).toFixed(1);
|
||||
}
|
||||
s.line.setAttribute("d", d);
|
||||
}
|
||||
function setMetric(key, value, text) {
|
||||
M[key].n.firstChild.nodeValue = text;
|
||||
if (value != null) { hist[key].push(value); if (hist[key].length > HIST) hist[key].shift(); }
|
||||
if (value != null) {
|
||||
const r = hist[key];
|
||||
r.push({ t: nowS, v: value });
|
||||
while (r.length && r[0].t < nowS - HIST_S) r.shift();
|
||||
}
|
||||
spark(key, hist[key]);
|
||||
}
|
||||
|
||||
@@ -1637,8 +1707,9 @@ function setMetric(key, value, text) {
|
||||
* publishes a floor and a recent window only for the decode step; for these it publishes one
|
||||
* figure per poll, so the three figures are the page's own:
|
||||
* best / highest - the extreme this page has seen at the current concurrency; it resets on
|
||||
* reload, not on a server restart. "highest" where more is not better.
|
||||
* recent - the mean of the last RECENT samples at that concurrency.
|
||||
* reload AND on a server restart (a new started_at runs newEngineRun()).
|
||||
* "highest" where more is not better.
|
||||
* recent - the mean of the last RECENT_S seconds at that concurrency.
|
||||
* now - the current value as a percentage of that extreme.
|
||||
* Figures are kept per concurrency ("@cN" past one), because a batched rate read against the
|
||||
* single-stream best reports a batch arriving as a level change. Requests in flight keeps one
|
||||
@@ -1647,28 +1718,44 @@ function setMetric(key, value, text) {
|
||||
* without a now clause. There is no ~99 cap as on the decode step: the extreme comes from the
|
||||
* same series as `now`, so 100% is exact.
|
||||
*
|
||||
* RECENT is shorter than the sparkline's 60 s: a 60 s mean still shows a burst long after the lane
|
||||
* RECENT_S is shorter than the sparkline's HIST_S: a 60 s mean still shows a burst long after the lane
|
||||
* went quiet, and 15 s decays within a quarter-minute while still tracking the mean mid-burst.
|
||||
* Prefill's window is 5 s, so `recent` follows a prefill of several seconds while it runs instead
|
||||
* of diluting it; the engine's prefill rate is itself already windowed. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll; acceptance is
|
||||
sampled only on polls that drafted, so its 30 samples can span minutes */
|
||||
const RECENT_PREFILL = 10; /* 5 s */
|
||||
const extAt = {}, winAt = {};
|
||||
let lastActiveC = 0;
|
||||
const RECENT_S = 15; /* the `recent` window in seconds, for a figure sampled every poll */
|
||||
const RECENT_PREFILL_S = 5; /* prefill's is shorter, so a several-second prefill shows up in it */
|
||||
const extAt = {}, winAt = {}, extAtS = {}; /* extAtS: the poll at which each extreme was set */
|
||||
let lastActiveC = 0, lastStart = null;
|
||||
/* A new engine process is a different discontinuity from a quiet minute: the previous run's
|
||||
* requests are gone and its configuration may differ, so nothing from it carries over. Every
|
||||
* other figure already refuses to pool across a restart -- accWindow drops its rings, histIngest
|
||||
* resets its base -- and the session extremes are no different, since a best from a run that no
|
||||
* longer exists is not this lane's best. */
|
||||
function newEngineRun() {
|
||||
resetWindows();
|
||||
for (const k in extAt) delete extAt[k];
|
||||
for (const k in extAtS) delete extAtS[k];
|
||||
}
|
||||
/* Whether the server streams its KV (--kv-resident). Settled at bringup, so it cannot change under
|
||||
* a running page: the cells that name a memory tier read it instead of guessing. */
|
||||
let kvStreamOn = false;
|
||||
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
|
||||
* `highest` from extAt. */
|
||||
function noteSample(key, c, value, cap, win) {
|
||||
function noteSample(key, c, value, capS, win) {
|
||||
if (value == null || !finite(value)) return;
|
||||
const e = extAt[key] || (extAt[key] = {});
|
||||
if (!(c in e) || value > e[c]) e[c] = value;
|
||||
if (!(c in e) || value > e[c]) {
|
||||
e[c] = value;
|
||||
/* When the extreme was set, so a figure that outlives its window can say how old it is. */
|
||||
const t = extAtS[key] || (extAtS[key] = {});
|
||||
t[c] = nowS;
|
||||
}
|
||||
if (win === false) return;
|
||||
const w = winAt[key] || (winAt[key] = {});
|
||||
const s = w[c] || (w[c] = []);
|
||||
s.push(value); if (s.length > (cap || RECENT)) s.shift();
|
||||
const lim = capS || RECENT_S;
|
||||
s.push({ t: nowS, v: value });
|
||||
while (s.length && s[0].t < nowS - lim) s.shift();
|
||||
}
|
||||
function triple(key, c, label, fmt, showNow) {
|
||||
/* `recent` is a window mean: a window maximum would equal `best` on any steady lane. */
|
||||
@@ -1676,16 +1763,30 @@ function triple(key, c, label, fmt, showNow) {
|
||||
if (!e || !(c in e)) return "";
|
||||
/* A bucket whose extreme is zero still renders (requests in flight before the first request);
|
||||
* only the `now` clause needs a nonzero extreme to divide by. */
|
||||
const s = winAt[key][c];
|
||||
let sum = 0;
|
||||
for (const v of s) sum += v;
|
||||
const recent = sum / s.length;
|
||||
const now = s[s.length - 1];
|
||||
/* The extreme is a property of the session and outlives a cleared window (a gap, a restart);
|
||||
* `recent` and `now` are properties of the window, so they are dropped until it fills again.
|
||||
* Rendering the extreme alone keeps the line's one surviving figure rather than blanking it. */
|
||||
const s = (winAt[key] || {})[c];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = label + " " + fmt(e[c]) + " · recent " + fmt(recent);
|
||||
let out = label + " " + fmt(e[c]);
|
||||
if (!s || !s.length) {
|
||||
/* The extreme outlives the window by design, so the age is what makes it honest: without it a
|
||||
* figure from before a gap -- or from before an engine restart, which the page treats as a
|
||||
* discontinuity everywhere else -- reads as the lane's current best. */
|
||||
const t = (extAtS[key] || {})[c];
|
||||
/* Only once it is actually stale: an extreme set on this poll is current, and "0 ms ago"
|
||||
* would be noise. A second is the resolution dur() itself reports below. */
|
||||
if (typeof t === "number" && nowS - t >= 1) out += " | " + dur(nowS - t) + " ago";
|
||||
return out;
|
||||
}
|
||||
let sum = 0;
|
||||
for (const p of s) sum += p.v;
|
||||
const recent = sum / s.length;
|
||||
const now = s[s.length - 1].v;
|
||||
out += " | recent " + fmt(recent);
|
||||
/* No `now` clause while nothing runs, as on the decode step: a zero rate is an idle lane, and
|
||||
* "now 0% of best" would read as a fault. */
|
||||
if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag;
|
||||
if (showNow !== false && e[c] > 0) out += " | now " + Math.round(100 * now / e[c]) + "% of " + label + tag;
|
||||
return out;
|
||||
}
|
||||
/* The acceptance tile's detail line. `highest` is the session's extreme of per-poll ratios;
|
||||
@@ -1693,15 +1794,21 @@ function triple(key, c, label, fmt, showNow) {
|
||||
function acceptTriple(c, showNow) {
|
||||
const e = extAt["accept"];
|
||||
const ring = accPool[c];
|
||||
if (!e || !(c in e) || !ring || !ring.length) return "";
|
||||
if (!e || !(c in e)) return "";
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = "highest " + pct(e[c], 0);
|
||||
if (!ring || !ring.length) {
|
||||
const t = (extAtS["accept"] || {})[c];
|
||||
if (typeof t === "number" && nowS - t >= 1) out += " | " + dur(nowS - t) + " ago";
|
||||
return out;
|
||||
}
|
||||
let R = 0, A = 0;
|
||||
for (const d of ring) { R += d.dr; A += d.da; }
|
||||
if (R <= 0) return "";
|
||||
if (R <= 0) return out;
|
||||
const last = ring[ring.length - 1];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = "highest " + pct(e[c], 0) + " \u00b7 recent " + pct(A / R, 0);
|
||||
out += " | recent " + pct(A / R, 0);
|
||||
if (showNow !== false && e[c] > 0 && last.dr > 0)
|
||||
out += " \u00b7 now " + Math.round(100 * (last.da / last.dr) / e[c]) + "% of highest" + tag;
|
||||
out += " | now " + Math.round(100 * (last.da / last.dr) / e[c]) + "% of highest" + tag;
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1925,15 +2032,20 @@ function lines(svgId, series) {
|
||||
}
|
||||
}
|
||||
let hi = 0;
|
||||
for (const s of series) for (const v of s.vals) if (v > hi) hi = v;
|
||||
for (const s of series) for (const p of s.pts) if (p.v > hi) hi = p.v;
|
||||
/* X IS TIME, as on the sparklines: both series share one window, so a busy stretch is the width
|
||||
* of its seconds in both and the two lines stay comparable to each other. */
|
||||
let t1 = 0;
|
||||
for (const s of series) if (s.pts.length) t1 = Math.max(t1, s.pts[s.pts.length - 1].t);
|
||||
series.forEach((s, k) => {
|
||||
const p = svg.childNodes[k + 1];
|
||||
if (s.vals.length < 2) { p.setAttribute("d", ""); return; }
|
||||
const dx = w / (s.vals.length - 1);
|
||||
if (s.pts.length < 2) { p.setAttribute("d", ""); return; }
|
||||
let d = "";
|
||||
for (let i = 0; i < s.vals.length; i++)
|
||||
d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," +
|
||||
(h - 1 - (h - 4) * (hi > 0 ? s.vals[i] / hi : 0)).toFixed(1);
|
||||
for (const q of s.pts) {
|
||||
const x = Math.min(w, Math.max(0, w * (1 - (t1 - q.t) / HIST_S)));
|
||||
d += (d ? "L" : "M") + x.toFixed(1) + "," +
|
||||
(h - 1 - (h - 4) * (hi > 0 ? q.v / hi : 0)).toFixed(1);
|
||||
}
|
||||
p.setAttribute("d", d);
|
||||
});
|
||||
return hi;
|
||||
@@ -2075,9 +2187,15 @@ function histSave() {
|
||||
/* Prefill rate: the prompt tokens computed (not from the prefix cache) over the time to first
|
||||
* token; none for a fully cached prompt. */
|
||||
function histPrefill(r) {
|
||||
if (!finite(r.prompt) || !finite(r.ttft_s) || r.ttft_s <= 0) return null;
|
||||
if (!finite(r.prompt)) return null;
|
||||
const fresh = r.prompt - (r.cached || 0);
|
||||
return fresh > 0 ? fresh / r.ttft_s : null;
|
||||
if (fresh <= 0) return null;
|
||||
/* GUIDE: prefill speed is the prefill's own duration, not the prompt over time to
|
||||
* first token -- the latter charges the admission queue to the prefill. Fall back to
|
||||
* ttft for a server that does not report prefill_s. */
|
||||
const t = finite(r.prefill_s) && r.prefill_s > 0 ? r.prefill_s
|
||||
: (finite(r.ttft_s) && r.ttft_s > 0 ? r.ttft_s : null);
|
||||
return t ? fresh / t : null;
|
||||
}
|
||||
function histFinish(r, run) {
|
||||
if (!r || !r.id) return;
|
||||
@@ -2130,7 +2248,17 @@ const HCOLS = [
|
||||
{ h: "tok/s", f: (h) => tps(h.tps) },
|
||||
{ h: "age", f: null }, /* rewritten in place every poll */
|
||||
];
|
||||
for (const c of HCOLS) $("hhead").appendChild(el("th", null, c.h));
|
||||
const HTITLE = {
|
||||
"id": "this browser's history id; 0 again after a clear",
|
||||
"prompt": "prompt tokens",
|
||||
"out": "output tokens",
|
||||
"ctx": "context tokens, prompt plus output",
|
||||
"ttft": "time to first token, measured from arrival, so it includes queue wait",
|
||||
"prefill tok/s": "fresh prompt tokens over the time from admission to first token, so queue wait is not charged to it; a mostly-cached prompt scores low",
|
||||
"tok/s": "this request's own decode rate since its first token",
|
||||
"age": "how long ago this request finished",
|
||||
};
|
||||
for (const c of HCOLS) { const th = el("th", null, c.h); if (HTITLE[c.h]) th.title = HTITLE[c.h]; $("hhead").appendChild(th); }
|
||||
|
||||
function histRender(missed) {
|
||||
const mean = (a) => a.length ? a.reduce((p, c) => p + c, 0) / a.length : null;
|
||||
@@ -2138,8 +2266,13 @@ function histRender(missed) {
|
||||
* the headline, and the recent window is what a change in the workload shows up in first. */
|
||||
const group = (vals, fmt, label) => {
|
||||
const all = mean(vals), a20 = mean(vals.slice(-20)), a5 = mean(vals.slice(-5));
|
||||
return label + " avg " + fmt(all) +
|
||||
(a20 != null ? " (20: " + fmt(a20) + ", 5: " + fmt(a5) + ")" : "");
|
||||
/* A window whose rows are a subset of a wider one shown is the same mean twice: show
|
||||
* "last 20" only once 20 requests exist and "last 5" only once 5 do, so every figure on
|
||||
* the line is a different question. */
|
||||
const w = [];
|
||||
if (vals.length >= 20) w.push("last 20: " + fmt(a20));
|
||||
if (vals.length >= 5) w.push("last 5: " + fmt(a5));
|
||||
return label + " mean " + fmt(all) + (w.length ? " | " + w.join(" | ") : "");
|
||||
};
|
||||
const tpsV = hRows.map((h) => h.tps).filter((v) => v != null);
|
||||
const pfV = hRows.map((h) => h.pf).filter((v) => v != null);
|
||||
@@ -2147,8 +2280,24 @@ function histRender(missed) {
|
||||
const parts = [hRows.length + " done"];
|
||||
if (tpsV.length) parts.push(group(tpsV, tps, "tok/s"));
|
||||
if (pfV.length) parts.push(group(pfV, cnt3, "prefill"));
|
||||
if (tfs.length) parts.push("ttft " + dur(tfs[Math.floor(tfs.length / 2)]));
|
||||
$("hsum").textContent = parts.join(" · ");
|
||||
if (tfs.length) parts.push("ttft median " + dur(tfs[Math.floor(tfs.length / 2)]));
|
||||
/* One element per category so it wraps whole, and the dot between them is its own element so
|
||||
* its spacing survives. The dot marks a category change; the pipe inside each group marks a
|
||||
* different question about the same category. */
|
||||
const hsum = $("hsum");
|
||||
hsum.textContent = "";
|
||||
parts.forEach((p, i) => {
|
||||
/* The zero-width space is the line's ONLY break opportunity. The groups are nowrap so they
|
||||
* cannot split, and with no break point here a long summary overflows the row and clips
|
||||
* whatever follows it -- which is what the padded separators did to this line. */
|
||||
if (i) hsum.appendChild(document.createTextNode("\u200b"));
|
||||
const g = el("span", "hgrp");
|
||||
/* The dot travels WITH the category it introduces: as a sibling it could be left stranded
|
||||
* at the end of a line when the category wrapped, which is the orphan this avoids. */
|
||||
if (i) g.appendChild(el("span", "hsep", "\u00b7"));
|
||||
g.appendChild(document.createTextNode(p));
|
||||
hsum.appendChild(g);
|
||||
});
|
||||
|
||||
/* Newest first. The rows are rebuilt only when the set changes; a poll only rewrites the ages. */
|
||||
const body = $("hbody");
|
||||
@@ -2185,8 +2334,13 @@ $("hclr").addEventListener("click", () => {
|
||||
lsSet(HK, "[]"); lsSet(HKN, "0"); lsSet(HKC, String(Date.now()));
|
||||
hDrawn = null; histRender(0);
|
||||
});
|
||||
$("hjson").addEventListener("click", () => {
|
||||
try { navigator.clipboard.writeText(JSON.stringify(hRows)); } catch (e) {}
|
||||
$("reqjson").addEventListener("click", () => {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(hRows, null, 2)],
|
||||
{ type: "application/json" }));
|
||||
const a = el("a");
|
||||
a.href = url; a.download = "radiance-history.json";
|
||||
document.body.appendChild(a); a.click(); a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
});
|
||||
histLoad();
|
||||
histRender(0);
|
||||
@@ -2202,11 +2356,12 @@ let lastStepMs = null;
|
||||
* lane is doing, so a restart priced against it would not pay back. Until the engine's first
|
||||
* window completes, the fastest single-stream step this tab has seen stands in. */
|
||||
let c1hist = [];
|
||||
const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */
|
||||
const C1CAP_S = 3600; /* the fallback floor's horizon in seconds */
|
||||
const bestAt = {}; /* fastest step seen at each concurrency, this process */
|
||||
|
||||
function update(s, dt) {
|
||||
$("ver").textContent = s.version + " · up " + dur(s.uptime_s);
|
||||
nowS = performance.now() / 1000;
|
||||
$("ver").textContent = s.version + " | up " + dur(s.uptime_s);
|
||||
|
||||
/* THE DECODE STEP TIME, OUT OF THE ENGINE'S OWN CLOCK, and deliberately not out of the
|
||||
* browser's. Wall time over step count is wrong in two directions at once, both of them silent:
|
||||
@@ -2228,14 +2383,18 @@ function update(s, dt) {
|
||||
|
||||
/* Single-stream steps only: the floor is a single-sequence window, and a batched step read
|
||||
* against it would report a batch arriving as a slowdown. */
|
||||
if (s.running === 1 && stepMs != null) { c1hist.push(stepMs); if (c1hist.length > C1CAP) c1hist.shift(); }
|
||||
if (s.running === 1 && stepMs != null) {
|
||||
c1hist.push({ t: nowS, v: stepMs });
|
||||
while (c1hist.length && c1hist[0].t < nowS - C1CAP_S) c1hist.shift();
|
||||
}
|
||||
const engBestMs = s.step_ns_decode_best > 0 ? s.step_ns_decode_best / 1e6 : 0;
|
||||
const engRecentMs = s.step_ns_decode_recent > 0 ? s.step_ns_decode_recent / 1e6 : 0;
|
||||
const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0);
|
||||
const floorMs = engBestMs > 0 ? engBestMs
|
||||
: (c1hist.length ? Math.min(...c1hist.map(x => x.v)) : 0);
|
||||
let det = "";
|
||||
if (floorMs > 0) {
|
||||
det = "best " + floorMs.toFixed(2) + "ms";
|
||||
if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms";
|
||||
if (engRecentMs > 0) det += " | recent " + engRecentMs.toFixed(2) + "ms";
|
||||
}
|
||||
/* The step as a percentage of the fastest at this concurrency (`@cN` above one). `now` is a
|
||||
* ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the
|
||||
@@ -2248,7 +2407,7 @@ function update(s, dt) {
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k];
|
||||
const shown = ref > 0 ? Math.min(99, Math.round(100 * ref / lastStepMs)) : 0;
|
||||
if (ref > 0) det += " · now " + (shown === 99 ? "~99" : shown) + "% of best" + (k === 1 ? "" : "@c" + k);
|
||||
if (ref > 0) det += " | now " + (shown === 99 ? "~99" : shown) + "% of best" + (k === 1 ? "" : "@c" + k);
|
||||
}
|
||||
$("m-stepdet").textContent = det;
|
||||
|
||||
@@ -2256,10 +2415,15 @@ function update(s, dt) {
|
||||
setMetric("prefill", s.prefill_tps, tps(s.prefill_tps));
|
||||
setMetric("flight", s.in_flight, String(s.in_flight));
|
||||
const busy = s.running > 0;
|
||||
if (busy) {
|
||||
lastActiveC = s.running;
|
||||
noteSample("decode", s.running, s.decode_tps);
|
||||
noteSample("prefill", s.running, s.prefill_tps, RECENT_PREFILL);
|
||||
if (busy) lastActiveC = s.running;
|
||||
/* Sampled every poll, idle included. The engine decays its own rate toward zero on idle, so
|
||||
* feeding that decayed value into the last active concurrency's window lets `recent` wind down
|
||||
* with the engine. Gating this on busy froze the detail line at the last busy mean, so it read
|
||||
* "recent 214" beside a headline of 0. Skipped before any activity (lastActiveC 0) so a fresh
|
||||
* idle page shows no figures rather than a column of zeros. */
|
||||
if (lastActiveC > 0) {
|
||||
noteSample("decode", lastActiveC, s.decode_tps);
|
||||
noteSample("prefill", lastActiveC, s.prefill_tps, RECENT_PREFILL_S);
|
||||
}
|
||||
noteSample("flight", "*", s.in_flight);
|
||||
const cNow = busy ? s.running : lastActiveC;
|
||||
@@ -2308,9 +2472,9 @@ function update(s, dt) {
|
||||
$("m-kvcap").textContent = kvStream ? "kv cache in ram" : "kv cache in vram";
|
||||
$("m-kvdet").textContent = s.kv_bytes_total > 0
|
||||
? (kvStream
|
||||
? "of " + hb(s.kv_bytes_total) + " in host mirror · " + cnt3(s.kv_tokens_used) + " tok"
|
||||
? "of " + hb(s.kv_bytes_total) + " in host mirror | " + cnt3(s.kv_tokens_used) + " tok"
|
||||
+ " · " + hb(s.kv_bytes_carved || 0) + " VRAM ring"
|
||||
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
|
||||
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") | "
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : ""))
|
||||
: "";
|
||||
@@ -2321,7 +2485,8 @@ function update(s, dt) {
|
||||
if (aw != null && aw.dr > 0) {
|
||||
const c = s.running > 0 ? s.running : lastActiveC;
|
||||
const ring = accPool[c] || (accPool[c] = []);
|
||||
ring.push(aw); if (ring.length > RECENT) ring.shift();
|
||||
ring.push({ t: nowS, dr: aw.dr, da: aw.da });
|
||||
while (ring.length && ring[0].t < nowS - RECENT_S) ring.shift();
|
||||
}
|
||||
/* The headline is this poll's conditional acceptance, as every other tile's big number is the
|
||||
* current value; the lifetime ratio stays in the Speculation panel, on /stats and on /metrics.
|
||||
@@ -2339,7 +2504,7 @@ function update(s, dt) {
|
||||
const list = s.requests || [];
|
||||
renderRequests(list, s.kv_tokens_total || 0);
|
||||
renderBatch(list, s);
|
||||
$("reqaside").textContent = list.length ? s.running + " running · " + s.waiting + " waiting" : "";
|
||||
$("reqaside").textContent = list.length ? s.running + " running | " + s.waiting + " waiting" : "";
|
||||
histRender(histIngest(s));
|
||||
|
||||
totals["Requests"].textContent = cnt(s.total_requests);
|
||||
@@ -2363,7 +2528,7 @@ function update(s, dt) {
|
||||
self-explanatory. The split is by who references the blocks: the first part is context a
|
||||
request on the card is reading, the second context nothing reads and the next eviction frees. */
|
||||
mKvSub.textContent = s.kv_tokens_used > 0
|
||||
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
|
||||
? cnt3(kvLive) + " tok read by running requests | " + cnt3(kvCached) + " kept for reuse"
|
||||
: "";
|
||||
mKvMax.textContent = kvStream
|
||||
? (s.kv_tokens_max > 0
|
||||
@@ -2434,8 +2599,15 @@ function update(s, dt) {
|
||||
|
||||
/* ---- devices, in the same panel as the cache meter: they are one question. */
|
||||
const cards = s.cards || [];
|
||||
if (devs.length !== cards.length)
|
||||
if (devs.length !== cards.length) {
|
||||
/* Rebuild means REPLACE. The old rows must leave the panel: a card-count change -- a
|
||||
* TP flip, a card swap -- otherwise stacks a fresh set on the stale one, and the panel
|
||||
* grows by the old count every time until the page is reloaded. Per-row removal rather
|
||||
* than the sibling guards' container-clear: #mem is shared with the KV and prefix
|
||||
* meters, which are built once and must survive. Same shape as the request rows above. */
|
||||
devs.forEach((d) => d.wrap.remove());
|
||||
devs = cards.map((c) => meter($("mem"), "dev", c.name, c.index));
|
||||
}
|
||||
cards.forEach((c, i) => {
|
||||
setBar(devs[i].i, c.vram_total ? c.vram_used / c.vram_total : 0, false);
|
||||
devs[i].v.textContent = hbOf(c.vram_used, c.vram_total, " / ");
|
||||
@@ -2459,8 +2631,8 @@ function update(s, dt) {
|
||||
name: t.name, ink: TIER_INK[i] || TIER_INK[3], w: t.units,
|
||||
a: cnt(t.units), b: hb(t.bytes) })));
|
||||
const res = ex.tiers && ex.tiers.length ? ex.tiers[0].units : 0;
|
||||
$("expaside").textContent = cnt(ex.n_units) + " units · " + hb(ex.bytes) +
|
||||
(ex.heat ? " · heat engine on" : " · static plan");
|
||||
$("expaside").textContent = cnt(ex.n_units) + " units | " + hb(ex.bytes) +
|
||||
(ex.heat ? " | heat engine on" : " | static plan");
|
||||
|
||||
/* THE HIT RATE, WHICH IS NOT THE RESIDENCY. Residency is a property of the PLAN -- how many
|
||||
* units sit in VRAM -- and this is a property of the TRAFFIC: how often the router asked for
|
||||
@@ -2499,7 +2671,7 @@ function update(s, dt) {
|
||||
const b = layerBars[i];
|
||||
b.style.height = Math.max(2, 100 * f).toFixed(1) + "%";
|
||||
b.className = f >= 0.999 ? "full" : "";
|
||||
b.title = "layer " + i + ": " + lr[i] + " of " + n + " resident · " + pct(f);
|
||||
b.title = "layer " + i + ": " + lr[i] + " of " + n + " resident | " + pct(f);
|
||||
});
|
||||
/* Only when there IS a weakest layer. Every layer fully resident is the answer this panel
|
||||
* most wants to be able to give, and colouring an arbitrary one of them amber says the
|
||||
@@ -2507,7 +2679,7 @@ function update(s, dt) {
|
||||
if (worst >= 0 && wf < 0.999) layerBars[worst].className = "min";
|
||||
$("layv").textContent = !lu.length ? DASH
|
||||
: wf >= 0.999 ? "all resident"
|
||||
: pct(sum / lu.length) + " mean · worst L" + worst + " " + pct(wf);
|
||||
: pct(sum / lu.length) + " mean | worst L" + worst + " " + pct(wf);
|
||||
/* Residency, not capability: every bucket says where units are, and the buckets add up to
|
||||
* the plan. The old "N movable" read as if cold disk experts could not move -- deposits and
|
||||
* the stager move them constantly; what they lack is an address heat can relocate without
|
||||
@@ -2517,7 +2689,7 @@ function update(s, dt) {
|
||||
cnt(t.units) + " " + (t.name === "pinned" ? "in host pool"
|
||||
: t.name === "ssd" ? "on the file tier" : t.name));
|
||||
$("planev").textContent = cnt(res) + " of " + cnt(ex.n_units) + " in VRAM" +
|
||||
(rest.length ? " · " + rest.join(" · ") : " · fully resident");
|
||||
(rest.length ? " · " + rest.join(" · ") : " | fully resident");
|
||||
|
||||
/* ---- the plane itself.
|
||||
*
|
||||
@@ -2647,7 +2819,7 @@ function update(s, dt) {
|
||||
/* THE CAVEAT SITS ON THE BAR IT QUALIFIES. Run along the panel's title it was a third line
|
||||
of heading, and it describes one element rather than the panel. */
|
||||
$("linkaside").textContent = lk.world > 1
|
||||
? lk.world + " cards · " + cnt3(lk.ar_calls) + " collectives" : "single rank";
|
||||
? lk.world + " cards | " + cnt3(lk.ar_calls) + " collectives" : "single rank";
|
||||
$("linkhint").textContent = live
|
||||
? "shares below are the rate over the last poll"
|
||||
: "idle — shares below are lifetime totals, not rates";
|
||||
@@ -2664,15 +2836,17 @@ function update(s, dt) {
|
||||
const rdn = prev && prev.experts && dt > 0
|
||||
? Math.max(0, (ex.demotions - prev.experts.demotions) / dt) : 0;
|
||||
if (prev && prev.experts && dt > 0) {
|
||||
moveHist.up.push(rup); if (moveHist.up.length > HIST) moveHist.up.shift();
|
||||
moveHist.down.push(rdn); if (moveHist.down.length > HIST) moveHist.down.shift();
|
||||
for (const pair of [[moveHist.up, rup], [moveHist.down, rdn]]) {
|
||||
pair[0].push({ t: nowS, v: pair[1] });
|
||||
while (pair[0].length && pair[0][0].t < nowS - HIST_S) pair[0].shift();
|
||||
}
|
||||
}
|
||||
const peak = lines("movechart", [{ ink: INK_UP, vals: moveHist.up },
|
||||
{ ink: INK_DOWN, vals: moveHist.down, dash: true }]);
|
||||
const peak = lines("movechart", [{ ink: INK_UP, pts: moveHist.up },
|
||||
{ ink: INK_DOWN, pts: moveHist.down, dash: true }]);
|
||||
$("mvr_n").firstChild.nodeValue = num3(rup + rdn);
|
||||
/* TWO FIGURES, because the column is a fixed width and their digit count is the data; the
|
||||
window's peak is the chart's scale and sits on its axis. */
|
||||
$("movev").textContent = peak > 0 ? num3(rup) + " up · " + num3(rdn) + " down" : "settled";
|
||||
$("movev").textContent = peak > 0 ? num3(rup) + " up | " + num3(rdn) + " down" : "settled";
|
||||
$("movepk").textContent = num3(peak);
|
||||
|
||||
moveKv["Promotions"].textContent = cnt(ex.promotions);
|
||||
@@ -2948,7 +3122,7 @@ function laneLabels(lanes) {
|
||||
if (l.length !== 1) return "spelled out";
|
||||
const g = geoms[i];
|
||||
const bits = differing.map((k) => k + " " + (g[k] === undefined ? "—" : g[k]));
|
||||
return bits.length ? bits.join(" · ") : "fused";
|
||||
return bits.length ? bits.join(" | ") : "fused";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3055,7 +3229,7 @@ function highlight(q) {
|
||||
}
|
||||
}
|
||||
$("gcount").textContent = needle ? hit + " of " + nodes.length + " nodes match"
|
||||
: cnt(graph.order.length) + " declared ops · " +
|
||||
: cnt(graph.order.length) + " declared ops | " +
|
||||
graph.ops.length + " distinct";
|
||||
}
|
||||
|
||||
@@ -3131,7 +3305,7 @@ function drawKernel(host, p) {
|
||||
if (p.shape) kvRow(dl, "compiled for", p.shape);
|
||||
if (p.dtypes) kvRow(dl, "dtypes", p.dtypes);
|
||||
if (p.variant) kvRow(dl, "variant", p.variant,
|
||||
p.variant_source + " · " + p.n_variants + " offered");
|
||||
p.variant_source + " | " + p.n_variants + " offered");
|
||||
if (p.scratch) kvRow(dl, "scratch", hb(p.scratch));
|
||||
if (dl.children.length) host.appendChild(dl);
|
||||
|
||||
@@ -3217,7 +3391,7 @@ function drawBand(host, b) {
|
||||
const s = el("div", "msub");
|
||||
s.appendChild(el("div", "sh", "host domain — the placement planner may run it here"));
|
||||
const t = el("div", "mtags");
|
||||
t.appendChild(el("span", "mtag", b.host.kernel + " · " + b.host.plugin));
|
||||
t.appendChild(el("span", "mtag", b.host.kernel + " | " + b.host.plugin));
|
||||
s.appendChild(t);
|
||||
bb.appendChild(s);
|
||||
}
|
||||
@@ -3244,7 +3418,7 @@ function drawWeights(host, o) {
|
||||
add("dtype", w.dtype);
|
||||
if (w.shape) add("shape", w.shape);
|
||||
add("layout", w.layout);
|
||||
add("lives", w.tier + " · " + w.site);
|
||||
add("lives", w.tier + " | " + w.site);
|
||||
if (w.layer >= 0) add("layer", String(w.layer));
|
||||
if (w.expert != null) add("expert", String(w.expert));
|
||||
it.appendChild(m);
|
||||
@@ -3336,7 +3510,7 @@ function drawSummary() {
|
||||
s.appendChild(cell(cnt(fusedLaunches), "", "fused launches"));
|
||||
s.appendChild(cell(cnt(fusedOps - fusedLaunches), "", "launches removed"));
|
||||
s.appendChild(cell(ab.n, ab.u, "activation arena"));
|
||||
s.appendChild(cell(String(m.n_layers), "", "layers · rank " + m.rank + "/" + m.world));
|
||||
s.appendChild(cell(String(m.n_layers), "", "layers | rank " + m.rank + "/" + m.world));
|
||||
|
||||
const gl = $("glibs");
|
||||
gl.textContent = "";
|
||||
@@ -3352,7 +3526,7 @@ function drawSummary() {
|
||||
d.appendChild(el("span", "n", pl.name));
|
||||
const used = libs[pl.name] || 0;
|
||||
d.appendChild(el("span", "c", pl.kernels + " kernels" +
|
||||
(used ? " · " + cnt(used) + " launches" : " · unused")));
|
||||
(used ? " · " + cnt(used) + " launches" : " | unused")));
|
||||
gl.appendChild(d);
|
||||
}
|
||||
$("gsum").textContent = missing ? cnt(missing) + " op(s) with no device kernel"
|
||||
@@ -3370,9 +3544,9 @@ function drawMeta() {
|
||||
host.className = "gmeta";
|
||||
const dm = (graph.misses || []).filter((m) => m.domain !== "host").length;
|
||||
$("gmetasum").textContent =
|
||||
(graph.notes ? graph.notes.length : 0) + " notes from the architecture plugin · " +
|
||||
(graph.kv_groups ? graph.kv_groups.length : 0) + " kv groups · " +
|
||||
(graph.drafter ? graph.drafter.name + " drafter · " : "") +
|
||||
(graph.notes ? graph.notes.length : 0) + " notes from the architecture plugin | " +
|
||||
(graph.kv_groups ? graph.kv_groups.length : 0) + " kv groups | " +
|
||||
(graph.drafter ? graph.drafter.name + " drafter | " : "") +
|
||||
(dm ? dm + " unresolved device band(s)" : "no unresolved device band");
|
||||
const block = (title, cls) => {
|
||||
const se = el("section", cls);
|
||||
@@ -3390,15 +3564,15 @@ function drawMeta() {
|
||||
const ul = block("kv groups — sized by the resolved attention kernels");
|
||||
for (const g of graph.kv_groups)
|
||||
ul.appendChild(el("li", null,
|
||||
g.name + " · " + g.kind + " · " + g.layers + " layer" + (g.layers === 1 ? "" : "s") +
|
||||
(g.block_size ? " · block " + g.block_size + " tokens, " + hb(g.bytes_per_block)
|
||||
: " · " + hb(g.bytes_per_state) + " a sequence")));
|
||||
g.name + " | " + g.kind + " | " + g.layers + " layer" + (g.layers === 1 ? "" : "s") +
|
||||
(g.block_size ? " | block " + g.block_size + " tokens, " + hb(g.bytes_per_block)
|
||||
: " | " + hb(g.bytes_per_state) + " a sequence")));
|
||||
}
|
||||
if (graph.drafter) {
|
||||
const ul = block("draft head");
|
||||
ul.appendChild(el("li", null, graph.drafter.name + " · " + graph.drafter.kind + " · " +
|
||||
ul.appendChild(el("li", null, graph.drafter.name + " | " + graph.drafter.kind + " | " +
|
||||
graph.drafter.depth + " token(s) a step" +
|
||||
(graph.drafter.window ? " · window " + graph.drafter.window
|
||||
(graph.drafter.window ? " | window " + graph.drafter.window
|
||||
: "")));
|
||||
}
|
||||
/* ABSENCE IS ASYMMETRIC (spec 2.1), and so is this list. No DEVICE kernel for a band is a hole
|
||||
@@ -3453,22 +3627,28 @@ $("gq").addEventListener("input", (e) => highlight(e.target.value));
|
||||
|
||||
/* ---------------------------------------------------------------- tabs */
|
||||
function show(which) {
|
||||
const model = which === "model", sess = which === "sess";
|
||||
$("view-dash").hidden = model || sess;
|
||||
const model = which === "model", sess = which === "sess", adv = which === "adv";
|
||||
/* The Advanced view holds no live figures, so the dashboard's poll pauses while it is open, as
|
||||
* it does for the Model view. Returning to the dashboard after more than a window there clears
|
||||
* the sampled windows, which is what poll() already does for a backgrounded tab. */
|
||||
$("view-dash").hidden = model || sess || adv;
|
||||
$("view-sess").hidden = !sess;
|
||||
$("view-model").hidden = !model;
|
||||
$("tab-dash").className = (model || sess) ? "" : "on";
|
||||
$("view-adv").hidden = !adv;
|
||||
$("tab-dash").className = (model || sess || adv) ? "" : "on";
|
||||
$("tab-sess").className = sess ? "on" : "";
|
||||
$("tab-model").className = model ? "on" : "";
|
||||
$("tab-adv").className = adv ? "on" : "";
|
||||
if (model) { loadGraph(); loadControlVector(); }
|
||||
if (sess) loadSessions();
|
||||
window.scrollTo(0, 0);
|
||||
const h = model ? "#model" : sess ? "#sessions" : "#";
|
||||
const h = model ? "#model" : sess ? "#sessions" : adv ? "#advanced" : "#";
|
||||
if (location.hash !== h) history.replaceState(null, "", h);
|
||||
}
|
||||
$("tab-dash").addEventListener("click", () => show("dash"));
|
||||
$("tab-sess").addEventListener("click", () => show("sess"));
|
||||
$("tab-model").addEventListener("click", () => show("model"));
|
||||
$("tab-adv").addEventListener("click", () => show("adv"));
|
||||
|
||||
/* WHAT THE ENGINE IS STILL HOLDING BETWEEN TURNS. Polled on its own schedule and only while the
|
||||
view is open: a stored session changes on the scale of its idle thresholds -- tens of seconds at
|
||||
@@ -3507,7 +3687,7 @@ function sessRow(r, hybrid, manyModels) {
|
||||
const reuse = reuseOf(r, hybrid), ret = tr.appendChild(el("td", "l ret"));
|
||||
if (reuse > 0) {
|
||||
ret.appendChild(el("b", null, "reuses " + cnt3(reuse)));
|
||||
ret.appendChild(document.createTextNode(" · prefills " + cnt3(r.tokens - reuse)));
|
||||
ret.appendChild(document.createTextNode(" | prefills " + cnt3(r.tokens - reuse)));
|
||||
} else {
|
||||
ret.textContent = "prefills all " + cnt3(r.tokens);
|
||||
}
|
||||
@@ -3633,8 +3813,8 @@ async function loadControlVector() {
|
||||
$("cvbox").disabled = false;
|
||||
$("cvbox").checked = !!p.default;
|
||||
/* The family the loader validated the file against, then its range and scale. */
|
||||
$("cvsum").textContent = (p.arch ? p.arch + " \u00b7 " : "") + "layers " + p.first +
|
||||
"\u2013" + p.last + " \u00b7 " + p.mode + " \u00b7 scale " + p.scale;
|
||||
$("cvsum").textContent = (p.arch ? p.arch + " | " : "") + "layers " + p.first +
|
||||
"\u2013" + p.last + " | " + p.mode + " | scale " + p.scale;
|
||||
/* A running request keeps the choice it was admitted with, and a refusal already in a
|
||||
* session's context is in the prompt the next turn reads. */
|
||||
$("cvnote").textContent = "New requests only. A session with a refusal already in its " +
|
||||
@@ -3676,31 +3856,107 @@ $("cvbox").addEventListener("change", async (e) => {
|
||||
}
|
||||
});
|
||||
|
||||
/* The poll runs every 100 ms while a request is in flight, so the history sees most finished
|
||||
* requests before they leave /stats, and every 500 ms otherwise. */
|
||||
/* THE POLL CADENCE, SET BY THIS BROWSER. Held in localStorage, not on the server: the cadence is
|
||||
* a property of who is reading, not of what is serving, and browser storage outlives an image swap
|
||||
* or an engine restart that a file beside the engine would not. Two intervals, both editable: the
|
||||
* page fetches at the idle interval while nothing runs and the busy interval while a request is in
|
||||
* flight. Set them equal for one fixed rate. One key holds both, so a change is one write. */
|
||||
const POLL_K = "radiance.poll";
|
||||
const POLL_MIN = 100, POLL_MAX = 5000;
|
||||
const clampMs = (v, d) => Math.min(POLL_MAX, Math.max(POLL_MIN, Math.round(+v || d)));
|
||||
let pollIdleMs = 500, pollBusyMs = 300;
|
||||
try {
|
||||
const raw = lsGet(POLL_K);
|
||||
if (raw) {
|
||||
const p = JSON.parse(raw) || {};
|
||||
if (typeof p.idle === "number") pollIdleMs = clampMs(p.idle, 500);
|
||||
if (typeof p.busy === "number") pollBusyMs = clampMs(p.busy, pollIdleMs);
|
||||
else if (typeof p.ms === "number") { pollIdleMs = clampMs(p.ms, 500); pollBusyMs = pollIdleMs; }
|
||||
}
|
||||
} catch (e) { /* the defaults */ }
|
||||
const pollCadence = (inFlight) => inFlight > 0 ? pollBusyMs : pollIdleMs;
|
||||
function pollSummary() {
|
||||
$("advsum").textContent = pollIdleMs === pollBusyMs ? pollIdleMs + " ms"
|
||||
: pollIdleMs + " ms idle | " + pollBusyMs + " ms busy";
|
||||
}
|
||||
function pollSave() {
|
||||
lsSet(POLL_K, JSON.stringify({ idle: pollIdleMs, busy: pollBusyMs }));
|
||||
pollSummary();
|
||||
}
|
||||
$("pollidle").value = pollIdleMs;
|
||||
$("pollbusy").value = pollBusyMs;
|
||||
pollSummary();
|
||||
$("pollidle").addEventListener("change", (e) => {
|
||||
pollIdleMs = clampMs(e.target.value, 500);
|
||||
e.target.value = pollIdleMs; /* show what was stored, not what was typed */
|
||||
pollSave();
|
||||
schedulePoll(pollIdleMs);
|
||||
});
|
||||
$("pollbusy").addEventListener("change", (e) => {
|
||||
pollBusyMs = clampMs(e.target.value, 300);
|
||||
e.target.value = pollBusyMs;
|
||||
pollSave();
|
||||
schedulePoll(pollIdleMs);
|
||||
});
|
||||
let pollTimer = null;
|
||||
function schedulePoll(ms) { clearTimeout(pollTimer); pollTimer = setTimeout(poll, ms); }
|
||||
/* Past one window's length of not polling, the sampled windows hold only pre-gap samples and the
|
||||
* first poll back would charge the whole span to a single sample. There is nothing to keep, so
|
||||
* the windows and the poll's baseline clear and the page refills from the return, rather than
|
||||
* presenting the pre-gap lane as current. The session's extremes (extAt) and the single-stream
|
||||
* floor (c1hist) survive: a fastest-ever and a floor are properties of the session, not of the
|
||||
* last minute. Checked in poll(), not on the visibility event, so a view switch, a backgrounded
|
||||
* tab and a laptop sleep all take the same path. */
|
||||
const GAP_S = HIST_S; /* the same span the sparklines draw: past it there is nothing to keep */
|
||||
let lastPollAt = 0;
|
||||
function resetWindows() {
|
||||
for (const k in hist) hist[k].length = 0;
|
||||
for (const k in winAt) delete winAt[k];
|
||||
for (const k in accPool) delete accPool[k];
|
||||
moveHist.up.length = 0; moveHist.down.length = 0;
|
||||
prev = null; prevAt = 0; accPrev = null;
|
||||
}
|
||||
async function poll() {
|
||||
/* A background tab watches nothing, and neither does the Model view -- which is static. */
|
||||
if (document.hidden || $("view-dash").hidden) { schedulePoll(500); return; }
|
||||
if (document.hidden || $("view-dash").hidden) { schedulePoll(pollIdleMs); return; }
|
||||
const wall = Date.now();
|
||||
if (lastPollAt && (wall - lastPollAt) / 1000 > GAP_S) resetWindows();
|
||||
lastPollAt = wall;
|
||||
try {
|
||||
const r = await api("stats");
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
const s = await r.json();
|
||||
/* A new engine process is a discontinuity, not a new measurement, and started_at names it.
|
||||
* It is a whole-second clock, so two processes could share one and the clear would be
|
||||
* missed. For that, the replacement would have to start within the same second as the one
|
||||
* the page last read -- and the page can only read it once /stats answers, startup_s after
|
||||
* the old process began (69 s here). A replacement that starts after its predecessor stopped
|
||||
* answering is therefore stamped a later second. The guarantee needs startup_s >= 1 s; a
|
||||
* model that came up inside a second could collide, and the cost would be one stale extreme
|
||||
* carrying a true age.
|
||||
*
|
||||
* uptime_s is NOT a backstop for that case, because it is derived: unix_now() - started_at_,
|
||||
* both whole seconds, so started_at + uptime_s is exactly the wall clock at every poll. A
|
||||
* later poll always reports a larger uptime for the same started_at, so a comparison firing
|
||||
* on a smaller one detects a backward NTP step and nothing else. Checked before update() so
|
||||
* the new run's samples land in fresh windows. */
|
||||
if (lastStart !== null && s.started_at !== lastStart) newEngineRun();
|
||||
lastStart = s.started_at;
|
||||
const now = performance.now();
|
||||
update(s, prevAt ? (now - prevAt) / 1000 : 0);
|
||||
prev = s; prevAt = now;
|
||||
$("view-dash").classList.remove("boot");
|
||||
$("dot").className = "dot";
|
||||
schedulePoll((s.in_flight || 0) > 0 ? 100 : 500);
|
||||
schedulePoll(pollCadence(s.in_flight || 0));
|
||||
} catch (e) {
|
||||
$("dot").className = "dot stale";
|
||||
schedulePoll(500);
|
||||
schedulePoll(pollIdleMs);
|
||||
}
|
||||
}
|
||||
identify();
|
||||
if (location.hash === "#model") show("model");
|
||||
else if (location.hash === "#sessions") show("sess");
|
||||
else if (location.hash === "#advanced") show("adv");
|
||||
/* A server that never answers still gets its frame drawn, rather than an empty page that gives
|
||||
* the reader nothing to tell "starting up" apart from "broken". */
|
||||
setTimeout(() => $("view-dash").classList.remove("boot"), 1500);
|
||||
|
||||
+17
-1
@@ -22,7 +22,8 @@
|
||||
struct RadModelMeta;
|
||||
|
||||
namespace rad {
|
||||
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; }
|
||||
namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket;
|
||||
struct ShapeRequest; struct ShapeGenInfo; }
|
||||
namespace mm { struct Frame; struct Item; }
|
||||
namespace server {
|
||||
|
||||
@@ -212,6 +213,7 @@ struct RequestStat {
|
||||
int32_t slot = -1;
|
||||
double age_s = 0;
|
||||
double ttft_s = -1; /* negative until the first token */
|
||||
double prefill_s = -1; /* first token minus admission; negative until both */
|
||||
double decode_tps = 0;
|
||||
};
|
||||
|
||||
@@ -816,5 +818,19 @@ public:
|
||||
virtual int64_t running() const = 0;
|
||||
};
|
||||
|
||||
/* The shape generator (core/gen/shape_driver.h), for a model that makes a 3-D shape from a
|
||||
* picture: its declared picture, sampler and grid (gen::ShapeGenInfo) and its request queue. The
|
||||
* server prepares the picture (gen::shape_picture), queues the request, and meshes the field the
|
||||
* ticket hands back. */
|
||||
class IShapeGen {
|
||||
public:
|
||||
virtual ~IShapeGen() = default;
|
||||
virtual const gen::ShapeGenInfo& info() const = 0;
|
||||
/* Queue a request; refused at once, with `why`, when it can never run. */
|
||||
virtual int submit(std::unique_ptr<gen::ShapeRequest> r, std::string* why) = 0;
|
||||
virtual int64_t queued() const = 0;
|
||||
virtual int64_t running() const = 0;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
+11
-3
@@ -3379,11 +3379,16 @@ int anthropic_image(const json& block, const std::string& at, json* out, ApiErro
|
||||
* continuation sends only the tail of the conversation), so a field outside these lists is
|
||||
* refused by name rather than ignored. The refusal says "Extra inputs are not permitted", as
|
||||
* Anthropic's does; Claude Code matches those words to retry without a beta field it can
|
||||
* drop. */
|
||||
* drop.
|
||||
*
|
||||
* The last row is not Anthropic's: the chat path's history penalties and min-p, under the chat
|
||||
* path's names, ranges and meaning, for clients that speak only this format to a model whose
|
||||
* card asks for them (Qwen's presence_penalty). */
|
||||
const char* kAnthropicFields[] = {
|
||||
"model", "messages", "system", "max_tokens", "temperature", "top_p", "top_k", "stream",
|
||||
"stop_sequences", "tools", "tool_choice", "thinking", "metadata", "output_config",
|
||||
"output_format", "context_management", "thread",
|
||||
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n",
|
||||
};
|
||||
|
||||
/* Accepted and not acted on: none of them can change the answer here. Capacity and placement
|
||||
@@ -3917,8 +3922,11 @@ int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string
|
||||
if (one) o["parallel_tool_calls"] = false;
|
||||
}
|
||||
|
||||
/* `model` included, since the reply names it back as Anthropic's does. */
|
||||
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" })
|
||||
/* `model` included, since the reply names it back as Anthropic's does. The penalties and
|
||||
* min-p are the chat path's own fields, checked there. */
|
||||
for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream",
|
||||
"min_p", "presence_penalty", "frequency_penalty", "repetition_penalty",
|
||||
"repeat_last_n" })
|
||||
if (b.contains(k)) o[k] = b.at(k);
|
||||
if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences");
|
||||
|
||||
|
||||
@@ -220,6 +220,12 @@ void Server::handle_realtime(const HttpRequest& req, WsConn& ws) {
|
||||
"this model does not transcribe: its architecture plugin states no "
|
||||
"transcription format (rad_arch_audio_format), or it was started without "
|
||||
"its audio encoder", 1008);
|
||||
/* An open turn is cut at the encoder's clip length; without one it would grow for as long as
|
||||
* the client appends audio. */
|
||||
if (deps_.mm->audio_max_samples() <= 0)
|
||||
return refuse("invalid_request_error", "model_not_supported",
|
||||
"this model's audio encoder states no clip length, which a realtime turn "
|
||||
"is cut at", 1008);
|
||||
/* A session holds a connection's thread and one of its own for its whole life, and runs one
|
||||
* pass at a time: more sessions than the engine has sequences would only queue. */
|
||||
const int64_t cap = std::max<int64_t>(1, opt_.max_seqs);
|
||||
|
||||
+63
-3
@@ -134,6 +134,10 @@ void Server::register_routes() {
|
||||
[this](const HttpRequest& q) { return handle_video_delete(q); });
|
||||
router_.get ("/v1/videos/:id/content",
|
||||
[this](const HttpRequest& q) { return handle_video_content(q); });
|
||||
/* Hunyuan3D-2's API server: a shape from a picture. */
|
||||
router_.post("/generate", [this](const HttpRequest& q) { return handle_shape_generate(q); });
|
||||
router_.post("/send", [this](const HttpRequest& q) { return handle_shape_send(q); });
|
||||
router_.get ("/status/:uid", [this](const HttpRequest& q) { return handle_shape_status(q); });
|
||||
router_.post("/v1/audio/transcriptions",
|
||||
[this](const HttpRequest& q) { return handle_transcription(q); });
|
||||
/* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET
|
||||
@@ -374,6 +378,7 @@ void Server::stop() {
|
||||
stopping_.store(true);
|
||||
transport_.stop();
|
||||
stop_videos();
|
||||
stop_shapes();
|
||||
drain_graveyard(2000);
|
||||
}
|
||||
|
||||
@@ -661,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];
|
||||
@@ -1223,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;
|
||||
}
|
||||
@@ -1389,6 +1446,8 @@ std::optional<HttpResponse> Server::refuse_text(const std::string& peer, ApiShap
|
||||
"generates no text"
|
||||
: opt_.video_model ? "this is a video model: it serves /v1/videos and generates "
|
||||
"no text"
|
||||
: opt_.shape_model ? "this is a 3-D shape model: it serves /generate and generates "
|
||||
"no text"
|
||||
: nullptr;
|
||||
if (!why) return std::nullopt;
|
||||
return error_response(err_not_implemented(why), peer, shape);
|
||||
@@ -1675,6 +1734,7 @@ HttpResponse Server::serve_pooled(const HttpRequest& req, bool rerank) {
|
||||
opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images"
|
||||
: opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio"
|
||||
: opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video"
|
||||
: opt_.shape_model ? "/v1/embeddings requires an embedding model; this one makes shapes"
|
||||
: "/v1/embeddings requires an embedding model; this one generates "
|
||||
"text"), req.peer);
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ struct Deps {
|
||||
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
|
||||
IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */
|
||||
IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */
|
||||
IShapeGen* shapes = nullptr; /* absent -> /generate is 501 */
|
||||
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
|
||||
|
||||
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
|
||||
@@ -88,6 +89,10 @@ struct ServerOptions {
|
||||
* many finished videos are kept at most (the oldest go first). */
|
||||
int64_t video_ttl_s = 3600;
|
||||
int64_t max_videos = 32;
|
||||
/* A shape generator (rad_declare_shape_generator) generates no text either: the text
|
||||
* endpoints answer 501 naming /generate. A shape made through /send is kept for /status for
|
||||
* as long as a video, as many at most. */
|
||||
bool shape_model = false;
|
||||
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
|
||||
* (systemone.h), "clef" serves it through the head on the card (clef.h), "laya" through the
|
||||
* Laya plugin's option logits (laya.h), "mica" through Mica's label logits (mica.h); empty
|
||||
@@ -264,6 +269,7 @@ private:
|
||||
struct RealtimeSession; /* realtime.cpp */
|
||||
struct SpeechSession; /* speech_stream.cpp */
|
||||
struct VideoJob; /* videos.cpp */
|
||||
struct ShapeJob; /* shapes.cpp */
|
||||
struct StreamState;
|
||||
|
||||
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
|
||||
@@ -366,6 +372,17 @@ private:
|
||||
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
|
||||
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
|
||||
json capabilities() const;
|
||||
/* ------------------------------------------------------------------ shapes.cpp
|
||||
* Hunyuan3D-2's own API: a shape from a picture, made at once (/generate) or in the
|
||||
* background (/send) and collected (/status/{uid}). */
|
||||
HttpResponse handle_shape_generate(const HttpRequest& req);
|
||||
HttpResponse handle_shape_send(const HttpRequest& req);
|
||||
HttpResponse handle_shape_status(const HttpRequest& req);
|
||||
void shape_work(std::shared_ptr<ShapeJob> j);
|
||||
void sweep_shapes_locked(int64_t now);
|
||||
void stop_shapes();
|
||||
static void shape_caps(json& caps, const IShapeGen* gen);
|
||||
|
||||
/* A video model's capabilities (videos.cpp). */
|
||||
static void video_caps(json& caps, const IVideoGen* gen);
|
||||
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
|
||||
@@ -453,6 +470,9 @@ private:
|
||||
std::mutex videos_m_;
|
||||
std::vector<std::shared_ptr<VideoJob>> videos_;
|
||||
std::vector<std::shared_ptr<VideoJob>> videos_gone_;
|
||||
/* The background shapes (/send), oldest first, and their threads (shapes.cpp). */
|
||||
std::mutex shapes_m_;
|
||||
std::vector<std::shared_ptr<ShapeJob>> shapes_;
|
||||
};
|
||||
|
||||
} /* namespace server */
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
/* shapes.cpp -- Hunyuan3D-2's API over a shape generator (core/gen/shape_driver.h): a 3-D shape
|
||||
* from one picture.
|
||||
*
|
||||
* The routes and fields are the reference's own API server's (hy3dgen's api_server.py), so its
|
||||
* clients (its Blender add-on, scripts written against it) work unchanged:
|
||||
*
|
||||
* POST /generate the shape, made while the request waits, as the file itself;
|
||||
* POST /send the same in the background, answered at once with {"uid"};
|
||||
* GET /status/{uid} {"status": "processing"}, or "completed" with the file as
|
||||
* `model_base64`, or "error" with its `message`.
|
||||
*
|
||||
* The body is JSON: `image`, the picture as base64 (or a data URL), with an alpha channel for a
|
||||
* cut-out object -- the reference removes the background of an opaque picture with rembg, which
|
||||
* this server does not, so an opaque picture is taken whole; `seed` (1234 when absent, as the
|
||||
* reference), `octree_resolution`, `num_inference_steps` and `guidance_scale` (the model's own
|
||||
* when absent), and `type`, the file: glb (the default), obj, ply or stl. `volume_decoding`
|
||||
* "dense" samples every point of the grid instead of refining it coarse to fine. Texturing
|
||||
* (`texture` true) and the reference's text-to-image and re-texturing inputs (`text`, `mesh`)
|
||||
* are refused. The reference's knobs that change nothing here are taken and ignored: `face_count`
|
||||
* (texturing's face budget), `num_chunks` (its decoder's batch) and `mc_algo` "mc"; any other
|
||||
* field is refused by name. A finished background shape is kept for as long as a video, as many
|
||||
* as videos.
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "gen/shape.h"
|
||||
#include "mm/media.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <thread>
|
||||
|
||||
namespace rad {
|
||||
namespace server {
|
||||
|
||||
namespace {
|
||||
|
||||
/* The largest picture decoded, as the image endpoints bound theirs. */
|
||||
constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
|
||||
|
||||
/* A request as the routes read it, and its file's format. */
|
||||
struct ShapeAsk {
|
||||
std::unique_ptr<gen::ShapeRequest> req;
|
||||
std::string type = "glb";
|
||||
};
|
||||
|
||||
int read_ask(const HttpRequest& q, const OaiLimits& lim, const gen::ShapeGenInfo& info,
|
||||
ShapeAsk* out, ApiError* err) {
|
||||
json b;
|
||||
if (parse_request_object(q.body, lim, &b, err) < 0) return RAD_E_INVAL;
|
||||
auto bad = [&](const std::string& p, const std::string& why) {
|
||||
*err = err_bad(p, why);
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
static const char* const kFields[] = { "image", "seed", "octree_resolution",
|
||||
"num_inference_steps", "guidance_scale", "type",
|
||||
"volume_decoding", "texture", "text", "mesh",
|
||||
"face_count", "num_chunks", "mc_algo" };
|
||||
for (auto it = b.begin(); it != b.end(); ++it) {
|
||||
bool known = false;
|
||||
for (const char* k : kFields) known = known || it.key() == k;
|
||||
if (!known)
|
||||
return bad(it.key(), "'" + it.key() + "' is not a field of /generate");
|
||||
}
|
||||
if (b.contains("mc_algo") && !b["mc_algo"].is_null() &&
|
||||
!(b["mc_algo"].is_string() && b["mc_algo"].get<std::string>() == "mc")) {
|
||||
*err = err_unsupported("mc_algo", "the surface is marching cubes ('mc'); differentiable "
|
||||
"marching cubes ('dmc') is not served");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (const char* k : { "text", "mesh" })
|
||||
if (b.contains(k) && !b[k].is_null()) {
|
||||
*err = err_unsupported(k, std::string("this server makes a shape from a picture; '") +
|
||||
k + "' (the reference's text-to-image and re-texturing "
|
||||
"inputs) is not served");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (b.contains("texture") && b["texture"].is_boolean() && b["texture"].get<bool>()) {
|
||||
*err = err_unsupported("texture", "texturing (Hunyuan3D-Paint) is not served: this "
|
||||
"server makes the untextured shape");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!b.contains("image") || !b["image"].is_string() || b["image"].get<std::string>().empty())
|
||||
return bad("image", "'image' must be the picture as base64");
|
||||
std::string img = b["image"].get<std::string>();
|
||||
if (img.rfind("data:", 0) == 0) {
|
||||
const size_t comma = img.find(',');
|
||||
if (comma == std::string::npos || img.compare(comma - 7, 7, ";base64") != 0)
|
||||
return bad("image", "a data URL must be base64 ('data:<type>;base64,...')");
|
||||
img = img.substr(comma + 1);
|
||||
}
|
||||
std::vector<uint8_t> bytes;
|
||||
if (!base64_decode(img, &bytes) || bytes.empty())
|
||||
return bad("image", "'image' is not valid base64");
|
||||
mm::FrameRGBA f;
|
||||
std::string why;
|
||||
if (mm::decode_image_rgba(bytes.data(), bytes.size(), kMaxSourcePixels, &f, &why) < 0)
|
||||
return bad("image", "the picture could not be decoded: " + why);
|
||||
|
||||
auto r = std::make_unique<gen::ShapeRequest>();
|
||||
if (gen::shape_picture(info, f, &r->patches, &why) < 0) return bad("image", why);
|
||||
auto int_field = [&](const char* k, int64_t lo, int64_t hi, int32_t* v) {
|
||||
if (!b.contains(k) || b[k].is_null()) return true;
|
||||
if (!b[k].is_number_integer() || b[k].get<int64_t>() < lo || b[k].get<int64_t>() > hi) {
|
||||
bad(k, std::string("'") + k + "' must be an integer " + std::to_string(lo) + ".." +
|
||||
std::to_string(hi));
|
||||
return false;
|
||||
}
|
||||
*v = (int32_t)b[k].get<int64_t>();
|
||||
return true;
|
||||
};
|
||||
if (!int_field("num_inference_steps", 2, info.max_steps, &r->steps) ||
|
||||
!int_field("octree_resolution", info.min_resolution, info.max_resolution,
|
||||
&r->resolution))
|
||||
return RAD_E_INVAL;
|
||||
if (b.contains("guidance_scale") && !b["guidance_scale"].is_null()) {
|
||||
if (!b["guidance_scale"].is_number() || !(b["guidance_scale"].get<double>() >= 0.0) ||
|
||||
!std::isfinite(b["guidance_scale"].get<double>()))
|
||||
return bad("guidance_scale", "'guidance_scale' must be a finite number, not negative");
|
||||
r->guidance = b["guidance_scale"].get<double>();
|
||||
}
|
||||
r->seed = 1234;
|
||||
if (b.contains("seed") && !b["seed"].is_null()) {
|
||||
if (!b["seed"].is_number_integer())
|
||||
return bad("seed", "'seed' must be an integer");
|
||||
r->seed = b["seed"].is_number_unsigned() ? b["seed"].get<uint64_t>()
|
||||
: (uint64_t)b["seed"].get<int64_t>();
|
||||
}
|
||||
if (b.contains("volume_decoding") && !b["volume_decoding"].is_null()) {
|
||||
const std::string v = b["volume_decoding"].is_string()
|
||||
? b["volume_decoding"].get<std::string>() : "";
|
||||
if (v != "hierarchical" && v != "dense")
|
||||
return bad("volume_decoding", "'volume_decoding' is hierarchical or dense");
|
||||
r->dense = v == "dense";
|
||||
}
|
||||
if (b.contains("type") && !b["type"].is_null()) {
|
||||
if (!b["type"].is_string()) return bad("type", "'type' is glb, obj, ply or stl");
|
||||
out->type = b["type"].get<std::string>();
|
||||
if (out->type != "glb" && out->type != "obj" && out->type != "ply" && out->type != "stl")
|
||||
return bad("type", "type '" + out->type + "' is not one this server writes: glb, obj, "
|
||||
"ply or stl");
|
||||
}
|
||||
r->ticket = std::make_shared<gen::ShapeTicket>();
|
||||
out->req = std::move(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The ticket's field as a mesh file, once the driver is done with it. */
|
||||
int finish_file(gen::ShapeTicket& t, const gen::ShapeGenInfo& info, const std::string& type,
|
||||
std::string* file, std::string* mime, std::string* why) {
|
||||
if (t.status() < 0) {
|
||||
*why = t.why();
|
||||
return t.status();
|
||||
}
|
||||
int32_t r = 0;
|
||||
std::vector<float> field = t.take_field(&r);
|
||||
gen::ShapeMesh mesh;
|
||||
gen::shape_mesh(field, r, info.bounds, info.level, &mesh);
|
||||
std::vector<float>().swap(field);
|
||||
if (mesh.f.empty()) {
|
||||
*why = "the model's field crosses the surface level nowhere in the grid: the picture made "
|
||||
"no shape";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return gen::shape_export(mesh, type, file, mime, why);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
struct Server::ShapeJob {
|
||||
std::string uid, type;
|
||||
int64_t created_at = 0, done_at = 0;
|
||||
std::shared_ptr<gen::ShapeTicket> ticket;
|
||||
std::thread worker;
|
||||
/* Under Server::shapes_m_ from here on. */
|
||||
bool finished = false, failed = false;
|
||||
std::string file, message;
|
||||
};
|
||||
|
||||
void Server::shape_caps(json& caps, const IShapeGen* gen) {
|
||||
const gen::ShapeGenInfo& info = gen->info();
|
||||
caps["shape_max_steps"] = info.max_steps;
|
||||
caps["shape_resolutions"] = { info.min_resolution, info.max_resolution };
|
||||
caps["shape_formats"] = json::array({ "glb", "obj", "ply", "stl" });
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_generate(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/generate requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
ShapeAsk a;
|
||||
ApiError err;
|
||||
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
|
||||
std::shared_ptr<gen::ShapeTicket> t = a.req->ticket;
|
||||
std::string why;
|
||||
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
|
||||
req.peer);
|
||||
while (!t->wait(500))
|
||||
if (stopping_.load()) {
|
||||
t->cancel.store(true);
|
||||
return error_response(err_overloaded("the server is stopping"), req.peer);
|
||||
}
|
||||
std::string file, mime;
|
||||
if (const int st = finish_file(*t, info, a.type, &file, &mime, &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_internal(why),
|
||||
req.peer);
|
||||
HttpResponse res;
|
||||
res.content_type = mime;
|
||||
res.body = std::move(file);
|
||||
return res;
|
||||
}
|
||||
|
||||
void Server::shape_work(std::shared_ptr<ShapeJob> j) {
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
gen::ShapeTicket& t = *j->ticket;
|
||||
while (!t.wait(500))
|
||||
if (stopping_.load()) {
|
||||
t.cancel.store(true);
|
||||
t.wait(60000);
|
||||
break;
|
||||
}
|
||||
std::string file, mime, why;
|
||||
const int st = t.finished() ? finish_file(t, info, j->type, &file, &mime, &why)
|
||||
: RAD_E_CANCELLED;
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
j->finished = true;
|
||||
j->done_at = unix_now();
|
||||
if (st < 0) {
|
||||
j->failed = true;
|
||||
j->message = why.empty() ? std::string(rad_strerror(st)) : why;
|
||||
} else {
|
||||
j->file = std::move(file);
|
||||
}
|
||||
}
|
||||
|
||||
void Server::sweep_shapes_locked(int64_t now) {
|
||||
for (size_t i = 0; i < shapes_.size();) {
|
||||
ShapeJob& j = *shapes_[i];
|
||||
const bool expired = j.finished && now - j.done_at > opt_.video_ttl_s;
|
||||
if (!expired) { ++i; continue; }
|
||||
if (j.worker.joinable()) j.worker.join();
|
||||
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
|
||||
}
|
||||
/* Past the cap the oldest finished shapes go first. */
|
||||
size_t done = 0;
|
||||
for (const auto& j : shapes_) done += j->finished;
|
||||
const size_t cap = (size_t)std::max<int64_t>(opt_.max_videos, 1);
|
||||
for (size_t i = 0; done > cap && i < shapes_.size();) {
|
||||
if (!shapes_[i]->finished) { ++i; continue; }
|
||||
if (shapes_[i]->worker.joinable()) shapes_[i]->worker.join();
|
||||
shapes_.erase(shapes_.begin() + (std::ptrdiff_t)i);
|
||||
--done;
|
||||
}
|
||||
}
|
||||
|
||||
void Server::stop_shapes() {
|
||||
std::vector<std::shared_ptr<ShapeJob>> all;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
all = shapes_;
|
||||
}
|
||||
for (auto& j : all) j->ticket->cancel.store(true);
|
||||
for (auto& j : all)
|
||||
if (j->worker.joinable()) j->worker.join();
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_send(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/send requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const gen::ShapeGenInfo& info = deps_.shapes->info();
|
||||
ShapeAsk a;
|
||||
ApiError err;
|
||||
if (read_ask(req, lim_, info, &a, &err) < 0) return error_response(err, req.peer);
|
||||
auto j = std::make_shared<ShapeJob>();
|
||||
j->uid = random_id("shape_");
|
||||
j->type = a.type;
|
||||
j->created_at = unix_now();
|
||||
j->ticket = a.req->ticket;
|
||||
std::string why;
|
||||
if (const int st = deps_.shapes->submit(std::move(a.req), &why); st < 0)
|
||||
return error_response(st == RAD_E_INVAL ? err_bad("image", why) : err_overloaded(why),
|
||||
req.peer);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
sweep_shapes_locked(unix_now());
|
||||
shapes_.push_back(j);
|
||||
}
|
||||
j->worker = std::thread([this, j] { shape_work(j); });
|
||||
json o;
|
||||
o["uid"] = j->uid;
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_shape_status(const HttpRequest& req) {
|
||||
if (!deps_.shapes)
|
||||
return error_response(err_not_implemented(
|
||||
"/status requires a 3-D shape model; this one does not make shapes"), req.peer);
|
||||
const std::string uid = req.param("uid");
|
||||
std::lock_guard<std::mutex> lk(shapes_m_);
|
||||
sweep_shapes_locked(unix_now());
|
||||
for (const auto& j : shapes_) {
|
||||
if (j->uid != uid) continue;
|
||||
json o;
|
||||
if (!j->finished) {
|
||||
o["status"] = "processing";
|
||||
int32_t steps = 0, points = 0;
|
||||
j->ticket->progress_of(&steps, &points);
|
||||
o["steps_done"] = steps;
|
||||
o["steps"] = j->ticket->steps;
|
||||
} else if (j->failed) {
|
||||
o["status"] = "error";
|
||||
o["message"] = j->message;
|
||||
} else {
|
||||
o["status"] = "completed";
|
||||
o["type"] = j->type;
|
||||
o["model_base64"] = base64_encode(j->file.data(), j->file.size());
|
||||
}
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
ApiError e = err_bad("uid", "no shape '" + uid + "'; it may have expired");
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -535,7 +535,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
|
||||
canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H);
|
||||
}
|
||||
if (W % info.size_multiple || H % info.size_multiple || W < info.min_side ||
|
||||
H < info.min_side || W * H > info.max_area ||
|
||||
H < info.min_side || W > info.max_area || H > info.max_area || W * H > info.max_area ||
|
||||
std::max(W, H) > info.max_aspect * std::min(W, H)) {
|
||||
int64_t sw = 0, sh = 0;
|
||||
canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh);
|
||||
@@ -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);
|
||||
|
||||
@@ -320,6 +320,12 @@ int parse_tokenizer_json(const char* path, VocabBuild& out);
|
||||
/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
|
||||
int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
|
||||
|
||||
/* The vocabulary of a model that reads no text (container metadata `radiance.text` = none: a
|
||||
* picture-to-shape generator): one control token, which no request reaches, since such a program
|
||||
* serves no text endpoint. rad-convert bakes it and the engine builds it for a checkpoint. */
|
||||
void vocab_textless(VocabBuild& out);
|
||||
inline bool meta_textless(const char* v) { return v && std::string_view(v) == "none"; }
|
||||
|
||||
/* Read a standalone chat template file into out.chat_template, trailing newlines stripped.
|
||||
* A release that ships no template (DeepSeek's does not) needs one from elsewhere; the caller
|
||||
* passes the file. An unreadable or empty file is an error, never a silent skip. Returns
|
||||
|
||||
@@ -892,6 +892,14 @@ const PreEntry k_pre[] = {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void vocab_textless(VocabBuild& out) {
|
||||
out = VocabBuild{};
|
||||
out.kind = RAD_TOK_BPE;
|
||||
out.tokens = { "<|no-text|>" };
|
||||
out.types = { RAD_TT_CONTROL };
|
||||
out.source = "none: the model reads no text";
|
||||
}
|
||||
|
||||
int vocab_from_gguf(const GgufFile& g, VocabBuild& out) {
|
||||
out = VocabBuild{};
|
||||
out.source = g.path();
|
||||
@@ -1107,7 +1115,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
|
||||
* in, so the caller cannot pass a mismatched one. */
|
||||
if (file_bytes < sizeof(RadFileHeader)) return RAD_E_FORMAT;
|
||||
const RadFileHeader* fh = reinterpret_cast<const RadFileHeader*>(base);
|
||||
if (fh->str_off + fh->str_bytes > file_bytes) return RAD_E_FORMAT;
|
||||
if (fh->str_off > file_bytes || fh->str_bytes > file_bytes - fh->str_off)
|
||||
return RAD_E_FORMAT;
|
||||
strs = reinterpret_cast<const char*>(base + fh->str_off);
|
||||
str_bytes = fh->str_bytes;
|
||||
}
|
||||
@@ -1128,7 +1137,8 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
|
||||
out.ignore_merges = (h->flags & RAD_VOCAB_IGNORE_MERGES) != 0;
|
||||
out.chat_template = S(h->chat_template);
|
||||
|
||||
if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)))
|
||||
if ((h->n_tokens && !h->tok_text_off) ||
|
||||
!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)))
|
||||
return RAD_E_FORMAT;
|
||||
const rad_stroff* toff = reinterpret_cast<const rad_stroff*>(base + h->tok_text_off);
|
||||
out.tokens.resize(h->n_tokens);
|
||||
|
||||
@@ -266,6 +266,12 @@ private:
|
||||
std::vector<size_t> off_; /* byte offset of each codepoint */
|
||||
size_t i_ = 0;
|
||||
size_t start_ = 0; /* where the construct being parsed began */
|
||||
/* Groups open around the construct being parsed: a possessive quantifier is taken only at
|
||||
* depth 0, where what follows its concatenation is the end of the match. */
|
||||
int depth_ = 0;
|
||||
/* Possessive repetitions parse_quant accepted, read as greedy; parse_concat checks that the
|
||||
* rest of their concatenation cannot take back what they consumed. */
|
||||
std::vector<int> possessive_;
|
||||
|
||||
bool decode_pattern() {
|
||||
const uint8_t* p = (const uint8_t*)pat_.data();
|
||||
@@ -382,6 +388,7 @@ private:
|
||||
if (a < 0) return -1;
|
||||
items.push_back(a);
|
||||
}
|
||||
if (!possessive_tails_ok(items)) return -1;
|
||||
if (items.empty()) return add(Node{});
|
||||
if (items.size() == 1) return items[0];
|
||||
Node n; n.kind = Node::CAT; n.kids = std::move(items);
|
||||
@@ -448,11 +455,17 @@ private:
|
||||
else if (!interval_at(i_, &mn, &mx, &len)) return atom;
|
||||
const bool brace = c == '{';
|
||||
i_ += len;
|
||||
bool greedy = true;
|
||||
bool greedy = true, possessive = false;
|
||||
if (!at_end() && peek() == '?') { greedy = false; ++i_; }
|
||||
else if (!at_end() && peek() == '+') {
|
||||
return failn(brace ? "a quantifier applied to a quantifier (Ruby reads '{n,m}+' as nested repetition)"
|
||||
: "a possessive quantifier");
|
||||
if (brace)
|
||||
return failn("a quantifier applied to a quantifier (Ruby reads '{n,m}+' as nested repetition)");
|
||||
/* A possessive repetition of one class at the top level is read as greedy, which
|
||||
* parse_concat proves gives the same matches; anything else has no DFA form. */
|
||||
if (depth_ > 0 || nodes[atom].kind != Node::SET)
|
||||
return failn("a possessive quantifier");
|
||||
possessive = true;
|
||||
++i_;
|
||||
}
|
||||
if (is_quantifier_at(i_)) return failn("a quantifier applied to a quantifier");
|
||||
if (nodes[atom].kind == Node::ASSERT) return failn("a quantifier on an assertion");
|
||||
@@ -461,7 +474,35 @@ private:
|
||||
if (mx < 0 && nullable(nodes, atom))
|
||||
return failn("unbounded repetition of an expression that can match empty");
|
||||
Node n; n.kind = Node::REP; n.min = mn; n.max = mx; n.greedy = greedy; n.kids = { atom };
|
||||
return add(n);
|
||||
const int r = add(n);
|
||||
if (possessive) possessive_.push_back(r);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* A possessive repetition of the class S never gives back, a greedy one gives back only when
|
||||
* the rest of the match fails after its longest run. At the top level that rest is the tail of
|
||||
* its concatenation and then the end of the match. When the tail is classes and repetitions of
|
||||
* classes, none of which can take a codepoint of S, a shorter run leaves the tail facing a
|
||||
* codepoint of S it cannot take, so no shorter run matches where the longest did not, and the
|
||||
* greedy reading reports exactly the possessive matches (Ling-3.0's `[^\r\n\p{L}\p{N}]?+\p{L}+`
|
||||
* and ` ?[^\s\p{L}\p{N}]++[\r\n]*`). Any other tail is refused. */
|
||||
bool possessive_tails_ok(const std::vector<int>& items) {
|
||||
for (size_t k = 0; k < items.size(); ++k) {
|
||||
if (std::find(possessive_.begin(), possessive_.end(), items[k]) == possessive_.end())
|
||||
continue;
|
||||
const CpSet& own = sets[nodes[nodes[items[k]].kids[0]].set];
|
||||
CpSet tail;
|
||||
for (size_t j = k + 1; j < items.size(); ++j) {
|
||||
const Node& n = nodes[items[j]];
|
||||
const Node& m = n.kind == Node::REP ? nodes[n.kids[0]] : n;
|
||||
if (m.kind != Node::SET)
|
||||
return fail("a possessive quantifier followed by something other than classes");
|
||||
tail = set_union(tail, sets[m.set]);
|
||||
}
|
||||
if (!set_intersect(own, tail).empty())
|
||||
return fail("a possessive quantifier whose class the rest of the match can take");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int literal(uint32_t c, const Flags& f) {
|
||||
@@ -494,6 +535,7 @@ private:
|
||||
|
||||
int parse_group(const Flags& outer) {
|
||||
/* `(` already consumed. */
|
||||
struct Depth { int& d; explicit Depth(int& x) : d(x) { ++d; } ~Depth() { --d; } } depth(depth_);
|
||||
Flags f = outer;
|
||||
if (peek() != '?') {
|
||||
const int r = parse_alt(f);
|
||||
|
||||
@@ -18,7 +18,9 @@
|
||||
* the `onig` crate does.
|
||||
*
|
||||
* Anything else is refused at compile time with the construct named: backreferences, atomic
|
||||
* groups and possessive quantifiers, lookaround wider than one codepoint, unbounded repetition of
|
||||
* groups, possessive quantifiers except where the greedy reading provably matches the same (one
|
||||
* class at the top level, followed only by classes it shares no codepoint with, as in Ling-3.0's
|
||||
* pattern), lookaround wider than one codepoint, unbounded repetition of
|
||||
* something that can match empty, `(?i)` over a character that folds to several (U+00DF vs "ss"),
|
||||
* and properties the tables do not carry. There is no fallback matcher; a pattern that does not
|
||||
* compile fails the vocabulary load.
|
||||
|
||||
Reference in new issue
Block a user