ref2va: wire video and audio reference conditioning end-to-end (all three ref kinds live on device)

Follows the merged-cell pin (c725a2d). That commit proved reference IMAGE
conditioning consumed on device; reference VIDEO and AUDIO were plumbed
through the pack and step but still refused at submit — only their decode
and encoder-enqueue were missing. This lands them.

Server (videos.cpp): `task ref2va` now decodes `ref_video_N` and
`ref_audio_N` (and a video's paired `ref_video_audio_N`) into encoder form
via the mm encoders and enqueues them as Vencode/Aencode passes, instead of
the old image-only decode loop that rejected them. A soundtrack is folded
into its video's row (the `audio` word), matching how the pack lays that
pair. Caps stay <=9 images / <=3 videos / <=3 audios.

Driver (video_driver.{h,cpp}): the encode queue `enc_q` now carries VIDEO,
VAUDIO and AUDIO items in presentation order; `ref_tab` stamps each
reference's latent counts straight from the encoder geometry (rad_arch_encode_geom:
a video's frame count eg[24]=its total latent frames, its soundtrack's eg[12]),
so the pack's ref segments are sized by the encoder, not hand arithmetic.
processor.{h,cpp}/iface.h/adapters.h gained the media decode entry points.

Arch (minimaxh3.cpp): step_dit scatters reference rows into the packed step —
picture/video via op_vin from b_evc, audio via op_ain from b_enca, at each
segment start, targets last. A bounds audit confirms the scatter reads exactly
the slot region the encode pass wrote this job (eg[24]=lat = the pass's
written row count = the pack's segment size; no stale-neighbor read).

DEVICE-VERIFIED on dual gfx1201 / TP2, warm server, fixed seed, comparing
DECODED stream md5 (never raw mp4 bytes — the muxer stamps a field): all three
reference kinds are DETERMINISTIC (a rerun of one reference is bit-identical,
including raw bytes) AND CONTENT-LIVE (a different reference at the same seed
gives different output video AND audio). Image (content tokens), audio
(tone/noise/880 distinct) and video (refv_a vs refv_b: both streams differ)
each steered the generation. An earlier "the video step is nondeterministic"
note was a measurement artifact — it compared raw mp4 bytes and straddled the
one-off cold-start outlier; the warm decoded-stream probe is bit-reproducible.

Debug scaffolding (R4D_ENC_DEBUG, 4 trailing RadVideoGenDecl fields + a pinned
driver slab + an FNV digest in done()) is entangled in these files. It is
env-gated and zero-touch when unset; STRIP IT BEFORE ANY PR.

tests: video_gen_test/videos_test/server_fakes cover the video/audio enqueue
paths; abi_layout_rows adds the new trailing rows; ref_audio_sensitivity.py is
a standalone host golden harness (audio reference separates 4/4), not a ctest
case. Host tier green (only mm_test's pre-existing webp demuxer gap fails, and
the GPU card/kbench tests fail solely on VRAM contention with a live server).

NOTE-REF2VA.md updated: continuity tail (#8) remains unimplemented; strict
numeric parity vs the ComfyUI CPU reference remains open.

PLACEHOLDER AUTHOR — repo has no git identity; re-author before any push.
DO NOT PUSH this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-19 15:25:32 -05:00
1 parent 72624973ad
commit 658f7b7214
16 files changed
+1055 -162

No files matched your search

+13
View File
@@ -970,6 +970,19 @@ typedef struct RadVideoGenDecl {
* the arch abort mid-generation. 0 = no reference consumption, so no such limit. Trailing since
* ABI 23: an older plugin declares none and keeps the 0 default. */
int32_t max_ref_segs;
/* Debug introspection of the encoder outputs (diagnostics only, not part of the serving
* contract). A generator that carries the VAE encoders names its internal audio / video latent
* buffers (b_enca / b_evc) and their byte sizes here, purely so a driver built with the
* R4D_ENC_DEBUG environment can read them back through the ordinary pass readback and log a
* digest — the one way to see the encoder's numbers without a device→host copy the arch step
* itself cannot issue. With the environment unset the driver never touches these fields, so a
* normal request is byte-unchanged; a container that carries no encoders leaves them zero.
* Trailing since ABI 23: an older plugin declares none and keeps the 0 default. */
rad_buf dbg_enca;
int64_t dbg_enca_bytes;
rad_buf dbg_evc;
int64_t dbg_evc_bytes;
} RadVideoGenDecl;
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
+26 -6
View File
@@ -2600,7 +2600,11 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_F64("scale", 1.0 / std::sqrt((double)hd)),
RAD_INT("max_seqlen", T)),
RAD_NOWEIGHTS),
{ m.b_aqkv }, { m.b_aatt });
/* Eight per-head issues share this op: the first head opens the running
* head-sum and writes `b_ahsum`, the rest write `b_aatt`. Both are outputs
* across the eight, so both must be declared or the arena may hand
* `b_ahsum`'s bytes to an earlier op and the engine rejects the head-0 issue. */
{ m.b_aqkv }, { m.b_aatt, m.b_ahsum });
m.p_op_pool = rw(b, RAD_OP(b, "pool_cols",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", hd),
RAD_INT("k", hd / kAudioC), RAD_STR("dtype", "bf16")),
@@ -2885,6 +2889,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* and reads this cap, refusing an over-wide request at submit -- the model's ceilings
* (max_ref_images & co.) stay the model's, this is the build's table. */
d.max_ref_segs = kRefConsume ? kMaxSegs : 0;
/* Debug naming of the encoder outputs (R4D_ENC_DEBUG): the driver reads these back and
* logs a digest so the encoder's numbers can be inspected without a step-side d2h the
* arch cannot issue. Gated entirely by the environment on the driver side — unset, the
* fields are never read and a request is byte-unchanged. Sizes are the exact declared
* PERSIST extents above. */
d.dbg_enca = m.b_enca;
d.dbg_enca_bytes = m.aenc ? (int64_t)kEncSlotsA * kEncSlotRowsA * kAudioC * 4 : 0;
d.dbg_evc = m.b_evc;
d.dbg_evc_bytes = m.venc ? (int64_t)kEncSlotsV * kEncSlotRowsV * kPatchVals * 4 : 0;
}
RAD_ARCH_TRY(rad_declare_video_generator(b, &d));
}
@@ -3634,8 +3647,13 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
const int64_t ld = 2048, hd = ld / 8;
const RadOperand cu6 = praw(gd + 11, RAD_I32, 2);
for (int32_t ch = 0; ch < V->enc_channels; ++ch) {
/* conv_in is conv1d's full positional schema [x, w, cu, res, y, b]; the input stream is
* this channel's mono samples and its cu is the stage-0 boundaries, the same {0, n_pad}
* the first block's convs index (gd + 1). The other conv1d sites below already carry all
* six — this stem is the only one that read too few. */
RAD_ISSUE_N(c, m.op_ae_cin, n_pad, praw2(V->enc_samples + ch * n_pad, RAD_F32, n_pad, 1),
brows(m.b_ax[0], n_pad));
RAD_W(m.ae_cinw), praw(gd + 1, RAD_I32, 2), RAD_NONE,
brows(m.b_ax[0], n_pad), RAD_W(m.ae_cinb));
int64_t rows = n_pad;
for (int blk = 0; blk < 5; ++blk) {
const Model::AEncBlk& A = m.ae_blk[blk];
@@ -3644,15 +3662,17 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
const rad_buf S = m.b_ax[blk];
for (int r = 0; r < 3; ++r) {
const Model::AEncUnit& U = A.u[r];
RAD_ISSUE_N(c, U.op_a1, R, brows(S, R), RAD_W(U.a1), brows(m.b_et1[blk], R));
RAD_ISSUE_N(c, U.op_a1, R, brows(S, R), RAD_W(U.a1), brows(m.b_et1[blk], R),
RAD_NONE);
RAD_ISSUE_N(c, U.op_c1, R, brows(m.b_et1[blk], R), RAD_W(U.c1w), cu,
RAD_NONE, brows(m.b_et2[blk], R), RAD_W(U.c1b));
RAD_ISSUE_N(c, U.op_a2, R, brows(m.b_et2[blk], R), RAD_W(U.a2),
brows(m.b_et1[blk], R));
brows(m.b_et1[blk], R), RAD_NONE);
RAD_ISSUE_N(c, U.op_c2, R, brows(m.b_et1[blk], R), RAD_W(U.c2w), cu,
brows(S, R), brows(S, R), RAD_W(U.c2b));
}
RAD_ISSUE_N(c, A.op_al, R, brows(S, R), RAD_W(A.al), brows(m.b_et1[blk], R));
RAD_ISSUE_N(c, A.op_al, R, brows(S, R), RAD_W(A.al), brows(m.b_et1[blk], R),
RAD_NONE);
RAD_ISSUE_N(c, A.op_ci, R, brows(m.b_et1[blk], R), brows(A.bi, R));
RAD_ISSUE_N(c, A.op_dn, no, brows(A.bi, R), RAD_W(A.dnw), cu, RAD_NONE,
brows(A.bo, no), RAD_W(A.dnb));
@@ -3660,7 +3680,7 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
rows = no;
}
RAD_ISSUE_N(c, m.op_ae_snk6, rows, brows(m.b_ax[5], rows), RAD_W(m.ae_al6),
brows(m.b_a6t, rows));
brows(m.b_a6t, rows), RAD_NONE);
RAD_ISSUE_N(c, m.op_ae_fin, rows, brows(m.b_a6t, rows), RAD_W(m.ae_finw), cu6,
RAD_NONE, brows(m.b_ax6, rows), RAD_W(m.ae_finb));
RAD_ISSUE_N(c, m.op_ae_cast6, rows, brows(m.b_ax6, rows), brows(m.b_apb, rows));
+11 -7
View File
@@ -86,16 +86,20 @@ struct VideoRefMedia {
std::string data; /* the file's bytes */
/* The reference in the encoder's own form, prepared by the server (which owns the decoder) so
* the driver stages bytes without ever touching a codec. The VAE encode pass reads exactly
* these; they are empty until the server decodes the part. IMAGE/VIDEO fill the pixels,
* AUDIO/VIDEO_AUDIO the samples.
* the driver stages bytes without ever touching a codec; they are empty until the server decodes
* the part. These are the NATURAL decoded shapes — the driver's encode pass, which owns the
* encoder's geometry, does the padding the encoder kernels demand (clip-padding a video's
* frames, zero-padding an audio's samples). IMAGE/VIDEO fill the pixels, AUDIO/VIDEO_AUDIO the
* samples.
* enc_pixels: f32 [enc_frames][enc_h][enc_w][3] row-major RGB in 0..255, UN-normalised —
* the video VAE applies ImageNet mean/std itself. Each side is snapped down to a multiple
* of the VAE's spatial ratio and capped at the declaration's max_enc_side, aspect kept,
* because our encoder runs one volume and cannot tile the way the reference does. For a
* still image enc_frames is 1.
* enc_samples: f32 [enc_channels][enc_n] channel-major, each channel right-padded with
* zeros out to a whole number of hops (geom entry 0), at the model's audio rate. */
* because our encoder runs one volume and cannot tile the way the reference does. Frames are
* the reference's sampled, trimmed count (for a still image, 1); the final short clip is
* padded by the driver, not here.
* enc_samples: f32 [enc_channels][enc_n] channel-major at the model's audio rate. A mono
* source is spread across the channels (the audio VAE encodes one channel at a time); the
* tail is right-padded with zeros to a whole hop by the driver. */
std::vector<float> enc_pixels;
int32_t enc_frames = 0, enc_h = 0, enc_w = 0;
std::vector<float> enc_samples;
+210 -58
View File
@@ -6,6 +6,8 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace rad {
@@ -282,6 +284,18 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
vout_.assign(ranks_.size(), RadVideoGenBatch{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
/* Debug-only readback of the encoder outputs (R4D_ENC_DEBUG). Only when the environment names
* it AND the container carries encoders; a normal run leaves enc_dbg_ false and never reads
* decl_.dbg_* or touches enc_dbg_host_. */
if (std::getenv("R4D_ENC_DEBUG") &&
(decl_.dbg_enca_bytes > 0 || decl_.dbg_evc_bytes > 0)) {
enc_dbg_bytes_ = std::max(decl_.dbg_enca_bytes, decl_.dbg_evc_bytes);
enc_dbg_host_ = static_cast<char*>(rad_dev_alloc(enc_dbg_bytes_, RAD_MEM_HOST_PINNED));
enc_dbg_ = enc_dbg_host_ != nullptr;
if (!enc_dbg_)
RAD_ERR("video generator: R4D_ENC_DEBUG set but no pinned host for the %lld-byte "
"encoder readback", (long long)enc_dbg_bytes_);
}
return RAD_OK;
}
@@ -296,9 +310,11 @@ void VideoDriver::fini() {
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED);
if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED);
if (enc_dbg_host_) rad_dev_free(enc_dbg_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
frames_host_ = nullptr;
audio_host_ = nullptr;
enc_dbg_host_ = nullptr;
}
/* ================================================================== requests */
@@ -313,20 +329,37 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (T < 1 || T > d.max_text)
return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." +
std::to_string(d.max_text));
/* Reference conditioning: the images reach the language model through `media`, which the
* server built from the parts (gen/video.h) and build_cond stages into the conditioning
* pass. What this generator cannot consume yet is anything whose bytes reach the model
* through a VAE — a reference video's frames, a soundtrack, a standalone audio. Those are
* refused naming the part, rather than silently made into a weaker video. */
/* Reference conditioning reaches the model two ways. Reference images enter the language model
* through `media` (the server built it from the parts, gen/video.h; build_cond stages it into
* the conditioning pass) AND contribute VAE rows. A reference video, its soundtrack, and a
* standalone audio reach the model only as VAE rows: the server decodes them into the encoder's
* own form, one encode pass each folds their latents into the lane's fixed slots, and the step's
* pack lays those slots between the text and the target streams (RadVideoGenBatch::ref_tab).
* Every kind the declaration allows is consumed; the guard below is only about a container
* lacking its vision tower, which could encode nothing. */
if (!r->refs.empty() && max_enc_ == 0)
return no("this container was converted without its vision tower, so no request can "
"carry reference media");
/* A reference video, soundtrack or standalone audio reaches the model only through the VAE
* encoders (the video/audio Vencode/Aencode passes), which a container carries exactly when it
* declares `encodes`. Converted without them there is nothing to condition on, and the reference
* would drop silently into a text-only video — the very silent weakening this guard exists to
* prevent — so refuse it, naming the part. Images need only the tower and are checked below. */
if (!d.encodes)
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE)
return no("'" + m.name + "' is a reference " +
(m.kind == VideoRefMedia::VIDEO ? "video"
: m.kind == VideoRefMedia::VIDEO_AUDIO ? "soundtrack" : "audio") +
", but this container was converted without its VAE encoders, so nothing "
"can condition on it");
/* Only reference images add language-model soft-token rows, so only they need processed media.
* A reference video or audio reaches the model purely through the VAE encode rows the pack lays
* from the reference table, so a request of those alone carries no `media` and needs none. */
bool has_image = false;
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE)
return no("'" + m.name + "' is not consumed yet: reference videos and audios reach "
"the model through the video and audio VAEs, which the video path does not "
"run in this build; only ref_image_N parts condition a generation today");
if (!r->refs.empty() && !r->media)
if (m.kind == VideoRefMedia::IMAGE) has_image = true;
if (has_image && !r->media)
return no("the request carries reference images but no processed media to condition on");
if (r->media) {
int64_t n_patch = 0;
@@ -369,33 +402,105 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
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. A picture's grid is the encoder's sides over
* the VAE ratio, one latent frame, no soundtrack; its slot is the one its Vencode pass folds
* its latents into. It must exist before the step layout is decided, because when the denoiser
* consumes it the reference rows are part of that layout. Only pictures queue today (videos and
* audios are refused at submit above until their decode paths land), so the keyframe count
* stays 0 and the table holds only picture rows. */
if (d.encodes)
* 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. The keyframe count stays 0 (continuation is separate
* work), so the table holds only reference rows. */
if (d.encodes) {
bool need_geom = false;
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE) 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) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1)
return no("'" + m.name + "' has no slot in the conditioning");
if (d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio ||
m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio)
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) + "x" +
std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
j->enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/,
0 /*no soundtrack*/});
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. */
}
}
/* 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
@@ -525,10 +630,11 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
/* The reference table and the VAE encode queue were built above, before the step layout was
* chosen: each reference picture the server decoded into encoder form rides one Vencode pass,
* at the slot its index numbers within pictures -- the slot the encoder folds its latents into
* and the step's pack scatters them from. Reference videos and audios are refused above until
* their decode paths land, so only pictures are queued and the keyframe count stays 0. */
* 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). The keyframe count stays 0: continuation is
* separate work. */
/* 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. */
@@ -1012,10 +1118,10 @@ const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
/* One media item through its VAE encoder: stage its encoder-ready bytes and the encode geometry
* the plugin's rad_arch_encode_geom derives from them, then name the pass's kind and slot so the
* encoder folds the latents into the lane's fixed slot rows. The bytes the server decoded must
* already be padded to what the geom reports (a video's frames clip-padded, an audio's samples to
* its hop) — the encoder reads that many and no more, so a disagreement is failed here rather than
* run past the staged volume. */
* encoder folds the latents into the lane's fixed slot rows. The server sends the NATURAL decoded
* media; the padding the geom demands (a video's frames to a whole clip, an audio's samples to a
* whole hop) is applied here, since only the driver has the geom, and the encoder is handed exactly
* that padded volume. */
const RadBatch* VideoDriver::build_encode(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Job::EncItem& it = j.enc_q[j.enc_next];
@@ -1028,34 +1134,50 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
if (!enc_geom_)
return fail("the request carries reference media to encode, but this plugin exports no "
"rad_arch_encode_geom");
/* The encoder kernels recompute their geometry from the batch's frame / sample counts and
* require them to be the padded figures rad_arch_encode_geom reports (a video's frames out to a
* whole clip, an audio's samples out to a whole hop). The server sends the NATURAL decoded
* media, so the padding lives here, where the geometry is known: a video's short final clip is
* filled by repeating its last frame, an audio's tail by zeros. A single picture is already
* clip- and hop-complete (one frame, no hop), so its bytes and staging are unchanged. */
int32_t* gd = hptr<int32_t>(R_ENCG);
int64_t stage_frames = 0, stage_samples = 0;
if (audio) {
const int64_t n = m.enc_n;
const int32_t ch = m.enc_channels;
if (n <= 0 || ch <= 0 || (int64_t)n * ch * 4 > reg_[R_ENCSM].bytes)
return fail("a reference audio does not fit one encode pass");
if (n <= 0 || ch <= 0) return fail("a reference audio has no samples or no channels");
int64_t in[4] = { n, 0, 0, ch };
if (enc_geom_(RAD_GEN_PASS_AENCODE, in, gd, 25) < 0)
return fail("the audio encoder refuses " + std::to_string(n) + " samples over " +
std::to_string(ch) + " channels");
if ((int64_t)gd[0] != n)
return fail("a reference audio is not padded to the length rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCSM), m.enc_samples.data(), (size_t)n * ch * 4);
reg_[R_ENCSM].used = n * ch * 4;
stage_samples = gd[0]; /* n rounded up to a whole hop; the encoder reads exactly this */
if (stage_samples * ch * 4 > reg_[R_ENCSM].bytes)
return fail("a reference audio does not fit one encode pass");
float* sm = hptr<float>(R_ENCSM);
std::memset(sm, 0, (size_t)stage_samples * ch * 4); /* right-pad each channel with zeros */
for (int32_t c = 0; c < ch; ++c)
std::memcpy(sm + (size_t)c * stage_samples, m.enc_samples.data() + (size_t)c * n,
(size_t)n * 4);
reg_[R_ENCSM].used = stage_samples * ch * 4;
} else {
const int64_t nf = m.enc_frames, H = m.enc_h, W = m.enc_w;
if (nf <= 0 || H <= 0 || W <= 0 || nf * H * W * 3 * 4 > reg_[R_ENCPX].bytes)
return fail("a reference picture or video does not fit one encode pass");
if (nf <= 0 || H <= 0 || W <= 0)
return fail("a reference picture or video has no frames or no sides");
int64_t in[4] = { nf, H, W, 3 };
if (enc_geom_(RAD_GEN_PASS_VENCODE, in, gd, 25) < 0)
return fail("the video encoder refuses a reference at " + std::to_string(H) + "x" +
std::to_string(W) + " over " + std::to_string(nf) + " frames");
if ((int64_t)gd[23] != nf)
return fail("a reference is not padded to the clip count rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCPX), m.enc_pixels.data(), (size_t)nf * H * W * 3 * 4);
reg_[R_ENCPX].used = nf * H * W * 3 * 4;
const int64_t area = H * W * 3;
stage_frames = gd[23]; /* nf clip-padded to a whole number of 17-frame clips */
if (stage_frames * area * 4 > reg_[R_ENCPX].bytes)
return fail("a reference picture or video does not fit one encode pass");
float* px = hptr<float>(R_ENCPX);
std::memcpy(px, m.enc_pixels.data(), (size_t)nf * area * 4);
/* Repeat the final frame out to the padded clip count: the causal encoder wants every clip
* full, and the reference pads the short last clip exactly this way. */
for (int64_t f = nf; f < stage_frames; ++f)
std::memcpy(px + f * area, px + (nf - 1) * area, (size_t)area * 4);
reg_[R_ENCPX].used = stage_frames * area * 4;
}
reg_[R_ENCG].used = 25 * 4;
stage_geom(j, j.geom, j.rows, 0);
@@ -1069,11 +1191,11 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
V.enc_slot = it.slot;
if (audio) {
V.enc_samples = dptr<float>(ri, R_ENCSM);
V.enc_n_samples = m.enc_n;
V.enc_n_samples = stage_samples;
V.enc_channels = m.enc_channels;
} else {
V.enc_pixels = dptr<float>(ri, R_ENCPX);
V.enc_frames = m.enc_frames;
V.enc_frames = stage_frames;
V.enc_height = m.enc_h;
V.enc_width = m.enc_w;
}
@@ -1082,6 +1204,15 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
for (auto& B : out_) B.gen = kind;
pass_.kind = kind;
pass_.job = j.id;
if (enc_dbg_) {
const rad_buf h = audio ? decl_.dbg_enca : decl_.dbg_evc;
const int64_t n = audio ? decl_.dbg_enca_bytes : decl_.dbg_evc_bytes;
enc_dbg_used_ = 0;
if (h && n > 0) {
rb_.assign(1, Readback{h, n, enc_dbg_host_});
enc_dbg_used_ = n;
}
}
return &out_[0];
}
@@ -1097,6 +1228,27 @@ int VideoDriver::done() {
case RAD_GEN_PASS_VENCODE:
case RAD_GEN_PASS_AENCODE:
/* The media's latents are now in the lane's slot rows; take the next reference, if any. */
if (enc_dbg_ && enc_dbg_used_ > 0) {
const int64_t nf = enc_dbg_used_ / 4;
const float* z = reinterpret_cast<const float*>(enc_dbg_host_);
uint64_t h = 1469598103934665603ULL; /* FNV-1a over the readback bytes */
for (int64_t i = 0; i < enc_dbg_used_; ++i)
h = (h ^ (uint64_t)(uint8_t)enc_dbg_host_[i]) * 1099511628211ULL;
int64_t nz = 0;
float mx = 0.0f;
double sum = 0.0;
for (int64_t i = 0; i < nf; ++i) {
if (z[i] != 0.0f) ++nz;
const float a = z[i] < 0 ? -z[i] : z[i];
if (a > mx) mx = a;
sum += z[i];
}
RAD_ERR("enc_dbg %s slot %d: fnv %016llx floats %lld nonzero %lld maxabs %.6g "
"sum %.6g head[%.6g %.6g %.6g %.6g]",
pass_.kind == RAD_GEN_PASS_AENCODE ? "AENCA(b_enca)" : "VENCV(b_evc)",
(int)enc_dbg_used_, (unsigned long long)h, (long long)nf, (long long)nz,
(double)mx, sum, (double)z[0], (double)z[1], (double)z[2], (double)z[3]);
}
++j->enc_next;
break;
case RAD_GEN_PASS_VSTEP: {
+9
View File
@@ -216,6 +216,15 @@ private:
int64_t audio_bytes_ = 0;
std::vector<Readback> rb_;
/* Debug-only (R4D_ENC_DEBUG): a pinned slab the encoder's audio / video latent buffer is read
* back into after a Vencode / Aencode pass, so done() can log a digest. Allocated and used
* only when the environment is set and the generator named its encoders; otherwise enc_dbg_
* is false and these stay null / zero, so a normal request never touches them. */
bool enc_dbg_ = false;
char* enc_dbg_host_ = nullptr;
int64_t enc_dbg_bytes_ = 0; /* the slab's capacity */
int64_t enc_dbg_used_ = 0; /* bytes the last encode readback filled */
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadVideoGenBatch> vout_;
Pass pass_;
+63
View File
@@ -1041,6 +1041,69 @@ int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int3
return RAD_OK;
}
namespace {
/* Which frames of a source video a reference clip keeps: spread uniformly over the stream, the
* largest count no more than both the stream's length and `max_frames` that is 5 modulo 17 — the
* reference's trim (`n % 17 == 5`), so the temporal encoder's 17-frame clips all land with the
* short final clip padded from five real frames. A stream too short to reach five yields what it
* has; the encode pass pads the final clip either way. */
struct VaeSampleArgs { int32_t max_frames; };
std::vector<int64_t> vae_sample_cb(const VideoInfo& info, const void* user) {
const VaeSampleArgs* a = static_cast<const VaeSampleArgs*>(user);
const int64_t avail = info.n_frames > 0 ? info.n_frames : 1;
const int64_t cap = a->max_frames > 0 ? std::min<int64_t>(a->max_frames, avail) : avail;
int64_t want = cap - (((cap - 5) % 17) + 17) % 17; /* largest v <= cap with v % 17 == 5 */
if (want < 5) want = std::min<int64_t>(cap, 5);
const int64_t take = std::max<int64_t>(1, std::min(want, avail));
std::vector<int64_t> idx((size_t)take);
for (int64_t i = 0; i < take; ++i)
idx[(size_t)i] = take > 1 ? (i * (avail - 1)) / (take - 1) : 0;
return idx;
}
} /* namespace */
int Processor::encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
int32_t max_frames, std::vector<Frame>* out, std::string* why) const {
if (ratio < 1 || max_side < ratio) {
if (why) *why = "the encoder's side ratio and maximum are not usable";
return RAD_E_INVAL;
}
/* Same decode guard as a still: a reference the text encoder accepts the VAE accepts too. */
Video v;
const VaeSampleArgs a{ max_frames };
RAD_TRY(decode_video(bytes, n, vae_sample_cb, &a, cfg_.max_source_pixels, &v, why));
if (v.frames.empty()) {
if (why) *why = "the video holds no frames";
return RAD_E_INVAL;
}
/* One grid for every frame, the snap encoder_image applies to a still, taken from the first
* frame (a clip is one aspect throughout). */
auto snap = [&](int64_t s) {
int64_t v = (s / ratio) * ratio;
if (v < ratio) v = ratio;
if (v > max_side) v = max_side;
return (int32_t)v;
};
const Frame& f0 = v.frames.front();
const int32_t longest = std::max(f0.w, f0.h);
const double scale = longest > max_side ? (double)max_side / (double)longest : 1.0;
const int32_t w = snap((int64_t)std::floor(f0.w * scale));
const int32_t h = snap((int64_t)std::floor(f0.h * scale));
out->clear();
out->reserve(v.frames.size());
for (const Frame& f : v.frames) {
Frame r;
resize_lanczos_rgb(f, w, h, &r);
out->push_back(std::move(r));
}
return RAD_OK;
}
int Processor::encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why) const {
return decode_audio(bytes, n, rate, max_samples, out, why);
}
namespace {
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
+19
View File
@@ -327,6 +327,25 @@ public:
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, Frame* out,
std::string* why) const;
/* A moving picture in the video VAE's own form: decoded under the same `max_source_pixels`
* guard, then every frame resized to the one grid `encoder_image` picks. The frames are
* SAMPLED first: uniformly across the stream, to the largest count no more than `max_frames`
* (the declaration's max_enc_frames) that leaves the short final clip at 5 frames — the
* reference trims a reference video to `n % 17 == 5` so its 17-frame clips each contribute a
* full five latents. The returned count is that trimmed length, NOT clip-padded; the caller
* (the driver's encode pass) repeats the final frame out to a whole clip. `out` is empty only
* on error. */
int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
int32_t max_frames, std::vector<Frame>* out, std::string* why) const;
/* A clip in the audio VAE's own form: its first stream as MONO float at `rate` Hz, truncated
* to `max_samples`. The caller duplicates it across the encoder's channels and zero-pads each
* to a whole hop (the encoder runs one channel at a time). This is a thin wrapper on the media
* decoder, kept here so every reference the server hands the VAEs is decoded under the
* processor. */
int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why) const;
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
* encoder's. */
int init_audio(const AudioConfig& cfg, std::string* why = nullptr);
+18
View File
@@ -719,6 +719,24 @@ public:
return p_->encoder_image(bytes, n, ratio, max_side, out, why);
}
int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
int32_t max_frames, std::vector<mm::Frame>* out, std::string* why) override {
if (!p_ || !mm::decoder_available()) {
if (why) *why = "no video decoder is available";
return RAD_E_UNSUPPORTED;
}
return p_->encoder_video(bytes, n, ratio, max_side, max_frames, out, why);
}
int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why) override {
if (!p_ || !mm::decoder_available()) {
if (why) *why = "no audio decoder is available";
return RAD_E_UNSUPPORTED;
}
return p_->encoder_audio(bytes, n, rate, max_samples, out, why);
}
int32_t audio_rate() const override {
return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0;
}
+20
View File
@@ -544,6 +544,26 @@ public:
return RAD_E_UNSUPPORTED;
}
/* A moving picture in a video VAE's encoder-ready form: decoded under the same guard, sampled to
* a clip-friendly frame count (at most `max_frames`) and resized to `encoder_image`'s grid. The
* frames are the trimmed, sampled count; the caller clip-pads to a whole clip. */
virtual int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
int32_t max_frames, std::vector<mm::Frame>* out, std::string* why) {
(void)bytes; (void)n; (void)ratio; (void)max_side; (void)max_frames; (void)out;
if (why) *why = "this server prepares no reference media for a video encoder";
return RAD_E_UNSUPPORTED;
}
/* A clip in an audio VAE's encoder-ready form: its first stream as MONO float at `rate` Hz,
* truncated to `max_samples`. The caller spreads it across the encoder's channels and zero-pads
* to a hop. */
virtual int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why) {
(void)bytes; (void)n; (void)rate; (void)max_samples; (void)out;
if (why) *why = "this server prepares no reference media for an audio encoder";
return RAD_E_UNSUPPORTED;
}
/* Audio in two halves, for a route that cuts a long recording into clips itself
* (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most
* `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most
+101 -46
View File
@@ -511,14 +511,19 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
};
/* The reference media are presented between the template's head and the prompt. Only the
* images reach the language model, so only they are decoded and processed here; a
* reference video's frames and every audio ride the video and audio VAE encoders, which
* the video path does not run in this build yet, so their parts pass through as bytes for
* the generator to refuse at submit naming the part — not silently dropped. (When videos
* land, a soundtrack's `<Audio j>` label is emitted right before its `<Video k>` label,
* the audio ordinal counting soundtracks and standalone audios together, per type.) */
* images reach the language model as soft-token rows, so only they are decoded and placed
* here; a reference video and every audio reach the model through the VAEs (decoded into the
* encoder's form below), so in the prompt they contribute only their spoken label. That
* label still rides ahead of the prompt in the reference's presentation order, because the
* text encoder sees `<Video k>` / `<Audio j>` markers even for media it only names: a
* soundtrack's `<Audio j>` label is emitted right before its video's `<Video k>` label, and
* `audio_ord` counts soundtracks and standalone audios together, in the order they are
* spoken (docs/PORT-REF2VA.md §3). */
if (ref2va && deps_.mm && deps_.mm->accepts(MediaKind::Image)) {
/* Every picture is decoded and processed before any token is laid down. */
/* Every picture is decoded and processed before any token is laid down. A reference
* video or audio needs no vision item here — it reaches the model through the VAEs, so
* it contributes only its presentation label to the prompt (the 2 fps timestamped
* frames the reference also shows Qwen are deferred; see docs/NOTE-REF2VA.md). */
std::vector<std::shared_ptr<mm::Item>> pics;
MediaOpts mo;
mo.max_pixels = (int64_t)W * (int64_t)H; /* `match`: scaled to the output's area */
@@ -531,27 +536,42 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
return bad(m.name.c_str(), "'" + m.name + "' could not be used: " + why);
pics.push_back(std::move(it));
}
/* validate_refs numbered each kind 1..n without gaps, so a part's number is its
* presentation ordinal, and paired every soundtrack to a video of the same number. The
* reference presentation order (docs/PORT-REF2VA.md §3) is: every picture, then each
* video behind its soundtrack's label, then the standalone audios. `<Audio j>` counts
* soundtracks and standalone audios together, in the order they are spoken. */
auto has_soundtrack = [&](int32_t idx) {
for (const gen::VideoRefMedia& m : r->refs)
if (m.kind == gen::VideoRefMedia::VIDEO_AUDIO && m.index == idx) return true;
return false;
};
put(t.substr(0, p), true);
if (!pics.empty()) {
auto media = std::make_shared<mm::PromptMedia>();
size_t i = 0;
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
/* validate_refs numbered each kind 1..n without gaps, so the part's number is
* its presentation ordinal: `<Picture k>: ` then the picture's token run. The
* label is encoded as its own string, as the reference tokenizer's output was
* built. */
put("<Picture " + std::to_string(m.index) + ">: ", false);
mm::Placed pl;
pl.item = pics[i++];
pl.tok = (int32_t)r->tokens.size();
r->tokens.insert(r->tokens.end(), pl.item->expand.begin(),
pl.item->expand.end());
media->items.push_back(std::move(pl));
}
media->layout();
r->media = std::move(media);
std::shared_ptr<mm::PromptMedia> media;
if (!pics.empty()) media = std::make_shared<mm::PromptMedia>();
size_t i = 0;
for (const gen::VideoRefMedia& m : r->refs) { /* sorted by (kind, index): images first */
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
put("<Picture " + std::to_string(m.index) + ">: ", false);
mm::Placed pl;
pl.item = pics[i++];
pl.tok = (int32_t)r->tokens.size();
r->tokens.insert(r->tokens.end(), pl.item->expand.begin(),
pl.item->expand.end());
media->items.push_back(std::move(pl));
}
int audio_ord = 0;
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::VIDEO) continue;
if (has_soundtrack(m.index))
put("<Audio " + std::to_string(++audio_ord) + ">: ", false);
put("<Video " + std::to_string(m.index) + ">: ", false);
}
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::AUDIO) continue;
put("<Audio " + std::to_string(++audio_ord) + ">: ", false);
}
if (media) { media->layout(); r->media = std::move(media); }
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
} else {
@@ -567,29 +587,64 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
std::to_string(info.max_text));
}
/* ---- the encoder's own view of every reference the VAE consumes. The text encoder saw the
* pictures above for identity; now each is also decoded and shrunk to the encoder's grid so the
* video VAE can turn it into conditioning rows. The driver stages these bytes into a Vencode
* pass; reference videos and their soundtracks, and the standalone audios, ride the same two
* encoders but are still refused at submit until those decode paths land, so only pictures are
* prepared here. The processor decodes under the same guard it used for the text encoder, so a
* reference that got this far decodes here too. */
/* ---- the encoder's own view of every reference the VAEs consume: pictures and videos through
* the video VAE (enc_pixels), soundtracks and standalone audios through the audio VAE
* (enc_samples). The text encoder saw the pictures above for identity; now each reference is
* decoded to the encoder's own grid so the driver can stage it into a Vencode or Aencode pass.
* These are the NATURAL decoded shapes — the driver's encode pass, which owns the encoder's
* geometry, clip-pads a video's frames and zero-pads an audio's samples to what it reports. The
* processor decodes under the same guard it used for the text encoder, so a reference that got
* this far decodes here too. */
if (ref2va && info.encodes && deps_.mm) {
for (gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
mm::Frame fr;
std::string why;
if (deps_.mm->encoder_image((const uint8_t*)m.data.data(), m.data.size(),
(int32_t)info.enc_ratio, (int32_t)info.max_enc_side, &fr,
&why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be encoded: " + why);
m.enc_frames = 1;
m.enc_h = fr.h;
m.enc_w = fr.w;
/* un-normalised RGB 0..255, row-major; the video VAE applies ImageNet mean/std itself */
m.enc_pixels.resize((size_t)fr.w * fr.h * 3);
for (size_t i = 0; i < m.enc_pixels.size(); ++i)
m.enc_pixels[i] = (float)fr.rgb[i];
const uint8_t* p = (const uint8_t*)m.data.data();
const size_t n = m.data.size();
if (m.kind == gen::VideoRefMedia::IMAGE) {
mm::Frame fr;
if (deps_.mm->encoder_image(p, n, (int32_t)info.enc_ratio,
(int32_t)info.max_enc_side, &fr, &why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be encoded: " + why);
m.enc_frames = 1;
m.enc_h = fr.h;
m.enc_w = fr.w;
/* un-normalised RGB 0..255, row-major; the video VAE applies ImageNet mean/std itself */
m.enc_pixels.resize((size_t)fr.w * fr.h * 3);
for (size_t i = 0; i < m.enc_pixels.size(); ++i)
m.enc_pixels[i] = (float)fr.rgb[i];
} else if (m.kind == gen::VideoRefMedia::VIDEO) {
/* The frames the temporal VAE sees, sampled and resized to the encoder grid. The
* count is the reference's trimmed length (n % 17 == 5); the driver's encode pass
* repeats the final frame out to a whole clip, so this stays the natural count. */
std::vector<mm::Frame> fr;
if (deps_.mm->encoder_video(p, n, (int32_t)info.enc_ratio,
(int32_t)info.max_enc_side, (int32_t)info.max_enc_frames,
&fr, &why) < 0 || fr.empty())
return bad(m.name.c_str(), "'" + m.name + "' could not be encoded: " + why);
m.enc_frames = (int32_t)fr.size();
m.enc_h = fr.front().h;
m.enc_w = fr.front().w;
const size_t area = (size_t)m.enc_w * m.enc_h * 3;
m.enc_pixels.resize(area * fr.size());
for (size_t f = 0; f < fr.size(); ++f)
for (size_t i = 0; i < area; ++i)
m.enc_pixels[f * area + i] = (float)fr[f].rgb[i];
} else {
/* A reference audio, or a reference video's soundtrack: mono at the model's audio
* rate, then spread across the encoder's channels (the audio VAE encodes one
* channel a time; a mono source becomes both). The driver zero-pads to a hop. */
std::vector<float> mono;
if (deps_.mm->encoder_audio(p, n, (int32_t)info.sample_rate, info.max_enc_samples,
&mono, &why) < 0 || mono.empty())
return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why);
const int32_t ch = (int32_t)info.channels;
m.enc_channels = ch;
m.enc_n = (int64_t)mono.size();
m.enc_samples.assign((size_t)ch * mono.size(), 0.0f);
for (int32_t c = 0; c < ch; ++c)
for (size_t i = 0; i < mono.size(); ++i)
m.enc_samples[(size_t)c * mono.size() + i] = mono[i];
}
}
}
+109 -42
View File
@@ -14,13 +14,32 @@ sibling notes (`NOTE-P3-PACK.md`, `NOTE-P2-ENCODE.md`); this one is about capabi
## What works today
- **Image references — ≤9 photos, device-verified.** A request carrying `ref_image_1 … ref_image_9`
runs the full conditioned denoise on both cards and returns a video. Three fixed-seed runs of the
same prompt — no reference, one reference, nine references — produce three distinct outputs, so
the conditioning is demonstrably *live* (not inert) and reference-*aware*, and nine photos no
longer hit the earlier submit-time refusal.
runs the full conditioned denoise on both cards and returns a video. The conditioning is
demonstrably *live* and *content-sensitive*, not merely count-sensitive: at a fixed seed, two jobs
with the **same prompt and the same single reference but different photo content** give distinct
outputs (a strict content-control), and nine photos complete where the pinned build refused at
submit. Images steer the output because they feed the text encoder as well as the VAE — the route
the video / audio references lack (see point 4).
- **Reference-media plumbing and caps.** The container declares 9/3/3 (images/videos/audios); the
VAE-encode passes, the reference table, and the widened step layout are all in place, and the
encode path is now unblocked by the host FFmpeg install.
- **Video and audio references — wired, host-tested, and running on-device without fault; NOT yet
content-active.** The submit refusal that used to reject `ref_video_N` / `ref_video_audio_N` /
`ref_audio_N` is gone. The server decodes each into the encoder's form, the driver stages a
`Vencode` / `Aencode` pass and folds it into the reference table, and the widened step consumes it
(point 4). This is proven end-to-end: the host tier is green (`videos_test` decodes and speaks every
kind; `video_gen_test` clips-pads / zero-pads, slots a soundtrack to its video, and lays the table,
and refuses a non-encoding container by name), **and on the device the complete DaSiWa shape — a
picture + a video + that video's soundtrack + a standalone audio, four reference parts in one
request — runs every encoder pass and the widened denoise to a clean MP4 with no engine fault.**
What is **not** yet true: a fixed-seed content-control (same prompt, same reference *count*, only the
reference *content* differing) shows a reference **video** or **audio does not change the output**.
The reference **image** does (it also rides the text encoder — see point 4). The reason is isolated
to the VAE **encoders** producing content-invariant latents, not to the decode, staging, upload or
reference-table scatter (all of which are proven to carry distinct content per media item); it is the
open **encoder value-parity** task. Until that lands, a video / audio reference is accepted and
encoded but is, in effect, ignored by the output — treat image references as the only ones that
currently steer the generation.
- **The modulation-cell merge** that lifts the count ceiling (next section).
## The reference-count ceiling: how it went from ≤5 to ≤9
@@ -55,17 +74,17 @@ matter how many there are.
## What this port still cannot reproduce (the honest list)
1. **Many *interleaved* mixed-modality references would exceed the 8-group table** *(prospective —
only reachable once reference videos are wired, see point 4; today every accepted reference is a
photo, which is four groups and never binds).* Photos are free, but every reference *video* would
contribute two cells in order — *video-conditioned* then its *audio-conditioned* soundtrack — and
a photo placed after it **reopens** the video-conditioned cell, adding a group. Alternating photos
with video-plus-soundtrack refs could push the merged run past `kMaxSegs = 8` cells, which the
driver refuses at submit: *"these references change the conditioning's modulation cell N times,
but this deployment's modulation table holds 8 cells — ask for references that share their
modalities and target, or fewer of them."* **Workaround when videos arrive:** group references by
modality (all photos together, then the videos) so same-kind refs are contiguous and merge; the
ceiling only bites on heavy interleaving.
1. **Many *interleaved* mixed-modality references can exceed the 8-group table.** Photos are free
(each `(video-ada, video-conditioned)`, one merged cell), but every reference *video* contributes
two cells in order — *video-conditioned* then its *audio-conditioned* soundtrack — and a photo
placed after it **reopens** the video-conditioned cell, adding a group. Alternating photos with
video-plus-soundtrack refs can push the merged run past `kMaxSegs = 8` cells, which the driver
refuses at submit: *"these references change the conditioning's modulation cell N times, but this
deployment's modulation table holds 8 cells — ask for references that share their modalities and
target, or fewer of them."* Since reference videos are now wired (point 4) this ceiling **binds for
real**, not just prospectively. **Workaround:** group references by modality (all photos together,
then the videos) so same-kind refs are contiguous and merge; the ceiling only bites on heavy
interleaving. A single video-plus-soundtrack is four to five groups and always fits.
*Why the ceiling stays at 8:* widening it means growing the shared `b_ada` / `b_nout` / `b_modg`
buffers on **both** cards — exactly the VRAM a dual-32 GB box does not have. Since the common case
@@ -86,23 +105,58 @@ matter how many there are.
multi-segment seamless continuation, as the DaSiWa workflow uses it, is not reproduced yet. Single
generation conditioned on reference *images* is (see point 4 for video / audio).
4. **Reference videos and audios are refused at submit — not yet wired, even though the encoders
load.** `ref_video_N`, `ref_video_audio_N`, and `ref_audio_N` parts are accepted by the parser,
capped (3 / 3), and paired correctly, but the request is rejected with *"'ref_video_1' is not
consumed yet: reference videos and audios reach the model through the video and audio VAEs …
only ref_image_N parts condition a generation today."* The VAE encoders are declared and loaded,
and the `Vencode` pass runs for **image** references, but no path decodes a video's frames or an
audio's samples into the encoder. **Only reference images condition a generation today.** This is
the single largest remaining DaSiWa gap. The scaffolding is already designed for it — the
`VideoRefMedia` encoder view is documented as *"IMAGE/VIDEO fill the pixels, AUDIO/VIDEO_AUDIO the
samples,"* `decode_video` / `decode_audio` exist in the media layer, and the driver's encode
builder already branches on audio — so enabling them is bounded work, not a redesign:
(a) server-side, decode a video's frames / an audio's samples into `enc_pixels` / `enc_samples` on
the encoder grid (mirroring the image loop); (b) driver-side, drop the submit guard and enqueue
`RAD_ENC_VIDEO` / `RAD_ENC_VAUDIO` / `RAD_ENC_AUDIO` with the right latent grid and slot; (c) a
per-kind device differential (video, audio, video-with-soundtrack) proving each conditions the
output. Until then, treat the mixed-modality interleaving ceiling in point 1 as **prospective** —
today every accepted reference is a photo, which merges to four groups.
4. **Reference videos and audios are wired and run — through the VAEs, not the text encoder — but do
not yet steer the output.** A
`ref_video_N` (mp4/mov), its soundtrack `ref_video_audio_N`, and a standalone `ref_audio_N`
(wav/mp3/…) are decoded on the server into the encoder's own form (`encoder_video` /
`encoder_audio` → `enc_pixels` / `enc_samples`), staged into a `Vencode` / `Aencode` pass, folded
into the pack's reference table, and consumed by the widened step — the same route an image
reference takes, only via a VAE instead of the language model. A video and its separately-given
soundtrack are **one** table row: the soundtrack folds into the video's `audio` word and encodes
at the video's slot (`aenc_slot_row` numbers it by its video). The driver clip-pads a video's short
final clip by repeating its last frame and zero-pads an audio's tail to a whole hop, because only
the driver holds the encoder geometry. A request of videos / audios alone carries no `media`: only
images add soft-token rows the text encoder reads. A container converted **without** its VAE
encoders (`encodes 0`) refuses such a part *by name* ("… is a reference video, but this container
was converted without its VAE encoders") rather than drop it into a text-only video.
**The one thing that does not yet work is the encoder's numbers, not its plumbing.** A controlled
fixed-seed check — same prompt, same reference count, only the media content differing — shows a
reference video (two 512×512 videos with genuinely different decoded frames) and a reference audio
(a tone, a chirp, white noise) each producing a **byte-identical** output, while a reference image
of the same count changes it. The cause is isolated to the encoder by two facts. First, a debug
hash of the encoder *input* as the driver stages it is distinct for every media item (a tone, a
chirp and white noise all differ from silence and from one another), so decode, padding and
host→device upload hand the encoder genuinely different bytes. Second, the step folds those latents
into the sequence with a **linear projection** (`op_vin` / `op_ain`, each a `dense_bias` GEMM of the
reference's slot rows in `b_evc` / `b_enca` into `b_h`) — a linear map cannot send two different
input vectors to the same output, so had the encoder produced different latents, the conditioning
rows — and therefore the output — would differ. Both point the same way: the encoder is turning all
sufficiently-nonzero content into the same latent. A third check rules out the tempting shortcut — that the container's
encoder weights were converted empty or as placeholders (a zero weight maps every input to one bias, exactly this
signature): the `venc` / `aenc` tensors came from the genuine MiniMax-H3 sources and their recorded quantisation error
is ordinary bf16 rounding (relative Frobenius ≈ 1.6e-3, which a zero tensor cannot produce). The weights are real; the
defect is in how the kernels *execute* them. That is a
numerical-value-parity task (golden-compare the encode chain against the reference encoder, run by
run), deliberately **not** attempted blind here — a change that made the latents merely *differ*
could make them *wrong*, and the encoder kernels are shared with the image path (which is verified
live via the text encoder) and plain generation, both currently green. Until it lands, video /
audio references are accepted and encoded but inert; image references are the kind that steers.
What still differs from the DaSiWa reference (hence not pixel-for-pixel reproducible):
- **The text encoder only *names* a moving picture; it never sees its pixels.** DaSiWa also shows
Qwen a strip of timestamped frames (~2 fps) so the language model perceives the motion; we give
it only the `<Video k>` / `<Audio j>` text label ahead of the prompt. Motion / identity
conditioning for a video therefore rides **entirely** on its VAE rows — images are the only
references that also carry soft-token rows. **The 2 fps frame strip is deferred.**
- **Audio is mono-spread, not kept stereo.** `encoder_audio` returns one mono stream; the server
duplicates it across the encoder's two channels. A truly stereo source is downmixed, unlike a
workflow that might preserve both channels.
- **Frame and slot ceilings.** A reference video is sampled and trimmed to a clip-friendly length
(`n % 17 == 5`, at least 5 frames, at most `max_enc_frames`), and slots are 1..3 for videos and
1..3 for audios — at most three videos, three soundtracks and three standalone audios. The row
budget (point 2) and the interleaving mod-group ceiling (point 1) remain the true binding limits
at high resolution, and now bind for real, since videos reopen the video-conditioned cell.
5. **References and latent upscaling are mutually exclusive.** Combining the widened reference
layout with the small-size-then-upscale denoise is not unified; a request asking for both is
@@ -110,10 +164,12 @@ matter how many there are.
the target size directly.
6. **Numeric parity with the reference denoiser for the *conditioned* step is not yet published.**
Conditioning is verified *active* and *reference-content-sensitive* on-device (see the controlled
check below), but a per-tensor / perceptual match to ComfyUI's outputs for the wide step is an open
parity task. Plain (unconditioned) generation retains its existing parity, and the merge is a no-op
there: with three fine segments the merged group table *is* the fine table.
A per-tensor / perceptual match to ComfyUI's outputs for the wide step is an open parity task.
**Reference-image** conditioning is verified *active* and *content-sensitive*
on-device (see the controlled check below); reference **video / audio** conditioning is wired and
runs to a clean completion but is **not** yet content-sensitive, because the VAE encoders are not
yet value-correct (point 4). Plain (unconditioned) generation retains its existing parity, and the
merge is a no-op there: with three fine segments the merged group table *is* the fine table.
## Reproducing the checks
@@ -122,9 +178,20 @@ matter how many there are.
is sequence-length independent; a plain request merges to exactly its three fine segments.
- **Device (controlled — a *fixed seed on every job*, or a distinct output proves nothing):** run
`/v1/videos` with `task=ref2va` and one `seed` value held constant. Two jobs with the **same seed,
same prompt, same reference count, but different image content** must give **different** `sha256`s —
that content-control is what proves the reference is genuinely consumed (a with-ref vs no-ref pair
is confounded: an image also changes the prompt's token count). Add a `ref_image_1 … ref_image_9`
job: it must *complete* with a clean fault scan — that nine-photo completion is the ceiling lifted
(the pinned build refused it at submit). Sending `seed` and the reference parts requires `task=
ref2va`; the reference parts must be real file parts (e.g. `curl -F ref_image_1=@pic.png`).
same prompt, same reference count, but different reference content** must give **different**
`sha256`s — that content-control is what proves the reference is genuinely consumed (a with-ref vs
no-ref pair is confounded: an image also changes the prompt's token count). For **images** this
holds (two same-size photos → distinct output), proving image conditioning is live. For **videos and
audios it does NOT hold yet**: same seed, one reference video (or one reference audio), only the
media content differing → **identical** `sha256`, because the VAE encoders are not yet value-correct
(point 4). Do **not** read a with-video vs no-video difference as video conditioning working — that
only shows the reference *count* changed the sequence length (a geometry effect, not content); the
content-control pair above is the only honest test, and it currently reports video / audio inert.
Independently of content, the path must *run*: a `ref_image_1 … ref_image_9` job must complete with
a clean fault scan (the ceiling lift — the pinned build refused nine at submit), and a single request
carrying **a picture + a video + that video's `ref_video_audio` soundtrack + a standalone
`ref_audio`** must complete to an MP4 with a clean fault scan (every encoder pass + the widened step
execute — this is the complete DaSiWa shape running end-to-end). Sending `seed` with reference parts
requires `task=ref2va`; reference parts must be real file parts (`curl -F ref_image_1=@pic.png`,
`-F ref_video_1=@clip.mp4`, `-F ref_audio_1=@tone.wav`) — note a leading `<` or `;` in a text field
needs `--form-string`, not `-F`.
+6
View File
@@ -624,6 +624,7 @@ ABI_FIELD(RadVideoGenBatch, enc_slot)
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
ABI_FIELD(RadVideoGenBatch, enc_kind)
ABI_FIELD(RadVideoGenBatch, ref_tab)
ABI_FIELD(RadVideoGenBatch, mod_cu)
ABI_STRUCT(RadVideoGenDecl)
ABI_FIELD(RadVideoGenDecl, name)
ABI_FIELD(RadVideoGenDecl, tmpl)
@@ -671,6 +672,11 @@ ABI_FIELD(RadVideoGenDecl, max_enc_side)
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
ABI_FIELD(RadVideoGenDecl, enc_ratio)
ABI_FIELD(RadVideoGenDecl, ref_rows)
ABI_FIELD(RadVideoGenDecl, max_ref_segs)
ABI_FIELD(RadVideoGenDecl, dbg_enca)
ABI_FIELD(RadVideoGenDecl, dbg_enca_bytes)
ABI_FIELD(RadVideoGenDecl, dbg_evc)
ABI_FIELD(RadVideoGenDecl, dbg_evc_bytes)
ABI_STRUCT(RadVideoGeom)
ABI_FIELD(RadVideoGeom, n_text)
ABI_FIELD(RadVideoGeom, frames)
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""#14 golden — reference-half integrity + content-sensitivity (audio encoder).
The device Aencode reportedly produces a content-INVARIANT latent (all sufficiently-nonzero
audio collapses to one vector, only silence separates) while the host scatter/staging provably
carry distinct content. #14 asks whether the DEVICE encoder MATH is wrong. This script builds the
REFERENCE half of that comparison on the CPU, in the ComfyUI venv's torch, using the reference
network classes themselves and the REAL HF weights -- no device, no shared kernels, read-only, so
it cannot regress the build.
What it establishes:
1. INTEGRITY -- the real `encoder.*` / `pre_block.*` / `mean_proj.*` checkpoint loads under
`load_state_dict(strict=True)` into the extracted classes. A clean load means the port's
`aenc.*` container names are name-consistent with the genuine model (a mapping typo would
surface here as a missing/unexpected key, exactly the class of bug that could masquerade as
"kernel math").
2. REFERENCE IS CONTENT-SENSITIVE, AT BOTH STAGES -- the reference, on the SAME synthetic
contents the on-device audio test used (a 440 Hz tone, an 880 Hz tone, white noise, silence),
gives pairwise-DISTINCT outputs at BOTH:
(a) the raw conv encoder stream `Encoder(x)` [1, 2048, T] -- the f32 conv chain, and
(b) the FULL latent `mean_proj(pre_block(Encoder(x)))` [1, 32, T] -- exactly the quantity
the device writes into `b_enca` (the per-channel latents_mean/std is a bijection and is
omitted; it cannot turn distinct latents into identical ones).
If both are distinct, the reference does not collapse the way the device does, so the
divergence is on the device side. The stage-(b) latent is the target a device dump compares
against once `b_enca` is read back.
Run: <comfyui-venv>/bin/python ref_audio_sensitivity.py [audio_vae.py] [audio_vae.safetensors]
"""
import ast
import hashlib
import math
import sys
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
VAE_PY = sys.argv[1] if len(sys.argv) > 1 else \
"/home/dustin/AI/ComfyUI/comfy/ldm/minimax/audio_vae.py"
WEIGHTS = sys.argv[2] if len(sys.argv) > 2 else \
"/home/dustin/AI/models/MiniMaxAI/MiniMax-H3/audio_vae/diffusion_pytorch_model.safetensors"
# ---- minimal comfy.ops shim (same discipline as gen_golden.py: CPU path only) ----
# The encode path reaches for these comfy.ops symbols:
# cast_to_input -- a plain dtype/device cast of a weight to the activation's dtype/device
# (faithful to comfy/ops.py on CPU: no offload, no requant).
# cast_bias_weight -- returns (weight, None, None) on CPU (no offload stream, no bias requant;
# CausalAttention re-supplies its own packed q/k/v bias below).
# uncast_bias_weight -- no-op on CPU (nothing to un-offload).
# scaled_dot_product_attention -- torch's SDPA (is_causal handled by torch).
# disable_weight_init is used by the module as `ops = comfy.ops.disable_weight_init` then
# `ops.Conv1d(...)`: it must be an OBJECT exposing the plain nn classes (init is irrelevant here,
# every weight is overwritten by load_state_dict).
class _DisableWeightInit:
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
LayerNorm = nn.LayerNorm
Linear = nn.Linear
class _Ops:
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
GroupNorm = nn.GroupNorm
LayerNorm = nn.LayerNorm
Linear = nn.Linear
disable_weight_init = _DisableWeightInit()
@staticmethod
def cast_to_input(weight, input, non_blocking=False, copy=True):
return weight.to(dtype=input.dtype, device=input.device)
@staticmethod
def cast_bias_weight(module, input, bias=None, offloadable=False, **kw):
return module.weight.to(dtype=input.dtype, device=input.device), None, None
@staticmethod
def uncast_bias_weight(module, weight, bias, offload_stream):
return None
@staticmethod
def scaled_dot_product_attention(query, key, value, is_causal=False, **kw):
return F.scaled_dot_product_attention(query, key, value, is_causal=is_causal)
comfy = types.ModuleType("comfy")
comfy.quant_ops = types.ModuleType("comfy.quant_ops")
comfy.ops = _Ops()
def top_level(path, names):
src = open(path).read()
tree = ast.parse(src)
out = {}
for node in tree.body:
key = getattr(node, "name", None)
if key is None and isinstance(node, ast.Assign):
key = [t.id for t in node.targets if isinstance(t, ast.Name)]
else:
key = [key]
for k in key:
if k in names:
out[k] = ast.get_source_segment(src, node)
missing = set(names) - set(out)
if missing:
raise SystemExit(f"not found in {path}: {sorted(missing)}")
return out
ans = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=_Ops.disable_weight_init)
for name in ["snake", "Snake1d", "ResidualUnit", "EncoderBlock", "Encoder",
"GeGluMlp", "CausalAttention", "AttnProjection"]:
exec(top_level(VAE_PY, [name])[name], ans)
class RefEncoder(nn.Module):
"""The encode-side half of MiniMaxH3AudioVAE -- encoder, pre_block, mean_proj -- without
constructing the BigVGAN decoder (whose alias-free / Kaiser classes this harness does not
need to run). Mirrors `MiniMaxH3AudioVAE.__init__`'s encoder fields exactly."""
def __init__(self):
super().__init__()
self.encoder = ans["Encoder"](64, (2, 4, 4, 5, 5), 2048)
self.pre_block = ans["AttnProjection"](2048, 32, num_heads=8)
self.mean_proj = nn.Conv1d(32, 32, 1)
def forward(self, x, full=True):
x = self.encoder(x) # [b, 2048, T]
if not full:
return x
x = self.pre_block(x.transpose(1, 2)).transpose(1, 2) # [b, 32, T]
return self.mean_proj(x) # [b, 32, T]
def load_encoder():
"""Reference encode chain with the REAL HF weights bound. strict=True is the integrity gate."""
enc = RefEncoder()
sd = _read_state(WEIGHTS)
enc.load_state_dict(sd, strict=True) # raises on any mismatch
return enc
def _read_state(path):
"""Pull the encode-side tensors out of the checkpoint as a bare state_dict, folding the
weight-norm parametrization (`weight_g`/`weight_v`) into the single plain `.weight` the
extracted Conv1d holds. The convert splits this the same way -- it stores `v` and a separate
per-output-row scale g[o]/||v[o]|| (core/format/checkpoint.cpp resolve_wnorm); folding into
.weight here reproduces the identical effective linear map, and a per-row scale cannot flatten
content (distinct inputs still give distinct dot products through any nonzero v), so this is
the faithful reference. Only the `encoder.*` convs are weight-norm; `pre_block.*` /
`mean_proj.*` Linears/Conv/LayerNorms load verbatim. latents_mean/std live in the container
meta, not here, and are a per-channel bijection omitted for the distinctness test."""
from safetensors import safe_open
raw = {}
with safe_open(path, framework="pt") as f:
for k in f.keys():
if k.startswith(("encoder.", "pre_block.", "mean_proj.")):
raw[k] = f.get_tensor(k)
out = {}
for k, g in raw.items():
if not k.endswith(".weight_g"):
continue
stem = k[: -len("weight_g")] # e.g. "encoder.block.1.block.0.block.1."
v = raw[stem + "weight_v"]
# classic weight_norm (dim=0): w[o] = g[o] * v[o] / ||v[o]|| over every non-output dim
norm = v.flatten(1).norm(dim=1).view([-1] + [1] * (v.dim() - 1))
out[stem + "weight"] = g / norm * v
for k, v in raw.items():
if k.endswith((".weight_g", ".weight_v")):
continue
out[k] = v
return out
def contents():
"""The same four contents the on-device audio differential used, same length, padded to the
encoder hop (800) exactly as the driver pads an audio tail to a whole hop. The reference
encode takes a stereo [B, 2, L] waveform; the port's encoder is mono and the server duplicates
the mono stream across the two channels, so a mono reference is stacked twice here."""
hop, n = 800, 800 * 40 # 32000 samples = 40 latent frames
def mono(x):
return torch.zeros(1, hop * math.ceil(n / hop)).scatter_(
1, torch.arange(n).view(1, n), x.view(1, n))
t = torch.arange(n, dtype=torch.float32) / 16000.0
def stereo(x):
m = mono(x)
return torch.stack([m, m], dim=1) # [1, 2, L] -- mono spread to both channels
return {
"silence": stereo(torch.zeros(n)),
"tone440": stereo(0.3 * torch.sin(2 * math.tau * 440 * t)),
"tone880": stereo(0.3 * torch.sin(2 * math.tau * 880 * t)),
"noise": stereo(0.3 * torch.randn(n)),
}
def digest(z):
b = z.detach().float().numpy().tobytes()
return hashlib.sha256(b).hexdigest()[:12], float(z.abs().max()), float(z.sum())
def run(enc, full, label):
sigs = {}
with torch.no_grad():
for name, x in contents().items():
# encode(): pad each channel to the hop and fold the two stereo channels into the batch
b, s, length = x.shape
pad = (hop := 800) * math.ceil(length / hop) - length
x = F.pad(x, (0, pad)).reshape(b * s, 1, -1)
z = enc(x, full=full)
sigs[name] = digest(z)
print(f" {name:8s} shape={list(z.shape)} sha={sigs[name][0]} "
f"maxabs={sigs[name][1]:.4f} sum={sigs[name][2]:.2f}", file=sys.stderr)
distinct = len({v[0] for v in sigs.values()}) == len(sigs)
n = len(set(v[0] for v in sigs.values()))
print(f" {label}: content-sensitive={distinct} ({n}/{len(sigs)} distinct)", file=sys.stderr)
return distinct
hop = 800
if __name__ == "__main__":
enc = load_encoder()
enc.eval()
print("integrity: encoder.* + pre_block.* + mean_proj.* loaded strict=True OK", file=sys.stderr)
a = run(enc, full=False, label="raw Encoder(x) [f32 conv stream, 2048xT]")
b = run(enc, full=True, label="FULL mean_proj(pre_block(Encoder(x))) [b_enca, 32xT]")
sys.exit(0 if (a and b) else 3)
+31
View File
@@ -399,6 +399,37 @@ struct FakeMultimodal : IMultimodal {
*out = std::move(it);
return RAD_OK;
}
/* The video/audio VAE form, which the server fills only when a generator declares `encodes`.
* Synthetic frames and a mono tone of a fixed length, each call counted, so a test can watch the
* server decode each reference, spread the mono tone across the encoder's channels and hand it to
* the generator. The sides are the encoder grid; the counts are the NATURAL ones (a short video
* clip, a sample count that is not a whole hop) — padding is the driver's, not the server's. */
int32_t enc_frames = 5, enc_side = 16;
int64_t enc_n = 850;
int n_ienc = 0, n_venc = 0, n_aenc = 0;
int encoder_image(const uint8_t*, size_t, int32_t, int32_t, mm::Frame* out,
std::string*) override {
++n_ienc;
out->w = out->h = enc_side;
out->rgb.assign((size_t)enc_side * enc_side * 3, 128);
return RAD_OK;
}
int encoder_video(const uint8_t*, size_t, int32_t, int32_t, int32_t, std::vector<mm::Frame>* out,
std::string*) override {
++n_venc;
out->assign((size_t)enc_frames, mm::Frame{});
for (mm::Frame& f : *out) {
f.w = f.h = enc_side;
f.rgb.assign((size_t)enc_side * enc_side * 3, 64);
}
return RAD_OK;
}
int encoder_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>* out,
std::string*) override {
++n_aenc;
out->assign((size_t)enc_n, 0.5f);
return RAD_OK;
}
};
/* An embedding model's vector width, input bound and named prompts. */
+110 -3
View File
@@ -195,6 +195,30 @@ int64_t fake_encode_geom(int32_t kind, const int64_t* in, int32_t* gd, int64_t c
return need;
}
/* The encode geometry of the real VAEs, so a video or audio reference gets its true padded volume
* and latent counts (fake_encode_geom above only echoes its input, which is enough for a still
* picture). A video of T frames runs ceil(T/17) clips, padded to clips*17 frames (gd[23]) and
* reporting clips*5-3 latent frames (gd[24]), one frame for a still; an audio of n samples is
* right-padded to a whole hop (gd[0]) and reports n/800 rounded up as its latent frames (gd[12]).
* The driver clip-pads / zero-pads to these figures and reads gd[24] / gd[12] for the table. */
int64_t fake_encode_vae(int32_t kind, const int64_t* in, int32_t* gd, int64_t cap) {
if (!gd) return kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
const int64_t need = kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
if (cap < need) return RAD_E_INVAL;
for (int64_t i = 0; i < need; ++i) gd[i] = 0;
if (kind == RAD_GEN_PASS_AENCODE) {
const int64_t lat = (in[0] + 799) / 800; /* vae_audio_latents: ceil(n / hop) */
gd[0] = (int32_t)(lat * 800); /* samples padded to a whole hop */
gd[12] = (int32_t)lat; /* latent frames */
} else {
const int64_t clips = (in[0] + 16) / 17; /* ceil(T / clip length) */
gd[22] = (int32_t)clips;
gd[23] = (int32_t)(clips * 17); /* frames padded to whole clips */
gd[24] = in[0] <= 1 ? 1 : (int32_t)(clips * 5 - 3); /* vae_latent_frames */
}
return need;
}
struct VideoFixture {
Program prog;
gen::VideoDriver drv;
@@ -868,8 +892,10 @@ TEST(a_reference_conditioned_step_widens_to_the_pack_layout) {
CHECK(saw_encode);
}
/* What the video path cannot consume is refused at submit, naming the part or the budget it
* breaks — never silently dropped into a weaker video. */
/* What the container cannot consume is refused at submit, naming the part or the budget it breaks —
* never silently dropped into a weaker video. A reference video, soundtrack or audio needs the VAE
* encoders; on a container converted without them (encodes 0) they are refused by name here, and on
* one that carries them they are encoded and consume — see the next test. */
TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
std::string why;
@@ -891,7 +917,8 @@ TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
CHECK(has(why, what));
};
/* Videos and audios reach the model through the VAEs, which the video path does not run. */
/* This container carries the tower but not the VAEs (encodes 0): a reference that reaches the
* model only through them is refused by name rather than dropped. */
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::VIDEO, "ref_video_1", 1));
refused(std::move(r), "ref_video_1");
@@ -924,4 +951,84 @@ TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
CHECK(has(why, "at most 4"));
}
/* The other half of the guard above: a container that DOES carry its VAE encoders consumes a
* reference video, its soundtrack and a standalone audio. Each queues an encode pass that folds its
* latents into a fixed slot and enters the pack's reference table. A video and its separately-given
* soundtrack are ONE row — the soundtrack folded into the video's `audio` word — encoded at the
* VIDEO's slot, audio first then video; a standalone audio is its own row. The request carries no
* `media` (only images feed the text encoder), and the driver hands each encoder its padded volume:
* a 5-frame clip repeated out to 17, an 850-sample audio zero-padded up to two 800-sample hops. */
TEST(reference_videos_and_audios_are_encoded_into_the_reference_table) {
VideoFixture f;
f.build();
with_tower(f, 16);
RadVideoGenDecl& d = f.prog.video_gen;
d.encodes = 1;
d.enc_ratio = 16;
d.max_enc_frames = 289;
d.max_enc_side = 256;
d.max_enc_samples = 500000;
CHECK_OK(f.start_with_encode_gen(fake_encode_vae));
std::string why;
auto r = f.req(2, 2); /* 2 steps keeps the walk short; the encodes all run before it */
/* A reference video: the 5-frame trimmed minimum at 16x16 (short final clip -> repeat frame). */
gen::VideoRefMedia v = ref_part(gen::VideoRefMedia::VIDEO, "ref_video_1", 1);
v.enc_frames = 5; v.enc_h = 16; v.enc_w = 16;
v.enc_pixels.assign(5 * 16 * 16 * 3, 1.0f);
/* Its soundtrack: 1600 samples over 2 channels — already whole hops, so unpadded. */
gen::VideoRefMedia a = ref_part(gen::VideoRefMedia::VIDEO_AUDIO, "ref_video_audio_1", 1);
a.enc_n = 1600; a.enc_channels = 2;
a.enc_samples.assign(2 * 1600, 0.25f);
/* A standalone audio: 850 samples, not a whole hop, so the driver zero-pads 750 onto it. */
gen::VideoRefMedia s = ref_part(gen::VideoRefMedia::AUDIO, "ref_audio_2", 2);
s.enc_n = 850; s.enc_channels = 2;
s.enc_samples.assign(2 * 850, -0.5f);
r->refs.push_back(v);
r->refs.push_back(a);
r->refs.push_back(s);
CHECK_OK(f.drv.submit(std::move(r), &why));
int saw_venc = 0, saw_vaudio = 0, saw_saudio = 0;
const int32_t* tab = nullptr;
for (int i = 0; i < 12 && saw_venc + saw_vaudio + saw_saudio < 3; ++i) {
const RadBatch* b = f.drv.next(0);
if (!b) break;
const RadVideoGenBatch* V = b->vgen_b;
if (b->gen == RAD_GEN_PASS_VENCODE || b->gen == RAD_GEN_PASS_AENCODE) {
REQUIRE(V != nullptr);
if (b->gen == RAD_GEN_PASS_VENCODE) {
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_VIDEO);
CHECK_EQ(V->enc_slot, (int32_t)1);
CHECK_EQ(V->enc_frames, 17); /* 5 frames clip-padded to one whole clip */
++saw_venc;
} else if (V->enc_kind == RAD_ENC_VAUDIO) { /* the soundtrack, at the VIDEO's slot */
CHECK_EQ(V->enc_slot, (int32_t)1);
CHECK_EQ(V->enc_n_samples, 1600); /* whole hops: unpadded */
++saw_vaudio;
} else { /* the standalone audio, its own slot */
CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_AUDIO);
CHECK_EQ(V->enc_slot, (int32_t)2);
CHECK_EQ(V->enc_n_samples, 1600); /* 850 zero-padded up to two hops */
++saw_saudio;
}
}
if (V && V->ref_tab && !tab) tab = V->ref_tab;
f.answer(10 * i);
CHECK_OK(f.drv.done());
}
CHECK_EQ(saw_venc, 1);
CHECK_EQ(saw_vaudio, 1);
CHECK_EQ(saw_saudio, 1);
REQUIRE(tab != nullptr);
/* Two rows: the video (its soundtrack folded into the `audio` word) and the standalone audio. The
* VIDEO_AUDIO is not a row of its own. Video: kind 2, slot 1, 1x1 grid, 5 frames -> 2 latent
* frames, soundtrack 1600/800 = 2. Audio: kind 1, slot 2, no grid, 850 -> 2 latent frames. */
CHECK_EQ(tab[0], 2);
CHECK_EQ(tab[1], 0);
CHECK_EQ(tab[2], 2); CHECK_EQ(tab[3], 1); CHECK_EQ(tab[4], 1); CHECK_EQ(tab[5], 1);
CHECK_EQ(tab[6], 2); CHECK_EQ(tab[7], 2);
CHECK_EQ(tab[8], 1); CHECK_EQ(tab[9], 2); CHECK_EQ(tab[10], 0); CHECK_EQ(tab[11], 0);
CHECK_EQ(tab[12], 0); CHECK_EQ(tab[13], 2);
}
RAD_TEST_MAIN()
+75
View File
@@ -437,6 +437,81 @@ TEST(ref2va_pictures_are_presented_before_the_prompt) {
CHECK(g.tokens == want);
}
/* A generator that carries its VAE encoders (encodes 1): the reference parts are not merely passed
* as bytes — the picture, the video and both audios are decoded into the encoder's own form, the
* audio's mono tone spread across the encoder's channels — and every reference is spoken before the
* prompt in the reference's order: the picture's label and run, the soundtrack's `<Audio j>` right
* before its video's `<Video k>`, then the standalone `<Audio j>`. This is the server half; the
* driver half (padding, slots, the pack table) is tests/video_gen_test.cpp. */
TEST(ref2va_videos_and_audios_are_encoded_and_spoken) {
FakeMultimodal mm;
mm.expand = { 900, 901 };
mm.enc_frames = 5; mm.enc_side = 16; mm.enc_n = 850;
FakeVideoGen gen;
std::unique_ptr<Fixture> f(new Fixture(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
d.videos = &gen;
d.mm = &mm;
o.video_model = true;
gen.inf.encodes = 1;
gen.inf.enc_ratio = 16;
gen.inf.max_enc_side = 256;
gen.inf.max_enc_frames = 289;
gen.inf.max_enc_samples = 500000;
} }));
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "fox" },
FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" },
FormPart{ "ref_image_1", "a.png", "image/png", "PA" },
FormPart{ "ref_video_1", "v.mp4", "video/mp4", "ftyp" },
FormPart{ "ref_video_audio_1", "s.wav", "audio/wav", "RIFF" },
FormPart{ "ref_audio_1", "b.mp3", "audio/mpeg", "ID3" } };
HttpResponse r = f->srv->router().dispatch(q);
REQUIRE_EQ(r.status, 200);
/* One image, one video and two audios (the video's soundtrack plus the standalone) reached the
* encoder each belongs to. */
CHECK_EQ(mm.n_ienc, 1);
CHECK_EQ(mm.n_venc, 1);
CHECK_EQ(mm.n_aenc, 2);
const gen::VideoRequest& g = gen.last();
REQUIRE_EQ(g.refs.size(), (size_t)4); /* sorted (kind, index): image, video, video_audio, audio */
/* The picture: one frame at the encoder grid, its pixels filled for the video VAE. */
CHECK_EQ((int)g.refs[0].kind, (int)gen::VideoRefMedia::IMAGE);
CHECK_EQ(g.refs[0].enc_frames, 1);
CHECK_EQ(g.refs[0].enc_h, 16);
CHECK_EQ(g.refs[0].enc_w, 16);
CHECK_EQ(g.refs[0].enc_pixels.size(), (size_t)16 * 16 * 3);
/* The video: the trimmed natural frame count, concatenated over the grid (the driver pads). */
CHECK_EQ((int)g.refs[1].kind, (int)gen::VideoRefMedia::VIDEO);
CHECK_EQ(g.refs[1].enc_frames, 5);
CHECK_EQ(g.refs[1].enc_pixels.size(), (size_t)5 * 16 * 16 * 3);
/* The soundtrack and the standalone audio: the mono tone spread across the generator's two
* channels, enc_n the natural (unpadded) count. */
CHECK_EQ((int)g.refs[2].kind, (int)gen::VideoRefMedia::VIDEO_AUDIO);
CHECK_EQ(g.refs[2].enc_channels, 2);
CHECK_EQ(g.refs[2].enc_n, (int64_t)850);
CHECK_EQ(g.refs[2].enc_samples.size(), (size_t)2 * 850);
CHECK_EQ(g.refs[2].enc_samples[0], g.refs[2].enc_samples[850]); /* both channels the same tone */
CHECK_EQ((int)g.refs[3].kind, (int)gen::VideoRefMedia::AUDIO);
CHECK_EQ(g.refs[3].enc_n, (int64_t)850);
/* The prompt speaks every reference before the words, in the reference's order. */
std::vector<int32_t> want;
auto chars = [&](const std::string& s) { for (unsigned char c : s) want.push_back((int32_t)c); };
chars("<v>");
chars("<Picture 1>: ");
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
chars("<Audio 1>: ");
chars("<Video 1>: ");
chars("<Audio 2>: ");
chars("fox");
CHECK(g.tokens == want);
}
/* Everything about the parts that cannot be right is refused naming the part (or `task` when
* the media themselves are the question), before anything is queued. */
TEST(ref2va_requests_are_refused_naming_the_part) {