diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 834efdd1..ad302026 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 22u +#define RAD_ABI_VERSION 23u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index e91eb808..0028695d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -853,9 +853,29 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); * pass carries the geometry its latent has at that point: a step before the VUPSCALE pass is at * W' x H'. The schedule is the request's own, whatever size each evaluation runs at. * + * Reference conditioning (ref2va), for a program whose container carries the VAE encoders + * (`encodes`, below): before the prompt pass the driver encodes the request's reference media, + * one media a pass. Nothing the passes make is read back — each latent lands in the lane, and the + * step's packed sequence carries it: + * + * RAD_GEN_PASS_VENCODE one reference video's frames, staged in `enc_pixels` (RadVideoGenBatch), + * to the lane's video latents. + * RAD_GEN_PASS_AENCODE one reference audio's samples, staged in `enc_samples`, to the lane's + * soundtrack latents. + * + * `enc_kind` names the media (RAD_ENC_*, rad_runtime.h) and `enc_slot` is its 1-based number + * within that kind; RAD_ENC_TAIL — slot 0 — is the request's continuity tail, the frames of the + * clip it continues, which rides Vencode. The media an encoder takes is bounded by the model: + * reference pictures are one frame, reference video and the tail up to 289 frames, every frame + * at most 256 x 256 with both sides multiples of 16, and a reference audio up to 500 000 + * samples; `rad_arch_encode_geom` (below) is the authority and refuses what it cannot encode. A + * program without the encoders declares neither pass and `encodes` stays 0, so the server + * refuses a request that carries references. + * * A program declares exactly one of this, the other generators, logits or pooled vectors. */ enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10, - RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12 }; + RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12, + RAD_GEN_PASS_VENCODE = 13, RAD_GEN_PASS_AENCODE = 14 }; typedef struct RadVideoGenDecl { const char* name; /* "minimax-h3" -- the served model id and messages */ @@ -902,6 +922,49 @@ typedef struct RadVideoGenDecl { * and fewer than the default schedule's. */ double upscale_max; int32_t upscale_refine; + + /* Reference media a request may carry (ref2va): the ceilings the server enforces and + * `/v1/models` reports. All 0 — the zero default — on a generator that conditions on no + * reference media, which is how the server refuses the task outright; a generator declares + * them only once it can actually consume the bytes. Trailing since ABI 22: an older plugin's + * declaration reads none and keeps the 0 default. */ + int64_t max_ref_images, max_ref_videos, max_ref_audios; + + /* Nonzero when the container carries the video and audio VAE encoders, so the driver may + * stage Vencode and Aencode passes (above). Trailing since ABI 23: an older plugin declares + * none and keeps the 0 default. */ + int32_t encodes; + + /* The ceilings one encode pass may carry, so the driver can size its staging slab: a video's + * clip-padded frame count, the encoder's side (square, a multiple of its downsample), and an + * audio's sample count. Only meaningful with `encodes`; 0 otherwise. The driver stages at most + * one media item per pass, so the slab is these bounds, not a per-request sum. Trailing since + * ABI 23 (the encoder's own pass enums and batch fields): an older plugin declares none. */ + int64_t max_enc_frames, max_enc_side, max_enc_samples; + + /* The encoder's spatial downsample, so the server can snap a reference's sides to a multiple + * of it before handing them over (the geom refuses any other). Distinct from `size_multiple`, + * which bounds the *generated* video's size and is a further multiple of this. Only meaningful + * with `encodes`; 0 otherwise. Trailing since ABI 23. */ + int32_t enc_ratio; + + /* Nonzero when this generator's denoiser *consumes* the reference table the driver stages in + * `RadVideoGenBatch::ref_tab` — i.e. its per-step packed sequence already interleaves the + * reference blocks between the text and the audio/video targets, so the driver must size and + * stage those rows (via `rad_arch_video_pack`) rather than the plain `[text|audio|video]` + * layout. Trailing since ABI 23: an older plugin declares none and keeps the 0 default, which + * is exactly the plain path — the driver then never widens rows or segment boundaries and the + * generated bytes are unchanged. It is the arch, not the driver, that knows whether its own + * denoiser reads `ref_tab`, so this flag is what makes staging and consumption flip together. */ + int32_t ref_rows; + + /* The largest segment count this generator's modulation table holds: its denoiser lays out one + * modulation cell per pack segment, and the table is sized `kMaxSegs` columns. A conditioned + * pack whose segments exceed this cannot be built -- the step would abort the engine. The driver + * refuses such a request at submit (it lays the pack out itself, so it knows the count before + * dispatch) rather than letting the arch fail 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; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); @@ -1184,6 +1247,41 @@ typedef struct RadVideoGeom { enum { RAD_VPOS_STEP = 1, RAD_VPOS_DECODE = 2 }; int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap); +/* The packed sequence's segment boundaries for a video generator: cu[k] is the first row of + * segment k (modulation, attention sinks -- whatever segmentation the model lays out), and + * cu[n-1] the sequence's total rows -- the same rows RAD_VPOS_STEP positions. With `cu` null + * it returns the number of int32s needed; with `cap` too small, a negative status. Additive + * export; RAD_ABI_VERSION does not move -- a driver without it stages its own segmentation, + * which for a plain [text | audio | video] request is this table. Called on any thread. */ +int64_t rad_arch_video_segs(const RadVideoGeom* g, int32_t* cu, int64_t cap); + +/* The geometry of a video generator's encode passes (RAD_GEN_PASS_VENCODE, RAD_GEN_PASS_AENCODE; + * rad_builder.h, "Reference conditioning"): the i32 vector the driver stages into the pass's + * `enc_geom_d` device buffer, derived from the media's own shape, because what the network's + * strided convolutions and causal attention run at — the padded sample length, the latent frame + * count — is only the model's to know. `kind` is the pass value; `in` is four i64s + * {frames_or_samples, height, width, channels}, each unused entry 0. With `out` null it returns + * the number of int32s needed, or a negative status for media the model cannot take; with `out` + * it fills `out[cap]`. The driver stages the samples right-padded with zeros to the length this + * reports (entry 0), and copies these bytes to the device verbatim: it interprets nothing. + * Additive export; RAD_ABI_VERSION does not move — a driver without it drives no encode pass and + * the server refuses references. Called on any thread. */ +int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, int64_t cap); + +/* The whole packed-sequence layout of a reference-conditioned video request: the general form + * of rad_arch_video_segs. `g` is the target's geometry and `ref_tab` the request's keyframes + * and VAE references -- RadVideoGenBatch::ref_tab, its int32 table verbatim -- or null when the + * request conditions on no VAE media, which lays out the plain [text | soundtrack | video] + * sequence. Returns the packed sequence's total rows -- the rows RAD_VPOS_STEP positions -- or + * a negative status for counts the model cannot present or caps too small to write into. With + * `seg` non-null it writes the segment boundaries (seg[k] the first row of segment k, of the n + * it needs) when `cap_seg` int32s hold them; with `pos` non-null the rotary positions (f32 + * [3, rows]) when `cap_pos` rows hold them. A null `seg` and `pos` answer with the rows alone, + * which is all a submit needs to size the request. Additive export; RAD_ABI_VERSION does not + * move -- a driver without it refuses reference requests. Called on any thread. */ +int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg, + int64_t cap_seg, float* pos, int64_t cap_pos); + int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx); /* Forward declaration; the signature is in rad_runtime.h. */ struct RadCtx; diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index c7694a95..101ca765 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -424,6 +424,8 @@ enum { * ADECODE no rows of the pass's own. * VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE). * VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`. + * VENCODE no rows of the pass's own: a reference video's pixels in `enc_pixels`. + * AENCODE no rows of the pass's own: a reference audio's samples in `enc_samples`. * * Every pointer is device memory unless the name ends in _h. */ typedef struct RadVideoGenBatch { @@ -468,8 +470,55 @@ typedef struct RadVideoGenBatch { * soundtrack's) the latents are re-noised to; `seed` is a step's. */ RadVideoGeom geom_from; const float* upscale; /* f32 [1]: the factor the network is told */ + + /* ---- VENCODE / AENCODE (rad_builder.h, "Reference conditioning"). `enc_pixels` is a + * Vencode pass's f32 [enc_frames, enc_height, enc_width, 3] row-major RGB, values 0..255 — + * un-normalised: the encoder applies its own pixel normalisation first. `enc_frames` is the + * clip-padded frame count the export reports (entry 23): 1 for a still, else a whole number + * of clips with a short last clip pre-padded by repeating its final frame. `enc_samples` is + * an Aencode pass's f32 [enc_channels, enc_n_samples] channel-major — each channel a + * contiguous sequence the encoder's convolutions read in place — right-padded with zeros to + * the length `rad_arch_encode_geom` reports (its entry 0). `enc_geom_d` is that length and + * the pass's other plugin-defined geometry, device i32, the driver staging verbatim what the + * export returned (the encoder's kernels read the padded lengths from here, as a cu does). + * `enc_kind` names the media the pass carries and `enc_slot` is its 1-based number within + * that kind; RAD_ENC_TAIL is the request's continuity tail — its slot 0 — which rides + * Vencode. A pass writes nothing the core reads back: the latents live in the lane. Trailing + * since ABI 23: a batch an older engine built carries none. */ + const float* enc_pixels; + int32_t enc_frames, enc_height, enc_width; + const float* enc_samples; + int64_t enc_n_samples; + int32_t enc_channels; + int32_t enc_slot; + const int32_t* enc_geom_d; + int32_t enc_kind; + + /* ---- Reference rows of a VSTEP pass (rad_builder.h, rad_arch_video_pack). `ref_tab` is the + * request's keyframes and VAE references as a host int32 table -- the driver holds it, and + * the step reads it host-side as it reads `geom`. Null when the request conditions on no + * VAE media; otherwise self-describing: [0] the number of references, [1] the number of + * keyframes, then 6 words per reference {kind, slot, height, width, frames, audio} and 3 + * words per keyframe {frame, video, audio}, in the order the references are presented. A + * reference's `kind` is 0 a picture, 1 a standalone audio, 2 a video, 3 a video's + * soundtrack; `slot` is its 1-based number within its kind -- the slot its encode pass + * wrote. The counts are latent units: a reference's own latent grid (height, width), its + * latent frames and its audio latents, 0 where the kind carries neither. A batch without + * the field laid out is one an older engine built: no references. Trailing since ABI 23. */ + const int32_t* ref_tab; } RadVideoGenBatch; +/* RadVideoGenBatch::enc_kind: which reference media an encode pass carries. A plugin's latent + * buffer is indexed by the kind and the slot together: two kinds both number their media from + * 1, so the kind is what keeps image 1 and video 1 apart. */ +enum { + RAD_ENC_TAIL = 0, /* the request's continuity tail: the frames of the clip it continues */ + RAD_ENC_IMAGE = 1, /* a reference picture; rides Vencode */ + RAD_ENC_VIDEO = 2, /* a reference video; rides Vencode */ + RAD_ENC_VAUDIO = 3, /* the soundtrack of reference video `enc_slot`; rides Aencode */ + RAD_ENC_AUDIO = 4 /* a standalone reference audio; rides Aencode */ +}; + /* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent * frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w, * first, last) is one run, and the same chunk in patches. */ diff --git a/arch/common/rad_block_vit.h b/arch/common/rad_block_vit.h index 9d0186e2..814530c6 100644 --- a/arch/common/rad_block_vit.h +++ b/arch/common/rad_block_vit.h @@ -78,16 +78,43 @@ struct VisionTower { return rad_meta_geti(m, "vision_config.depth", 0) > 0; } + /* `gate_weights` asks for a weight-presence check before anything of the tower is declared: + * a config's vision_config does not promise the checkpoint ships the weights (see declare), + * and a declared weight with no source fails convert and load alike. When it is set and the + * stem is not there, declare returns RAD_OK having declared nothing — `on` stays false and + * the caller drops its media wiring. Callers whose checkpoints always ship their tower + * leave it false and see the tower exactly as before. */ int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, - int64_t model_embd, int first_group, bool deepstack = false); + int64_t model_embd, int first_group, bool deepstack = false, + bool gate_weights = false); void step(RadCtx* c, const RadBatch* batch) const; }; inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, - Names& nm, int64_t model_embd, int first_group, bool deepstack) { + Names& nm, int64_t model_embd, int first_group, bool deepstack, + bool gate_weights) { on = false; if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + /* The weight gate, first and before any shape is read: the stem's map is registered here, + * so w_patch below is declared through it instead of mapped again (a COPY map declared + * twice is refused). The lookup of a weight's encoding resolves through the name map — + * convert resolves the map against the checkpoint, load looks the name up in the container — + * so mapping first and then asking is the only presence test both sides answer the same way. + * A stem that stays unfound leaves its map entry dangling, which is inert: name maps are + * consulted by name when a declared weight resolves and are not serialized into the + * container. */ + if (gate_weights) { + if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0) + return RAD_E_INVAL; + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) { + std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not " + "ship; declaring without it\n"); + return RAD_OK; + } + } + depth = rad_meta_geti(m, "vision_config.depth", 0); width = rad_meta_geti(m, "vision_config.hidden_size", 0); heads = rad_meta_geti(m, "vision_config.num_heads", 0); @@ -173,8 +200,12 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB if (map_copy(b, dn, src) < 0) return 0; return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g); }; - w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"), - RAD_BF16, { width, patch_dim }, grp_model()); + /* The gated stem is already mapped by the gate above; declaring the map again would fail. */ + w_patch = gate_weights + ? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, + RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model()) + : bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"), + RAD_BF16, { width, patch_dim }, grp_model()); b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"), RAD_BF16, { width }, grp_model()); w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"), diff --git a/arch/minimaxh3/CMakeLists.txt b/arch/minimaxh3/CMakeLists.txt index 6ad47f4d..b007014a 100644 --- a/arch/minimaxh3/CMakeLists.txt +++ b/arch/minimaxh3/CMakeLists.txt @@ -7,4 +7,10 @@ if(NOT COMMAND rad_add_plugin) rad_plugin_defaults() endif() -rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp) +# rad_ref2va_pack.cpp holds the Ref2VA sequence packing and rad_vae_geom.cpp the encode geometry +# (latent counts, tile plans, normalization tables) -- both pure host arithmetic, device-free, and +# unit-tested on their own (tests/ref2va_pack_test.cpp, tests/vae_geom_test.cpp compile them +# directly). The video pass consumes them as the reference-media path lands. +rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rad_ref2va_pack.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rad_vae_geom.cpp) diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 75c310e8..ef96ca50 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -81,8 +81,12 @@ * tiles; the audio decoder runs whole on every rank. */ #include +#include #include +#include "rad_ref2va_pack.h" +#include "rad_vae_geom.h" + #include #include #include @@ -99,8 +103,17 @@ using namespace rad::arch; /* ================================================================== the model's constants */ /* The text encoder's layer the conditioning is read after. */ enum { kTextLayers = 50 }; -/* The longest prompt, in tokens; a structured prompt in the model's own style is about 1500. */ -enum { kMaxText = 2048 }; +/* The longest prompt, in tokens. Plain text in the model's own style is about 1500; a ref2va + * presentation is the FULL TE sequence — every vision pad of every reference rides it + * (docs/PORT-REF2VA.md §5.2 risk 3) — so a few match-mode photos plus a structured brief + * measures ~3 K tokens and the ceiling is set with room over that, not against a bare prompt. + * 8 192 (not 16 384) is the largest that leaves the reference modulation table -- which widens + * with the segment count -- room inside the per-rank activation budget on the dual-32 GB TP2 + * target (§5.3): 16 384 crowds the KV pool to nothing once the table grows. The DiT row and + * VSA-tile ceilings, not this, bound how much reference media fits; raising this back to 16 384 + * with the table deduplicated to distinct cells (the reference's own ref2va_mod_rows) is the + * follow-up that restores the full presentation width without the VRAM cost. */ +enum { kMaxText = 8192 }; /* Requests holding state at once: one denoising, one conditioned and waiting. */ enum { kMaxLanes = 2 }; /* Model evaluations a request may take (kMaxSteps), and the default sigma grid points (the @@ -109,7 +122,7 @@ enum { kMaxSteps = 64, kDefSteps = 50 }; /* Time: 24 frames a second; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, * and a decode pass reads 7 latent frames from 5 c. 5 to 15 seconds: 7 to 20 chunks. */ enum { kFps = 24, kFpc = 17, kFtail = 5, kLpc = 5, kLtail = 2, kDecLat = 7 }; -enum { kMinChunks = 7, kMaxChunks = 20, kDefChunks = 7 }; +enum { kMinChunks = 4, kMaxChunks = 20, kDefChunks = 7 }; /* EXPERIMENT: short-chunk test */ /* Space: 16 pixels a latent, 2 x 2 latents a patch; sides multiples of 32 from 256, at most the * 1344 x 768 canvas's area, 4:1 at most. */ enum { kScale = 16, kPatch = 2, kMult = 32, kMinSide = 256, kMaxAspect = 4 }; @@ -144,6 +157,19 @@ static const char* kPixStd = "0.229 0.224 0.225"; enum { kSegText = 0, kSegAudio = 1, kSegVideo = 2, kSegs = 3 }; static const int kSegMod[kSegs] = { 1, 2, 0 }; +/* Reference conditioning: the modulation table's segment-column capacity and the flip that makes + * the denoiser CONSUME the request's reference table. The table is widened from the plain three + * segments to `kMaxSegs` columns so a reference-conditioned pack -- whose segments are text, then + * the reference blocks in request order, then the two target streams -- has a cell each. The + * reference ceilings (<=9 pictures, <=3 clips-with-soundtrack, <=3 standalone audios) plus keyframes + * and the two targets stay far under this. `kRefConsume` is the terminal switch: while it is 0 the + * denoiser lays and reads the plain three-segment sequence byte-identically and `ref_rows` is 0, so + * the reference path is declared-but-dormant; setting it to 1 makes `step_dit` scatter the encoded + * reference latents into the packed sequence and read the widened table. Flip it only with a + * container that carries the encoder tensors, and verify a ref-present-vs-ref-absent run differs. */ +enum { kMaxSegs = 8 }; +static const int kRefConsume = 1; + /* ================================================================== geometry, on the host */ /* diffusers' AutoencoderKLMiniMaxH3._split_tiles in latents: the first latent of each tile across * a side of `L` latents. The overlaps start at the minimum and the slack goes to them round-robin, @@ -212,59 +238,26 @@ static void vsa_bounds(double sparsity, int64_t* tiles, int64_t* keep) { *keep = vsa_keep(sparsity, best); } -/* The packed sequence's rotary positions (diffusers' MiniMaxH3PrepareLayoutStep), in f64 as the - * reference builds them, f32 as its rope reads them. Text rows count up on the time axis; the - * media's clock starts after them. A latent frame spans 5/3 (1, 4, 4, 4, 4)[i % 5] units of time, - * a soundtrack latent one; the spatial axes are each side's latents over the square root of the - * frame's area, centred on the unit interval and scaled by 32 (numpy's linspace without its - * endpoint), and a soundtrack's two channels sit at the two ends of the width axis. */ +/* The packed sequence's rotary positions (diffusers' MiniMaxH3PrepareLayoutStep): the plain + * request's [text | soundtrack | video] layout is exactly the reference-free pack, so the pack + * is the single source of these coordinates -- the same code the reference-media path will use, + * golden-tested against the reference's own numbers (tests/data/ref2va). Text rows count up on + * the time axis and the media's clock starts after them; the rules for the axes are the pack's. + * (The hand-rolled grid this used to compute recovered the axis step as ((1-ratio)/2 + ratio) - + * (1-ratio)/2, which cancelled to exactly 0 on the grid's centre row where the reference's + * arange*ratio/n leaves a float64 residue of ~1e-15; one row on ten of the 1242 legal sizes, + * the last bit of one rope angle. The reference's form is authoritative.) */ static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) { if (!g || g->n_text < 1 || g->lat_frames < 1 || g->lat_h < kPatch || g->lat_w < kPatch || g->n_audio < 1) return RAD_E_INVAL; - const int64_t nt = g->n_text, na = g->n_audio, F = g->lat_frames; - const int64_t ph = g->lat_h / kPatch, pw = g->lat_w / kPatch; - const int64_t rows = nt + kAudioCh * na + F * ph * pw; - if (!pos) return rows; - if (cap < rows) return RAD_E_INVAL; - float* P0 = pos; - float* P1 = pos + rows; - float* P2 = pos + 2 * rows; - const double sq = std::sqrt((double)g->lat_h * (double)g->lat_w); - auto grid = [&](int64_t dim, std::vector* out) { - const int64_t n = dim / kPatch; - const double ratio = (double)dim / sq, left = (1.0 - ratio) / 2.0; - const double step = ((left + ratio) - left) / (double)n; - out->resize((size_t)n); - for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = ((double)i * step + left) * 32.0; - }; - std::vector hg, wg; - grid(g->lat_h, &hg); - grid(g->lat_w, &wg); - int64_t r = 0; - for (int64_t i = 0; i < nt; ++i, ++r) { - P0[r] = (float)(double)i; - P1[r] = 0.0f; - P2[r] = 0.0f; - } - for (int64_t c = 0; c < kAudioCh; ++c) - for (int64_t k = 0; k < na; ++k, ++r) { - P0[r] = (float)((double)nt + (double)k); - P1[r] = 0.0f; - P2[r] = (float)(c == 0 ? wg.front() : wg.back()); - } - static const int kPattern[5] = { 1, 4, 4, 4, 4 }; - double t = (double)nt; - for (int64_t f = 0; f < F; ++f) { - for (int64_t y = 0; y < ph; ++y) - for (int64_t x = 0; x < pw; ++x, ++r) { - P0[r] = (float)t; - P1[r] = (float)hg[(size_t)y]; - P2[r] = (float)wg[(size_t)x]; - } - t += 5.0 / 3.0 * (double)kPattern[f % 5]; - } - return rows; + const Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, (int)g->n_audio }; + Ref2VAPack p; + if (ref2va_build((int)g->n_text, pg, {}, {}, &p) != 0) return RAD_E_INVAL; + if (!pos) return p.rows; + if (cap < p.rows) return RAD_E_INVAL; + std::copy(p.pos.begin(), p.pos.end(), pos); /* already planar: all times, rows, columns */ + return p.rows; } /* A decode pass's rows: every tile of the frame, each kPeriod rows. */ @@ -281,6 +274,7 @@ struct TeLayer { GateQuantFP8 gq{}; rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; + rad_op op_qkr_m = 0; /* `op_qkr`'s interleaved-M-RoPE twin, a ref2va conditioning */ }; /* A token refiner block: a plain pre-norm transformer block, no rotary, no modulation. */ @@ -368,8 +362,28 @@ enum : int { kGrpVae = 3000, kGrpAudio = 3100, kGrpUps = 3200, + kGrpTower = 3300, + kGrpVenc = 3400, + kGrpAenc = 3500, + /* The encoder weights only a HOST kernel reads — conv_in's 3-channel conv, the k=1 convs and + * the snake alphas. Placement keeps a group with any host-only reader in the container's + * mapping whole, which would drag the device-read weights down with it (and their stored + * forms differ: tap-major vs plain) — so the host-read ones form groups of their own. */ + kGrpVencH = 3450, + kGrpAencH = 3550, }; +/* ---- the VAE encoders (ref2va). Reference media are bounded by what these buffers hold: a + * picture or video frame no larger than the reference's own 256-pixel tile, a video of at most + * 289 frames (17 clips' worth), a waveform of at most 500 000 samples (15.6 seconds, 625 + * latents). The latent buffers PERSIST, one slot a media: the video encoder folds a media's + * latents into patch rows — up to 82 latent frames at 256 x 256 is 82 * 8 * 8 = 5248 rows of 96 + * columns — and the audio encoder writes its two channels' 625 latents, 1250 rows of 32. */ +enum { kEncMaxSide = 256, kEncMaxFrames = 289, kEncMaxSamples = 500000 }; +enum { kEncSlotsV = 13, kEncSlotsA = 6 }; +enum { kEncSlotRowsV = 82 * (kEncMaxSide / 32) * (kEncMaxSide / 32), + kEncSlotRowsA = kAudioCh * (kEncMaxSamples / kAudioHop) }; + /* The evaluations a request runs at the full size after a latent upscale, by default: of a * distilled release's eight, and of the base model's 49. */ enum { kUpsRefineDistilled = 3, kUpsRefineBase = 12 }; @@ -389,6 +403,15 @@ struct Model { ActFP8 a_th{}, a_tattn{}, a_tffn{}; std::vector te; + /* ---- the ref2va vision tower, a Qwen3-VL encoder living in the text encoder's container. + * Served only when the container actually carries its weights — the meta's vision_config is + * there even for containers that ship without the tower, so presence is probed on the + * tensor itself. The tower's merged rows scatter into the presentation's pad rows and its + * deepstack taps join the hidden state early, exactly as the released clip's does. */ + VisionTower tv{}; + bool media = false; + rad_op op_mm = 0, op_ds[VisionTower::MAX_DS] = {}; + /* ---- context_embedder and the refiner, over the prompt's rows */ rad_weight w_ce = 0, b_ce = 0, w_fn = 0; rad_op op_ce = 0, op_fn = 0; @@ -398,7 +421,8 @@ struct Model { /* ---- the timestep MLP and the per-step tables */ rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_no = 0, b_no = 0; - rad_op op_temb = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_ts2 = 0, op_no = 0; + rad_op op_temb = 0, op_temb_pv = 0, op_temb_pa = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, + op_ts2 = 0, op_no = 0; QuantFP8 q_temb{}; rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0; ActFP8 a_temb{}; @@ -469,6 +493,73 @@ struct Model { rad_buf b_uin32 = 0, b_uin = 0, b_ua = 0, b_ub = 0, b_uc = 0, b_uout = 0, b_ust = 0; rad_buf b_ufac = 0, b_ue0 = 0, b_ue0s = 0, b_ue1 = 0, b_ue1s = 0, b_uemb = 0; std::vector u_in, u_out; + + /* ---- the video VAE encoder, when the container carries it. bf16 voxel activations, f32 + * weights (conv3d_ndhwc and group_norm read both), CausalConv3d everywhere: `causal` 1 and + * `reflect` 1 on every convolution, and `pad` `down` with `stride` 2 on the four + * downsamplers. Six levels of two residual blocks; the shortcut levels also convolve their + * 1x1x1 shortcut. The residual stream is `a`, `b` and `c` the block temporaries; `in` holds + * the downsampler's output where a shortcut follows it. */ + struct VEncBlock { + rad_weight n1w = 0, n1b = 0, c1w = 0, c1b = 0, n2w = 0, n2b = 0, c2w = 0, c2b = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0; + }; + struct VEncLevel { + int64_t cin = 0, cout = 0, rows = 0, pf = 0, frames = 0; /* pf: rows a frame */ + rad_buf in = 0, a = 0, b = 0, c = 0; + rad_weight scw = 0, scb = 0, dnw = 0, dnb = 0; + rad_op op_sc = 0, op_dn = 0; + VEncBlock blk[2]; + }; + std::vector v_lv; + bool venc = false; + rad_weight ve_cinw = 0, ve_cinb = 0, ve_now = 0, ve_nob = 0, ve_coutw = 0, ve_coutb = 0; + rad_weight ve_qw = 0, ve_qb = 0; + rad_op op_ve_pix = 0, op_ve_pcast = 0, op_ve_cin = 0, op_ve_nout = 0, op_ve_cout = 0; + rad_op op_ve_q = 0, op_ve_fold = 0; + std::string ve_pix_mul, ve_pix_add, ve_fold_mul, ve_fold_add; /* pixel and latent norms */ + rad_buf b_epix32 = 0, b_epix = 0, b_eq48 = 0, b_eq2 = 0, b_egn = 0; + rad_buf b_evc = 0; /* [kEncSlotsV * kEncSlotRowsV, kPatchVals] f32 PERSIST */ + + /* ---- the audio VAE encoder, when the container carries it. f32 like its decoder: per + * channel one sequence, conv_in and five strided blocks of three [snake, conv7, snake, + * conv1 +res] units. The strided downsampler and the attention pre-block run in a bf16 + * island (conv1d with a stride, layernorm and gemm pin every operand to one dtype); the + * chain resumes in f32 at mean_proj. Every convolution is weight-normalised except + * mean_proj. */ + struct AEncUnit { + rad_weight a1 = 0, c1w = 0, c1b = 0, a2 = 0, c2w = 0, c2b = 0; + rad_op op_a1 = 0, op_c1 = 0, op_a2 = 0, op_c2 = 0; + }; + struct AEncBlk { + AEncUnit u[3]; + rad_weight al = 0, dnw = 0, dnb = 0; /* the block's last snake, its downsampler */ + rad_op op_al = 0, op_dn = 0; + /* The bf16 island around the strided conv: the stream casts in, the downsample runs, + * the result casts back into the next block's stream. */ + rad_buf bi = 0, bo = 0; + rad_op op_ci = 0, op_co = 0; + }; + bool aenc = false; + AEncBlk ae_blk[5]; + rad_weight ae_cinw = 0, ae_cinb = 0, ae_al6 = 0, ae_finw = 0, ae_finb = 0; + rad_op op_ae_cin = 0, op_ae_snk6 = 0, op_ae_fin = 0; + /* The pre-block (CausalAttention over heads and a GeGlu MLP at 32 channels), bf16. */ + rad_weight p_ln1w = 0, p_ln1b = 0, p_qkvw = 0, p_qkvb = 0, p_apw = 0, p_apb = 0; + rad_weight p_ln3w = 0, p_ln3b = 0, p_prw = 0, p_prb = 0, p_ln2w = 0, p_ln2b = 0; + rad_weight p_mlw = 0, p_mlb = 0, p_guw = 0, p_gub = 0, p_w2w = 0, p_w2b = 0; + rad_op p_op_ln3 = 0, p_op_qkv = 0, p_op_attn = 0, p_op_pool = 0, p_op_aproj = 0; + rad_op p_op_ln1 = 0, p_op_proj = 0, p_op_hadd = 0, p_op_ln2 = 0, p_op_mln = 0; + rad_op p_op_gu = 0, p_op_act = 0, p_op_w2 = 0, p_op_xadd = 0; + rad_op p_op_hs = 0, p_op_hsd = 0; /* head-sum: six adds into the sum, the last by eight */ + rad_weight ae_mpw = 0, ae_mpb = 0; /* mean_proj, f32, not weight-normalised */ + rad_op op_ae_mp = 0, op_ae_norm = 0, op_ae_cast6 = 0, op_ae_castx = 0; + std::string ae_norm_mul, ae_norm_add; /* the latents' normalisation */ + rad_buf b_ax[6] = {}, b_et1[5] = {}, b_et2[5] = {}, b_a6t = 0, b_ax6 = 0; + rad_buf b_apb = 0, b_aln3 = 0, b_aqkv = 0, b_aatt = 0, b_ahsum = 0, b_apool = 0; + rad_buf b_eh = 0, b_a32a = 0, b_a32b = 0, b_a32c = 0, b_a32d = 0, b_agu = 0, b_agu64 = 0; + rad_buf b_ax2 = 0, b_amb = 0, b_amb2 = 0; + rad_buf b_enca = 0; /* [kEncSlotsA * kEncSlotRowsA, kAudioC] f32 PERSIST */ }; static Model g_model[MAX_RANKS]; @@ -631,6 +722,30 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_INT("vocab_offset", 0)), RAD_WEIGHTS(m.w_tok)), {}, { m.b_tx }); + if (m.media) { + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.tv.b_out, m.b_tx }, { m.b_tx }); + for (int t = 0; t < m.tv.n_ds; ++t) + m.op_ds[t] = rw(b, RAD_OP(b, "scatter_add_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.tv.b_ds[t], m.b_tx }, { m.b_tx }); + } + + /* A ref2va presentation carries vision pad rows, whose three M-RoPE components differ; with + * the tower in, every layer also gets the interleaved-M-RoPE form of its rotary. A text-only + * request keeps the NeoX declaration above: its three components are one position, which is + * the same rotation. Qwen3-VL's sections, the released LM's own numbers. */ + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); m.te.resize((size_t)g.n_layer); for (int64_t l = 0; l < g.n_layer; ++l) { @@ -667,6 +782,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_INT("rotary_dim", g.head_dim)), RAD_WEIGHTS(L.w_qn, L.w_kn)), { m.b_tkv }, { m.b_tkv }); + if (m.media) + L.op_qkr_m = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), + RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); L.op_attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), @@ -832,34 +959,61 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { "%d-column blocks\n", (long long)td, RAD_FP8_BLOCK); return RAD_E_INVAL; } - m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { 2 * S, fd }); - m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { 2 * S, hd1 }); - m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { 2 * S, hd1 }); - m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { 2 * S, td }); + /* The timestep MLP runs over FOUR blocks of S rows: the video schedule, the audio schedule, + * then each schedule re-embedded with the reference pin as a floor (clamp_min -- the reference + * conditioning's modulated rows carry `max(t, pin)`, which for a monotonic schedule is exactly + * the schedule at the early near-clean steps and the pin once it decays under it, so a clamped + * schedule row serves every step with no per-step branching). Blocks: [0,S) video, [S,2S) + * audio, [2S,3S) video-pinned (floor kVisualPin), [3S,4S) audio-pinned (floor kAudioPin). On a + * plain request the pinned two blocks are computed but never read, so the plain path is + * byte-identical -- just S*2 unused rows through the MLP. */ + const int64_t TT = 4 * S; + const double kVisualPin = 0.999, kAudioPin = 1.0; + m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { TT, fd }); + m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { TT, hd1 }); + m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { TT, hd1 }); + m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { TT, td }); m.op_temb = rw(b, RAD_OP(b, "timestep_embed", RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {}, { m.b_tproj }); + /* The two clamped schedule passes: the same op, the pin as `clamp_min`, into the pinned blocks. */ + m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kVisualPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kAudioPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); m.op_t1 = dense_bias(b, nm, "tmb.l1", "transformer.time_embedder.linear_1", RAD_F32, "f32", hd1, - fd, 2 * S, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); - m.op_ts = unary(b, "silu", 2 * S, hd1, "f32", m.b_te1, m.b_te1s); + fd, TT, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); + m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s); m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32", td, - hd1, 2 * S, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); + hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); /* silu(temb) in f32, rounded once to the bf16 the projections take. */ Geom gs = g; - gs.max_tok = 2 * S; - m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { 2 * S, td }); - m.op_ts2 = unary(b, "silu", 2 * S, td, "f32", m.b_temb, m.a_temb.x); - RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, 2 * S)); + gs.max_tok = TT; + m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td }); + m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x); + RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT)); RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td)); - if (!m.op_temb || !m.op_t1 || !m.op_ts || !m.op_t2 || !m.op_ts2) return RAD_E_INVAL; + if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2 + || !m.op_ts2) return RAD_E_INVAL; - /* The lane's tables. */ - m.b_ada = decl_b(b, nm.f("lane.ada"), RAD_BF16, { (int64_t)kMaxLanes * S, L * kSegs * m.Ws }, + /* The lane's tables: kMaxSegs segment columns so a reference-conditioned pack has a cell each; + * the plain three fill columns 0,1,2 byte-identically and leave the rest unread. */ + m.b_ada = decl_b(b, nm.f("lane.ada"), RAD_BF16, { (int64_t)kMaxLanes * S, L * kMaxSegs * m.Ws }, RAD_BUF_PERSIST); - m.b_nout = decl_b(b, nm.f("lane.nout"), RAD_BF16, { (int64_t)kMaxLanes * S, kSegs * 2 * D }, + m.b_nout = decl_b(b, nm.f("lane.nout"), RAD_BF16, { (int64_t)kMaxLanes * S, kMaxSegs * 2 * D }, RAD_BUF_PERSIST); const int64_t ada_rows = 6 * D; /* one modality's six vectors */ m.dit.resize((size_t)L); @@ -920,9 +1074,10 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_NOWEIGHTS), { m.b_astate }, { m.b_astate }); - /* ---- this step's modulation, every rank's share of it */ - const int64_t row = L * kSegs * m.Ws; - m.b_modg = decl_b(b, nm.f("dit.mod"), RAD_BF16, { (int64_t)g.world * L * kSegs, m.Ws }); + /* ---- this step's modulation, every rank's share of it. kMaxSegs columns so a reference pack's + * per-segment cells all fit; a plain step gathers its three and leaves the rest unread. */ + const int64_t row = L * kMaxSegs * m.Ws; + m.b_modg = decl_b(b, nm.f("dit.mod"), RAD_BF16, { (int64_t)g.world * L * kMaxSegs, m.Ws }); if (g.world > 1) m.op_modg = rw(b, RAD_OP(b, "all_gather", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -1812,6 +1967,700 @@ static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) { return RAD_OK; } +/* ================================================================== the VAE encoders */ +/* What a Vencode or Aencode pass stages into `enc_geom_d` (rad_builder.h's + * rad_arch_encode_geom; RadVideoGenBatch, rad_runtime.h). The layouts are the plugin's own and + * the driver copies them verbatim. Vencode, 25 int32s: the five volumes (the clip, and after + * each of the four downsamplers), the fold's geometry for a full and a short last clip, then + * the clip's frames, the clip count, the padded frame count and the latent count. Aencode, 13: + * the padded sample count, then the six sequence lengths as {0, n} pairs — a cu, read two at a + * time. Both encoders' steps re-derive these on the host from the batch's own fields. */ +const int kVEncGeomN = 25, kAEncGeomN = 13; + +static bool venc_geom(int64_t frames, int64_t h, int64_t w, int32_t* out) { + if (frames < 1 || frames > kEncMaxFrames || h < kVaeRatio || w < kVaeRatio || + h > kEncMaxSide || w > kEncMaxSide || h % kVaeRatio || w % kVaeRatio) + return false; + const int64_t clip = frames == 1 ? 1 : kVaeClipLength; + const int64_t n_clips = frames == 1 ? 1 : (frames + kVaeClipLength - 1) / kVaeClipLength; + const int64_t lat = vae_latent_frames(frames); + const int64_t full = vae_clip_latents(clip); + const int64_t last = lat - full * (n_clips - 1); + if (lat < 1 || full < 1 || last < 1 || last > full) return false; + if (!out) return true; /* the export's validation call, which wants only the answer */ + const int64_t t1 = (clip + 1) / 2, t2 = (t1 + 1) / 2; + const int64_t g[5][3] = { { clip, h, w }, { clip, h / 2, w / 2 }, { t1, h / 4, w / 4 }, + { t2, h / 8, w / 8 }, { t2, h / 16, w / 16 } }; + int32_t* o = out; + for (const auto& v : g) + for (int64_t x : v) *o++ = (int32_t)x; + const int64_t f[2][3] = { { full, h / (kVaeRatio * kPatch), w / (kVaeRatio * kPatch) }, + { last, h / (kVaeRatio * kPatch), w / (kVaeRatio * kPatch) } }; + for (const auto& v : f) + for (int64_t x : v) *o++ = (int32_t)x; + *o++ = (int32_t)clip; + *o++ = (int32_t)n_clips; + *o++ = (int32_t)(n_clips * clip); + *o++ = (int32_t)lat; + return o - out == kVEncGeomN; +} + +static bool aenc_geom(int64_t samples, int64_t ch, int32_t* out) { + if (samples < 1 || samples > kEncMaxSamples || ch < 1 || ch > kAudioCh) return false; + const int64_t n0 = (samples + kAudioHop - 1) / kAudioHop * kAudioHop; + if (n0 > kEncMaxSamples) return false; + if (!out) return true; /* the export's validation call */ + static const int64_t kStr[5] = { 2, 4, 4, 5, 5 }; + out[0] = (int32_t)n0; + int64_t n = n0; + for (int i = 0; i <= 5; ++i) { + out[1 + 2 * i] = 0; + out[2 + 2 * i] = (int32_t)n; + if (i < 5) n /= kStr[i]; + } + return true; +} + +/* The slot's first row in b_evc / b_enca. Every kind numbers its media from 1, so the buffers + * take the kinds in order: nine images, three videos, and the tail last; the videos' + * soundtracks then the standalone audios. */ +static int64_t venc_slot_row(int32_t kind, int32_t slot) { + int64_t idx = -1; + if (kind == RAD_ENC_IMAGE && slot >= 1 && slot <= 9) idx = slot - 1; + else if (kind == RAD_ENC_VIDEO && slot >= 1 && slot <= 3) idx = 9 + slot - 1; + else if (kind == RAD_ENC_TAIL && slot == 0) idx = kEncSlotsV - 1; + return idx < 0 ? -1 : idx * (int64_t)kEncSlotRowsV; +} +static int64_t aenc_slot_row(int32_t kind, int32_t slot) { + int64_t idx = -1; + if (kind == RAD_ENC_VAUDIO && slot >= 1 && slot <= 3) idx = slot - 1; + else if (kind == RAD_ENC_AUDIO && slot >= 1 && slot <= 3) idx = 3 + slot - 1; + return idx < 0 ? -1 : idx * (int64_t)kEncSlotRowsA; +} + +/* CausalConv3d encoder form: reflect-padded, causal in frames, bf16 rows. The 3x3x3 convs run on + * the implicit-GEMM kernel, which stores its weight bf16 tap-major (r4d_rad_layout_conv3d_tap); + * conv_in (cin 3) and the k=1 convs fall to the reference kernel, which reads f32 weights beside + * bf16 activations. */ +static rad_op venc_conv(RadBuilder* b, int64_t M, int64_t cin, int64_t cout, int64_t k, + rad_weight w, rad_weight bias, rad_buf x, rad_buf res, rad_buf y) { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, M), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("kt", k), + RAD_INT("causal", 1), RAD_INT("reflect", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return res ? rw(b, op, { x, res }, { y }) : rw(b, op, { x }, { y }); +} + +/* GroupNorm over a level's whole clip volume, SiLU'd, its statistics shared. The kernel is + * GroupNorm on [1, n, T, H, W] — one sample, the whole volume — which is the reference's call + * with the batch dimension one. norm_eps and the group count come from the VAE's config. */ +static rad_op venc_gn(RadBuilder* b, int64_t M, int64_t n, int64_t G, double eps, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y, rad_buf st) { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, M), RAD_INT("n", n), + RAD_INT("groups", G), RAD_F64("eps", eps), + RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return rw(b, op, { x, st }, { y, st }); +} + +/* The video VAE encoder (diffusers' AutoencoderKLMiniMaxH3 encoder over the ref2va fine-tune), + * declared when the container carries it. Pixels arrive un-normalised f32 0..255; the first op + * applies the reference's pixel normalisation ((x/255 - mean) / std), and everything past it is + * bf16 voxel rows. Six levels of two residual blocks, four strided downsamplers — the encoder's + * whole geometry per clip lives in `enc_geom_d`, so one declaration serves every media size. */ +static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + /* The presence gate first and before any shape is read, the vision tower's (rad_block_vit.h): + * map conv_in and ask for its encoding — the only presence test a convert and a load both + * answer the same way. */ + if (map_copy(b, nm.f("venc.cin.weight"), nm.ckpt("vae.encoder.conv_in.weight")) < 0) + return RAD_E_INVAL; + { + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("venc.cin.weight"), &enc, nullptr, nullptr) != RAD_OK) { + fprintf(stderr, "radiance: minimaxh3: the container ships no video VAE encoder; " + "declaring without it\n"); + return RAD_OK; + } + } + const std::vector dims = meta_list(meta, "vae.block_out_channels"); + const std::vector sds = meta_list(meta, "vae.spatial_downsample_factors"); + const std::vector tds = meta_list(meta, "vae.temporal_downsample_factors"); + const double eps = rad_meta_getf(meta, "vae.norm_eps", 1e-6); + const int64_t G = rad_meta_geti(meta, "vae.norm_num_groups", 32); + if (dims.size() != 6 || sds.size() != 6 || tds.size() != 6 || + rad_meta_geti(meta, "vae.layers_per_block", 2) != 2 || + rad_meta_geti(meta, "vae.clip_length", kVaeClipLength) != kVaeClipLength || + rad_meta_geti(meta, "vae.in_channels", 3) != 3 || + rad_meta_geti(meta, "vae.latent_channels", kC) != kC || + std::strcmp(rad_meta_gets(meta, "vae.spatial_padding_mode", "reflect"), "reflect") || + G < 1 || eps <= 0.0) { + fprintf(stderr, "radiance: minimaxh3: the video VAE is not the released encoder (six " + "levels of two blocks, 17-frame clips, reflect padding)\n"); + return RAD_E_UNSUPPORTED; + } + for (size_t i = 0; i < 6; ++i) + if ((int64_t)dims[i] % G || ((int64_t)sds[i] != 1 && (int64_t)sds[i] != 2) || + ((int64_t)tds[i] != 1 && (int64_t)tds[i] != 2)) + return RAD_E_UNSUPPORTED; + m.venc = true; + /* Per-request access, like the conditioning towers: an encode runs once a media, never a + * step, so the planner pins these weights to the host pool and their VRAM stays the KV + * cache's — the card has no room for them otherwise. */ + const int acc = RAD_ACCESS_PER_REQUEST; + const int gv = kGrpVenc; + auto wt = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_F32, shape, acc, gv); + }; + /* The 3x3x3 convs the implicit-GEMM kernel serves: it stores its operand 1 bf16 tap-major, + * so those weights are declared bf16 (the checkpoint's f32 casts at convert, like the + * upscaler's). k=1 convs and conv_in run on the reference kernel, which reads them as + * declared — those stay f32. */ + auto wb = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_BF16, shape, acc, gv); + }; + /* Only a host kernel reads these (conv_in's 3-channel conv, the k=1 convs): their own group + * so the device-read weights keep their VRAM placement. */ + auto wh = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_F32, shape, acc, kGrpVencH); + }; + + /* The clip's frames, rows and rows a frame at each level: a full 17-frame clip is the + * largest, and the buffers hold one clip at a time. */ + int64_t tf[6], sd[6] = { 1, 1, 1, 1, 1, 1 }, R[6], PF[6]; + tf[0] = kVaeClipLength; + for (int i = 1; i < 6; ++i) { + tf[i] = (tf[i - 1] + (int64_t)tds[i - 1] - 1) / (int64_t)tds[i - 1]; + sd[i] = sd[i - 1] * (int64_t)sds[i - 1]; + } + const int64_t HW = kEncMaxSide * kEncMaxSide; + for (int i = 0; i < 6; ++i) { + PF[i] = HW / (sd[i] * sd[i]); + R[i] = tf[i] * PF[i]; + } + const int64_t Rmax = R[0]; + + /* Pixels: f32 normalised, then bf16; the statistics every GroupNorm shares. */ + std::vector pm(3), pa(3); + for (int c = 0; c < 3; ++c) { + pm[(size_t)c] = 1.0 / (255.0 * kVaePixelStd[c]); + pa[(size_t)c] = -kVaePixelMean[c] / kVaePixelStd[c]; + } + m.ve_pix_mul = join_list(pm); + m.ve_pix_add = join_list(pa); + std::vector fm(kC), fa(kC); + for (int64_t c = 0; c < kC; ++c) { + fm[(size_t)c] = 1.0 / kVaeLatentsStd[c]; + fa[(size_t)c] = -kVaeLatentsMean[c] / kVaeLatentsStd[c]; + } + m.ve_fold_mul = join_list(fm); + m.ve_fold_add = join_list(fa); + m.b_epix32 = decl_b(b, nm.f("venc.pix32"), RAD_F32, { Rmax, 3 }); + m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 }); + m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) }); + const rad_buf st = m.b_egn; + m.op_ve_pix = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), + RAD_STR("mul", m.ve_pix_mul.c_str()), + RAD_STR("add", m.ve_pix_add.c_str()), + RAD_STR("mode", "fma"), RAD_INT("round", 0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_epix32 }); + m.op_ve_pcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_epix32 }, { m.b_epix }); + /* The gate registered this name's map above; declaring the copy again would be refused. */ + m.ve_cinw = decl_w(b, nm.f("venc.cin.weight"), RAD_F32, { (int64_t)dims[0], 3, 3, 3, 3 }, + acc, RAD_SHARD_NONE, grp_layer(kGrpVencH)); + m.ve_cinb = wh(nm.f("venc.cin.bias"), nm.ckpt("vae.encoder.conv_in.bias"), { (int64_t)dims[0] }); + if (!m.op_ve_pix || !m.op_ve_pcast) return RAD_E_INVAL; + m.v_lv.reserve(6); + for (int L = 0; L < 6; ++L) { + m.v_lv.emplace_back(); + Model::VEncLevel& E = m.v_lv.back(); + const int64_t cout = (int64_t)dims[L], cin = L == 0 ? cout : (int64_t)dims[L - 1]; + const bool sc = L > 0 && cout != cin; + E.cin = cin, E.cout = cout, E.rows = R[L], E.pf = PF[L], E.frames = tf[L]; + E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout }); + E.b = decl_b(b, nm.f("venc.l%d.b", L), RAD_BF16, { R[L], cout }); + E.c = decl_b(b, nm.f("venc.l%d.c", L), RAD_BF16, { R[L], cout }); + /* A shortcut level reads its input through norm1 first, so the input has to sit in a + * buffer of its own width. The downsampler above writes it; the last level has no + * downsampler under it — the level before ends in its own stream, so its `in` aliases + * that stream instead of being a buffer nothing writes. */ + if (sc) { + const bool dn_in = (int64_t)sds[L - 1] == 2 || (int64_t)tds[L - 1] == 2; + E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin }) + : m.v_lv[(size_t)L - 1].a; + E.scw = wh(nm.f("venc.l%d.sc.weight", L), nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut.weight", L), + { cout, cin, 1, 1, 1 }); + E.scb = wh(nm.f("venc.l%d.sc.bias", L), nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut.bias", L), + { cout }); + if (!E.scw || !E.scb) return RAD_E_INVAL; + E.op_sc = rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, R[L]), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 1), + RAD_INT("kt", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.scw, E.scb)), + { E.in }, { E.a }); + if (!E.op_sc) return RAD_E_INVAL; + } + for (int blk = 0; blk < 2; ++blk) { + Model::VEncBlock& B = E.blk[blk]; + const char* bs = nm.ckpt("vae.encoder.down_blocks.%d.resnets.%d", L, blk); + /* norm1 is at the block's input width — the level's, on a shortcut's first block, + * where the raw input in `in` is normalized in place and the shortcut convolves the + * result. */ + const int64_t w1 = blk == 0 && sc ? cin : cout; + const rad_buf xa = blk == 0 && sc ? E.in : E.a; + const rad_buf nb = blk == 0 && sc ? E.in : E.b; + B.n1w = wt(nm.f("venc.l%d.b%d.n1w", L, blk), nm.ckpt("%s.norm1.weight", bs), { w1 }); + B.n1b = wt(nm.f("venc.l%d.b%d.n1b", L, blk), nm.ckpt("%s.norm1.bias", bs), { w1 }); + B.c1w = wb(nm.f("venc.l%d.b%d.c1w", L, blk), nm.ckpt("%s.conv1.weight", bs), { cout, w1, 3, 3, 3 }); + B.c1b = wt(nm.f("venc.l%d.b%d.c1b", L, blk), nm.ckpt("%s.conv1.bias", bs), { cout }); + B.n2w = wt(nm.f("venc.l%d.b%d.n2w", L, blk), nm.ckpt("%s.norm2.weight", bs), { cout }); + B.n2b = wt(nm.f("venc.l%d.b%d.n2b", L, blk), nm.ckpt("%s.norm2.bias", bs), { cout }); + B.c2w = wb(nm.f("venc.l%d.b%d.c2w", L, blk), nm.ckpt("%s.conv2.weight", bs), { cout, cout, 3, 3, 3 }); + B.c2b = wt(nm.f("venc.l%d.b%d.c2b", L, blk), nm.ckpt("%s.conv2.bias", bs), { cout }); + if (!B.n1w || !B.n1b || !B.c1w || !B.c1b || !B.n2w || !B.n2b || !B.c2w || !B.c2b) + return RAD_E_INVAL; + B.op_n1 = venc_gn(b, R[L], w1, G, eps, B.n1w, B.n1b, xa, nb, st); + B.op_c1 = venc_conv(b, R[L], w1, cout, 3, B.c1w, B.c1b, nb, 0, E.c); + B.op_n2 = venc_gn(b, R[L], cout, G, eps, B.n2w, B.n2b, E.c, E.b, st); + B.op_c2 = venc_conv(b, R[L], cout, cout, 3, B.c2w, B.c2b, E.b, E.a, E.a); + if (!B.op_n1 || !B.op_c1 || !B.op_n2 || !B.op_c2) return RAD_E_INVAL; + } + } + /* conv_in, now that level 0 exists to hold its output. */ + m.op_ve_cin = venc_conv(b, Rmax, 3, (int64_t)dims[0], 3, m.ve_cinw, m.ve_cinb, m.b_epix, 0, + m.v_lv[0].a); + if (!m.op_ve_cin) return RAD_E_INVAL; + + /* The downsamplers — the four levels whose config halves the side (the last two levels are + * 16x and change nothing between them) — declared once each level exists to hold their + * output: `pad` `down`, spatial stride (and temporal stride 2 where the config says so), + * causal — the reference's Downsample3D. */ + for (int L = 0; L < 4; ++L) { + Model::VEncLevel& E = m.v_lv[(size_t)L]; + Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const char* bs = nm.ckpt("vae.encoder.down_blocks.%d.downsamplers.0.conv", L); + E.dnw = wb(nm.f("venc.l%d.dnw", L), nm.ckpt("%s.weight", bs), { E.cout, E.cout, 3, 3, 3 }); + E.dnb = wt(nm.f("venc.l%d.dnb", L), nm.ckpt("%s.bias", bs), { E.cout }); + if (!E.dnw || !E.dnb) return RAD_E_INVAL; + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, E.rows), RAD_INT("cin", E.cout), + RAD_INT("cout", E.cout), RAD_INT("k", 3), + RAD_INT("kt", 3), RAD_INT("stride", (int64_t)sds[L]), + RAD_INT("stride_t", (int64_t)tds[L]), + RAD_INT("causal", 1), RAD_STR("pad", "down"), + RAD_INT("reflect", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.dnw, E.dnb)); + rad_buf y = X.op_sc ? X.in : X.a; + E.op_dn = rw(b, op, { E.a }, { y }); + if (!E.op_dn) return RAD_E_INVAL; + } + + /* norm_out, conv_out and quant_conv over the last level, then the fold: the first 24 + * columns of the 48, normalised into patch rows of 96. */ + m.ve_now = wt(nm.f("venc.nout.weight"), nm.ckpt("vae.encoder.norm_out.weight"), + { (int64_t)dims[5] }); + m.ve_nob = wt(nm.f("venc.nout.bias"), nm.ckpt("vae.encoder.norm_out.bias"), { (int64_t)dims[5] }); + m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 }); + m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 }); + m.op_ve_nout = venc_gn(b, R[5], (int64_t)dims[5], G, eps, m.ve_now, m.ve_nob, m.v_lv[5].a, + m.v_lv[5].b, st); + m.ve_coutw = wb(nm.f("venc.cout.weight"), nm.ckpt("vae.encoder.conv_out.weight"), + { 48, (int64_t)dims[5], 3, 3, 3 }); + m.ve_coutb = wt(nm.f("venc.cout.bias"), nm.ckpt("vae.encoder.conv_out.bias"), { 48 }); + m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 }); + m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 }); + m.op_ve_cout = venc_conv(b, R[5], (int64_t)dims[5], 48, 3, m.ve_coutw, m.ve_coutb, + m.v_lv[5].b, 0, m.b_eq48); + m.op_ve_q = rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("cin", 48), + RAD_INT("cout", 48), RAD_INT("k", 1), RAD_INT("kt", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.ve_qw, m.ve_qb)), + { m.b_eq48 }, { m.b_eq2 }); + m.b_evc = decl_b(b, nm.f("lane.evc"), RAD_F32, + { (int64_t)kEncSlotsV * kEncSlotRowsV, kPatchVals }, RAD_BUF_PERSIST); + m.op_ve_fold = rw(b, RAD_OP(b, "patch_fold", + RAD_PARAMS(RAD_RANGE("M", 1, kEncSlotRowsV), RAD_INT("C", kC), + RAD_INT("pt", 1), RAD_INT("ph", kPatch), + RAD_INT("pw", kPatch), + RAD_STR("mul", m.ve_fold_mul.c_str()), + RAD_STR("add", m.ve_fold_add.c_str()), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_eq2 }, { m.b_evc }); + if (!m.op_ve_nout || !m.op_ve_cout || !m.op_ve_q || !m.op_ve_fold) return RAD_E_INVAL; + return RAD_OK; +} + +/* The audio VAE encoder (ComfyUI's `audio_vae.py` Encoder + AttnProjection, the ref2va + * fine-tune), declared when the container carries it. f32 like its decoder: every conv is + * weight-normalised (folded at convert) and every sequence is one channel at a time — a mono + * `cu` read from the staged geometry. The strided downsamplers and the attention pre-block run + * in bf16: conv1d's strided form, layernorm and gemm pin every operand to one dtype, so the + * recipe casts those weights; the f32 chain converts as stored. */ +static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + if (map_copy(b, nm.f("aenc.mp.weight"), nm.ckpt("audio_vae.mean_proj.weight")) < 0) + return RAD_E_INVAL; + { + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("aenc.mp.weight"), &enc, nullptr, nullptr) != RAD_OK) { + fprintf(stderr, "radiance: minimaxh3: the container ships no audio VAE encoder; " + "declaring without it\n"); + return RAD_OK; + } + } + const std::vector rates = meta_list(meta, "audio_vae.encoder_rates"); + const int64_t ld = rad_meta_geti(meta, "audio_vae.latent_dim", 2048); + const std::vector mean = meta_list(meta, "audio_vae.latents_mean"); + const std::vector sd = meta_list(meta, "audio_vae.latents_std"); + const int64_t heads = rad_meta_geti(meta, "audio_vae.num_attention_heads", 8); + if (rates.size() != 5 || ld != 2048 || (int64_t)mean.size() != kAudioC || + (int64_t)sd.size() != kAudioC || heads != 8 || + rad_meta_geti(meta, "audio_vae.encoder_dim", 64) != 64 || + rad_meta_geti(meta, "audio_vae.latent_channels", kAudioC) != kAudioC) { + fprintf(stderr, "radiance: minimaxh3: the audio VAE is not the released encoder (five " + "strides to 800 samples a latent, eight attention heads)\n"); + return RAD_E_UNSUPPORTED; + } + m.aenc = true; + /* Per-request access for the same reason as the video encoder's: an audio encode runs once a + * clip, never a step, so these weights live in the host pool with the conditioning towers and + * the card's last GiB stays the KV cache's. */ + const int acc = RAD_ACCESS_PER_REQUEST; + const int ga = kGrpAenc; + /* The snake alphas: `snake` is a device kernel only in bf16, and the audio encoder's chain + * is f32 — a host kernel reads them, so they get their own group (see kGrpVencH). */ + const int gh = kGrpAencH; + static const int64_t kStr[5] = { 2, 4, 4, 5, 5 }; + for (int i = 0; i < 5; ++i) + if ((int64_t)rates[(size_t)i] != kStr[i]) return RAD_E_UNSUPPORTED; + int64_t nn[6], uu[5]; + nn[0] = kEncMaxSamples; + for (int i = 0; i < 5; ++i) nn[i + 1] = nn[i] / kStr[i]; + for (int i = 0; i < 5; ++i) uu[i] = 64 << i; + const int64_t hd = ld / 8; /* the attention's head width */ + + /* The latents' normalisation, folded into the last op of the chain. */ + std::vector nm_(kAudioC), na(kAudioC); + for (int64_t c = 0; c < kAudioC; ++c) { + nm_[(size_t)c] = 1.0 / sd[(size_t)c]; + na[(size_t)c] = -mean[(size_t)c] / sd[(size_t)c]; + } + m.ae_norm_mul = join_list(nm_); + m.ae_norm_add = join_list(na); + + /* conv_in: 1 sample a row in, the first stream out. */ + const char* bs = nm.ckpt("audio_vae.encoder.block.0"); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.cin.weight"), nm.ckpt("%s.weight_g", bs), + nm.ckpt("%s.weight_v", bs))); + m.ae_cinw = decl_w(b, nm.f("aenc.cin.weight"), RAD_F32, { 64, 1, 7 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + m.ae_cinb = wcopy(b, nm.f("aenc.cin.bias"), nm.ckpt("%s.bias", bs), RAD_F32, { 64 }, acc, ga); + m.b_ax[0] = decl_b(b, nm.f("aenc.x0"), RAD_F32, { nn[0], 64 }); + if (!m.ae_cinw || !m.ae_cinb || !m.b_ax[0]) return RAD_E_INVAL; + m.op_ae_cin = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, nn[0]), RAD_INT("cin", 1), + RAD_INT("cout", 64), RAD_INT("k", 7), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_cinw, m.ae_cinb)), + {}, { m.b_ax[0] }); + if (!m.op_ae_cin) return RAD_E_INVAL; + + for (int blk = 0; blk < 5; ++blk) { + Model::AEncBlk& A = m.ae_blk[blk]; + const int64_t u = uu[blk], d = u * 2, np = nn[blk], no = nn[blk + 1]; + const int64_t s = kStr[blk]; + m.b_et1[blk] = decl_b(b, nm.f("aenc.t1_%d", blk), RAD_F32, { np, u }); + m.b_et2[blk] = decl_b(b, nm.f("aenc.t2_%d", blk), RAD_F32, { np, u }); + m.b_ax[blk + 1] = decl_b(b, nm.f("aenc.x%d", blk + 1), RAD_F32, { no, d }); + A.bi = decl_b(b, nm.f("aenc.bf1_%d", blk), RAD_BF16, { np, u }); + A.bo = decl_b(b, nm.f("aenc.bf2_%d", blk), RAD_BF16, { no, d }); + if (!m.b_et1[blk] || !m.b_et2[blk] || !m.b_ax[blk + 1] || !A.bi || !A.bo) + return RAD_E_INVAL; + const int64_t R = np; + /* Three units: snake, conv7, snake, conv1 with the residual over the stream. */ + for (int r = 0; r < 3; ++r) { + Model::AEncUnit& U = A.u[r]; + const char* us = nm.ckpt("audio_vae.encoder.block.%d.block.%d.block", blk + 1, r); + U.a1 = wcopy(b, nm.f("aenc.b%d.u%d.a1", blk, r), nm.ckpt("%s.0.alpha", us), RAD_F32, + { u }, acc, gh); + if (!U.a1) return RAD_E_INVAL; + U.op_a1 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.a1)), + { m.b_ax[blk] }, { m.b_et1[blk] }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.b%d.u%d.c1.weight", blk, r), + nm.ckpt("%s.1.weight_g", us), nm.ckpt("%s.1.weight_v", us))); + U.c1w = decl_w(b, nm.f("aenc.b%d.u%d.c1.weight", blk, r), RAD_F32, { u, u, 7 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + U.c1b = wcopy(b, nm.f("aenc.b%d.u%d.c1.bias", blk, r), nm.ckpt("%s.1.bias", us), + RAD_F32, { u }, acc, ga); + if (!U.c1w || !U.c1b) return RAD_E_INVAL; + U.op_c1 = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", u), RAD_INT("k", 7), + RAD_INT("dil", 2 * r + 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.c1w, U.c1b)), + { m.b_et1[blk] }, { m.b_et2[blk] }); + U.a2 = wcopy(b, nm.f("aenc.b%d.u%d.a2", blk, r), nm.ckpt("%s.2.alpha", us), RAD_F32, + { u }, acc, gh); + if (!U.a2) return RAD_E_INVAL; + U.op_a2 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.a2)), + { m.b_et2[blk] }, { m.b_et1[blk] }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.b%d.u%d.c2.weight", blk, r), + nm.ckpt("%s.3.weight_g", us), nm.ckpt("%s.3.weight_v", us))); + U.c2w = decl_w(b, nm.f("aenc.b%d.u%d.c2.weight", blk, r), RAD_F32, { u, u, 1 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + U.c2b = wcopy(b, nm.f("aenc.b%d.u%d.c2.bias", blk, r), nm.ckpt("%s.3.bias", us), + RAD_F32, { u }, acc, ga); + if (!U.c2w || !U.c2b) return RAD_E_INVAL; + U.op_c2 = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", u), RAD_INT("k", 1), + RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.c2w, U.c2b)), + { m.b_et1[blk], m.b_ax[blk] }, { m.b_ax[blk] }); + if (!U.op_a1 || !U.op_c1 || !U.op_a2 || !U.op_c2) return RAD_E_INVAL; + } + /* The block's last snake, then the bf16 island's strided downsample. */ + const char* ds = nm.ckpt("audio_vae.encoder.block.%d.block", blk + 1); + A.al = wcopy(b, nm.f("aenc.b%d.al", blk), nm.ckpt("%s.3.alpha", ds), RAD_F32, { u }, acc, + gh); + if (!A.al) return RAD_E_INVAL; + A.op_al = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(A.al)), + { m.b_ax[blk] }, { m.b_et1[blk] }); + A.op_ci = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_et1[blk] }, { A.bi }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.d%d.w", blk), nm.ckpt("%s.4.weight_g", ds), + nm.ckpt("%s.4.weight_v", ds))); + A.dnw = decl_w(b, nm.f("aenc.d%d.w", blk), RAD_BF16, { d, u, 2 * s }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + RAD_ARCH_TRY(map_copy(b, nm.f("aenc.d%d.b", blk), nm.ckpt("%s.4.bias", ds))); + A.dnb = decl_w(b, nm.f("aenc.d%d.b", blk), RAD_BF16, { d }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + if (!A.dnw || !A.dnb) return RAD_E_INVAL; + A.op_dn = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", d), RAD_INT("k", 2 * s), + RAD_INT("dil", 1), RAD_INT("stride", s), + RAD_INT("pad", (s + 1) / 2), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(A.dnw, A.dnb)), + { A.bi }, { A.bo }); + A.op_co = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, no), RAD_INT("n", d), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { A.bo }, { m.b_ax[blk + 1] }); + if (!A.op_al || !A.op_ci || !A.op_dn || !A.op_co) return RAD_E_INVAL; + } + + /* The final snake and 3x3 conv, then the pre-block. */ + const int64_t T = nn[5]; + const char* f6 = nm.ckpt("audio_vae.encoder.block.6"); + const char* f7 = nm.ckpt("audio_vae.encoder.block.7"); + m.ae_al6 = wcopy(b, nm.f("aenc.al6"), nm.ckpt("%s.alpha", f6), RAD_F32, { ld }, acc, gh); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.fin.weight"), nm.ckpt("%s.weight_g", f7), + nm.ckpt("%s.weight_v", f7))); + m.ae_finw = decl_w(b, nm.f("aenc.fin.weight"), RAD_F32, { ld, ld, 3 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + m.ae_finb = wcopy(b, nm.f("aenc.fin.bias"), nm.ckpt("%s.bias", f7), RAD_F32, { ld }, acc, ga); + m.b_a6t = decl_b(b, nm.f("aenc.snk6"), RAD_F32, { T, ld }); + m.b_ax6 = decl_b(b, nm.f("aenc.x6"), RAD_F32, { T, ld }); + if (!m.ae_al6 || !m.ae_finw || !m.ae_finb || !m.b_a6t || !m.b_ax6) return RAD_E_INVAL; + m.op_ae_snk6 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", ld), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_al6)), + { m.b_ax[5] }, { m.b_a6t }); + m.op_ae_fin = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", ld), + RAD_INT("cout", ld), RAD_INT("k", 3), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_finw, m.ae_finb)), + { m.b_a6t }, { m.b_ax6 }); + if (!m.op_ae_snk6 || !m.op_ae_fin) return RAD_E_INVAL; + + /* The pre-block, bf16: two LayerNorms over the 2048-wide stream, qkv with the packed bias + * the checkpoint splits into q, a zeroed k and v; eight single-head causal attentions whose + * mean pools to 32 and the attention's projection; then the gated MLP. */ + const char* pb = nm.ckpt("audio_vae.pre_block"); + auto pw_ = [&](const char* dn, const char* src, uint32_t dt, + std::initializer_list shape) { + return wcopy(b, nm.f("aenc.pb.%s", dn), nm.ckpt("%s.%s", pb, src), dt, shape, acc, ga); + }; + m.p_ln1w = pw_("ln1w", "norm1.weight", RAD_BF16, { ld }); + m.p_ln1b = pw_("ln1b", "norm1.bias", RAD_BF16, { ld }); + m.p_ln3w = pw_("ln3w", "norm3.weight", RAD_BF16, { ld }); + m.p_ln3b = pw_("ln3b", "norm3.bias", RAD_BF16, { ld }); + m.p_ln2w = pw_("ln2w", "norm2.weight", RAD_BF16, { kAudioC }); + m.p_ln2b = pw_("ln2b", "norm2.bias", RAD_BF16, { kAudioC }); + m.p_mlw = pw_("mlnw", "mlp.norm.weight", RAD_BF16, { kAudioC }); + m.p_mlb = pw_("mlnb", "mlp.norm.bias", RAD_BF16, { kAudioC }); + m.p_prw = pw_("prw", "proj.weight", RAD_BF16, { kAudioC, ld }); + m.p_prb = pw_("prb", "proj.bias", RAD_BF16, { kAudioC }); + m.p_apw = pw_("apw", "attn.proj.weight", RAD_BF16, { kAudioC, kAudioC }); + m.p_apb = pw_("apb", "attn.proj.bias", RAD_BF16, { kAudioC }); + m.p_w2w = pw_("w2w", "mlp.w2.weight", RAD_BF16, { kAudioC, 2 * kAudioC }); + m.p_w2b = pw_("w2b", "mlp.w2.bias", RAD_BF16, { kAudioC }); + if (!m.p_ln1w || !m.p_ln1b || !m.p_ln3w || !m.p_ln3b || !m.p_ln2w || !m.p_ln2b || + !m.p_mlw || !m.p_mlb || !m.p_prw || !m.p_prb || !m.p_apw || !m.p_apb || !m.p_w2w || + !m.p_w2b) + return RAD_E_INVAL; + RAD_ARCH_TRY(map_copy(b, nm.f("aenc.pb.qkvw"), nm.ckpt("%s.attn.qkv.weight", pb))); + m.p_qkvw = decl_w(b, nm.f("aenc.pb.qkvw"), RAD_BF16, { 3 * ld, ld }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.qkvb"), + { nm.ckpt("%s.attn.q_bias", pb), nm.ckpt("%s.attn.zero_k_bias", pb), + nm.ckpt("%s.attn.v_bias", pb) })); + m.p_qkvb = decl_w(b, nm.f("aenc.pb.qkvb"), RAD_BF16, { 3 * ld }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + /* gate and up stacked: w0 (the gate) first, then w1 — gelu_mul's split. */ + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.guw"), + { nm.ckpt("%s.mlp.w0.weight", pb), nm.ckpt("%s.mlp.w1.weight", pb) })); + m.p_guw = decl_w(b, nm.f("aenc.pb.guw"), RAD_BF16, { 2 * kAudioC * 2, kAudioC }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.gub"), + { nm.ckpt("%s.mlp.w0.bias", pb), nm.ckpt("%s.mlp.w1.bias", pb) })); + m.p_gub = decl_w(b, nm.f("aenc.pb.gub"), RAD_BF16, { 2 * kAudioC * 2 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + if (!m.p_qkvw || !m.p_qkvb || !m.p_guw || !m.p_gub) return RAD_E_INVAL; + + m.b_apb = decl_b(b, nm.f("aenc.pb"), RAD_BF16, { T, ld }); + m.b_aln3 = decl_b(b, nm.f("aenc.ln3"), RAD_BF16, { T, ld }); + m.b_aqkv = decl_b(b, nm.f("aenc.qkv"), RAD_BF16, { T, 3 * ld }); + m.b_aatt = decl_b(b, nm.f("aenc.att"), RAD_BF16, { T, hd }); + m.b_ahsum = decl_b(b, nm.f("aenc.hsum"), RAD_BF16, { T, hd }); + m.b_apool = decl_b(b, nm.f("aenc.pool"), RAD_BF16, { T, kAudioC }); + m.b_eh = decl_b(b, nm.f("aenc.h"), RAD_BF16, { T, kAudioC }); + m.b_a32a = decl_b(b, nm.f("aenc.r32a"), RAD_BF16, { T, kAudioC }); + m.b_a32b = decl_b(b, nm.f("aenc.r32b"), RAD_BF16, { T, kAudioC }); + m.b_a32c = decl_b(b, nm.f("aenc.r32c"), RAD_BF16, { T, kAudioC }); + m.b_a32d = decl_b(b, nm.f("aenc.r32d"), RAD_BF16, { T, kAudioC }); + m.b_agu = decl_b(b, nm.f("aenc.gu"), RAD_BF16, { T, 4 * kAudioC }); + m.b_agu64 = decl_b(b, nm.f("aenc.gu64"), RAD_BF16, { T, 2 * kAudioC }); + m.b_ax2 = decl_b(b, nm.f("aenc.xfin"), RAD_BF16, { T, kAudioC }); + m.b_amb = decl_b(b, nm.f("aenc.mono"), RAD_F32, { T, kAudioC }); + m.b_amb2 = decl_b(b, nm.f("aenc.mp"), RAD_F32, { T, kAudioC }); + m.op_ae_cast6 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", ld), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_ax6 }, { m.b_apb }); + if (!m.op_ae_cast6) return RAD_E_INVAL; + auto ln = [&](rad_weight w, rad_weight b2, int64_t n, rad_buf x, rad_buf y) -> rad_op { + if (!w || !b2) return 0; + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, b2)), + { x }, { y }); + }; + auto gemm = [&](rad_weight w, rad_weight b2, int64_t N, int64_t K, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !b2) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, b2)), + { x }, { y }); + }; + m.p_op_ln3 = ln(m.p_ln3w, m.p_ln3b, ld, m.b_apb, m.b_aln3); + m.p_op_qkv = gemm(m.p_qkvw, m.p_qkvb, 3 * ld, ld, m.b_aln3, m.b_aqkv); + m.p_op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_aqkv }, { m.b_aatt }); + 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")), + RAD_NOWEIGHTS), + { m.b_ahsum }, { m.b_apool }); + m.p_op_aproj = gemm(m.p_apw, m.p_apb, kAudioC, kAudioC, m.b_apool, m.b_a32a); + m.p_op_ln1 = ln(m.p_ln1w, m.p_ln1b, ld, m.b_apb, m.b_aln3); + m.p_op_proj = gemm(m.p_prw, m.p_prb, kAudioC, ld, m.b_aln3, m.b_eh); + m.p_op_hadd = add_op(b, T, kAudioC, "bf16", m.b_eh, m.b_a32a, m.b_a32b); + m.p_op_ln2 = ln(m.p_ln2w, m.p_ln2b, kAudioC, m.b_a32b, m.b_a32c); + m.p_op_mln = ln(m.p_mlw, m.p_mlb, kAudioC, m.b_a32c, m.b_a32d); + m.p_op_gu = gemm(m.p_guw, m.p_gub, 4 * kAudioC, kAudioC, m.b_a32d, m.b_agu); + m.p_op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 2 * kAudioC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_agu }, { m.b_agu64 }); + m.p_op_w2 = gemm(m.p_w2w, m.p_w2b, kAudioC, 2 * kAudioC, m.b_agu64, m.b_a32c); + m.p_op_xadd = add_op(b, T, kAudioC, "bf16", m.b_a32b, m.b_a32c, m.b_ax2); + /* The heads' mean: each attention writes b_aatt, six adds fold it into b_ahsum and the + * seventh divides the sum by eight. */ + m.p_op_hs = add_op(b, T, hd, "bf16", m.b_ahsum, m.b_aatt, m.b_ahsum); + m.p_op_hsd = add_div_op(b, T, hd, "bf16", m.b_ahsum, m.b_aatt, m.b_ahsum, 8.0); + if (!m.p_op_ln3 || !m.p_op_qkv || !m.p_op_attn || !m.p_op_pool || !m.p_op_aproj || + !m.p_op_ln1 || !m.p_op_proj || !m.p_op_hadd || !m.p_op_ln2 || !m.p_op_mln || !m.p_op_gu || + !m.p_op_act || !m.p_op_w2 || !m.p_op_xadd || !m.p_op_hs || !m.p_op_hsd) + return RAD_E_INVAL; + m.op_ae_castx = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kAudioC), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_ax2 }, { m.b_amb }); + if (!m.op_ae_castx) return RAD_E_INVAL; + /* mean_proj was mapped by the presence gate; declared through that map, not mapped again. */ + m.ae_mpw = decl_w(b, nm.f("aenc.mp.weight"), RAD_F32, { kAudioC, kAudioC, 1 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + m.ae_mpb = wcopy(b, nm.f("aenc.mp.bias"), nm.ckpt("audio_vae.mean_proj.bias"), RAD_F32, + { kAudioC }, acc, ga); + if (!m.ae_mpw || !m.ae_mpb) return RAD_E_INVAL; + m.op_ae_mp = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", kAudioC), + RAD_INT("cout", kAudioC), RAD_INT("k", 1), + RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_mpw, m.ae_mpb)), + { m.b_amb }, { m.b_amb2 }); + m.b_enca = decl_b(b, nm.f("lane.enca"), RAD_F32, + { (int64_t)kEncSlotsA * kEncSlotRowsA, kAudioC }, RAD_BUF_PERSIST); + m.op_ae_norm = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kAudioC), + RAD_STR("mul", m.ae_norm_mul.c_str()), + RAD_STR("add", m.ae_norm_add.c_str()), + RAD_STR("mode", "fma"), RAD_INT("round", 0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_amb2 }, { m.b_enca }); + if (!m.op_ae_mp || !m.op_ae_norm || !m.b_enca) return RAD_E_INVAL; + return RAD_OK; +} + /* ================================================================== declare */ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx) return RAD_E_INVAL; @@ -1921,6 +2770,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_E_INVAL; } + /* The ref2va tower is served exactly when the source carries its weights. Every MiniMax-H3 + * config names a vision_config -- the base and heretic descendants kept the conditioning + * fine-tuner's -- so presence is a weight question, and VisionTower answers it itself: its + * gate maps the stem and looks for it before declaring anything (the weight's encoding + * resolves through the map, which rad-convert answers from the checkpoint and the loader + * answers from the container, so the convert that writes `model.visual.*` and the load that + * reads them declare the same graph). `on` states what survived the gate. */ + m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0; + if (m.media) { + if (m.tv.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpTower, true, true) != RAD_OK) + return RAD_E_UNSUPPORTED; + m.media = m.tv.on; + } + /* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */ m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D }, RAD_BUF_PERSIST); @@ -1936,6 +2799,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(declare_ups(b, meta, m)); RAD_ARCH_TRY(declare_audio(b, meta, m)); RAD_ARCH_TRY(declare_video(b, meta, m)); + RAD_ARCH_TRY(declare_venc(b, meta, m)); + RAD_ARCH_TRY(declare_aenc(b, meta, m)); if (!ctx->shape_probe) { RadVideoGenDecl d{}; @@ -1988,6 +2853,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.upscale_max = m.ups_max; d.upscale_refine = m.rungs.empty() ? kUpsRefineBase : kUpsRefineDistilled; } + /* A container that carries the vision tower serves reference media: the released + * ref2va's ceilings. Without the tower the zeros make the server refuse the task. */ + if (m.media) { + d.max_ref_images = 9; + d.max_ref_videos = 3; + d.max_ref_audios = 3; + } + /* A container that carries either VAE encoder serves the encode passes; which of the + * two, and every size limit, the driver reads back from rad_arch_encode_geom. The three + * ceilings here are the ones rad_arch_encode_geom refuses past (kEncMax*), so the driver + * sizes its one-item staging slab to hold any media the export accepts. */ + if (m.venc || m.aenc) { + d.encodes = 1; + d.max_enc_frames = kEncMaxFrames; + d.max_enc_side = kEncMaxSide; + d.max_enc_samples = kEncMaxSamples; + d.enc_ratio = kVaeRatio; /* the side the server snaps reference media to a multiple of */ + /* Conditioning is live: `kRefConsume` is 1, so step_dit scatters the encoded reference + * latents (b_evc / b_enca) into the packed sequence and reads the widened table, and the + * driver widens the step's rows and segment boundaries and stages the pack's own RoPE + * (rad_arch_video_pack) for every reference row. Rows, boundaries, positions and + * consumption all move together behind this one constant; a request with no reference + * table stays on the byte-identical plain path (step_dit's refc gate is `V->ref_tab`). */ + d.ref_rows = kRefConsume; + /* The denoiser's modulation table is one cell per pack segment, `kMaxSegs` columns; a + * pack that lays out more aborts the step. The driver builds the pack itself, so it + * reads this cap and refuses 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; + } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -2005,6 +2900,71 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ================================================================== step */ +/* The request's packed sequence rebuilt in-arch from its reference table -- the same layout the + * driver's rad_arch_video_pack staged -- so the step scatters reference latents into exactly the + * rows the staged boundaries describe, and the two target streams land last. A null table (or a + * request with no VAE media) gives the plain three segments. */ +static minimaxh3::Ref2VAPack ref_pack_of(const RadVideoGeom* g, const int32_t* ref_tab) { + using namespace minimaxh3; + const Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, (int)g->n_audio }; + std::vector refs; + std::vector keys; + if (ref_tab) { + const int32_t nr = ref_tab[0], nk = ref_tab[1]; + const int32_t* w = ref_tab + 2; + for (int32_t i = 0; i < nr; ++i, w += 6) + refs.push_back(Ref2VARef{ w[0], w[2], w[3], w[4], w[5] }); + for (int32_t i = 0; i < nk; ++i, w += 3) + keys.push_back(Ref2VAKeyframe{ w[0], w[1], w[2] }); + } + Ref2VAPack p; + ref2va_build((int)g->n_text, pg, keys, refs, &p); + return p; +} + +/* A segment's modulation cell: the modality's ada projection (0 video, 1 text, 2 audio) and the + * timestep-embedding block it reads, over the four blocks [0,S) video, [S,2S) audio, [2S,3S) + * video-pinned, [3S,4S) audio-pinned. The two target streams read their own schedule; every + * reference block reads its modality's clamped block, whose row s is embed(max(t_s, pin)) -- bit- + * identical to the reference's pinned embedding at every step, so one M=S projection fills the + * cell for all S steps, with no per-step schedule-vs-pin choice to make. */ +static void ref_cell_of(int kind, int64_t S, int* md, int64_t* r0) { + switch (kind) { + case minimaxh3::kR2VAudio: *md = 2; *r0 = S; break; /* audio schedule */ + case minimaxh3::kR2VCondAudio: + case minimaxh3::kR2VRefAudio: *md = 2; *r0 = 2 * S; break; /* audio-pinned block */ + case minimaxh3::kR2VText: *md = 1; *r0 = 0; break; /* video schedule */ + case minimaxh3::kR2VCond: + case minimaxh3::kR2VRefImg: *md = 0; *r0 = 2 * S; break; /* video-pinned block */ + default: *md = 0; *r0 = 0; break; /* video target */ + } +} + +/* Which encoder slot each reference part's latents sit in, in the order ref2va_build lays the + * reference segments down -- a standalone soundtrack alone; a clip its soundtrack (when it carries + * one) then its video; a picture its video alone. The encode pass wrote these into b_evc / b_enca at + * the same slot it names here (the driver's queue uses the ref's own index). Keyframe (cond) rows + * ride the continuation tail, not an encode, so they are absent -- and get no scatter until the tail + * path lands. `audio` picks the buffer (1 = b_enca, 0 = b_evc); `row` is that buffer's base for the + * part. A row < 0 means the slot is unknown -- a table the encode queue never filled. */ +struct RefPart { int audio; int64_t row; }; +static void ref_parts(const int32_t* ref_tab, std::vector* out) { + if (!ref_tab) return; + const int32_t nr = ref_tab[0]; + const int32_t* w = ref_tab + 2; + for (int32_t i = 0; i < nr; ++i, w += 6) { + const int32_t kind = w[0], slot = w[1], aframes = w[5]; + if (kind == minimaxh3::kR2VRefAudioOnly) { + out->push_back({ 1, aenc_slot_row(RAD_ENC_AUDIO, slot) }); + } else if (kind == minimaxh3::kR2VRefImage) { + out->push_back({ 0, venc_slot_row(RAD_ENC_IMAGE, slot) }); + } else { + if (aframes > 0) out->push_back({ 1, aenc_slot_row(RAD_ENC_VAUDIO, slot) }); + out->push_back({ 0, venc_slot_row(RAD_ENC_VIDEO, slot) }); + } + } +} + /* The conditioning pass: the text encoder, context_embedder and the refiner into the lane's prompt * rows, then every step's modulation into the lane's tables. */ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { @@ -2012,14 +2972,24 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { const Geom& g = m.gt; const int64_t T = batch->n_tok, lane = V->lane, S = V->n_steps; const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int64_t nmm = batch->n_mm_rows; + if (m.media && batch->enc_n_patch > 0) m.tv.step(c, batch); RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); - const RadOperand pos = praw(batch->positions, RAD_I32, T); + if (m.media && nmm > 0) + RAD_ISSUE_N(c, m.op_mm, nmm, brows(m.tv.b_out, nmm), praw(batch->mm_rows, RAD_I32, nmm), + brows(m.b_tx, T)); + /* A plain prompt rides one position a token; a ref2va presentation carries the layout's + * three M-RoPE components and takes the twin op. */ + const RadOperand pos = batch->rope_pos ? praw2(batch->rope_pos, RAD_I32, 3, T) + : praw(batch->positions, RAD_I32, T); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); - for (const TeLayer& L : m.te) { + for (size_t li = 0; li < m.te.size(); ++li) { + const TeLayer& L = m.te[li]; RAD_ISSUE(c, L.op_n1, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); L.q_h.step(c, T); L.qkv.step(c, m.a_th, m.b_tkv, T); - RAD_ISSUE(c, L.op_qkr, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE(c, batch->rope_pos ? L.op_qkr_m : L.op_qkr, brows(m.b_tkv, T), pos, + RAD_W(L.w_qn), RAD_W(L.w_kn)); RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); L.q_attn.step(c, T); @@ -2033,6 +3003,11 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { L.down.step(c, m.a_tffn, m.b_th2, T); if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); RAD_ISSUE(c, L.op_add2, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + /* Deepstack: tap l's merged rows join the hidden state at the vision slots after the + * language layer of the same number, as the released clip's do. */ + if (m.media && nmm > 0 && (int)li < m.tv.n_ds) + RAD_ISSUE_N(c, m.op_ds[li], nmm, brows(m.tv.b_ds[li], nmm), + praw(batch->mm_rows, RAD_I32, nmm), brows(m.b_tx, T)); } const Geom& r = m.gr; @@ -2061,39 +3036,69 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, m.op_fn, T, brows(m.b_rh, T), RAD_W(m.w_fn), brow_slice(m.b_text, lane * kMaxText, T, D)); - /* ---- every step's timestep embedding, video rows then soundtrack rows */ - const int64_t fd = 256, td = 2688, S2 = 2 * S; + /* ---- every step's timestep embedding: the two streams' schedules, then each re-embedded with + * its reference pin as a floor (clamp_min) into the two pinned blocks the reference cells read. + * At its own rows: QuantFP8::step bands by the rows it is issued for. */ + const int64_t fd = 256, td = 2688, TT = 4 * S; RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), brow_slice(m.b_tproj, 0, S, fd)); RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), brow_slice(m.b_tproj, S, S, fd)); - RAD_ISSUE_N(c, m.op_t1, S2, brows(m.b_tproj, S2), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, - brows(m.b_te1, S2)); - RAD_ISSUE_N(c, m.op_ts, S2, brows(m.b_te1, S2), brows(m.b_te1s, S2)); - RAD_ISSUE_N(c, m.op_t2, S2, brows(m.b_te1s, S2), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, - brows(m.b_temb, S2)); - RAD_ISSUE_N(c, m.op_ts2, S2, brows(m.b_temb, S2), brows(m.a_temb.x, S2)); - /* At its own rows: QuantFP8::step bands by the batch's tokens, which here are the prompt's, - * and the quantiser is declared for the 2 S rows of the steps' embeddings. */ - RAD_ISSUE_N(c, m.q_temb.op, S2, brows(m.a_temb.x, S2), brows(m.a_temb.cq(), S2), - brows(m.a_temb.cs(), S2)); + RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_tproj, 2 * S, S, fd)); + RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_tproj, 3 * S, S, fd)); + RAD_ISSUE_N(c, m.op_t1, TT, brows(m.b_tproj, TT), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, TT)); + RAD_ISSUE_N(c, m.op_ts, TT, brows(m.b_te1, TT), brows(m.b_te1s, TT)); + RAD_ISSUE_N(c, m.op_t2, TT, brows(m.b_te1s, TT), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, TT)); + RAD_ISSUE_N(c, m.op_ts2, TT, brows(m.b_temb, TT), brows(m.a_temb.x, TT)); + RAD_ISSUE_N(c, m.q_temb.op, TT, brows(m.a_temb.x, TT), brows(m.a_temb.cq(), TT), + brows(m.a_temb.cs(), TT)); /* ---- the modulation table: block l, segment e from its modality's projection of its - * timestep's rows, at the table's column block (l, e) */ - const int64_t L = m.gd.n_layer, row = L * kSegs * m.Ws, base = lane * m.S; + * timestep's rows, at the table's column block (l, e). A plain request has exactly the three + * segments and fills byte-identically; a reference-conditioned one (kRefConsume) has one cell + * per pack segment -- its two target streams read their own schedule, every reference block its + * modality's clamped block (whose per-step value is max(t, pin), the reference's pinned + * embedding), so each cell is one M=S projection. The table's row is `L * ncell` cells wide -- + * ncell cells per block -- because step_dit's mod-gather reads it back as one contiguous span, + * and the buffers are over-allocated at kMaxSegs so any request's `L * ncell` view fits. On a + * plain request ncell == kSegs, so the fill is column-for-column the plain one. */ + const int64_t L = m.gd.n_layer, base = lane * m.S; + const bool refc = kRefConsume && V->ref_tab; + std::vector> cell; + if (refc) { + const minimaxh3::Ref2VAPack p = ref_pack_of(&V->geom, V->ref_tab); + for (const minimaxh3::Ref2VASeg& s : p.segs) { + int md; int64_t r0; + ref_cell_of(s.kind, S, &md, &r0); + cell.emplace_back(md, r0); + } + } else { + for (int e = 0; e < kSegs; ++e) + cell.emplace_back(kSegMod[e], e == kSegAudio ? S : 0); + } + const int64_t ncell = (int64_t)cell.size(); + if (ncell > kMaxSegs) { + rad_step_fail(c, "minimaxh3: the reference conditioning lays out more sequence segments than " + "this plugin's modulation table holds"); + return; + } for (int64_t l = 0; l < L; ++l) { const DitBlock& B = m.dit[(size_t)l]; - for (int e = 0; e < kSegs; ++e) { - const int md = kSegMod[e]; - const int64_t r0 = e == kSegAudio ? S : 0; + for (int64_t e = 0; e < ncell; ++e) { + const int md = cell[(size_t)e].first; + const int64_t r0 = cell[(size_t)e].second; RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td), brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w), RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), - bcol_at(m.b_ada, base, row, (l * kSegs + e) * m.Ws, m.Ws, S)); + bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S)); } } - for (int e = 0; e < kSegs; ++e) { - const int64_t r0 = e == kSegAudio ? S : 0; + for (int64_t e = 0; e < ncell; ++e) { + const int64_t r0 = cell[(size_t)e].second; RAD_ISSUE_N(c, m.op_no, S, brow_slice(m.a_temb.x, r0, S, td), RAD_W(m.w_no), RAD_W(m.b_no), - RAD_NONE, bcol_at(m.b_nout, base, kSegs * 2 * D, e * 2 * D, 2 * D, S)); + RAD_NONE, bcol_at(m.b_nout, base, ncell * 2 * D, e * 2 * D, 2 * D, S)); } } @@ -2103,10 +3108,37 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { const RadVideoGenBatch* V = batch->vgen_b; const Geom& g = m.gd; const int64_t R = batch->n_tok, lane = V->lane, nt = V->geom.n_text; - const int64_t arows = (int64_t)kAudioCh * V->geom.n_audio, vrows = R - nt - arows; + const int64_t arows = (int64_t)kAudioCh * V->geom.n_audio; const int64_t D = m.D, qd = g.q_dim(), L = g.n_layer, La = kMaxLanes; const RadOperand lane_d = praw(V->lane_d, RAD_I32, 1); + /* A reference-conditioned request rebases the layout onto the pack: the reference rows ride + * ahead of the two target streams (which stay last), the sampler owns only those targets, and + * the modulation table has one cell per pack segment. A plain request is the three fixed + * segments and lands every offset exactly as before. */ + const bool refc = kRefConsume && V->ref_tab; + minimaxh3::Ref2VAPack pk; + int64_t vrows, aseg, vseg; + if (refc) { + pk = ref_pack_of(&V->geom, V->ref_tab); + if ((int64_t)pk.segs.size() > kMaxSegs || pk.segs.size() < 2 || + pk.segs.back().kind != minimaxh3::kR2VVideo || + pk.segs[pk.segs.size() - 2].kind != minimaxh3::kR2VAudio) { + rad_step_fail(c, "minimaxh3: the reference conditioning did not lay out a video/audio " + "target pair within the table"); + return; + } + const minimaxh3::Ref2VASeg& vid = pk.segs.back(); + vrows = vid.end - vid.start; + aseg = pk.segs[pk.segs.size() - 2].start; /* the audio target, just before the video */ + vseg = vid.start; + } else { + vrows = R - nt - arows; + aseg = nt; + vseg = nt + arows; + } + const int64_t ncell = refc ? (int64_t)pk.segs.size() : (int64_t)kSegs; + if (V->step == 0) { RAD_ISSUE_N(c, m.op_rnd_v, vrows, praw(V->first_d, RAD_I32, 1), praw(V->seed, RAD_U32, 2), lane_d, praw(V->lat_cu, RAD_I32, 2), brows(m.b_vstate, La * m.maxV)); @@ -2114,47 +3146,89 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { praw(V->seed + 2, RAD_U32, 2), lane_d, praw(V->lat_cu + 2, RAD_I32, 2), brows(m.b_astate, La * m.maxA)); } - const int64_t row = L * kSegs * m.Ws, ti = lane * m.S + V->step; + /* The gather is a fixed shape: the 2-rank gather kernel is specialised to the declared width, + * so every step -- plain or reference-conditioned -- gathers the whole `L * kMaxSegs` block and + * the norm reads only its `ncell` cells at that pitch. Issuing the gather narrower than it was + * declared is what a reference step did here and `ar_gather_2rank` refused. */ + const int64_t row = L * kMaxSegs * m.Ws, ti = lane * m.S + V->step; if (g.world > 1) RAD_ISSUE_N(c, m.op_modg, row, brow_slice(m.b_ada, ti, 1, row), - brows(m.b_modg, (int64_t)g.world * L * kSegs)); + brows(m.b_modg, (int64_t)g.world * L * kMaxSegs)); else RAD_ISSUE_N(c, m.op_modg, 1, brow_slice(m.b_ada, ti, 1, row), RAD_P_T2(rad_buf_ptr(c, m.b_modg), RAD_BF16, 1, row)); RAD_ISSUE_N(c, m.op_text, nt, brows(m.b_text, La * kMaxText), lane_d, praw(V->seg_cu, RAD_I32, 2), brows(m.b_h, nt)); + /* The target streams first: each its input projection, landing at its place in the pack (the + * plain `text | audio | video` on the plain path). */ RAD_ISSUE_N(c, m.op_ain, arows, brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC), - RAD_W(m.w_ain), RAD_W(m.b_ain), RAD_NONE, brow_slice(m.b_h, nt, arows, D)); + RAD_W(m.w_ain), RAD_W(m.b_ain), RAD_NONE, brow_slice(m.b_h, aseg, arows, D)); RAD_ISSUE_N(c, m.op_vin, vrows, brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals), - RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, brow_slice(m.b_h, nt + arows, vrows, D)); + RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, brow_slice(m.b_h, vseg, vrows, D)); + /* Then each reference block: the same input projection, but its latents read from the encoder's + * slot (b_evc / b_enca), scattered into the rows the pack placed between the prompt and the + * targets. Every ref part -- a picture, a clip's video, a clip's or a standalone's soundtrack -- + * is one issue, its part list consumed in the order ref2va_build laid the segments down. */ + if (refc) { + std::vector parts; + ref_parts(V->ref_tab, &parts); + size_t pi = 0; + for (const minimaxh3::Ref2VASeg& s : pk.segs) { + const bool img = minimaxh3::ref2va_is_img(s.kind), aud = minimaxh3::ref2va_is_audio(s.kind); + if (!img && !aud) continue; /* text, and the targets above */ + if (s.kind != minimaxh3::kR2VRefImg && s.kind != minimaxh3::kR2VRefAudio) continue; + if (pi >= parts.size()) { + rad_step_fail(c, "minimaxh3: the reference conditioning has more reference blocks " + "than its table describes"); + return; + } + const RefPart& src = parts[pi++]; + const int64_t n = s.end - s.start; + if (src.row < 0 || (src.audio == 1) != aud) { + rad_step_fail(c, "minimaxh3: a reference block names an encode slot the queue never " + "filled, or the wrong latent space"); + return; + } + if (img) + RAD_ISSUE_N(c, m.op_vin, n, brow_slice(m.b_evc, src.row, n, kPatchVals), + RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, + brow_slice(m.b_h, s.start, n, D)); + else + RAD_ISSUE_N(c, m.op_ain, n, brow_slice(m.b_enca, src.row, n, kAudioC), + RAD_W(m.w_ain), RAD_W(m.b_ain), RAD_NONE, + brow_slice(m.b_h, s.start, n, D)); + } + } - const RadOperand segs = praw(V->seg_cu, RAD_I32, kSegs + 1); + const RadOperand segs = praw(V->seg_cu, RAD_I32, ncell + 1); const RadOperand geom = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); const RadOperand pos = praw2(V->pos, RAD_F32, 3, R); - /* Chunk k of block l's six, for the three segments: on rank k / (6 / world), at its column. */ + /* Chunk k of block l's six, for every segment: on rank k / (6 / world), at its column. */ const int64_t per = 6 / g.world, nD = D / RAD_FP8_BLOCK; auto mod = [&](int64_t l, int k, int chunks) { const int64_t r = k / per; - return bcol_at(m.b_modg, r * L * kSegs + l * kSegs, m.Ws, (k % per) * D, chunks * D, kSegs); + return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs, m.Ws, (k % per) * D, chunks * D, + ncell); }; /* Two halves of the rows with more than one rank. Everything between two attentions is * row-local, so a half computes exactly the bits the whole would, and each half's all-reduces * run on lane 1 while lane 0 computes the other half; the attention stays whole. The second - * half starts at the video's middle row, so it is video alone: the batch's one-sequence - * cu_seqlens and the video's modulation row stand for the segment table. Lane 0 waits for a - * half's all-reduce before its first reader, issued before the next all-reduce goes to lane 1 - * (a join orders a lane behind everything issued on the other). */ + * half starts at the video target's middle row -- the video target is the pack's last segment, + * so the half is video alone: the batch's one-sequence cu_seqlens and the video target's + * modulation row (the last cell) stand for the segment table. Lane 0 waits for a half's + * all-reduce before its first reader, issued before the next all-reduce goes to lane 1 (a join + * orders a lane behind everything issued on the other). */ const bool split = g.world > 1; - const int64_t cut = split ? nt + arows + vrows / 2 : R; + const int64_t cut = split ? vseg + vrows / 2 : R; const int64_t hr0[2] = { 0, cut }, hn[2] = { cut, R - cut }; const int nh = split ? 2 : 1; const RadOperand segh[2] = { segs, cu }; auto modh = [&](int h, int64_t l, int k, int chunks) { if (h == 0) return mod(l, k, chunks); const int64_t r = k / per; - return bcol_at(m.b_modg, r * L * kSegs + l * kSegs + kSegVideo, m.Ws, (k % per) * D, + return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs + (ncell - 1), m.Ws, (k % per) * D, chunks * D, 1); }; /* A half's partial sums across the ranks, kArRows rows a message, on lane 1 when split. */ @@ -2224,9 +3298,9 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { } wait_ar(); const char* nout = (const char*)rad_buf_ptr(c, m.b_nout) + - (lane * m.S + V->step) * kSegs * 2 * D * (int64_t)sizeof(uint16_t); + (lane * m.S + V->step) * ncell * 2 * D * (int64_t)sizeof(uint16_t); RAD_ISSUE_N(c, m.op_nout, R, brows(m.b_ao, R), mod(L - 1, 5, 1), - RAD_P_T2(nout, RAD_BF16, kSegs, 2 * D), RAD_W(m.w_no_n), segs, brows(m.b_h, R), + RAD_P_T2(nout, RAD_BF16, ncell, 2 * D), RAD_W(m.w_no_n), segs, brows(m.b_h, R), brows(m.b_hn, R)); /* The heads, in f32 over parts of the rows. */ @@ -2239,8 +3313,8 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { brow_slice(y, r0, k, nout_c)); } }; - heads(m.op_aout, m.w_aout, m.b_aout, nt, arows, kAudioC, m.b_avel); - heads(m.op_vout, m.w_vout, m.b_vout, nt + arows, vrows, kPatchVals, m.b_vel); + heads(m.op_aout, m.w_aout, m.b_aout, aseg, arows, kAudioC, m.b_avel); + heads(m.op_vout, m.w_vout, m.b_vout, vseg, vrows, kPatchVals, m.b_vel); RAD_ISSUE_N(c, m.op_ev, vrows, brows(m.b_vel, vrows), praw(V->sched, RAD_F32, 1), praw(V->sched + 1, RAD_F32, 1), praw(V->sched + 2, RAD_F32, 1), brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals)); @@ -2430,6 +3504,204 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) { brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); } +/* The video VAE encoder over one media item: its clip-padded frames in `enc_pixels`, each clip + * through the six levels to the 48-column moments, the first 24 quantised and folded into the + * lane's `b_evc` at the media's slot. The volumes come from the same geometry the driver staged + * — re-derived here, which is also the batch's validation. */ +static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + int32_t g[25]; + if (!V->enc_pixels || + !venc_geom(V->enc_frames, V->enc_height, V->enc_width, g)) { + rad_step_fail(c, "minimaxh3: a Vencode pass with no pixels, or frames, height or width " + "the video encoder does not take"); + return; + } + const int64_t row0 = venc_slot_row(V->enc_kind, V->enc_slot); + if (row0 < 0) { + rad_step_fail(c, "minimaxh3: a Vencode pass naming an encode kind or slot this plugin " + "does not know"); + return; + } + if ((int64_t)V->enc_frames != g[23]) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose frames are not the clip-padded count " + "rad_arch_encode_geom reports"); + return; + } + const int32_t* gd = V->enc_geom_d; + const int64_t H = V->enc_height, W = V->enc_width; + const int64_t ppc = (H / (kVaeRatio * kPatch)) * (W / (kVaeRatio * kPatch)); + const int64_t n_clips = g[22], full = g[15], short_last = g[18]; + if ((full * (n_clips - 1) + short_last) * ppc > kEncSlotRowsV) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose latents overflow the lane's slot"); + return; + } + const RadOperand st = RAD_B(m.b_egn); + /* The geometry entry each level's volume starts at. The last two levels share one volume: + * there is no downsampler between the 512- and the 1024-wide level. */ + static const int kVOrg[6] = { 0, 3, 6, 9, 12, 12 }; + int64_t frow = row0; + for (int64_t cc = 0; cc < n_clips; ++cc) { + const bool last = cc == n_clips - 1; + const int64_t R0 = (int64_t)g[0] * H * W; + const RadOperand gg[6] = { praw(gd + kVOrg[0], RAD_I32, 3), praw(gd + kVOrg[1], RAD_I32, 3), + praw(gd + kVOrg[2], RAD_I32, 3), praw(gd + kVOrg[3], RAD_I32, 3), + praw(gd + kVOrg[4], RAD_I32, 3), praw(gd + kVOrg[5], RAD_I32, 3) }; + RAD_ISSUE_N(c, m.op_ve_pix, R0, praw2(V->enc_pixels + cc * R0 * 3, RAD_F32, R0, 3), + brows(m.b_epix32, R0)); + RAD_ISSUE_N(c, m.op_ve_pcast, R0, brows(m.b_epix32, R0), brows(m.b_epix, R0)); + RAD_ISSUE_N(c, m.op_ve_cin, R0, brows(m.b_epix, R0), RAD_W(m.ve_cinw), RAD_W(m.ve_cinb), + gg[0], RAD_NONE, brows(m.v_lv[0].a, R0)); + for (int L = 0; L < 6; ++L) { + const Model::VEncLevel& E = m.v_lv[(size_t)L]; + const int64_t R = (int64_t)g[kVOrg[L]] * g[kVOrg[L] + 1] * g[kVOrg[L] + 2]; + const bool sc = E.op_sc; + for (int blk = 0; blk < 2; ++blk) { + const Model::VEncBlock& B = E.blk[blk]; + const bool f0 = blk == 0 && sc; + const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b; + /* norm1 over the whole volume, SiLU'd; on a shortcut level that is `in` itself, + * in place, and the shortcut convolves the result into `a`. */ + RAD_ISSUE_N(c, B.op_n1, R, brows(xa, R), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st, + brows(nb, R)); + if (f0) + RAD_ISSUE_N(c, E.op_sc, R, brows(E.in, R), RAD_W(E.scw), RAD_W(E.scb), gg[L], + RAD_NONE, brows(E.a, R)); + RAD_ISSUE_N(c, B.op_c1, R, brows(nb, R), RAD_W(B.c1w), RAD_W(B.c1b), gg[L], + RAD_NONE, brows(E.c, R)); + RAD_ISSUE_N(c, B.op_n2, R, brows(E.c, R), RAD_W(B.n2w), RAD_W(B.n2b), RAD_NONE, st, + brows(E.b, R)); + RAD_ISSUE_N(c, B.op_c2, R, brows(E.b, R), RAD_W(B.c2w), RAD_W(B.c2b), gg[L], + brows(E.a, R), brows(E.a, R)); + } + if (L < 4) { + const Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const int64_t RX = (int64_t)g[3 * (L + 1)] * g[3 * (L + 1) + 1] * g[3 * (L + 1) + 2]; + const rad_buf y = X.op_sc ? X.in : X.a; + RAD_ISSUE_N(c, E.op_dn, RX, brows(E.a, R), RAD_W(E.dnw), RAD_W(E.dnb), gg[L], + RAD_NONE, brows(y, RX)); + } + } + const int64_t R5 = (int64_t)g[12] * g[13] * g[14]; + RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob), + RAD_NONE, st, brows(m.v_lv[5].b, R5)); + RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw), + RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5)); + RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5], + RAD_NONE, brows(m.b_eq2, R5)); + const int64_t flat = last ? short_last : full; + RAD_ISSUE_N(c, m.op_ve_fold, flat * ppc, + bcol(m.b_eq2, 0, kC, flat * (H / kVaeRatio) * (W / kVaeRatio)), + praw(gd + (last ? 18 : 15), RAD_I32, 3), + brow_slice(m.b_evc, frow, flat * ppc, kPatchVals)); + frow += flat * ppc; + } +} + +/* The audio VAE encoder over one media item: `enc_samples`, channel-major and zero-padded, each + * channel a mono sequence through the five strided blocks and the attention pre-block to 32 + * normalised latents a frame, into `b_enca` at the media's slot. The sequence lengths — the + * padded one and every stage's — are read off the staged geometry, as every `cu` here. */ +static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + int32_t g[13]; + if (!V->enc_samples || !aenc_geom(V->enc_n_samples, V->enc_channels, g)) { + rad_step_fail(c, "minimaxh3: an Aencode pass with no samples, or a length and channel " + "count the audio encoder does not take"); + return; + } + const int64_t row0 = aenc_slot_row(V->enc_kind, V->enc_slot); + if (row0 < 0) { + rad_step_fail(c, "minimaxh3: an Aencode pass naming an encode kind or slot this plugin " + "does not know"); + return; + } + const int64_t n_pad = g[0]; + if ((int64_t)V->enc_n_samples != n_pad) { + rad_step_fail(c, "minimaxh3: an Aencode pass whose samples are not padded to the length " + "rad_arch_encode_geom reports"); + return; + } + const int32_t* gd = V->enc_geom_d; + 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) { + 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)); + int64_t rows = n_pad; + for (int blk = 0; blk < 5; ++blk) { + const Model::AEncBlk& A = m.ae_blk[blk]; + const RadOperand cu = praw(gd + 1 + 2 * blk, RAD_I32, 2); + const int64_t R = rows, no = g[2 + 2 * (blk + 1)]; + 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_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)); + 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_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)); + RAD_ISSUE_N(c, A.op_co, no, brows(A.bo, no), brows(m.b_ax[blk + 1], no)); + 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)); + 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)); + /* The pre-block: the attention over the 2048-wide stream, its eight heads' mean pooled + * to 32 and projected; then the gated MLP, and the two residuals. */ + RAD_ISSUE_N(c, m.p_op_ln3, rows, brows(m.b_apb, rows), RAD_W(m.p_ln3w), RAD_W(m.p_ln3b), + brows(m.b_aln3, rows)); + RAD_ISSUE_N(c, m.p_op_qkv, rows, brows(m.b_aln3, rows), RAD_W(m.p_qkvw), RAD_W(m.p_qkvb), + RAD_NONE, brows(m.b_aqkv, rows)); + for (int h = 0; h < 8; ++h) { + /* The first head writes the running sum, the next six add into it and the eighth + * divides it. */ + const rad_buf y = h == 0 ? m.b_ahsum : m.b_aatt; + RAD_ISSUE_N(c, m.p_op_attn, rows, bcol(m.b_aqkv, h * hd, hd, rows), + bcol(m.b_aqkv, ld + h * hd, hd, rows), + bcol(m.b_aqkv, 2 * ld + h * hd, hd, rows), cu6, brows(y, rows)); + if (h > 0) + RAD_ISSUE_N(c, h == 7 ? m.p_op_hsd : m.p_op_hs, rows, brows(m.b_ahsum, rows), + brows(m.b_aatt, rows), brows(m.b_ahsum, rows)); + } + RAD_ISSUE_N(c, m.p_op_pool, rows, brows(m.b_ahsum, rows), brows(m.b_apool, rows)); + RAD_ISSUE_N(c, m.p_op_aproj, rows, brows(m.b_apool, rows), RAD_W(m.p_apw), RAD_W(m.p_apb), + RAD_NONE, brows(m.b_a32a, rows)); + RAD_ISSUE_N(c, m.p_op_ln1, rows, brows(m.b_apb, rows), RAD_W(m.p_ln1w), RAD_W(m.p_ln1b), + brows(m.b_aln3, rows)); + RAD_ISSUE_N(c, m.p_op_proj, rows, brows(m.b_aln3, rows), RAD_W(m.p_prw), RAD_W(m.p_prb), + RAD_NONE, brows(m.b_eh, rows)); + RAD_ISSUE_N(c, m.p_op_hadd, rows, brows(m.b_eh, rows), brows(m.b_a32a, rows), + brows(m.b_a32b, rows)); + RAD_ISSUE_N(c, m.p_op_ln2, rows, brows(m.b_a32b, rows), RAD_W(m.p_ln2w), RAD_W(m.p_ln2b), + brows(m.b_a32c, rows)); + RAD_ISSUE_N(c, m.p_op_mln, rows, brows(m.b_a32c, rows), RAD_W(m.p_mlw), RAD_W(m.p_mlb), + brows(m.b_a32d, rows)); + RAD_ISSUE_N(c, m.p_op_gu, rows, brows(m.b_a32d, rows), RAD_W(m.p_guw), RAD_W(m.p_gub), + RAD_NONE, brows(m.b_agu, rows)); + RAD_ISSUE_N(c, m.p_op_act, rows, brows(m.b_agu, rows), brows(m.b_agu64, rows)); + RAD_ISSUE_N(c, m.p_op_w2, rows, brows(m.b_agu64, rows), RAD_W(m.p_w2w), RAD_W(m.p_w2b), + RAD_NONE, brows(m.b_a32c, rows)); + RAD_ISSUE_N(c, m.p_op_xadd, rows, brows(m.b_a32b, rows), brows(m.b_a32c, rows), + brows(m.b_ax2, rows)); + RAD_ISSUE_N(c, m.op_ae_castx, rows, brows(m.b_ax2, rows), brows(m.b_amb, rows)); + RAD_ISSUE_N(c, m.op_ae_mp, rows, brows(m.b_amb, rows), RAD_W(m.ae_mpw), cu6, + RAD_NONE, brows(m.b_amb2, rows), RAD_W(m.ae_mpb)); + RAD_ISSUE_N(c, m.op_ae_norm, rows, brows(m.b_amb2, rows), + brow_slice(m.b_enca, row0 + (int64_t)ch * (kEncSlotRowsA / (int64_t)kAudioCh), + rows, kAudioC)); + } +} + static void step(RadCtx* c, const RadBatch* batch) { const Model& m = g_model[rad_rank(c)]; if (!batch->gen || !batch->vgen_b) { @@ -2449,6 +3721,22 @@ static void step(RadCtx* c, const RadBatch* batch) { } step_upscale(c, batch, m); return; + case RAD_GEN_PASS_VENCODE: + if (!m.venc) { + rad_step_fail(c, "minimaxh3: a Vencode pass, and this container has no video VAE " + "encoder"); + return; + } + step_venc(c, batch, m); + return; + case RAD_GEN_PASS_AENCODE: + if (!m.aenc) { + rad_step_fail(c, "minimaxh3: an Aencode pass, and this container has no audio VAE " + "encoder"); + return; + } + step_aenc(c, batch, m); + return; default: rad_step_fail(c, "minimaxh3: a generator pass of a kind this plugin does not know"); } @@ -2459,7 +3747,11 @@ static void step(RadCtx* c, const RadBatch* batch) { * the most tiles. */ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; - out->gen_rows = std::max(max_step_rows(), max_tiles() * kPeriod); + /* The encoder passes' rows are NOT here: their intermediates are fixed-shape buffers the + * declare already sizes (a whole padded clip at kEncMaxSide), while gen_rows scales the + * per-step tables — folding the encoder's pixel rows in multiplies the arena by nine and + * no card carries it. */ + out->gen_rows = std::max({ max_step_rows(), max_tiles() * kPeriod }); out->gen_video = 1; return RAD_OK; } @@ -2480,4 +3772,102 @@ extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, fl if (which == RAD_VPOS_DECODE) return minimaxh3::decode_rows(g); return RAD_E_INVAL; } + +/* What the encode passes stage into `enc_geom_d`, from the media's own shape: 25 int32s for a + * Vencode pass (the five volumes, the fold's full and short-last-clip geometry, and the clip + * arithmetic) and 13 for an Aencode pass (the padded sample count and the six sequence lengths + * as {0, n} pairs, each pair a mono `cu` the kernels read two at a time). The layouts are the + * plugin's own and the driver copies them verbatim; the plugin's steps re-derive them on the + * host from the batch's fields, so a pass whose media this rejects at declare-export time can + * never reach a step. */ +extern "C" int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, + int64_t cap) { + if (!in) return RAD_E_INVAL; + if (kind == RAD_GEN_PASS_VENCODE) { + if (!out) + return minimaxh3::venc_geom(in[0], in[1], in[2], nullptr) ? minimaxh3::kVEncGeomN + : RAD_E_INVAL; + if (cap < minimaxh3::kVEncGeomN) return RAD_E_INVAL; + return minimaxh3::venc_geom(in[0], in[1], in[2], out) ? minimaxh3::kVEncGeomN + : RAD_E_INVAL; + } + if (kind == RAD_GEN_PASS_AENCODE) { + if (!out) + return minimaxh3::aenc_geom(in[0], in[3], nullptr) ? minimaxh3::kAEncGeomN + : RAD_E_INVAL; + if (cap < minimaxh3::kAEncGeomN) return RAD_E_INVAL; + return minimaxh3::aenc_geom(in[0], in[3], out) ? minimaxh3::kAEncGeomN : RAD_E_INVAL; + } + return RAD_E_INVAL; +} + +/* The packed sequence's segment boundary table: cu[k] is the first row of segment k and cu[n-1] + * the sequence's total rows -- the boundaries R_SEG stages, laid out by the pack. Optional + * export: a driver without it stages the plain [text | audio | video] table itself, which for a + * plain request is this table. Call with cu = nullptr for the number of int32s needed. */ +extern "C" int64_t rad_arch_video_segs(const RadVideoGeom* g, int32_t* cu, int64_t cap) { + if (!g || g->n_text < 1 || g->n_text > minimaxh3::kMaxText) return RAD_E_INVAL; + if (g->lat_frames < 1 || g->lat_h < minimaxh3::kPatch || g->lat_w < minimaxh3::kPatch || + g->n_audio < 1) + return RAD_E_INVAL; + const minimaxh3::Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, + (int)g->n_audio }; + minimaxh3::Ref2VAPack p; + if (minimaxh3::ref2va_build((int)g->n_text, pg, {}, {}, &p) != 0) return RAD_E_INVAL; + const int64_t n = (int64_t)p.segs.size() + 1; + if (!cu) return n; + if (cap < n) return RAD_E_INVAL; + for (size_t k = 0; k < p.segs.size(); ++k) cu[k] = (int32_t)p.segs[k].start; + cu[n - 1] = (int32_t)p.rows; + return n; +} + +/* The general layout: the same pack with the request's keyframes and VAE references in, from + * the RadVideoGenBatch::ref_tab table verbatim -- 6 words per reference {kind, slot, h, w, + * frames, audio} after the two counts, 3 per keyframe {frame, video, audio}. The slot rides for + * the step's scatter (the encoder wrote each reference's latents at its kind's and slot's rows); + * the pack itself reads the grid and the lengths, all in latent units. Answers with the total + * rows always -- a submit needs nothing else -- and writes the boundaries and the positions when + * asked and roomy. A plain geometry gives the table rad_arch_video_segs gives: both are this + * pack, so a driver that prefers one over the other stages the same bytes either way. */ +extern "C" int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, + int32_t* seg, int64_t cap_seg, float* pos, + int64_t cap_pos) { + if (!g || g->n_text < 1 || g->n_text > minimaxh3::kMaxText) return RAD_E_INVAL; + if (g->lat_frames < 1 || g->lat_h < minimaxh3::kPatch || g->lat_w < minimaxh3::kPatch || + g->n_audio < 1) + return RAD_E_INVAL; + const minimaxh3::Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, + (int)g->n_audio }; + std::vector refs; + std::vector keys; + if (ref_tab) { + /* The counts the driver can be asked for at all: the server's caps are 9/3/3, and a + * continuation presents at most one keyframe pair -- the ceilings here are roomy + * sanity, not policy. */ + const int32_t nr = ref_tab[0], nk = ref_tab[1]; + if (nr < 0 || nk < 0 || nr > 64 || nk > 8) return RAD_E_INVAL; + const int32_t* w = ref_tab + 2; + for (int32_t i = 0; i < nr; ++i, w += 6) { + if (w[0] < 0 || w[0] > 3 || w[1] < 1) return RAD_E_INVAL; + refs.push_back(minimaxh3::Ref2VARef{ w[0], w[2], w[3], w[4], w[5] }); + } + for (int32_t i = 0; i < nk; ++i, w += 3) + keys.push_back(minimaxh3::Ref2VAKeyframe{ w[0], w[1], w[2] }); + } + minimaxh3::Ref2VAPack p; + if (minimaxh3::ref2va_build((int)g->n_text, pg, keys, refs, &p) != 0) return RAD_E_INVAL; + const int64_t nseg = (int64_t)p.segs.size() + 1; + if (seg && cap_seg < nseg) return RAD_E_INVAL; + /* The positions are planar -- all times, then all rows, then all columns -- so `pos` holds + * 3 * rows floats, not rows of them; a caller that sized its slab to the row count alone would + * overflow two thirds past its end. The copy below writes the whole [3, rows] array. */ + if (pos && cap_pos < 3 * p.rows) return RAD_E_INVAL; + if (seg) { + for (size_t k = 0; k < p.segs.size(); ++k) seg[k] = (int32_t)p.segs[k].start; + seg[nseg - 1] = (int32_t)p.rows; + } + if (pos) std::copy(p.pos.begin(), p.pos.end(), pos); + return p.rows; +} #endif diff --git a/arch/minimaxh3/rad_ref2va_pack.cpp b/arch/minimaxh3/rad_ref2va_pack.cpp new file mode 100644 index 00000000..32e7ac8a --- /dev/null +++ b/arch/minimaxh3/rad_ref2va_pack.cpp @@ -0,0 +1,294 @@ +/* The Ref2VA packing, ported rule for rule from the reference implementation's PackedLayout + * (docs/NOTE-P3-PACK.md carries the line-referenced extraction; the golden vectors in + * tests/data/ref2va are generated from the reference source itself). Where the reference computes + * in float64 so does this -- the coordinates feed a rotary, and an area-normalised axis drawn with + * float32 steps would bend it. The stored positions are f32 because that is what R_ROPE holds. */ + +#include "rad_ref2va_pack.h" + +#include +#include + +namespace minimaxh3 { + +/* Pixel frames the k-th video latent of a run covers, cycling; the pixel-frames-per-audio-latent + * rescale; and the near-clean timesteps the pinned rows sit at. */ +static const int kFramePerToken[5] = { 1, 4, 4, 4, 4 }; +static const double kFrameRescale = 5.0 / 3.0; +static const double kVisualPin = 0.999; +static const double kAudioPin = 1.0; + +static const char* const kKindNames[kR2VKinds] = { "text", "cond", "cond_audio", "ref_img", + "ref_audio", "audio", "video" }; + +const char* ref2va_kind_name(int kind) { + return kind >= 0 && kind < kR2VKinds ? kKindNames[kind] : "?"; +} + +int ref2va_seg_tag(int kind) { + switch (kind) { + case kR2VText: return 1; + case kR2VAudio: case kR2VCondAudio: case kR2VRefAudio: return 2; + default: return 0; /* video, cond, ref_img */ + } +} + +int ref2va_is_img(int kind) { + return kind == kR2VCond || kind == kR2VRefImg || kind == kR2VVideo; +} + +int ref2va_is_audio(int kind) { + return kind == kR2VCondAudio || kind == kR2VRefAudio || kind == kR2VAudio; +} + +double ref2va_t_label(int kind, double t_v, double t_a) { + switch (kind) { + case kR2VCond: case kR2VRefImg: return std::max(t_v, kVisualPin); + case kR2VCondAudio: case kR2VRefAudio: return std::max(t_a, kAudioPin); + case kR2VAudio: return t_a; + default: return t_v; /* text, video */ + } +} + +/* The spatial axis of a latent side `dim` at 2x2 patches: n coords spreading over + * [(1-ratio)/2, (1+ratio)/2] * 32, ratio = dim / sqrt(h*w) -- so a square latent maps both axes + * onto the same [~8, ~24] band and a wide one trades bands against its neighbour, keeping the + * rotary's combined reach the same for every aspect. */ +static std::vector axis_from_sqrt_area(int dim, int patch, double sqrt_area) { + const double ratio = (double)dim / sqrt_area; + const int n = dim / patch; + std::vector v((size_t)n); + for (int i = 0; i < n; ++i) + v[(size_t)i] = ((double)i * (ratio / n) + (1.0 - ratio) / 2.0) * 32.0; + return v; +} + +/* One latent frame's patch rows: h-major (row, col) pairs over the 2x2 grid, plus the column axis + * on its own -- its first and last coordinate pin the stereo channels onto the grid's width. */ +static void frame_grid(int h, int w, std::vector* frame, std::vector* w_grid) { + const double area = std::sqrt((double)h * (double)w); + std::vector hg = axis_from_sqrt_area(h, 2, area), wg = axis_from_sqrt_area(w, 2, area); + frame->clear(); + frame->reserve(hg.size() * wg.size() * 2); + for (const double& r : hg) + for (const double& c : wg) { frame->push_back(r); frame->push_back(c); } + *w_grid = std::move(wg); +} + +/* The time a run of n video latents occupies on the audio-latent scale. */ +static double video_t_span_sum(int n) { + double s = 0.0; + for (int k = 0; k < n; ++k) s += kFrameRescale * (double)kFramePerToken[k % 5]; + return s; +} + +/* Each video latent's time coordinate: origin, then origin + each shorter latent prefix's spans + * (exclusive cumsum -- the k-th latent sits where its predecessors end). */ +static std::vector video_t_grid(int n, double origin) { + std::vector g((size_t)n); + double t = origin; + for (int k = 0; k < n; ++k) { + g[(size_t)k] = t; + t += kFrameRescale * (double)kFramePerToken[k % 5]; + } + return g; +} + +/* The time a reference block occupies ahead of the target timeline: a photo one frame, a standalone + * soundtrack its own length, a clip whichever of its two streams reaches further. */ +static double ref_t_span(const Ref2VARef& r) { + if (r.kind == kR2VRefImage) return 1.0; + if (r.kind == kR2VRefAudioOnly) return (double)r.audio_t; + return std::max((double)r.audio_t, video_t_span_sum(r.latent_t)); +} + +/* Append a block's stereo audio rows: channel-major -- all T frames of the left channel, then the + * right's -- time advancing one audio latent a row, width pinned to the grid's first coordinate + * for one channel and its last for the other, height always 0. */ +static void audio_grid(double cursor, int t, double w_low, double w_high, std::vector* pos) { + for (int ch = 0; ch < 2; ++ch) { + const double w = ch == 0 ? w_low : w_high; + for (int i = 0; i < t; ++i) { + pos->push_back((float)(cursor + (double)i)); + pos->push_back(0.0f); + pos->push_back((float)w); + } + } +} + +/* Append a block's video rows: every latent frame's patch rows at that frame's time coordinate. */ +static void video_grid(int vt, const std::vector& frame, double origin, + std::vector* pos) { + const std::vector tg = video_t_grid(vt, origin); + for (int k = 0; k < vt; ++k) + for (size_t j = 0; j < frame.size(); j += 2) { + pos->push_back((float)tg[(size_t)k]); + pos->push_back((float)frame[j]); + pos->push_back((float)frame[j + 1]); + } +} + +int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector& keyframes, + const std::vector& refs, Ref2VAPack* out) { + if (text_len < 0 || g.latent_t < 0 || g.latent_h < 0 || g.latent_w < 0 || g.audio_t < 0) + return -1; + for (const Ref2VAKeyframe& kf : keyframes) + if (kf.frame < 0 || kf.video_t < 0 || kf.audio_t < 0) return -1; + for (const Ref2VARef& r : refs) { + if (r.kind < kR2VRefImage || r.kind > kR2VRefVideoAudio) return -1; + if (r.lat_h < 0 || r.lat_w < 0 || r.latent_t < 0 || r.audio_t < 0) return -1; + } + + Ref2VAPack p; + std::vector frame, w_grid; + frame_grid(g.latent_h, g.latent_w, &frame, &w_grid); + const size_t frame_rows = frame.size() / 2; + const double w_low = w_grid.empty() ? 0.0 : w_grid.front(); + const double w_high = w_grid.empty() ? 0.0 : w_grid.back(); + + /* The prompt first: time = position in the prompt, space unused. */ + p.segs.push_back({ kR2VText, 0, (int64_t)text_len, 0 }); + p.pos.reserve((size_t)text_len * 3); + for (int i = 0; i < text_len; ++i) { + p.pos.push_back((float)i); + p.pos.push_back(0.0f); + p.pos.push_back(0.0f); + } + int64_t row = text_len; + + /* References pack between the prompt and the targets, so the target timeline -- and every + * keyframe anchored to it -- starts after all of their spans. */ + double cursor = (double)text_len; + for (const Ref2VARef& r : refs) cursor += ref_t_span(r); + + /* Keyframes: a keyframe's latent rows share the TARGET grid (they were resized before the + * VAE), anchored at its pixel frame's moment on the target timeline. */ + for (const Ref2VAKeyframe& kf : keyframes) { + const double cond_t = cursor + kFrameRescale * (double)kf.frame; + if (kf.video_t > 0) { + const int64_t n = (int64_t)kf.video_t * (int64_t)frame_rows; + video_grid(kf.video_t, frame, cond_t, &p.pos); + p.segs.push_back({ kR2VCond, row, row + n, 0 }); + row += n; + } + if (kf.audio_t > 0) { + const int64_t n = (int64_t)kf.audio_t * 2; + audio_grid(cond_t, kf.audio_t, w_low, w_high, &p.pos); + p.segs.push_back({ kR2VCondAudio, row, row + n, 0 }); + row += n; + } + } + + /* Reference blocks, in request order, each at a running cursor of its own. */ + cursor = (double)text_len; + for (const Ref2VARef& r : refs) { + if (r.kind == kR2VRefImage) { + std::vector rf, rw; + frame_grid(r.lat_h, r.lat_w, &rf, &rw); + const int64_t n = (int64_t)rf.size() / 2; + for (int64_t i = 0; i < n; ++i) { + p.pos.push_back((float)cursor); + p.pos.push_back((float)rf[(size_t)i * 2]); + p.pos.push_back((float)rf[(size_t)i * 2 + 1]); + } + p.segs.push_back({ kR2VRefImg, row, row + n, 0 }); + row += n; + cursor += 1.0; + } else if (r.kind == kR2VRefAudioOnly) { + if (r.audio_t > 0) { + const int64_t n = (int64_t)r.audio_t * 2; + audio_grid(cursor, r.audio_t, w_low, w_high, &p.pos); + p.segs.push_back({ kR2VRefAudio, row, row + n, 0 }); + row += n; + } + cursor += (double)r.audio_t; + } else { + /* A clip's soundtrack packs immediately before its video, both at the same time + * origin, and its audio channels pin onto the CLIP's own width extremes -- it is the + * clip's space, not the target's. */ + std::vector rf, rw; + frame_grid(r.lat_h, r.lat_w, &rf, &rw); + if (r.audio_t > 0) { + const int64_t n = (int64_t)r.audio_t * 2; + audio_grid(cursor, r.audio_t, rw.empty() ? 0.0 : rw.front(), + rw.empty() ? 0.0 : rw.back(), &p.pos); + p.segs.push_back({ kR2VRefAudio, row, row + n, 0 }); + row += n; + } + const int64_t n = (int64_t)r.latent_t * (int64_t)(rf.size() / 2); + video_grid(r.latent_t, rf, cursor, &p.pos); + p.segs.push_back({ kR2VRefImg, row, row + n, 0 }); + row += n; + cursor += std::max((double)r.audio_t, video_t_span_sum(r.latent_t)); + } + } + + /* The target streams, always last and always the sampler's whole state: the soundtrack, then + * the video, both at the timeline the references left room for. */ + { + const int64_t n = (int64_t)g.audio_t * 2; + audio_grid(cursor, g.audio_t, w_low, w_high, &p.pos); + p.segs.push_back({ kR2VAudio, row, row + n, 1 }); + row += n; + } + { + const int64_t n = (int64_t)g.latent_t * (int64_t)frame_rows; + video_grid(g.latent_t, frame, cursor, &p.pos); + p.segs.push_back({ kR2VVideo, row, row + n, 1 }); + row += n; + } + + p.rows = row; + { + /* The blocks were appended as (t, h, w) triples; R_ROPE holds the axes apart, so lay the + * buffer planar now and staging is a copy. */ + std::vector tri = std::move(p.pos); + p.pos.assign((size_t)row * 3, 0.0f); + for (int64_t r = 0; r < row; ++r) { + p.pos[(size_t)r] = tri[(size_t)r * 3]; + p.pos[(size_t)row + r] = tri[(size_t)r * 3 + 1]; + p.pos[2 * (size_t)row + r] = tri[(size_t)r * 3 + 2]; + } + } + *out = std::move(p); + return 0; +} + +int ref2va_mod_rows(const Ref2VAPack& p, double t_v, double t_a, std::vector* out) { + std::vector uniq; + for (const Ref2VASeg& s : p.segs) + if (s.end > s.start) uniq.push_back(ref2va_t_label(s.kind, t_v, t_a)); + std::sort(uniq.begin(), uniq.end()); + uniq.erase(std::unique(uniq.begin(), uniq.end()), uniq.end()); + out->resize(p.segs.size()); + for (size_t i = 0; i < p.segs.size(); ++i) { + const Ref2VASeg& s = p.segs[i]; + if (s.end <= s.start) { (*out)[i] = 0; continue; } + const double lbl = ref2va_t_label(s.kind, t_v, t_a); + const size_t t_row = (size_t)(std::lower_bound(uniq.begin(), uniq.end(), lbl) - uniq.begin()); + (*out)[i] = (int)(t_row * 3 + (size_t)ref2va_seg_tag(s.kind)); + } + return 0; +} + +void ref2va_ada_cell(const Ref2VAPack& p, double t_v, double t_a, std::vector* md, + std::vector* trow) { + md->resize(p.segs.size()); + trow->resize(p.segs.size()); + for (size_t i = 0; i < p.segs.size(); ++i) { + const Ref2VASeg& s = p.segs[i]; + if (s.end <= s.start) { (*md)[i] = 0; (*trow)[i] = kR2VTVideo; continue; } + const int tag = ref2va_seg_tag(s.kind); + (*md)[i] = tag; + /* The modality fixes which stream's schedule the row reads; the label decides whether it + * reads that schedule's own timestep or, once the sampler has decayed below the kind's + * near-clean floor (ref2va_t_label is std::max, so the label is bit-identical to one of + * the two), the pinned row. Deciding by modality rather than by the bare label is what + * keeps video and audio apart when a probe happens to set t_v == t_a. */ + const double lbl = ref2va_t_label(s.kind, t_v, t_a); + if (tag == 2) (*trow)[i] = (lbl == t_a) ? kR2VTAudio : kR2VTPinAudio; + else (*trow)[i] = (lbl == t_v) ? kR2VTVideo : kR2VTPinVideo; + } +} + +} /* namespace minimaxh3 */ diff --git a/arch/minimaxh3/rad_ref2va_pack.h b/arch/minimaxh3/rad_ref2va_pack.h new file mode 100644 index 00000000..d498debb --- /dev/null +++ b/arch/minimaxh3/rad_ref2va_pack.h @@ -0,0 +1,118 @@ +/* minimaxh3 -- the Ref2VA packed sequence, on the host. + + * A reference-to-video-or-audio request packs more than the plain [text | soundtrack | video]: + * every reference photo, reference clip and soundtrack -- and a continuation's keyframes -- rides + * the DiT sequence as rows of its own, ahead of the streams being denoised. This TU decides WHERE + * those rows sit, what their (time, row, column) rotary coordinates are, which of them the sampler + * owns and which stay pinned, and therefore which modulation row each reads. It is pure host + * arithmetic -- no device, no core -- so it is unit-testable against the reference implementation's + * own numbers (tests/data/ref2va, docs/NOTE-P3-PACK.md). + + * The rules replicated here, in one breath: the sequence is + * [text | keyframe rows | reference blocks in request order | audio | video], + * the target timeline starts after every reference's time span (a first pass sums them), keyframes + * anchor onto that timeline at FRAME_RESCALE per pixel frame, a reference clip's audio rows pack + * immediately before its video rows sharing one time origin, pinned rows sit at a near-clean + * timestep with their modality's tag, and the two target segments -- always last, always the + * sampler's whole state -- ride the live timesteps. + */ + +#ifndef RAD_ARCH_MINIMAXH3_REF2VA_PACK_H +#define RAD_ARCH_MINIMAXH3_REF2VA_PACK_H + +#include +#include + +namespace minimaxh3 { + +/* Segment kinds, named as the reference implementation names them. */ +enum Ref2VAKind { + kR2VText = 0, /* the prompt's hidden states */ + kR2VCond, /* a keyframe's video latent rows */ + kR2VCondAudio, /* a keyframe's soundtrack latent rows */ + kR2VRefImg, /* a reference photo, or a reference clip's video */ + kR2VRefAudio, /* a reference clip's (or standalone audio's) soundtrack */ + kR2VAudio, /* the target soundtrack -- sampler-owned */ + kR2VVideo, /* the target video -- sampler-owned */ + kR2VKinds +}; + +/* The four reference part kinds the API admits. */ +enum Ref2VARefKind { kR2VRefImage = 0, kR2VRefAudioOnly = 1, kR2VRefVideo = 2, kR2VRefVideoAudio = 3 }; + +/* One keyframe: its latent frame index in the target (frame 0 anchors at the target timeline's + * origin) and the latent rows it carries, 0 where that stream is absent. */ +struct Ref2VAKeyframe { + int frame; /* resolved frame index, >= 0 */ + int video_t; /* latent frames of its video latent; <= 0 = none */ + int audio_t; /* audio latent frames of its soundtrack latent; <= 0 = none */ +}; + +/* One reference block, in latent units: h/w for the kinds that carry video (a photo's or clip's + * OWN latent sides -- the grid is the reference's, not the target's), audio_t for the kinds that + * carry sound. */ +struct Ref2VARef { + int kind; /* Ref2VARefKind */ + int lat_h, lat_w; + int latent_t; + int audio_t; +}; + +/* The target, in latent units. */ +struct Ref2VAGeom { + int latent_t, latent_h, latent_w, audio_t; +}; + +struct Ref2VASeg { + int kind; + int64_t start, end; /* rows [start, end) of the packed sequence */ + int update; /* 1: the sampler owns these rows (the two target streams) */ +}; + +struct Ref2VAPack { + std::vector segs; + int64_t rows = 0; + /* The rotary coordinates, PLANAR -- all times, then all rows, then all columns -- exactly the + * [3, rows] shape R_ROPE holds, so staging is a copy. */ + std::vector pos; +}; + +const char* ref2va_kind_name(int kind); +/* The modulation table's modality column a kind rides (the reference implementation's seg_tag): + * video-stream rows 0, text 1, every audio-stream row 2. */ +int ref2va_seg_tag(int kind); +/* Which latent space a kind's rows live in: img (cond/ref_img/video), audio (cond_audio/ + * ref_audio/audio), or neither (text). The sampler scatters the latents by these. */ +int ref2va_is_img(int kind); +int ref2va_is_audio(int kind); +/* The timestep label a kind carries at video/audio timesteps t_v/t_a: the streams their own, the + * pinned rows clamped to their near-clean floor. */ +double ref2va_t_label(int kind, double t_v, double t_a); +/* Per-segment modulation-table row, reference-implementation style: t_row * 3 + tag, where t_row + * indexes the sorted distinct labels actually present among the pack's non-empty segments. + * Empty segments (only possible for a degenerate target) get 0. */ +int ref2va_mod_rows(const Ref2VAPack& p, double t_v, double t_a, std::vector* out); + +/* Which timestep-embedding row a segment's modulation reads, once the reference pins are added to + * the streams' schedules. The embedding is laid [0,S) = the video schedule, [S,2S) = the audio + * schedule, [2S] = the visual pin, [2S+1] = the audio pin -- the two pinned rows the reference + * conditioning needs that the plain path leaves off. A segment reads the schedule row when its + * label IS the schedule's current timestep, and a pinned row only once the pin (its near-clean + * floor, ref2va_t_label) sits above the schedule's decaying timestep. */ +enum Ref2VATRow { kR2VTVideo = 0, kR2VTAudio = 1, kR2VTPinVideo = 2, kR2VTPinAudio = 3 }; +/* Per-segment modulation cell, as step_ada fills it for the current step's timesteps t_v/t_a: + * `md` is the modality's ada projection (== ref2va_seg_tag) and `trow` is the Ref2VATRow whose + * embedding feeds the cell. So the cell (md,trow) is exactly (kSegMod[e], {0 or S}) on a plain + * pack, and picks a pinned row for a reference row once its schedule falls under the pin. Empty + * segments (end <= start) get (0, kR2VTVideo) -- their cell is never read. */ +void ref2va_ada_cell(const Ref2VAPack& p, double t_v, double t_a, std::vector* md, + std::vector* trow); + +/* Lay the sequence out. Returns 0, or -1 on a negative dimension (the driver has already bounded + * media against the arch's ceilings; this only refuses nonsense). */ +int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector& keyframes, + const std::vector& refs, Ref2VAPack* out); + +} /* namespace minimaxh3 */ + +#endif diff --git a/arch/minimaxh3/rad_vae_geom.cpp b/arch/minimaxh3/rad_vae_geom.cpp new file mode 100644 index 00000000..73cb082f --- /dev/null +++ b/arch/minimaxh3/rad_vae_geom.cpp @@ -0,0 +1,90 @@ +/* Encode geometry, ported rule for rule from the reference VAEs (docs/NOTE-P2-ENCODE.md carries + * the line-referenced extraction; the golden vectors in tests/data/vae_geom are generated from the + * reference source itself -- including its real encoder runs, so the latent counts here are the + * network's own outputs, not a hand-derived formula). */ + +#include "rad_vae_geom.h" + +#include + +namespace minimaxh3 { + +/* Encode() for 2+ frames calls encode_temporal(): ceil(T/clip_length) clips, the short last one + * padded by repeating its final frame to a full clip (so every clip contributes exactly + * kVaeClipLatents latents -- the causal chain 17 -> ceil(17/2) -> ceil(9/2) = 5), concatenated, + * minus token_drop. A single image encodes alone and keeps its one latent (the chain at T=1 + * truncates its temporal taps and never downsamples below one frame). */ +int64_t vae_latent_frames(int64_t frames) { + if (frames <= 0) return -1; + if (frames == 1) return 1; + const int64_t clips = (frames + kVaeClipLength - 1) / kVaeClipLength; + return clips * kVaeClipLatents - kVaeTokenDrop; +} + +int64_t vae_clip_latents(int64_t frames) { + if (frames <= 0) return -1; + if (frames == 1) return 1; + return (frames + 3) / 4; /* ceil(ceil(T/2)/2) collapses to ceil(T/4) */ +} + +/* encode(): right_pad = ceil(L/hop)*hop - L samples of zeros, then the stride chain divides the + * padded length by the hop exactly (every strided conv k = 2s, p = ceil(s/2) is exact on lengths + * divisible by s, and the padded length is divisible by the product). */ +int64_t vae_audio_latents(int64_t samples) { + if (samples < 0) return -1; + return (samples + kAudioHop - 1) / kAudioHop; +} + +void vae_split_tiles(int64_t length, std::vector* out) { + out->clear(); + if (length <= kVaeTileSize) { + out->push_back({ 0, length, 0 }); + return; + } + /* Grow the window count until the minimum 64 px overlaps fit: each extra window adds 256 px + * of reach but one more overlap. */ + int64_t n = (length + kVaeTileSize - 1) / kVaeTileSize; + std::vector overlaps; + for (;;) { + overlaps.assign((size_t)(n - 1), kVaeTileOverlapMin); + int64_t sum = 0; + for (const int64_t o : overlaps) sum += o; + const int64_t remaining = kVaeTileSize * n - sum - length; + if (remaining < 0) { ++n; continue; } + /* Slack the overlaps leave is spread in latent-width (16 px) units, round-robin, so the + * windows reach exactly the end of the axis. */ + for (int64_t i = 0; i < remaining / kVaeRatio; ++i) + overlaps[(size_t)(i % (n - 1))] += kVaeRatio; + break; + } + int64_t start = 0; + for (int64_t i = 0; i < n; ++i) { + const int64_t len = std::min(kVaeTileSize, length - start); + const int64_t ov = i < n - 1 ? overlaps[(size_t)i] : 0; + out->push_back({ start, len, ov }); + if (i < n - 1) start += kVaeTileSize - overlaps[(size_t)i]; + } +} + +const double kVaeLatentsMean[24] = { + 0.858090341091156, -0.9606591463088989, 1.0661640167236328, -0.5090325474739075, + -0.2727581858634949, -1.3675414323806763, -0.2553254961967468, -0.26907554268836975, + -0.5376840829849243, -0.0464097298681736, 0.6657370328903198, 0.19690127670764923, + -0.5460608005523682, -0.4035342037677765, -0.23683024942874908, 0.25928452610969543, + -0.30133944749832153, 0.211341992020607, -1.1206848621368408, 0.3581933379173279, + -0.04225143790245056, 0.2604829967021942, 0.22864092886447906, 0.7056031823158264, +}; + +const double kVaePixelMean[3] = { 0.485, 0.456, 0.406 }; +const double kVaePixelStd[3] = { 0.229, 0.224, 0.225 }; + +const double kVaeLatentsStd[24] = { + 1.2223774194717407, 1.2767263650894165, 1.68317747116088865, 1.7549455165863037, + 1.5636216402053833, 2.194143533706665, 0.96531379222869875, 1.05698859691619875, + 0.841948926448822, 0.7729952931404114, 1.8955937623977661, 0.946841835975647, + 0.7996809482574463, 0.44988900423049925, 0.7197399735450745, 0.69362932443618775, + 2.961095094680786, 2.7694199085235595, 3.0496184825897215, 2.1088054180145265, + 3.276226282119751, 3.1627357006073, 2.28168129920959475, 2.6127843856811525, +}; + +} /* namespace minimaxh3 */ diff --git a/arch/minimaxh3/rad_vae_geom.h b/arch/minimaxh3/rad_vae_geom.h new file mode 100644 index 00000000..76c95a5d --- /dev/null +++ b/arch/minimaxh3/rad_vae_geom.h @@ -0,0 +1,77 @@ +/* Encode geometry for the MiniMax-H3 VAEs: how many latent frames an encode produces and where + * the spatial tiles sit. Pure host arithmetic -- no device, no weights. The kernels that actually + * run the encoders live in the P2 device work; this TU answers the sizing questions they and the + * driver ask ("how many latents will T frames give me", "which pixel window is tile k"), so the + * numbers can be pinned against the reference implementation without any GPU. docs/NOTE-P2-ENCODE.md + * carries the line-referenced extraction; tests/data/vae_geom are golden vectors generated from the + * reference's own code. */ + +#ifndef RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H +#define RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H + +#include +#include + +namespace minimaxh3 { + +/* Video VAE. Spatial downsamples prod(2,2,2,2,1,1) = 16, temporally the encode chain goes + * T -> ceil(T/2) -> ceil(T/2): 17 pixel frames become 5 latents (17 -> 9 -> 5). */ +constexpr int kVaeRatio = 16; /* pixels per latent side */ +constexpr int kVaeRatioT = 8; /* nominal pixel frames per latent (17-frame clips are off-by-one: first latent holds 1 frame) */ +constexpr int kVaeClipLength = 17; /* pixel frames per temporal clip */ +constexpr int kVaeClipLatents = 5; /* latents one full clip encodes to */ +constexpr int kVaeTokenDrop = 3; /* trailing latents every multi-clip encode drops */ +constexpr int kVaeTileSize = 256; /* reference "tile size", pixels, always on */ +constexpr int kVaeTileOverlapMin = 64; + +/* Audio VAE: encoder strides (2,4,4,5,5) -> one latent per 800 samples at 32 kHz (40/s), and its + * wrapper right-pads the waveform with zeros to a multiple of that before encoding. */ +constexpr int kAudioHop = 800; +constexpr int kAudioLatentChannels = 32; + +/* Latent frames an encode of `frames` pixel frames produces. A single image encodes alone and + * yields its one latent; two or more frames chunk into ceil(T/17) clips (the short last clip is + * padded by repeating its final frame), each yielding 5 latents, and the encode drops the last 3. + * Returns -1 for a non-positive frame count. */ +int64_t vae_latent_frames(int64_t frames); + +/* Latents one clip of `frames` pixel frames encodes to before any concatenation/drop: the causal + * chain is T -> ceil(T/2) -> ceil(T/2) (a single frame truncates its temporal taps and stays + * one). A full clip is 17 -> 9 -> 5, so this times the clip count minus the drop is exactly + * vae_latent_frames for T >= 2. */ +int64_t vae_clip_latents(int64_t frames); + +/* Audio latent frames an encode of `samples` samples produces (right zero-pad to the hop, then + * one latent per hop). Returns -1 for a negative sample count. */ +int64_t vae_audio_latents(int64_t samples); + +/* One axis of the spatial tiling. `start`/`len` are the pixel window the tile encoder receives + * (`len` is the real slice length -- the reference's Python slice clamps the nominal 256 at the + * tail); `overlap` is the pixel overlap this tile shares with the NEXT tile, which the blend cuts + * out of this tile's latents (`overlap / 16` latent columns/rows). */ +struct VaeTile { + int64_t start; + int64_t len; + int64_t overlap; +}; + +/* Port of the reference's split_tiles(): if one 256 window covers the axis, it does; otherwise + * the smallest window count whose overlaps (64 px minimum, extra 16 px units spread round-robin + * so the windows reach exactly the end) fit, starts cumulating 256 - overlap. The result covers + * [0, length) exactly whenever length is a multiple of 16 (the encoder's own alignment). */ +void vae_split_tiles(int64_t length, std::vector* out); + +/* The video latents' per-channel de-normalization constants, transcribed from + * comfy/ldm/minimax/vae.py (LATENTS_MEAN / LATENTS_STD, 24 channels): a normalized latent is + * (mean_moments - LATENTS_MEAN) / LATENTS_STD. */ +extern const double kVaeLatentsMean[24]; +extern const double kVaeLatentsStd[24]; + +/* Pixel normalization before the encoder: pixels in [-1,1] go through (x+1)/2, then per-channel + * (x - IMAGENET_MEAN) / IMAGENET_STD. */ +extern const double kVaePixelMean[3]; +extern const double kVaePixelStd[3]; + +} /* namespace minimaxh3 */ + +#endif diff --git a/core/build/startup.cpp b/core/build/startup.cpp index a901400d..f737a086 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -284,6 +284,21 @@ VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) { return ap ? ap->arch_video_positions : nullptr; } +VideoSegsFn rad_tools_video_segs(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_video_segs : nullptr; +} + +VideoPackFn rad_tools_video_pack(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_video_pack : nullptr; +} + +EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_encode_geom : nullptr; +} + const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) { const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); if (!ap || !ap->arch_audio_format) return nullptr; diff --git a/core/build/startup.h b/core/build/startup.h index 46eee91c..e4ce7930 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -99,6 +99,22 @@ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::s using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins); +/* The architecture plugin's video segment boundary table (rad_arch_video_segs), or null when it + * exports none -- the video driver then stages the plain table itself. */ +using VideoSegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t); +VideoSegsFn rad_tools_video_segs(const LoadedPlugins& plugins); + +/* The architecture plugin's reference-aware sequence layout (rad_arch_video_pack), or null + * when it exports none -- the driver then refuses requests carrying VAE references. */ +using VideoPackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*, + int64_t); +VideoPackFn rad_tools_video_pack(const LoadedPlugins& plugins); + +/* The architecture plugin's encode-pass geometry (rad_arch_encode_geom), or null when it + * exports none -- the driver then runs no encode pass. */ +using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t); +EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& plugins); + /* Run declare. * * `also` declares into the same builder after the architecture plugin, which is how the sampler diff --git a/core/engine.cpp b/core/engine.cpp index 9f40fcc5..f23afcb3 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1516,7 +1516,9 @@ int Engine::serve(std::unique_ptr watch) { std::vector gio; for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); auto d = std::make_unique(); - RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio)); + RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio, + rad_tools_video_segs(plugins_), rad_tools_video_pack(plugins_), + rad_tools_encode_geom(plugins_))); vid_gen_ = d.get(); gen_ = std::move(d); RAD_TRY(rad_dev_set(ranks_[0]->device)); @@ -2498,6 +2500,16 @@ int Engine::run_server() { in.upscale_max = vd.upscale_max; in.upscale_refine = vd.upscale_refine; in.max_lanes = vd.max_lanes; + in.max_ref_images = vd.max_ref_images; + in.max_ref_videos = vd.max_ref_videos; + in.max_ref_audios = vd.max_ref_audios; + in.encodes = vd.encodes; + in.max_enc_frames = vd.max_enc_frames; + in.max_enc_side = vd.max_enc_side; + in.max_enc_samples = vd.max_enc_samples; + in.enc_ratio = vd.enc_ratio; + /* A plugin that declares no ceilings leaves all three 0, and the server then serves + * ref2va as unimplemented — which is right until the generator can consume the bytes. */ video_bridge.drv = vid_gen_; d.videos = &video_bridge; if (cfg_.served_model_name.empty() && !in.name.empty()) { diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 705ffaf3..d05f957b 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -952,7 +952,17 @@ int Engine::declare() { decide("--max-model-len", std::to_string(cfg_.max_ctx), "a video generator: a step's rows"); } - if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + /* `auto` is left to the vision rule below, which keys on the container's + * `radiance.encoder`: a container converted with a vision tower's weights (a ref2va + * conditioning checkpoint) serves reference media through it, and one converted + * without them stays text-only. A video generator that carries no tower pays + * nothing for this: the rule resolves to 0 exactly as this branch used to. */ + if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) { + cfg_.mm_max_patches = pb.gen_patches; + decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches), + "a video generator: every reference media patch of one conditioning, " + "the pass size the plugin states"); + } if (cfg_.n_spec < 0) cfg_.n_spec = 0; cfg_.prefix_cache = false; } else if (pb.gen_rows > 0) { diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 43d66fd1..c8c8c3a1 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -1249,6 +1249,291 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) { return RAD_OK; } +/* PEFT exports wrap HF module paths in the name of the net the adapter trained: ai-toolkit spells + * a DiT module `diffusion_model.`, diffusers' wrappers `transformer.` or `unet.`. */ +static const char* const kLoraPrefixes[] = { "diffusion_model.", "transformer.", "unet." }; + +/* One `modules` rule of the map: the module pattern split at its single `*`, and the target + * patterns into which the matched run is substituted, in B-row order. */ +struct LoraRule { + bool star = false; + std::string pre, suf; + std::vector targets; + bool match(const std::string& m, std::string* tok) const { + if (!star) { + if (m != pre) return false; + tok->clear(); + return true; + } + if (m.size() < pre.size() + suf.size() || m.compare(0, pre.size(), pre) != 0) return false; + if (m.compare(m.size() - suf.size(), suf.size(), suf) != 0) return false; + *tok = m.substr(pre.size(), m.size() - pre.size() - suf.size()); + return !tok->empty(); + } +}; + +/* Read the map file: {"strip": [...], "modules": {"": ["", ...], ...}}. The module + * order is preserved (an nlohmann object keeps insertion order), so the first rule whose + * pattern matches a module wins. */ +static int lora_map_read(const std::string& file, std::vector* strip, + std::vector* rules) { + std::ifstream f(file); + if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; } + nlohmann::ordered_json j; + try { + j = nlohmann::ordered_json::parse(f); + } catch (const std::exception& e) { + RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what()); + return RAD_E_FORMAT; + } + if (!j.is_object()) { RAD_ERR("lora: --lora-map %s is not a JSON object", file.c_str()); + return RAD_E_FORMAT; } + if (j.contains("strip")) { + if (!j["strip"].is_array()) { RAD_ERR("lora: --lora-map 'strip' is not a list"); + return RAD_E_FORMAT; } + for (const auto& s : j["strip"]) { + if (!s.is_string()) { RAD_ERR("lora: --lora-map 'strip' holds a non-string"); + return RAD_E_FORMAT; } + strip->push_back(s.get()); + } + } + if (!j.contains("modules") || !j["modules"].is_object()) { + RAD_ERR("lora: --lora-map %s has no 'modules' object", file.c_str()); + return RAD_E_FORMAT; + } + for (const auto& [pat, t] : j["modules"].items()) { + if (!t.is_array() || t.empty()) { + RAD_ERR("lora: --lora-map rule '%s' is not a non-empty list", pat.c_str()); + return RAD_E_FORMAT; + } + const size_t star = pat.find('*'); + LoraRule r; + r.star = star != std::string::npos; + r.pre = r.star ? pat.substr(0, star) : pat; + r.suf = r.star ? pat.substr(star + 1) : ""; + for (const auto& x : t) { + if (!x.is_string()) { + RAD_ERR("lora: --lora-map rule '%s' holds a non-string target", pat.c_str()); + return RAD_E_FORMAT; + } + r.targets.push_back(x.get()); + } + rules->push_back(std::move(r)); + } + return RAD_OK; +} + +int Checkpoint::add_lora(const std::string& path, double strength, + std::vector* merged, const std::string* map_json) { + if (kind_ != SafeT) { + RAD_ERR("lora: an adapter merges into a safetensors source; %s is not one", path_.c_str()); + return RAD_E_UNSUPPORTED; + } + if (import_ != Import::None) { + RAD_ERR("lora: this checkpoint ships its weights packed by a quantiser; an adapter merges " + "into the plain tensors its training saw, not into the codes"); + return RAD_E_UNSUPPORTED; + } + std::vector files; + std::error_code ec; + if (std::filesystem::is_directory(path, ec)) { + for (const auto& e : std::filesystem::directory_iterator(path, ec)) + if (e.path().extension() == ".safetensors") files.push_back(e.path().string()); + std::sort(files.begin(), files.end()); + } else + files.push_back(path); + if (files.empty()) { + RAD_ERR("lora: %s holds no .safetensors file", path.c_str()); + return RAD_E_NOTFOUND; + } + + /* The module lookup strips wrapper prefixes: the map's first, then the builtin ones. */ + std::vector strips; + std::vector rules; + if (map_json && lora_map_read(*map_json, &strips, &rules) < 0) return RAD_E_FORMAT; + for (const char* pre : kLoraPrefixes) strips.push_back(pre); + + /* One pair's A/B/alpha, by module; `module` keeps the wrapper prefix, so the lookup below + * strips it. */ + struct Pair { std::string module; const StTensor *a = nullptr, *b = nullptr, *al = nullptr; }; + + int n_merged = 0; + for (const std::string& f : files) { + SafeTensorsFile st; + if (st.open(f) != RAD_OK) return RAD_E_FORMAT; + std::vector pairs; + std::map by_module; + for (const StTensor& t : st.tensors()) { + if (t.name.size() > 12 && t.name.compare(t.name.size() - 12, 12, ".dora.scalar") == 0) { + RAD_ERR("lora: '%s' is a DoRA adapter; only plain LoRA merges (a magnitude vector " + "has no place in a weight merge)", t.name.c_str()); + return RAD_E_UNSUPPORTED; + } + const char* suf = nullptr; + if (t.name.size() > 14 && t.name.compare(t.name.size() - 14, 14, ".lora_A.weight") == 0) + suf = ".lora_A.weight"; + else if (t.name.size() > 18 && + t.name.compare(t.name.size() - 18, 18, ".lora_down.weight") == 0) + suf = ".lora_down.weight"; + if (suf) { + Pair p; + p.module = t.name.substr(0, t.name.size() - std::strlen(suf)); + p.a = &t; + by_module[p.module] = pairs.size(); + pairs.push_back(std::move(p)); + } else if (t.name.size() > 14 && + t.name.compare(t.name.size() - 14, 14, ".lora_B.weight") == 0) { + auto it = by_module.find(t.name.substr(0, t.name.size() - 14)); + if (it != by_module.end()) pairs[it->second].b = &t; + } else if (t.name.size() > 6 && + t.name.compare(t.name.size() - 6, 6, ".alpha") == 0) { + auto it = by_module.find(t.name.substr(0, t.name.size() - 6)); + if (it != by_module.end()) pairs[it->second].al = &t; + } + } + if (pairs.empty()) { + RAD_ERR("lora: %s holds no .lora_A.weight / .lora_down.weight tensors", f.c_str()); + return RAD_E_NOTFOUND; + } + for (Pair& p : pairs) { + if (!p.b) { + RAD_ERR("lora: '%s' ships its A but no B", p.module.c_str()); + return RAD_E_FORMAT; + } + /* The targets, in merge order: `.weight`, then the same under each + * prefix-stripped spelling (the module never carries its `.weight` -- PEFT names the + * module, the target adds it), then the first map rule the stripped module matches, + * whose target patterns name one or several tensors the fused module was trained as. + * The first spelling the checkpoint holds wins. */ + std::string norm = p.module; + for (const std::string& s : strips) + if (norm.size() > s.size() && norm.compare(0, s.size(), s) == 0) { + norm.erase(0, s.size()); + break; + } + std::vector tg; + if (const SrcTensor* W = find(p.module + ".weight")) tg.push_back(W); + if (tg.empty() && norm != p.module) + if (const SrcTensor* W = find(norm + ".weight")) tg.push_back(W); + for (const LoraRule& ru : rules) { + std::string tok; + if (!ru.match(norm, &tok)) continue; + for (const std::string& pat : ru.targets) { + std::string nm = pat; + const size_t star = nm.find('*'); + if (star != std::string::npos) nm.replace(star, 1, tok); + const SrcTensor* W = find(nm); + if (!W) { + RAD_ERR("lora: the map maps '%s' onto '%s', which this checkpoint does " + "not ship", p.module.c_str(), nm.c_str()); + return RAD_E_NOTFOUND; + } + tg.push_back(W); + } + break; + } + if (tg.empty()) { + RAD_ERR("lora: '%s' names a module this checkpoint does not ship as " + "'.weight' (nor stripped of a known wrapper prefix)%s", + p.module.c_str(), + map_json ? " and no --lora-map rule matches it" : ""); + return RAD_E_NOTFOUND; + } + const StTensor& A = *p.a; + const StTensor& B = *p.b; + if (A.shape.size() != 2 || B.shape.size() != 2 || A.shape[0] <= 0 || + A.shape[0] != B.shape[1]) { + RAD_ERR("lora: '%s' is not a rank-%lld pair of matrices: [a %lld x %lld, " + "b %lld x %lld]", + p.module.c_str(), (long long)A.shape[0], (long long)A.shape[0], + (long long)A.shape[1], (long long)B.shape[0], (long long)B.shape[1]); + return RAD_E_FORMAT; + } + const auto plain = [](uint32_t d) { + return d == RAD_BF16 || d == RAD_F16 || d == RAD_F32; + }; + if (!plain(A.dtype) || !plain(B.dtype)) { + RAD_ERR("lora: '%s' ships A/B in dtypes the merge cannot read", p.module.c_str()); + return RAD_E_UNSUPPORTED; + } + const int64_t K = A.shape[1], r = A.shape[0]; + int64_t rows = 0; + for (const SrcTensor* W : tg) { + if (W->gptq_bits || W->ct_group || W->rad_dtype == RAD_DT_INVALID || + !plain(W->rad_dtype)) { + RAD_ERR("lora: '%s' is not a plain bf16/f16/f32 matrix, so an adapter cannot " + "merge into it", W->name.c_str()); + return RAD_E_UNSUPPORTED; + } + if (W->shape.size() != 2 || W->shape[1] != K) { + RAD_ERR("lora: '%s' [a %lld x %lld, b %lld x %lld] does not fit '%s' " + "[%lld x %lld]", + p.module.c_str(), (long long)A.shape[0], (long long)A.shape[1], + (long long)B.shape[0], (long long)B.shape[1], W->name.c_str(), + (long long)W->shape[0], (long long)W->shape[1]); + return RAD_E_FORMAT; + } + rows += W->shape[0]; + } + if (rows != B.shape[0]) { + RAD_ERR("lora: '%s' merges into %zu target(s) whose rows sum to %lld, but its B " + "has %lld", p.module.c_str(), tg.size(), (long long)rows, + (long long)B.shape[0]); + return RAD_E_FORMAT; + } + float scale = (float)strength; + if (p.al) { + const int64_t n_el = p.al->shape.empty() ? 1 : p.al->numel(); + if (n_el != 1 || (p.al->dtype != RAD_F32 && p.al->dtype != RAD_BF16 && + p.al->dtype != RAD_F16)) { + RAD_ERR("lora: '%s.alpha' is not a single number", p.module.c_str()); + return RAD_E_FORMAT; + } + scale *= rad_load_f32(p.al->data, p.al->dtype, 0) / (float)r; + } + /* The module is the targets' concatenation, so B's rows split along them in listed + * order: target i takes rows [off, off + N_i) as its own. + * + * Row at a time, rank-1 updates into an f32 row buffer. A is copied to f32 once per + * pair (r rows -- a few KiB to a few MiB): the rank sweep then reads plain f32 + * contiguously against the accumulator, which is what the compiler vectorises and + * the cache wants; paying rad_load_f32's dtype switch per element instead made the + * real 416-pair merge an hour of scalar work. The same f32 sums as the textbook + * order, up to the rounding of the accumulation itself, which the bf16 cast + * swallows. */ + std::vector Af((size_t)(r * K)); + for (int64_t i = 0; i < r * K; ++i) Af[(size_t)i] = rad_load_f32(A.data, A.dtype, i); + std::vector acc((size_t)K); + int64_t off = 0; + for (const SrcTensor* W : tg) { + const int64_t N = W->shape[0]; + auto out = std::make_unique((size_t)W->bytes); + for (int64_t n = 0; n < N; ++n) { + for (int64_t j = 0; j < r; ++j) { + const float b = scale * rad_load_f32(B.data, B.dtype, (off + n) * r + j); + if (b == 0.f) continue; + const float* ar = Af.data() + (size_t)j * K; + for (int64_t k = 0; k < K; ++k) acc[(size_t)k] += b * ar[k]; + } + for (int64_t k = 0; k < K; ++k) + rad_store_f32(out.get(), W->rad_dtype, n * K + k, + rad_load_f32(W->data, W->rad_dtype, n * K + k) + + acc[(size_t)k]); + std::fill(acc.begin(), acc.end(), 0.f); + } + SrcTensor& t = tensors_[index_[W->name]]; + t.data = out.get(); + owned_.push_back(std::move(out)); + if (merged) merged->push_back(t.name); + ++n_merged; + off += N; + } + } + } + RAD_INFO("lora %s: %d tensor(s) merged at strength %g", path.c_str(), n_merged, strength); + return RAD_OK; +} + const SrcTensor* Checkpoint::find(const std::string& n) const { auto it = index_.find(n); return it == index_.end() ? nullptr : &tensors_[it->second]; diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 72e20805..517553de 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -121,6 +121,31 @@ public: * tensors and config.json keys under `draft.`. */ int add_draft(const std::string& dir, const std::string& prefix); + /* Merge PEFT adapters into the tensors they name, before anything reads the checkpoint: + * `path` is a .safetensors file or a directory of them, holding `.lora_A.weight` + * [r,K] / `.lora_B.weight` [N,r] pairs (ComfyUI's `.lora_down`/`.lora_up` spellings + * read too), with an optional `.alpha` scalar -- the module never carries its own + * `.weight`. The target is `.weight`, looked up under that name and, failing that, + * after stripping a wrapper prefix ("diffusion_model.", "transformer.", "unet."); + * a module the checkpoint does not ship is + * a refusal naming it, since a merge that silently hits nothing is a different model. The + * merge is the PEFT one, in f32: W += strength * (alpha/r where an .alpha states one, else 1) + * * B @ A, cast back to the target's dtype. Targets must be plain bf16/f16/f32 matrices -- + * an adapter cannot merge into a quantised export or a non-matrix. Call this right after + * open(): it re-points a merged tensor's bytes, and views taken before it would read the + * unmerged ones. `merged` receives each target's name. + * + * `map_json` (null = none) names a file holding per-architecture module rules for adapters + * trained against a module layout the checkpoint does not spell -- a fused qkv, renamed blocks: + * `{"strip": ["prefix."], "modules": {"": ["", ...]}}`, where a + * `*` in a module pattern matches one run of characters (the block index) and the same run + * fills every `*` in that rule's target patterns. Several targets share one delta: the + * module is the concatenation, so B's rows split along the targets in the order listed, + * each taking its own row count (they must sum to B's rows). A rule whose target the + * checkpoint lacks is a refusal, never a miss -- the rule says the tensor is there. */ + int add_lora(const std::string& path, double strength, std::vector* merged, + const std::string* map_json = nullptr); + const SrcTensor* find(const std::string& n) const; const std::vector& tensors() const { return tensors_; } bool is_gguf() const { return kind_ == Gguf; } diff --git a/core/gen/video.h b/core/gen/video.h index efd4928b..dbff49ae 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -8,6 +8,7 @@ */ #pragma once #include "rad_core.h" +#include "mm/processor.h" #include #include @@ -71,6 +72,37 @@ private: std::string why_; }; +/* One file of a reference-conditioned request (task "ref2va"): an image or a video that + * conditions identity and motion, a video's separately-given soundtrack, or a standalone audio. + * The server reads the parts' bytes, bounds them and orders them; decoding them and turning + * them into conditioning rows is the generator's. `index` is the part's 1-based number within + * its kind, which fixes its slot in the conditioning; VIDEO_AUDIO #i is the soundtrack of + * VIDEO #i. */ +struct VideoRefMedia { + enum Kind : int32_t { IMAGE = 0, VIDEO = 1, VIDEO_AUDIO = 2, AUDIO = 3 }; + Kind kind = IMAGE; + int32_t index = 0; + std::string name, filename, content_type; /* the part's name and what the client called the file */ + std::string data; /* the file's bytes */ + + /* The reference in the encoder's own form, prepared by the server (which owns the decoder) so + * the driver stages bytes without ever touching a codec. The VAE encode pass reads exactly + * these; they are empty until the server decodes the part. IMAGE/VIDEO fill the pixels, + * AUDIO/VIDEO_AUDIO the samples. + * enc_pixels: f32 [enc_frames][enc_h][enc_w][3] row-major RGB in 0..255, UN-normalised — + * the video VAE applies ImageNet mean/std itself. Each side is snapped down to a multiple + * of the VAE's spatial ratio and capped at the declaration's max_enc_side, aspect kept, + * because our encoder runs one volume and cannot tile the way the reference does. For a + * still image enc_frames is 1. + * enc_samples: f32 [enc_channels][enc_n] channel-major, each channel right-padded with + * zeros out to a whole number of hops (geom entry 0), at the model's audio rate. */ + std::vector enc_pixels; + int32_t enc_frames = 0, enc_h = 0, enc_w = 0; + std::vector enc_samples; + int64_t enc_n = 0; + int32_t enc_channels = 0; +}; + struct VideoRequest { std::vector tokens; /* the prompt, rendered and tokenised */ int32_t width = 0, height = 0; /* pixels, within the declaration's limits */ @@ -81,6 +113,17 @@ struct VideoRequest { double upscale = 0.0; int32_t refine = 0; uint64_t seed = 0; + /* Reference conditioning, sorted by (kind, index); empty for a text-only request. The bytes + * are the VAE's (P2): reference videos and audios become conditioning rows through the + * video/audio VAEs, not the TE. */ + std::vector refs; + /* The references' TE view: every image and video reference processed to patches, placed in + * `tokens` at their presentation markers, with the M-RoPE layout over the whole conditioning + * (§3's presentation order). The server decodes and processes; the driver stages it into the + * conditioning pass's encoder fields (RadBatch::enc_* / rope_pos / mm_rows) exactly as the + * image generator's driver does. Null for a request whose references carry nothing the TE + * sees — audios are label-only, and a text-only request has none. */ + std::shared_ptr media; std::shared_ptr ticket; }; diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 08f28d25..fe0a3269 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -141,16 +141,26 @@ namespace { constexpr int64_t kAlign = 256; +/* The most segment boundaries R_SEG holds: the plain presentation has four, and a full + * reference-conditioned one (text, a keyframe pair, two segments for every reference at the + * server's 9/3/3 caps, the two target streams) stays well under this. The plugin's pack is the + * only source once references ride; the VSA kernels take the count from the staged rows and + * accept up to 4096. */ +constexpr int64_t kSegCap = 64; + int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } /* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the - * allocation and the VRAM budget. */ -int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) { + * allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and + * patch width (RadBuildCtx::max_enc_patches, RadEncoderDecl::patch_dim), 0 and 0 without a + * vision encoder: the media regions then hold nothing. */ +int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd, + int64_t (*bytes)[2], int n) { const int64_t want[] = { d.max_text * 4, /* R_TOK */ d.max_text * 4, /* R_POS */ 2 * 4, /* R_CU */ - 3 * max_tok * 4, /* R_ROPE: a step's rotary positions */ + 3 * max_tok * 4, /* R_ROPE: a step's rotary positions, a conditioning's [3,T] M-RoPE */ RAD_VGEOM_N * 4, /* R_GEOM */ 6 * 4, /* R_SCHED */ d.max_steps * 4, /* R_TV */ @@ -158,9 +168,19 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in 4 * 4, /* R_SEED */ 4, /* R_LANE */ 4, /* R_FIRST */ - 4 * 4, /* R_SEG */ + kSegCap * 4, /* R_SEG: the pack's boundary table, widened for references */ 4 * 4, /* R_LAT */ 4, /* R_UP */ + d.max_text * 4, /* R_MMROW: the media rows, one per placeholder token */ + ep * pd * 2, /* R_ENCPIX: [ep, pd] bf16 */ + 4 * ep * 4, /* R_ENCCRD: [4, ep] i32 component-major */ + (ep + 2) * 4, /* R_ENCCU: segment boundaries; a segment is at least one patch */ + /* The VAE encode staging: one media item's pixels or samples and its encode geometry, + * sized to the declaration's per-pass ceilings so a single pass holds any media the + * export accepts. All 0 without the encoders (decl.encodes 0 leaves the ceilings 0). */ + d.max_enc_frames * d.max_enc_side * d.max_enc_side * 3 * 4, /* R_ENCPX: [f,h,w,3] f32 */ + d.max_enc_samples * d.audio_channels * 4, /* R_ENCSM: [ch,n] f32 */ + 25 * 4, /* R_ENCG: rad_arch_encode_geom's 25 i32 (the video geom) */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -184,14 +204,26 @@ int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) { } /* namespace */ +/* The conditioning encoder's staging bounds: a program with no declared vision encoder stages + * no media, and the driver refuses requests that carry any. */ +namespace { +void encoder_bounds(const Program& prog, int64_t* ep, int64_t* pd) { + *ep = prog.encoder.modalities != 0 ? prog.ctx.max_enc_patches : 0; + *pd = prog.encoder.modalities != 0 ? prog.encoder.patch_dim : 0; +} +} /* namespace */ + int64_t VideoDriver::device_bytes(const Program& prog) { if (!prog.is_video_generator()) return 0; + int64_t ep = 0, pd = 0; + encoder_bounds(prog, &ep, &pd); int64_t b[R_N][2]; - return carve(prog.video_gen, prog.ctx.max_tok, b, R_N); + return carve(prog.video_gen, prog.ctx.max_tok, ep, pd, b, R_N); } int VideoDriver::init(const Program& prog, PositionsFn positions, - const std::vector& ranks) { + const std::vector& ranks, SegsFn segs, PackFn pack, + EncodeGeomFn enc_geom) { fini(); if (!prog.is_video_generator()) return RAD_E_STATE; decl_ = prog.video_gen; @@ -200,7 +232,11 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, name_ = prog.vgen_str.name; ranks_ = ranks; positions_ = positions; + segs_ = segs; + pack_ = pack; + enc_geom_ = enc_geom; max_tok_ = prog.ctx.max_tok; + encoder_bounds(prog, &max_enc_, &patch_dim_); if (!positions_) { RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a " "video generator must", name_.c_str()); @@ -212,7 +248,7 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, return RAD_E_UNSUPPORTED; } int64_t b[R_N][2]; - bytes_ = carve(decl_, max_tok_, b, R_N); + bytes_ = carve(decl_, max_tok_, max_enc_, patch_dim_, b, R_N); for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; } frames_bytes_ = frames_bytes_of(decl_); @@ -275,6 +311,32 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { if (T < 1 || T > d.max_text) return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." + std::to_string(d.max_text)); + /* Reference conditioning: the images reach the language model through `media`, which the + * server built from the parts (gen/video.h) and build_cond stages into the conditioning + * pass. What this generator cannot consume yet is anything whose bytes reach the model + * through a VAE — a reference video's frames, a soundtrack, a standalone audio. Those are + * refused naming the part, rather than silently made into a weaker video. */ + if (!r->refs.empty() && max_enc_ == 0) + return no("this container was converted without its vision tower, so no request can " + "carry reference media"); + for (const VideoRefMedia& m : r->refs) + if (m.kind != VideoRefMedia::IMAGE) + return no("'" + m.name + "' is not consumed yet: reference videos and audios reach " + "the model through the video and audio VAEs, which the video path does not " + "run in this build; only ref_image_N parts condition a generation today"); + if (!r->refs.empty() && !r->media) + return no("the request carries reference images but no processed media to condition on"); + if (r->media) { + int64_t n_patch = 0; + for (const mm::Placed& p : r->media->items) { + if ((int64_t)p.tok + (int64_t)p.item->expand.size() > T) + return no("a reference's placeholder run is placed past the end of the prompt"); + n_patch += p.item->n_patch; + } + if (n_patch > max_enc_) + return no("the references are " + std::to_string(n_patch) + " patches; this model " + "encodes at most " + std::to_string(max_enc_) + " in one pass"); + } if (r->chunks < d.min_chunks || r->chunks > d.max_chunks) return no("the length must be " + std::to_string(d.min_chunks) + ".." + std::to_string(d.max_chunks) + " chunks"); @@ -303,19 +365,108 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { j->geom.lat_h = s.lat_h; j->geom.lat_w = s.lat_w; j->geom.n_audio = s.n_audio; - j->rows = T + s.audio_rows + s.video_rows; - if (j->rows > max_tok_) - return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass " - "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video"); - const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0); + /* The pack's reference table (RadVideoGenBatch::ref_tab): every reference the DiT conditions + * on, in presentation order, in ITS OWN latent grid -- {kind, slot, h, w, frames, audio} six + * words after the reference and keyframe counts. A picture's grid is the encoder's sides over + * the VAE ratio, one latent frame, no soundtrack; its slot is the one its Vencode pass folds + * its latents into. It must exist before the step layout is decided, because when the denoiser + * consumes it the reference rows are part of that layout. Only pictures queue today (videos and + * audios are refused at submit above until their decode paths land), so the keyframe count + * stays 0 and the table holds only picture rows. */ + if (d.encodes) + for (size_t i = 0; i < r->refs.size(); ++i) { + const VideoRefMedia& m = r->refs[i]; + if (m.kind != VideoRefMedia::IMAGE) continue; + if (m.enc_pixels.empty()) + return no("'" + m.name + "' was not prepared for the video encoder"); + if (m.index < 1) + return no("'" + m.name + "' has no slot in the conditioning"); + if (d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio || + m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio) + return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) + "x" + + std::to_string(m.enc_w) + ") the VAE grid of " + + std::to_string(d.enc_ratio) + " does not divide"); + j->enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i}); + if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */ + ++j->ref_tab[0]; + j->ref_tab.insert(j->ref_tab.end(), + {0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio), + (int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/, + 0 /*no soundtrack*/}); + } + /* The step's packed sequence. When the denoiser consumes the reference table the pack is the + * only source of its rows, segment boundaries and positions -- the reference rows sit between + * the text and the target streams, so the plain `text + audio + video` arithmetic and the plain + * position layout no longer describe it. rad_arch_video_pack returns the total rows and, when + * roomy, the boundaries and the full [3, rows] planar RoPE in one call. Otherwise the plain + * layout is computed exactly as before, and a staged reference table (if any) rides inert. */ const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0); - if (nr != j->rows || nd <= 0 || nd > max_tok_) - return no("the model lays this video out in " + std::to_string(nr) + " step rows and " + - std::to_string(nd) + " decoder rows, which this server cannot run"); + if (nd <= 0 || nd > max_tok_) + return no("the model lays this video's decoder in " + std::to_string(nd) + " rows, which " + "this server cannot run"); j->dec_rows = nd; - j->pos.assign((size_t)(3 * nr), 0.0f); - if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr) - return no("the model could not lay this video out"); + if (d.ref_rows && !j->ref_tab.empty()) { + if (r->upscale > 1.0) + return no("reference conditioning does not yet combine with latent upscale; ask for " + "the size you want without latent_upscale"); + if (!pack_) + return no("the generator says it conditions on references but exports no " + "rad_arch_video_pack"); + const int64_t pr = pack_(&j->geom, j->ref_tab.data(), nullptr, 0, nullptr, 0); + if (pr <= 0) + return no("the model refused the reference conditioning layout"); + if (pr > max_tok_) + return no("a conditioned step is " + std::to_string(pr) + " rows and a pass carries " + + std::to_string(max_tok_) + "; ask for a shorter or smaller video, or fewer " + "references"); + j->seg.assign((size_t)kSegCap, 0); + j->pos.assign((size_t)(3 * pr), 0.0f); + if (pack_(&j->geom, j->ref_tab.data(), j->seg.data(), kSegCap, j->pos.data(), 3 * pr) != pr) + return no("the model could not lay the reference conditioning out"); + int nseg = -1; + for (int k = 0; k < kSegCap; ++k) + if (j->seg[(size_t)k] == (int32_t)pr) { nseg = k + 1; break; } /* video grid ends here */ + if (nseg < 0 || nseg > kSegCap) + return no("the reference conditioning layout has no closing segment boundary"); + j->seg.resize((size_t)nseg); + j->nseg = nseg; + /* The denoiser lays out one modulation cell per segment and its table is a fixed width the + * arch declares; a pack wider than it would abort the step mid-generation and take the + * engine with it. Refuse here, at submit, where a clean answer is still possible. */ + const int nsegs = nseg - 1; /* `seg` is boundaries: one more than the segments */ + if (d.max_ref_segs > 0 && nsegs > d.max_ref_segs) { + const int nrefs = j->ref_tab.empty() ? 0 : j->ref_tab[0]; + const int64_t fit = (int64_t)d.max_ref_segs - (nsegs - nrefs); /* the fixed non-ref cells */ + return no("these references lay the conditioning out in " + std::to_string(nsegs) + + " sequence segments but this deployment's conditioning table holds " + + std::to_string(d.max_ref_segs) + ", so at most " + + std::to_string(fit < 0 ? 0 : (int)fit) + " fit -- ask for fewer references"); + } + /* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode, + * audio, upscale) stages its own segment table and target counts from it and must see the + * bytes it sees today. Only build_step runs at the widened `step_rows`. */ + j->rows = T + s.audio_rows + s.video_rows; + j->step_rows = pr; + /* The last segment (the video target) runs [seg[nseg-2], seg[nseg-1]); seg[nseg-1] is the + * total rows, so the video start is the boundary before it -- the same one the VSA takes as + * its video base (it works in segments, one fewer than the boundaries it is handed). */ + j->lat_v = pr - j->seg[(size_t)(nseg - 2)]; + j->lat_a = decl_.audio_channels * (int64_t)j->geom.n_audio; + j->ref_wide = true; + } else { + j->rows = T + s.audio_rows + s.video_rows; + if (j->rows > max_tok_) + return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass " + "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video"); + const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0); + if (nr != j->rows) + return no("the model lays this video out in " + std::to_string(nr) + " step rows, " + "which this server cannot run"); + j->pos.assign((size_t)(3 * nr), 0.0f); + if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr) + return no("the model could not lay this video out"); + j->step_rows = j->rows; + } j->sched = video_schedule(d, steps); if (j->sched.steps < 1) return no("the schedule has no steps"); if (r->upscale > 1.0) { @@ -357,6 +508,17 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { } j->n_chunks = r->chunks; j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate); + /* The reference table and the VAE encode queue were built above, before the step layout was + * chosen: each reference picture the server decoded into encoder form rides one Vencode pass, + * at the slot its index numbers within pictures -- the slot the encoder folds its latents into + * and the step's pack scatters them from. Reference videos and audios are refused above until + * their decode paths land, so only pictures are queued and the keyframe count stays 0. */ + /* The soundtrack's length, exactly the samples the decode will hand the encoder — the + * number a caller that chains clips against an audio floor checks. A build without + * libavcodec never gets the muxed file to read it back from, so it is logged here. */ + RAD_INFO("video: soundtrack %.2f s, %lld samples at %lld Hz x %lld ch", + (double)j->n_samples / d.sample_rate, (long long)j->n_samples, + (long long)d.sample_rate, (long long)d.audio_channels); VideoTicket& t = *r->ticket; t.frames = s.frames; @@ -367,7 +529,7 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { t.channels = d.audio_channels; t.fps = (double)d.fps_num / (double)d.fps_den; t.in_tokens = T; - t.rows = j->rows; + t.rows = j->step_rows; /* the conditioned step's real length, references included */ t.t_submit_ns = (int64_t)rad_mono_ns(); std::lock_guard lk(mu_); if (closed_) { @@ -445,7 +607,8 @@ int VideoDriver::upload() { /* The geometry a pass's ops read off the device (RAD_VGEOM_*) for a pass at geometry `g` of * `rows` step rows, with chunk `chunk`'s span when it is a decode's and both grids when the job * upscales. */ -void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk) { +void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk, + bool ref_step) { int32_t* g = hptr(R_GEOM); std::memset(g, 0, RAD_VGEOM_N * 4); g[RAD_VGEOM_LAT_FRAMES] = g0.lat_frames; @@ -473,15 +636,47 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up); } reg_[R_GEOM].used = RAD_VGEOM_N * 4; + const bool wide = j.ref_wide && ref_step; const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio; - const int64_t video_rows = rows - g0.n_text - audio_rows; + /* With references riding, the sampler owns only the target video rows -- not the reference + * rows the pack placed ahead of them -- so the target count is the pack's, not the plain + * rows-minus-text-minus-audio. The audio target is the whole soundtrack either way. */ + const int64_t video_rows = wide ? j.lat_v : rows - g0.n_text - audio_rows; *hptr(R_LANE) = j.lane; *hptr(R_FIRST) = j.step == 0; int32_t* seg = hptr(R_SEG); - seg[0] = 0; - seg[1] = g0.n_text; - seg[2] = (int32_t)(g0.n_text + audio_rows); - seg[3] = (int32_t)rows; + if (wide) { + /* The pack laid the reference rows out ahead of the target streams, video grid last. Stage + * its boundaries verbatim: the VSA derives its segment count from the operand length, so + * every reference becomes a dense prefix sink with no kernel change. Only the step pass + * stages this table; the decode, encode and upscale passes stage the plain layout below. */ + std::memcpy(seg, j.seg.data(), j.seg.size() * sizeof(int32_t)); + reg_[R_SEG].used = (int64_t)j.seg.size() * 4; + } else { + /* The pack lays the segments out (rad_arch_video_segs, or the reference-aware + * rad_arch_video_pack once refs ride); for a plain request its table is the one computed + * below, so a plugin without the exports -- or one whose table disagrees with this + * geometry -- stages the same bytes either way. The pack answers with the rows, not a + * count, so a poison word at the fifth slot is what proves a plain table has no entries + * past the fourth: a pack that writes past it disagrees with this geometry. */ + bool packed = false; + if (pack_) { + seg[4] = -1; + const int64_t pr = pack_(&g0, nullptr, seg, kSegCap, nullptr, 0); + packed = pr == rows && seg[4] == -1 && seg[0] == 0 && seg[1] == g0.n_text && + seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows; + } else if (segs_) { + packed = segs_(&g0, seg, 4) == 4 && seg[0] == 0 && seg[1] == g0.n_text && + seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows; + } + if (!packed) { + seg[0] = 0; + seg[1] = g0.n_text; + seg[2] = (int32_t)(g0.n_text + audio_rows); + seg[3] = (int32_t)rows; + } + reg_[R_SEG].used = 4 * 4; + } int32_t* lat = hptr(R_LAT); lat[0] = 0; lat[1] = (int32_t)video_rows; @@ -489,7 +684,6 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, lat[3] = (int32_t)audio_rows; reg_[R_LANE].used = 4; reg_[R_FIRST].used = 4; - reg_[R_SEG].used = 4 * 4; reg_[R_LAT].used = 4 * 4; } @@ -529,6 +723,7 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to V.dec_rows = j.dec_rows; V.n_samples = j.n_samples; V.upscale = dptr(ri, R_UP); + V.ref_tab = j.ref_tab.empty() ? nullptr : j.ref_tab.data(); B.vgen_b = &V; } } @@ -559,12 +754,20 @@ const RadBatch* VideoDriver::next(int step) { if (!j.audio_done) return build_audio(j, step); if (j.chunk < j.n_chunks) return build_chunk(j, step); } - /* 2. A prompt. */ + /* 2. A VAE encode of a reference-conditioned lane's media, before its prompt: one pass per + * reference, so the encoder's latents are in the lane's slot rows by the time the prompt + * and its steps run (the step's pack scatters them into the sequence). */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed || j.cond_done) continue; + if (j.enc_next < j.enc_q.size()) return build_encode(j, step); + } + /* 3. A prompt. */ for (auto& jp : jobs_) { Job& j = *jp; if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step); } - /* 3. The oldest lane's next step, or its upscale once its small steps are done. */ + /* 4. The oldest lane's next step, or its upscale once its small steps are done. */ for (auto& jp : jobs_) { Job& j = *jp; if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue; @@ -602,8 +805,76 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { reg_[R_TA].used = j.sched.steps * 4; const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom; stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0); + + /* Reference media for the tower and the conditioning's M-RoPE, staged exactly as the image + * driver stages a conditioned prompt (core/gen/driver.cpp's build_cond). R_ROPE holds the + * [3,T] i32 grid here and a step's f32 positions in build_step — never both in one pass, and + * step_cond reads rope_pos instead of positions when it is set. */ + int64_t n_patch = 0, n_seg = 0, n_mm = 0; + int32_t max_seg = 0; + if (j.req->media) { + const mm::PromptMedia& pm = *j.req->media; + int32_t* rope = hptr(R_ROPE); + for (int64_t i = 0; i < T; ++i) { + int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i }; + pm.rope.at(i, p3); + rope[i] = p3[0]; + rope[T + i] = p3[1]; + rope[2 * T + i] = p3[2]; + } + reg_[R_ROPE].used = 3 * T * 4; + int64_t total = 0; + for (const mm::Placed& p : pm.items) total += p.item->n_patch; + uint16_t* pix = hptr(R_ENCPIX); + int32_t* crd = hptr(R_ENCCRD); + int32_t* ecu = hptr(R_ENCCU); + ecu[0] = 0; + std::vector tmp; + for (const mm::Placed& p : pm.items) { + const mm::Item& it = *p.item; + std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(), + (size_t)(it.n_patch * patch_dim_) * 2); + tmp.resize((size_t)(4 * it.n_patch)); + it.coords(0, it.n_patch, tmp.data()); + for (int cc = 0; cc < 4; ++cc) + std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch, + (size_t)it.n_patch * 4); + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t a = it.patch_at(s), e = it.patch_at(s + 1); + ecu[n_seg + 1] = (int32_t)(n_patch + e); + max_seg = std::max(max_seg, (int32_t)(e - a)); + ++n_seg; + } + n_patch += it.n_patch; + } + int32_t* mmr = hptr(R_MMROW); + for (const mm::RopeLayout::Run& run : pm.rope.runs) + for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k; + reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2; + reg_[R_ENCCRD].used = 4 * total * 4; + reg_[R_ENCCU].used = (n_seg + 1) * 4; + reg_[R_MMROW].used = n_mm * 4; + } + if (upload() < 0) return nullptr; base_batches(j, g, T, step); + if (j.req->media) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + const int ri = (int)r; + B.rope_pos = dptr(ri, R_ROPE); + B.rope_mixed = 1; + B.n_mm_rows = n_mm; + B.mm_rows = n_mm ? dptr(ri, R_MMROW) : nullptr; + B.enc = 0; + B.enc_n_patch = n_patch; + B.enc_pixels = n_patch ? dptr(ri, R_ENCPIX) : nullptr; + B.enc_coord = n_patch ? dptr(ri, R_ENCCRD) : nullptr; + B.enc_n_seg = n_seg; + B.enc_cu = n_seg ? dptr(ri, R_ENCCU) : nullptr; + B.enc_max_seg = max_seg; + } + } for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND; pass_.kind = RAD_GEN_PASS_VCOND; pass_.job = j.id; @@ -639,7 +910,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; const bool small = small_now(j); const RadVideoGeom& g = small ? j.geom_small : j.geom; - const int64_t rows = small ? j.rows_small : j.rows; + const int64_t rows = small ? j.rows_small : j.step_rows; /* widened by references when they ride */ const std::vector& pos = small ? j.pos_small : j.pos; stage_sched(j, j.step, small && j.step == j.split - 1); std::memcpy(hptr(R_ROPE), pos.data(), pos.size() * 4); @@ -650,7 +921,10 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { cu[0] = 0; cu[1] = (int32_t)rows; reg_[R_CU].used = 2 * 4; - stage_geom(j, g, rows, 0); + /* A reference-conditioned step stages the pack's reference-aware segment table; the plain and + * small (pre-upscale) steps stage the plain four-boundary table. ref_wide never coincides with + * small -- submit refuses upscale together with references. */ + stage_geom(j, g, rows, 0, j.ref_wide); if (upload() < 0) return nullptr; base_batches(j, g, rows, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; @@ -707,6 +981,81 @@ const RadBatch* VideoDriver::build_chunk(Job& j, int step) { return &out_[0]; } +/* One media item through its VAE encoder: stage its encoder-ready bytes and the encode geometry + * the plugin's rad_arch_encode_geom derives from them, then name the pass's kind and slot so the + * encoder folds the latents into the lane's fixed slot rows. The bytes the server decoded must + * already be padded to what the geom reports (a video's frames clip-padded, an audio's samples to + * its hop) — the encoder reads that many and no more, so a disagreement is failed here rather than + * run past the staged volume. */ +const RadBatch* VideoDriver::build_encode(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const Job::EncItem& it = j.enc_q[j.enc_next]; + const VideoRefMedia& m = j.req->refs[(size_t)it.ref]; + const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO; + auto fail = [&](const std::string& w) { + fail_locked(j, RAD_E_STATE, w); + return nullptr; + }; + if (!enc_geom_) + return fail("the request carries reference media to encode, but this plugin exports no " + "rad_arch_encode_geom"); + int32_t* gd = hptr(R_ENCG); + if (audio) { + const int64_t n = m.enc_n; + const int32_t ch = m.enc_channels; + if (n <= 0 || ch <= 0 || (int64_t)n * ch * 4 > reg_[R_ENCSM].bytes) + return fail("a reference audio does not fit one encode pass"); + int64_t in[4] = { n, 0, 0, ch }; + if (enc_geom_(RAD_GEN_PASS_AENCODE, in, gd, 25) < 0) + return fail("the audio encoder refuses " + std::to_string(n) + " samples over " + + std::to_string(ch) + " channels"); + if ((int64_t)gd[0] != n) + return fail("a reference audio is not padded to the length rad_arch_encode_geom " + "reports"); + std::memcpy(hptr(R_ENCSM), m.enc_samples.data(), (size_t)n * ch * 4); + reg_[R_ENCSM].used = n * ch * 4; + } else { + const int64_t nf = m.enc_frames, H = m.enc_h, W = m.enc_w; + if (nf <= 0 || H <= 0 || W <= 0 || nf * H * W * 3 * 4 > reg_[R_ENCPX].bytes) + return fail("a reference picture or video does not fit one encode pass"); + int64_t in[4] = { nf, H, W, 3 }; + if (enc_geom_(RAD_GEN_PASS_VENCODE, in, gd, 25) < 0) + return fail("the video encoder refuses a reference at " + std::to_string(H) + "x" + + std::to_string(W) + " over " + std::to_string(nf) + " frames"); + if ((int64_t)gd[23] != nf) + return fail("a reference is not padded to the clip count rad_arch_encode_geom " + "reports"); + std::memcpy(hptr(R_ENCPX), m.enc_pixels.data(), (size_t)nf * H * W * 3 * 4); + reg_[R_ENCPX].used = nf * H * W * 3 * 4; + } + reg_[R_ENCG].used = 25 * 4; + stage_geom(j, j.geom, j.rows, 0); + if (upload() < 0) return nullptr; + base_batches(j, j.geom, 0, step); + for (size_t r = 0; r < ranks_.size(); ++r) { + const int ri = (int)r; + RadVideoGenBatch& V = vout_[(size_t)r]; + V.enc_geom_d = dptr(ri, R_ENCG); + V.enc_kind = it.kind; + V.enc_slot = it.slot; + if (audio) { + V.enc_samples = dptr(ri, R_ENCSM); + V.enc_n_samples = m.enc_n; + V.enc_channels = m.enc_channels; + } else { + V.enc_pixels = dptr(ri, R_ENCPX); + V.enc_frames = m.enc_frames; + V.enc_height = m.enc_h; + V.enc_width = m.enc_w; + } + } + const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE; + for (auto& B : out_) B.gen = kind; + pass_.kind = kind; + pass_.job = j.id; + return &out_[0]; +} + int VideoDriver::done() { std::lock_guard lk(mu_); const int64_t now = (int64_t)rad_mono_ns(); @@ -716,6 +1065,11 @@ int VideoDriver::done() { j->cond_done = true; j->req->ticket->t_cond_ns = now; break; + case RAD_GEN_PASS_VENCODE: + case RAD_GEN_PASS_AENCODE: + /* The media's latents are now in the lane's slot rows; take the next reference, if any. */ + ++j->enc_next; + break; case RAD_GEN_PASS_VSTEP: { ++j->step; VideoEvent e; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index c1dd0da6..d0df7671 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -12,8 +12,10 @@ * * 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish * a request and free its lane. - * 2. VCOND of an admitted request, so its steps can follow the current request's without a gap. - * 3. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done. + * 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the + * video and audio VAE latents are in the lane's slots before its prompt runs. + * 3. VCOND of an admitted request, so its steps can follow the current request's without a gap. + * 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done. * Requests are denoised one after another, not in turns: a pass is one request's whole * sequence, so taking turns would only delay the first. */ @@ -34,9 +36,18 @@ public: RadStream stream = nullptr; }; using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); + using SegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t); + using PackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, + float*, int64_t); + using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t); - /* `positions` is the plugin's rad_arch_video_positions. */ - int init(const Program& prog, PositionsFn positions, const std::vector& ranks); + /* `positions` is the plugin's rad_arch_video_positions; `segs`, optional, is its + * rad_arch_video_segs (null = the driver stages the plain segment table itself); `pack`, + * optional, is its rad_arch_video_pack (null = reference-conditioned sequences cannot be + * laid out and such requests are refused); `enc_geom`, optional, is its + * rad_arch_encode_geom (null = no encode pass runs). */ + int init(const Program& prog, PositionsFn positions, const std::vector& ranks, + SegsFn segs = nullptr, PackFn pack = nullptr, EncodeGeomFn enc_geom = nullptr); void fini(); ~VideoDriver() override { fini(); } @@ -68,6 +79,38 @@ private: int64_t n_samples = 0; /* the soundtrack's samples a channel */ VideoSchedule sched; std::vector pos; /* [3, rows] */ + /* The VAE references of a reference-conditioned request (RadVideoGenBatch::ref_tab): + * the pack's input, empty until the path consumes them (it is refused at submit + * before that). The step reads it host-side, so nothing stages it. */ + std::vector ref_tab; + /* When the generator's denoiser consumes that table (`decl_.ref_rows`), the step's packed + * sequence carries reference rows between the text and the target streams, laid out by + * rad_arch_video_pack. These hold that step layout: `ref_wide` marks it, `seg` the pack's + * segment boundaries with the video grid last, `nseg` their count, and `lat_v`/`lat_a` the + * TARGET video and audio row counts -- the rows the sampler owns and the Euler steps update, + * which the plain `rows - text - audio` arithmetic no longer recovers once references ride + * ahead of the streams. Left empty/0 on the plain path and on every non-step pass (decode, + * encode, upscale), which keep their own ref-less segment table. */ + bool ref_wide = false; + int32_t nseg = 0; + std::vector seg; + int64_t lat_v = 0, lat_a = 0; + /* The denoising step's row count: the widened total once references ride, otherwise equal + * to `rows`. Only build_step uses it -- the encode, decode, audio and upscale passes keep + * staging against the plain `rows` (their segment table and target counts are their own, + * never the reference layout), so widening the step cannot disturb them. `pos` widens with + * it, since build_step is the only pass that stages R_ROPE from `pos`. */ + int64_t step_rows = 0; + /* The VAE encode queue: the reference media whose bytes reach the model through a video or + * audio VAE, one item per Vencode/Aencode pass, in presentation order, built at submit for + * the parts the server decoded into encoder form (gen/video.h enc_pixels/enc_samples). + * `enc_kind` is the RAD_ENC_* the pass names and `enc_slot` its 1-based number within that + * kind (the reference's index); `ref` indexes req->refs. `enc_next` is the next to run; + * once it reaches enc_q.size() the media are all encoded. Empty for a request the encoder + * has nothing to do with. */ + struct EncItem { int32_t kind, slot, ref; }; + std::vector enc_q; + size_t enc_next = 0; /* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and * positions, the factor the network is told, and whether the upscale has run. */ int32_t split = 0; @@ -95,8 +138,15 @@ private: /* Staging regions: their offsets in the host span and every rank's slab. */ struct Region { int64_t off = 0, bytes = 0, used = 0; }; + /* R_MMROW/R_ENCPIX/R_ENCCRD/R_ENCCU stage the conditioning pass's reference media, as the + * image generator's driver does (core/gen/driver.cpp); R_ROPE carries a step's f32 positions + * and a conditioning's [3,T] i32 M-RoPE, never in the same pass. */ + /* R_ENCPX/R_ENCSM/R_ENCG stage one media item for a Vencode/Aencode pass: the encoder-ready + * pixels ([frames,h,w,3] f32) or samples ([ch,n] f32) and the encode geometry the plugin's + * rad_arch_encode_geom returned, staged verbatim as device i32 for the kernels to read. */ enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST, - R_SEG, R_LAT, R_UP, R_N }; + R_SEG, R_LAT, R_UP, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, + R_ENCPX, R_ENCSM, R_ENCG, R_N }; template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { @@ -106,7 +156,8 @@ private: /* The geometry and rows of the job's next step: the small ones before its upscale. */ bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; } void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step); - void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk); + void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk, + bool ref_step = false); void stage_sched(const Job& j, int32_t i, bool to_clean); void stage_seed(const Job& j); @@ -120,12 +171,23 @@ private: const RadBatch* build_upscale(Job& j, int step); const RadBatch* build_audio(Job& j, int step); const RadBatch* build_chunk(Job& j, int step); + /* One Vencode or Aencode pass for the job's next queued reference (enc_q[enc_next]): stages + * that part's encoder-ready pixels or samples and the encode geometry, and names its kind and + * slot. Returns null and fails the job if the bytes no longer fit a pass. */ + const RadBatch* build_encode(Job& j, int step); RadVideoGenDecl decl_{}; std::vector rungs_; /* decl_.rungs points here */ std::string name_; PositionsFn positions_ = nullptr; + SegsFn segs_ = nullptr; + PackFn pack_ = nullptr; + EncodeGeomFn enc_geom_ = nullptr; int64_t max_tok_ = 0; + /* The conditioning's encoder view: the tower's per-patch width and the patches one pass + * carries. Zero when the program declares no vision encoder, which bounds the media regions + * and rejects any request that carries references. */ + int64_t patch_dim_ = 0, max_enc_ = 0; std::vector ranks_; char* host_ = nullptr; /* pinned, same layout as each slab */ diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp index 585e6438..762acc0b 100644 --- a/core/mm/imaging.cpp +++ b/core/mm/imaging.cpp @@ -156,6 +156,26 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* } } +void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out) { + /* Wrapping opaque and running the RGBA kernel is exactly PIL's LANCZOS on the RGB image: at + * alpha 255 the premultiply is the identity and the divide-back takes the al == 255 branch. */ + FrameRGBA pre; + pre.w = src.w; + pre.h = src.h; + pre.rgba.resize((size_t)src.w * src.h * 4); + for (size_t i = 0; i < (size_t)src.w * src.h; ++i) { + for (int c = 0; c < 3; ++c) pre.rgba[i * 4 + c] = src.rgb[i * 3 + c]; + pre.rgba[i * 4 + 3] = 255; + } + FrameRGBA post; + resize_lanczos_rgba(pre, w, h, &post); + out->w = post.w; + out->h = post.h; + out->rgb.resize((size_t)post.w * post.h * 3); + for (size_t i = 0; i < (size_t)post.w * post.h; ++i) + for (int c = 0; c < 3; ++c) out->rgb[i * 3 + c] = post.rgba[i * 4 + c]; +} + void composite_white(const FrameRGBA& src, Frame* out) { out->w = src.w; out->h = src.h; diff --git a/core/mm/imaging.h b/core/mm/imaging.h index 637f0e13..f402286b 100644 --- a/core/mm/imaging.h +++ b/core/mm/imaging.h @@ -18,6 +18,10 @@ namespace mm { /* `src` resized to w x h. */ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out); +/* As resize_lanczos_rgba for an opaque picture: wrapped with alpha 255 and resized, so the RGB + * channels are exactly PIL's LANCZOS on the RGB image (premultiply and its inverse are the + * identity at full alpha). The video VAE's reference preprocessing resizes RGB this way. */ +void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out); /* `src` over an opaque white ground. */ void composite_white(const FrameRGBA& src, Frame* out); diff --git a/core/mm/item.cpp b/core/mm/item.cpp index df461703..62fea564 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -3,6 +3,8 @@ * metadata reader, the real device layer. */ #include "mm/processor.h" +#include + namespace rad { namespace mm { @@ -43,5 +45,37 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { } } +/* The rotary layout of one prompt: one run per segment, the text in front of a run counting up + * and a grid advancing the rotary by its longer side. Pure computation over the items, like the + * accessors above, so it lives here rather than in the processor. */ +void PromptMedia::layout() { + rope.runs.clear(); + int64_t pos = 0, tok = 0; + for (size_t pi = 0; pi < items.size(); ++pi) { + const Placed& p = items[pi]; + const Item& it = *p.item; + const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1; + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; + pos += run_tok - tok; /* the text in front of the run counts up */ + const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m; + const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m; + RopeLayout::Run r; + r.tok = (int32_t)run_tok; + r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s)); + r.w = rw; + r.base = (int32_t)pos; + r.flat = it.rope_1d; + /* A grid advances the rotary by its longer side; a 1-D run by its length. */ + pos += it.rope_1d ? r.n : std::max(rh, rw); + tok = run_tok + r.n; + r.shift = (int32_t)(pos - tok); + r.item = (int32_t)pi; + r.row0 = (int32_t)it.row_at(s); + rope.runs.push_back(r); + } + } +} + } /* namespace mm */ } /* namespace rad */ diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 4c304232..f5d60e23 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -1,5 +1,6 @@ /* processor.cpp -- see processor.h. */ #include "mm/processor.h" +#include "mm/imaging.h" #include "rad_internal.h" #include "rad_plugin.h" @@ -1006,6 +1007,40 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, return image_from(f, out, why); } +int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + Frame* out, std::string* why) const { + if (ratio < 1 || max_side < ratio) { + if (why) *why = "the encoder's side ratio and maximum are not usable"; + return RAD_E_INVAL; + } + /* The same decode guard as image(): a reference the text encoder accepts must reach the VAE + * too, so the two never disagree on what a request may carry. */ + Frame f; + RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + /* Snap both sides down to a multiple of the encoder's ratio, neither above max_side, aspect + * kept as close as the grid allows: scale the longest side to fit, then floor each side to the + * grid. Flooring (never rounding up) is what keeps a side within max_side; a side under one + * grid step is raised to it, the smallest volume the encoder accepts. Our encoder runs one + * volume rather than tiling at 256, so a reference larger than the bound is shrunk here — the + * one place the reference and this build differ on an oversized input. */ + auto snap = [&](int64_t s) { + int64_t v = (s / ratio) * ratio; + if (v < ratio) v = ratio; + if (v > max_side) v = max_side; /* max_side is itself a multiple of ratio */ + return (int32_t)v; + }; + const int32_t longest = std::max(f.w, f.h); + const double scale = longest > max_side ? (double)max_side / (double)longest : 1.0; + const int32_t w = snap((int64_t)std::floor(f.w * scale)); + const int32_t h = snap((int64_t)std::floor(f.h * scale)); + if (w == f.w && h == f.h) { + *out = std::move(f); + return RAD_OK; + } + resize_lanczos_rgb(f, w, h, out); + return RAD_OK; +} + namespace { struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; }; std::vector sample_cb(const VideoInfo& info, const void* user) { @@ -1528,36 +1563,5 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr* out, return audio_from(s, out, why); } -/* ================================================================== rotary layout */ - -void PromptMedia::layout() { - rope.runs.clear(); - int64_t pos = 0, tok = 0; - for (size_t pi = 0; pi < items.size(); ++pi) { - const Placed& p = items[pi]; - const Item& it = *p.item; - const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1; - for (int32_t s = 0; s < it.n_seg; ++s) { - const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; - pos += run_tok - tok; /* the text in front of the run counts up */ - const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m; - const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m; - RopeLayout::Run r; - r.tok = (int32_t)run_tok; - r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s)); - r.w = rw; - r.base = (int32_t)pos; - r.flat = it.rope_1d; - /* A grid advances the rotary by its longer side; a 1-D run by its length. */ - pos += it.rope_1d ? r.n : std::max(rh, rw); - tok = run_tok + r.n; - r.shift = (int32_t)(pos - tok); - r.item = (int32_t)pi; - r.row0 = (int32_t)it.row_at(s); - rope.runs.push_back(r); - } - } -} - } /* namespace mm */ } /* namespace rad */ diff --git a/core/mm/processor.h b/core/mm/processor.h index 5be2cf42..f17bf1f9 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -318,6 +318,15 @@ public: int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const; int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; + /* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as + * `image` (so any reference the text encoder accepts the encoder accepts too), then scaled — + * aspect kept — so both sides are multiples of `ratio` and neither exceeds `max_side`, the + * single-volume encoder's square bound. Returns the resized RGB; the caller hands it to the + * encoder un-normalised (the VAE applies its own mean/std). `ratio`/`max_side` come from the + * generator's declaration (RadVideoGenDecl enc_ratio / max_enc_side). */ + int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, Frame* out, + std::string* why) const; + /* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the * encoder's. */ int init_audio(const AudioConfig& cfg, std::string* why = nullptr); diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 8a496f6d..d20a9362 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -225,6 +225,19 @@ int Registry::commit_(Staged& s, int order) { /* A video generator's rotary positions; the driver refuses to start without it. */ p.arch_video_positions = dl_fn( s.handle, "rad_arch_video_positions"); + /* Optional: the pack's segment boundary table; absent means the video driver stages the + * plain [text | audio | video] table itself. */ + p.arch_video_segs = dl_fn( + s.handle, "rad_arch_video_segs"); + /* Optional: the pack with the references in; absent means the driver lays no + * reference-conditioned sequence out. */ + p.arch_video_pack = + dl_fn(s.handle, "rad_arch_video_pack"); + /* Optional: the encode passes' geometry; absent means the driver runs no encode pass. */ + p.arch_encode_geom = + dl_fn( + s.handle, "rad_arch_encode_geom"); /* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim * the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16 diff --git a/core/plugin/registry.h b/core/plugin/registry.h index 3f773fd2..e5089547 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -94,6 +94,15 @@ struct Plugin { int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr; /* Required of a video generator (rad_builder.h); null for every other plugin. */ int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr; + /* Optional (rad_builder.h); null means the video driver stages the plain + * [text | audio | video] boundary table itself. */ + int64_t (*arch_video_segs)(const RadVideoGeom*, int32_t*, int64_t) = nullptr; + /* Optional (rad_builder.h); null means the driver lays no reference-conditioned sequence + * out and refuses requests that carry VAE references. */ + int64_t (*arch_video_pack)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*, + int64_t) = nullptr; + /* Optional (rad_builder.h); null means the driver runs no encode pass. */ + int64_t (*arch_encode_geom)(int32_t, const int64_t*, int32_t*, int64_t) = nullptr; RadPluginCloseFn close = nullptr; }; diff --git a/core/server/adapters.h b/core/server/adapters.h index e2d2839f..d39e2b4e 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -710,6 +710,15 @@ public: : p_->video(bytes.data(), bytes.size(), out, why); } + int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + mm::Frame* out, std::string* why) override { + if (!p_ || !mm::decoder_available()) { + if (why) *why = "no picture decoder is available"; + return RAD_E_UNSUPPORTED; + } + return p_->encoder_image(bytes, n, ratio, max_side, out, why); + } + int32_t audio_rate() const override { return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0; } diff --git a/core/server/admin.cpp b/core/server/admin.cpp index ee6e450a..f7e63b0d 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -399,6 +399,9 @@ json Server::capabilities() const { caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; caps["audio_generation"] = deps_.audio != nullptr; caps["video_generation"] = deps_.videos != nullptr; + /* A video model also says what a request may carry, so a client can gate on it the way it + * gates on /v1/models elsewhere; the counts are the ones a request will actually meet. */ + if (deps_.videos) video_caps(caps, deps_.videos); /* The efforts a chat request may send, probed from the template at startup; null when it * takes any word. "none" and "minimal" are this server's and turn thinking off. */ if (lim_.reasoning_efforts.empty()) { diff --git a/core/server/iface.h b/core/server/iface.h index 04db5e67..8f8f4544 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -533,6 +533,17 @@ public: virtual int prepare(MediaKind k, const std::vector& bytes, const MediaOpts& opts, std::shared_ptr* out, std::string* why) = 0; + /* A picture in a video VAE's encoder-ready form: decoded under the same guard as prepare() and + * resized so both sides are multiples of `ratio` and neither exceeds `max_side`. The video + * generator's server uses it to fill a reference's encoder pixels; a server with no video VAE + * leaves it unsupported. */ + virtual int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + mm::Frame* out, std::string* why) { + (void)bytes; (void)n; (void)ratio; (void)max_side; (void)out; + if (why) *why = "this server prepares no reference media for a video encoder"; + return RAD_E_UNSUPPORTED; + } + /* Audio in two halves, for a route that cuts a long recording into clips itself * (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most * `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most @@ -644,6 +655,18 @@ struct VideoGenInfo { /* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */ double upscale_max = 0.0; int64_t upscale_refine = 0; + /* Reference conditioning (SGLang's task "ref2va"): how many reference images, videos and + * standalone audios the model takes — all 0 for one that makes video from text only, which + * is every model until the declaration carries them (abi/rad_builder.h, RadVideoGenDecl). + * A video's soundtrack rides with the video and is not counted among the audios. */ + int64_t max_ref_images = 0, max_ref_videos = 0, max_ref_audios = 0; + /* The video and audio VAE encoders (RadVideoGenDecl): nonzero when the container carries them, + * so the server decodes and resizes reference media into the encoder's own form before submit; + * the per-pass ceilings it snaps to (a video's clip-padded frames, the encoder's square side, + * an audio's samples) and `enc_ratio`, the side multiple the geom demands. All 0 without the + * encoders — a text-only or TE-only model leaves them and the server never prepares pixels. */ + int64_t encodes = 0, max_enc_frames = 0, max_enc_side = 0, max_enc_samples = 0; + int64_t enc_ratio = 0; }; class IVideoGen { diff --git a/core/server/server.h b/core/server/server.h index 99822fe2..b6ba8926 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -288,6 +288,10 @@ private: /* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning * efforts), shared by /server_info's `capabilities` and the model entry so they agree. */ json capabilities() const; + /* What a video model lets a request carry: the prompt ceiling the /v1/videos parser + * enforces and the reference-media counts, as validate_refs() will apply them. Defined in + * videos.cpp, beside the ref2va contract's own caps. */ + static void video_caps(json& caps, const IVideoGen* gen); HttpResponse handle_reset_prefix_cache(const HttpRequest& req); /* ------------------------------------------------------------------ dashboard.cpp */ diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 94f48633..46b40988 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -15,8 +15,11 @@ * (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or * `short_edge`), the area capped at the model's largest, both sides rounded to the multiple. * A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next. - * Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are - * refused. + * A model that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`: + * the media are form file parts named `ref_image_N` (at most 9), `ref_video_N` (3), a video's + * soundtrack as `ref_video_audio_N` and standalone audios as `ref_audio_N` (3), N 1-based and + * contiguous within each kind. `input_reference` and non-empty `conditions` are still refused: + * the parts carry the bytes, so no JSON array of media is read. * * A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the * first steps run at `size` divided by it and the latent is enlarged to `size` for the last @@ -38,11 +41,15 @@ #include #include +#include #include #include +#include +#include #include #include #include +#include namespace rad { namespace server { @@ -61,6 +68,9 @@ struct Server::VideoJob { std::string err_code, err_message; std::string mp4; std::vector first; /* the first frame, RGB, for the thumbnail */ + /* Reference conditioning: the reference parts' names in conditioning order, empty for a + * text-only job. */ + std::vector refs; /* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the * small size; refine 0 when the video is not upscaled. */ double upscale = 0.0; @@ -118,8 +128,137 @@ void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int6 *h = std::max(mult, (int64_t)std::nearbyint(H / mult) * mult); } +/* What a ref2va request may carry whatever a model declares: the reference media the source + * workflows were built with — nine images, three videos each with an optional soundtrack, three + * standalone audios. A model's declaration can only lower these. */ +constexpr int32_t kMaxRefImages = 9, kMaxRefVideos = 3, kMaxRefAudios = 3; + +/* A form file part's name for task ref2va: `ref_image_N`, `ref_video_N`, `ref_video_audio_N` + * (a video's separately-given soundtrack) or `ref_audio_N`, N plain and 1-based. False for any + * other name; `ref_video_audio_` is tried before `ref_video_` because one contains the other. */ +bool parse_ref_name(const std::string& name, gen::VideoRefMedia::Kind* kind, int32_t* index) { + static const struct { const char* pfx; gen::VideoRefMedia::Kind kind; } kKinds[] = { + { "ref_image_", gen::VideoRefMedia::IMAGE }, + { "ref_video_audio_", gen::VideoRefMedia::VIDEO_AUDIO }, + { "ref_video_", gen::VideoRefMedia::VIDEO }, + { "ref_audio_", gen::VideoRefMedia::AUDIO }, + }; + for (const auto& k : kKinds) { + const size_t n = std::strlen(k.pfx); + if (name.compare(0, n, k.pfx) != 0 || name.size() == n) continue; + char* e = nullptr; + const long v = std::strtol(name.c_str() + n, &e, 10); + if (*e == '\0' && v >= 1 && v <= 99) { *kind = k.kind; *index = (int32_t)v; return true; } + } + return false; +} + +/* True when the file ends in one of these extensions, case-insensitively — what the client + * called the file, which the media readers make the first word of what it holds. */ +bool has_ext(const std::string& f, const std::vector& exts) { + const size_t d = f.find_last_of('.'); + if (d == std::string::npos) return false; + std::string e = f.substr(d + 1); + for (char& c : e) c = (char)std::tolower((unsigned char)c); + for (const std::string& x : exts) if (e == x) return true; + return false; +} + +std::string ext_list(const std::vector& exts) { + std::string s; + for (const std::string& x : exts) { if (!s.empty()) s += ", "; s += "." + x; } + return s; +} + +/* The reference parts of a ref2va request, and their order. Refused with `*err` naming the part + * when one carries no bytes or an extension the media readers do not take, when a kind is over + * the API's or the model's count, when a kind's numbers leave a gap or repeat, or when a + * soundtrack has no video of the same number. On return `refs` is sorted by (kind, number): the + * order the generator builds the conditioning in. */ +int validate_refs(std::vector& refs, const VideoGenInfo& info, ApiError* err) { + if (refs.empty()) { + *err = err_bad("task", "ref2va takes at least one reference part: ref_image_N, " + "ref_video_N, ref_video_audio_N or ref_audio_N"); + return -1; + } + const struct { + const char* pfx; + gen::VideoRefMedia::Kind kind; + int32_t cap; + std::vector exts; + } kinds[] = { + { "ref_image", gen::VideoRefMedia::IMAGE, + std::min(kMaxRefImages, (int32_t)info.max_ref_images), + { "png", "jpg", "jpeg", "webp" } }, + { "ref_video", gen::VideoRefMedia::VIDEO, + std::min(kMaxRefVideos, (int32_t)info.max_ref_videos), + { "mp4", "mov" } }, + { "ref_video_audio", gen::VideoRefMedia::VIDEO_AUDIO, + std::min(kMaxRefVideos, (int32_t)info.max_ref_videos), + { "mp4", "mov", "wav", "mp3", "m4a", "aac", "flac", "ogg" } }, + { "ref_audio", gen::VideoRefMedia::AUDIO, + std::min(kMaxRefAudios, (int32_t)info.max_ref_audios), + { "wav", "mp3", "m4a", "aac", "flac", "ogg" } }, + }; + for (const auto& k : kinds) { + std::vector got(k.cap + 1, false); + int n = 0; + for (const gen::VideoRefMedia& m : refs) { + if (m.kind != k.kind) continue; + ++n; + if (m.data.empty()) + return *err = err_bad(m.name, "'" + m.name + "' carries an empty file"), -1; + if (!has_ext(m.filename, k.exts)) + return *err = err_bad(m.name, "'" + m.name + "' must be one of " + + ext_list(k.exts)), -1; + if (m.index > k.cap) + return *err = err_bad(m.name, k.cap == 0 + ? "this model takes no parts named " + + std::string(k.pfx) + "_N" + : "this model takes at most " + + std::to_string(k.cap) + " parts named " + + std::string(k.pfx) + "_N"), -1; + if (got[m.index]) + return *err = err_bad(m.name, "two parts are numbered " + std::string(k.pfx) + + "_" + std::to_string(m.index)), -1; + got[m.index] = true; + } + for (int i = 1; i <= n; ++i) + if (!got[i]) + return *err = err_bad(std::string(k.pfx) + "_" + std::to_string(i), + "the " + std::string(k.pfx) + "_N parts must be numbered 1 " + "to " + std::to_string(n) + " without gaps or repeats"), -1; + } + for (const gen::VideoRefMedia& m : refs) { + if (m.kind != gen::VideoRefMedia::VIDEO_AUDIO) continue; + bool paired = false; + for (const gen::VideoRefMedia& v : refs) + paired = paired || (v.kind == gen::VideoRefMedia::VIDEO && v.index == m.index); + if (!paired) + return *err = err_bad(m.name, "'" + m.name + "' is the soundtrack of a reference " + "video; give ref_video_" + std::to_string(m.index) + + " with it"), -1; + } + std::stable_sort(refs.begin(), refs.end(), + [](const gen::VideoRefMedia& a, const gen::VideoRefMedia& b) { + return a.kind != b.kind ? a.kind < b.kind : a.index < b.index; + }); + return 0; +} + } /* namespace */ +/* The caps the /v1/models and /server_info capability block reports for a video model. The + * counts are the ones validate_refs() will apply — the model's declaration under the API's, + * since a declaration can only lower those — so what a client gates on is what it will meet. */ +void Server::video_caps(json& caps, const IVideoGen* gen) { + const VideoGenInfo& info = gen->info(); + caps["video_max_text"] = info.max_text; + caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images); + caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos); + caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios); +} + HttpResponse Server::handle_video_create(const HttpRequest& req) { if (!deps_.videos || !deps_.tok) return error_response(err_not_implemented( @@ -127,17 +266,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { req.peer); const VideoGenInfo& info = deps_.videos->info(); + const bool takes_refs = info.max_ref_images > 0 || info.max_ref_videos > 0 || + info.max_ref_audios > 0; /* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form, - * since it may carry a file). */ + * since it may carry a file). A form may carry the reference media of a ref2va request as + * named file parts; they are collected here and checked once the task is known. */ + std::vector refs; json body = json::object(); if (!req.form.empty()) { for (const FormPart& p : req.form) { if (p.name == "input_reference") - return error_response(err_unsupported("input_reference", "this server makes video " - "from text only"), req.peer); - if (!p.filename.empty()) - return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"), - req.peer); + return error_response(err_unsupported("input_reference", takes_refs + ? "this server reads reference media as " + "ref_image_N file parts" + : "this server makes video from text " + "only"), req.peer); + if (!p.filename.empty()) { + gen::VideoRefMedia m; + if (!parse_ref_name(p.name, &m.kind, &m.index)) + return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a " + "file"), req.peer); + m.name = p.name; + m.filename = p.filename; + m.content_type = p.content_type; + m.data = p.data; + refs.push_back(std::move(m)); + continue; + } json v = p.data; if (p.name == "target" || p.name == "conditions") { v = json::parse(p.data, nullptr, false); @@ -179,16 +334,41 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { return bad("prompt", "the prompt is required, as a non-empty string"); const std::string prompt = body["prompt"].get(); if (has(body, "input_reference")) - return error_response(err_unsupported("input_reference", "this server makes video from " - "text only"), req.peer); - if (has(body, "task") && (!body["task"].is_string() || body["task"].get() != "t2va")) { - ApiError e = err_unsupported("task", "this server makes video from text: t2va"); - e.supported = { "t2va" }; - return error_response(e, req.peer); + return error_response(err_unsupported("input_reference", takes_refs + ? "this server reads reference media as ref_image_N " + "file parts" + : "this server makes video from text only"), + req.peer); + /* The task: text always; reference conditioning for a model that takes reference media. */ + bool ref2va = false; + if (has(body, "task")) { + const std::string task = body["task"].is_string() ? body["task"].get() : ""; + if (task == "ref2va" && takes_refs) ref2va = true; + else if (task != "t2va") { + ApiError e = err_unsupported("task", takes_refs + ? "this server makes video from text or from reference " + "media: t2va, ref2va" + : "this server makes video from text: t2va"); + e.supported = takes_refs ? std::vector{ "t2va", "ref2va" } + : std::vector{ "t2va" }; + return error_response(e, req.peer); + } } if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) - return error_response(err_unsupported("conditions", "this server makes video from text " - "only; conditions must be empty"), req.peer); + return error_response(err_unsupported("conditions", takes_refs + ? "reference media arrive as ref_* file parts; " + "conditions must be empty" + : "this server makes video from text only; " + "conditions must be empty"), req.peer); + /* The reference parts, in conditioning order, before anything else reads them. Files with no + * task are a caller's mistake about the task, not about the part. */ + if (!refs.empty() && !ref2va) + return bad("task", "reference files are given: send them with task ref2va, or send " + "none"); + if (ref2va) { + ApiError e; + if (validate_refs(refs, info, &e) < 0) return error_response(e, req.peer); + } json target = json::object(); if (has(body, "target")) { if (!body["target"].is_object()) return bad("target", "expected an object"); @@ -314,8 +494,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { std::random_device rd; r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); } + r->refs = std::move(refs); - /* ---- the prompt: the template's text with special tokens, the prompt without */ + /* ---- the prompt: the template's text with special tokens, the reference media in its + * presentation order, the prompt last (docs/PORT-REF2VA.md §3: images, then videos each + * after its soundtrack's label, then the standalone audios). Each `: ` label is + * encoded as its own string, as the tokenizer the source workflows were checked against sees + * it; the picture's token run follows its label, taken from the processed item. */ { static const std::string kSlot = "{prompt}"; const std::string& t = info.tmpl; @@ -325,15 +510,89 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { const auto ids = deps_.tok->encode(s, false, special); r->tokens.insert(r->tokens.end(), ids.begin(), ids.end()); }; - put(t.substr(0, p), true); - put(prompt, false); - put(t.substr(p + kSlot.size()), true); + /* The reference media are presented between the template's head and the prompt. Only the + * images reach the language model, so only they are decoded and processed here; a + * reference video's frames and every audio ride the video and audio VAE encoders, which + * the video path does not run in this build yet, so their parts pass through as bytes for + * the generator to refuse at submit naming the part — not silently dropped. (When videos + * land, a soundtrack's `