radiance 1.9.0

New models:
- LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first
  frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2
  latent upsampler
- Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up
  to ten reference pictures, on one card
- GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze)
- Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81)

Engine:
- --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81)
- the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168)
- eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes)
- the dashboard shows the single-stream decode floor and its most recent window (Memoria)

Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses
namespaces (#119), system messages merged when a template refuses several (#137), a prefill
continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns
read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state.
Plugin ABI 24.
This commit is contained in:
Deadcode committed 2026-10-19 21:58:07 +02:00
1 parent 778cbf315e
commit 685ec5bd85
136 files changed
+18917 -3821

No files matched your search

+134 -21
View File
@@ -14,6 +14,7 @@
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <mutex>
@@ -940,7 +941,8 @@ int Builder::decl_name_map(const RadNameMap* m) {
return RAD_E_INVAL;
}
if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM &&
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) {
m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA &&
m->mode != RAD_MAP_TAP) {
err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode);
return RAD_E_INVAL;
}
@@ -951,9 +953,9 @@ int Builder::decl_name_map(const RadNameMap* m) {
: "the magnitude and the direction", m->n_src);
return RAD_E_INVAL;
}
if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d",
m->declared, m->n_src);
if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) {
err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared,
m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src);
return RAD_E_INVAL;
}
@@ -1192,16 +1194,27 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
: prog_.is_audio_generator() ? "an audio generator" : "a video generator");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) {
err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm,
(int)d->layout);
return RAD_E_INVAL;
}
const bool joint = d->layout == RAD_GEN_LAYOUT_JOINT_STEP;
auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); };
if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and "
"{prompt}, and tmpl_image {image}, where the picture's tokens go", nm);
if (joint ? !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}")
: !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text and tmpl_edit need {prompt}, and "
"with the pictures in the prompt tmpl_edit needs {images} and tmpl_image "
"{image}, where the picture's tokens go", nm);
return RAD_E_INVAL;
}
if (joint && (d->cond_rows <= 0 || !(d->rope_hw_scale > 0) || d->pad_multiple < 0 ||
(d->pad_multiple > 0 && d->pad_token < 0))) {
err(RAD_E_INVAL, "declare_generator '%s': the joint layout needs cond_rows, a positive "
"rope_hw_scale and, with padding, a pad token (cond_rows %lld, scale %g, "
"pad %d to a multiple of %d)", nm, (long long)d->cond_rows,
d->rope_hw_scale, (int)d->pad_token, (int)d->pad_multiple);
return RAD_E_INVAL;
}
if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 ||
@@ -1220,7 +1233,8 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
return RAD_E_INVAL;
}
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) ||
(d->n_sigmas == 0 && d->default_steps <= 0) ||
!(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) ||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
(!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) {
err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld "
@@ -1255,17 +1269,19 @@ int Builder::declare_generator(const RadGeneratorDecl* d) {
g.name = nm;
g.tmpl_text = d->tmpl_text;
g.tmpl_edit = d->tmpl_edit;
g.tmpl_image = d->tmpl_image;
g.tmpl_image = d->tmpl_image ? d->tmpl_image : "";
g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : "";
g.drop_prefix = d->drop_prefix ? d->drop_prefix : "";
g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
g.has_default_negative = d->default_negative != nullptr;
g.default_negative = d->default_negative ? d->default_negative : "";
g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
prog_.generator = *d;
/* The Program is moved after declare, which would invalidate pointers into gen_str, so the
* decl's string fields are cleared; read them only through gen_str. */
RadGeneratorDecl& c = prog_.generator;
c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
c.drop_prefix = c.tmpl_transparent = nullptr;
c.drop_prefix = c.tmpl_transparent = c.default_negative = nullptr;
c.sigmas = nullptr;
return RAD_OK;
}
@@ -1461,22 +1477,78 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
(long long)d->audio_latent_channels);
return RAD_E_INVAL;
}
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) ||
!(d->shift_audio > 0.0) || d->max_lanes <= 0) {
/* Form 1 (LTX-2's FlowMatchEulerDiscrete) steps both modalities the same sigmas and reads
* no per-modality shift. */
const bool shifts = d->sched_kind == 1 || (d->shift_video > 0.0 && d->shift_audio > 0.0);
if (d->default_steps <= 0 || d->max_steps < d->default_steps || !shifts || d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by "
"default, %lld at most, shifts %g and %g, %lld lanes)", nm,
(long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio,
(long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid "
"points, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps,
/* Form 0 counts grid points, form 1 evaluations. */
const int64_t rung_steps = d->sched_kind == 1 ? d->n_rungs : d->n_rungs + 1;
if (d->sched_kind < 0 || d->sched_kind > 1 || d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) ||
(d->n_rungs > 0 && (d->default_steps != rung_steps || d->max_steps != rung_steps))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %lld "
"steps, which default_steps and max_steps must both be (%lld, %lld)", nm,
(int)d->n_rungs, (long long)rung_steps, (long long)d->default_steps,
(long long)d->max_steps);
return RAD_E_INVAL;
}
if (d->sched_kind == 1 && d->dyn_shift &&
(!(d->max_seq > d->base_seq) || !std::isfinite(d->base_shift) ||
!std::isfinite(d->max_shift))) {
err(RAD_E_INVAL, "declare_video_generator '%s': the dynamic shift runs from %lld tokens "
"(%g) to %lld (%g); the second length must be the larger", nm,
(long long)d->base_seq, d->base_shift, (long long)d->max_seq, d->max_shift);
return RAD_E_INVAL;
}
if (!(d->shift_terminal >= 0.0 && d->shift_terminal < 1.0)) {
err(RAD_E_INVAL, "declare_video_generator '%s': shift_terminal %g is outside [0, 1)", nm,
d->shift_terminal);
return RAD_E_INVAL;
}
if (d->n_refine_rungs < 0 || (d->n_refine_rungs > 0 && (!d->refine_rungs ||
d->sched_kind != 1 || d->n_rungs == 0 || !(d->upscale_max > 1.0)))) {
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rungs need a trained schedule of "
"form 1 and a latent upscaler", nm);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_refine_rungs; ++i)
if (!(d->refine_rungs[i] > 0.0 && d->refine_rungs[i] <= 1.0) ||
(i > 0 && !(d->refine_rungs[i] < d->refine_rungs[i - 1]))) {
err(RAD_E_INVAL, "declare_video_generator '%s': refinement rung %d (%g) is outside "
"(0, 1] or not below the one before it", nm, i, d->refine_rungs[i]);
return RAD_E_INVAL;
}
if (d->step_text_rows < 0 || d->step_text_rows > d->max_text * 64 || d->image_crf < 0 ||
d->image_crf > 51 || (d->image_cond != 0 && d->image_cond != 1) ||
(d->guidance != 0 && d->guidance != 1)) {
err(RAD_E_INVAL, "declare_video_generator '%s': step_text_rows %lld, image_cond %d, "
"image_crf %d (0..51) or guidance %d is out of range", nm,
(long long)d->step_text_rows, (int)d->image_cond, (int)d->image_crf, (int)d->guidance);
return RAD_E_INVAL;
}
if (d->text_left_pad < 0 || (d->text_left_pad > 0 && d->text_left_pad < d->max_text) ||
d->audio_streams < 0 ||
(d->upscale_exact && (!(d->upscale_max > 1.0) ||
d->upscale_max != std::floor(d->upscale_max)))) {
err(RAD_E_INVAL, "declare_video_generator '%s': text_left_pad %lld must hold the longest "
"prompt (%lld), audio_streams %d may not be negative, and an exact "
"upscaler's factor (%g) is a whole number above 1", nm,
(long long)d->text_left_pad, (long long)d->max_text, (int)d->audio_streams,
d->upscale_max);
return RAD_E_INVAL;
}
if (d->guidance)
for (int i = 0; i < 8; ++i)
if (!std::isfinite(d->guidance_default[i]) || d->guidance_default[i] < 0.0) {
err(RAD_E_INVAL, "declare_video_generator '%s': default guidance term %d (%g) must "
"be finite and not negative", nm, i, d->guidance_default[i]);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_rungs; ++i)
if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) ||
(i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) {
@@ -1486,9 +1558,13 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
}
/* An upscaler needs a schedule it can split: one evaluation at the small size at least, and
* `upscale_refine` of them after it by default. */
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs : d->default_steps - 1;
const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs
: d->sched_kind == 1 ? d->default_steps : d->default_steps - 1;
const bool own_refine = d->n_refine_rungs > 0;
if (d->upscale_max != 0.0 &&
(!(d->upscale_max > 1.0) || d->upscale_refine < 1 || d->upscale_refine >= def_evals)) {
(!(d->upscale_max > 1.0) ||
(!own_refine && (d->upscale_refine < 1 || d->upscale_refine >= def_evals)) ||
(own_refine && d->upscale_refine != d->n_refine_rungs))) {
err(RAD_E_INVAL, "declare_video_generator '%s': a latent upscaler of factor %g at most, "
"refining %d evaluations of %lld by default; the factor must be above 1 "
"and the refinement 1 to %lld", nm, d->upscale_max, (int)d->upscale_refine,
@@ -1521,15 +1597,52 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) {
if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") ||
!buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out"))
return RAD_E_INVAL;
if (d->duration_out != RAD_NULL_HANDLE) {
if (!buf_ok(d->duration_out, RAD_F32, 1, "duration_out")) return RAD_E_INVAL;
if (!(d->duration_min > 0.0 && d->duration_max > d->duration_min) ||
!std::isfinite(d->duration_max) ||
(d->duration_dtype != RAD_F32 && d->duration_dtype != RAD_BF16)) {
err(RAD_E_INVAL, "declare_video_generator '%s': a length head clamps to "
"[%g, %g] seconds in dtype %u; the bounds must be positive, finite "
"and in order, the dtype f32 or bf16", nm, d->duration_min,
d->duration_max, (unsigned)d->duration_dtype);
return RAD_E_INVAL;
}
}
prog_.vgen_str.name = nm;
prog_.vgen_str.tmpl = d->tmpl;
prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs);
prog_.vgen_str.refine_rungs.assign(d->refine_rungs, d->refine_rungs + d->n_refine_rungs);
prog_.vgen_str.default_negative = d->default_negative ? d->default_negative : "";
prog_.vgen_str.decoders.clear();
prog_.vgen_str.decoder_max_area.clear();
for (const char* s = d->decoders; s && *s;) {
while (*s == ' ') ++s;
const char* e = s;
while (*e && *e != ' ') ++e;
if (e > s) prog_.vgen_str.decoders.emplace_back(s, e);
s = e;
}
for (size_t i = 0; i < prog_.vgen_str.decoders.size(); ++i) {
const int64_t a = d->decoder_max_area ? d->decoder_max_area[i] : 0;
if (a < 0 || a > d->max_area) {
err(RAD_E_INVAL, "declare_video_generator '%s': decoder '%s' makes frames of %lld pixels "
"at most, outside 0..max_area", nm,
prog_.vgen_str.decoders[i].c_str(), (long long)a);
return RAD_E_INVAL;
}
prog_.vgen_str.decoder_max_area.push_back(a > 0 ? a : d->max_area);
}
prog_.video_gen = *d;
/* As for the other generators: the Program is moved after declare; strings and the rungs live
* in vgen_str. */
prog_.video_gen.name = nullptr;
prog_.video_gen.tmpl = nullptr;
prog_.video_gen.rungs = nullptr;
prog_.video_gen.refine_rungs = nullptr;
prog_.video_gen.default_negative = nullptr;
prog_.video_gen.decoders = nullptr;
prog_.video_gen.decoder_max_area = nullptr;
return RAD_OK;
}
+1 -1
View File
@@ -73,7 +73,7 @@ static const Flag g_flags[] = {
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
{ "--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" },
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
" pins its host memory at startup (default 4096)" },
+28 -2
View File
@@ -8,6 +8,7 @@
#include "gen/video_driver.h"
#include "kld.h"
#include "mm/processor.h"
#include "mm/media.h"
#include "build/startup.h"
#include "build/rad_build.h"
@@ -2375,8 +2376,11 @@ int Engine::run_server() {
in.size_multiple = gd.size_multiple;
in.pixel_channels = gd.pixel_channels;
in.max_tokens = gd.max_tokens;
/* Edits need the conditioning network to read pictures. */
in.max_refs = mm_proc ? gd.max_refs : 0;
/* Edits need the conditioning network to read pictures, unless only the generator's
* own encoder reads them. */
in.refs_encoder_only = gd.layout == RAD_GEN_LAYOUT_JOINT_STEP;
in.max_refs = mm_proc || in.refs_encoder_only ? gd.max_refs : 0;
in.ref_shrink_only = gd.ref_shrink_only != 0;
in.ref_area = gd.ref_area;
in.default_width = gd.default_width;
in.default_height = gd.default_height;
@@ -2386,6 +2390,9 @@ int Engine::run_server() {
in.fixed_schedule = !pg.gen_str.sigmas.empty();
in.fixed_steps = (int64_t)pg.gen_str.sigmas.size();
in.default_cfg = gd.default_cfg;
in.cfg_original = gd.cfg_original != 0;
in.has_default_negative = pg.gen_str.has_default_negative;
in.default_negative = pg.gen_str.default_negative;
image_bridge.drv = img_gen_;
image_bridge.proc = mm_proc.get();
d.images = &image_bridge;
@@ -2497,6 +2504,19 @@ int Engine::run_server() {
in.fixed_steps = vd.n_rungs > 0;
in.upscale_max = vd.upscale_max;
in.upscale_refine = vd.upscale_refine;
in.step_evals = vd.sched_kind == 1;
in.guidance = vd.guidance != 0;
for (int i = 0; i < 8; ++i) in.guidance_default[i] = vd.guidance_default[i];
in.default_negative = pg.vgen_str.default_negative;
in.image_cond = vd.image_cond != 0;
in.image_crf = vd.image_crf;
in.length_head = vd.duration_out != RAD_NULL_HANDLE;
in.decoders = pg.vgen_str.decoders;
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);
in.max_lanes = vd.max_lanes;
video_bridge.drv = vid_gen_;
d.videos = &video_bridge;
@@ -2555,6 +2575,12 @@ int Engine::run_server() {
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
mapped.c_str());
/* What a request naming no effort gets, which a client cannot see: Qwen3.8's template
* renders xhigh into a system prompt (#113). */
const std::string& dflt = srv.template_default_effort();
if (cfg_.reasoning_effort.empty() && !dflt.empty())
RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the "
"template's own default (--reasoning-effort sets another)", dflt.c_str());
} else if (!mapped.empty()) {
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
}
+4
View File
@@ -162,6 +162,10 @@ static bool dump_at(Ctx& ctx, int step, const char* phase, const std::string& na
return true;
}
/* A buffer is read where it lives after the pass, and the arena shares a transient's bytes with
* every buffer whose lifetime does not overlap it. So a dump after a drafter's context pass shows
* a tap buffer (dflash_src) already overwritten by a later one in that pass (df_c), and only the
* step loop's dump, after the trunk, shows the taps as written. A PERSIST buffer is never shared. */
void dump_buffers(Ctx& ctx, int step, const char* phase) {
if ((int)log_level() < (int)Log::Trace) return;
static const char* const names = std::getenv("RADIANCE_DUMP_BUF");
+54 -18
View File
@@ -56,6 +56,25 @@ void MetaOwn::finish() {
* path, and typed fields are read from `text_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
* vocoder's per-resnet dilations, [[1, 3, 5], [1, 3, 5]], read as "1 3 5 1 3 5"); false for an
* array holding an object or a null. */
static bool join_scalars(const nlohmann::json& v, std::string* s) {
for (const auto& e : v) {
if (e.is_array()) {
if (!join_scalars(e, s)) return false;
continue;
}
if (!s->empty()) *s += ' ';
if (e.is_number_integer()) *s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) *s += fmt("%.17g", e.get<double>());
else if (e.is_string()) *s += e.get<std::string>();
else if (e.is_boolean()) *s += e.get<bool>() ? "1" : "0";
else return false;
}
return true;
}
static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) {
for (auto it = j.begin(); it != j.end(); ++it) {
const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key();
@@ -74,19 +93,10 @@ 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 ..."). Arrays of objects are
* skipped. */
* layer_types "linear_attention full_attention ..."), nested arrays row-major.
* Arrays of objects are skipped. */
std::string s;
bool ok = true;
for (const auto& e : v) {
if (!s.empty()) s += ' ';
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else if (e.is_boolean()) s += e.get<bool>() ? "1" : "0";
else { ok = false; break; }
}
if (ok) out->kv(key, s);
if (join_scalars(v, &s)) out->kv(key, s);
}
}
}
@@ -590,7 +600,9 @@ int Checkpoint::open_diffusers() {
RAD_TRY(meta_merge_json_file(dir_ + "/" + sc + "/scheduler_config.json", sc, true,
&meta_));
}
for (const char* sub : { "processor", "tokenizer" }) {
/* The tokenizer's own folder, or the text encoder's when the release keeps it there (FLUX.3
* [klein]'s modular pipeline points its tokenizer at text_encoder/). */
for (const char* sub : { "processor", "tokenizer", "text_encoder" }) {
const std::string d = dir_ + "/" + sub;
if (!path_exists(d + "/tokenizer.json")) continue;
tok_dir_ = d;
@@ -1552,9 +1564,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp
return RAD_OK;
}
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]) and RAD_MAP_EMA (src[0] the embedding
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), computed in
* f32 into `derived`. */
/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding
* sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and
* RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */
static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>& maps,
bool optional, CkptWeight* out, std::string* why) {
auto refuse = [&](int rc, std::string msg) {
@@ -1618,7 +1630,30 @@ static int resolve_derived(Checkpoint& ck, const std::vector<const RadNameMap*>&
return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32");
out->rank = (uint32_t)rank;
for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i];
if (ema) {
if (m.mode == RAD_MAP_TAP) {
const int d = m.concat_dim;
if (d < 0 || (size_t)d >= rank || rank < 3)
return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) +
"; a tap of dimension " + std::to_string(d) +
" leaves no matrix");
const int64_t k = a->shape[(size_t)d];
const int64_t t = m.src_index[0] < 0 ? k + m.src_index[0] : m.src_index[0];
if (t < 0 || t >= k)
return refuse(RAD_E_SHAPE, "tap " + std::to_string(m.src_index[0]) + " of '" +
a->name + "' dimension " + std::to_string(d) + " of " +
std::to_string(k));
int64_t outer = 1, inner = 1;
for (int i = 0; i < d; ++i) outer *= a->shape[(size_t)i];
for (size_t i = (size_t)d + 1; i < rank; ++i) inner *= a->shape[i];
out->derived.resize((size_t)(outer * inner));
for (int64_t o = 0; o < outer; ++o)
std::memcpy(&out->derived[(size_t)(o * inner)], &src[(size_t)((o * k + t) * inner)],
(size_t)inner * sizeof(float));
out->rank = (uint32_t)(rank - 1);
for (size_t i = (size_t)d; i + 1 < rank; ++i) out->shape[i] = a->shape[i + 1];
out->why = "it is tap " + std::to_string(t) + " of '" + a->name + "' dimension " +
std::to_string(d) + ", at convert -- a recipe rule stores it";
} else if (ema) {
const int64_t bins = a->shape[0], per = n / bins;
int64_t un = 1;
for (int64_t x : u->shape) un *= x;
@@ -1673,7 +1708,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it");
if (maps.front()->mode == RAD_MAP_WNORM)
return resolve_wnorm(ck, *maps.front(), optional, out, why);
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA)
if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA ||
maps.front()->mode == RAD_MAP_TAP)
return resolve_derived(ck, maps, optional, out, why);
struct Src1 { const char* name; int index; int64_t rows; };
std::vector<Src1> srcs;
+229 -52
View File
@@ -24,6 +24,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) {
struct Sizes {
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
bool joint = false;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
@@ -34,7 +35,10 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0;
z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0;
z.R = d.max_refs;
z.P = z.T + z.R * ref_tokens_max(d);
z.joint = d.layout == RAD_GEN_LAYOUT_JOINT_STEP;
/* The longest conditioning: in the joint layout, the declared bound (its rows ride in the
* step, which the step size bounds anyway). */
z.P = z.joint ? std::min(d.cond_rows, z.T) : z.T + z.R * ref_tokens_max(d);
const int64_t s2 = d.latent_scale * d.latent_scale;
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
z.NT = d.max_tokens;
@@ -47,6 +51,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
const int64_t I = 4, H = 2;
const int64_t rope_rows = std::max(z.P, z.T);
const int64_t J = z.joint ? 1 : 0; /* the joint layout's regions, empty otherwise */
const int64_t want[][2] = {
{ 0, z.T * I }, /* R_TOK */
{ 0, z.T * I }, /* R_POS */
@@ -56,7 +61,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
{ 0, z.EP * z.PD * H }, /* R_ENCPIX */
{ 0, 4 * z.EP * I }, /* R_ENCCRD */
{ 0, (z.R + 2) * I }, /* R_ENCCU */
{ 0, z.P * I }, /* R_SRC */
{ 0, rope_rows * I }, /* R_SRC: a COND's rows, or a joint DENOISE's */
{ 0, 3 * rope_rows * I }, /* R_GROPE */
{ 0, (12 * z.R + 24) * I }, /* R_SEG: offsets; per segment a {0, length} pair and a start; per picture a {0, tokens} pair */
{ 0, z.P * I }, /* R_SLOT */
@@ -71,6 +76,15 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
{ 0, 2 * z.S * 4 }, /* R_SEED */
{ 0, z.S * z.NB * I }, /* R_BT */
{ 0, z.S * I }, /* R_USED */
{ 0, J * 4 * rope_rows * 4 }, /* R_ROPEF */
{ 0, J * (z.S + 1) * I }, /* R_ICU */
{ 0, J * z.T * I }, /* R_IROWS */
{ 0, J * (3 * z.S + 1) * I }, /* R_MCU */
{ 0, J * 2 * I }, /* R_VCU */
{ 0, J * z.T * I }, /* R_MROWS */
{ 0, J * z.T * I }, /* R_MSRC */
{ 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */
{ 0, J * 4 * z.T * 4 }, /* R_MROPE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -84,8 +98,10 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
} /* namespace */
int64_t Driver::device_bytes(const Program& prog) {
if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
if (!prog.is_generator()) return 0;
const bool joint = prog.generator.layout == RAD_GEN_LAYOUT_JOINT_STEP;
if (!joint && prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, joint ? 0 : prog.kv_groups[1].block_size);
int64_t b[R_N][2];
return carve(z, prog.generator.pixel_channels, b, R_N);
}
@@ -97,16 +113,26 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
fixed_ = prog.gen_str.sigmas;
kv_ = kv;
ranks_ = ranks;
/* Exactly one paged full-attention KV group, holding the conditioning. Group handles start at
* 1 (group 0 is the null handle); the KV manager and a batch both index by handle. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
/* Exactly one paged full-attention KV group, holding the conditioning; none in the joint
* layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the
* null handle); the KV manager and a batch both index by handle. */
if (joint()) {
if (prog.kv_groups.size() > 1) {
RAD_ERR("image generator: the joint layout keeps its conditioning in the plugin's "
"state, and the program declares %zu KV group(s)", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 0;
block_size_ = 0;
} else if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the conditioning's", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
} else {
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
@@ -181,9 +207,9 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
" latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) +
" pixels)");
if (tokens * nb > max_tok_)
return no("an image of this size with guidance needs " + std::to_string(tokens * nb) +
" rows a step and a step carries " + std::to_string(max_tok_) +
" (--max-num-batched-tokens)");
return no("an image of this size" + std::string(nb > 1 ? " with guidance" : "") +
" needs " + std::to_string(tokens * nb) + " rows a step and a step carries " +
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
if (r->n < 1 || r->n > d.max_lanes)
return no("n must be 1.." + std::to_string(d.max_lanes));
if ((int64_t)r->refs.size() > d.max_refs)
@@ -293,22 +319,36 @@ int Driver::admit_locked() {
for (const Pixels& p : r.refs)
j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale),
(int32_t)(p.w / decl_.latent_scale) });
int64_t step_rows = 0;
for (int b = 0; b < j.n_branch; ++b) {
std::string why;
const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw,
&j.cond[b].lay, &why);
const int s = joint()
? build_joint_layout(b ? r.neg : r.pos, decl_.pad_multiple,
decl_.rope_hw_scale, decl_.rope_text_l != 0, j.ref_hw,
&j.cond[b].lay, &why)
: build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, &j.cond[b].lay,
&why);
if (s < 0) { fail_locked(j, s, why); break; }
if (j.cond[b].lay.rows > max_rows_) {
fail_locked(j, RAD_E_INVAL, "the conditioning is " +
std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " +
std::to_string(j.cond[b].lay.rows) + " rows (the prompt" +
std::string(r.refs.empty() ? "" : " and its pictures") +
"); this model conditions on at most " +
std::to_string(max_rows_));
break;
}
step_rows += entry_rows(j, b);
}
if (j.failed) continue;
if (step_rows > max_tok_) {
fail_locked(j, RAD_E_INVAL, "an image with its conditioning needs " +
std::to_string(step_rows) + " rows a step and a step carries " +
std::to_string(max_tok_) + " (--max-num-batched-tokens)");
continue;
}
}
bool ok = true;
for (int b = 0; b < j.n_branch && ok; ++b) {
for (int b = 0; b < j.n_branch && ok && !joint(); ++b) {
Cond& c = j.cond[b];
if (c.have_kv) continue;
if (!kv_->can_ever_fit(c.lay.rows)) {
@@ -337,8 +377,14 @@ int Driver::admit_locked() {
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int b = 0; b < j.n_branch; ++b) {
Cond& c = j.cond[b];
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
if (joint()) {
c.rope_img_f.assign((size_t)(4 * j.tokens), 0.0f);
grid_rope_f(decl_.rope_hw_scale, 0.0f, j.h_lat, j.w_lat, c.rope_img_f.data(),
j.tokens);
} else {
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
}
}
for (int32_t i = 0; i < r.n; ++i) {
const int32_t l = free_lanes_.back();
@@ -413,8 +459,8 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
B.kv = &K;
B.n_kv_groups = joint() ? 0 : 1;
B.kv = joint() ? nullptr : &K;
B.gen_b = &G;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
@@ -431,6 +477,20 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
G.lane_dh = hptr<int32_t>(R_LANE);
G.flags = dptr<int32_t>(ri, R_FLAGS);
G.seed = dptr<uint32_t>(ri, R_SEED);
/* The joint layout's fields, which only the passes that use them set. */
G.branch = 0;
G.n_pad = 0;
G.valid_cu = nullptr;
G.n_img = 0;
G.img_cu = nullptr;
G.img_rows = nullptr;
G.mode_cu = nullptr;
G.rope_f = nullptr;
G.mode_rows = nullptr;
G.mode_src = nullptr;
G.mode_ccu = nullptr;
G.n_mode_h = nullptr;
G.mode_rope_f = nullptr;
}
}
@@ -482,7 +542,8 @@ const RadBatch* Driver::next(int step) {
for (int32_t l : j.lanes) {
const Lane& ln = lanes_[(size_t)l];
if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue;
const int64_t need = j.tokens * j.n_branch;
int64_t need = 0;
for (int b = 0; b < j.n_branch; ++b) need += entry_rows(j, b);
if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break;
rows += need;
entries += j.n_branch;
@@ -503,15 +564,19 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
const Request& r = *j.req;
const Branch& br = branch ? r.neg : r.pos;
const Cond& c = j.cond[branch];
const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows;
/* The joint layout's padding tokens follow the prompt's; each sits at position 1 and sees
* only the prompt (`valid_cu`), as a masked padding token does in the reference. */
const int64_t T_valid = (int64_t)br.tokens.size();
const int64_t T = T_valid + (joint() ? c.lay.n_pad : 0), P = c.lay.rows;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* rope = hptr<int32_t>(R_ROPE);
std::memcpy(tok, br.tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
std::memcpy(tok, br.tokens.data(), (size_t)T_valid * 4);
for (int64_t i = T_valid; i < T; ++i) tok[i] = decl_.pad_token;
for (int64_t i = 0; i < T; ++i) pos[i] = i < T_valid ? (int32_t)i : 1;
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
int32_t p3[3] = { pos[i], pos[i], pos[i] };
if (br.media) br.media->rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
@@ -571,7 +636,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4);
for (int64_t s = 0; s < nsg; ++s) {
const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a;
for (int cc = 0; cc < 3; ++cc)
/* The joint layout's positions are f32, staged whole below. */
for (int cc = 0; cc < 3 && !joint(); ++cc)
std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len,
&c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4);
segp[nsg + 1 + 2 * s] = 0;
@@ -579,21 +645,31 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
segp[nsg + 1 + 2 * nsg + s] = a;
}
reg_[R_SRC].used = P * 4;
reg_[R_GROPE].used = 3 * P * 4;
reg_[R_GROPE].used = joint() ? 0 : 3 * P * 4;
reg_[R_SEG].used = (4 * nsg + 1) * 4;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_)
: -1;
static const std::vector<int32_t> no_bt;
const std::vector<int32_t>& bt = joint() ? no_bt : kv_->block_table(c.seq, kv_group_);
if (joint()) {
std::memcpy(hptr<float>(R_ROPEF), c.lay.rope_f.data(), (size_t)(4 * P) * 4);
reg_[R_ROPEF].used = 4 * P * 4;
int32_t* vcu = hptr<int32_t>(R_VCU);
vcu[0] = 0;
vcu[1] = (int32_t)T_valid;
reg_[R_VCU].used = 2 * 4;
} else {
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size()
? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) : -1;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
/* Pictures again for the generator's own encoder, plus the inpainting source when masked.
* Only the positive conditioning's pass writes the lanes. */
@@ -632,7 +708,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
* for the life of the pass. */
host_bidi_ = c.lay.bidi;
host_px_ = pxh;
host_lanes_ = inp ? j.lanes : std::vector<int32_t>{};
/* The joint layout's conditioning goes to every lane of the request. */
host_lanes_ = inp || joint() ? j.lanes : std::vector<int32_t>{};
/* The lanes on the device too: an op copies the inpainting latent and mask into each. */
if (!host_lanes_.empty()) {
std::memcpy(hptr<int32_t>(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
@@ -681,6 +758,16 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
G.n_lane = (int64_t)host_lanes_.size();
G.lane_h = host_lanes_.data();
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
if (joint()) {
B.n_kv_groups = 0;
B.kv = nullptr;
G.slot_mapping = nullptr;
G.branch = branch;
G.n_pad = c.lay.n_pad;
G.valid_cu = dptr<int32_t>(ri, R_VCU);
G.rope = nullptr;
G.rope_f = dptr<float>(ri, R_ROPEF);
}
}
pass_.kind = RAD_GEN_PASS_COND;
pass_.job = j.id;
@@ -699,15 +786,28 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
}
const int64_t S = (int64_t)es.size();
int64_t n_tok = 0;
int64_t n_tok = 0, n_img = 0;
int32_t max_q = 0, max_ctx = 0;
int64_t pitch = 1;
for (const E& e : es) {
n_tok += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)e.j->tokens);
const int64_t rows = entry_rows(*e.j, e.branch);
n_tok += rows;
n_img += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)rows);
max_ctx = std::max<int32_t>(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows);
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size());
if (!joint())
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq,
kv_group_).size());
}
/* The joint layout's per-row arrays: each row's source, the compact image order's bounds and
* rows, each entry's three modes, and the f32 positions. */
int32_t* src = hptr<int32_t>(R_SRC);
int32_t* icu = hptr<int32_t>(R_ICU);
int32_t* irows = hptr<int32_t>(R_IROWS);
int32_t* mcu = hptr<int32_t>(R_MCU);
float* ropef = hptr<float>(R_ROPEF);
int64_t img = 0;
if (joint()) icu[0] = 0;
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* tok = hptr<int32_t>(R_TOK);
@@ -731,9 +831,37 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
const Lane& ln = lanes_[(size_t)e.lane];
const Cond& c = j.cond[e.branch];
const int64_t N = j.tokens;
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
if (joint()) {
/* [conditioning | image]: the conditioning's rows from the plugin's copy at this lane
* and branch, the image's from the compact order. */
const int64_t P = c.lay.rows;
const int64_t base = (2 * (int64_t)e.lane + e.branch) * decl_.cond_rows;
for (int64_t k = 0; k < P; ++k) {
src[row + k] = (int32_t)(base + k);
pos[row + k] = (int32_t)k;
tok[row + k] = 0;
}
for (int cc = 0; cc < 4; ++cc)
std::memcpy(ropef + cc * n_tok + row, c.lay.rope_f.data() + cc * P, (size_t)P * 4);
mcu[3 * i] = (int32_t)row;
mcu[3 * i + 1] = (int32_t)(row + c.lay.text);
mcu[3 * i + 2] = (int32_t)(row + P);
row += P;
for (int64_t k = 0; k < N; ++k) {
src[row + k] = (int32_t)(-(1 + img + k));
irows[img + k] = (int32_t)(row + k);
pos[row + k] = (int32_t)k;
tok[row + k] = 0;
}
for (int cc = 0; cc < 4; ++cc)
std::memcpy(ropef + cc * n_tok + row, c.rope_img_f.data() + cc * N, (size_t)N * 4);
img += N;
icu[i + 1] = (int32_t)img;
} else {
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
}
row += N;
cu[i + 1] = (int32_t)row;
sig[i] = j.sigmas[(size_t)ln.step];
@@ -758,6 +886,7 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
flags[i] = f;
seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(ln.seed >> 32);
if (joint()) continue;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
for (int64_t b = 0; b < pitch; ++b)
btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1;
@@ -765,12 +894,46 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
}
reg_[R_CU].used = (S + 1) * 4;
reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4;
reg_[R_GROPE].used = 3 * n_tok * 4;
if (joint()) {
mcu[3 * S] = (int32_t)n_tok;
/* The mode-major order: every entry's text, then pictures, then image. */
int32_t* mrows = hptr<int32_t>(R_MROWS);
int32_t* msrc = hptr<int32_t>(R_MSRC);
int32_t* mccu = hptr<int32_t>(R_MCCU);
float* mrope = hptr<float>(R_MROPE);
int64_t k = 0;
for (int mode = 0; mode < 3; ++mode) {
const int64_t k0 = k;
int64_t nm = 0;
for (int64_t i = 0; i < S; ++i) nm += mcu[3 * i + mode + 1] - mcu[3 * i + mode];
for (int64_t i = 0; i < S; ++i) {
mccu[mode * (S + 1) + i] = (int32_t)(k - k0);
for (int32_t r = mcu[3 * i + mode]; r < mcu[3 * i + mode + 1]; ++r, ++k) {
mrows[k] = r;
msrc[k] = src[r];
for (int cc = 0; cc < 4; ++cc)
mrope[4 * k0 + cc * nm + (k - k0)] = ropef[cc * n_tok + r];
}
}
mccu[mode * (S + 1) + S] = (int32_t)(k - k0);
host_nmode_[mode] = k - k0;
}
reg_[R_MROWS].used = reg_[R_MSRC].used = n_tok * 4;
reg_[R_MCCU].used = 3 * (S + 1) * 4;
reg_[R_MROPE].used = 4 * n_tok * 4;
reg_[R_SRC].used = n_tok * 4;
reg_[R_IROWS].used = n_img * 4;
reg_[R_ICU].used = (S + 1) * 4;
reg_[R_MCU].used = (3 * S + 1) * 4;
reg_[R_ROPEF].used = 4 * n_tok * 4;
} else {
reg_[R_GROPE].used = 3 * n_tok * 4;
}
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
reg_[R_BT].used = joint() ? 0 : S * pitch * 4;
reg_[R_USED].used = joint() ? 0 : S * 4;
if (upload() < 0) return nullptr;
finish_batches(n_tok, S, max_q, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
@@ -789,8 +952,22 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
G.inpaint = 0;
G.n_lane = 0;
G.lane_h = nullptr;
G.rope = dptr<int32_t>(ri, R_GROPE);
G.rope = joint() ? nullptr : dptr<int32_t>(ri, R_GROPE);
G.lane_dh = hptr<int32_t>(R_LANE);
if (joint()) {
G.src = dptr<int32_t>(ri, R_SRC);
G.n_img = n_img;
G.img_cu = dptr<int32_t>(ri, R_ICU);
G.img_rows = dptr<int32_t>(ri, R_IROWS);
G.mode_cu = dptr<int32_t>(ri, R_MCU);
G.rope_f = dptr<float>(ri, R_ROPEF);
G.slot_mapping = nullptr;
G.mode_rows = dptr<int32_t>(ri, R_MROWS);
G.mode_src = dptr<int32_t>(ri, R_MSRC);
G.mode_ccu = dptr<int32_t>(ri, R_MCCU);
G.n_mode_h = host_nmode_;
G.mode_rope_f = dptr<float>(ri, R_MROPE);
}
}
pass_.kind = RAD_GEN_PASS_DENOISE;
return &out_[0];
+10 -1
View File
@@ -75,6 +75,7 @@ private:
bool have_kv = false;
bool encoded = false;
std::vector<int32_t> rope_img; /* [3, image tokens]: the image's rows at this sequence */
std::vector<float> rope_img_f; /* JOINT_STEP: [4, image tokens] */
};
struct Job {
uint64_t id = 0;
@@ -117,7 +118,7 @@ private:
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
R_BT, R_USED, R_N };
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N };
int layout_regions();
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
@@ -133,6 +134,13 @@ private:
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
/* The JOINT_STEP layout: the conditioning rides in every denoising entry, and no KV. */
bool joint() const { return decl_.layout == RAD_GEN_LAYOUT_JOINT_STEP; }
/* An entry's rows in a denoising pass. */
int64_t entry_rows(const Job& j, int branch) const {
return j.tokens + (joint() ? j.cond[branch].lay.rows : 0);
}
const RadBatch* build_cond(Job& j, int branch, int step);
const RadBatch* build_denoise(const std::vector<int32_t>& lanes, int step);
const RadBatch* build_decode(int32_t lane, bool preview, int step);
@@ -162,6 +170,7 @@ private:
Pass pass_;
/* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
int64_t host_nmode_[3] = { 0, 0, 0 };
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
+61
View File
@@ -106,6 +106,67 @@ void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_to
}
}
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total) {
const float s = (float)hw_scale;
int64_t k = 0;
for (int32_t r = 0; r < h; ++r)
for (int32_t c = 0; c < w; ++c, ++k) {
planes[k] = 0.0f;
planes[n_total + k] = s * (float)r;
planes[2 * n_total + k] = s * (float)c;
planes[3 * n_total + k] = l;
}
}
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
*out = Layout{};
const int64_t T = (int64_t)b.tokens.size();
if (b.n_drop < 0 || b.n_drop >= T) {
if (why) *why = "the conditioning prompt is no longer than its fixed prefix";
return RAD_E_INVAL;
}
if (b.media) {
if (why) *why = "the joint layout reads no pictures in the prompt";
return RAD_E_INVAL;
}
const int64_t text = T - b.n_drop;
const int64_t padded = pad_multiple > 0 ? (text + pad_multiple - 1) / pad_multiple * pad_multiple
: text;
int64_t refs = 0;
for (const auto& hw : ref_hw) refs += (int64_t)hw.first * hw.second;
const int64_t rows = padded + refs;
out->rows = rows;
out->text = padded;
out->n_pad = (int32_t)(padded - text);
out->src.resize((size_t)rows);
out->rope_f.assign((size_t)(4 * rows), 0.0f);
for (int64_t i = 0; i < padded; ++i) {
out->src[(size_t)i] = (int32_t)(b.n_drop + i);
if (text_l) out->rope_f[(size_t)(3 * rows + i)] = (float)i;
}
out->seg.push_back(0);
out->bidi.push_back(0);
int64_t row = padded, lat = 0;
for (size_t k = 0; k < ref_hw.size(); ++k) {
const int32_t h = ref_hw[k].first, w = ref_hw[k].second;
const int64_t n = (int64_t)h * w;
std::vector<float> pl((size_t)(4 * n));
grid_rope_f(hw_scale, -(float)(1 + k), h, w, pl.data(), n);
for (int cc = 0; cc < 4; ++cc)
std::memcpy(&out->rope_f[(size_t)(cc * rows + row)], &pl[(size_t)(cc * n)],
(size_t)n * sizeof(float));
for (int64_t i = 0; i < n; ++i) out->src[(size_t)(row + i)] = (int32_t)(-(1 + lat + i));
out->seg.push_back((int32_t)row);
out->bidi.push_back(1);
row += n;
lat += n;
}
out->seg.push_back((int32_t)rows);
return RAD_OK;
}
int build_layout(const Branch& b, int64_t slot_rows,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
+16
View File
@@ -129,6 +129,11 @@ struct Layout {
std::vector<int32_t> seg; /* [n_seg + 1] */
std::vector<int32_t> bidi; /* [n_seg] */
int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */
/* JOINT_STEP only: the text's rows (padding included), the padding rows among them, and the
* f32 positions, [4, rows] component-major (`rope` is then empty). */
int64_t text = 0;
int32_t n_pad = 0;
std::vector<float> rope_f;
};
/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the
* prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */
@@ -137,5 +142,16 @@ int build_layout(const Branch& b, int64_t slot_rows, const std::vector<std::pair
/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total);
/* A conditioning in the JOINT_STEP layout (RadGeneratorDecl): the prompt's rows after its drop
* prefix, padding to a multiple of `pad_multiple` (0: none), then each reference picture's latent
* tokens. `src` is the prompt row behind a text row -- a padding row's is past the prompt's last,
* where the COND pass appends the padding tokens -- or -(1 + i) for reference latent row i. One
* text segment (causal) and a segment per picture (bidirectional). */
int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why);
/* The f32 positions (0, s h, s w, l) of an h x w grid: [4, h * w] component-major. */
void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total);
} /* namespace gen */
} /* namespace rad */
+25 -7
View File
@@ -10,6 +10,7 @@
#include "rad_core.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <deque>
#include <memory>
@@ -22,12 +23,13 @@ namespace gen {
/* One thing a request has made. */
struct VideoEvent {
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 };
enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3, LENGTH = 4 };
int kind = 0;
int32_t steps_done = 0; /* STEP: denoising steps finished */
/* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */
std::vector<float> samples;
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */
/* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. LENGTH:
* the `n` frames the model chose for a request that named no length, before any step. */
int32_t first = 0, n = 0;
std::vector<uint8_t> rgb;
};
@@ -49,7 +51,8 @@ public:
std::atomic<bool> cancel{false};
/* What the request makes, written by the driver at submit: the frames and their size, the
* steps, and the soundtrack's rate and channels. */
* steps, and the soundtrack's rate and channels. A request whose length the model predicts
* has its `frames`, `steps` and `rows` rewritten once, before its LENGTH event. */
int32_t frames = 0, width = 0, height = 0, steps = 0;
int64_t sample_rate = 0, channels = 0;
double fps = 0.0;
@@ -81,6 +84,17 @@ struct VideoRequest {
double upscale = 0.0;
int32_t refine = 0;
uint64_t seed = 0;
/* Guidance (RadVideoGenDecl::guidance): the eight terms, NaN for the model's default, and the
* negative prompt, rendered and tokenised; `has_neg` false for the model's default. */
double guidance[8] = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN };
std::vector<int32_t> neg_tokens;
bool has_neg = false;
/* A first frame (RadVideoGenDecl::image_cond): [height, width, 3] u8 RGB at the size the
* first evaluations run at (video_small_size under upscaling, else the video's), already
* prepared as the model's pipeline prepares it; empty for none. */
std::vector<uint8_t> image;
/* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */
int32_t decoder = 0;
std::shared_ptr<VideoTicket> ticket;
};
@@ -98,14 +112,18 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor,
int32_t* small_w, int32_t* small_h);
/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each
* the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a
* trained schedule any other step count than n_rungs + 1 gives no steps. */
/* The two schedules a request of `steps` runs (RadVideoGenDecl, "The sampler": grid points under
* form 0, evaluations under form 1): each the f32 sigmas, last 0, and the model evaluations it
* takes, the shorter of the two. With a trained schedule any other step count than the declared
* one gives no steps. `video_tokens` are the video's latent tokens, which form 1's dynamic shift
* reads. With `refine` (form 1 and refinement rungs) the rungs are followed by the refinement
* rungs instead of a 0, the evaluations their sum. */
struct VideoSchedule {
std::vector<float> sig_v, sig_a;
int32_t steps = 0;
};
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps);
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0,
bool refine = false);
} /* namespace gen */
} /* namespace rad */
+309 -86
View File
@@ -2,6 +2,7 @@
* waits on, and a request's shape and schedule (video.h). */
#include "video_driver.h"
#include "rad_internal.h"
#include "rad_plugin.h"
#include <algorithm>
#include <chrono>
@@ -75,7 +76,7 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height,
if (r2 > den || (r2 == den && (q & 1))) ++q;
s.n_audio = (int32_t)q;
s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch);
s.audio_rows = d.audio_channels * (int64_t)s.n_audio;
s.audio_rows = (d.audio_streams > 0 ? d.audio_streams : d.audio_channels) * (int64_t)s.n_audio;
return s;
}
@@ -120,8 +121,47 @@ static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) {
/* Form 1 (RadVideoGenDecl::sched_kind): FlowMatchEulerDiscreteScheduler.set_timesteps with
* LTX-2's sigmas. numpy's linspace in f64 (i * step + start, the last exactly the stop) taken to
* f32; the shift and the terminal stretch in f32, as numpy computes on an f32 array with Python
* scalars. */
static std::vector<float> flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64_t tokens) {
std::vector<float> s((size_t)n);
const double stop = 1.0 / n, step = n > 1 ? (stop - 1.0) / (n - 1) : 0.0;
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = (float)(i == n - 1 && n > 1 ? stop : i * step + 1.0);
if (d.dyn_shift) {
const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq);
const double mu = (double)tokens * m + (d.base_shift - m * (double)d.base_seq);
const float e = (float)std::exp(mu);
for (float& v : s) v = e / (e + (1.0f / v - 1.0f));
}
if (d.shift_terminal > 0.0) {
const float sf = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal);
for (float& v : s) v = 1.0f - (1.0f - v) / sf;
}
s.push_back(0.0f);
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens,
bool refine) {
VideoSchedule v;
if (d.sched_kind == 1) {
if (d.n_rungs > 0) {
if (steps != d.n_rungs) return v;
for (int32_t i = 0; i < d.n_rungs; ++i) v.sig_v.push_back((float)d.rungs[i]);
if (refine)
for (int32_t i = 0; i < d.n_refine_rungs; ++i)
v.sig_v.push_back((float)d.refine_rungs[i]);
v.sig_v.push_back(0.0f);
} else {
if (steps < 1) return v;
v.sig_v = flow_sigmas(d, steps, video_tokens);
}
v.sig_a = v.sig_v;
v.steps = (int32_t)v.sig_v.size() - 1;
return v;
}
if (d.n_rungs > 0) {
if (steps != d.n_rungs + 1) return v;
v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs);
@@ -146,10 +186,12 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, 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;
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
prompts * d.max_text * 4, /* R_TOK */
prompts * d.max_text * 4, /* R_POS */
3 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
@@ -161,6 +203,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in
4 * 4, /* R_SEG */
4 * 4, /* R_LAT */
4, /* R_UP */
d.image_cond ? d.max_area * 3 * 2 : 0, /* R_IMG: a first frame, bf16 */
8 * 4, /* R_GUIDE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -206,9 +250,17 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
"video generator must", name_.c_str());
return RAD_E_UNSUPPORTED;
}
if (max_tok_ < decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens",
name_.c_str(), (long long)max_tok_, (long long)decl_.max_text);
decoder_names_ = prog.vgen_str.decoders;
decoder_area_ = prog.vgen_str.decoder_max_area;
refine_rungs_ = prog.vgen_str.refine_rungs;
decl_.refine_rungs = refine_rungs_.empty() ? nullptr : refine_rungs_.data();
default_negative_ = prog.vgen_str.default_negative;
decl_.default_negative = default_negative_.c_str();
const int64_t prompts = decl_.guidance ? 2 : 1;
if (max_tok_ < prompts * decl_.max_text) {
RAD_ERR("video generator '%s': a pass carries %lld rows and %s may be %lld tokens",
name_.c_str(), (long long)max_tok_, prompts == 2 ? "a prompt and its negative" :
"a prompt", (long long)(prompts * decl_.max_text));
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
@@ -222,7 +274,8 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
frames_host_ = static_cast<uint8_t*>(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED));
audio_host_ = static_cast<float*>(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_) {
duration_host_ = static_cast<float*>(rad_dev_alloc(64, RAD_MEM_HOST_PINNED));
if (!host_ || !frames_host_ || !audio_host_ || !duration_host_) {
RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + "
"%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_,
(long long)audio_bytes_);
@@ -258,12 +311,157 @@ void VideoDriver::fini() {
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
if (duration_host_) rad_dev_free(duration_host_, RAD_MEM_HOST_PINNED);
duration_host_ = nullptr;
host_ = nullptr;
frames_host_ = nullptr;
audio_host_ = nullptr;
}
/* ================================================================== requests */
/* A length head's prediction (RadVideoGenDecl::duration_out) in chunks: diffusers'
* LTX2DurationHead.predict_num_frames on the chunk grid -- the seconds clamped to the declared
* bounds, rounded to frames, floored to the grid and lifted one chunk when that falls under the
* minimum -- then held to min_chunks..max_chunks. `note` says what was clamped. */
int32_t VideoDriver::predicted_chunks(double log_seconds, std::string* note) const {
const RadVideoGenDecl& d = decl_;
const double fps = (double)d.fps_num / (double)d.fps_den;
float e = std::exp((float)log_seconds);
if (d.duration_dtype == RAD_BF16) e = rad_bf16_to_f32(rad_f32_to_bf16(e));
const double sec = e;
auto round_even = [](double v) { return (int64_t)std::nearbyint(v); };
const int64_t lo = std::max<int64_t>(1, round_even(d.duration_min * fps));
const int64_t hi = round_even(d.duration_max * fps);
const int64_t want = std::isfinite(sec) ? round_even(sec * fps) : hi;
const int64_t frames = std::max(lo, std::min(want, hi));
int64_t n = std::max<int64_t>(0, (frames - d.frames_tail) / d.frames_per_chunk);
if (d.frames_per_chunk * n + d.frames_tail < lo &&
d.frames_per_chunk * (n + 1) + d.frames_tail <= hi)
++n;
std::string what = fmt(": %.3f s predicted", sec);
if (!(sec >= d.duration_min && sec <= d.duration_max))
what += fmt(", held to %g..%g s", d.duration_min, d.duration_max);
if (n < d.min_chunks || n > d.max_chunks) {
n = std::max<int64_t>(d.min_chunks, std::min<int64_t>(n, d.max_chunks));
what += fmt(", within the %lld..%lld frames this model makes",
(long long)(d.frames_per_chunk * d.min_chunks + d.frames_tail),
(long long)(d.frames_per_chunk * d.max_chunks + d.frames_tail));
}
if (note) *note = what;
return (int32_t)n;
}
/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the
* upscale's split and what its ticket says it makes. Run at submit, and again for a request whose
* length the model predicts once its VCOND pass has written the prediction. */
int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps,
std::string* why) {
const RadVideoGenDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
const int64_t T = (int64_t)r.tokens.size();
const VideoShape s = video_shape(d, r.width, r.height, chunks);
j.geom.n_text = (int32_t)(d.step_text_rows > 0 ? d.step_text_rows : T);
j.geom.frames = s.frames;
j.geom.lat_frames = s.lat_frames;
j.geom.lat_h = s.lat_h;
j.geom.lat_w = s.lat_w;
j.geom.n_audio = s.n_audio;
j.rows = j.geom.n_text + s.audio_rows + s.video_rows;
if (j.rows > max_tok_)
return no("a step of this video is " + std::to_string(j.rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j.geom, nullptr, 0);
const int64_t nd = positions_(RAD_VPOS_DECODE, &j.geom, nullptr, 0);
if (nr != j.rows || nd <= 0 || nd > max_tok_)
return no("the model lays this video out in " + std::to_string(nr) + " step rows and " +
std::to_string(nd) + " decoder rows, which this server cannot run");
j.dec_rows = nd;
j.pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j.geom, j.pos.data(), nr) != nr)
return no("the model could not lay this video out");
/* The schedule follows the upscale's split, which needs the small size first. */
const bool upscaling = r.upscale > 1.0;
const bool own_refine = upscaling && d.n_refine_rungs > 0;
int64_t first_tokens = s.video_rows;
if (upscaling) {
int32_t sw = 0, sh = 0;
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
first_tokens = video_shape(d, sw, sh, chunks).video_rows;
}
j.sched = video_schedule(d, steps, first_tokens, own_refine);
if (j.sched.steps < 1) return no("the schedule has no steps");
int32_t first_w = r.width, first_h = r.height;
if (upscaling) {
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
if (d.upscale_exact) {
const int64_t m = (int64_t)std::llround(d.size_multiple * d.upscale_max);
if (r.upscale != d.upscale_max || r.width % m || r.height % m)
return no("this model's latent upscaler enlarges by exactly " +
fmt("%g", d.upscale_max) + ": latent_upscale must be that, and both "
"sides multiples of " + std::to_string(m));
}
if (r.upscale > d.upscale_max)
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
int32_t sw = 0, sh = 0;
video_small_size(d, r.width, r.height, r.upscale, &sw, &sh);
if (sw == r.width && sh == r.height)
return no("latent_upscale " + fmt("%g", r.upscale) + " leaves " +
std::to_string(r.width) + "x" + std::to_string(r.height) + " as it is: "
"the small size is each side over the factor, rounded to a multiple of " +
std::to_string(d.size_multiple));
const int32_t evals = j.sched.steps;
int32_t refine = r.refine;
if (own_refine) {
if (refine != 0 && refine != d.n_refine_rungs)
return no("upscale_refine_steps must be " + std::to_string(d.n_refine_rungs) +
": this model refines the upscaled video over the schedule it was "
"trained on");
refine = d.n_refine_rungs;
}
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
if (refine < 1 || refine >= evals)
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
"schedule takes " + std::to_string(evals) + " evaluations and the small "
"size at least one of them");
const VideoShape ss = video_shape(d, sw, sh, chunks);
j.geom_small = j.geom;
j.geom_small.lat_h = ss.lat_h;
j.geom_small.lat_w = ss.lat_w;
j.rows_small = j.geom.n_text + ss.audio_rows + ss.video_rows;
const int64_t ns = positions_(RAD_VPOS_STEP, &j.geom_small, nullptr, 0);
if (ns != j.rows_small)
return no("the model lays the small size " + std::to_string(sw) + "x" +
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
"this server cannot run");
j.pos_small.assign((size_t)(3 * ns), 0.0f);
if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns)
return no("the model could not lay the small size out");
j.split = evals - refine;
j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0);
r.ticket->small_width = sw;
r.ticket->small_height = sh;
r.ticket->refine = refine;
first_w = sw;
first_h = sh;
}
if (!r.image.empty()) {
if (!d.image_cond) return no("this model cannot start from a picture");
if (r.image.size() != (size_t)first_w * first_h * 3)
return no("the first frame is not " + std::to_string(first_w) + "x" +
std::to_string(first_h) + " RGB");
}
j.n_chunks = chunks;
j.n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
VideoTicket& t = *r.ticket;
t.frames = s.frames;
t.steps = j.sched.steps;
t.rows = j.rows;
return RAD_OK;
}
int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadVideoGenDecl& d = decl_;
@@ -275,7 +473,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (T < 1 || T > d.max_text)
return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." +
std::to_string(d.max_text));
if (r->chunks < d.min_chunks || r->chunks > d.max_chunks)
if (r->chunks != 0 && (r->chunks < d.min_chunks || r->chunks > d.max_chunks))
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
std::to_string(d.max_chunks) + " chunks");
const int64_t W = r->width, H = r->height;
@@ -287,87 +485,53 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
" pixels, the long side at most " + std::to_string(d.max_aspect) +
" times the short");
const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps;
if (d.n_rungs > 0 && steps != d.n_rungs + 1)
return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model "
const bool evals = d.sched_kind == 1; /* form 1 counts evaluations, form 0 grid points */
const int32_t rung_steps = evals ? d.n_rungs : d.n_rungs + 1;
if (d.n_rungs > 0 && steps != rung_steps)
return no("num_inference_steps must be " + std::to_string(rung_steps) + ": this model "
"runs the schedule it was trained on, " + std::to_string(d.n_rungs) +
" evaluations");
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 0)");
if (steps < (evals ? 1 : 2) || steps > d.max_steps)
return no("num_inference_steps must be " + std::to_string(evals ? 1 : 2) + ".." +
std::to_string(d.max_steps) + (evals ? " (model evaluations)" :
" (sigma grid points, the last one 0)"));
auto j = std::make_unique<Job>();
const VideoShape s = video_shape(d, r->width, r->height, r->chunks);
j->geom.n_text = (int32_t)T;
j->geom.frames = s.frames;
j->geom.lat_frames = s.lat_frames;
j->geom.lat_h = s.lat_h;
j->geom.lat_w = s.lat_w;
j->geom.n_audio = s.n_audio;
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0);
if (nr != j->rows || nd <= 0 || nd > max_tok_)
return no("the model lays this video out in " + std::to_string(nr) + " step rows and " +
std::to_string(nd) + " decoder rows, which this server cannot run");
j->dec_rows = nd;
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
j->sched = video_schedule(d, steps);
if (j->sched.steps < 1) return no("the schedule has no steps");
if (r->upscale > 1.0) {
if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler");
if (r->upscale > d.upscale_max)
return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model");
int32_t sw = 0, sh = 0;
video_small_size(d, r->width, r->height, r->upscale, &sw, &sh);
if (sw == r->width && sh == r->height)
return no("latent_upscale " + fmt("%g", r->upscale) + " leaves " +
std::to_string(r->width) + "x" + std::to_string(r->height) + " as it is: "
"the small size is each side over the factor, rounded to a multiple of " +
std::to_string(d.size_multiple));
const int32_t evals = j->sched.steps;
int32_t refine = r->refine;
if (refine == 0) refine = std::min<int32_t>(d.upscale_refine, evals - 1);
if (refine < 1 || refine >= evals)
return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the "
"schedule takes " + std::to_string(evals) + " evaluations and the small "
"size at least one of them");
const VideoShape ss = video_shape(d, sw, sh, r->chunks);
j->geom_small = j->geom;
j->geom_small.lat_h = ss.lat_h;
j->geom_small.lat_w = ss.lat_w;
j->rows_small = T + ss.audio_rows + ss.video_rows;
const int64_t ns = positions_(RAD_VPOS_STEP, &j->geom_small, nullptr, 0);
if (ns != j->rows_small)
return no("the model lays the small size " + std::to_string(sw) + "x" +
std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which "
"this server cannot run");
j->pos_small.assign((size_t)(3 * ns), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom_small, j->pos_small.data(), ns) != ns)
return no("the model could not lay the small size out");
j->split = evals - refine;
j->factor = (float)(((double)r->width / sw + (double)r->height / sh) / 2.0);
r->ticket->small_width = sw;
r->ticket->small_height = sh;
r->ticket->refine = refine;
/* Guidance: the request's terms over the model's defaults; a negative prompt only when a
* scale asks for the unconditional branch. */
bool named = r->has_neg;
for (int i = 0; i < 8; ++i) {
named = named || !std::isnan(r->guidance[i]);
j->guidance[i] = (float)(std::isnan(r->guidance[i]) ? d.guidance_default[i] : r->guidance[i]);
if (!(j->guidance[i] >= 0.0f) || !std::isfinite(j->guidance[i]))
return no("guidance terms must be finite and not negative");
}
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
if (!d.guidance && named)
return no("this model takes no guidance or negative prompt");
j->n_neg = 0;
if (d.guidance && (j->guidance[0] != 1.0f || j->guidance[4] != 1.0f)) {
const int64_t N = (int64_t)r->neg_tokens.size();
if (N < 1 || N > d.max_text)
return no("the negative prompt is " + std::to_string(N) + " tokens; this model takes "
"1.." + std::to_string(d.max_text));
j->n_neg = (int32_t)N;
}
if (r->decoder < 0 || (r->decoder > 0 && (size_t)r->decoder >= decoder_area_.size()))
return no("this model has no decoder " + std::to_string(r->decoder));
if (r->decoder > 0 && W * H > decoder_area_[(size_t)r->decoder])
return no("the " + decoder_names_[(size_t)r->decoder] + " decoder makes frames of " +
std::to_string(decoder_area_[(size_t)r->decoder]) + " pixels at most");
j->auto_len = r->chunks == 0 && d.duration_out != RAD_NULL_HANDLE;
const int32_t chunks = r->chunks == 0 ? (int32_t)d.default_chunks : r->chunks;
if (shape_job(*j, *r, chunks, steps, why) < 0) return RAD_E_INVAL;
VideoTicket& t = *r->ticket;
t.frames = s.frames;
t.width = r->width;
t.height = r->height;
t.steps = j->sched.steps;
t.sample_rate = d.sample_rate;
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->rows;
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -472,8 +636,16 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
b.lat_frames, b.lat_h / p, b.lat_w / p };
std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up);
}
g[RAD_VGEOM_AUDIO_VOL] = g0.n_audio;
g[RAD_VGEOM_AUDIO_VOL + 1] = 1;
g[RAD_VGEOM_AUDIO_VOL + 2] = 1;
const int32_t ppf = (int32_t)((g0.lat_h / decl_.patch) * (g0.lat_w / decl_.patch));
g[RAD_VGEOM_FIRST_CU] = 0;
g[RAD_VGEOM_FIRST_CU + 1] = ppf;
g[RAD_VGEOM_FIRST_CU + 2] = ppf * g0.lat_frames;
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio;
const int64_t audio_rows =
(decl_.audio_streams > 0 ? decl_.audio_streams : decl_.audio_channels) * (int64_t)g0.n_audio;
const int64_t video_rows = rows - g0.n_text - audio_rows;
*hptr<int32_t>(R_LANE) = j.lane;
*hptr<int32_t>(R_FIRST) = j.step == 0;
@@ -487,6 +659,8 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
lat[1] = (int32_t)video_rows;
lat[2] = 0;
lat[3] = (int32_t)audio_rows;
std::memcpy(hptr<float>(R_GUIDE), j.guidance, sizeof j.guidance);
reg_[R_GUIDE].used = sizeof j.guidance;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_SEG].used = 4 * 4;
@@ -529,6 +703,10 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
V.dec_rows = j.dec_rows;
V.n_samples = j.n_samples;
V.upscale = dptr<float>(ri, R_UP);
V.guidance_h = j.guidance;
V.guidance = dptr<float>(ri, R_GUIDE);
V.has_image = !j.req->image.empty();
V.decoder = j.req->decoder;
B.vgen_b = &V;
}
}
@@ -581,30 +759,54 @@ const RadBatch* VideoDriver::batch_for(int rank) const {
const RadBatch* VideoDriver::build_cond(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const int64_t T = j.geom.n_text;
/* The prompt, then the negative prompt when the request is guided against one, each its own
* sequence from position 0. */
const int64_t T = (int64_t)j.req->tokens.size(), N = j.n_neg;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
if (N > 0) std::memcpy(tok + T, j.req->neg_tokens.data(), (size_t)N * 4);
/* A left-padded encoder's prompt ends at text_left_pad - 1. */
const int64_t lp = decl_.text_left_pad;
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)(lp > 0 ? lp - T + i : i);
for (int64_t i = 0; i < N; ++i) pos[T + i] = (int32_t)(lp > 0 ? lp - N + i : i);
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
cu[2] = (int32_t)(T + N);
/* The first frame as the reference's image processor hands it to the VAE: x / 255 * 2 - 1 in
* f32, then bf16. */
const std::vector<uint8_t>& img = j.req->image;
if (!img.empty()) {
uint16_t* px = hptr<uint16_t>(R_IMG);
for (size_t i = 0; i < img.size(); ++i)
px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f);
reg_[R_IMG].used = (int64_t)img.size() * 2;
}
float* tv = hptr<float>(R_TV);
float* ta = hptr<float>(R_TA);
for (int32_t i = 0; i < j.sched.steps; ++i) {
tv[i] = 1.0f - j.sched.sig_v[(size_t)i];
ta[i] = 1.0f - j.sched.sig_a[(size_t)i];
}
reg_[R_TOK].used = T * 4;
reg_[R_POS].used = T * 4;
reg_[R_CU].used = 2 * 4;
reg_[R_TOK].used = (T + N) * 4;
reg_[R_POS].used = (T + N) * 4;
reg_[R_CU].used = (N > 0 ? 3 : 2) * 4;
reg_[R_TV].used = j.sched.steps * 4;
reg_[R_TA].used = j.sched.steps * 4;
const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom;
stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0);
if (upload() < 0) return nullptr;
base_batches(j, g, T, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
base_batches(j, g, T + N, step);
for (size_t r = 0; r < out_.size(); ++r) {
RadBatch& B = out_[r];
B.gen = RAD_GEN_PASS_VCOND;
B.n_seq = N > 0 ? 2 : 1;
B.max_q_len = B.max_q_len_prefill = (int32_t)std::max(T, N);
vout_[r].n_neg = (int32_t)N;
if (!img.empty()) vout_[r].image = dptr<uint16_t>((int)r, R_IMG);
}
if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ });
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
return &out_[0];
@@ -691,6 +893,7 @@ const RadBatch* VideoDriver::build_audio(Job& j, int step) {
const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
stage_geom(j, j.geom, j.rows, j.chunk);
stage_seed(j); /* a decoder that denoises draws from the request's seed */
if (upload() < 0) return nullptr;
base_batches(j, j.geom, j.dec_rows, step);
const bool last = j.chunk == j.n_chunks - 1;
@@ -715,6 +918,26 @@ int VideoDriver::done() {
case RAD_GEN_PASS_VCOND:
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
if (j->auto_len) {
j->auto_len = false;
std::string note, why;
int32_t n = predicted_chunks((double)duration_host_[0], &note);
/* Shaped as at submit, which passed at default_chunks; a longer video than a pass
* can carry is shortened until it fits. */
const int32_t steps = j->req->steps > 0 ? j->req->steps : (int32_t)decl_.default_steps;
const int32_t at_submit = j->n_chunks;
while (n > at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) --n;
if (n <= at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) {
fail_locked(*j, RAD_E_INVAL, why);
break;
}
RAD_INFO("video: the model gives the prompt %d frames (%.2f s)%s", j->geom.frames,
(double)j->geom.frames * decl_.fps_den / decl_.fps_num, note.c_str());
VideoEvent e;
e.kind = VideoEvent::LENGTH;
e.n = j->geom.frames;
j->req->ticket->push(std::move(e));
}
break;
case RAD_GEN_PASS_VSTEP: {
++j->step;
+17 -2
View File
@@ -6,7 +6,8 @@
* threads through `submit()` and leave through their VideoTicket.
*
* A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary
* positions are fixed at submit, so nothing is computed between passes but the staging.
* positions are fixed at submit, so nothing is computed between passes but the staging; a request
* whose length the model predicts is shaped again once, after its VCOND pass.
*
* Pass priority, one pass at a time:
*
@@ -76,6 +77,13 @@ private:
std::vector<float> pos_small;
float factor = 0.0f;
bool upscaled = false;
/* Guidance resolved against the model's defaults (RadVideoGenBatch::guidance_h) and the
* negative prompt's tokens the VCOND pass carries (0: none). */
float guidance[8] = {};
int32_t n_neg = 0;
/* The request named no length and the model predicts one (RadVideoGenDecl::duration_out):
* shaped at default_chunks until its VCOND pass is done. */
bool auto_len = false;
int32_t lane = -1;
bool admitted = false;
bool cond_done = false;
@@ -96,7 +104,7 @@ private:
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST,
R_SEG, R_LAT, R_UP, R_N };
R_SEG, R_LAT, R_UP, R_IMG, R_GUIDE, 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 {
@@ -105,6 +113,8 @@ private:
int upload();
/* The geometry and rows of the job's next step: the small ones before its upscale. */
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why);
int32_t predicted_chunks(double log_seconds, std::string* note) const;
void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step);
void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk);
void stage_sched(const Job& j, int32_t i, bool to_clean);
@@ -123,6 +133,10 @@ private:
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::vector<double> refine_rungs_; /* decl_.refine_rungs */
std::string default_negative_;
std::vector<std::string> decoder_names_; /* RadVideoGenDecl::decoders */
std::vector<int64_t> decoder_area_; /* each one's largest frame */
std::string name_;
PositionsFn positions_ = nullptr;
int64_t max_tok_ = 0;
@@ -136,6 +150,7 @@ private:
int64_t frames_bytes_ = 0;
float* audio_host_ = nullptr;
int64_t audio_bytes_ = 0;
float* duration_host_ = nullptr; /* duration_out's readback, f32 [1] */
std::vector<Readback> rb_;
std::vector<RadBatch> out_; /* one per rank */
+3 -4
View File
@@ -774,10 +774,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
/* Evict the least recently used snapshot, where a use is its reservation or a lookup
* resuming from it, and never one handed out or reserved this step (its admission
* restores from the slot ahead of the step; the save lands in it after). A tip gets
* no protection beyond its recency: sessions
* are request ids, and a client that rewrites its last message leaves one tip per
* turn that no later turn reaches, while the anchor every turn resumes from is used
* each turn. */
* no protection beyond its recency: sessions are request ids, and a client that
* rewrites its last message leaves one tip per turn that no later turn reaches, while
* the anchor every turn resumes from is used each turn. */
const Ckpt* victim = nullptr;
for (const auto& kvp : ck_by_prefix_) {
if (handed(kvp.first) || reserved(kvp.first)) continue;
+21 -4
View File
@@ -22,6 +22,12 @@ double sinc(double x) {
double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; }
/* PIL's BILINEAR filter: a triangle of support 1. */
double triangle(double x) {
if (x < 0.0) x = -x;
return x < 1.0 ? 1.0 - x : 0.0;
}
/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point
* coefficients. */
struct Axis {
@@ -30,11 +36,11 @@ struct Axis {
std::vector<int> kk; /* [out, ksize] */
};
Axis coeffs(int in_size, int out_size) {
Axis coeffs(int in_size, int out_size, bool bilinear) {
Axis a;
const double scale = (double)in_size / (double)out_size;
double filterscale = scale < 1.0 ? 1.0 : scale;
const double support = 3.0 * filterscale;
const double support = (bilinear ? 1.0 : 3.0) * filterscale;
a.ksize = (int)std::ceil(support) * 2 + 1;
a.bounds.assign((size_t)out_size * 2, 0);
a.kk.assign((size_t)out_size * a.ksize, 0);
@@ -50,7 +56,8 @@ Axis coeffs(int in_size, int out_size) {
xmax -= xmin;
int x = 0;
for (; x < xmax; ++x) {
const double w = lanczos((x + xmin - center + 0.5) * ss);
const double t = (x + xmin - center + 0.5) * ss;
const double w = bilinear ? triangle(t) : lanczos(t);
k[(size_t)x] = w;
ww += w;
}
@@ -80,7 +87,17 @@ inline unsigned muldiv255(unsigned a, unsigned b) {
} /* namespace */
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out);
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
resize_rgba(src, w, h, false, out);
}
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
resize_rgba(src, w, h, true, out);
}
static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out) {
const int iw = src.w, ih = src.h;
/* Image.resize returns a copy at the same size. The premultiplied round trip below is not
* lossless where alpha is below 255. */
@@ -96,7 +113,7 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
pre[i * 4 + 3] = (uint8_t)al;
}
const bool horiz = w != iw, vert = h != ih;
const Axis ax = coeffs(iw, w), ay = coeffs(ih, h);
const Axis ax = coeffs(iw, w, bilinear), ay = coeffs(ih, h, bilinear);
/* the rows the vertical pass reads */
const int y_first = ay.bounds[0];
const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1];
+2
View File
@@ -18,6 +18,8 @@ namespace mm {
/* `src` resized to w x h. */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* The same with PIL's BILINEAR filter (a triangle of support 1, widened when shrinking). */
void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
+109
View File
@@ -46,6 +46,8 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
std::string* why) {
return no_decoder(why);
}
int h264_roundtrip(const Frame&, int32_t, Frame*, std::string* why) { return no_decoder(why); }
bool h264_roundtrip_available() { return false; }
int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
std::string* why) {
return no_decoder(why);
@@ -677,6 +679,113 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample
return RAD_OK;
}
bool h264_roundtrip_available() {
return avcodec_find_encoder_by_name("libx264") && 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. */
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* 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; }
AVCodecContext* ec = avcodec_alloc_context3(enc);
AVCodecContext* dc = avcodec_alloc_context3(dcd);
AVFrame* yuv = av_frame_alloc();
AVFrame* dec = av_frame_alloc();
AVPacket* pkt = av_packet_alloc();
SwsContext* sws = nullptr;
int st = RAD_OK;
auto fail = [&](const char* what, int e) {
*why = std::string(what) + (e < 0 ? " (" + averr(e) + ")" : std::string());
st = e == AVERROR(ENOMEM) ? RAD_E_NOMEM : RAD_E_INVAL;
};
bool got = false;
if (!ec || !dc || !yuv || !dec || !pkt) {
*why = "out of memory";
st = RAD_E_NOMEM;
} else {
ec->width = W;
ec->height = H;
ec->pix_fmt = AV_PIX_FMT_YUV420P;
ec->time_base = AVRational{ 1, 1 };
ec->framerate = AVRational{ 1, 1 };
/* PyAV's codec defaults: as many threads as the machine has, splitting each frame into
* 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);
int e = avcodec_open2(ec, enc, nullptr);
if (e < 0) fail("opening libx264", 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;
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,
nullptr, nullptr, nullptr);
if (!sws) fail("no RGB to yuv420p conversion", 0);
}
if (st == RAD_OK) {
/* The source rows into a padded RGB frame: the scaler reads whole vectors past a tight
* row's end. */
AVFrame* rgb = av_frame_alloc();
if (!rgb) fail("out of memory", AVERROR(ENOMEM));
else {
rgb->format = AV_PIX_FMT_RGB24;
rgb->width = W;
rgb->height = H;
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)
fail("colour conversion failed", 0);
}
av_frame_free(&rgb);
}
}
/* Encode the frame and flush; every packet goes straight to the decoder. */
for (int pass = 0; st == RAD_OK && pass < 2; ++pass) {
yuv->pts = 0;
if ((e = avcodec_send_frame(ec, pass == 0 ? yuv : nullptr)) < 0) { fail("encoding", e); break; }
while (st == RAD_OK && (e = avcodec_receive_packet(ec, pkt)) >= 0) {
if ((e = avcodec_send_packet(dc, pkt)) < 0) fail("decoding", e);
av_packet_unref(pkt);
}
if (st == RAD_OK && e != AVERROR(EAGAIN) && e != AVERROR_EOF) fail("encoding", e);
}
if (st == RAD_OK) avcodec_send_packet(dc, nullptr);
while (st == RAD_OK && (e = avcodec_receive_frame(dc, dec)) >= 0) {
if (!got) {
SwsContext* back = nullptr;
st = to_rgb(dec, &back, out, why);
sws_freeContext(back);
got = st == RAD_OK;
}
av_frame_unref(dec);
}
if (st == RAD_OK && !got) fail("the round trip decoded to no frame", 0);
}
sws_freeContext(sws);
av_packet_free(&pkt);
av_frame_free(&yuv);
av_frame_free(&dec);
avcodec_free_context(&ec);
avcodec_free_context(&dc);
return st;
}
#endif /* RAD_HAVE_FFMPEG */
} /* namespace mm */
+8
View File
@@ -77,5 +77,13 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why);
/* `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. */
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. */
bool h264_roundtrip_available();
} /* namespace mm */
} /* namespace rad */
+10 -3
View File
@@ -376,7 +376,8 @@ public:
RadGeneratorDecl generator{};
struct GenStrings {
std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
tmpl_transparent;
tmpl_transparent, default_negative;
bool has_default_negative = false;
std::vector<double> sigmas;
} gen_str;
bool is_generator() const { return generator.layout != 0; }
@@ -392,6 +393,11 @@ public:
struct VideoGenStrings {
std::string name, tmpl;
std::vector<double> rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */
std::vector<double> refine_rungs;
std::string default_negative;
/* RadVideoGenDecl::decoders, one name each, and their largest frames (0: max_area). */
std::vector<std::string> decoders;
std::vector<int64_t> decoder_max_area;
} vgen_str;
bool is_video_generator() const { return video_gen.max_lanes != 0; }
/* Driven by passes, not token steps: any generator. */
@@ -740,8 +746,9 @@ struct Config {
/* --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),
* served only where the plugin says so. Each changes the model's output slightly, so it is explicit and bf16 is the
* default. No "auto": it would always resolve to bf16 and only add another name. */
* served only where the plugin says so. Each changes the model's output slightly, so it is
* explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add
* another name. */
std::string kv_cache_dtype = "bf16";
int64_t host_pool_mib = 0;
int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */
+9 -2
View File
@@ -113,8 +113,15 @@ int Ctx::prepare() {
RAD_TRY(bind_routing());
RAD_TRY(bind_profiling());
/* Recorded passes need a recording backend, and are off whenever every issue must be seen:
* per-op profile, oracle. */
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_;
* per-op profile, oracle, and a calibration tap. A `gram_accum` sums across passes while its
* plugin counts the rows it has summed in step and writes the Grams once a token target is
* reached; a played pass reissues the accumulation without calling step, so the files would
* hold more rows than their header says and be written late. */
const bool taps = std::any_of(program_->ops.begin(), program_->ops.end(),
[](const OpInfo& o) { return o.op == "gram_accum"; });
tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ && !taps;
if (taps && record_passes_ && tape_supported() && rank_ == 0)
RAD_INFO("recorded passes: off, the program accumulates calibration Grams (gram_accum)");
return RAD_OK;
}
+2
View File
@@ -205,6 +205,8 @@ public:
/* ---------------------------------------------------------- run-phase queries */
const RadBatch* batch() const { return batch_; }
int rank() const { return rank_; }
/* Whether repeated passes are recorded and played back (prepare() says when they are not). */
bool records_passes() const { return tape_on_; }
int world_size() const { return world_size_; }
RadStream stream() const { return stream_; }
Program* program() const { return program_; }
+34 -72
View File
@@ -51,19 +51,10 @@ struct SchedMetrics {
int64_t step_ns = 0;
int64_t step_ns_decode = 0;
/* The single-sequence decode floor, nanoseconds; 0 until a window of eligible steps fills.
* A min over WINDOW MEANS of single-sequence decode steps (see DecodeFloor), not over raw
* brackets -- a raw min latches a degenerate bracket forever. Single-sequence on purpose: a
* decode step at eight sequences is a different measurement, so keying the floor to one row
* keeps a batch arriving from being misread as drift. Scheduler::step_finished feeds DecodeFloor. */
/* The single-sequence decode floor and the most recent window, nanoseconds: both window means
* of single-sequence decode steps (DecodeFloor), 0 until a gated window completes. A decode
* step at more sequences is a different measurement and does not count. */
int64_t step_ns_decode_best = 0;
/* The most recent completed window mean of single-sequence decode steps, nanoseconds; 0 until
* the first gated window completes. The advisory's OTHER side: best() is how fast the engine
* has ever been, recent() is how fast it is now, and both are window means of the same stream
* at the same size -- so they cannot disagree by order statistics the way the engine's floor
* disagreed with the browser's per-poll min (7.7% phantom drift on a flat lane, 2026-10-18).
* Scheduler::step_finished records it. */
int64_t step_ns_decode_recent = 0;
/* Per KV group. `name` points into the Program, which outlives any scrape. */
@@ -147,84 +138,55 @@ struct SchedMetrics {
};
/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best).
*
* A min over RAW step brackets is unbounded below: a decode step issued ahead behind a step with
* long host work (a prefill chunk, or a decode step that saves a KV checkpoint) has its forward
* pass finished before its own bracket opens, so the bracket holds only readback and commit --
* about a millisecond, no GPU work. A min latches that degenerate on the first occurrence and
* never recovers. Measured live 2026-10-18: floor 1.34 ms against a 15.70 ms mean, after which
* the dashboard's restart advice read "heavily drifted, pays back fast" on a healthy engine --
* a systematically wrong advisory, worse than none, because it recommends a restart that cannot
* help.
*
* The fix mirrors the construction the dashboard already proves clean on this lane: a min over
* WINDOW MEANS, not over raw samples. Each full window of single-sequence decode steps
* contributes one mean; a degenerate is diluted by the honest steps sharing its window, so the
* floor tracks the real floor. Two biases on that floor partially cancel: a window MEAN sits
* above the true floor (it averages, so it cannot reach a lone fast step), while min-over-windows
* picks the window with the most degenerates and pulls back down. A simulation of the live lane
* (real ~15.9 ms, true floor ~14.4 ms, degenerate ~1.34 ms) puts the estimate at 14.3 ms median
* at the observed ~1.4% degenerate rate, worst case ~13.6 ms -- within a few percent of the true
* floor, and never the 12x latch of the raw min. The residual can sit slightly BELOW the true
* floor (a degenerate-heavy window), which mildly OVER-reports drift; it is bounded and small,
* not the unbounded latch. kWindow is a structural count of samples to average, not a magic
* threshold a real step could fall below. Scheduler::step_finished feeds it one update per
* single-sequence decode step. */
/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best): a min over
* window means, not over raw step brackets. A decode step issued ahead behind a step with long
* host work (a prefill chunk, a KV checkpoint save) has its forward pass finished before its own
* bracket opens, so the bracket holds only readback and commit, about a tenth of a real step; a
* raw min would latch that forever. Such brackets are rejected before they enter a window, and the
* window mean dilutes what remains. */
struct DecodeFloor {
/* Single-sequence decode steps averaged into one floor candidate. 32 approximates the number
* of decode steps the dashboard's 500 ms poll spans at this lane's step time, so the engine
* floor and the page's own c1 floor are computed over comparable windows. */
/* Steps averaged into one floor candidate: about what the dashboard's 500 ms poll spans at a
* single-sequence step, so the engine's floor and the page's are over comparable windows. */
static constexpr int kWindow = 32;
static constexpr int64_t kHorizon = 8 * kWindow;
void update(int64_t ns) {
/* Reject degenerate brackets BEFORE they enter a window. A decode step issued ahead behind
* a long host commit (a prefill chunk, or a KV checkpoint every 256 tokens) brackets at
* ~9% of a real step; real single-sequence steps bracket at ~96%. The populations are ~10x
* apart, so any threshold between them separates them -- 0.5 is the midpoint of that gap,
* not a value tuned to one distribution. Filtering at the STEP level is essential: at the
* observed ~1.4% rate a degenerate dilutes inside a 32-step window to a mean of ~0.91x,
* which no window-level threshold would catch, and a min over hundreds of windows then
* reliably lands on a degenerate-heavy window ~10% below the true floor.
* No rejection until a window's worth of samples has been accepted, so the running mean is
* never bootstrapped from a degenerate. */
if (accepted_ >= kWindow && ns * 2 < mean_) return;
++accepted_;
mean_ += (ns - mean_) / (double)accepted_;
/* A degenerate bracket is ~0.09 of a real step and a real one ~0.96 of the mean, so half
* the reference separates them. The reference is a running mean over every step, the
* rejected ones included, with a horizon of kHorizon steps: degenerates are rare enough to
* barely move it, and when the real step gets faster (a slow warm-up, a shorter context)
* it follows instead of rejecting every later step. No rejection until a window's worth
* of samples has been seen. */
++seen_;
mean_ += (ns - mean_) / (double)(seen_ < kHorizon ? seen_ : kHorizon);
if (seen_ > kWindow && ns * 2 < mean_) return;
sum_ += ns;
if (++count_ < kWindow) return;
const int64_t mean = sum_ / count_;
/* The FIRST window is recorded by neither side. The rejection gate needs a window's worth
* of accepted samples before it can judge one, so the first window is by construction
* un-gated and can carry degenerates; recording it would let the floor latch a value the
* engine can no longer reach -- the same artifact the gate exists to remove, smuggled in
* through bootstrap. Measured: at a 5% degenerate rate the un-gated first window put the
* floor ~2% below the true floor and it stuck there forever. */
/* The first window ran before the gate could judge and may carry degenerates, so it is
* recorded by neither side. */
if (warmed_) {
if (best_ == 0 || mean < best_) best_ = mean;
recent_ = mean; /* most recent completed window, same size as best_ */
recent_ = mean;
}
warmed_ = true;
sum_ = 0;
count_ = 0;
}
/* The floor: the fastest window mean ever seen. A restart is priced against this. */
/* The fastest window mean seen. */
int64_t best() const { return best_; }
/* The CURRENT speed: the most recent completed window mean, from the SAME stream and window
* size as best(). The advisory compares best() against recent() -- both window means of one
* population -- so the two sides cannot disagree by order statistics the way the engine's
* floor disagreed with the browser's per-poll min (a 7.7% phantom gap on a flat lane,
* 2026-10-18). 0 until the first window completes; the page must not divide by it. */
/* The most recent completed window mean, from the same stream and window size as best();
* 0 until the first gated window completes. */
int64_t recent() const { return recent_; }
private:
int64_t sum_ = 0;
int count_ = 0; /* samples in the window being accumulated */
int64_t best_ = 0;
int64_t recent_ = 0;
bool warmed_ = 0; /* false until one window has completed (the un-gated bootstrap) */
int64_t accepted_ = 0; /* samples accepted across all windows (rejection gate's support) */
double mean_ = 0.0; /* running mean of ACCEPTED steps -- the rejection reference */
int64_t sum_ = 0;
int count_ = 0; /* samples in the window being accumulated */
int64_t best_ = 0;
int64_t recent_ = 0;
bool warmed_ = false; /* one window has completed */
int64_t seen_ = 0; /* samples seen, rejected ones included */
double mean_ = 0.0; /* the rejection reference */
};
} /* namespace rad */
+6 -8
View File
@@ -1599,7 +1599,10 @@ const RadBatch* Scheduler::step() {
/* ------------------------------------------------------------------ media */
bool Scheduler::prefill_continues() const {
std::lock_guard<std::mutex> lk(mu_);
if (stage_rows_ <= 0) return false;
/* Only the step being released has a plan to read. Between a commit and the next step (an
* encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no
* longer holds: a cancel and reap may have released one (#127). */
if (stage_rows_ <= 0 || !step_open_) return false;
/* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
* would be dropped by that step. */
if (interleave_left_ > 0) return false;
@@ -2010,13 +2013,8 @@ void Scheduler::step_finished() {
m_.step_ns += ns;
if (plan_.phase == RAD_PHASE_DECODE) {
m_.step_ns_decode += ns;
/* The single-sequence floor, keyed to the concurrency of THIS step (plan_.n_seq_decode is
* the row count that was just timed, not a later snapshot). A mixed step is excluded by the
* phase gate even when it carries one decode row: its lone row shares the step with a
* prefill chunk and is not the mechanical floor. The estimator is a min over WINDOW MEANS,
* not raw brackets: a decode step issued ahead behind a long host commit has no GPU work
* in its bracket, and a raw min latches that degenerate forever; averaging a window of
* single-row steps first dilutes it. See rad::DecodeFloor. */
/* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step
* never counts: its decode row shares the step with a prefill chunk. */
if (plan_.n_seq_decode == 1) {
decode_floor_.update(ns);
m_.step_ns_decode_best = decode_floor_.best();
+1 -3
View File
@@ -604,9 +604,7 @@ private:
* 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;
bool step_open_ = false;
/* Estimator for the single-sequence decode floor (see rad::DecodeFloor). Replaces a raw min
* over step brackets, which latched a degenerate bracket forever (live defect 2026-10-18:
* 1.16 ms against a 15.55 ms mean). step_finished feeds it each single-sequence decode step. */
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
DecodeFloor decode_floor_;
/* arrival; mu_ held */
+19 -68
View File
@@ -125,10 +125,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["model"] = opt_.model_id;
o["version"] = opt_.version;
o["uptime_s"] = unix_now() - started_at_;
/* How long this process took to come up, measured on this machine. Raw figure: a restart's
* real cost, for whoever is deciding whether one is worth it. 0 before the server listens.
* The page no longer consumes it -- see the note on the decode-step detail line for why the
* payback arithmetic that used to live there was removed. */
/* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */
o["startup_s"] = startup_s_;
o["in_flight"] = in_flight_.load(std::memory_order_relaxed);
o["queue_cap"] = queue_depth_;
@@ -1363,31 +1360,18 @@ for (const k of METRICS) {
* is for is the variation, and the number above it already states the level -- scaled from zero
* every steady state is a flat line on the floor. No variation draws down the middle.
*
* THE ENDS OF THAT RANGE ARE PERCENTILES, not the extremes. On a min/max axis one rare spike
* owns the whole box and the typical variation is squeezed into a couple of pixels: measured over
* real /stats samples, prefill sits at zero on a third of polls and spikes past 4,000 on the rest,
* which leaves its middle band 0.1px of the 15px available -- a flat line for a metric that is
* anything but. Taking the 5th and 95th percentiles and clamping to them gives the ordinary
* movement the height it was being denied (the same samples' middle band rises 1.2x to 3.9x
* depending on the metric). The cost is stated rather than hidden: a spike beyond the 95th now
* draws pinned to the top of the box instead of towering over the line, so the box shows how the
* metric has been behaving and not how bad its worst poll was. The number above still carries the
* level, and the detail line still carries the extremes.
*
* THE INSET IS ONE UNIT, not two and three. The stroke is 1.25 units wide, so a half-unit of
* clearance keeps it off the edge of the box; the extra it used to leave was a fifth of the
* height spent on nothing, and on a 17px box that is the difference between a line that moves
* and one that merely shifts. */
* The ends of the range are the 5th and 95th percentiles, not the extremes: on a min/max axis one
* 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) {
const s = M[key], w = 200, h = 22;
if (vals.length < 3) { s.line.setAttribute("d", ""); return; }
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);
/* WHEN THE PERCENTILES COLLAPSE, fall back to the extremes. If nine tenths of the window holds
* one value, the 5th and 95th land on it and carry nothing -- and a metric that is constant
* apart from rare spikes has those spikes as its ONLY news, so pinning them outside the axis
* would draw a flat line where the old axis at least showed them. */
/* A window that is one value apart from rare spikes puts both percentiles on that value; the
* 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);
@@ -1686,35 +1670,16 @@ function renderRequests(list, poolTokens) {
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
let lastStepMs = null, lastTps = null;
/* THE SINGLE-STREAM FLOOR and the engine's most recent window, shown as two numbers and
* interpreted by nobody. The engine records the fastest single-sequence decode window it has
* measured (step_ns_decode_best) and its most recent one (step_ns_decode_recent); the page states
* both and draws no conclusion. Neither is asked of a human: a typed ruler goes stale and
* mis-advises silently, and a browser meter sees only the steps taken while this tab is open. On
* an engine too old to emit the floor, the page falls back to the fastest single-stream step this
* tab has seen.
*
* THERE IS DELIBERATELY NO RESTART ADVICE HERE, and it was not never-built -- it was built,
* deployed, measured, and removed the same day (2026-10-18). It compared the floor against the
* recent window, called the gap drift, and priced a payback from startup_s. The gap is not drift.
* On a HEALTHY shared lane the floor sat flat at 14.79 ms while the recent window moved between
* 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane
* went idle and ROSE on a fresh short request, so it was neither context length nor engine age.
* The payback formula assumes a restart's improvement is permanent, so acting on it pays the 49 s
* bringup and re-drifts within minutes; the line was telling the operator to restart every 12-19
* minutes forever, for a gain that was never there. What best-vs-recent actually measures is the
* distance between the lane's most favorable moment and its typical one.
*
* A verdict could go back here IF someone first observes the thing none of today's data shows:
* step time rising with ENGINE AGE and STAYING up. Every excursion seen so far was load. The
* full chain, including the estimator that survives this, is in patches/CHANGELOG-SOURCE.md. */
/* The single-stream floor and the engine's most recent window, shown as two numbers with no
* verdict. The engine records the fastest single-sequence decode window it has measured
* (step_ns_decode_best) and its most recent one (step_ns_decode_recent). Their gap is not engine
* drift: on a healthy lane the recent window moves 3-11% above a flat floor with whatever else the
* 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 */
let bestEver = 0; /* the best engine floor ever seen here, across restarts */
try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {}
const bestAt = {}; /* fastest step seen at each concurrency, this process */
function update(s, dt) {
$("ver").textContent = s.version + " · up " + dur(s.uptime_s);
@@ -1734,35 +1699,21 @@ function update(s, dt) {
M.step.u.textContent = st.u;
setMetric("step", lastStepMs, st.n);
/* THE FLOOR, single-stream on both sides of the engine's own measurement. The floor is a
* single-sequence window, so the engine keys it to one row deliberately: a decode step at eight
* sequences is a different measurement, and reading it against a single-sequence floor would
* report a batch arriving as a slowdown. */
/* 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(); }
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;
if (engBestMs > 0 && (bestEver === 0 || engBestMs < bestEver)) {
bestEver = engBestMs;
try { localStorage.setItem("radiance.c1best", String(bestEver)); } catch (e) {}
}
const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0);
/* The two engine figures, stated plainly. Painted every poll: without a verdict there is
* nothing for a fast repaint to make unactionable, and `recent` only moves when a window of 32
* single-sequence steps completes anyway. */
let det = "";
if (floorMs > 0) {
det = "best " + floorMs.toFixed(2) + "ms";
if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms";
}
/* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: ~99% is the fastest the lane has done, anything slower a percentage of it. Keyed by
* concurrency on purpose: a c8 step read against the single-stream floor would report the batch
* arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no
* threshold, no colour: the number is the statement. Capped at ~99 (shown with a tilde): `now` is a ~500 ms poll mean while
* `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the
* recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a
* completed 32-step window, and a sub-window blip is not one. The cap is 99, not 100: a 500 ms window that briefly beats the
* floor is not a sustained record, and 100% would claim a floor the window cannot confirm -- it
* would read as a bug. ~99% says "at your best" without overclaiming. */
/* 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
* floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a
* record the window cannot confirm. */
if (s.running > 0 && lastStepMs != null) {
const k = s.running;
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
+29 -4
View File
@@ -127,11 +127,8 @@ struct SchedMetrics {
* a decode step regardless of load. */
int64_t step_ns = 0;
int64_t step_ns_decode = 0;
/* The fastest single-sequence decode step this process has measured, nanoseconds; 0 until one
* runs. The dashboard reads this instead of asking a human to type a ruler (see the same field
* on rad::SchedMetrics, where it is recorded). */
/* The single-sequence decode floor and most recent window (rad::SchedMetrics). */
int64_t step_ns_decode_best = 0;
/* The most recent completed single-sequence decode window mean; see SchedMetrics. */
int64_t step_ns_decode_recent = 0;
};
@@ -589,7 +586,19 @@ struct ImageGenInfo {
/* The model samples on a schedule of its own and takes no step count (a distilled model). */
bool fixed_schedule = false;
int64_t fixed_steps = 0;
/* Guidance in the model card's terms: with `cfg_original` the scale s means cond + s (cond -
* uncond), off at 0, and the core runs s + 1; otherwise uncond + s (cond - uncond), off at 1. */
double default_cfg = 1.0;
bool cfg_original = false;
/* The negative prompt a guided request gets when it names none; without one it must. */
bool has_default_negative = false;
std::string default_negative;
/* The pictures are not read by the conditioning network: they go to the generator's own
* encoder only (RAD_GEN_LAYOUT_JOINT_STEP). */
bool refs_encoder_only = false;
/* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the
* size multiple; otherwise resized to `ref_area` at its aspect. */
bool ref_shrink_only = false;
};
class IImageGen {
@@ -650,6 +659,22 @@ struct VideoGenInfo {
/* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */
double upscale_max = 0.0;
int64_t upscale_refine = 0;
/* `steps` counts model evaluations rather than sigma grid points (RadVideoGenDecl form 1). */
bool step_evals = false;
/* Guidance (RadVideoGenDecl::guidance): the terms a request may name, their defaults and the
* negative prompt a guided request gets when it names none. */
bool guidance = false;
double guidance_default[8] = {};
std::string default_negative;
/* Image to video: a first frame is taken, after an H.264 round trip at image_crf when > 0. */
bool image_cond = false;
int32_t image_crf = 0;
/* A length head: a request that names no length gets the one the model predicts. */
bool length_head = false;
/* The decoders a request may name, the default first, and each one's largest frame in pixels
* (RadVideoGenDecl::decoders); empty for a model with one. */
std::vector<std::string> decoders;
std::vector<int64_t> decoder_max_area;
};
class IVideoGen {
+92 -31
View File
@@ -9,8 +9,10 @@
* repainted where the mask is transparent; the rest is restored exactly after decoding.
*
* Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale`
* (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule
* (distilled) model accepts only its own step count.
* (guidance, in the model card's terms; `guidance_scale` is the same field under diffusers' name),
* `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule (distilled)
* model accepts only its own step count. A model whose card guides by default does so with its
* own negative prompt unless the request names one or turns guidance off.
*
* Refused: `response_format: url`, since no image is stored to serve later; only b64_json.
*
@@ -77,7 +79,7 @@ json form_value(const std::string& key, const std::string& v) {
if (e && *e == 0 && !v.empty()) return json(x);
return json(v);
}
if (key == "true_cfg_scale") {
if (key == "true_cfg_scale" || key == "guidance_scale") {
char* e = nullptr;
const double x = std::strtod(v.c_str(), &e);
if (e && *e == 0 && !v.empty()) return json(x);
@@ -107,18 +109,34 @@ std::string replace_all(std::string s, const std::string& what, const std::strin
}
/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */
gen::Pixels to_pixels(const mm::FrameRGBA& f) {
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). An RGB model reads the colour
* channels and not the alpha, as PIL's convert("RGB") drops it. */
gen::Pixels to_pixels(const mm::FrameRGBA& f, int ch) {
gen::Pixels p;
p.w = f.w;
p.h = f.h;
p.ch = 4;
p.bf16.resize(f.rgba.size());
for (size_t i = 0; i < f.rgba.size(); ++i)
p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
p.ch = ch;
p.bf16.resize((size_t)f.w * f.h * ch);
for (size_t px = 0; px < (size_t)f.w * f.h; ++px)
for (int c = 0; c < ch; ++c)
p.bf16[px * ch + c] =
rad_f32_to_bf16(2.0f * ((float)f.rgba[px * 4 + c] / 255.0f) - 1.0f);
return p;
}
/* The centred w x h window of a picture (diffusers' resize_mode "crop" after its resize). */
mm::FrameRGBA crop_centre(const mm::FrameRGBA& f, int32_t w, int32_t h) {
mm::FrameRGBA o;
o.w = w;
o.h = h;
o.rgba.resize((size_t)w * h * 4);
const int32_t x0 = (f.w - w) / 2, y0 = (f.h - h) / 2;
for (int32_t y = 0; y < h; ++y)
std::memcpy(&o.rgba[(size_t)y * w * 4], &f.rgba[((size_t)(y0 + y) * f.w + x0) * 4],
(size_t)w * 4);
return o;
}
/* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */
std::vector<uint8_t> on_white(const std::vector<uint8_t>& rgba, int32_t w, int32_t h) {
mm::FrameRGBA f;
@@ -216,6 +234,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
"prompt", "model", "n", "size", "quality", "background", "output_format",
"output_compression", "response_format", "stream", "partial_images", "moderation",
"style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale",
"guidance_scale",
"num_inference_steps", "width", "height",
};
for (auto it = body.begin(); it != body.end(); ++it) {
@@ -274,6 +293,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
if (r.background == "transparent" && r.format == "jpeg")
return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
"webp"), req.peer);
if (r.background == "transparent" && info.pixel_channels < 4)
return error_response(err_bad("background", "this model makes opaque images"), req.peer);
if (num("output_compression", 0, 100, &v) < 0)
return error_response(err_bad("output_compression", "expected an integer in 0..100"),
req.peer);
@@ -323,21 +344,35 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
}
if (str("negative_prompt", &r.negative) < 0)
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
if (!body["true_cfg_scale"].is_number())
return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer);
r.cfg = body["true_cfg_scale"].get<double>();
if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"),
req.peer);
/* The scale in the model card's terms: off at 0 for a card that states it as
* cond + s (cond - uncond), at 1 for uncond + s (cond - uncond). */
const double cfg_off = info.cfg_original ? 0.0 : 1.0;
const char* cfg_key = body.contains("guidance_scale") && !body["guidance_scale"].is_null()
? "guidance_scale" : "true_cfg_scale";
const bool cfg_given = body.contains(cfg_key) && !body[cfg_key].is_null();
if (cfg_given && body.contains("true_cfg_scale") && body.contains("guidance_scale") &&
!body["true_cfg_scale"].is_null())
return error_response(err_bad("guidance_scale", "true_cfg_scale and guidance_scale are "
"the same field; name one"), req.peer);
r.cfg = info.default_cfg;
if (cfg_given) {
if (!body[cfg_key].is_number())
return error_response(err_bad(cfg_key, "expected a number"), req.peer);
r.cfg = body[cfg_key].get<double>();
if (!(r.cfg >= cfg_off && r.cfg <= 30.0))
return error_response(err_bad(cfg_key, "expected a number in " +
std::string(cfg_off > 0 ? "1" : "0") +
"..30"), req.peer);
}
/* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the
* reference pipeline. */
r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
if (r.has_neg && r.negative.empty()) r.negative = " ";
if (r.cfg > 1.0 && !r.has_neg)
return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"),
req.peer);
/* Guidance needs a scale past its off value and a negative prompt: the request's (empty
* becomes " ", as in the reference pipeline), or the model's own. */
const bool guided = r.cfg > cfg_off;
const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null();
r.has_neg = guided && (named_neg || info.has_default_negative);
if (r.has_neg && !named_neg) r.negative = info.default_negative;
else if (r.has_neg && r.negative.empty()) r.negative = " ";
if (guided && !r.has_neg)
return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer);
/* ---- the pictures */
if (edit) {
@@ -372,7 +407,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
* image generated without transparency has only decoder noise in its alpha. */
if (r.background == "auto") {
bool alpha = false;
if (r.format != "jpeg")
if (r.format != "jpeg" && info.pixel_channels >= 4)
for (const mm::FrameRGBA& f : r.images)
for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4)
alpha = f.rgba[i] < kTransparentBelow;
@@ -437,17 +472,40 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
g->steps = r.steps;
g->seed = r.seed;
g->previews = r.previews;
g->cfg = (float)r.cfg;
/* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is
* that at s + 1. */
g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg);
g->has_neg = r.has_neg;
g->ticket = std::make_shared<gen::Ticket>();
std::vector<std::shared_ptr<mm::Item>> items;
const int pch = (int)info.pixel_channels;
for (const mm::FrameRGBA& f : r.images) {
int32_t rw = 0, rh = 0;
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
mm::FrameRGBA rs;
mm::resize_lanczos_rgba(f, rw, rh, &rs);
g->refs.push_back(to_pixels(rs));
if (info.ref_shrink_only) {
/* Shrunk to the reference area only when larger, then cut to the size multiple. */
const double area = (double)f.w * f.h;
if (area > (double)info.ref_area) {
const double k = std::sqrt((double)info.ref_area / area);
rw = std::max<int32_t>(1, (int32_t)(f.w * k));
rh = std::max<int32_t>(1, (int32_t)(f.h * k));
mm::resize_lanczos_rgba(f, rw, rh, &rs);
} else {
rs = f;
}
const int32_t cw = rs.w / mult * mult, ch = rs.h / mult * mult;
if (cw <= 0 || ch <= 0)
return error_response(err_bad("image", "a picture must be at least " +
std::to_string(mult) + " pixels a side"),
req.peer);
if (cw != rs.w || ch != rs.h) rs = crop_centre(rs, cw, ch);
} else {
dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh);
mm::resize_lanczos_rgba(f, rw, rh, &rs);
}
g->refs.push_back(to_pixels(rs, pch));
if (info.refs_encoder_only) continue;
mm::Frame rgb;
mm::composite_white(rs, &rgb);
std::shared_ptr<mm::Item> it;
@@ -465,7 +523,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src);
mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk);
g->inpaint = true;
g->inp_src = to_pixels(src);
g->inp_src = to_pixels(src, pch);
const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls;
g->inp_mask.assign((size_t)lw * lh, 0.0f);
keep_px.assign((size_t)r.w * r.h, 0);
@@ -567,12 +625,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64,
std::string* why) -> int {
std::vector<uint8_t>& px = im.px;
const size_t ch = (size_t)im.ch;
if (!keep_px.empty() && !im.preview)
for (size_t i = 0; i < keep_px.size(); ++i)
if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4);
if (keep_px[i]) std::memcpy(&px[i * ch], &src_px[i * 4], ch);
std::vector<uint8_t> file;
int s;
if (flatten) {
if (ch == 3) {
s = mm::encode_image(px.data(), im.w, im.h, 3, fmt, comp, &file, why);
} else if (flatten) {
const std::vector<uint8_t> rgb = on_white(px, im.w, im.h);
s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why);
} else {
+77 -20
View File
@@ -13,6 +13,7 @@
#include <ctime>
#include <limits>
#include <random>
#include <set>
#include <type_traits>
namespace rad {
@@ -3854,9 +3855,17 @@ json message_item(const std::string& id, const std::string& text, const char* st
{ "content", text.empty() && std::strcmp(status, "in_progress") == 0
? json::array() : json::array({ text_part(text) }) } };
}
json call_item(const ToolCall& tc, const char* status) {
return json{ { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
/* A call to a flattened namespace tool reports its namespace and its own name apart, as the
* Responses API's function_call item does. */
json call_item(const OaiRequest& r, const ToolCall& tc, const char* status) {
json it = { { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id },
{ "name", tc.name }, { "arguments", tc.arguments }, { "status", status } };
auto ns = r.tool_namespace.find(tc.name);
if (ns != r.tool_namespace.end()) {
it["namespace"] = ns->second.first;
it["name"] = ns->second.second;
}
return it;
}
/* The response object, around its output items, with the request fields it echoes. */
@@ -3880,7 +3889,8 @@ json response_object(const OaiRequest& r, const char* status, const json& output
} /* namespace */
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* echo, ApiError* err) {
std::string* echo, ApiError* err,
std::map<std::string, std::pair<std::string, std::string>>* ns) {
json b;
RAD_TRY(parse_request_object(body, lim, &b, err));
auto prev = b.find("previous_response_id");
@@ -3983,11 +3993,14 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
}
msgs.push_back(json{ { "role", role }, { "content", parts } });
} else if (type == "function_call") {
std::string id, name, args = "{}";
std::string id, name, args = "{}", space;
if (!member_str(item, "call_id", "input[].call_id", &id, err) ||
!member_str(item, "name", "input[].name", &name, err) ||
!member_str(item, "arguments", "input[].arguments", &args, err))
!member_str(item, "arguments", "input[].arguments", &args, err) ||
!member_str(item, "namespace", "input[].namespace", &space, err))
return RAD_E_INVAL;
/* A namespaced call, under the name its tool was flattened to below. */
if (!space.empty()) name = space + "__" + name;
json call = { { "id", id }, { "type", "function" },
{ "function", { { "name", name }, { "arguments", args } } } };
json* prev = last_assistant();
@@ -4040,34 +4053,78 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string
}
o["messages"] = std::move(msgs);
/* Function tools only. Built-in tools (web search, file search, computer use) and freeform
* custom tools have no chat-completions counterpart and are left out. */
/* Function tools, and the function tools a namespace groups (Codex sends every MCP server's
* tools that way), flattened to "<namespace>__<name>": the chat path has one flat list, and
* the reply's function_call items report the two apart again (OaiRequest::tool_namespace).
* Built-in tools (web search, file search, computer use) and freeform custom tools have no
* chat-completions counterpart and are left out. */
json echo_tools = json::array();
auto tit = b.find("tools");
if (tit != b.end() && tit->is_array()) {
json tools = json::array();
std::set<std::string> names;
auto add = [&](const json& t, const std::string& space) -> int {
std::string name;
if (!member_str(t, "name", space.empty() ? "tools[].name" : "tools[].tools[].name",
&name, err))
return RAD_E_INVAL;
const std::string flat = space.empty() ? name : space + "__" + name;
if (!names.insert(flat).second) {
*err = err_bad("tools", "two tools are named \"" + flat + "\" (a namespace's tools "
"are offered to the model as <namespace>__<name>)");
return RAD_E_INVAL;
}
json fn = { { "name", flat },
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
if (t.contains("description")) fn["description"] = t.at("description");
tools.push_back(json{ { "type", "function" }, { "function", fn } });
if (!space.empty() && ns) (*ns)[flat] = { space, name };
return RAD_OK;
};
for (const json& t : *tit) {
if (str_or(t, "type") != "function") {
const std::string type = str_or(t, "type");
if (type == "namespace") {
std::string space;
if (!member_str(t, "name", "tools[].name", &space, err)) return RAD_E_INVAL;
if (space.empty()) {
*err = err_bad("tools[].name", "a namespace needs a name");
return RAD_E_INVAL;
}
auto inner = t.find("tools");
if (inner == t.end() || !inner->is_array()) {
*err = err_bad("tools[].tools", "a namespace holds an array of tools");
return RAD_E_INVAL;
}
for (const json& f : *inner) {
if (str_or(f, "type") != "function") {
RAD_DEBUG("responses: tool of type \"%s\" in namespace \"%s\" left out: "
"no chat equivalent", str_or(f, "type", "?").c_str(),
space.c_str());
continue;
}
RAD_TRY(add(f, space));
}
echo_tools.push_back(t);
continue;
}
if (type != "function") {
RAD_DEBUG("responses: tool of type \"%s\" left out: no chat equivalent",
str_or(t, "type", "?").c_str());
continue;
}
std::string name;
if (!member_str(t, "name", "tools[].name", &name, err)) return RAD_E_INVAL;
json fn = { { "name", name },
{ "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } };
if (t.contains("description")) fn["description"] = t.at("description");
tools.push_back(json{ { "type", "function" }, { "function", fn } });
RAD_TRY(add(t, ""));
echo_tools.push_back(t);
}
if (!tools.empty()) o["tools"] = std::move(tools);
}
auto tc = b.find("tool_choice");
if (tc != b.end() && !tc->is_null()) {
std::string type = "auto", name;
std::string type = "auto", name, space;
if (tc->is_object() && (!member_str(*tc, "type", "tool_choice.type", &type, err) ||
!member_str(*tc, "name", "tool_choice.name", &name, err)))
!member_str(*tc, "name", "tool_choice.name", &name, err) ||
!member_str(*tc, "namespace", "tool_choice.namespace", &space, err)))
return RAD_E_INVAL;
if (!space.empty()) name = space + "__" + name;
if (!tc->is_object()) o["tool_choice"] = *tc;
else if (type == "function")
o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } };
@@ -4119,7 +4176,7 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO
out.push_back(reasoning_item(random_id("rs_"), c.msg.reasoning, "completed"));
if (!c.msg.content.empty())
out.push_back(message_item(random_id("msg_"), c.msg.content, "completed"));
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(tc, "completed"));
for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(r, tc, "completed"));
const bool cut = c.finish == Finish::Length;
return response_object(r, cut ? "incomplete" : "completed", out, &u,
cut ? "max_output_tokens" : nullptr).dump();
@@ -4175,7 +4232,7 @@ void ResponsesStream::open(std::string& out, Item k, size_t call) {
const ToolCall& tc = last_.tool_calls[call];
item_id_ = fc_id(tc.id);
event(out, "response.output_item.added",
json{ { "output_index", at }, { "item", call_item(tc, "in_progress") } });
json{ { "output_index", at }, { "item", call_item(*r_, tc, "in_progress") } });
}
}
@@ -4207,7 +4264,7 @@ void ResponsesStream::close(std::string& out) {
const bool cut = finished_ && last_.open_call && call_ + 1 == last_.tool_calls.size();
event(out, "response.function_call_arguments.done",
json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } });
item = call_item(tc, cut ? "incomplete" : "completed");
item = call_item(*r_, tc, cut ? "incomplete" : "completed");
}
event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } });
items_.push_back(std::move(item));
+8 -2
View File
@@ -109,6 +109,10 @@ struct OaiRequest {
/* The Responses API request fields its response object echoes (instructions, tools,
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
std::string echo_json;
/* The Responses API's namespaced function tools, flattened for the chat path: the flattened
* name ("<namespace>__<name>") to its namespace and name, which a function_call item reports
* apart. Empty for the other shapes. */
std::map<std::string, std::pair<std::string, std::string>> tool_namespace;
/* llama-server's native /completion: the generated token ids beside the text. */
bool return_tokens = false;
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
@@ -499,9 +503,11 @@ std::string anthropic_error_body(const ApiError& e);
/* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo`
* holds the request fields the response object repeats. previous_response_id needs server-side
* storage and is refused; non-function tool types have no chat equivalent and are dropped, as
* llama-server does. */
* llama-server does. A namespace's function tools are flattened to "<namespace>__<name>", and
* `*ns` (when given) maps each flattened name back for the reply's function_call items. */
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* echo, ApiError* err);
std::string* echo, ApiError* err,
std::map<std::string, std::pair<std::string, std::string>>* ns = nullptr);
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
+28 -11
View File
@@ -170,7 +170,12 @@ void Server::register_routes() {
router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); });
router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); });
auto responses_tokens = [this](const HttpRequest& q) {
return count_tokens(q, responses_to_chat, ApiShape::OpenAI, "response.input_tokens");
return count_tokens(q,
[](const std::string& b, const OaiLimits& l, std::string* c,
std::string* ec, ApiError* e) {
return responses_to_chat(b, l, c, ec, e);
},
ApiShape::OpenAI, "response.input_tokens");
};
router_.post("/v1/responses/input_tokens", responses_tokens);
router_.post("/responses/input_tokens", responses_tokens);
@@ -210,9 +215,7 @@ static const int64_t kSpareWorkers = 64;
void Server::note_ready(uint64_t begin_ns) {
if (begin_ns == 0) return;
const uint64_t now = rad_mono_ns();
/* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather
* than written as zero: a zero cost would price every restart as free in any payback formula
* that divides by it. */
/* A stamp that is not in the past leaves the figure unset rather than writing a zero. */
if (now <= begin_ns) return;
startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull);
}
@@ -264,20 +267,32 @@ std::vector<std::string> Server::probe_reasoning_efforts() {
l.default_reasoning_effort.clear();
l.reasoning_effort_map.clear();
l.probe = true;
auto takes = [&](const std::string& effort) {
template_default_effort_.clear();
auto render = [&](const std::string& effort, std::string* text) {
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
body += "}";
OaiRequest r;
ApiError e;
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
if (parse_chat_request(body, odeps_, l, &r, &e) < 0) return false;
if (text) *text = r.prompts.empty() ? std::string() : r.prompts[0].text;
return true;
};
/* A render that fails without an effort says nothing about efforts; one that takes a
* nonsense word takes every word. */
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
std::vector<std::string> set;
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
if (takes(w)) set.push_back(w);
std::string plain;
if (!render("", &plain) || render("radiance-probe-not-a-level", nullptr)) return {};
std::vector<std::string> set, same;
for (const char* w : { "low", "medium", "high", "xhigh", "max" }) {
std::string text;
if (!render(w, &text)) continue;
set.push_back(w);
if (text == plain) same.push_back(w);
}
/* The level a request naming none gets: the one level whose render is the same. A template may
* spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or
* none, say nothing. */
if (same.size() == 1) template_default_effort_ = same[0];
lim_.reasoning_efforts = set;
return set;
}
@@ -1548,10 +1563,12 @@ HttpResponse Server::handle_responses(const HttpRequest& req) {
std::string chat, echo;
ApiError err;
OaiRequest r;
if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 ||
std::map<std::string, std::pair<std::string, std::string>> ns;
if (responses_to_chat(req.body, lim_, &chat, &echo, &err, &ns) < 0 ||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
r.shape = ApiShape::Responses;
r.tool_namespace = std::move(ns);
r.id = random_id("resp_");
r.echo_json = std::move(echo);
return serve(req, r);
+6 -2
View File
@@ -181,6 +181,9 @@ public:
* also takes a nonsense word it takes any word, and the result is empty. Used to refuse words
* outside the set and for /server_info; called once, before run(). */
std::vector<std::string> probe_reasoning_efforts();
/* The effort the template applies to a request that names none, found by the probe above as
* the one whose render is the same; "" when none matches or the probe found no set. */
const std::string& template_default_effort() const { return template_default_effort_; }
/* Renders each --reasoning-effort-map target as a request's effort. Empty when the template
* takes all of them; otherwise the first refusal, naming the target. */
std::string check_reasoning_effort_map() const;
@@ -198,6 +201,7 @@ public:
void note_ready(uint64_t begin_ns);
private:
std::string template_default_effort_;
struct Generation;
struct TranscriptionJob; /* speech.cpp */
struct RealtimeSession; /* realtime.cpp */
@@ -357,8 +361,8 @@ private:
std::atomic<int64_t> speech_sessions_{0};
std::atomic<bool> stopping_{false};
int64_t started_at_ = 0;
/* Seconds from the top of Engine::start() to the moment the server began listening -- the
* cost of a restart, measured on this machine rather than guessed. 0 until note_ready(). */
/* Seconds from the top of Engine::start() to the moment the server began listening; 0 until
* note_ready(). */
int64_t startup_s_ = 0;
/* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the
+212 -27
View File
@@ -15,8 +15,19 @@
* (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or
* `short_edge`), the area capped at the model's largest, both sides rounded to the multiple.
* A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next.
* Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are
* refused.
* A model with a length head (LTX-2.5's duration head) chooses the length of a request that names
* none, or says `"seconds": "auto"`; the video object reports it once chosen. A model with more
* than one decoder takes `decoder`, one of their names (LTX-2.5: `vae`, the default, or
* `diffusion`).
* A model that can start from a picture takes OpenAI's `input_reference`, a file in the form or a
* data URL (a string or {image_url}) in JSON, as the video's first frame, prepared as the model's
* pipeline prepares it: an H.264 round trip at the model's quality, then a bilinear resize to the
* size the first steps run at. Non-empty `conditions` are refused.
*
* A guided model takes `negative_prompt` and its guidance terms, each the model's default when
* absent: `guidance_scale`, `stg_scale`, `modality_scale` and `guidance_rescale` for the video,
* the same with `audio_` in front for the soundtrack. A scale of 1 turns that modality's
* unconditional branch off; the negative prompt is the model's own unless named.
*
* A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
@@ -31,6 +42,7 @@
#include "oai.h"
#include "gen/video.h"
#include "mm/imaging.h"
#include "mm/media.h"
#include "mm/mp4.h"
#include "rad_internal.h"
@@ -40,6 +52,7 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <ctime>
#include <random>
#include <thread>
@@ -66,12 +79,24 @@ struct Server::VideoJob {
double upscale = 0.0;
int32_t refine = 0;
std::string upscale_from;
/* A guided model's terms as resolved against its defaults, the negative prompt when a scale
* used it, and whether the video started from a picture. */
bool guided = false;
double guidance[8] = {};
std::string negative;
bool has_negative = false;
bool from_image = false;
std::string decoder; /* a decoder the request named other than the default */
int32_t w = 0, h = 0;
bool worker_done = false; /* its thread has nothing left to do but return */
};
namespace {
/* The largest picture `input_reference` may decode to, which bounds the memory a request can make
* the server allocate before the resize. */
constexpr int64_t kMaxRefPixels = (int64_t)1 << 26;
std::string new_video_id() {
static const char* hex = "0123456789abcdef";
std::random_device rd;
@@ -130,11 +155,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
/* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form,
* since it may carry a file). */
json body = json::object();
std::vector<uint8_t> ref_bytes;
bool has_ref = false;
if (!req.form.empty()) {
for (const FormPart& p : req.form) {
if (p.name == "input_reference")
return error_response(err_unsupported("input_reference", "this server makes video "
"from text only"), req.peer);
if (p.name == "input_reference" && !p.filename.empty()) {
ref_bytes.assign(p.data.begin(), p.data.end());
has_ref = true;
continue;
}
if (!p.filename.empty())
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
@@ -154,6 +183,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
static const char* kKnown[] = {
"model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps",
"task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps",
"negative_prompt", "decoder",
/* RadVideoGenBatch::guidance_h's order */
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
};
for (auto it = body.begin(); it != body.end(); ++it) {
bool known = false;
@@ -178,12 +211,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
body["prompt"].get<std::string>().find_first_not_of(" \t\r\n") == std::string::npos)
return bad("prompt", "the prompt is required, as a non-empty string");
const std::string prompt = body["prompt"].get<std::string>();
if (has(body, "input_reference"))
return error_response(err_unsupported("input_reference", "this server makes video from "
if (has(body, "input_reference")) {
/* JSON: a data URL, as a string or an image_url object. */
const json& v = body["input_reference"];
std::string u;
if (v.is_string()) u = v.get<std::string>();
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_string())
u = v["image_url"].get<std::string>();
else if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() &&
v["image_url"].contains("url") && v["image_url"]["url"].is_string())
u = v["image_url"]["url"].get<std::string>();
else
return bad("input_reference", "a picture is a file, a data: URL, or an object with an "
"image_url");
ApiError err;
if (decode_media_url(u, "input_reference", &ref_bytes, &err) < 0)
return error_response(err, req.peer);
has_ref = true;
}
if (has_ref && !info.image_cond)
return error_response(err_unsupported("input_reference", "this model makes video from "
"text only"), req.peer);
if (has(body, "task") && (!body["task"].is_string() || body["task"].get<std::string>() != "t2va")) {
ApiError e = err_unsupported("task", "this server makes video from text: t2va");
e.supported = { "t2va" };
const std::string task_want = has_ref ? "i2va" : "t2va";
if (has(body, "task") && (!body["task"].is_string() ||
body["task"].get<std::string>() != task_want)) {
ApiError e = err_unsupported("task", has_ref ? "a video from a picture is i2va"
: "this request makes video from text: t2va");
e.supported = { task_want };
return error_response(e, req.peer);
}
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
@@ -250,7 +304,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds");
if (has_sec && has_dur)
return bad("seconds", "give seconds or target's duration_seconds, not both");
if (has_sec || has_dur) {
/* A model with a length head chooses the length of a request that names none, or `auto`. */
const bool auto_len = info.length_head &&
(!(has_sec || has_dur) ||
(has_sec && body["seconds"].is_string() && body["seconds"].get<std::string>() == "auto"));
if (auto_len) {
chunks = 0;
} else if (has_sec || has_dur) {
double sec = 0;
if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0))
return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds");
@@ -263,26 +323,81 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
"this model makes " + rad::fmt("%.2f", min_s) + " to " +
rad::fmt("%.2f", max_s) + " seconds");
}
const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail;
/* The length the job reports until the model has chosen one. */
const int64_t frames =
info.frames_per_chunk * (chunks > 0 ? chunks : info.default_chunks) + info.frames_tail;
std::unique_ptr<gen::VideoRequest> r = std::make_unique<gen::VideoRequest>();
r->width = (int32_t)W;
r->height = (int32_t)H;
r->chunks = (int32_t)chunks;
/* ---- the decoder, by name, the model's first when absent */
std::string decoder;
if (has(body, "decoder")) {
if (!body["decoder"].is_string())
return bad("decoder", "the decoder is a name");
decoder = body["decoder"].get<std::string>();
std::string names;
int32_t idx = -1;
for (size_t i = 0; i < info.decoders.size(); ++i) {
names += (i ? ", " : "") + info.decoders[i];
if (info.decoders[i] == decoder) idx = (int32_t)i;
}
if (idx < 0)
return bad("decoder", info.decoders.empty()
? std::string("this model has one decoder and takes no name")
: "this model decodes with " + names);
if (W * H > info.decoder_max_area[(size_t)idx])
return bad("decoder", "the " + decoder + " decoder makes frames of " +
std::to_string(info.decoder_max_area[(size_t)idx]) +
" pixels at most");
r->decoder = idx;
if (idx == 0) decoder.clear();
}
if (has(body, "num_inference_steps")) {
double v = 0;
const char* unit = info.step_evals ? " model evaluations"
: " sigma grid points, the last one 0";
const int64_t lo = info.step_evals ? 1 : 2;
if (info.fixed_steps && (!number(body["num_inference_steps"], &v) ||
v != (double)info.max_steps))
return bad("num_inference_steps",
"this model runs the schedule it was trained on: " +
std::to_string(info.max_steps) + " sigma grid points, the last one 0");
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 ||
std::to_string(info.max_steps) + unit);
if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < lo ||
v > (double)info.max_steps)
return bad("num_inference_steps", "expected an integer in 2.." +
std::to_string(info.max_steps) +
" (sigma grid points, the last one 0)");
return bad("num_inference_steps", "expected an integer in " + std::to_string(lo) +
".." + std::to_string(info.max_steps) + " (" +
(unit + 1) + ")");
r->steps = (int32_t)v;
}
/* ---- guidance */
static const char* kGuide[8] = {
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale",
};
for (int i = 0; i < 8; ++i) {
if (!has(body, kGuide[i])) continue;
if (!info.guidance)
return error_response(err_unsupported(kGuide[i], "this model takes no guidance"),
req.peer);
double v = 0;
const bool rescale = i % 4 == 3;
if (!number(body[kGuide[i]], &v) || !(v >= 0.0) || v > (rescale ? 1.0 : 100.0))
return bad(kGuide[i], rescale ? "expected a number from 0 to 1"
: "expected a number from 0 to 100");
r->guidance[i] = v;
}
std::string negative = info.default_negative;
if (has(body, "negative_prompt")) {
if (!info.guidance)
return error_response(err_unsupported("negative_prompt", "this model takes no "
"guidance"), req.peer);
if (!body["negative_prompt"].is_string())
return bad("negative_prompt", "expected a string");
negative = body["negative_prompt"].get<std::string>();
r->has_neg = true;
}
if (has(body, "latent_upscale")) {
double v = 0;
if (!(info.upscale_max > 0.0))
@@ -320,18 +435,65 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
static const std::string kSlot = "{prompt}";
const std::string& t = info.tmpl;
const size_t p = t.find(kSlot);
auto put = [&](const std::string& s, bool special) {
if (s.empty()) return;
const auto ids = deps_.tok->encode(s, false, special);
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
auto render = [&](const std::string& text, std::vector<int32_t>* out) {
auto put = [&](const std::string& s, bool special) {
if (s.empty()) return;
const auto ids = deps_.tok->encode(s, false, special);
out->insert(out->end(), ids.begin(), ids.end());
};
put(t.substr(0, p), true);
put(text, false);
put(t.substr(p + kSlot.size()), true);
};
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
render(prompt, &r->tokens);
if ((int64_t)r->tokens.size() > info.max_text)
return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) +
" tokens; this model takes at most " +
std::to_string(info.max_text));
if (info.guidance) {
render(negative, &r->neg_tokens);
if ((int64_t)r->neg_tokens.size() > info.max_text)
return bad("negative_prompt", "the negative prompt is " +
std::to_string(r->neg_tokens.size()) +
" tokens; this model takes at most " +
std::to_string(info.max_text));
}
}
/* ---- the first frame, at the size the first steps run at */
if (has_ref) {
int32_t fw = r->width, fh = r->height;
if (r->upscale > 1.0) {
RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */
geo.size_multiple = info.size_multiple;
gen::video_small_size(geo, r->width, r->height, r->upscale, &fw, &fh);
}
mm::Frame f;
std::string why;
if (mm::decode_image(ref_bytes.data(), ref_bytes.size(), kMaxRefPixels, &f, &why) < 0)
return bad("input_reference", "the picture could not be read: " + why);
if (info.image_crf > 0) {
mm::Frame rt;
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"; }
return error_response(err, req.peer);
}
f = std::move(rt);
}
mm::FrameRGBA a, sized;
a.w = f.w;
a.h = f.h;
a.rgba.resize((size_t)f.w * f.h * 4);
for (size_t i = 0, n = (size_t)f.w * f.h; i < n; ++i) {
std::memcpy(&a.rgba[4 * i], &f.rgb[3 * i], 3);
a.rgba[4 * i + 3] = 255;
}
mm::resize_bilinear_rgba(a, fw, fh, &sized);
r->image.resize((size_t)fw * fh * 3);
for (size_t i = 0, n = (size_t)fw * fh; i < n; ++i)
std::memcpy(&r->image[3 * i], &sized.rgba[4 * i], 3);
}
/* ---- admitted and queued: the job holds its place until its file is written */
@@ -340,7 +502,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->id = new_video_id();
j->model = opt_.model_id;
j->prompt = prompt;
j->seconds = rad::fmt("%.2f", (double)frames / fps);
j->seconds = auto_len ? std::string("auto") : rad::fmt("%.2f", (double)frames / fps);
j->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
@@ -348,6 +510,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
r->ticket = j->ticket;
const int64_t n_tok = (int64_t)r->tokens.size();
const int32_t steps = r->steps;
j->guided = info.guidance;
for (int i = 0; i < 8; ++i)
j->guidance[i] = std::isnan(r->guidance[i]) ? info.guidance_default[i] : r->guidance[i];
j->has_negative = info.guidance && (j->guidance[0] != 1.0 || j->guidance[4] != 1.0);
if (j->has_negative) j->negative = negative;
j->from_image = !r->image.empty();
j->decoder = decoder;
const double upscale = r->upscale;
{
std::string w;
@@ -365,8 +534,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->refine = tk.refine;
j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height);
}
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s, seed=%llu",
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
RAD_INFO("video %s: %s, %s, %lld prompt tokens, %d steps%s, seed=%llu",
j->id.c_str(), j->size.c_str(),
auto_len ? "the length the model chooses"
: rad::fmt("%lld frames (%s s)", (long long)frames, j->seconds.c_str()).c_str(),
(long long)n_tok, steps > 0 ? steps : (int)tk.steps,
tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)",
(int)(tk.steps - tk.refine), (int)tk.small_width,
@@ -406,6 +577,9 @@ void Server::video_work(std::shared_ptr<VideoJob> j) {
std::lock_guard<std::mutex> lk(videos_m_);
j->status = "in_progress";
j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0;
} else if (e.kind == gen::VideoEvent::LENGTH) {
std::lock_guard<std::mutex> lk(videos_m_);
j->seconds = rad::fmt("%.2f", (double)e.n * info.fps_den / info.fps_num);
} else if (e.kind == gen::VideoEvent::AUDIO) {
if (t.channels > 0)
st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why);
@@ -530,6 +704,17 @@ json Server::video_json(const VideoJob& j) {
o["upscale_refine_steps"] = j.refine;
o["upscale_from"] = j.upscale_from;
}
if (j.guided) {
static const char* kGuide[8] = {
"guidance_scale", "stg_scale", "modality_scale", "guidance_rescale",
"audio_guidance_scale", "audio_stg_scale", "audio_modality_scale",
"audio_guidance_rescale",
};
for (int i = 0; i < 8; ++i) o[kGuide[i]] = j.guidance[i];
if (j.has_negative) o["negative_prompt"] = j.negative;
}
if (j.from_image) o["input_reference"] = true;
if (!j.decoder.empty()) o["decoder"] = j.decoder;
o["remixed_from_video_id"] = nullptr;
if (j.failed) {
json e;
+75 -3
View File
@@ -10,6 +10,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <atomic>
#include <cstdlib>
namespace rad {
@@ -130,6 +131,54 @@ static size_t json_depth(const ojson& root) {
return deepest;
}
/* The conversation with every system message merged, in order, into one at its head, or false
* when that is the conversation already (none, or one leading) or a system message carries more
* than text. The Chat Completions API places no constraint on system messages, while many
* templates raise unless there is exactly one, first (#137). */
static bool lead_system(const ojson& messages, ojson* out) {
if (!messages.is_array()) return false;
std::string text;
size_t n_sys = 0;
bool first = false;
for (size_t i = 0; i < messages.size(); ++i) {
const ojson& m = messages[i];
if (!m.is_object() || m.value("role", "") != "system") continue;
if (i == 0) first = true;
std::string t;
const auto c = m.find("content");
if (c != m.end() && c->is_string()) {
t = c->get<std::string>();
} else if (c != m.end() && c->is_array()) {
for (const ojson& part : *c) {
if (!part.is_object() || part.value("type", "") != "text" ||
!part.contains("text") || !part.at("text").is_string())
return false;
t += part.at("text").get<std::string>();
}
} else if (c != m.end() && !c->is_null()) {
return false;
}
if (n_sys++ && !text.empty() && !t.empty()) text += "\n\n";
text += t;
}
if (n_sys == 0 || (n_sys == 1 && first)) return false;
*out = ojson::array();
out->push_back(ojson{ { "role", "system" }, { "content", text } });
for (const ojson& m : messages)
if (!m.is_object() || m.value("role", "") != "system") out->push_back(m);
return true;
}
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
* about parser generation, which the render's failure is not. */
static std::string template_words(const char* what) {
static const char kWrap[] = "Unable to generate parser for this template. Automatic parser "
"generation failed: ";
std::string w = what ? what : "";
if (w.compare(0, sizeof kWrap - 1, kWrap) == 0) w.erase(0, sizeof kWrap - 1);
return w;
}
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
ChatPrompt* out) const {
if (!ready()) {
@@ -190,9 +239,32 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
try {
p = common_chat_templates_apply(impl_->tmpls.get(), in);
} catch (const std::exception& e) {
if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what());
out->error = e.what();
return RAD_E_UNSUPPORTED;
/* A template that takes one system message, first, refuses a conversation that has
* another or has it later, which the API allows: it is rendered once more with them
* merged into one at the head. Anything else the template refuses is the request's. */
ojson merged;
bool served = false;
if (lead_system(messages, &merged)) {
try {
in.messages = common_chat_msgs_parse_oaicompat(merged);
p = common_chat_templates_apply(impl_->tmpls.get(), in);
served = true;
static std::atomic<bool> said{ false };
if (!opt.quiet && !said.exchange(true))
RAD_WARN("chat: the model's chat template refuses system messages after the "
"first (%s); such a conversation is rendered with its system "
"messages merged, in order, into one at the head. Said once.",
template_words(e.what()).c_str());
} catch (const std::exception&) {
}
}
if (!served) {
const std::string w = template_words(e.what());
if (!opt.quiet) RAD_WARN("chat: the model's chat template refused the request: %s",
w.c_str());
out->error = "the model's chat template refused this conversation: " + w;
return RAD_E_INVAL;
}
}
out->prompt = std::move(p.prompt);
+14 -3
View File
@@ -72,11 +72,22 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
const char* base = std::strrchr(file, '/');
base = base ? base + 1 : file;
char msg[4096];
va_list ap;
/* A line longer than the stack buffer is formatted again in full: a trace row of many values
* (RADIANCE_DUMP_HEAD) was cut at 4 KiB without a mark (#113). */
char buf[4096];
std::string big;
va_list ap, ap2;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_copy(ap2, ap);
const int n = vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
if (n >= (int)sizeof buf) {
big.resize((size_t)n + 1);
vsnprintf(big.data(), big.size(), fmt, ap2);
big.resize((size_t)n);
}
va_end(ap2);
const char* msg = big.empty() ? buf : big.c_str();
const char* col = level_colour(l);
const char* rst = col[0] ? "\033[0m" : "";