merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port

Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.

Notable reconciliations:
  * videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
    (i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
    so upstream models keep refusing them as unknown tasks; input_reference,
    the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
    coexist with refs/ref2va; the prompt put() helper hoisted to block scope
    for the media branch.
  * video_schedule(): upstream's (steps, video_tokens, refine) keeps its
    positional slots; the port's shift_video/shift_audio overrides move to the
    tail so upstream's schedule tests call unchanged.
  * r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
    upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
    2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
    upstream's wadd/norm_once/norm parameters.
  * tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
    staging dir -- plugin .so files still land in the absolute
    RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
    relative bin/, which needs no root.

Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-22 18:38:04 -05:00
commit a1a75da7e9
415 files changed
+78837 -5310

No files matched your search

+317 -56
View File
@@ -23,7 +23,8 @@ 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;
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0, AX = 0;
bool joint = false;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
@@ -34,11 +35,15 @@ 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;
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
z.AX = d.aux_tokens ? d.aux_max_tokens : 0;
return z;
}
@@ -47,6 +52,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 +62,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 +77,21 @@ 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 */
{ 0, (z.AX ? z.AX + 2 : 0) * I }, /* R_AUX: a COND's {0, n} and second-tokenizer ids */
{ 0, z.S * 4 }, /* R_SIGP */
{ 0, z.S * 4 }, /* R_TSTEP */
{ 0, z.S * I }, /* R_SAMP */
{ 0, z.S * I }, /* R_STEPI */
{ 0, 2 * z.S * 4 }, /* R_SIZE */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -84,8 +105,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 +120,34 @@ 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) {
table_ = DiscreteTable{};
if (discrete()) {
std::string why;
if (discrete_table(decl_, &table_, &why) < 0) {
RAD_ERR("image generator: %s", why.c_str());
return RAD_E_INVAL;
}
}
/* 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,15 +222,19 @@ 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)
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
for (const Branch* b : { &r->pos, &r->neg }) {
if (b == &r->neg && !r->has_neg) continue;
if (d.aux_tokens && (b->aux.empty() || (int64_t)b->aux.size() > d.aux_max_tokens))
return no("the prompt is " + std::to_string(b->aux.size()) + " tokens to the "
"model's second tokenizer, which reads 1.." +
std::to_string(d.aux_max_tokens));
if ((int64_t)b->tokens.size() > max_tok_)
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
@@ -209,6 +254,10 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
r->inp_src.h != r->height))
return no("the mask's picture is not at the size being made");
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
if (discrete() && (r->sampler < 0 || r->sampler >= RAD_GEN_SAMPLER_COUNT ||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
r->scheduler >= RAD_GEN_SCHED_COUNT))
return no("the sampler or scheduler is not one this model serves");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -293,22 +342,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)) {
@@ -333,12 +396,24 @@ int Driver::admit_locked() {
release_kv_locked(j);
break;
}
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
if (discrete()) {
j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps);
j.tsteps.clear();
for (float sg : j.sigmas) j.tsteps.push_back(sg > 0 ? (float)table_.timestep(sg) : 0.0f);
} else {
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
}
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 +488,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 +506,30 @@ 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;
G.n_aux = 0;
G.aux_ids = nullptr;
G.aux_cu = nullptr;
G.sigma_prev = nullptr;
G.timestep = nullptr;
G.sampler = nullptr;
G.step = nullptr;
G.size_px = nullptr;
G.entry_h = nullptr;
G.tokens_h = nullptr;
}
}
@@ -469,28 +568,35 @@ const RadBatch* Driver::next(int step) {
for (int b = 0; b < j.n_branch; ++b)
if (!j.cond[b].encoded) return build_cond(j, b, step);
}
/* 3. A denoise step over what is in flight, oldest request first. */
/* 3. A denoise step over what is in flight, oldest request first, with the oldest one's
* adapters: a pass runs one runtime LoRA slot in every row. */
std::vector<int32_t> take;
int64_t rows = 0, entries = 0;
int32_t lora = -2;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
bool ready = true;
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
if (!ready) continue;
if (lora != -2 && j.req->lora_slot != lora) continue;
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
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;
take.push_back(l);
lora = j.req->lora_slot;
}
}
if (take.empty()) return nullptr;
return build_denoise(take, step);
const RadBatch* b = build_denoise(take, step);
pass_.lora_slot = lora;
return b;
}
const RadBatch* Driver::batch_for(int rank) const {
@@ -503,15 +609,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 +681,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 +690,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. */
@@ -628,11 +749,21 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
/* The conditioning is modulated at t = 0. */
hptr<float>(R_SIG)[0] = 0.0f;
reg_[R_SIG].used = 4;
/* The prompt through the second tokenizer, for a model that reads it. */
const int64_t n_aux = decl_.aux_tokens ? (int64_t)br.aux.size() : 0;
if (n_aux) {
int32_t* ax = hptr<int32_t>(R_AUX);
ax[0] = 0;
ax[1] = (int32_t)n_aux;
std::memcpy(ax + 2, br.aux.data(), (size_t)n_aux * 4);
reg_[R_AUX].used = (n_aux + 2) * 4;
}
/* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver
* 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,9 +812,25 @@ 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;
G.n_aux = n_aux;
G.aux_cu = n_aux ? dptr<int32_t>(ri, R_AUX) : nullptr;
G.aux_ids = n_aux ? dptr<int32_t>(ri, R_AUX) + 2 : nullptr;
G.tokens_h = hptr<int32_t>(R_TOK);
G.cond_opts = j.req->cond_opts;
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;
pass_.lora_slot = j.req->lora_slot;
pass_.branch = branch;
return &out_[0];
}
@@ -699,15 +846,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);
@@ -721,6 +881,12 @@ const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step
uint32_t* seed = hptr<uint32_t>(R_SEED);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
float* sigp = hptr<float>(R_SIGP);
float* tstep = hptr<float>(R_TSTEP);
int32_t* samp = hptr<int32_t>(R_SAMP);
int32_t* stepi = hptr<int32_t>(R_STEPI);
float* size = hptr<float>(R_SIZE);
host_entry_.assign((size_t)(4 * S), 0);
int64_t row = 0;
cu[0] = 0;
pass_.lanes.clear();
@@ -731,13 +897,51 @@ 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];
sign[i] = j.sigmas[(size_t)ln.step + 1];
sigp[i] = ln.step > 0 ? j.sigmas[(size_t)ln.step - 1] : 0.0f;
tstep[i] = discrete() ? j.tsteps[(size_t)ln.step] : 0.0f;
samp[i] = j.req->sampler;
stepi[i] = ln.step;
size[2 * i] = (float)j.req->height;
size[2 * i + 1] = (float)j.req->width;
host_entry_[(size_t)(4 * i)] = joint() ? (int32_t)c.lay.rows : 0;
host_entry_[(size_t)(4 * i + 1)] = j.req->height;
host_entry_[(size_t)(4 * i + 2)] = j.req->width;
host_entry_[(size_t)(4 * i + 3)] = e.branch;
const bool neg = e.branch == 1;
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
@@ -758,6 +962,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 +970,48 @@ 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_SIGP].used = reg_[R_TSTEP].used = reg_[R_SAMP].used = reg_[R_STEPI].used = S * 4;
reg_[R_SIZE].used = 2 * 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 +1030,28 @@ 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);
G.sigma_prev = dptr<float>(ri, R_SIGP);
G.timestep = dptr<float>(ri, R_TSTEP);
G.sampler = dptr<int32_t>(ri, R_SAMP);
G.step = dptr<int32_t>(ri, R_STEPI);
G.size_px = dptr<float>(ri, R_SIZE);
G.entry_h = host_entry_.data();
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];
+20 -1
View File
@@ -60,6 +60,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
/* A decode pass's pixels: `image_out` into the pinned image buffer. */
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -75,6 +76,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;
@@ -84,6 +86,8 @@ private:
int32_t h_lat = 0, w_lat = 0;
int64_t tokens = 0;
std::vector<float> sigmas;
/* A discrete-time model's: each step's timestep, beside `sigmas`. */
std::vector<float> tsteps;
std::vector<int32_t> lanes;
std::vector<std::pair<int32_t, int32_t>> ref_hw;
int32_t images_done = 0;
@@ -111,13 +115,15 @@ private:
bool preview = false;
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
std::vector<char> marks; /* ... and whether each was marked for a preview */
int32_t lora_slot = -1; /* every image of a pass runs with the same adapters */
};
/* 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_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_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
int layout_regions();
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
@@ -133,12 +139,22 @@ 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);
RadGeneratorDecl decl_{};
std::vector<double> fixed_;
/* A discrete-time model's sigma table (RadGeneratorDecl::train_steps), empty otherwise. */
DiscreteTable table_;
bool discrete() const { return decl_.train_steps > 0; }
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
int64_t max_rows_ = 0; /* the longest conditioning sequence */
int64_t max_px_ = 0; /* pixels the staging holds */
@@ -162,6 +178,9 @@ 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_;
/* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */
std::vector<int32_t> host_entry_;
int64_t host_nmode_[3] = { 0, 0, 0 };
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
+192
View File
@@ -67,6 +67,16 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
std::vector<float> s;
if (!fixed.empty()) {
for (double v : fixed) s.push_back((float)v);
} else if (d.sigma_grid > 0) {
/* ComfyUI's `simple` scheduler: the model's table holds t = k / N for k = 1..N (an f32
* quotient), and step i reads entry N - 1 - floor(i N / n), the floor of a Python float. */
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
const int64_t N = d.sigma_grid;
const double ss = (double)N / (double)n;
for (int32_t i = 0; i < n; ++i) {
const int64_t k = N - (int64_t)((double)i * ss);
s.push_back((float)k / (float)N);
}
} else {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
@@ -94,6 +104,127 @@ std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>
return s;
}
/* ================================================================== a discrete-time schedule */
float DiscreteTable::sigma_at(double t) const {
const double hi = (double)(log_sigmas.size() - 1);
t = t < 0.0 ? 0.0 : t > hi ? hi : t;
const size_t lo = (size_t)std::floor(t), up = (size_t)std::ceil(t);
const float w = (float)(t - std::floor(t));
return std::exp((1.0f - w) * log_sigmas[lo] + w * log_sigmas[up]);
}
int32_t DiscreteTable::timestep(float sigma) const {
const float l = std::log(sigma);
int32_t best = 0;
float bd = std::fabs(l - log_sigmas[0]);
for (size_t i = 1; i < log_sigmas.size(); ++i) {
const float d = std::fabs(l - log_sigmas[i]);
if (d < bd) { bd = d; best = (int32_t)i; }
}
return best;
}
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why) {
const int32_t n = d.train_steps;
if (n < 2 || !(d.beta_start > 0) || !(d.beta_end > d.beta_start) || d.beta_end >= 1 ||
(d.beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && d.beta_schedule != RAD_GEN_BETAS_LINEAR)) {
if (why) *why = "the discrete schedule needs two or more timesteps and betas rising in (0, 1)";
return RAD_E_INVAL;
}
std::vector<double> sig((size_t)n);
double abar = 1.0;
const bool sq = d.beta_schedule == RAD_GEN_BETAS_SCALED_LINEAR;
const double a = sq ? std::sqrt(d.beta_start) : d.beta_start;
const double b = sq ? std::sqrt(d.beta_end) : d.beta_end;
for (int32_t i = 0; i < n; ++i) {
const double v = a + (b - a) * (double)i / (double)(n - 1);
abar *= 1.0 - (sq ? v * v : v);
sig[(size_t)i] = std::sqrt((1.0 - abar) / abar);
}
if (d.zero_snr) {
/* ComfyUI's rescale_zero_terminal_snr_sigmas: sqrt(abar) shifted to end at 0 and scaled
* to keep its start, the last abar then set to a small positive value. */
std::vector<double> s((size_t)n);
for (int32_t i = 0; i < n; ++i) s[(size_t)i] = std::sqrt(1.0 / (sig[(size_t)i] * sig[(size_t)i] + 1.0));
const double s0 = s.front(), sT = s.back();
for (int32_t i = 0; i < n; ++i) {
double v = (s[(size_t)i] - sT) * (s0 / (s0 - sT));
double ab = v * v;
if (i == n - 1) ab = 4.8973451890853435e-08;
sig[(size_t)i] = std::sqrt((1.0 - ab) / ab);
}
}
out->sigmas.resize((size_t)n);
out->log_sigmas.resize((size_t)n);
for (int32_t i = 0; i < n; ++i) {
out->sigmas[(size_t)i] = (float)sig[(size_t)i];
out->log_sigmas[(size_t)i] = (float)std::log(sig[(size_t)i]);
}
return RAD_OK;
}
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps) {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
std::vector<float> s;
const double smin = t.sigma_min(), smax = t.sigma_max();
/* A point i of n evenly spaced from `a` to `b`, both ends included. */
auto lin = [](double a, double b, int32_t i, int32_t cnt) {
return cnt <= 1 ? a : a + (b - a) * (double)i / (double)(cnt - 1);
};
switch (scheduler) {
case RAD_GEN_SCHED_KARRAS: {
const double rho = 7.0, lo = std::pow(smin, 1.0 / rho), hi = std::pow(smax, 1.0 / rho);
for (int32_t i = 0; i < n; ++i) s.push_back((float)std::pow(lin(hi, lo, i, n), rho));
break;
}
case RAD_GEN_SCHED_EXPONENTIAL:
for (int32_t i = 0; i < n; ++i)
s.push_back((float)std::exp(lin(std::log(smax), std::log(smin), i, n)));
break;
case RAD_GEN_SCHED_SIMPLE: {
const double stride = (double)t.sigmas.size() / (double)n;
for (int32_t i = 0; i < n; ++i)
s.push_back(t.sigmas[t.sigmas.size() - 1 - (size_t)((double)i * stride)]);
break;
}
case RAD_GEN_SCHED_SGM_UNIFORM:
case RAD_GEN_SCHED_NORMAL:
default: {
/* Timesteps from the largest sigma's to the smallest's, evenly spaced; sgm_uniform
* spaces n + 1 and drops the last. The model's clock ends at 0. */
const double a = (double)t.timestep(t.sigma_max()), b = (double)t.timestep(t.sigma_min());
const bool sgm = scheduler == RAD_GEN_SCHED_SGM_UNIFORM;
const int32_t cnt = sgm ? n + 1 : n;
for (int32_t i = 0; i < n; ++i) s.push_back(t.sigma_at(lin(a, b, i, cnt)));
break;
}
}
s.push_back(0.0f);
return s;
}
namespace {
const char* const kSamplers[RAD_GEN_SAMPLER_COUNT] = { "euler", "euler_ancestral", "dpmpp_2m" };
const char* const kScheds[RAD_GEN_SCHED_COUNT] = { "normal", "karras", "exponential",
"sgm_uniform", "simple" };
} /* namespace */
const char* sampler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SAMPLER_COUNT ? kSamplers[id] : "";
}
const char* scheduler_name(int32_t id) {
return id >= 0 && id < RAD_GEN_SCHED_COUNT ? kScheds[id] : "";
}
int32_t sampler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) if (name == kSamplers[i]) return i;
return -1;
}
int32_t scheduler_id(const std::string& name) {
for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) if (name == kScheds[i]) return i;
return -1;
}
/* ================================================================== the sequence */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
@@ -106,6 +237,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) {
+52
View File
@@ -48,6 +48,9 @@ struct Branch {
std::vector<int32_t> tokens;
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
int32_t n_drop = 0;
/* The user's prompt through the model's second tokenizer (RadGeneratorDecl::aux_tokens);
* empty otherwise. */
std::vector<int32_t> aux;
};
/* One finished image, or a preview of one. */
@@ -99,6 +102,8 @@ struct Request {
float cfg = 1.0f;
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
/* A discrete-time model's sampler and scheduler (RAD_GEN_SAMPLER_*, RAD_GEN_SCHED_*). */
int32_t sampler = 0, scheduler = 0;
int32_t n = 1;
uint64_t seed = 0; /* image i draws its noise from seed + i */
int32_t previews = 0; /* partial images per image, 0..3 */
@@ -109,6 +114,12 @@ struct Request {
bool inpaint = false;
Pixels inp_src;
std::vector<float> inp_mask;
/* The runtime LoRA slot every pass of the request runs with (Engine::gen_lora_acquire), -1
* for none, and the hold that keeps the slot's adapters in it until the request is done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
/* RAD_GEN_COND_* for the plugin's COND passes (`rebalance`: Krea 2's tap gains). */
int32_t cond_opts = 0;
std::shared_ptr<Ticket> ticket;
};
@@ -119,6 +130,31 @@ struct Request {
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens);
/* ================================================================== a discrete-time schedule */
/* The sigma table of a model trained on discrete timesteps (RadGeneratorDecl::train_steps), as
* ComfyUI's ModelSamplingDiscrete builds it: betas in f64, their cumulative product, sigma_t =
* sqrt((1 - abar_t) / abar_t), then f32, and the f32 logs. */
struct DiscreteTable {
std::vector<float> sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */
std::vector<float> log_sigmas;
float sigma_min() const { return sigmas.front(); }
float sigma_max() const { return sigmas.back(); }
/* sigma at a fractional timestep: the logs interpolated linearly, t clamped to the table. */
float sigma_at(double t) const;
/* The timestep a sigma is conditioned at: the table's nearest in log sigma. */
int32_t timestep(float sigma) const;
};
/* RAD_E_INVAL with `why` for a declaration whose schedule cannot be built. */
int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why);
/* The n + 1 sigmas `scheduler` places for `steps` (0: the default) steps, the last 0. */
std::vector<float> schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t,
int32_t scheduler, int32_t steps);
/* The names a request spells samplers and schedulers by, and their ids (-1: none). */
const char* sampler_name(int32_t id);
const char* scheduler_name(int32_t id);
int32_t sampler_id(const std::string& name);
int32_t scheduler_id(const std::string& name);
/* ================================================================== the generator's sequence */
/* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or
* reference latent row behind each row, rotary positions, segments, and the output image's frame. */
@@ -129,6 +165,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 +178,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 */
+2
View File
@@ -29,6 +29,8 @@ struct IPassDriver {
* `step` is the engine's pass counter, carried into RadBatch::step. */
virtual const RadBatch* next(int step) = 0;
virtual const RadBatch* batch_for(int rank) const = 0;
/* The runtime LoRA slot every row of the staged pass runs with, -1 for none. */
virtual int32_t lora_slot() const { return -1; }
/* What the staged pass's results are, valid until done(). */
virtual const std::vector<Readback>& readbacks() const = 0;
/* The pass has run on every rank, its streams are drained and the readbacks have landed. */
+33 -10
View File
@@ -11,6 +11,7 @@
#include "mm/processor.h"
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <deque>
#include <memory>
@@ -23,12 +24,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;
};
@@ -50,7 +52,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;
@@ -153,6 +156,22 @@ struct VideoRequest {
* 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;
/* 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;
/* The runtime LoRA slot the request's conditioning and denoising passes run with
* (Engine::gen_lora_acquire), -1 for none, and the hold that keeps it until the request is
* done. */
int32_t lora_slot = -1;
std::shared_ptr<void> lora_hold;
std::shared_ptr<VideoTicket> ticket;
};
@@ -170,17 +189,21 @@ 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. `shift_video`/`shift_audio`
* above 0 override the declaration's per-stream shift for the exponential sigma shift; 0 keeps the
* declaration's. The shift only re-shapes the staged sigmas, so it reaches the plugin through the
* schedule region, not the batch. */
/* 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. `shift_video`/`shift_audio` above 0 override
* the declaration's per-stream shift for the exponential sigma shift; 0 keeps the declaration's.
* The shift only re-shapes the staged sigmas, so it reaches the plugin through the schedule
* region, not the batch. */
struct VideoSchedule {
std::vector<float> sig_v, sig_a;
int32_t steps = 0;
};
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, double shift_video = 0.0,
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0,
bool refine = false, double shift_video = 0.0,
double shift_audio = 0.0);
} /* namespace gen */
+522 -298
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>
@@ -78,7 +79,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;
}
@@ -123,12 +124,51 @@ static std::vector<float> rung_sigmas(double shift, const double* rungs, int32_t
return s;
}
VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, double shift_video,
double shift_audio) {
/* A request's shift overrides the declaration's per stream; 0 keeps the trained value. */
/* 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, double shift_video, double shift_audio) {
/* A request's shift overrides the declaration's per stream; 0 keeps the trained value. Form 1
* ignores both: its shift is the declaration's, dynamic or terminal. */
const double sv = shift_video > 0.0 ? shift_video : d.shift_video;
const double sa = shift_audio > 0.0 ? shift_audio : d.shift_audio;
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(sv, d.rungs, d.n_rungs);
@@ -163,10 +203,12 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
* 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) {
/* 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, a conditioning's [3,T] M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
16 * 4, /* R_SCHED: the Euler scalars [0..5], then the res_multistep
@@ -190,6 +232,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
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) */
kSegCap * 4, /* R_MOD: the merged modulation-group boundaries (<= R_SEG) */
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) {
@@ -252,9 +296,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];
@@ -268,7 +320,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_);
@@ -362,6 +415,8 @@ void VideoDriver::fini() {
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
if (enc_dbg_host_) rad_dev_free(enc_dbg_host_, RAD_MEM_HOST_PINNED);
if (dit_host_) rad_dev_free(dit_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;
@@ -370,6 +425,358 @@ void VideoDriver::fini() {
}
/* ================================================================== 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;
/* The step's row count and its positions. A reference-conditioned step widens them; the
* encode queue and the pack's table are built first because the layout depends on them. */
j.ref_tab.clear();
j.enc_q.clear();
/* 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. `kind` is a pack Ref2VARefKind (picture 0,
* standalone audio 1, video 2), the server's VIDEO_AUDIO being folded into its video's `audio`
* word rather than a row of its own. Each reference's slot is the one its encode pass folds its
* latents into, and its latent counts come from the encoder's own geometry, not hand arithmetic:
* a picture is one latent frame (its grid the encoder's sides over the VAE ratio); a video's
* frames and its soundtrack's are the Vencode/Aencode latent counts rad_arch_encode_geom gives
* (a video's are the same before and after the encode pass clip-pads its short final clip). The
* table must exist before the step layout is decided, because when the denoiser consumes it the
* reference rows are part of that layout. Endpoint keyframes (a first and/or last frame pinned
* at the output's ends) are appended after the reference rows as {frame, video_t, audio_t}
* triples; a request carries either references or keyframes, never both. */
if (d.encodes) {
bool need_geom = false;
for (const VideoRefMedia& m : r.refs)
if (m.kind != VideoRefMedia::IMAGE && m.kind != VideoRefMedia::FIRST_FRAME &&
m.kind != VideoRefMedia::LAST_FRAME) need_geom = true;
if (need_geom && !enc_geom_)
return no("the request carries a reference video or audio, but this plugin exports no "
"rad_arch_encode_geom, so their encoder geometry cannot be sized");
int32_t eg[25];
/* A reference's latent frame counts, straight from the encoder's geometry. */
auto video_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_frames, m.enc_h, m.enc_w, 3 };
return enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[24];
};
auto audio_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_n, 0, 0, m.enc_channels };
return enc_geom_(RAD_GEN_PASS_AENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[12];
};
/* Pictures and videos share a side-grid check against the VAE ratio. */
auto bad_side = [&](const VideoRefMedia& m) {
return 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;
};
for (size_t i = 0; i < r.refs.size(); ++i) {
const VideoRefMedia& m = r.refs[i];
if (m.kind == VideoRefMedia::IMAGE) {
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 (bad_side(m))
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*/});
} else if (m.kind == VideoRefMedia::VIDEO) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no video slot (1..3)");
if (bad_side(m))
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");
/* A soundtrack given for this video (ref_video_audio_N) is folded into THIS row's
* `audio` word, not a row of its own; the pack lays its block right before the
* video's and the scatter reads the two back as the pair they are. It is encoded at
* the VIDEO's slot, since aenc_slot_row numbers a soundtrack by its video. */
int64_t a_t = 0;
for (size_t k = 0; k < r.refs.size(); ++k) {
const VideoRefMedia& a = r.refs[k];
if (a.kind != VideoRefMedia::VIDEO_AUDIO || a.index != m.index) continue;
if (a.enc_samples.empty() || a.enc_n < 1 || a.enc_channels < 1)
return no("'" + a.name + "' (the soundtrack of '" + m.name +
"') was not prepared for the audio encoder");
a_t = audio_lat(a);
if (a_t < 1)
return no("the audio encoder refuses the soundtrack '" + a.name + "'");
j.enc_q.push_back({RAD_ENC_VAUDIO, m.index, (int32_t)k});
}
const int64_t v_t = video_lat(m);
if (v_t < 1) return no("the video encoder refuses '" + m.name + "'");
j.enc_q.push_back({RAD_ENC_VIDEO, m.index, (int32_t)i});
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0);
++j.ref_tab[0];
j.ref_tab.insert(j.ref_tab.end(),
{2 /*a video*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), (int32_t)v_t, (int32_t)a_t});
} else if (m.kind == VideoRefMedia::AUDIO) {
if (m.enc_samples.empty() || m.enc_n < 1 || m.enc_channels < 1)
return no("'" + m.name + "' was not prepared for the audio encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no audio slot (1..3)");
const int64_t a_t = audio_lat(m);
if (a_t < 1) return no("the audio encoder refuses '" + m.name + "'");
j.enc_q.push_back({RAD_ENC_AUDIO, m.index, (int32_t)i});
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0);
++j.ref_tab[0];
j.ref_tab.insert(j.ref_tab.end(),
{1 /*a standalone audio*/, m.index, 0, 0, 0, (int32_t)a_t});
}
/* VIDEO_AUDIO rows are folded into their video above, so they take no row here. */
}
/* Endpoint keyframes: each FIRST_FRAME/LAST_FRAME the server resized to the target canvas
* and staged in enc_pixels folds into the pack's KEYFRAME table -- not a reference row. The
* DiT reads its latent rows PINNED at that frame's moment on the target timeline (denoised
* never): the first pins output frame 0, the last the final frame, and the gap between is
* diffused. The key triple is {pixel frame, video_t, audio_t}; a picture anchor is video-only
* (video_t = one latent frame, audio_t = 0), and its pixel frame is 0 or frames-1 -- the same
* resolved frame index the reference's MiniMaxH3ImageToVideo assigns. Its latents ride the
* image slot its keyframe ORDER names (1, then 2): a keyframe request carries no references,
* so those slots are free, and ref_parts -- and the scatter -- read them back by the same
* order. Keyframe rows are appended after every reference row, which is where ref_pack_of
* reads the table's key block. */
for (size_t i = 0; i < r.refs.size(); ++i) {
const VideoRefMedia& m = r.refs[i];
const bool first = m.kind == VideoRefMedia::FIRST_FRAME;
if (!first && m.kind != VideoRefMedia::LAST_FRAME) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (bad_side(m))
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");
if (j.ref_tab.empty()) j.ref_tab.assign(2, 0); /* [n_refs, n_keys] */
const int32_t slot = ++j.ref_tab[1]; /* keyframe order -> image slot 1, 2 */
j.enc_q.push_back({RAD_ENC_IMAGE, slot, (int32_t)i});
j.ref_tab.insert(j.ref_tab.end(),
{first ? 0 : s.frames - 1, 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 (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;
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 modulation groups. A modulation cell is fixed by a segment's kind, so the denoiser
* merges runs of consecutive same-cell segments and pitches its fixed-width table by the
* GROUP count, not the reference count -- which is how nine reference photos (four groups:
* prompt, all-photos, soundtrack, video) ride a table the fine layout (twelve segments)
* would overrun. The plugin merges for us (rad_arch_video_mod_segs); one that exports none
* merges nothing, so the group table is the fine one and the older per-segment ceiling
* applies. Refuse over-wide merges here, at submit, where a clean answer is still possible. */
int nmod = -1;
if (mod_segs_) {
j.mod_seg.assign((size_t)kSegCap, 0);
nmod = (int)mod_segs_(&j.geom, j.ref_tab.data(), j.mod_seg.data(), kSegCap);
if (nmod < 0 || nmod > kSegCap)
return no("the model could not merge the reference conditioning into its "
"modulation groups");
j.mod_seg.resize((size_t)nmod);
} else {
nmod = nseg; /* nothing merges: the groups are the fine segments */
j.mod_seg = j.seg;
}
j.nmod = nmod;
const int ngroups = nmod - 1; /* `mod_seg` is boundaries: one more than the groups */
if (d.max_ref_segs > 0 && ngroups > d.max_ref_segs)
return no("these references change the conditioning's modulation cell " +
std::to_string(ngroups) + " times, but this deployment's modulation table holds " +
std::to_string(d.max_ref_segs) + " cells -- ask for references that share their "
"modalities and target, or fewer of them");
/* `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 = j.geom.n_text + 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 = 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);
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;
}
/* 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, r.shift_video, r.shift_audio);
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.step_rows; /* the conditioned step's real length, references included */
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_;
@@ -436,7 +843,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
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)
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;
@@ -448,287 +855,46 @@ 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;
/* 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. `kind` is a pack Ref2VARefKind (picture 0,
* standalone audio 1, video 2), the server's VIDEO_AUDIO being folded into its video's `audio`
* word rather than a row of its own. Each reference's slot is the one its encode pass folds its
* latents into, and its latent counts come from the encoder's own geometry, not hand arithmetic:
* a picture is one latent frame (its grid the encoder's sides over the VAE ratio); a video's
* frames and its soundtrack's are the Vencode/Aencode latent counts rad_arch_encode_geom gives
* (a video's are the same before and after the encode pass clip-pads its short final clip). The
* table must exist before the step layout is decided, because when the denoiser consumes it the
* reference rows are part of that layout. Endpoint keyframes (a first and/or last frame pinned
* at the output's ends) are appended after the reference rows as {frame, video_t, audio_t}
* triples; a request carries either references or keyframes, never both. */
if (d.encodes) {
bool need_geom = false;
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE && m.kind != VideoRefMedia::FIRST_FRAME &&
m.kind != VideoRefMedia::LAST_FRAME) need_geom = true;
if (need_geom && !enc_geom_)
return no("the request carries a reference video or audio, but this plugin exports no "
"rad_arch_encode_geom, so their encoder geometry cannot be sized");
int32_t eg[25];
/* A reference's latent frame counts, straight from the encoder's geometry. */
auto video_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_frames, m.enc_h, m.enc_w, 3 };
return enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[24];
};
auto audio_lat = [&](const VideoRefMedia& m) -> int64_t {
int64_t in[4] = { m.enc_n, 0, 0, m.enc_channels };
return enc_geom_(RAD_GEN_PASS_AENCODE, in, eg, 25) < 0 ? -1 : (int64_t)eg[12];
};
/* Pictures and videos share a side-grid check against the VAE ratio. */
auto bad_side = [&](const VideoRefMedia& m) {
return 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;
};
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
if (m.kind == VideoRefMedia::IMAGE) {
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 (bad_side(m))
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*/});
} else if (m.kind == VideoRefMedia::VIDEO) {
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no video slot (1..3)");
if (bad_side(m))
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");
/* A soundtrack given for this video (ref_video_audio_N) is folded into THIS row's
* `audio` word, not a row of its own; the pack lays its block right before the
* video's and the scatter reads the two back as the pair they are. It is encoded at
* the VIDEO's slot, since aenc_slot_row numbers a soundtrack by its video. */
int64_t a_t = 0;
for (size_t k = 0; k < r->refs.size(); ++k) {
const VideoRefMedia& a = r->refs[k];
if (a.kind != VideoRefMedia::VIDEO_AUDIO || a.index != m.index) continue;
if (a.enc_samples.empty() || a.enc_n < 1 || a.enc_channels < 1)
return no("'" + a.name + "' (the soundtrack of '" + m.name +
"') was not prepared for the audio encoder");
a_t = audio_lat(a);
if (a_t < 1)
return no("the audio encoder refuses the soundtrack '" + a.name + "'");
j->enc_q.push_back({RAD_ENC_VAUDIO, m.index, (int32_t)k});
}
const int64_t v_t = video_lat(m);
if (v_t < 1) return no("the video encoder refuses '" + m.name + "'");
j->enc_q.push_back({RAD_ENC_VIDEO, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0);
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{2 /*a video*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), (int32_t)v_t, (int32_t)a_t});
} else if (m.kind == VideoRefMedia::AUDIO) {
if (m.enc_samples.empty() || m.enc_n < 1 || m.enc_channels < 1)
return no("'" + m.name + "' was not prepared for the audio encoder");
if (m.index < 1 || m.index > 3)
return no("'" + m.name + "' has no audio slot (1..3)");
const int64_t a_t = audio_lat(m);
if (a_t < 1) return no("the audio encoder refuses '" + m.name + "'");
j->enc_q.push_back({RAD_ENC_AUDIO, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0);
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{1 /*a standalone audio*/, m.index, 0, 0, 0, (int32_t)a_t});
}
/* VIDEO_AUDIO rows are folded into their video above, so they take no row here. */
}
/* Endpoint keyframes: each FIRST_FRAME/LAST_FRAME the server resized to the target canvas
* and staged in enc_pixels folds into the pack's KEYFRAME table -- not a reference row. The
* DiT reads its latent rows PINNED at that frame's moment on the target timeline (denoised
* never): the first pins output frame 0, the last the final frame, and the gap between is
* diffused. The key triple is {pixel frame, video_t, audio_t}; a picture anchor is video-only
* (video_t = one latent frame, audio_t = 0), and its pixel frame is 0 or frames-1 -- the same
* resolved frame index the reference's MiniMaxH3ImageToVideo assigns. Its latents ride the
* image slot its keyframe ORDER names (1, then 2): a keyframe request carries no references,
* so those slots are free, and ref_parts -- and the scatter -- read them back by the same
* order. Keyframe rows are appended after every reference row, which is where ref_pack_of
* reads the table's key block. */
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
const bool first = m.kind == VideoRefMedia::FIRST_FRAME;
if (!first && m.kind != VideoRefMedia::LAST_FRAME) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (bad_side(m))
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");
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
const int32_t slot = ++j->ref_tab[1]; /* keyframe order -> image slot 1, 2 */
j->enc_q.push_back({RAD_ENC_IMAGE, slot, (int32_t)i});
j->ref_tab.insert(j->ref_tab.end(),
{first ? 0 : s.frames - 1, 1 /*one latent frame*/, 0 /*no soundtrack*/});
}
/* 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");
}
/* 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 (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;
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 modulation groups. A modulation cell is fixed by a segment's kind, so the denoiser
* merges runs of consecutive same-cell segments and pitches its fixed-width table by the
* GROUP count, not the reference count -- which is how nine reference photos (four groups:
* prompt, all-photos, soundtrack, video) ride a table the fine layout (twelve segments)
* would overrun. The plugin merges for us (rad_arch_video_mod_segs); one that exports none
* merges nothing, so the group table is the fine one and the older per-segment ceiling
* applies. Refuse over-wide merges here, at submit, where a clean answer is still possible. */
int nmod = -1;
if (mod_segs_) {
j->mod_seg.assign((size_t)kSegCap, 0);
nmod = (int)mod_segs_(&j->geom, j->ref_tab.data(), j->mod_seg.data(), kSegCap);
if (nmod < 0 || nmod > kSegCap)
return no("the model could not merge the reference conditioning into its "
"modulation groups");
j->mod_seg.resize((size_t)nmod);
} else {
nmod = nseg; /* nothing merges: the groups are the fine segments */
j->mod_seg = j->seg;
}
j->nmod = nmod;
const int ngroups = nmod - 1; /* `mod_seg` is boundaries: one more than the groups */
if (d.max_ref_segs > 0 && ngroups > d.max_ref_segs)
return no("these references change the conditioning's modulation cell " +
std::to_string(ngroups) + " times, but this deployment's modulation table holds " +
std::to_string(d.max_ref_segs) + " cells -- ask for references that share their "
"modalities and target, or fewer of them");
/* `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;
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;
}
j->sched = video_schedule(d, steps, r->shift_video, r->shift_audio);
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;
}
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 the server decoded into encoder form rides one encode pass at the slot
* its index numbers within its kind -- a picture or video a Vencode pass, a standalone audio and
* every video's soundtrack an Aencode pass (a soundtrack at its video's slot, since the encoder
* and the scatter both number it by its video). Endpoint keyframes ride the same queue as
* picture anchors -- a Vencode pass at the image slot their keyframe order names. */
/* The soundtrack's length, exactly the samples the decode will hand the encoder — the
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;
/* 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",
@@ -736,15 +902,12 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
(long long)d.sample_rate, (long long)d.audio_channels);
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->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_) {
@@ -850,9 +1013,17 @@ 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 bool wide = j.ref_wide && ref_step;
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;
/* 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. */
@@ -909,6 +1080,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_LAT].used = 4 * 4;
@@ -953,6 +1126,10 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
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();
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;
}
}
@@ -1013,23 +1190,39 @@ 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;
if (dit_dbg_)
@@ -1090,7 +1283,7 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
}
if (upload() < 0) return nullptr;
base_batches(j, g, T, step);
base_batches(j, g, T + N, step);
if (j.req->media) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
@@ -1108,9 +1301,18 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
B.enc_max_seg = max_seg;
}
}
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
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;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
@@ -1241,6 +1443,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
}
pass_.kind = RAD_GEN_PASS_VSTEP;
pass_.job = j.id;
pass_.lora_slot = j.req->lora_slot;
return &out_[0];
}
@@ -1276,6 +1479,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;
@@ -1495,6 +1699,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_VENCODE:
case RAD_GEN_PASS_AENCODE:
+19 -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:
*
@@ -67,6 +68,7 @@ public:
/* ---------------------------------------------------------- the engine thread */
const RadBatch* next(int step) override;
const RadBatch* batch_for(int rank) const override;
int32_t lora_slot() const override { return pass_.lora_slot; }
const std::vector<Readback>& readbacks() const override { return rb_; }
int done() override;
@@ -130,6 +132,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;
@@ -145,6 +154,7 @@ private:
int kind = 0;
uint64_t job = 0;
int32_t n_frames = 0;
int32_t lora_slot = -1;
};
/* Staging regions: their offsets in the host span and every rank's slab. */
@@ -161,7 +171,7 @@ private:
* path, stages R_SEG's bytes into it as well. */
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_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU,
R_ENCPX, R_ENCSM, R_ENCG, R_MOD, R_N };
R_ENCPX, R_ENCSM, R_ENCG, R_MOD, 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 {
@@ -170,6 +180,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,
bool ref_step = false);
@@ -193,6 +205,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;
SegsFn segs_ = nullptr;
@@ -214,6 +230,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_;
/* Debug-only (R4D_ENC_DEBUG): a pinned slab the encoder's audio / video latent buffer is read