PIN ref2va: verified device differential + ref-count gate (revert anchor)

Ref2VA ref-image conditioning verified on-device: ref step runs all steps no
fault; output differs ref-present vs ref-absent (by log). 6-9 images rejected
cleanly at submit (no engine crash). Merged-cell modulation (<=9) tracked next.
NOTE: placeholder author -- re-author before any push. Do NOT push this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-19 12:04:47 -05:00
1 parent 816e24bd46
commit 490d4c604a
73 files changed
+16484 -432

No files matched your search

+15
View File
@@ -284,6 +284,21 @@ VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) {
return ap ? ap->arch_video_positions : nullptr;
}
VideoSegsFn rad_tools_video_segs(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_segs : nullptr;
}
VideoPackFn rad_tools_video_pack(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_pack : nullptr;
}
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_encode_geom : nullptr;
}
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_audio_format) return nullptr;
+16
View File
@@ -99,6 +99,22 @@ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::s
using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins);
/* The architecture plugin's video segment boundary table (rad_arch_video_segs), or null when it
* exports none -- the video driver then stages the plain table itself. */
using VideoSegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t);
VideoSegsFn rad_tools_video_segs(const LoadedPlugins& plugins);
/* The architecture plugin's reference-aware sequence layout (rad_arch_video_pack), or null
* when it exports none -- the driver then refuses requests carrying VAE references. */
using VideoPackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t);
VideoPackFn rad_tools_video_pack(const LoadedPlugins& plugins);
/* The architecture plugin's encode-pass geometry (rad_arch_encode_geom), or null when it
* exports none -- the driver then runs no encode pass. */
using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t);
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& plugins);
/* Run declare.
*
* `also` declares into the same builder after the architecture plugin, which is how the sampler
+13 -1
View File
@@ -1516,7 +1516,9 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::VideoDriver>();
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio));
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio,
rad_tools_video_segs(plugins_), rad_tools_video_pack(plugins_),
rad_tools_encode_geom(plugins_)));
vid_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
@@ -2498,6 +2500,16 @@ int Engine::run_server() {
in.upscale_max = vd.upscale_max;
in.upscale_refine = vd.upscale_refine;
in.max_lanes = vd.max_lanes;
in.max_ref_images = vd.max_ref_images;
in.max_ref_videos = vd.max_ref_videos;
in.max_ref_audios = vd.max_ref_audios;
in.encodes = vd.encodes;
in.max_enc_frames = vd.max_enc_frames;
in.max_enc_side = vd.max_enc_side;
in.max_enc_samples = vd.max_enc_samples;
in.enc_ratio = vd.enc_ratio;
/* A plugin that declares no ceilings leaves all three 0, and the server then serves
* ref2va as unimplemented — which is right until the generator can consume the bytes. */
video_bridge.drv = vid_gen_;
d.videos = &video_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
+11 -1
View File
@@ -952,7 +952,17 @@ int Engine::declare() {
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a video generator: a step's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
/* `auto` is left to the vision rule below, which keys on the container's
* `radiance.encoder`: a container converted with a vision tower's weights (a ref2va
* conditioning checkpoint) serves reference media through it, and one converted
* without them stays text-only. A video generator that carries no tower pays
* nothing for this: the rule resolves to 0 exactly as this branch used to. */
if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) {
cfg_.mm_max_patches = pb.gen_patches;
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
"a video generator: every reference media patch of one conditioning, "
"the pass size the plugin states");
}
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0) {
+285
View File
@@ -1249,6 +1249,291 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
return RAD_OK;
}
/* PEFT exports wrap HF module paths in the name of the net the adapter trained: ai-toolkit spells
* a DiT module `diffusion_model.<path>`, diffusers' wrappers `transformer.` or `unet.`. */
static const char* const kLoraPrefixes[] = { "diffusion_model.", "transformer.", "unet." };
/* One `modules` rule of the map: the module pattern split at its single `*`, and the target
* patterns into which the matched run is substituted, in B-row order. */
struct LoraRule {
bool star = false;
std::string pre, suf;
std::vector<std::string> targets;
bool match(const std::string& m, std::string* tok) const {
if (!star) {
if (m != pre) return false;
tok->clear();
return true;
}
if (m.size() < pre.size() + suf.size() || m.compare(0, pre.size(), pre) != 0) return false;
if (m.compare(m.size() - suf.size(), suf.size(), suf) != 0) return false;
*tok = m.substr(pre.size(), m.size() - pre.size() - suf.size());
return !tok->empty();
}
};
/* Read the map file: {"strip": [...], "modules": {"<pat>": ["<t>", ...], ...}}. The module
* order is preserved (an nlohmann object keeps insertion order), so the first rule whose
* pattern matches a module wins. */
static int lora_map_read(const std::string& file, std::vector<std::string>* strip,
std::vector<LoraRule>* rules) {
std::ifstream f(file);
if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; }
nlohmann::ordered_json j;
try {
j = nlohmann::ordered_json::parse(f);
} catch (const std::exception& e) {
RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what());
return RAD_E_FORMAT;
}
if (!j.is_object()) { RAD_ERR("lora: --lora-map %s is not a JSON object", file.c_str());
return RAD_E_FORMAT; }
if (j.contains("strip")) {
if (!j["strip"].is_array()) { RAD_ERR("lora: --lora-map 'strip' is not a list");
return RAD_E_FORMAT; }
for (const auto& s : j["strip"]) {
if (!s.is_string()) { RAD_ERR("lora: --lora-map 'strip' holds a non-string");
return RAD_E_FORMAT; }
strip->push_back(s.get<std::string>());
}
}
if (!j.contains("modules") || !j["modules"].is_object()) {
RAD_ERR("lora: --lora-map %s has no 'modules' object", file.c_str());
return RAD_E_FORMAT;
}
for (const auto& [pat, t] : j["modules"].items()) {
if (!t.is_array() || t.empty()) {
RAD_ERR("lora: --lora-map rule '%s' is not a non-empty list", pat.c_str());
return RAD_E_FORMAT;
}
const size_t star = pat.find('*');
LoraRule r;
r.star = star != std::string::npos;
r.pre = r.star ? pat.substr(0, star) : pat;
r.suf = r.star ? pat.substr(star + 1) : "";
for (const auto& x : t) {
if (!x.is_string()) {
RAD_ERR("lora: --lora-map rule '%s' holds a non-string target", pat.c_str());
return RAD_E_FORMAT;
}
r.targets.push_back(x.get<std::string>());
}
rules->push_back(std::move(r));
}
return RAD_OK;
}
int Checkpoint::add_lora(const std::string& path, double strength,
std::vector<std::string>* merged, const std::string* map_json) {
if (kind_ != SafeT) {
RAD_ERR("lora: an adapter merges into a safetensors source; %s is not one", path_.c_str());
return RAD_E_UNSUPPORTED;
}
if (import_ != Import::None) {
RAD_ERR("lora: this checkpoint ships its weights packed by a quantiser; an adapter merges "
"into the plain tensors its training saw, not into the codes");
return RAD_E_UNSUPPORTED;
}
std::vector<std::string> files;
std::error_code ec;
if (std::filesystem::is_directory(path, ec)) {
for (const auto& e : std::filesystem::directory_iterator(path, ec))
if (e.path().extension() == ".safetensors") files.push_back(e.path().string());
std::sort(files.begin(), files.end());
} else
files.push_back(path);
if (files.empty()) {
RAD_ERR("lora: %s holds no .safetensors file", path.c_str());
return RAD_E_NOTFOUND;
}
/* The module lookup strips wrapper prefixes: the map's first, then the builtin ones. */
std::vector<std::string> strips;
std::vector<LoraRule> rules;
if (map_json && lora_map_read(*map_json, &strips, &rules) < 0) return RAD_E_FORMAT;
for (const char* pre : kLoraPrefixes) strips.push_back(pre);
/* One pair's A/B/alpha, by module; `module` keeps the wrapper prefix, so the lookup below
* strips it. */
struct Pair { std::string module; const StTensor *a = nullptr, *b = nullptr, *al = nullptr; };
int n_merged = 0;
for (const std::string& f : files) {
SafeTensorsFile st;
if (st.open(f) != RAD_OK) return RAD_E_FORMAT;
std::vector<Pair> pairs;
std::map<std::string, size_t> by_module;
for (const StTensor& t : st.tensors()) {
if (t.name.size() > 12 && t.name.compare(t.name.size() - 12, 12, ".dora.scalar") == 0) {
RAD_ERR("lora: '%s' is a DoRA adapter; only plain LoRA merges (a magnitude vector "
"has no place in a weight merge)", t.name.c_str());
return RAD_E_UNSUPPORTED;
}
const char* suf = nullptr;
if (t.name.size() > 14 && t.name.compare(t.name.size() - 14, 14, ".lora_A.weight") == 0)
suf = ".lora_A.weight";
else if (t.name.size() > 18 &&
t.name.compare(t.name.size() - 18, 18, ".lora_down.weight") == 0)
suf = ".lora_down.weight";
if (suf) {
Pair p;
p.module = t.name.substr(0, t.name.size() - std::strlen(suf));
p.a = &t;
by_module[p.module] = pairs.size();
pairs.push_back(std::move(p));
} else if (t.name.size() > 14 &&
t.name.compare(t.name.size() - 14, 14, ".lora_B.weight") == 0) {
auto it = by_module.find(t.name.substr(0, t.name.size() - 14));
if (it != by_module.end()) pairs[it->second].b = &t;
} else if (t.name.size() > 6 &&
t.name.compare(t.name.size() - 6, 6, ".alpha") == 0) {
auto it = by_module.find(t.name.substr(0, t.name.size() - 6));
if (it != by_module.end()) pairs[it->second].al = &t;
}
}
if (pairs.empty()) {
RAD_ERR("lora: %s holds no .lora_A.weight / .lora_down.weight tensors", f.c_str());
return RAD_E_NOTFOUND;
}
for (Pair& p : pairs) {
if (!p.b) {
RAD_ERR("lora: '%s' ships its A but no B", p.module.c_str());
return RAD_E_FORMAT;
}
/* The targets, in merge order: `<module>.weight`, then the same under each
* prefix-stripped spelling (the module never carries its `.weight` -- PEFT names the
* module, the target adds it), then the first map rule the stripped module matches,
* whose target patterns name one or several tensors the fused module was trained as.
* The first spelling the checkpoint holds wins. */
std::string norm = p.module;
for (const std::string& s : strips)
if (norm.size() > s.size() && norm.compare(0, s.size(), s) == 0) {
norm.erase(0, s.size());
break;
}
std::vector<const SrcTensor*> tg;
if (const SrcTensor* W = find(p.module + ".weight")) tg.push_back(W);
if (tg.empty() && norm != p.module)
if (const SrcTensor* W = find(norm + ".weight")) tg.push_back(W);
for (const LoraRule& ru : rules) {
std::string tok;
if (!ru.match(norm, &tok)) continue;
for (const std::string& pat : ru.targets) {
std::string nm = pat;
const size_t star = nm.find('*');
if (star != std::string::npos) nm.replace(star, 1, tok);
const SrcTensor* W = find(nm);
if (!W) {
RAD_ERR("lora: the map maps '%s' onto '%s', which this checkpoint does "
"not ship", p.module.c_str(), nm.c_str());
return RAD_E_NOTFOUND;
}
tg.push_back(W);
}
break;
}
if (tg.empty()) {
RAD_ERR("lora: '%s' names a module this checkpoint does not ship as "
"'<module>.weight' (nor stripped of a known wrapper prefix)%s",
p.module.c_str(),
map_json ? " and no --lora-map rule matches it" : "");
return RAD_E_NOTFOUND;
}
const StTensor& A = *p.a;
const StTensor& B = *p.b;
if (A.shape.size() != 2 || B.shape.size() != 2 || A.shape[0] <= 0 ||
A.shape[0] != B.shape[1]) {
RAD_ERR("lora: '%s' is not a rank-%lld pair of matrices: [a %lld x %lld, "
"b %lld x %lld]",
p.module.c_str(), (long long)A.shape[0], (long long)A.shape[0],
(long long)A.shape[1], (long long)B.shape[0], (long long)B.shape[1]);
return RAD_E_FORMAT;
}
const auto plain = [](uint32_t d) {
return d == RAD_BF16 || d == RAD_F16 || d == RAD_F32;
};
if (!plain(A.dtype) || !plain(B.dtype)) {
RAD_ERR("lora: '%s' ships A/B in dtypes the merge cannot read", p.module.c_str());
return RAD_E_UNSUPPORTED;
}
const int64_t K = A.shape[1], r = A.shape[0];
int64_t rows = 0;
for (const SrcTensor* W : tg) {
if (W->gptq_bits || W->ct_group || W->rad_dtype == RAD_DT_INVALID ||
!plain(W->rad_dtype)) {
RAD_ERR("lora: '%s' is not a plain bf16/f16/f32 matrix, so an adapter cannot "
"merge into it", W->name.c_str());
return RAD_E_UNSUPPORTED;
}
if (W->shape.size() != 2 || W->shape[1] != K) {
RAD_ERR("lora: '%s' [a %lld x %lld, b %lld x %lld] does not fit '%s' "
"[%lld x %lld]",
p.module.c_str(), (long long)A.shape[0], (long long)A.shape[1],
(long long)B.shape[0], (long long)B.shape[1], W->name.c_str(),
(long long)W->shape[0], (long long)W->shape[1]);
return RAD_E_FORMAT;
}
rows += W->shape[0];
}
if (rows != B.shape[0]) {
RAD_ERR("lora: '%s' merges into %zu target(s) whose rows sum to %lld, but its B "
"has %lld", p.module.c_str(), tg.size(), (long long)rows,
(long long)B.shape[0]);
return RAD_E_FORMAT;
}
float scale = (float)strength;
if (p.al) {
const int64_t n_el = p.al->shape.empty() ? 1 : p.al->numel();
if (n_el != 1 || (p.al->dtype != RAD_F32 && p.al->dtype != RAD_BF16 &&
p.al->dtype != RAD_F16)) {
RAD_ERR("lora: '%s.alpha' is not a single number", p.module.c_str());
return RAD_E_FORMAT;
}
scale *= rad_load_f32(p.al->data, p.al->dtype, 0) / (float)r;
}
/* The module is the targets' concatenation, so B's rows split along them in listed
* order: target i takes rows [off, off + N_i) as its own.
*
* Row at a time, rank-1 updates into an f32 row buffer. A is copied to f32 once per
* pair (r rows -- a few KiB to a few MiB): the rank sweep then reads plain f32
* contiguously against the accumulator, which is what the compiler vectorises and
* the cache wants; paying rad_load_f32's dtype switch per element instead made the
* real 416-pair merge an hour of scalar work. The same f32 sums as the textbook
* order, up to the rounding of the accumulation itself, which the bf16 cast
* swallows. */
std::vector<float> Af((size_t)(r * K));
for (int64_t i = 0; i < r * K; ++i) Af[(size_t)i] = rad_load_f32(A.data, A.dtype, i);
std::vector<float> acc((size_t)K);
int64_t off = 0;
for (const SrcTensor* W : tg) {
const int64_t N = W->shape[0];
auto out = std::make_unique<uint8_t[]>((size_t)W->bytes);
for (int64_t n = 0; n < N; ++n) {
for (int64_t j = 0; j < r; ++j) {
const float b = scale * rad_load_f32(B.data, B.dtype, (off + n) * r + j);
if (b == 0.f) continue;
const float* ar = Af.data() + (size_t)j * K;
for (int64_t k = 0; k < K; ++k) acc[(size_t)k] += b * ar[k];
}
for (int64_t k = 0; k < K; ++k)
rad_store_f32(out.get(), W->rad_dtype, n * K + k,
rad_load_f32(W->data, W->rad_dtype, n * K + k) +
acc[(size_t)k]);
std::fill(acc.begin(), acc.end(), 0.f);
}
SrcTensor& t = tensors_[index_[W->name]];
t.data = out.get();
owned_.push_back(std::move(out));
if (merged) merged->push_back(t.name);
++n_merged;
off += N;
}
}
}
RAD_INFO("lora %s: %d tensor(s) merged at strength %g", path.c_str(), n_merged, strength);
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
return it == index_.end() ? nullptr : &tensors_[it->second];
+25
View File
@@ -121,6 +121,31 @@ public:
* tensors and config.json keys under `draft.`. */
int add_draft(const std::string& dir, const std::string& prefix);
/* Merge PEFT adapters into the tensors they name, before anything reads the checkpoint:
* `path` is a .safetensors file or a directory of them, holding `<module>.lora_A.weight`
* [r,K] / `<module>.lora_B.weight` [N,r] pairs (ComfyUI's `.lora_down`/`.lora_up` spellings
* read too), with an optional `<module>.alpha` scalar -- the module never carries its own
* `.weight`. The target is `<module>.weight`, looked up under that name and, failing that,
* after stripping a wrapper prefix ("diffusion_model.", "transformer.", "unet.");
* a module the checkpoint does not ship is
* a refusal naming it, since a merge that silently hits nothing is a different model. The
* merge is the PEFT one, in f32: W += strength * (alpha/r where an .alpha states one, else 1)
* * B @ A, cast back to the target's dtype. Targets must be plain bf16/f16/f32 matrices --
* an adapter cannot merge into a quantised export or a non-matrix. Call this right after
* open(): it re-points a merged tensor's bytes, and views taken before it would read the
* unmerged ones. `merged` receives each target's name.
*
* `map_json` (null = none) names a file holding per-architecture module rules for adapters
* trained against a module layout the checkpoint does not spell -- a fused qkv, renamed blocks:
* `{"strip": ["prefix."], "modules": {"<pattern>": ["<target pattern>", ...]}}`, where a
* `*` in a module pattern matches one run of characters (the block index) and the same run
* fills every `*` in that rule's target patterns. Several targets share one delta: the
* module is the concatenation, so B's rows split along the targets in the order listed,
* each taking its own row count (they must sum to B's rows). A rule whose target the
* checkpoint lacks is a refusal, never a miss -- the rule says the tensor is there. */
int add_lora(const std::string& path, double strength, std::vector<std::string>* merged,
const std::string* map_json = nullptr);
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
bool is_gguf() const { return kind_ == Gguf; }
+43
View File
@@ -8,6 +8,7 @@
*/
#pragma once
#include "rad_core.h"
#include "mm/processor.h"
#include <atomic>
#include <condition_variable>
@@ -71,6 +72,37 @@ private:
std::string why_;
};
/* One file of a reference-conditioned request (task "ref2va"): an image or a video that
* conditions identity and motion, a video's separately-given soundtrack, or a standalone audio.
* The server reads the parts' bytes, bounds them and orders them; decoding them and turning
* them into conditioning rows is the generator's. `index` is the part's 1-based number within
* its kind, which fixes its slot in the conditioning; VIDEO_AUDIO #i is the soundtrack of
* VIDEO #i. */
struct VideoRefMedia {
enum Kind : int32_t { IMAGE = 0, VIDEO = 1, VIDEO_AUDIO = 2, AUDIO = 3 };
Kind kind = IMAGE;
int32_t index = 0;
std::string name, filename, content_type; /* the part's name and what the client called the file */
std::string data; /* the file's bytes */
/* The reference in the encoder's own form, prepared by the server (which owns the decoder) so
* the driver stages bytes without ever touching a codec. The VAE encode pass reads exactly
* these; they are empty until the server decodes the part. IMAGE/VIDEO fill the pixels,
* AUDIO/VIDEO_AUDIO the samples.
* enc_pixels: f32 [enc_frames][enc_h][enc_w][3] row-major RGB in 0..255, UN-normalised —
* the video VAE applies ImageNet mean/std itself. Each side is snapped down to a multiple
* of the VAE's spatial ratio and capped at the declaration's max_enc_side, aspect kept,
* because our encoder runs one volume and cannot tile the way the reference does. For a
* still image enc_frames is 1.
* enc_samples: f32 [enc_channels][enc_n] channel-major, each channel right-padded with
* zeros out to a whole number of hops (geom entry 0), at the model's audio rate. */
std::vector<float> enc_pixels;
int32_t enc_frames = 0, enc_h = 0, enc_w = 0;
std::vector<float> enc_samples;
int64_t enc_n = 0;
int32_t enc_channels = 0;
};
struct VideoRequest {
std::vector<int32_t> tokens; /* the prompt, rendered and tokenised */
int32_t width = 0, height = 0; /* pixels, within the declaration's limits */
@@ -81,6 +113,17 @@ struct VideoRequest {
double upscale = 0.0;
int32_t refine = 0;
uint64_t seed = 0;
/* Reference conditioning, sorted by (kind, index); empty for a text-only request. The bytes
* are the VAE's (P2): reference videos and audios become conditioning rows through the
* video/audio VAEs, not the TE. */
std::vector<VideoRefMedia> refs;
/* The references' TE view: every image and video reference processed to patches, placed in
* `tokens` at their presentation markers, with the M-RoPE layout over the whole conditioning
* (§3's presentation order). The server decodes and processes; the driver stages it into the
* conditioning pass's encoder fields (RadBatch::enc_* / rope_pos / mm_rows) exactly as the
* image generator's driver does. Null for a request whose references carry nothing the TE
* sees — audios are label-only, and a text-only request has none. */
std::shared_ptr<mm::PromptMedia> media;
std::shared_ptr<VideoTicket> ticket;
};
+384 -30
View File
@@ -141,16 +141,26 @@ namespace {
constexpr int64_t kAlign = 256;
/* The most segment boundaries R_SEG holds: the plain presentation has four, and a full
* reference-conditioned one (text, a keyframe pair, two segments for every reference at the
* server's 9/3/3 caps, the two target streams) stays well under this. The plugin's pack is the
* only source once references ride; the VSA kernels take the count from the staged rows and
* accept up to 4096. */
constexpr int64_t kSegCap = 64;
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) {
* allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and
* patch width (RadBuildCtx::max_enc_patches, RadEncoderDecl::patch_dim), 0 and 0 without a
* vision encoder: the media regions then hold nothing. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
int64_t (*bytes)[2], int n) {
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions, a conditioning's [3,T] M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */
@@ -158,9 +168,19 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in
4 * 4, /* R_SEED */
4, /* R_LANE */
4, /* R_FIRST */
4 * 4, /* R_SEG */
kSegCap * 4, /* R_SEG: the pack's boundary table, widened for references */
4 * 4, /* R_LAT */
4, /* R_UP */
d.max_text * 4, /* R_MMROW: the media rows, one per placeholder token */
ep * pd * 2, /* R_ENCPIX: [ep, pd] bf16 */
4 * ep * 4, /* R_ENCCRD: [4, ep] i32 component-major */
(ep + 2) * 4, /* R_ENCCU: segment boundaries; a segment is at least one patch */
/* The VAE encode staging: one media item's pixels or samples and its encode geometry,
* sized to the declaration's per-pass ceilings so a single pass holds any media the
* export accepts. All 0 without the encoders (decl.encodes 0 leaves the ceilings 0). */
d.max_enc_frames * d.max_enc_side * d.max_enc_side * 3 * 4, /* R_ENCPX: [f,h,w,3] f32 */
d.max_enc_samples * d.audio_channels * 4, /* R_ENCSM: [ch,n] f32 */
25 * 4, /* R_ENCG: rad_arch_encode_geom's 25 i32 (the video geom) */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -184,14 +204,26 @@ int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) {
} /* namespace */
/* The conditioning encoder's staging bounds: a program with no declared vision encoder stages
* no media, and the driver refuses requests that carry any. */
namespace {
void encoder_bounds(const Program& prog, int64_t* ep, int64_t* pd) {
*ep = prog.encoder.modalities != 0 ? prog.ctx.max_enc_patches : 0;
*pd = prog.encoder.modalities != 0 ? prog.encoder.patch_dim : 0;
}
} /* namespace */
int64_t VideoDriver::device_bytes(const Program& prog) {
if (!prog.is_video_generator()) return 0;
int64_t ep = 0, pd = 0;
encoder_bounds(prog, &ep, &pd);
int64_t b[R_N][2];
return carve(prog.video_gen, prog.ctx.max_tok, b, R_N);
return carve(prog.video_gen, prog.ctx.max_tok, ep, pd, b, R_N);
}
int VideoDriver::init(const Program& prog, PositionsFn positions,
const std::vector<RankIO>& ranks) {
const std::vector<RankIO>& ranks, SegsFn segs, PackFn pack,
EncodeGeomFn enc_geom) {
fini();
if (!prog.is_video_generator()) return RAD_E_STATE;
decl_ = prog.video_gen;
@@ -200,7 +232,11 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
name_ = prog.vgen_str.name;
ranks_ = ranks;
positions_ = positions;
segs_ = segs;
pack_ = pack;
enc_geom_ = enc_geom;
max_tok_ = prog.ctx.max_tok;
encoder_bounds(prog, &max_enc_, &patch_dim_);
if (!positions_) {
RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a "
"video generator must", name_.c_str());
@@ -212,7 +248,7 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(decl_, max_tok_, b, R_N);
bytes_ = carve(decl_, max_tok_, max_enc_, patch_dim_, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
frames_bytes_ = frames_bytes_of(decl_);
@@ -275,6 +311,32 @@ 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));
/* Reference conditioning: the images reach the language model through `media`, which the
* server built from the parts (gen/video.h) and build_cond stages into the conditioning
* pass. What this generator cannot consume yet is anything whose bytes reach the model
* through a VAE — a reference video's frames, a soundtrack, a standalone audio. Those are
* refused naming the part, rather than silently made into a weaker video. */
if (!r->refs.empty() && max_enc_ == 0)
return no("this container was converted without its vision tower, so no request can "
"carry reference media");
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE)
return no("'" + m.name + "' is not consumed yet: reference videos and audios reach "
"the model through the video and audio VAEs, which the video path does not "
"run in this build; only ref_image_N parts condition a generation today");
if (!r->refs.empty() && !r->media)
return no("the request carries reference images but no processed media to condition on");
if (r->media) {
int64_t n_patch = 0;
for (const mm::Placed& p : r->media->items) {
if ((int64_t)p.tok + (int64_t)p.item->expand.size() > T)
return no("a reference's placeholder run is placed past the end of the prompt");
n_patch += p.item->n_patch;
}
if (n_patch > max_enc_)
return no("the references are " + std::to_string(n_patch) + " patches; this model "
"encodes at most " + std::to_string(max_enc_) + " in one pass");
}
if (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");
@@ -303,19 +365,108 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
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);
/* The pack's reference table (RadVideoGenBatch::ref_tab): every reference the DiT conditions
* on, in presentation order, in ITS OWN latent grid -- {kind, slot, h, w, frames, audio} six
* words after the reference and keyframe counts. A picture's grid is the encoder's sides over
* the VAE ratio, one latent frame, no soundtrack; its slot is the one its Vencode pass folds
* its latents into. It must exist before the step layout is decided, because when the denoiser
* consumes it the reference rows are part of that layout. Only pictures queue today (videos and
* audios are refused at submit above until their decode paths land), so the keyframe count
* stays 0 and the table holds only picture rows. */
if (d.encodes)
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
if (m.kind != VideoRefMedia::IMAGE) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1)
return no("'" + m.name + "' has no slot in the conditioning");
if (d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio ||
m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio)
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) + "x" +
std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
j->enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/,
0 /*no soundtrack*/});
}
/* The step's packed sequence. When the denoiser consumes the reference table the pack is the
* only source of its rows, segment boundaries and positions -- the reference rows sit between
* the text and the target streams, so the plain `text + audio + video` arithmetic and the plain
* position layout no longer describe it. rad_arch_video_pack returns the total rows and, when
* roomy, the boundaries and the full [3, rows] planar RoPE in one call. Otherwise the plain
* layout is computed exactly as before, and a staged reference table (if any) rides inert. */
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");
if (nd <= 0 || nd > max_tok_)
return no("the model lays this video's decoder in " + std::to_string(nd) + " 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");
if (d.ref_rows && !j->ref_tab.empty()) {
if (r->upscale > 1.0)
return no("reference conditioning does not yet combine with latent upscale; ask for "
"the size you want without latent_upscale");
if (!pack_)
return no("the generator says it conditions on references but exports no "
"rad_arch_video_pack");
const int64_t pr = pack_(&j->geom, j->ref_tab.data(), nullptr, 0, nullptr, 0);
if (pr <= 0)
return no("the model refused the reference conditioning layout");
if (pr > max_tok_)
return no("a conditioned step is " + std::to_string(pr) + " rows and a pass carries " +
std::to_string(max_tok_) + "; ask for a shorter or smaller video, or fewer "
"references");
j->seg.assign((size_t)kSegCap, 0);
j->pos.assign((size_t)(3 * pr), 0.0f);
if (pack_(&j->geom, j->ref_tab.data(), j->seg.data(), kSegCap, j->pos.data(), 3 * pr) != pr)
return no("the model could not lay the reference conditioning out");
int nseg = -1;
for (int k = 0; k < kSegCap; ++k)
if (j->seg[(size_t)k] == (int32_t)pr) { nseg = k + 1; break; } /* video grid ends here */
if (nseg < 0 || nseg > kSegCap)
return no("the reference conditioning layout has no closing segment boundary");
j->seg.resize((size_t)nseg);
j->nseg = nseg;
/* The denoiser lays out one modulation cell per segment and its table is a fixed width the
* arch declares; a pack wider than it would abort the step mid-generation and take the
* engine with it. Refuse here, at submit, where a clean answer is still possible. */
const int nsegs = nseg - 1; /* `seg` is boundaries: one more than the segments */
if (d.max_ref_segs > 0 && nsegs > d.max_ref_segs) {
const int nrefs = j->ref_tab.empty() ? 0 : j->ref_tab[0];
const int64_t fit = (int64_t)d.max_ref_segs - (nsegs - nrefs); /* the fixed non-ref cells */
return no("these references lay the conditioning out in " + std::to_string(nsegs) +
" sequence segments but this deployment's conditioning table holds " +
std::to_string(d.max_ref_segs) + ", so at most " +
std::to_string(fit < 0 ? 0 : (int)fit) + " fit -- ask for fewer references");
}
/* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode,
* audio, upscale) stages its own segment table and target counts from it and must see the
* bytes it sees today. Only build_step runs at the widened `step_rows`. */
j->rows = T + s.audio_rows + s.video_rows;
j->step_rows = pr;
/* The last segment (the video target) runs [seg[nseg-2], seg[nseg-1]); seg[nseg-1] is the
* total rows, so the video start is the boundary before it -- the same one the VSA takes as
* its video base (it works in segments, one fewer than the boundaries it is handed). */
j->lat_v = pr - j->seg[(size_t)(nseg - 2)];
j->lat_a = decl_.audio_channels * (int64_t)j->geom.n_audio;
j->ref_wide = true;
} else {
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);
if (nr != j->rows)
return no("the model lays this video out in " + std::to_string(nr) + " step rows, "
"which this server cannot run");
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->step_rows = j->rows;
}
j->sched = video_schedule(d, steps);
if (j->sched.steps < 1) return no("the schedule has no steps");
if (r->upscale > 1.0) {
@@ -357,6 +508,17 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
}
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
/* The reference table and the VAE encode queue were built above, before the step layout was
* chosen: each reference picture the server decoded into encoder form rides one Vencode pass,
* at the slot its index numbers within pictures -- the slot the encoder folds its latents into
* and the step's pack scatters them from. Reference videos and audios are refused above until
* their decode paths land, so only pictures are queued and the keyframe count stays 0. */
/* The soundtrack's length, exactly the samples the decode will hand the encoder — the
* number a caller that chains clips against an audio floor checks. A build without
* libavcodec never gets the muxed file to read it back from, so it is logged here. */
RAD_INFO("video: soundtrack %.2f s, %lld samples at %lld Hz x %lld ch",
(double)j->n_samples / d.sample_rate, (long long)j->n_samples,
(long long)d.sample_rate, (long long)d.audio_channels);
VideoTicket& t = *r->ticket;
t.frames = s.frames;
@@ -367,7 +529,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->rows;
t.rows = j->step_rows; /* the conditioned step's real length, references included */
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -445,7 +607,8 @@ int VideoDriver::upload() {
/* The geometry a pass's ops read off the device (RAD_VGEOM_*) for a pass at geometry `g` of
* `rows` step rows, with chunk `chunk`'s span when it is a decode's and both grids when the job
* upscales. */
void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk) {
void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk,
bool ref_step) {
int32_t* g = hptr<int32_t>(R_GEOM);
std::memset(g, 0, RAD_VGEOM_N * 4);
g[RAD_VGEOM_LAT_FRAMES] = g0.lat_frames;
@@ -473,15 +636,47 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up);
}
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const bool wide = j.ref_wide && ref_step;
const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio;
const int64_t video_rows = rows - g0.n_text - audio_rows;
/* With references riding, the sampler owns only the target video rows -- not the reference
* rows the pack placed ahead of them -- so the target count is the pack's, not the plain
* rows-minus-text-minus-audio. The audio target is the whole soundtrack either way. */
const int64_t video_rows = wide ? j.lat_v : rows - g0.n_text - audio_rows;
*hptr<int32_t>(R_LANE) = j.lane;
*hptr<int32_t>(R_FIRST) = j.step == 0;
int32_t* seg = hptr<int32_t>(R_SEG);
seg[0] = 0;
seg[1] = g0.n_text;
seg[2] = (int32_t)(g0.n_text + audio_rows);
seg[3] = (int32_t)rows;
if (wide) {
/* The pack laid the reference rows out ahead of the target streams, video grid last. Stage
* its boundaries verbatim: the VSA derives its segment count from the operand length, so
* every reference becomes a dense prefix sink with no kernel change. Only the step pass
* stages this table; the decode, encode and upscale passes stage the plain layout below. */
std::memcpy(seg, j.seg.data(), j.seg.size() * sizeof(int32_t));
reg_[R_SEG].used = (int64_t)j.seg.size() * 4;
} else {
/* The pack lays the segments out (rad_arch_video_segs, or the reference-aware
* rad_arch_video_pack once refs ride); for a plain request its table is the one computed
* below, so a plugin without the exports -- or one whose table disagrees with this
* geometry -- stages the same bytes either way. The pack answers with the rows, not a
* count, so a poison word at the fifth slot is what proves a plain table has no entries
* past the fourth: a pack that writes past it disagrees with this geometry. */
bool packed = false;
if (pack_) {
seg[4] = -1;
const int64_t pr = pack_(&g0, nullptr, seg, kSegCap, nullptr, 0);
packed = pr == rows && seg[4] == -1 && seg[0] == 0 && seg[1] == g0.n_text &&
seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows;
} else if (segs_) {
packed = segs_(&g0, seg, 4) == 4 && seg[0] == 0 && seg[1] == g0.n_text &&
seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows;
}
if (!packed) {
seg[0] = 0;
seg[1] = g0.n_text;
seg[2] = (int32_t)(g0.n_text + audio_rows);
seg[3] = (int32_t)rows;
}
reg_[R_SEG].used = 4 * 4;
}
int32_t* lat = hptr<int32_t>(R_LAT);
lat[0] = 0;
lat[1] = (int32_t)video_rows;
@@ -489,7 +684,6 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
lat[3] = (int32_t)audio_rows;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_SEG].used = 4 * 4;
reg_[R_LAT].used = 4 * 4;
}
@@ -529,6 +723,7 @@ 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.ref_tab = j.ref_tab.empty() ? nullptr : j.ref_tab.data();
B.vgen_b = &V;
}
}
@@ -559,12 +754,20 @@ const RadBatch* VideoDriver::next(int step) {
if (!j.audio_done) return build_audio(j, step);
if (j.chunk < j.n_chunks) return build_chunk(j, step);
}
/* 2. A prompt. */
/* 2. A VAE encode of a reference-conditioned lane's media, before its prompt: one pass per
* reference, so the encoder's latents are in the lane's slot rows by the time the prompt
* and its steps run (the step's pack scatters them into the sequence). */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.cond_done) continue;
if (j.enc_next < j.enc_q.size()) return build_encode(j, step);
}
/* 3. A prompt. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step, or its upscale once its small steps are done. */
/* 4. The oldest lane's next step, or its upscale once its small steps are done. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue;
@@ -602,8 +805,76 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
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);
/* Reference media for the tower and the conditioning's M-RoPE, staged exactly as the image
* driver stages a conditioned prompt (core/gen/driver.cpp's build_cond). R_ROPE holds the
* [3,T] i32 grid here and a step's f32 positions in build_step — never both in one pass, and
* step_cond reads rope_pos instead of positions when it is set. */
int64_t n_patch = 0, n_seg = 0, n_mm = 0;
int32_t max_seg = 0;
if (j.req->media) {
const mm::PromptMedia& pm = *j.req->media;
int32_t* rope = hptr<int32_t>(R_ROPE);
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
pm.rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
rope[2 * T + i] = p3[2];
}
reg_[R_ROPE].used = 3 * T * 4;
int64_t total = 0;
for (const mm::Placed& p : pm.items) total += p.item->n_patch;
uint16_t* pix = hptr<uint16_t>(R_ENCPIX);
int32_t* crd = hptr<int32_t>(R_ENCCRD);
int32_t* ecu = hptr<int32_t>(R_ENCCU);
ecu[0] = 0;
std::vector<int32_t> tmp;
for (const mm::Placed& p : pm.items) {
const mm::Item& it = *p.item;
std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(),
(size_t)(it.n_patch * patch_dim_) * 2);
tmp.resize((size_t)(4 * it.n_patch));
it.coords(0, it.n_patch, tmp.data());
for (int cc = 0; cc < 4; ++cc)
std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch,
(size_t)it.n_patch * 4);
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t a = it.patch_at(s), e = it.patch_at(s + 1);
ecu[n_seg + 1] = (int32_t)(n_patch + e);
max_seg = std::max<int32_t>(max_seg, (int32_t)(e - a));
++n_seg;
}
n_patch += it.n_patch;
}
int32_t* mmr = hptr<int32_t>(R_MMROW);
for (const mm::RopeLayout::Run& run : pm.rope.runs)
for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k;
reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2;
reg_[R_ENCCRD].used = 4 * total * 4;
reg_[R_ENCCU].used = (n_seg + 1) * 4;
reg_[R_MMROW].used = n_mm * 4;
}
if (upload() < 0) return nullptr;
base_batches(j, g, T, step);
if (j.req->media) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
const int ri = (int)r;
B.rope_pos = dptr<int32_t>(ri, R_ROPE);
B.rope_mixed = 1;
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? dptr<int32_t>(ri, R_MMROW) : nullptr;
B.enc = 0;
B.enc_n_patch = n_patch;
B.enc_pixels = n_patch ? dptr<uint16_t>(ri, R_ENCPIX) : nullptr;
B.enc_coord = n_patch ? dptr<int32_t>(ri, R_ENCCRD) : nullptr;
B.enc_n_seg = n_seg;
B.enc_cu = n_seg ? dptr<int32_t>(ri, R_ENCCU) : nullptr;
B.enc_max_seg = max_seg;
}
}
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
@@ -639,7 +910,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const bool small = small_now(j);
const RadVideoGeom& g = small ? j.geom_small : j.geom;
const int64_t rows = small ? j.rows_small : j.rows;
const int64_t rows = small ? j.rows_small : j.step_rows; /* widened by references when they ride */
const std::vector<float>& pos = small ? j.pos_small : j.pos;
stage_sched(j, j.step, small && j.step == j.split - 1);
std::memcpy(hptr<float>(R_ROPE), pos.data(), pos.size() * 4);
@@ -650,7 +921,10 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
cu[0] = 0;
cu[1] = (int32_t)rows;
reg_[R_CU].used = 2 * 4;
stage_geom(j, g, rows, 0);
/* A reference-conditioned step stages the pack's reference-aware segment table; the plain and
* small (pre-upscale) steps stage the plain four-boundary table. ref_wide never coincides with
* small -- submit refuses upscale together with references. */
stage_geom(j, g, rows, 0, j.ref_wide);
if (upload() < 0) return nullptr;
base_batches(j, g, rows, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
@@ -707,6 +981,81 @@ const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
return &out_[0];
}
/* One media item through its VAE encoder: stage its encoder-ready bytes and the encode geometry
* the plugin's rad_arch_encode_geom derives from them, then name the pass's kind and slot so the
* encoder folds the latents into the lane's fixed slot rows. The bytes the server decoded must
* already be padded to what the geom reports (a video's frames clip-padded, an audio's samples to
* its hop) — the encoder reads that many and no more, so a disagreement is failed here rather than
* run past the staged volume. */
const RadBatch* VideoDriver::build_encode(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Job::EncItem& it = j.enc_q[j.enc_next];
const VideoRefMedia& m = j.req->refs[(size_t)it.ref];
const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO;
auto fail = [&](const std::string& w) {
fail_locked(j, RAD_E_STATE, w);
return nullptr;
};
if (!enc_geom_)
return fail("the request carries reference media to encode, but this plugin exports no "
"rad_arch_encode_geom");
int32_t* gd = hptr<int32_t>(R_ENCG);
if (audio) {
const int64_t n = m.enc_n;
const int32_t ch = m.enc_channels;
if (n <= 0 || ch <= 0 || (int64_t)n * ch * 4 > reg_[R_ENCSM].bytes)
return fail("a reference audio does not fit one encode pass");
int64_t in[4] = { n, 0, 0, ch };
if (enc_geom_(RAD_GEN_PASS_AENCODE, in, gd, 25) < 0)
return fail("the audio encoder refuses " + std::to_string(n) + " samples over " +
std::to_string(ch) + " channels");
if ((int64_t)gd[0] != n)
return fail("a reference audio is not padded to the length rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCSM), m.enc_samples.data(), (size_t)n * ch * 4);
reg_[R_ENCSM].used = n * ch * 4;
} else {
const int64_t nf = m.enc_frames, H = m.enc_h, W = m.enc_w;
if (nf <= 0 || H <= 0 || W <= 0 || nf * H * W * 3 * 4 > reg_[R_ENCPX].bytes)
return fail("a reference picture or video does not fit one encode pass");
int64_t in[4] = { nf, H, W, 3 };
if (enc_geom_(RAD_GEN_PASS_VENCODE, in, gd, 25) < 0)
return fail("the video encoder refuses a reference at " + std::to_string(H) + "x" +
std::to_string(W) + " over " + std::to_string(nf) + " frames");
if ((int64_t)gd[23] != nf)
return fail("a reference is not padded to the clip count rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCPX), m.enc_pixels.data(), (size_t)nf * H * W * 3 * 4);
reg_[R_ENCPX].used = nf * H * W * 3 * 4;
}
reg_[R_ENCG].used = 25 * 4;
stage_geom(j, j.geom, j.rows, 0);
if (upload() < 0) return nullptr;
base_batches(j, j.geom, 0, step);
for (size_t r = 0; r < ranks_.size(); ++r) {
const int ri = (int)r;
RadVideoGenBatch& V = vout_[(size_t)r];
V.enc_geom_d = dptr<int32_t>(ri, R_ENCG);
V.enc_kind = it.kind;
V.enc_slot = it.slot;
if (audio) {
V.enc_samples = dptr<float>(ri, R_ENCSM);
V.enc_n_samples = m.enc_n;
V.enc_channels = m.enc_channels;
} else {
V.enc_pixels = dptr<float>(ri, R_ENCPX);
V.enc_frames = m.enc_frames;
V.enc_height = m.enc_h;
V.enc_width = m.enc_w;
}
}
const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE;
for (auto& B : out_) B.gen = kind;
pass_.kind = kind;
pass_.job = j.id;
return &out_[0];
}
int VideoDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
@@ -716,6 +1065,11 @@ int VideoDriver::done() {
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
break;
case RAD_GEN_PASS_VENCODE:
case RAD_GEN_PASS_AENCODE:
/* The media's latents are now in the lane's slot rows; take the next reference, if any. */
++j->enc_next;
break;
case RAD_GEN_PASS_VSTEP: {
++j->step;
VideoEvent e;
+68 -6
View File
@@ -12,8 +12,10 @@
*
* 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish
* a request and free its lane.
* 2. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
* 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the
* video and audio VAE latents are in the lane's slots before its prompt runs.
* 3. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
* Requests are denoised one after another, not in turns: a pass is one request's whole
* sequence, so taking turns would only delay the first.
*/
@@ -34,9 +36,18 @@ public:
RadStream stream = nullptr;
};
using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
using SegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t);
using PackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t,
float*, int64_t);
using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t);
/* `positions` is the plugin's rad_arch_video_positions. */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks);
/* `positions` is the plugin's rad_arch_video_positions; `segs`, optional, is its
* rad_arch_video_segs (null = the driver stages the plain segment table itself); `pack`,
* optional, is its rad_arch_video_pack (null = reference-conditioned sequences cannot be
* laid out and such requests are refused); `enc_geom`, optional, is its
* rad_arch_encode_geom (null = no encode pass runs). */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks,
SegsFn segs = nullptr, PackFn pack = nullptr, EncodeGeomFn enc_geom = nullptr);
void fini();
~VideoDriver() override { fini(); }
@@ -68,6 +79,38 @@ private:
int64_t n_samples = 0; /* the soundtrack's samples a channel */
VideoSchedule sched;
std::vector<float> pos; /* [3, rows] */
/* The VAE references of a reference-conditioned request (RadVideoGenBatch::ref_tab):
* the pack's input, empty until the path consumes them (it is refused at submit
* before that). The step reads it host-side, so nothing stages it. */
std::vector<int32_t> ref_tab;
/* When the generator's denoiser consumes that table (`decl_.ref_rows`), the step's packed
* sequence carries reference rows between the text and the target streams, laid out by
* rad_arch_video_pack. These hold that step layout: `ref_wide` marks it, `seg` the pack's
* segment boundaries with the video grid last, `nseg` their count, and `lat_v`/`lat_a` the
* TARGET video and audio row counts -- the rows the sampler owns and the Euler steps update,
* which the plain `rows - text - audio` arithmetic no longer recovers once references ride
* ahead of the streams. Left empty/0 on the plain path and on every non-step pass (decode,
* encode, upscale), which keep their own ref-less segment table. */
bool ref_wide = false;
int32_t nseg = 0;
std::vector<int32_t> seg;
int64_t lat_v = 0, lat_a = 0;
/* The denoising step's row count: the widened total once references ride, otherwise equal
* to `rows`. Only build_step uses it -- the encode, decode, audio and upscale passes keep
* staging against the plain `rows` (their segment table and target counts are their own,
* never the reference layout), so widening the step cannot disturb them. `pos` widens with
* it, since build_step is the only pass that stages R_ROPE from `pos`. */
int64_t step_rows = 0;
/* The VAE encode queue: the reference media whose bytes reach the model through a video or
* audio VAE, one item per Vencode/Aencode pass, in presentation order, built at submit for
* the parts the server decoded into encoder form (gen/video.h enc_pixels/enc_samples).
* `enc_kind` is the RAD_ENC_* the pass names and `enc_slot` its 1-based number within that
* kind (the reference's index); `ref` indexes req->refs. `enc_next` is the next to run;
* once it reaches enc_q.size() the media are all encoded. Empty for a request the encoder
* has nothing to do with. */
struct EncItem { int32_t kind, slot, ref; };
std::vector<EncItem> enc_q;
size_t enc_next = 0;
/* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and
* positions, the factor the network is told, and whether the upscale has run. */
int32_t split = 0;
@@ -95,8 +138,15 @@ private:
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
/* R_MMROW/R_ENCPIX/R_ENCCRD/R_ENCCU stage the conditioning pass's reference media, as the
* image generator's driver does (core/gen/driver.cpp); R_ROPE carries a step's f32 positions
* and a conditioning's [3,T] i32 M-RoPE, never in the same pass. */
/* R_ENCPX/R_ENCSM/R_ENCG stage one media item for a Vencode/Aencode pass: the encoder-ready
* pixels ([frames,h,w,3] f32) or samples ([ch,n] f32) and the encode geometry the plugin's
* rad_arch_encode_geom returned, staged verbatim as device i32 for the kernels to read. */
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_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU,
R_ENCPX, R_ENCSM, R_ENCG, 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 {
@@ -106,7 +156,8 @@ private:
/* 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; }
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_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk,
bool ref_step = false);
void stage_sched(const Job& j, int32_t i, bool to_clean);
void stage_seed(const Job& j);
@@ -120,12 +171,23 @@ private:
const RadBatch* build_upscale(Job& j, int step);
const RadBatch* build_audio(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
/* One Vencode or Aencode pass for the job's next queued reference (enc_q[enc_next]): stages
* that part's encoder-ready pixels or samples and the encode geometry, and names its kind and
* slot. Returns null and fails the job if the bytes no longer fit a pass. */
const RadBatch* build_encode(Job& j, int step);
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::string name_;
PositionsFn positions_ = nullptr;
SegsFn segs_ = nullptr;
PackFn pack_ = nullptr;
EncodeGeomFn enc_geom_ = nullptr;
int64_t max_tok_ = 0;
/* The conditioning's encoder view: the tower's per-patch width and the patches one pass
* carries. Zero when the program declares no vision encoder, which bounds the media regions
* and rejects any request that carries references. */
int64_t patch_dim_ = 0, max_enc_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
+20
View File
@@ -156,6 +156,26 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
}
}
void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out) {
/* Wrapping opaque and running the RGBA kernel is exactly PIL's LANCZOS on the RGB image: at
* alpha 255 the premultiply is the identity and the divide-back takes the al == 255 branch. */
FrameRGBA pre;
pre.w = src.w;
pre.h = src.h;
pre.rgba.resize((size_t)src.w * src.h * 4);
for (size_t i = 0; i < (size_t)src.w * src.h; ++i) {
for (int c = 0; c < 3; ++c) pre.rgba[i * 4 + c] = src.rgb[i * 3 + c];
pre.rgba[i * 4 + 3] = 255;
}
FrameRGBA post;
resize_lanczos_rgba(pre, w, h, &post);
out->w = post.w;
out->h = post.h;
out->rgb.resize((size_t)post.w * post.h * 3);
for (size_t i = 0; i < (size_t)post.w * post.h; ++i)
for (int c = 0; c < 3; ++c) out->rgb[i * 3 + c] = post.rgba[i * 4 + c];
}
void composite_white(const FrameRGBA& src, Frame* out) {
out->w = src.w;
out->h = src.h;
+4
View File
@@ -18,6 +18,10 @@ namespace mm {
/* `src` resized to w x h. */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* As resize_lanczos_rgba for an opaque picture: wrapped with alpha 255 and resized, so the RGB
* channels are exactly PIL's LANCZOS on the RGB image (premultiply and its inverse are the
* identity at full alpha). The video VAE's reference preprocessing resizes RGB this way. */
void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
+34
View File
@@ -3,6 +3,8 @@
* metadata reader, the real device layer. */
#include "mm/processor.h"
#include <algorithm>
namespace rad {
namespace mm {
@@ -43,5 +45,37 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
}
}
/* The rotary layout of one prompt: one run per segment, the text in front of a run counting up
* and a grid advancing the rotary by its longer side. Pure computation over the items, like the
* accessors above, so it lives here rather than in the processor. */
void PromptMedia::layout() {
rope.runs.clear();
int64_t pos = 0, tok = 0;
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
}
} /* namespace mm */
} /* namespace rad */
+35 -31
View File
@@ -1,5 +1,6 @@
/* processor.cpp -- see processor.h. */
#include "mm/processor.h"
#include "mm/imaging.h"
#include "rad_internal.h"
#include "rad_plugin.h"
@@ -1006,6 +1007,40 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
return image_from(f, out, why);
}
int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
Frame* out, std::string* why) const {
if (ratio < 1 || max_side < ratio) {
if (why) *why = "the encoder's side ratio and maximum are not usable";
return RAD_E_INVAL;
}
/* The same decode guard as image(): a reference the text encoder accepts must reach the VAE
* too, so the two never disagree on what a request may carry. */
Frame f;
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
/* Snap both sides down to a multiple of the encoder's ratio, neither above max_side, aspect
* kept as close as the grid allows: scale the longest side to fit, then floor each side to the
* grid. Flooring (never rounding up) is what keeps a side within max_side; a side under one
* grid step is raised to it, the smallest volume the encoder accepts. Our encoder runs one
* volume rather than tiling at 256, so a reference larger than the bound is shrunk here — the
* one place the reference and this build differ on an oversized input. */
auto snap = [&](int64_t s) {
int64_t v = (s / ratio) * ratio;
if (v < ratio) v = ratio;
if (v > max_side) v = max_side; /* max_side is itself a multiple of ratio */
return (int32_t)v;
};
const int32_t longest = std::max(f.w, f.h);
const double scale = longest > max_side ? (double)max_side / (double)longest : 1.0;
const int32_t w = snap((int64_t)std::floor(f.w * scale));
const int32_t h = snap((int64_t)std::floor(f.h * scale));
if (w == f.w && h == f.h) {
*out = std::move(f);
return RAD_OK;
}
resize_lanczos_rgb(f, w, h, out);
return RAD_OK;
}
namespace {
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
@@ -1528,36 +1563,5 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
return audio_from(s, out, why);
}
/* ================================================================== rotary layout */
void PromptMedia::layout() {
rope.runs.clear();
int64_t pos = 0, tok = 0;
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
}
} /* namespace mm */
} /* namespace rad */
+9
View File
@@ -318,6 +318,15 @@ public:
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
/* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as
* `image` (so any reference the text encoder accepts the encoder accepts too), then scaled —
* aspect kept — so both sides are multiples of `ratio` and neither exceeds `max_side`, the
* single-volume encoder's square bound. Returns the resized RGB; the caller hands it to the
* encoder un-normalised (the VAE applies its own mean/std). `ratio`/`max_side` come from the
* generator's declaration (RadVideoGenDecl enc_ratio / max_enc_side). */
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, Frame* out,
std::string* why) const;
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
* encoder's. */
int init_audio(const AudioConfig& cfg, std::string* why = nullptr);
+13
View File
@@ -225,6 +225,19 @@ int Registry::commit_(Staged& s, int order) {
/* A video generator's rotary positions; the driver refuses to start without it. */
p.arch_video_positions = dl_fn<int64_t (*)(int, const RadVideoGeom*, float*, int64_t)>(
s.handle, "rad_arch_video_positions");
/* Optional: the pack's segment boundary table; absent means the video driver stages the
* plain [text | audio | video] table itself. */
p.arch_video_segs = dl_fn<int64_t (*)(const RadVideoGeom*, int32_t*, int64_t)>(
s.handle, "rad_arch_video_segs");
/* Optional: the pack with the references in; absent means the driver lays no
* reference-conditioned sequence out. */
p.arch_video_pack =
dl_fn<int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t)>(s.handle, "rad_arch_video_pack");
/* Optional: the encode passes' geometry; absent means the driver runs no encode pass. */
p.arch_encode_geom =
dl_fn<int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t)>(
s.handle, "rad_arch_encode_geom");
/* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
* the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
+9
View File
@@ -94,6 +94,15 @@ struct Plugin {
int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr;
/* Required of a video generator (rad_builder.h); null for every other plugin. */
int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr;
/* Optional (rad_builder.h); null means the video driver stages the plain
* [text | audio | video] boundary table itself. */
int64_t (*arch_video_segs)(const RadVideoGeom*, int32_t*, int64_t) = nullptr;
/* Optional (rad_builder.h); null means the driver lays no reference-conditioned sequence
* out and refuses requests that carry VAE references. */
int64_t (*arch_video_pack)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t) = nullptr;
/* Optional (rad_builder.h); null means the driver runs no encode pass. */
int64_t (*arch_encode_geom)(int32_t, const int64_t*, int32_t*, int64_t) = nullptr;
RadPluginCloseFn close = nullptr;
};
+9
View File
@@ -710,6 +710,15 @@ public:
: p_->video(bytes.data(), bytes.size(), out, why);
}
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
mm::Frame* out, std::string* why) override {
if (!p_ || !mm::decoder_available()) {
if (why) *why = "no picture decoder is available";
return RAD_E_UNSUPPORTED;
}
return p_->encoder_image(bytes, n, ratio, max_side, out, why);
}
int32_t audio_rate() const override {
return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0;
}
+3
View File
@@ -399,6 +399,9 @@ json Server::capabilities() const {
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
caps["audio_generation"] = deps_.audio != nullptr;
caps["video_generation"] = deps_.videos != nullptr;
/* A video model also says what a request may carry, so a client can gate on it the way it
* gates on /v1/models elsewhere; the counts are the ones a request will actually meet. */
if (deps_.videos) video_caps(caps, deps_.videos);
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+23
View File
@@ -533,6 +533,17 @@ public:
virtual int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
std::shared_ptr<mm::Item>* out, std::string* why) = 0;
/* A picture in a video VAE's encoder-ready form: decoded under the same guard as prepare() and
* resized so both sides are multiples of `ratio` and neither exceeds `max_side`. The video
* generator's server uses it to fill a reference's encoder pixels; a server with no video VAE
* leaves it unsupported. */
virtual int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
mm::Frame* out, std::string* why) {
(void)bytes; (void)n; (void)ratio; (void)max_side; (void)out;
if (why) *why = "this server prepares no reference media for a video encoder";
return RAD_E_UNSUPPORTED;
}
/* Audio in two halves, for a route that cuts a long recording into clips itself
* (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most
* `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most
@@ -644,6 +655,18 @@ 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;
/* Reference conditioning (SGLang's task "ref2va"): how many reference images, videos and
* standalone audios the model takes — all 0 for one that makes video from text only, which
* is every model until the declaration carries them (abi/rad_builder.h, RadVideoGenDecl).
* A video's soundtrack rides with the video and is not counted among the audios. */
int64_t max_ref_images = 0, max_ref_videos = 0, max_ref_audios = 0;
/* The video and audio VAE encoders (RadVideoGenDecl): nonzero when the container carries them,
* so the server decodes and resizes reference media into the encoder's own form before submit;
* the per-pass ceilings it snaps to (a video's clip-padded frames, the encoder's square side,
* an audio's samples) and `enc_ratio`, the side multiple the geom demands. All 0 without the
* encoders — a text-only or TE-only model leaves them and the server never prepares pixels. */
int64_t encodes = 0, max_enc_frames = 0, max_enc_side = 0, max_enc_samples = 0;
int64_t enc_ratio = 0;
};
class IVideoGen {
+4
View File
@@ -288,6 +288,10 @@ private:
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
json capabilities() const;
/* What a video model lets a request carry: the prompt ceiling the /v1/videos parser
* enforces and the reference-media counts, as validate_refs() will apply them. Defined in
* videos.cpp, beside the ref2va contract's own caps. */
static void video_caps(json& caps, const IVideoGen* gen);
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
/* ------------------------------------------------------------------ dashboard.cpp */
+287 -22
View File
@@ -15,8 +15,11 @@
* (`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 that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`:
* the media are form file parts named `ref_image_N` (at most 9), `ref_video_N` (3), a video's
* soundtrack as `ref_video_audio_N` and standalone audios as `ref_audio_N` (3), N 1-based and
* contiguous within each kind. `input_reference` and non-empty `conditions` are still refused:
* the parts carry the bytes, so no JSON array of media is read.
*
* 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
@@ -38,11 +41,15 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <random>
#include <thread>
#include <vector>
namespace rad {
namespace server {
@@ -61,6 +68,9 @@ struct Server::VideoJob {
std::string err_code, err_message;
std::string mp4;
std::vector<uint8_t> first; /* the first frame, RGB, for the thumbnail */
/* Reference conditioning: the reference parts' names in conditioning order, empty for a
* text-only job. */
std::vector<std::string> refs;
/* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the
* small size; refine 0 when the video is not upscaled. */
double upscale = 0.0;
@@ -118,8 +128,137 @@ void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int6
*h = std::max<int64_t>(mult, (int64_t)std::nearbyint(H / mult) * mult);
}
/* What a ref2va request may carry whatever a model declares: the reference media the source
* workflows were built with — nine images, three videos each with an optional soundtrack, three
* standalone audios. A model's declaration can only lower these. */
constexpr int32_t kMaxRefImages = 9, kMaxRefVideos = 3, kMaxRefAudios = 3;
/* A form file part's name for task ref2va: `ref_image_N`, `ref_video_N`, `ref_video_audio_N`
* (a video's separately-given soundtrack) or `ref_audio_N`, N plain and 1-based. False for any
* other name; `ref_video_audio_` is tried before `ref_video_` because one contains the other. */
bool parse_ref_name(const std::string& name, gen::VideoRefMedia::Kind* kind, int32_t* index) {
static const struct { const char* pfx; gen::VideoRefMedia::Kind kind; } kKinds[] = {
{ "ref_image_", gen::VideoRefMedia::IMAGE },
{ "ref_video_audio_", gen::VideoRefMedia::VIDEO_AUDIO },
{ "ref_video_", gen::VideoRefMedia::VIDEO },
{ "ref_audio_", gen::VideoRefMedia::AUDIO },
};
for (const auto& k : kKinds) {
const size_t n = std::strlen(k.pfx);
if (name.compare(0, n, k.pfx) != 0 || name.size() == n) continue;
char* e = nullptr;
const long v = std::strtol(name.c_str() + n, &e, 10);
if (*e == '\0' && v >= 1 && v <= 99) { *kind = k.kind; *index = (int32_t)v; return true; }
}
return false;
}
/* True when the file ends in one of these extensions, case-insensitively — what the client
* called the file, which the media readers make the first word of what it holds. */
bool has_ext(const std::string& f, const std::vector<std::string>& exts) {
const size_t d = f.find_last_of('.');
if (d == std::string::npos) return false;
std::string e = f.substr(d + 1);
for (char& c : e) c = (char)std::tolower((unsigned char)c);
for (const std::string& x : exts) if (e == x) return true;
return false;
}
std::string ext_list(const std::vector<std::string>& exts) {
std::string s;
for (const std::string& x : exts) { if (!s.empty()) s += ", "; s += "." + x; }
return s;
}
/* The reference parts of a ref2va request, and their order. Refused with `*err` naming the part
* when one carries no bytes or an extension the media readers do not take, when a kind is over
* the API's or the model's count, when a kind's numbers leave a gap or repeat, or when a
* soundtrack has no video of the same number. On return `refs` is sorted by (kind, number): the
* order the generator builds the conditioning in. */
int validate_refs(std::vector<gen::VideoRefMedia>& refs, const VideoGenInfo& info, ApiError* err) {
if (refs.empty()) {
*err = err_bad("task", "ref2va takes at least one reference part: ref_image_N, "
"ref_video_N, ref_video_audio_N or ref_audio_N");
return -1;
}
const struct {
const char* pfx;
gen::VideoRefMedia::Kind kind;
int32_t cap;
std::vector<std::string> exts;
} kinds[] = {
{ "ref_image", gen::VideoRefMedia::IMAGE,
std::min(kMaxRefImages, (int32_t)info.max_ref_images),
{ "png", "jpg", "jpeg", "webp" } },
{ "ref_video", gen::VideoRefMedia::VIDEO,
std::min(kMaxRefVideos, (int32_t)info.max_ref_videos),
{ "mp4", "mov" } },
{ "ref_video_audio", gen::VideoRefMedia::VIDEO_AUDIO,
std::min(kMaxRefVideos, (int32_t)info.max_ref_videos),
{ "mp4", "mov", "wav", "mp3", "m4a", "aac", "flac", "ogg" } },
{ "ref_audio", gen::VideoRefMedia::AUDIO,
std::min(kMaxRefAudios, (int32_t)info.max_ref_audios),
{ "wav", "mp3", "m4a", "aac", "flac", "ogg" } },
};
for (const auto& k : kinds) {
std::vector<bool> got(k.cap + 1, false);
int n = 0;
for (const gen::VideoRefMedia& m : refs) {
if (m.kind != k.kind) continue;
++n;
if (m.data.empty())
return *err = err_bad(m.name, "'" + m.name + "' carries an empty file"), -1;
if (!has_ext(m.filename, k.exts))
return *err = err_bad(m.name, "'" + m.name + "' must be one of " +
ext_list(k.exts)), -1;
if (m.index > k.cap)
return *err = err_bad(m.name, k.cap == 0
? "this model takes no parts named " +
std::string(k.pfx) + "_N"
: "this model takes at most " +
std::to_string(k.cap) + " parts named " +
std::string(k.pfx) + "_N"), -1;
if (got[m.index])
return *err = err_bad(m.name, "two parts are numbered " + std::string(k.pfx) +
"_" + std::to_string(m.index)), -1;
got[m.index] = true;
}
for (int i = 1; i <= n; ++i)
if (!got[i])
return *err = err_bad(std::string(k.pfx) + "_" + std::to_string(i),
"the " + std::string(k.pfx) + "_N parts must be numbered 1 "
"to " + std::to_string(n) + " without gaps or repeats"), -1;
}
for (const gen::VideoRefMedia& m : refs) {
if (m.kind != gen::VideoRefMedia::VIDEO_AUDIO) continue;
bool paired = false;
for (const gen::VideoRefMedia& v : refs)
paired = paired || (v.kind == gen::VideoRefMedia::VIDEO && v.index == m.index);
if (!paired)
return *err = err_bad(m.name, "'" + m.name + "' is the soundtrack of a reference "
"video; give ref_video_" + std::to_string(m.index) +
" with it"), -1;
}
std::stable_sort(refs.begin(), refs.end(),
[](const gen::VideoRefMedia& a, const gen::VideoRefMedia& b) {
return a.kind != b.kind ? a.kind < b.kind : a.index < b.index;
});
return 0;
}
} /* namespace */
/* The caps the /v1/models and /server_info capability block reports for a video model. The
* counts are the ones validate_refs() will apply — the model's declaration under the API's,
* since a declaration can only lower those — so what a client gates on is what it will meet. */
void Server::video_caps(json& caps, const IVideoGen* gen) {
const VideoGenInfo& info = gen->info();
caps["video_max_text"] = info.max_text;
caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images);
caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos);
caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios);
}
HttpResponse Server::handle_video_create(const HttpRequest& req) {
if (!deps_.videos || !deps_.tok)
return error_response(err_not_implemented(
@@ -127,17 +266,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
req.peer);
const VideoGenInfo& info = deps_.videos->info();
const bool takes_refs = info.max_ref_images > 0 || info.max_ref_videos > 0 ||
info.max_ref_audios > 0;
/* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form,
* since it may carry a file). */
* since it may carry a file). A form may carry the reference media of a ref2va request as
* named file parts; they are collected here and checked once the task is known. */
std::vector<gen::VideoRefMedia> refs;
json body = json::object();
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.filename.empty())
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
return error_response(err_unsupported("input_reference", takes_refs
? "this server reads reference media as "
"ref_image_N file parts"
: "this server makes video from text "
"only"), req.peer);
if (!p.filename.empty()) {
gen::VideoRefMedia m;
if (!parse_ref_name(p.name, &m.kind, &m.index))
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a "
"file"), req.peer);
m.name = p.name;
m.filename = p.filename;
m.content_type = p.content_type;
m.data = p.data;
refs.push_back(std::move(m));
continue;
}
json v = p.data;
if (p.name == "target" || p.name == "conditions") {
v = json::parse(p.data, nullptr, false);
@@ -179,16 +334,41 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
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 "
"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" };
return error_response(e, req.peer);
return error_response(err_unsupported("input_reference", takes_refs
? "this server reads reference media as ref_image_N "
"file parts"
: "this server makes video from text only"),
req.peer);
/* The task: text always; reference conditioning for a model that takes reference media. */
bool ref2va = false;
if (has(body, "task")) {
const std::string task = body["task"].is_string() ? body["task"].get<std::string>() : "";
if (task == "ref2va" && takes_refs) ref2va = true;
else if (task != "t2va") {
ApiError e = err_unsupported("task", takes_refs
? "this server makes video from text or from reference "
"media: t2va, ref2va"
: "this server makes video from text: t2va");
e.supported = takes_refs ? std::vector<std::string>{ "t2va", "ref2va" }
: std::vector<std::string>{ "t2va" };
return error_response(e, req.peer);
}
}
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
return error_response(err_unsupported("conditions", "this server makes video from text "
"only; conditions must be empty"), req.peer);
return error_response(err_unsupported("conditions", takes_refs
? "reference media arrive as ref_* file parts; "
"conditions must be empty"
: "this server makes video from text only; "
"conditions must be empty"), req.peer);
/* The reference parts, in conditioning order, before anything else reads them. Files with no
* task are a caller's mistake about the task, not about the part. */
if (!refs.empty() && !ref2va)
return bad("task", "reference files are given: send them with task ref2va, or send "
"none");
if (ref2va) {
ApiError e;
if (validate_refs(refs, info, &e) < 0) return error_response(e, req.peer);
}
json target = json::object();
if (has(body, "target")) {
if (!body["target"].is_object()) return bad("target", "expected an object");
@@ -314,8 +494,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
r->refs = std::move(refs);
/* ---- the prompt: the template's text with special tokens, the prompt without */
/* ---- the prompt: the template's text with special tokens, the reference media in its
* presentation order, the prompt last (docs/PORT-REF2VA.md §3: images, then videos each
* after its soundtrack's label, then the standalone audios). Each `<Picture k>: ` label is
* encoded as its own string, as the tokenizer the source workflows were checked against sees
* it; the picture's token run follows its label, taken from the processed item. */
{
static const std::string kSlot = "{prompt}";
const std::string& t = info.tmpl;
@@ -325,15 +510,89 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
const auto ids = deps_.tok->encode(s, false, special);
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
};
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
/* The reference media are presented between the template's head and the prompt. Only the
* images reach the language model, so only they are decoded and processed here; a
* reference video's frames and every audio ride the video and audio VAE encoders, which
* the video path does not run in this build yet, so their parts pass through as bytes for
* the generator to refuse at submit naming the part — not silently dropped. (When videos
* land, a soundtrack's `<Audio j>` label is emitted right before its `<Video k>` label,
* the audio ordinal counting soundtracks and standalone audios together, per type.) */
if (ref2va && deps_.mm && deps_.mm->accepts(MediaKind::Image)) {
/* Every picture is decoded and processed before any token is laid down. */
std::vector<std::shared_ptr<mm::Item>> pics;
MediaOpts mo;
mo.max_pixels = (int64_t)W * (int64_t)H; /* `match`: scaled to the output's area */
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
const std::vector<uint8_t> bytes(m.data.begin(), m.data.end());
std::shared_ptr<mm::Item> it;
std::string why;
if (deps_.mm->prepare(MediaKind::Image, bytes, mo, &it, &why) < 0 || !it)
return bad(m.name.c_str(), "'" + m.name + "' could not be used: " + why);
pics.push_back(std::move(it));
}
put(t.substr(0, p), true);
if (!pics.empty()) {
auto media = std::make_shared<mm::PromptMedia>();
size_t i = 0;
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
/* validate_refs numbered each kind 1..n without gaps, so the part's number is
* its presentation ordinal: `<Picture k>: ` then the picture's token run. The
* label is encoded as its own string, as the reference tokenizer's output was
* built. */
put("<Picture " + std::to_string(m.index) + ">: ", false);
mm::Placed pl;
pl.item = pics[i++];
pl.tok = (int32_t)r->tokens.size();
r->tokens.insert(r->tokens.end(), pl.item->expand.begin(),
pl.item->expand.end());
media->items.push_back(std::move(pl));
}
media->layout();
r->media = std::move(media);
}
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
} else {
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
}
if ((int64_t)r->tokens.size() > info.max_text)
return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) +
return bad("prompt", "the prompt" + std::string(ref2va ? " with its reference media"
: "") +
" is " + std::to_string(r->tokens.size()) +
" tokens; this model takes at most " +
std::to_string(info.max_text));
}
/* ---- the encoder's own view of every reference the VAE consumes. The text encoder saw the
* pictures above for identity; now each is also decoded and shrunk to the encoder's grid so the
* video VAE can turn it into conditioning rows. The driver stages these bytes into a Vencode
* pass; reference videos and their soundtracks, and the standalone audios, ride the same two
* encoders but are still refused at submit until those decode paths land, so only pictures are
* prepared here. The processor decodes under the same guard it used for the text encoder, so a
* reference that got this far decodes here too. */
if (ref2va && info.encodes && deps_.mm) {
for (gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
mm::Frame fr;
std::string why;
if (deps_.mm->encoder_image((const uint8_t*)m.data.data(), m.data.size(),
(int32_t)info.enc_ratio, (int32_t)info.max_enc_side, &fr,
&why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be encoded: " + why);
m.enc_frames = 1;
m.enc_h = fr.h;
m.enc_w = fr.w;
/* un-normalised RGB 0..255, row-major; the video VAE applies ImageNet mean/std itself */
m.enc_pixels.resize((size_t)fr.w * fr.h * 3);
for (size_t i = 0; i < m.enc_pixels.size(); ++i)
m.enc_pixels[i] = (float)fr.rgb[i];
}
}
/* ---- admitted and queued: the job holds its place until its file is written */
if (auto no = admit(1, req.peer)) return *no;
auto j = std::make_shared<VideoJob>();
@@ -344,6 +603,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
for (const gen::VideoRefMedia& m : r->refs) j->refs.push_back(m.name);
j->ticket = std::make_shared<gen::VideoTicket>();
r->ticket = j->ticket;
const int64_t n_tok = (int64_t)r->tokens.size();
@@ -365,13 +625,14 @@ 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",
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s%s, seed=%llu",
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.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,
(int)tk.small_height, (int)tk.refine).c_str()
: "",
j->refs.empty() ? "" : rad::fmt(", %zu reference parts", j->refs.size()).c_str(),
(unsigned long long)j->seed);
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
@@ -530,6 +791,10 @@ json Server::video_json(const VideoJob& j) {
o["upscale_refine_steps"] = j.refine;
o["upscale_from"] = j.upscale_from;
}
if (!j.refs.empty()) {
o["task"] = "ref2va";
o["refs"] = j.refs; /* the reference parts, in conditioning order */
}
o["remixed_from_video_id"] = nullptr;
if (j.failed) {
json e;