From 658f7b7214da30935efff5cc1d15317a2ba3e4d1 Mon Sep 17 00:00:00 2001 From: gearwave00001 Date: Mon, 19 Oct 2026 15:25:32 -0500 Subject: [PATCH] ref2va: wire video and audio reference conditioning end-to-end (all three ref kinds live on device) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- abi/rad_builder.h | 13 + arch/minimaxh3/minimaxh3.cpp | 32 ++- core/gen/video.h | 18 +- core/gen/video_driver.cpp | 268 +++++++++++++++---- core/gen/video_driver.h | 9 + core/mm/processor.cpp | 63 +++++ core/mm/processor.h | 19 ++ core/server/adapters.h | 18 ++ core/server/iface.h | 20 ++ core/server/videos.cpp | 147 ++++++---- docs/NOTE-REF2VA.md | 151 ++++++++--- tests/abi_layout_rows.h | 6 + tests/data/vae_geom/ref_audio_sensitivity.py | 234 ++++++++++++++++ tests/server_fakes.h | 31 +++ tests/video_gen_test.cpp | 113 +++++++- tests/videos_test.cpp | 75 ++++++ 16 files changed, 1055 insertions(+), 162 deletions(-) create mode 100644 tests/data/vae_geom/ref_audio_sensitivity.py diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 45f59c87..e3fc97b8 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -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); diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index c40f9707..862970d8 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -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)); diff --git a/core/gen/video.h b/core/gen/video.h index dbff49ae..9767e2e6 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -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 enc_pixels; int32_t enc_frames = 0, enc_h = 0, enc_w = 0; std::vector enc_samples; diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index ca28057d..1d382abf 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include 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(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 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 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 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(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(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(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(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(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(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(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(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: { diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index cc89aa27..6e7fdd92 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -216,6 +216,15 @@ private: int64_t audio_bytes_ = 0; std::vector 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 out_; /* one per rank */ std::vector vout_; Pass pass_; diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index f5d60e23..84321341 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -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 vae_sample_cb(const VideoInfo& info, const void* user) { + const VaeSampleArgs* a = static_cast(user); + const int64_t avail = info.n_frames > 0 ? info.n_frames : 1; + const int64_t cap = a->max_frames > 0 ? std::min(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(cap, 5); + const int64_t take = std::max(1, std::min(want, avail)); + std::vector 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* 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* 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 sample_cb(const VideoInfo& info, const void* user) { diff --git a/core/mm/processor.h b/core/mm/processor.h index f17bf1f9..f89a22c1 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -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* 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* 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); diff --git a/core/server/adapters.h b/core/server/adapters.h index d39e2b4e..e46135c6 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -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* 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* 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; } diff --git a/core/server/iface.h b/core/server/iface.h index 8f8f4544..bbe0d9d1 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -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* 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* 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 diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 46b40988..cd0edd07 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -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 `