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

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

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

No files matched your search

+1 -1
View File
@@ -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:
+99 -1
View File
@@ -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;
+49
View File
@@ -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. */
+35 -4
View File
@@ -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"),
+7 -1
View File
@@ -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)
+1504 -114
View File
File diff suppressed because it is too large. Load diff
+294
View File
@@ -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 <algorithm>
#include <cmath>
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<double> 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<double> 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<double>* frame, std::vector<double>* w_grid) {
const double area = std::sqrt((double)h * (double)w);
std::vector<double> 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<double> video_t_grid(int n, double origin) {
std::vector<double> 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<float>* 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<double>& frame, double origin,
std::vector<float>* pos) {
const std::vector<double> 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<Ref2VAKeyframe>& keyframes,
const std::vector<Ref2VARef>& 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<double> 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<double> 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<double> 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<float> 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<int>* out) {
std::vector<double> 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<int>* md,
std::vector<int>* 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 */
+118
View File
@@ -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 <cstdint>
#include <vector>
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<Ref2VASeg> 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<float> 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<int>* 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<int>* md,
std::vector<int>* 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<Ref2VAKeyframe>& keyframes,
const std::vector<Ref2VARef>& refs, Ref2VAPack* out);
} /* namespace minimaxh3 */
#endif
+90
View File
@@ -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 <algorithm>
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<VaeTile>* 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<int64_t> 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<int64_t>(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 */
+77
View File
@@ -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 <cstdint>
#include <vector>
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<VaeTile>* 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
+15
View File
@@ -284,6 +284,21 @@ VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) {
return ap ? ap->arch_video_positions : nullptr;
}
VideoSegsFn rad_tools_video_segs(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_segs : nullptr;
}
VideoPackFn rad_tools_video_pack(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_video_pack : nullptr;
}
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& lp) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
return ap ? ap->arch_encode_geom : nullptr;
}
const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) {
const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin);
if (!ap || !ap->arch_audio_format) return nullptr;
+16
View File
@@ -99,6 +99,22 @@ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::s
using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins);
/* The architecture plugin's video segment boundary table (rad_arch_video_segs), or null when it
* exports none -- the video driver then stages the plain table itself. */
using VideoSegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t);
VideoSegsFn rad_tools_video_segs(const LoadedPlugins& plugins);
/* The architecture plugin's reference-aware sequence layout (rad_arch_video_pack), or null
* when it exports none -- the driver then refuses requests carrying VAE references. */
using VideoPackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t);
VideoPackFn rad_tools_video_pack(const LoadedPlugins& plugins);
/* The architecture plugin's encode-pass geometry (rad_arch_encode_geom), or null when it
* exports none -- the driver then runs no encode pass. */
using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t);
EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& plugins);
/* Run declare.
*
* `also` declares into the same builder after the architecture plugin, which is how the sampler
+13 -1
View File
@@ -1516,7 +1516,9 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
std::vector<gen::VideoDriver::RankIO> gio;
for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() });
auto d = std::make_unique<gen::VideoDriver>();
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio));
RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio,
rad_tools_video_segs(plugins_), rad_tools_video_pack(plugins_),
rad_tools_encode_geom(plugins_)));
vid_gen_ = d.get();
gen_ = std::move(d);
RAD_TRY(rad_dev_set(ranks_[0]->device));
@@ -2498,6 +2500,16 @@ int Engine::run_server() {
in.upscale_max = vd.upscale_max;
in.upscale_refine = vd.upscale_refine;
in.max_lanes = vd.max_lanes;
in.max_ref_images = vd.max_ref_images;
in.max_ref_videos = vd.max_ref_videos;
in.max_ref_audios = vd.max_ref_audios;
in.encodes = vd.encodes;
in.max_enc_frames = vd.max_enc_frames;
in.max_enc_side = vd.max_enc_side;
in.max_enc_samples = vd.max_enc_samples;
in.enc_ratio = vd.enc_ratio;
/* A plugin that declares no ceilings leaves all three 0, and the server then serves
* ref2va as unimplemented — which is right until the generator can consume the bytes. */
video_bridge.drv = vid_gen_;
d.videos = &video_bridge;
if (cfg_.served_model_name.empty() && !in.name.empty()) {
+11 -1
View File
@@ -952,7 +952,17 @@ int Engine::declare() {
decide("--max-model-len", std::to_string(cfg_.max_ctx),
"a video generator: a step's rows");
}
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
/* `auto` is left to the vision rule below, which keys on the container's
* `radiance.encoder`: a container converted with a vision tower's weights (a ref2va
* conditioning checkpoint) serves reference media through it, and one converted
* without them stays text-only. A video generator that carries no tower pays
* nothing for this: the rule resolves to 0 exactly as this branch used to. */
if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) {
cfg_.mm_max_patches = pb.gen_patches;
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
"a video generator: every reference media patch of one conditioning, "
"the pass size the plugin states");
}
if (cfg_.n_spec < 0) cfg_.n_spec = 0;
cfg_.prefix_cache = false;
} else if (pb.gen_rows > 0) {
+285
View File
@@ -1249,6 +1249,291 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
return RAD_OK;
}
/* PEFT exports wrap HF module paths in the name of the net the adapter trained: ai-toolkit spells
* a DiT module `diffusion_model.<path>`, diffusers' wrappers `transformer.` or `unet.`. */
static const char* const kLoraPrefixes[] = { "diffusion_model.", "transformer.", "unet." };
/* One `modules` rule of the map: the module pattern split at its single `*`, and the target
* patterns into which the matched run is substituted, in B-row order. */
struct LoraRule {
bool star = false;
std::string pre, suf;
std::vector<std::string> targets;
bool match(const std::string& m, std::string* tok) const {
if (!star) {
if (m != pre) return false;
tok->clear();
return true;
}
if (m.size() < pre.size() + suf.size() || m.compare(0, pre.size(), pre) != 0) return false;
if (m.compare(m.size() - suf.size(), suf.size(), suf) != 0) return false;
*tok = m.substr(pre.size(), m.size() - pre.size() - suf.size());
return !tok->empty();
}
};
/* Read the map file: {"strip": [...], "modules": {"<pat>": ["<t>", ...], ...}}. The module
* order is preserved (an nlohmann object keeps insertion order), so the first rule whose
* pattern matches a module wins. */
static int lora_map_read(const std::string& file, std::vector<std::string>* strip,
std::vector<LoraRule>* rules) {
std::ifstream f(file);
if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; }
nlohmann::ordered_json j;
try {
j = nlohmann::ordered_json::parse(f);
} catch (const std::exception& e) {
RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what());
return RAD_E_FORMAT;
}
if (!j.is_object()) { RAD_ERR("lora: --lora-map %s is not a JSON object", file.c_str());
return RAD_E_FORMAT; }
if (j.contains("strip")) {
if (!j["strip"].is_array()) { RAD_ERR("lora: --lora-map 'strip' is not a list");
return RAD_E_FORMAT; }
for (const auto& s : j["strip"]) {
if (!s.is_string()) { RAD_ERR("lora: --lora-map 'strip' holds a non-string");
return RAD_E_FORMAT; }
strip->push_back(s.get<std::string>());
}
}
if (!j.contains("modules") || !j["modules"].is_object()) {
RAD_ERR("lora: --lora-map %s has no 'modules' object", file.c_str());
return RAD_E_FORMAT;
}
for (const auto& [pat, t] : j["modules"].items()) {
if (!t.is_array() || t.empty()) {
RAD_ERR("lora: --lora-map rule '%s' is not a non-empty list", pat.c_str());
return RAD_E_FORMAT;
}
const size_t star = pat.find('*');
LoraRule r;
r.star = star != std::string::npos;
r.pre = r.star ? pat.substr(0, star) : pat;
r.suf = r.star ? pat.substr(star + 1) : "";
for (const auto& x : t) {
if (!x.is_string()) {
RAD_ERR("lora: --lora-map rule '%s' holds a non-string target", pat.c_str());
return RAD_E_FORMAT;
}
r.targets.push_back(x.get<std::string>());
}
rules->push_back(std::move(r));
}
return RAD_OK;
}
int Checkpoint::add_lora(const std::string& path, double strength,
std::vector<std::string>* merged, const std::string* map_json) {
if (kind_ != SafeT) {
RAD_ERR("lora: an adapter merges into a safetensors source; %s is not one", path_.c_str());
return RAD_E_UNSUPPORTED;
}
if (import_ != Import::None) {
RAD_ERR("lora: this checkpoint ships its weights packed by a quantiser; an adapter merges "
"into the plain tensors its training saw, not into the codes");
return RAD_E_UNSUPPORTED;
}
std::vector<std::string> files;
std::error_code ec;
if (std::filesystem::is_directory(path, ec)) {
for (const auto& e : std::filesystem::directory_iterator(path, ec))
if (e.path().extension() == ".safetensors") files.push_back(e.path().string());
std::sort(files.begin(), files.end());
} else
files.push_back(path);
if (files.empty()) {
RAD_ERR("lora: %s holds no .safetensors file", path.c_str());
return RAD_E_NOTFOUND;
}
/* The module lookup strips wrapper prefixes: the map's first, then the builtin ones. */
std::vector<std::string> strips;
std::vector<LoraRule> rules;
if (map_json && lora_map_read(*map_json, &strips, &rules) < 0) return RAD_E_FORMAT;
for (const char* pre : kLoraPrefixes) strips.push_back(pre);
/* One pair's A/B/alpha, by module; `module` keeps the wrapper prefix, so the lookup below
* strips it. */
struct Pair { std::string module; const StTensor *a = nullptr, *b = nullptr, *al = nullptr; };
int n_merged = 0;
for (const std::string& f : files) {
SafeTensorsFile st;
if (st.open(f) != RAD_OK) return RAD_E_FORMAT;
std::vector<Pair> pairs;
std::map<std::string, size_t> by_module;
for (const StTensor& t : st.tensors()) {
if (t.name.size() > 12 && t.name.compare(t.name.size() - 12, 12, ".dora.scalar") == 0) {
RAD_ERR("lora: '%s' is a DoRA adapter; only plain LoRA merges (a magnitude vector "
"has no place in a weight merge)", t.name.c_str());
return RAD_E_UNSUPPORTED;
}
const char* suf = nullptr;
if (t.name.size() > 14 && t.name.compare(t.name.size() - 14, 14, ".lora_A.weight") == 0)
suf = ".lora_A.weight";
else if (t.name.size() > 18 &&
t.name.compare(t.name.size() - 18, 18, ".lora_down.weight") == 0)
suf = ".lora_down.weight";
if (suf) {
Pair p;
p.module = t.name.substr(0, t.name.size() - std::strlen(suf));
p.a = &t;
by_module[p.module] = pairs.size();
pairs.push_back(std::move(p));
} else if (t.name.size() > 14 &&
t.name.compare(t.name.size() - 14, 14, ".lora_B.weight") == 0) {
auto it = by_module.find(t.name.substr(0, t.name.size() - 14));
if (it != by_module.end()) pairs[it->second].b = &t;
} else if (t.name.size() > 6 &&
t.name.compare(t.name.size() - 6, 6, ".alpha") == 0) {
auto it = by_module.find(t.name.substr(0, t.name.size() - 6));
if (it != by_module.end()) pairs[it->second].al = &t;
}
}
if (pairs.empty()) {
RAD_ERR("lora: %s holds no .lora_A.weight / .lora_down.weight tensors", f.c_str());
return RAD_E_NOTFOUND;
}
for (Pair& p : pairs) {
if (!p.b) {
RAD_ERR("lora: '%s' ships its A but no B", p.module.c_str());
return RAD_E_FORMAT;
}
/* The targets, in merge order: `<module>.weight`, then the same under each
* prefix-stripped spelling (the module never carries its `.weight` -- PEFT names the
* module, the target adds it), then the first map rule the stripped module matches,
* whose target patterns name one or several tensors the fused module was trained as.
* The first spelling the checkpoint holds wins. */
std::string norm = p.module;
for (const std::string& s : strips)
if (norm.size() > s.size() && norm.compare(0, s.size(), s) == 0) {
norm.erase(0, s.size());
break;
}
std::vector<const SrcTensor*> tg;
if (const SrcTensor* W = find(p.module + ".weight")) tg.push_back(W);
if (tg.empty() && norm != p.module)
if (const SrcTensor* W = find(norm + ".weight")) tg.push_back(W);
for (const LoraRule& ru : rules) {
std::string tok;
if (!ru.match(norm, &tok)) continue;
for (const std::string& pat : ru.targets) {
std::string nm = pat;
const size_t star = nm.find('*');
if (star != std::string::npos) nm.replace(star, 1, tok);
const SrcTensor* W = find(nm);
if (!W) {
RAD_ERR("lora: the map maps '%s' onto '%s', which this checkpoint does "
"not ship", p.module.c_str(), nm.c_str());
return RAD_E_NOTFOUND;
}
tg.push_back(W);
}
break;
}
if (tg.empty()) {
RAD_ERR("lora: '%s' names a module this checkpoint does not ship as "
"'<module>.weight' (nor stripped of a known wrapper prefix)%s",
p.module.c_str(),
map_json ? " and no --lora-map rule matches it" : "");
return RAD_E_NOTFOUND;
}
const StTensor& A = *p.a;
const StTensor& B = *p.b;
if (A.shape.size() != 2 || B.shape.size() != 2 || A.shape[0] <= 0 ||
A.shape[0] != B.shape[1]) {
RAD_ERR("lora: '%s' is not a rank-%lld pair of matrices: [a %lld x %lld, "
"b %lld x %lld]",
p.module.c_str(), (long long)A.shape[0], (long long)A.shape[0],
(long long)A.shape[1], (long long)B.shape[0], (long long)B.shape[1]);
return RAD_E_FORMAT;
}
const auto plain = [](uint32_t d) {
return d == RAD_BF16 || d == RAD_F16 || d == RAD_F32;
};
if (!plain(A.dtype) || !plain(B.dtype)) {
RAD_ERR("lora: '%s' ships A/B in dtypes the merge cannot read", p.module.c_str());
return RAD_E_UNSUPPORTED;
}
const int64_t K = A.shape[1], r = A.shape[0];
int64_t rows = 0;
for (const SrcTensor* W : tg) {
if (W->gptq_bits || W->ct_group || W->rad_dtype == RAD_DT_INVALID ||
!plain(W->rad_dtype)) {
RAD_ERR("lora: '%s' is not a plain bf16/f16/f32 matrix, so an adapter cannot "
"merge into it", W->name.c_str());
return RAD_E_UNSUPPORTED;
}
if (W->shape.size() != 2 || W->shape[1] != K) {
RAD_ERR("lora: '%s' [a %lld x %lld, b %lld x %lld] does not fit '%s' "
"[%lld x %lld]",
p.module.c_str(), (long long)A.shape[0], (long long)A.shape[1],
(long long)B.shape[0], (long long)B.shape[1], W->name.c_str(),
(long long)W->shape[0], (long long)W->shape[1]);
return RAD_E_FORMAT;
}
rows += W->shape[0];
}
if (rows != B.shape[0]) {
RAD_ERR("lora: '%s' merges into %zu target(s) whose rows sum to %lld, but its B "
"has %lld", p.module.c_str(), tg.size(), (long long)rows,
(long long)B.shape[0]);
return RAD_E_FORMAT;
}
float scale = (float)strength;
if (p.al) {
const int64_t n_el = p.al->shape.empty() ? 1 : p.al->numel();
if (n_el != 1 || (p.al->dtype != RAD_F32 && p.al->dtype != RAD_BF16 &&
p.al->dtype != RAD_F16)) {
RAD_ERR("lora: '%s.alpha' is not a single number", p.module.c_str());
return RAD_E_FORMAT;
}
scale *= rad_load_f32(p.al->data, p.al->dtype, 0) / (float)r;
}
/* The module is the targets' concatenation, so B's rows split along them in listed
* order: target i takes rows [off, off + N_i) as its own.
*
* Row at a time, rank-1 updates into an f32 row buffer. A is copied to f32 once per
* pair (r rows -- a few KiB to a few MiB): the rank sweep then reads plain f32
* contiguously against the accumulator, which is what the compiler vectorises and
* the cache wants; paying rad_load_f32's dtype switch per element instead made the
* real 416-pair merge an hour of scalar work. The same f32 sums as the textbook
* order, up to the rounding of the accumulation itself, which the bf16 cast
* swallows. */
std::vector<float> Af((size_t)(r * K));
for (int64_t i = 0; i < r * K; ++i) Af[(size_t)i] = rad_load_f32(A.data, A.dtype, i);
std::vector<float> acc((size_t)K);
int64_t off = 0;
for (const SrcTensor* W : tg) {
const int64_t N = W->shape[0];
auto out = std::make_unique<uint8_t[]>((size_t)W->bytes);
for (int64_t n = 0; n < N; ++n) {
for (int64_t j = 0; j < r; ++j) {
const float b = scale * rad_load_f32(B.data, B.dtype, (off + n) * r + j);
if (b == 0.f) continue;
const float* ar = Af.data() + (size_t)j * K;
for (int64_t k = 0; k < K; ++k) acc[(size_t)k] += b * ar[k];
}
for (int64_t k = 0; k < K; ++k)
rad_store_f32(out.get(), W->rad_dtype, n * K + k,
rad_load_f32(W->data, W->rad_dtype, n * K + k) +
acc[(size_t)k]);
std::fill(acc.begin(), acc.end(), 0.f);
}
SrcTensor& t = tensors_[index_[W->name]];
t.data = out.get();
owned_.push_back(std::move(out));
if (merged) merged->push_back(t.name);
++n_merged;
off += N;
}
}
}
RAD_INFO("lora %s: %d tensor(s) merged at strength %g", path.c_str(), n_merged, strength);
return RAD_OK;
}
const SrcTensor* Checkpoint::find(const std::string& n) const {
auto it = index_.find(n);
return it == index_.end() ? nullptr : &tensors_[it->second];
+25
View File
@@ -121,6 +121,31 @@ public:
* tensors and config.json keys under `draft.`. */
int add_draft(const std::string& dir, const std::string& prefix);
/* Merge PEFT adapters into the tensors they name, before anything reads the checkpoint:
* `path` is a .safetensors file or a directory of them, holding `<module>.lora_A.weight`
* [r,K] / `<module>.lora_B.weight` [N,r] pairs (ComfyUI's `.lora_down`/`.lora_up` spellings
* read too), with an optional `<module>.alpha` scalar -- the module never carries its own
* `.weight`. The target is `<module>.weight`, looked up under that name and, failing that,
* after stripping a wrapper prefix ("diffusion_model.", "transformer.", "unet.");
* a module the checkpoint does not ship is
* a refusal naming it, since a merge that silently hits nothing is a different model. The
* merge is the PEFT one, in f32: W += strength * (alpha/r where an .alpha states one, else 1)
* * B @ A, cast back to the target's dtype. Targets must be plain bf16/f16/f32 matrices --
* an adapter cannot merge into a quantised export or a non-matrix. Call this right after
* open(): it re-points a merged tensor's bytes, and views taken before it would read the
* unmerged ones. `merged` receives each target's name.
*
* `map_json` (null = none) names a file holding per-architecture module rules for adapters
* trained against a module layout the checkpoint does not spell -- a fused qkv, renamed blocks:
* `{"strip": ["prefix."], "modules": {"<pattern>": ["<target pattern>", ...]}}`, where a
* `*` in a module pattern matches one run of characters (the block index) and the same run
* fills every `*` in that rule's target patterns. Several targets share one delta: the
* module is the concatenation, so B's rows split along the targets in the order listed,
* each taking its own row count (they must sum to B's rows). A rule whose target the
* checkpoint lacks is a refusal, never a miss -- the rule says the tensor is there. */
int add_lora(const std::string& path, double strength, std::vector<std::string>* merged,
const std::string* map_json = nullptr);
const SrcTensor* find(const std::string& n) const;
const std::vector<SrcTensor>& tensors() const { return tensors_; }
bool is_gguf() const { return kind_ == Gguf; }
+43
View File
@@ -8,6 +8,7 @@
*/
#pragma once
#include "rad_core.h"
#include "mm/processor.h"
#include <atomic>
#include <condition_variable>
@@ -71,6 +72,37 @@ private:
std::string why_;
};
/* One file of a reference-conditioned request (task "ref2va"): an image or a video that
* conditions identity and motion, a video's separately-given soundtrack, or a standalone audio.
* The server reads the parts' bytes, bounds them and orders them; decoding them and turning
* them into conditioning rows is the generator's. `index` is the part's 1-based number within
* its kind, which fixes its slot in the conditioning; VIDEO_AUDIO #i is the soundtrack of
* VIDEO #i. */
struct VideoRefMedia {
enum Kind : int32_t { IMAGE = 0, VIDEO = 1, VIDEO_AUDIO = 2, AUDIO = 3 };
Kind kind = IMAGE;
int32_t index = 0;
std::string name, filename, content_type; /* the part's name and what the client called the file */
std::string data; /* the file's bytes */
/* The reference in the encoder's own form, prepared by the server (which owns the decoder) so
* the driver stages bytes without ever touching a codec. The VAE encode pass reads exactly
* these; they are empty until the server decodes the part. IMAGE/VIDEO fill the pixels,
* AUDIO/VIDEO_AUDIO the samples.
* enc_pixels: f32 [enc_frames][enc_h][enc_w][3] row-major RGB in 0..255, UN-normalised —
* the video VAE applies ImageNet mean/std itself. Each side is snapped down to a multiple
* of the VAE's spatial ratio and capped at the declaration's max_enc_side, aspect kept,
* because our encoder runs one volume and cannot tile the way the reference does. For a
* still image enc_frames is 1.
* enc_samples: f32 [enc_channels][enc_n] channel-major, each channel right-padded with
* zeros out to a whole number of hops (geom entry 0), at the model's audio rate. */
std::vector<float> enc_pixels;
int32_t enc_frames = 0, enc_h = 0, enc_w = 0;
std::vector<float> enc_samples;
int64_t enc_n = 0;
int32_t enc_channels = 0;
};
struct VideoRequest {
std::vector<int32_t> tokens; /* the prompt, rendered and tokenised */
int32_t width = 0, height = 0; /* pixels, within the declaration's limits */
@@ -81,6 +113,17 @@ struct VideoRequest {
double upscale = 0.0;
int32_t refine = 0;
uint64_t seed = 0;
/* Reference conditioning, sorted by (kind, index); empty for a text-only request. The bytes
* are the VAE's (P2): reference videos and audios become conditioning rows through the
* video/audio VAEs, not the TE. */
std::vector<VideoRefMedia> refs;
/* The references' TE view: every image and video reference processed to patches, placed in
* `tokens` at their presentation markers, with the M-RoPE layout over the whole conditioning
* (§3's presentation order). The server decodes and processes; the driver stages it into the
* conditioning pass's encoder fields (RadBatch::enc_* / rope_pos / mm_rows) exactly as the
* image generator's driver does. Null for a request whose references carry nothing the TE
* sees — audios are label-only, and a text-only request has none. */
std::shared_ptr<mm::PromptMedia> media;
std::shared_ptr<VideoTicket> ticket;
};
+384 -30
View File
@@ -141,16 +141,26 @@ namespace {
constexpr int64_t kAlign = 256;
/* The most segment boundaries R_SEG holds: the plain presentation has four, and a full
* reference-conditioned one (text, a keyframe pair, two segments for every reference at the
* server's 9/3/3 caps, the two target streams) stays well under this. The plugin's pack is the
* only source once references ride; the VSA kernels take the count from the staged rows and
* accept up to 4096. */
constexpr int64_t kSegCap = 64;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
* allocation and the VRAM budget. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) {
* allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and
* patch width (RadBuildCtx::max_enc_patches, RadEncoderDecl::patch_dim), 0 and 0 without a
* vision encoder: the media regions then hold nothing. */
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
int64_t (*bytes)[2], int n) {
const int64_t want[] = {
d.max_text * 4, /* R_TOK */
d.max_text * 4, /* R_POS */
2 * 4, /* R_CU */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions */
3 * max_tok * 4, /* R_ROPE: a step's rotary positions, a conditioning's [3,T] M-RoPE */
RAD_VGEOM_N * 4, /* R_GEOM */
6 * 4, /* R_SCHED */
d.max_steps * 4, /* R_TV */
@@ -158,9 +168,19 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in
4 * 4, /* R_SEED */
4, /* R_LANE */
4, /* R_FIRST */
4 * 4, /* R_SEG */
kSegCap * 4, /* R_SEG: the pack's boundary table, widened for references */
4 * 4, /* R_LAT */
4, /* R_UP */
d.max_text * 4, /* R_MMROW: the media rows, one per placeholder token */
ep * pd * 2, /* R_ENCPIX: [ep, pd] bf16 */
4 * ep * 4, /* R_ENCCRD: [4, ep] i32 component-major */
(ep + 2) * 4, /* R_ENCCU: segment boundaries; a segment is at least one patch */
/* The VAE encode staging: one media item's pixels or samples and its encode geometry,
* sized to the declaration's per-pass ceilings so a single pass holds any media the
* export accepts. All 0 without the encoders (decl.encodes 0 leaves the ceilings 0). */
d.max_enc_frames * d.max_enc_side * d.max_enc_side * 3 * 4, /* R_ENCPX: [f,h,w,3] f32 */
d.max_enc_samples * d.audio_channels * 4, /* R_ENCSM: [ch,n] f32 */
25 * 4, /* R_ENCG: rad_arch_encode_geom's 25 i32 (the video geom) */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
@@ -184,14 +204,26 @@ int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) {
} /* namespace */
/* The conditioning encoder's staging bounds: a program with no declared vision encoder stages
* no media, and the driver refuses requests that carry any. */
namespace {
void encoder_bounds(const Program& prog, int64_t* ep, int64_t* pd) {
*ep = prog.encoder.modalities != 0 ? prog.ctx.max_enc_patches : 0;
*pd = prog.encoder.modalities != 0 ? prog.encoder.patch_dim : 0;
}
} /* namespace */
int64_t VideoDriver::device_bytes(const Program& prog) {
if (!prog.is_video_generator()) return 0;
int64_t ep = 0, pd = 0;
encoder_bounds(prog, &ep, &pd);
int64_t b[R_N][2];
return carve(prog.video_gen, prog.ctx.max_tok, b, R_N);
return carve(prog.video_gen, prog.ctx.max_tok, ep, pd, b, R_N);
}
int VideoDriver::init(const Program& prog, PositionsFn positions,
const std::vector<RankIO>& ranks) {
const std::vector<RankIO>& ranks, SegsFn segs, PackFn pack,
EncodeGeomFn enc_geom) {
fini();
if (!prog.is_video_generator()) return RAD_E_STATE;
decl_ = prog.video_gen;
@@ -200,7 +232,11 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
name_ = prog.vgen_str.name;
ranks_ = ranks;
positions_ = positions;
segs_ = segs;
pack_ = pack;
enc_geom_ = enc_geom;
max_tok_ = prog.ctx.max_tok;
encoder_bounds(prog, &max_enc_, &patch_dim_);
if (!positions_) {
RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a "
"video generator must", name_.c_str());
@@ -212,7 +248,7 @@ int VideoDriver::init(const Program& prog, PositionsFn positions,
return RAD_E_UNSUPPORTED;
}
int64_t b[R_N][2];
bytes_ = carve(decl_, max_tok_, b, R_N);
bytes_ = carve(decl_, max_tok_, max_enc_, patch_dim_, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
frames_bytes_ = frames_bytes_of(decl_);
@@ -275,6 +311,32 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
if (T < 1 || T > d.max_text)
return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." +
std::to_string(d.max_text));
/* Reference conditioning: the images reach the language model through `media`, which the
* server built from the parts (gen/video.h) and build_cond stages into the conditioning
* pass. What this generator cannot consume yet is anything whose bytes reach the model
* through a VAE — a reference video's frames, a soundtrack, a standalone audio. Those are
* refused naming the part, rather than silently made into a weaker video. */
if (!r->refs.empty() && max_enc_ == 0)
return no("this container was converted without its vision tower, so no request can "
"carry reference media");
for (const VideoRefMedia& m : r->refs)
if (m.kind != VideoRefMedia::IMAGE)
return no("'" + m.name + "' is not consumed yet: reference videos and audios reach "
"the model through the video and audio VAEs, which the video path does not "
"run in this build; only ref_image_N parts condition a generation today");
if (!r->refs.empty() && !r->media)
return no("the request carries reference images but no processed media to condition on");
if (r->media) {
int64_t n_patch = 0;
for (const mm::Placed& p : r->media->items) {
if ((int64_t)p.tok + (int64_t)p.item->expand.size() > T)
return no("a reference's placeholder run is placed past the end of the prompt");
n_patch += p.item->n_patch;
}
if (n_patch > max_enc_)
return no("the references are " + std::to_string(n_patch) + " patches; this model "
"encodes at most " + std::to_string(max_enc_) + " in one pass");
}
if (r->chunks < d.min_chunks || r->chunks > d.max_chunks)
return no("the length must be " + std::to_string(d.min_chunks) + ".." +
std::to_string(d.max_chunks) + " chunks");
@@ -303,19 +365,108 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
j->geom.lat_h = s.lat_h;
j->geom.lat_w = s.lat_w;
j->geom.n_audio = s.n_audio;
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
/* The pack's reference table (RadVideoGenBatch::ref_tab): every reference the DiT conditions
* on, in presentation order, in ITS OWN latent grid -- {kind, slot, h, w, frames, audio} six
* words after the reference and keyframe counts. A picture's grid is the encoder's sides over
* the VAE ratio, one latent frame, no soundtrack; its slot is the one its Vencode pass folds
* its latents into. It must exist before the step layout is decided, because when the denoiser
* consumes it the reference rows are part of that layout. Only pictures queue today (videos and
* audios are refused at submit above until their decode paths land), so the keyframe count
* stays 0 and the table holds only picture rows. */
if (d.encodes)
for (size_t i = 0; i < r->refs.size(); ++i) {
const VideoRefMedia& m = r->refs[i];
if (m.kind != VideoRefMedia::IMAGE) continue;
if (m.enc_pixels.empty())
return no("'" + m.name + "' was not prepared for the video encoder");
if (m.index < 1)
return no("'" + m.name + "' has no slot in the conditioning");
if (d.enc_ratio < 1 || m.enc_h < d.enc_ratio || m.enc_w < d.enc_ratio ||
m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio)
return no("'" + m.name + "' has encoder sides (" + std::to_string(m.enc_h) + "x" +
std::to_string(m.enc_w) + ") the VAE grid of " +
std::to_string(d.enc_ratio) + " does not divide");
j->enc_q.push_back({RAD_ENC_IMAGE, m.index, (int32_t)i});
if (j->ref_tab.empty()) j->ref_tab.assign(2, 0); /* [n_refs, n_keys] */
++j->ref_tab[0];
j->ref_tab.insert(j->ref_tab.end(),
{0 /*a picture*/, m.index, (int32_t)(m.enc_h / d.enc_ratio),
(int32_t)(m.enc_w / d.enc_ratio), 1 /*one latent frame*/,
0 /*no soundtrack*/});
}
/* The step's packed sequence. When the denoiser consumes the reference table the pack is the
* only source of its rows, segment boundaries and positions -- the reference rows sit between
* the text and the target streams, so the plain `text + audio + video` arithmetic and the plain
* position layout no longer describe it. rad_arch_video_pack returns the total rows and, when
* roomy, the boundaries and the full [3, rows] planar RoPE in one call. Otherwise the plain
* layout is computed exactly as before, and a staged reference table (if any) rides inert. */
const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0);
if (nr != j->rows || nd <= 0 || nd > max_tok_)
return no("the model lays this video out in " + std::to_string(nr) + " step rows and " +
std::to_string(nd) + " decoder rows, which this server cannot run");
if (nd <= 0 || nd > max_tok_)
return no("the model lays this video's decoder in " + std::to_string(nd) + " rows, which "
"this server cannot run");
j->dec_rows = nd;
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
if (d.ref_rows && !j->ref_tab.empty()) {
if (r->upscale > 1.0)
return no("reference conditioning does not yet combine with latent upscale; ask for "
"the size you want without latent_upscale");
if (!pack_)
return no("the generator says it conditions on references but exports no "
"rad_arch_video_pack");
const int64_t pr = pack_(&j->geom, j->ref_tab.data(), nullptr, 0, nullptr, 0);
if (pr <= 0)
return no("the model refused the reference conditioning layout");
if (pr > max_tok_)
return no("a conditioned step is " + std::to_string(pr) + " rows and a pass carries " +
std::to_string(max_tok_) + "; ask for a shorter or smaller video, or fewer "
"references");
j->seg.assign((size_t)kSegCap, 0);
j->pos.assign((size_t)(3 * pr), 0.0f);
if (pack_(&j->geom, j->ref_tab.data(), j->seg.data(), kSegCap, j->pos.data(), 3 * pr) != pr)
return no("the model could not lay the reference conditioning out");
int nseg = -1;
for (int k = 0; k < kSegCap; ++k)
if (j->seg[(size_t)k] == (int32_t)pr) { nseg = k + 1; break; } /* video grid ends here */
if (nseg < 0 || nseg > kSegCap)
return no("the reference conditioning layout has no closing segment boundary");
j->seg.resize((size_t)nseg);
j->nseg = nseg;
/* The denoiser lays out one modulation cell per segment and its table is a fixed width the
* arch declares; a pack wider than it would abort the step mid-generation and take the
* engine with it. Refuse here, at submit, where a clean answer is still possible. */
const int nsegs = nseg - 1; /* `seg` is boundaries: one more than the segments */
if (d.max_ref_segs > 0 && nsegs > d.max_ref_segs) {
const int nrefs = j->ref_tab.empty() ? 0 : j->ref_tab[0];
const int64_t fit = (int64_t)d.max_ref_segs - (nsegs - nrefs); /* the fixed non-ref cells */
return no("these references lay the conditioning out in " + std::to_string(nsegs) +
" sequence segments but this deployment's conditioning table holds " +
std::to_string(d.max_ref_segs) + ", so at most " +
std::to_string(fit < 0 ? 0 : (int)fit) + " fit -- ask for fewer references");
}
/* `rows` stays the plain text+audio+video count: every non-step pass (encode, decode,
* audio, upscale) stages its own segment table and target counts from it and must see the
* bytes it sees today. Only build_step runs at the widened `step_rows`. */
j->rows = T + s.audio_rows + s.video_rows;
j->step_rows = pr;
/* The last segment (the video target) runs [seg[nseg-2], seg[nseg-1]); seg[nseg-1] is the
* total rows, so the video start is the boundary before it -- the same one the VSA takes as
* its video base (it works in segments, one fewer than the boundaries it is handed). */
j->lat_v = pr - j->seg[(size_t)(nseg - 2)];
j->lat_a = decl_.audio_channels * (int64_t)j->geom.n_audio;
j->ref_wide = true;
} else {
j->rows = T + s.audio_rows + s.video_rows;
if (j->rows > max_tok_)
return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass "
"carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video");
const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0);
if (nr != j->rows)
return no("the model lays this video out in " + std::to_string(nr) + " step rows, "
"which this server cannot run");
j->pos.assign((size_t)(3 * nr), 0.0f);
if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr)
return no("the model could not lay this video out");
j->step_rows = j->rows;
}
j->sched = video_schedule(d, steps);
if (j->sched.steps < 1) return no("the schedule has no steps");
if (r->upscale > 1.0) {
@@ -357,6 +508,17 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
}
j->n_chunks = r->chunks;
j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate);
/* The reference table and the VAE encode queue were built above, before the step layout was
* chosen: each reference picture the server decoded into encoder form rides one Vencode pass,
* at the slot its index numbers within pictures -- the slot the encoder folds its latents into
* and the step's pack scatters them from. Reference videos and audios are refused above until
* their decode paths land, so only pictures are queued and the keyframe count stays 0. */
/* The soundtrack's length, exactly the samples the decode will hand the encoder — the
* number a caller that chains clips against an audio floor checks. A build without
* libavcodec never gets the muxed file to read it back from, so it is logged here. */
RAD_INFO("video: soundtrack %.2f s, %lld samples at %lld Hz x %lld ch",
(double)j->n_samples / d.sample_rate, (long long)j->n_samples,
(long long)d.sample_rate, (long long)d.audio_channels);
VideoTicket& t = *r->ticket;
t.frames = s.frames;
@@ -367,7 +529,7 @@ int VideoDriver::submit(std::unique_ptr<VideoRequest> r, std::string* why) {
t.channels = d.audio_channels;
t.fps = (double)d.fps_num / (double)d.fps_den;
t.in_tokens = T;
t.rows = j->rows;
t.rows = j->step_rows; /* the conditioned step's real length, references included */
t.t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
@@ -445,7 +607,8 @@ int VideoDriver::upload() {
/* The geometry a pass's ops read off the device (RAD_VGEOM_*) for a pass at geometry `g` of
* `rows` step rows, with chunk `chunk`'s span when it is a decode's and both grids when the job
* upscales. */
void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk) {
void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk,
bool ref_step) {
int32_t* g = hptr<int32_t>(R_GEOM);
std::memset(g, 0, RAD_VGEOM_N * 4);
g[RAD_VGEOM_LAT_FRAMES] = g0.lat_frames;
@@ -473,15 +636,47 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up);
}
reg_[R_GEOM].used = RAD_VGEOM_N * 4;
const bool wide = j.ref_wide && ref_step;
const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio;
const int64_t video_rows = rows - g0.n_text - audio_rows;
/* With references riding, the sampler owns only the target video rows -- not the reference
* rows the pack placed ahead of them -- so the target count is the pack's, not the plain
* rows-minus-text-minus-audio. The audio target is the whole soundtrack either way. */
const int64_t video_rows = wide ? j.lat_v : rows - g0.n_text - audio_rows;
*hptr<int32_t>(R_LANE) = j.lane;
*hptr<int32_t>(R_FIRST) = j.step == 0;
int32_t* seg = hptr<int32_t>(R_SEG);
seg[0] = 0;
seg[1] = g0.n_text;
seg[2] = (int32_t)(g0.n_text + audio_rows);
seg[3] = (int32_t)rows;
if (wide) {
/* The pack laid the reference rows out ahead of the target streams, video grid last. Stage
* its boundaries verbatim: the VSA derives its segment count from the operand length, so
* every reference becomes a dense prefix sink with no kernel change. Only the step pass
* stages this table; the decode, encode and upscale passes stage the plain layout below. */
std::memcpy(seg, j.seg.data(), j.seg.size() * sizeof(int32_t));
reg_[R_SEG].used = (int64_t)j.seg.size() * 4;
} else {
/* The pack lays the segments out (rad_arch_video_segs, or the reference-aware
* rad_arch_video_pack once refs ride); for a plain request its table is the one computed
* below, so a plugin without the exports -- or one whose table disagrees with this
* geometry -- stages the same bytes either way. The pack answers with the rows, not a
* count, so a poison word at the fifth slot is what proves a plain table has no entries
* past the fourth: a pack that writes past it disagrees with this geometry. */
bool packed = false;
if (pack_) {
seg[4] = -1;
const int64_t pr = pack_(&g0, nullptr, seg, kSegCap, nullptr, 0);
packed = pr == rows && seg[4] == -1 && seg[0] == 0 && seg[1] == g0.n_text &&
seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows;
} else if (segs_) {
packed = segs_(&g0, seg, 4) == 4 && seg[0] == 0 && seg[1] == g0.n_text &&
seg[2] == (int32_t)(g0.n_text + audio_rows) && seg[3] == (int32_t)rows;
}
if (!packed) {
seg[0] = 0;
seg[1] = g0.n_text;
seg[2] = (int32_t)(g0.n_text + audio_rows);
seg[3] = (int32_t)rows;
}
reg_[R_SEG].used = 4 * 4;
}
int32_t* lat = hptr<int32_t>(R_LAT);
lat[0] = 0;
lat[1] = (int32_t)video_rows;
@@ -489,7 +684,6 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows,
lat[3] = (int32_t)audio_rows;
reg_[R_LANE].used = 4;
reg_[R_FIRST].used = 4;
reg_[R_SEG].used = 4 * 4;
reg_[R_LAT].used = 4 * 4;
}
@@ -529,6 +723,7 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to
V.dec_rows = j.dec_rows;
V.n_samples = j.n_samples;
V.upscale = dptr<float>(ri, R_UP);
V.ref_tab = j.ref_tab.empty() ? nullptr : j.ref_tab.data();
B.vgen_b = &V;
}
}
@@ -559,12 +754,20 @@ const RadBatch* VideoDriver::next(int step) {
if (!j.audio_done) return build_audio(j, step);
if (j.chunk < j.n_chunks) return build_chunk(j, step);
}
/* 2. A prompt. */
/* 2. A VAE encode of a reference-conditioned lane's media, before its prompt: one pass per
* reference, so the encoder's latents are in the lane's slot rows by the time the prompt
* and its steps run (the step's pack scatters them into the sequence). */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.cond_done) continue;
if (j.enc_next < j.enc_q.size()) return build_encode(j, step);
}
/* 3. A prompt. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 3. The oldest lane's next step, or its upscale once its small steps are done. */
/* 4. The oldest lane's next step, or its upscale once its small steps are done. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue;
@@ -602,8 +805,76 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) {
reg_[R_TA].used = j.sched.steps * 4;
const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom;
stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0);
/* Reference media for the tower and the conditioning's M-RoPE, staged exactly as the image
* driver stages a conditioned prompt (core/gen/driver.cpp's build_cond). R_ROPE holds the
* [3,T] i32 grid here and a step's f32 positions in build_step — never both in one pass, and
* step_cond reads rope_pos instead of positions when it is set. */
int64_t n_patch = 0, n_seg = 0, n_mm = 0;
int32_t max_seg = 0;
if (j.req->media) {
const mm::PromptMedia& pm = *j.req->media;
int32_t* rope = hptr<int32_t>(R_ROPE);
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
pm.rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
rope[2 * T + i] = p3[2];
}
reg_[R_ROPE].used = 3 * T * 4;
int64_t total = 0;
for (const mm::Placed& p : pm.items) total += p.item->n_patch;
uint16_t* pix = hptr<uint16_t>(R_ENCPIX);
int32_t* crd = hptr<int32_t>(R_ENCCRD);
int32_t* ecu = hptr<int32_t>(R_ENCCU);
ecu[0] = 0;
std::vector<int32_t> tmp;
for (const mm::Placed& p : pm.items) {
const mm::Item& it = *p.item;
std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(),
(size_t)(it.n_patch * patch_dim_) * 2);
tmp.resize((size_t)(4 * it.n_patch));
it.coords(0, it.n_patch, tmp.data());
for (int cc = 0; cc < 4; ++cc)
std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch,
(size_t)it.n_patch * 4);
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t a = it.patch_at(s), e = it.patch_at(s + 1);
ecu[n_seg + 1] = (int32_t)(n_patch + e);
max_seg = std::max<int32_t>(max_seg, (int32_t)(e - a));
++n_seg;
}
n_patch += it.n_patch;
}
int32_t* mmr = hptr<int32_t>(R_MMROW);
for (const mm::RopeLayout::Run& run : pm.rope.runs)
for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k;
reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2;
reg_[R_ENCCRD].used = 4 * total * 4;
reg_[R_ENCCU].used = (n_seg + 1) * 4;
reg_[R_MMROW].used = n_mm * 4;
}
if (upload() < 0) return nullptr;
base_batches(j, g, T, step);
if (j.req->media) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
const int ri = (int)r;
B.rope_pos = dptr<int32_t>(ri, R_ROPE);
B.rope_mixed = 1;
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? dptr<int32_t>(ri, R_MMROW) : nullptr;
B.enc = 0;
B.enc_n_patch = n_patch;
B.enc_pixels = n_patch ? dptr<uint16_t>(ri, R_ENCPIX) : nullptr;
B.enc_coord = n_patch ? dptr<int32_t>(ri, R_ENCCRD) : nullptr;
B.enc_n_seg = n_seg;
B.enc_cu = n_seg ? dptr<int32_t>(ri, R_ENCCU) : nullptr;
B.enc_max_seg = max_seg;
}
}
for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND;
pass_.kind = RAD_GEN_PASS_VCOND;
pass_.job = j.id;
@@ -639,7 +910,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const bool small = small_now(j);
const RadVideoGeom& g = small ? j.geom_small : j.geom;
const int64_t rows = small ? j.rows_small : j.rows;
const int64_t rows = small ? j.rows_small : j.step_rows; /* widened by references when they ride */
const std::vector<float>& pos = small ? j.pos_small : j.pos;
stage_sched(j, j.step, small && j.step == j.split - 1);
std::memcpy(hptr<float>(R_ROPE), pos.data(), pos.size() * 4);
@@ -650,7 +921,10 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) {
cu[0] = 0;
cu[1] = (int32_t)rows;
reg_[R_CU].used = 2 * 4;
stage_geom(j, g, rows, 0);
/* A reference-conditioned step stages the pack's reference-aware segment table; the plain and
* small (pre-upscale) steps stage the plain four-boundary table. ref_wide never coincides with
* small -- submit refuses upscale together with references. */
stage_geom(j, g, rows, 0, j.ref_wide);
if (upload() < 0) return nullptr;
base_batches(j, g, rows, step);
for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP;
@@ -707,6 +981,81 @@ const RadBatch* VideoDriver::build_chunk(Job& j, int step) {
return &out_[0];
}
/* One media item through its VAE encoder: stage its encoder-ready bytes and the encode geometry
* the plugin's rad_arch_encode_geom derives from them, then name the pass's kind and slot so the
* encoder folds the latents into the lane's fixed slot rows. The bytes the server decoded must
* already be padded to what the geom reports (a video's frames clip-padded, an audio's samples to
* its hop) — the encoder reads that many and no more, so a disagreement is failed here rather than
* run past the staged volume. */
const RadBatch* VideoDriver::build_encode(Job& j, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Job::EncItem& it = j.enc_q[j.enc_next];
const VideoRefMedia& m = j.req->refs[(size_t)it.ref];
const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO;
auto fail = [&](const std::string& w) {
fail_locked(j, RAD_E_STATE, w);
return nullptr;
};
if (!enc_geom_)
return fail("the request carries reference media to encode, but this plugin exports no "
"rad_arch_encode_geom");
int32_t* gd = hptr<int32_t>(R_ENCG);
if (audio) {
const int64_t n = m.enc_n;
const int32_t ch = m.enc_channels;
if (n <= 0 || ch <= 0 || (int64_t)n * ch * 4 > reg_[R_ENCSM].bytes)
return fail("a reference audio does not fit one encode pass");
int64_t in[4] = { n, 0, 0, ch };
if (enc_geom_(RAD_GEN_PASS_AENCODE, in, gd, 25) < 0)
return fail("the audio encoder refuses " + std::to_string(n) + " samples over " +
std::to_string(ch) + " channels");
if ((int64_t)gd[0] != n)
return fail("a reference audio is not padded to the length rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCSM), m.enc_samples.data(), (size_t)n * ch * 4);
reg_[R_ENCSM].used = n * ch * 4;
} else {
const int64_t nf = m.enc_frames, H = m.enc_h, W = m.enc_w;
if (nf <= 0 || H <= 0 || W <= 0 || nf * H * W * 3 * 4 > reg_[R_ENCPX].bytes)
return fail("a reference picture or video does not fit one encode pass");
int64_t in[4] = { nf, H, W, 3 };
if (enc_geom_(RAD_GEN_PASS_VENCODE, in, gd, 25) < 0)
return fail("the video encoder refuses a reference at " + std::to_string(H) + "x" +
std::to_string(W) + " over " + std::to_string(nf) + " frames");
if ((int64_t)gd[23] != nf)
return fail("a reference is not padded to the clip count rad_arch_encode_geom "
"reports");
std::memcpy(hptr<float>(R_ENCPX), m.enc_pixels.data(), (size_t)nf * H * W * 3 * 4);
reg_[R_ENCPX].used = nf * H * W * 3 * 4;
}
reg_[R_ENCG].used = 25 * 4;
stage_geom(j, j.geom, j.rows, 0);
if (upload() < 0) return nullptr;
base_batches(j, j.geom, 0, step);
for (size_t r = 0; r < ranks_.size(); ++r) {
const int ri = (int)r;
RadVideoGenBatch& V = vout_[(size_t)r];
V.enc_geom_d = dptr<int32_t>(ri, R_ENCG);
V.enc_kind = it.kind;
V.enc_slot = it.slot;
if (audio) {
V.enc_samples = dptr<float>(ri, R_ENCSM);
V.enc_n_samples = m.enc_n;
V.enc_channels = m.enc_channels;
} else {
V.enc_pixels = dptr<float>(ri, R_ENCPX);
V.enc_frames = m.enc_frames;
V.enc_height = m.enc_h;
V.enc_width = m.enc_w;
}
}
const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE;
for (auto& B : out_) B.gen = kind;
pass_.kind = kind;
pass_.job = j.id;
return &out_[0];
}
int VideoDriver::done() {
std::lock_guard<std::mutex> lk(mu_);
const int64_t now = (int64_t)rad_mono_ns();
@@ -716,6 +1065,11 @@ int VideoDriver::done() {
j->cond_done = true;
j->req->ticket->t_cond_ns = now;
break;
case RAD_GEN_PASS_VENCODE:
case RAD_GEN_PASS_AENCODE:
/* The media's latents are now in the lane's slot rows; take the next reference, if any. */
++j->enc_next;
break;
case RAD_GEN_PASS_VSTEP: {
++j->step;
VideoEvent e;
+68 -6
View File
@@ -12,8 +12,10 @@
*
* 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish
* a request and free its lane.
* 2. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 3. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
* 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the
* video and audio VAE latents are in the lane's slots before its prompt runs.
* 3. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
* Requests are denoised one after another, not in turns: a pass is one request's whole
* sequence, so taking turns would only delay the first.
*/
@@ -34,9 +36,18 @@ public:
RadStream stream = nullptr;
};
using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t);
using SegsFn = int64_t (*)(const RadVideoGeom*, int32_t*, int64_t);
using PackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t,
float*, int64_t);
using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t);
/* `positions` is the plugin's rad_arch_video_positions. */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks);
/* `positions` is the plugin's rad_arch_video_positions; `segs`, optional, is its
* rad_arch_video_segs (null = the driver stages the plain segment table itself); `pack`,
* optional, is its rad_arch_video_pack (null = reference-conditioned sequences cannot be
* laid out and such requests are refused); `enc_geom`, optional, is its
* rad_arch_encode_geom (null = no encode pass runs). */
int init(const Program& prog, PositionsFn positions, const std::vector<RankIO>& ranks,
SegsFn segs = nullptr, PackFn pack = nullptr, EncodeGeomFn enc_geom = nullptr);
void fini();
~VideoDriver() override { fini(); }
@@ -68,6 +79,38 @@ private:
int64_t n_samples = 0; /* the soundtrack's samples a channel */
VideoSchedule sched;
std::vector<float> pos; /* [3, rows] */
/* The VAE references of a reference-conditioned request (RadVideoGenBatch::ref_tab):
* the pack's input, empty until the path consumes them (it is refused at submit
* before that). The step reads it host-side, so nothing stages it. */
std::vector<int32_t> ref_tab;
/* When the generator's denoiser consumes that table (`decl_.ref_rows`), the step's packed
* sequence carries reference rows between the text and the target streams, laid out by
* rad_arch_video_pack. These hold that step layout: `ref_wide` marks it, `seg` the pack's
* segment boundaries with the video grid last, `nseg` their count, and `lat_v`/`lat_a` the
* TARGET video and audio row counts -- the rows the sampler owns and the Euler steps update,
* which the plain `rows - text - audio` arithmetic no longer recovers once references ride
* ahead of the streams. Left empty/0 on the plain path and on every non-step pass (decode,
* encode, upscale), which keep their own ref-less segment table. */
bool ref_wide = false;
int32_t nseg = 0;
std::vector<int32_t> seg;
int64_t lat_v = 0, lat_a = 0;
/* The denoising step's row count: the widened total once references ride, otherwise equal
* to `rows`. Only build_step uses it -- the encode, decode, audio and upscale passes keep
* staging against the plain `rows` (their segment table and target counts are their own,
* never the reference layout), so widening the step cannot disturb them. `pos` widens with
* it, since build_step is the only pass that stages R_ROPE from `pos`. */
int64_t step_rows = 0;
/* The VAE encode queue: the reference media whose bytes reach the model through a video or
* audio VAE, one item per Vencode/Aencode pass, in presentation order, built at submit for
* the parts the server decoded into encoder form (gen/video.h enc_pixels/enc_samples).
* `enc_kind` is the RAD_ENC_* the pass names and `enc_slot` its 1-based number within that
* kind (the reference's index); `ref` indexes req->refs. `enc_next` is the next to run;
* once it reaches enc_q.size() the media are all encoded. Empty for a request the encoder
* has nothing to do with. */
struct EncItem { int32_t kind, slot, ref; };
std::vector<EncItem> enc_q;
size_t enc_next = 0;
/* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and
* positions, the factor the network is told, and whether the upscale has run. */
int32_t split = 0;
@@ -95,8 +138,15 @@ private:
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
/* R_MMROW/R_ENCPIX/R_ENCCRD/R_ENCCU stage the conditioning pass's reference media, as the
* image generator's driver does (core/gen/driver.cpp); R_ROPE carries a step's f32 positions
* and a conditioning's [3,T] i32 M-RoPE, never in the same pass. */
/* R_ENCPX/R_ENCSM/R_ENCG stage one media item for a Vencode/Aencode pass: the encoder-ready
* pixels ([frames,h,w,3] f32) or samples ([ch,n] f32) and the encode geometry the plugin's
* rad_arch_encode_geom returned, staged verbatim as device i32 for the kernels to read. */
enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST,
R_SEG, R_LAT, R_UP, R_N };
R_SEG, R_LAT, R_UP, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU,
R_ENCPX, R_ENCSM, R_ENCG, R_N };
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
@@ -106,7 +156,8 @@ private:
/* The geometry and rows of the job's next step: the small ones before its upscale. */
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step);
void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk);
void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk,
bool ref_step = false);
void stage_sched(const Job& j, int32_t i, bool to_clean);
void stage_seed(const Job& j);
@@ -120,12 +171,23 @@ private:
const RadBatch* build_upscale(Job& j, int step);
const RadBatch* build_audio(Job& j, int step);
const RadBatch* build_chunk(Job& j, int step);
/* One Vencode or Aencode pass for the job's next queued reference (enc_q[enc_next]): stages
* that part's encoder-ready pixels or samples and the encode geometry, and names its kind and
* slot. Returns null and fails the job if the bytes no longer fit a pass. */
const RadBatch* build_encode(Job& j, int step);
RadVideoGenDecl decl_{};
std::vector<double> rungs_; /* decl_.rungs points here */
std::string name_;
PositionsFn positions_ = nullptr;
SegsFn segs_ = nullptr;
PackFn pack_ = nullptr;
EncodeGeomFn enc_geom_ = nullptr;
int64_t max_tok_ = 0;
/* The conditioning's encoder view: the tower's per-patch width and the patches one pass
* carries. Zero when the program declares no vision encoder, which bounds the media regions
* and rejects any request that carries references. */
int64_t patch_dim_ = 0, max_enc_ = 0;
std::vector<RankIO> ranks_;
char* host_ = nullptr; /* pinned, same layout as each slab */
+20
View File
@@ -156,6 +156,26 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA*
}
}
void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out) {
/* Wrapping opaque and running the RGBA kernel is exactly PIL's LANCZOS on the RGB image: at
* alpha 255 the premultiply is the identity and the divide-back takes the al == 255 branch. */
FrameRGBA pre;
pre.w = src.w;
pre.h = src.h;
pre.rgba.resize((size_t)src.w * src.h * 4);
for (size_t i = 0; i < (size_t)src.w * src.h; ++i) {
for (int c = 0; c < 3; ++c) pre.rgba[i * 4 + c] = src.rgb[i * 3 + c];
pre.rgba[i * 4 + 3] = 255;
}
FrameRGBA post;
resize_lanczos_rgba(pre, w, h, &post);
out->w = post.w;
out->h = post.h;
out->rgb.resize((size_t)post.w * post.h * 3);
for (size_t i = 0; i < (size_t)post.w * post.h; ++i)
for (int c = 0; c < 3; ++c) out->rgb[i * 3 + c] = post.rgba[i * 4 + c];
}
void composite_white(const FrameRGBA& src, Frame* out) {
out->w = src.w;
out->h = src.h;
+4
View File
@@ -18,6 +18,10 @@ namespace mm {
/* `src` resized to w x h. */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* As resize_lanczos_rgba for an opaque picture: wrapped with alpha 255 and resized, so the RGB
* channels are exactly PIL's LANCZOS on the RGB image (premultiply and its inverse are the
* identity at full alpha). The video VAE's reference preprocessing resizes RGB this way. */
void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
+34
View File
@@ -3,6 +3,8 @@
* metadata reader, the real device layer. */
#include "mm/processor.h"
#include <algorithm>
namespace rad {
namespace mm {
@@ -43,5 +45,37 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
}
}
/* The rotary layout of one prompt: one run per segment, the text in front of a run counting up
* and a grid advancing the rotary by its longer side. Pure computation over the items, like the
* accessors above, so it lives here rather than in the processor. */
void PromptMedia::layout() {
rope.runs.clear();
int64_t pos = 0, tok = 0;
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
}
} /* namespace mm */
} /* namespace rad */
+35 -31
View File
@@ -1,5 +1,6 @@
/* processor.cpp -- see processor.h. */
#include "mm/processor.h"
#include "mm/imaging.h"
#include "rad_internal.h"
#include "rad_plugin.h"
@@ -1006,6 +1007,40 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
return image_from(f, out, why);
}
int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
Frame* out, std::string* why) const {
if (ratio < 1 || max_side < ratio) {
if (why) *why = "the encoder's side ratio and maximum are not usable";
return RAD_E_INVAL;
}
/* The same decode guard as image(): a reference the text encoder accepts must reach the VAE
* too, so the two never disagree on what a request may carry. */
Frame f;
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
/* Snap both sides down to a multiple of the encoder's ratio, neither above max_side, aspect
* kept as close as the grid allows: scale the longest side to fit, then floor each side to the
* grid. Flooring (never rounding up) is what keeps a side within max_side; a side under one
* grid step is raised to it, the smallest volume the encoder accepts. Our encoder runs one
* volume rather than tiling at 256, so a reference larger than the bound is shrunk here — the
* one place the reference and this build differ on an oversized input. */
auto snap = [&](int64_t s) {
int64_t v = (s / ratio) * ratio;
if (v < ratio) v = ratio;
if (v > max_side) v = max_side; /* max_side is itself a multiple of ratio */
return (int32_t)v;
};
const int32_t longest = std::max(f.w, f.h);
const double scale = longest > max_side ? (double)max_side / (double)longest : 1.0;
const int32_t w = snap((int64_t)std::floor(f.w * scale));
const int32_t h = snap((int64_t)std::floor(f.h * scale));
if (w == f.w && h == f.h) {
*out = std::move(f);
return RAD_OK;
}
resize_lanczos_rgb(f, w, h, out);
return RAD_OK;
}
namespace {
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
@@ -1528,36 +1563,5 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
return audio_from(s, out, why);
}
/* ================================================================== rotary layout */
void PromptMedia::layout() {
rope.runs.clear();
int64_t pos = 0, tok = 0;
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
}
} /* namespace mm */
} /* namespace rad */
+9
View File
@@ -318,6 +318,15 @@ public:
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
/* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as
* `image` (so any reference the text encoder accepts the encoder accepts too), then scaled —
* aspect kept — so both sides are multiples of `ratio` and neither exceeds `max_side`, the
* single-volume encoder's square bound. Returns the resized RGB; the caller hands it to the
* encoder un-normalised (the VAE applies its own mean/std). `ratio`/`max_side` come from the
* generator's declaration (RadVideoGenDecl enc_ratio / max_enc_side). */
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, Frame* out,
std::string* why) const;
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
* encoder's. */
int init_audio(const AudioConfig& cfg, std::string* why = nullptr);
+13
View File
@@ -225,6 +225,19 @@ int Registry::commit_(Staged& s, int order) {
/* A video generator's rotary positions; the driver refuses to start without it. */
p.arch_video_positions = dl_fn<int64_t (*)(int, const RadVideoGeom*, float*, int64_t)>(
s.handle, "rad_arch_video_positions");
/* Optional: the pack's segment boundary table; absent means the video driver stages the
* plain [text | audio | video] table itself. */
p.arch_video_segs = dl_fn<int64_t (*)(const RadVideoGeom*, int32_t*, int64_t)>(
s.handle, "rad_arch_video_segs");
/* Optional: the pack with the references in; absent means the driver lays no
* reference-conditioned sequence out. */
p.arch_video_pack =
dl_fn<int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t)>(s.handle, "rad_arch_video_pack");
/* Optional: the encode passes' geometry; absent means the driver runs no encode pass. */
p.arch_encode_geom =
dl_fn<int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t)>(
s.handle, "rad_arch_encode_geom");
/* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim
* the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16
+9
View File
@@ -94,6 +94,15 @@ struct Plugin {
int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr;
/* Required of a video generator (rad_builder.h); null for every other plugin. */
int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr;
/* Optional (rad_builder.h); null means the video driver stages the plain
* [text | audio | video] boundary table itself. */
int64_t (*arch_video_segs)(const RadVideoGeom*, int32_t*, int64_t) = nullptr;
/* Optional (rad_builder.h); null means the driver lays no reference-conditioned sequence
* out and refuses requests that carry VAE references. */
int64_t (*arch_video_pack)(const RadVideoGeom*, const int32_t*, int32_t*, int64_t, float*,
int64_t) = nullptr;
/* Optional (rad_builder.h); null means the driver runs no encode pass. */
int64_t (*arch_encode_geom)(int32_t, const int64_t*, int32_t*, int64_t) = nullptr;
RadPluginCloseFn close = nullptr;
};
+9
View File
@@ -710,6 +710,15 @@ public:
: p_->video(bytes.data(), bytes.size(), out, why);
}
int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
mm::Frame* out, std::string* why) override {
if (!p_ || !mm::decoder_available()) {
if (why) *why = "no picture decoder is available";
return RAD_E_UNSUPPORTED;
}
return p_->encoder_image(bytes, n, ratio, max_side, out, why);
}
int32_t audio_rate() const override {
return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0;
}
+3
View File
@@ -399,6 +399,9 @@ json Server::capabilities() const {
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
caps["audio_generation"] = deps_.audio != nullptr;
caps["video_generation"] = deps_.videos != nullptr;
/* A video model also says what a request may carry, so a client can gate on it the way it
* gates on /v1/models elsewhere; the counts are the ones a request will actually meet. */
if (deps_.videos) video_caps(caps, deps_.videos);
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
+23
View File
@@ -533,6 +533,17 @@ public:
virtual int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
std::shared_ptr<mm::Item>* out, std::string* why) = 0;
/* A picture in a video VAE's encoder-ready form: decoded under the same guard as prepare() and
* resized so both sides are multiples of `ratio` and neither exceeds `max_side`. The video
* generator's server uses it to fill a reference's encoder pixels; a server with no video VAE
* leaves it unsupported. */
virtual int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
mm::Frame* out, std::string* why) {
(void)bytes; (void)n; (void)ratio; (void)max_side; (void)out;
if (why) *why = "this server prepares no reference media for a video encoder";
return RAD_E_UNSUPPORTED;
}
/* Audio in two halves, for a route that cuts a long recording into clips itself
* (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most
* `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most
@@ -644,6 +655,18 @@ struct VideoGenInfo {
/* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */
double upscale_max = 0.0;
int64_t upscale_refine = 0;
/* Reference conditioning (SGLang's task "ref2va"): how many reference images, videos and
* standalone audios the model takes — all 0 for one that makes video from text only, which
* is every model until the declaration carries them (abi/rad_builder.h, RadVideoGenDecl).
* A video's soundtrack rides with the video and is not counted among the audios. */
int64_t max_ref_images = 0, max_ref_videos = 0, max_ref_audios = 0;
/* The video and audio VAE encoders (RadVideoGenDecl): nonzero when the container carries them,
* so the server decodes and resizes reference media into the encoder's own form before submit;
* the per-pass ceilings it snaps to (a video's clip-padded frames, the encoder's square side,
* an audio's samples) and `enc_ratio`, the side multiple the geom demands. All 0 without the
* encoders — a text-only or TE-only model leaves them and the server never prepares pixels. */
int64_t encodes = 0, max_enc_frames = 0, max_enc_side = 0, max_enc_samples = 0;
int64_t enc_ratio = 0;
};
class IVideoGen {
+4
View File
@@ -288,6 +288,10 @@ private:
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
json capabilities() const;
/* What a video model lets a request carry: the prompt ceiling the /v1/videos parser
* enforces and the reference-media counts, as validate_refs() will apply them. Defined in
* videos.cpp, beside the ref2va contract's own caps. */
static void video_caps(json& caps, const IVideoGen* gen);
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
/* ------------------------------------------------------------------ dashboard.cpp */
+287 -22
View File
@@ -15,8 +15,11 @@
* (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or
* `short_edge`), the area capped at the model's largest, both sides rounded to the multiple.
* A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next.
* Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are
* refused.
* A model that takes reference media (VideoGenInfo) also serves SGLang's `task` value `ref2va`:
* the media are form file parts named `ref_image_N` (at most 9), `ref_video_N` (3), a video's
* soundtrack as `ref_video_audio_N` and standalone audios as `ref_audio_N` (3), N 1-based and
* contiguous within each kind. `input_reference` and non-empty `conditions` are still refused:
* the parts carry the bytes, so no JSON array of media is read.
*
* A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
@@ -38,11 +41,15 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <random>
#include <thread>
#include <vector>
namespace rad {
namespace server {
@@ -61,6 +68,9 @@ struct Server::VideoJob {
std::string err_code, err_message;
std::string mp4;
std::vector<uint8_t> first; /* the first frame, RGB, for the thumbnail */
/* Reference conditioning: the reference parts' names in conditioning order, empty for a
* text-only job. */
std::vector<std::string> refs;
/* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the
* small size; refine 0 when the video is not upscaled. */
double upscale = 0.0;
@@ -118,8 +128,137 @@ void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int6
*h = std::max<int64_t>(mult, (int64_t)std::nearbyint(H / mult) * mult);
}
/* What a ref2va request may carry whatever a model declares: the reference media the source
* workflows were built with — nine images, three videos each with an optional soundtrack, three
* standalone audios. A model's declaration can only lower these. */
constexpr int32_t kMaxRefImages = 9, kMaxRefVideos = 3, kMaxRefAudios = 3;
/* A form file part's name for task ref2va: `ref_image_N`, `ref_video_N`, `ref_video_audio_N`
* (a video's separately-given soundtrack) or `ref_audio_N`, N plain and 1-based. False for any
* other name; `ref_video_audio_` is tried before `ref_video_` because one contains the other. */
bool parse_ref_name(const std::string& name, gen::VideoRefMedia::Kind* kind, int32_t* index) {
static const struct { const char* pfx; gen::VideoRefMedia::Kind kind; } kKinds[] = {
{ "ref_image_", gen::VideoRefMedia::IMAGE },
{ "ref_video_audio_", gen::VideoRefMedia::VIDEO_AUDIO },
{ "ref_video_", gen::VideoRefMedia::VIDEO },
{ "ref_audio_", gen::VideoRefMedia::AUDIO },
};
for (const auto& k : kKinds) {
const size_t n = std::strlen(k.pfx);
if (name.compare(0, n, k.pfx) != 0 || name.size() == n) continue;
char* e = nullptr;
const long v = std::strtol(name.c_str() + n, &e, 10);
if (*e == '\0' && v >= 1 && v <= 99) { *kind = k.kind; *index = (int32_t)v; return true; }
}
return false;
}
/* True when the file ends in one of these extensions, case-insensitively — what the client
* called the file, which the media readers make the first word of what it holds. */
bool has_ext(const std::string& f, const std::vector<std::string>& exts) {
const size_t d = f.find_last_of('.');
if (d == std::string::npos) return false;
std::string e = f.substr(d + 1);
for (char& c : e) c = (char)std::tolower((unsigned char)c);
for (const std::string& x : exts) if (e == x) return true;
return false;
}
std::string ext_list(const std::vector<std::string>& exts) {
std::string s;
for (const std::string& x : exts) { if (!s.empty()) s += ", "; s += "." + x; }
return s;
}
/* The reference parts of a ref2va request, and their order. Refused with `*err` naming the part
* when one carries no bytes or an extension the media readers do not take, when a kind is over
* the API's or the model's count, when a kind's numbers leave a gap or repeat, or when a
* soundtrack has no video of the same number. On return `refs` is sorted by (kind, number): the
* order the generator builds the conditioning in. */
int validate_refs(std::vector<gen::VideoRefMedia>& refs, const VideoGenInfo& info, ApiError* err) {
if (refs.empty()) {
*err = err_bad("task", "ref2va takes at least one reference part: ref_image_N, "
"ref_video_N, ref_video_audio_N or ref_audio_N");
return -1;
}
const struct {
const char* pfx;
gen::VideoRefMedia::Kind kind;
int32_t cap;
std::vector<std::string> exts;
} kinds[] = {
{ "ref_image", gen::VideoRefMedia::IMAGE,
std::min(kMaxRefImages, (int32_t)info.max_ref_images),
{ "png", "jpg", "jpeg", "webp" } },
{ "ref_video", gen::VideoRefMedia::VIDEO,
std::min(kMaxRefVideos, (int32_t)info.max_ref_videos),
{ "mp4", "mov" } },
{ "ref_video_audio", gen::VideoRefMedia::VIDEO_AUDIO,
std::min(kMaxRefVideos, (int32_t)info.max_ref_videos),
{ "mp4", "mov", "wav", "mp3", "m4a", "aac", "flac", "ogg" } },
{ "ref_audio", gen::VideoRefMedia::AUDIO,
std::min(kMaxRefAudios, (int32_t)info.max_ref_audios),
{ "wav", "mp3", "m4a", "aac", "flac", "ogg" } },
};
for (const auto& k : kinds) {
std::vector<bool> got(k.cap + 1, false);
int n = 0;
for (const gen::VideoRefMedia& m : refs) {
if (m.kind != k.kind) continue;
++n;
if (m.data.empty())
return *err = err_bad(m.name, "'" + m.name + "' carries an empty file"), -1;
if (!has_ext(m.filename, k.exts))
return *err = err_bad(m.name, "'" + m.name + "' must be one of " +
ext_list(k.exts)), -1;
if (m.index > k.cap)
return *err = err_bad(m.name, k.cap == 0
? "this model takes no parts named " +
std::string(k.pfx) + "_N"
: "this model takes at most " +
std::to_string(k.cap) + " parts named " +
std::string(k.pfx) + "_N"), -1;
if (got[m.index])
return *err = err_bad(m.name, "two parts are numbered " + std::string(k.pfx) +
"_" + std::to_string(m.index)), -1;
got[m.index] = true;
}
for (int i = 1; i <= n; ++i)
if (!got[i])
return *err = err_bad(std::string(k.pfx) + "_" + std::to_string(i),
"the " + std::string(k.pfx) + "_N parts must be numbered 1 "
"to " + std::to_string(n) + " without gaps or repeats"), -1;
}
for (const gen::VideoRefMedia& m : refs) {
if (m.kind != gen::VideoRefMedia::VIDEO_AUDIO) continue;
bool paired = false;
for (const gen::VideoRefMedia& v : refs)
paired = paired || (v.kind == gen::VideoRefMedia::VIDEO && v.index == m.index);
if (!paired)
return *err = err_bad(m.name, "'" + m.name + "' is the soundtrack of a reference "
"video; give ref_video_" + std::to_string(m.index) +
" with it"), -1;
}
std::stable_sort(refs.begin(), refs.end(),
[](const gen::VideoRefMedia& a, const gen::VideoRefMedia& b) {
return a.kind != b.kind ? a.kind < b.kind : a.index < b.index;
});
return 0;
}
} /* namespace */
/* The caps the /v1/models and /server_info capability block reports for a video model. The
* counts are the ones validate_refs() will apply — the model's declaration under the API's,
* since a declaration can only lower those — so what a client gates on is what it will meet. */
void Server::video_caps(json& caps, const IVideoGen* gen) {
const VideoGenInfo& info = gen->info();
caps["video_max_text"] = info.max_text;
caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images);
caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos);
caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios);
}
HttpResponse Server::handle_video_create(const HttpRequest& req) {
if (!deps_.videos || !deps_.tok)
return error_response(err_not_implemented(
@@ -127,17 +266,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
req.peer);
const VideoGenInfo& info = deps_.videos->info();
const bool takes_refs = info.max_ref_images > 0 || info.max_ref_videos > 0 ||
info.max_ref_audios > 0;
/* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form,
* since it may carry a file). */
* since it may carry a file). A form may carry the reference media of a ref2va request as
* named file parts; they are collected here and checked once the task is known. */
std::vector<gen::VideoRefMedia> refs;
json body = json::object();
if (!req.form.empty()) {
for (const FormPart& p : req.form) {
if (p.name == "input_reference")
return error_response(err_unsupported("input_reference", "this server makes video "
"from text only"), req.peer);
if (!p.filename.empty())
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"),
req.peer);
return error_response(err_unsupported("input_reference", takes_refs
? "this server reads reference media as "
"ref_image_N file parts"
: "this server makes video from text "
"only"), req.peer);
if (!p.filename.empty()) {
gen::VideoRefMedia m;
if (!parse_ref_name(p.name, &m.kind, &m.index))
return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a "
"file"), req.peer);
m.name = p.name;
m.filename = p.filename;
m.content_type = p.content_type;
m.data = p.data;
refs.push_back(std::move(m));
continue;
}
json v = p.data;
if (p.name == "target" || p.name == "conditions") {
v = json::parse(p.data, nullptr, false);
@@ -179,16 +334,41 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
return bad("prompt", "the prompt is required, as a non-empty string");
const std::string prompt = body["prompt"].get<std::string>();
if (has(body, "input_reference"))
return error_response(err_unsupported("input_reference", "this server makes video from "
"text only"), req.peer);
if (has(body, "task") && (!body["task"].is_string() || body["task"].get<std::string>() != "t2va")) {
ApiError e = err_unsupported("task", "this server makes video from text: t2va");
e.supported = { "t2va" };
return error_response(e, req.peer);
return error_response(err_unsupported("input_reference", takes_refs
? "this server reads reference media as ref_image_N "
"file parts"
: "this server makes video from text only"),
req.peer);
/* The task: text always; reference conditioning for a model that takes reference media. */
bool ref2va = false;
if (has(body, "task")) {
const std::string task = body["task"].is_string() ? body["task"].get<std::string>() : "";
if (task == "ref2va" && takes_refs) ref2va = true;
else if (task != "t2va") {
ApiError e = err_unsupported("task", takes_refs
? "this server makes video from text or from reference "
"media: t2va, ref2va"
: "this server makes video from text: t2va");
e.supported = takes_refs ? std::vector<std::string>{ "t2va", "ref2va" }
: std::vector<std::string>{ "t2va" };
return error_response(e, req.peer);
}
}
if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty()))
return error_response(err_unsupported("conditions", "this server makes video from text "
"only; conditions must be empty"), req.peer);
return error_response(err_unsupported("conditions", takes_refs
? "reference media arrive as ref_* file parts; "
"conditions must be empty"
: "this server makes video from text only; "
"conditions must be empty"), req.peer);
/* The reference parts, in conditioning order, before anything else reads them. Files with no
* task are a caller's mistake about the task, not about the part. */
if (!refs.empty() && !ref2va)
return bad("task", "reference files are given: send them with task ref2va, or send "
"none");
if (ref2va) {
ApiError e;
if (validate_refs(refs, info, &e) < 0) return error_response(e, req.peer);
}
json target = json::object();
if (has(body, "target")) {
if (!body["target"].is_object()) return bad("target", "expected an object");
@@ -314,8 +494,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
std::random_device rd;
r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
r->refs = std::move(refs);
/* ---- the prompt: the template's text with special tokens, the prompt without */
/* ---- the prompt: the template's text with special tokens, the reference media in its
* presentation order, the prompt last (docs/PORT-REF2VA.md §3: images, then videos each
* after its soundtrack's label, then the standalone audios). Each `<Picture k>: ` label is
* encoded as its own string, as the tokenizer the source workflows were checked against sees
* it; the picture's token run follows its label, taken from the processed item. */
{
static const std::string kSlot = "{prompt}";
const std::string& t = info.tmpl;
@@ -325,15 +510,89 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
const auto ids = deps_.tok->encode(s, false, special);
r->tokens.insert(r->tokens.end(), ids.begin(), ids.end());
};
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
/* The reference media are presented between the template's head and the prompt. Only the
* images reach the language model, so only they are decoded and processed here; a
* reference video's frames and every audio ride the video and audio VAE encoders, which
* the video path does not run in this build yet, so their parts pass through as bytes for
* the generator to refuse at submit naming the part — not silently dropped. (When videos
* land, a soundtrack's `<Audio j>` label is emitted right before its `<Video k>` label,
* the audio ordinal counting soundtracks and standalone audios together, per type.) */
if (ref2va && deps_.mm && deps_.mm->accepts(MediaKind::Image)) {
/* Every picture is decoded and processed before any token is laid down. */
std::vector<std::shared_ptr<mm::Item>> pics;
MediaOpts mo;
mo.max_pixels = (int64_t)W * (int64_t)H; /* `match`: scaled to the output's area */
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
const std::vector<uint8_t> bytes(m.data.begin(), m.data.end());
std::shared_ptr<mm::Item> it;
std::string why;
if (deps_.mm->prepare(MediaKind::Image, bytes, mo, &it, &why) < 0 || !it)
return bad(m.name.c_str(), "'" + m.name + "' could not be used: " + why);
pics.push_back(std::move(it));
}
put(t.substr(0, p), true);
if (!pics.empty()) {
auto media = std::make_shared<mm::PromptMedia>();
size_t i = 0;
for (const gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
/* validate_refs numbered each kind 1..n without gaps, so the part's number is
* its presentation ordinal: `<Picture k>: ` then the picture's token run. The
* label is encoded as its own string, as the reference tokenizer's output was
* built. */
put("<Picture " + std::to_string(m.index) + ">: ", false);
mm::Placed pl;
pl.item = pics[i++];
pl.tok = (int32_t)r->tokens.size();
r->tokens.insert(r->tokens.end(), pl.item->expand.begin(),
pl.item->expand.end());
media->items.push_back(std::move(pl));
}
media->layout();
r->media = std::move(media);
}
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
} else {
put(t.substr(0, p), true);
put(prompt, false);
put(t.substr(p + kSlot.size()), true);
}
if ((int64_t)r->tokens.size() > info.max_text)
return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) +
return bad("prompt", "the prompt" + std::string(ref2va ? " with its reference media"
: "") +
" is " + std::to_string(r->tokens.size()) +
" tokens; this model takes at most " +
std::to_string(info.max_text));
}
/* ---- the encoder's own view of every reference the VAE consumes. The text encoder saw the
* pictures above for identity; now each is also decoded and shrunk to the encoder's grid so the
* video VAE can turn it into conditioning rows. The driver stages these bytes into a Vencode
* pass; reference videos and their soundtracks, and the standalone audios, ride the same two
* encoders but are still refused at submit until those decode paths land, so only pictures are
* prepared here. The processor decodes under the same guard it used for the text encoder, so a
* reference that got this far decodes here too. */
if (ref2va && info.encodes && deps_.mm) {
for (gen::VideoRefMedia& m : r->refs) {
if (m.kind != gen::VideoRefMedia::IMAGE) continue;
mm::Frame fr;
std::string why;
if (deps_.mm->encoder_image((const uint8_t*)m.data.data(), m.data.size(),
(int32_t)info.enc_ratio, (int32_t)info.max_enc_side, &fr,
&why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be encoded: " + why);
m.enc_frames = 1;
m.enc_h = fr.h;
m.enc_w = fr.w;
/* un-normalised RGB 0..255, row-major; the video VAE applies ImageNet mean/std itself */
m.enc_pixels.resize((size_t)fr.w * fr.h * 3);
for (size_t i = 0; i < m.enc_pixels.size(); ++i)
m.enc_pixels[i] = (float)fr.rgb[i];
}
}
/* ---- admitted and queued: the job holds its place until its file is written */
if (auto no = admit(1, req.peer)) return *no;
auto j = std::make_shared<VideoJob>();
@@ -344,6 +603,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->size = std::to_string(W) + "x" + std::to_string(H);
j->created_at = unix_now();
j->seed = r->seed;
for (const gen::VideoRefMedia& m : r->refs) j->refs.push_back(m.name);
j->ticket = std::make_shared<gen::VideoTicket>();
r->ticket = j->ticket;
const int64_t n_tok = (int64_t)r->tokens.size();
@@ -365,13 +625,14 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
j->refine = tk.refine;
j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height);
}
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s, seed=%llu",
RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s%s, seed=%llu",
j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(),
(long long)n_tok, steps > 0 ? steps : (int)tk.steps,
tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)",
(int)(tk.steps - tk.refine), (int)tk.small_width,
(int)tk.small_height, (int)tk.refine).c_str()
: "",
j->refs.empty() ? "" : rad::fmt(", %zu reference parts", j->refs.size()).c_str(),
(unsigned long long)j->seed);
std::lock_guard<std::mutex> lk(videos_m_);
sweep_videos_locked(unix_now());
@@ -530,6 +791,10 @@ json Server::video_json(const VideoJob& j) {
o["upscale_refine_steps"] = j.refine;
o["upscale_from"] = j.upscale_from;
}
if (!j.refs.empty()) {
o["task"] = "ref2va";
o["refs"] = j.refs; /* the reference parts, in conditioning order */
}
o["remixed_from_video_id"] = nullptr;
if (j.failed) {
json e;
+22 -1
View File
@@ -30,7 +30,10 @@
# step or less: the embedding table, context_embedder and norm_out (bf16), the timestep MLP and the
# four patch projections (f32), every norm and bias. The video decoder's linears are cast to bf16
# from the checkpoint's f32, its norms, layer scales, biases and register tokens stay f32; the
# audio decoder stays f32 (its weight norms folded at convert).
# audio decoder stays f32 (its weight norms folded at convert). The ref2va encoders convert with
# them when the checkpoint ships them: the audio encoder's f32 chain convs are weight-normalised
# and stored folded; the video encoder's 3x3x3 convs are cast to bf16, which is how the implicit-
# GEMM kernel stores them (conv_in and the k=1 convs read f32 as declared and need no rule).
te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
@@ -53,5 +56,23 @@ vae.blk.*.ffn_up.weight cast dtype=bf16
vae.blk.*.ffn_down.weight cast dtype=bf16
vae.proj_out.* cast dtype=bf16
aud.*.weight cast dtype=f32
# The audio encoder's strided downsamplers and its attention/MLP pre-block run in a bf16 island
# inside the f32 chain (arch/minimaxh3/minimaxh3.cpp, declare_aenc): conv1d, layernorm and gemm
# pin every operand to one dtype, so their weights cast; the chain's own f32 weights are stored
# folded from the checkpoint's weight-norm pairs.
aenc.d*.w cast dtype=bf16
aenc.d*.b cast dtype=bf16
aenc.pb.* cast dtype=bf16
aenc.b*.u*.c1.weight cast dtype=f32
aenc.b*.u*.c2.weight cast dtype=f32
aenc.cin.weight cast dtype=f32
aenc.fin.weight cast dtype=f32
# The video encoder: the implicit-GEMM kernel stores its 3x3x3 weights bf16 tap-major, so those
# four name classes cast; conv_in (3 input channels) and the k=1 shortcut/quant convs run on the
# reference kernel with their f32 weights as they are, and the norms and biases need no rule.
venc.l*.b*.c1w cast dtype=bf16
venc.l*.b*.c2w cast dtype=bf16
venc.l*.dnw cast dtype=bf16
venc.cout.weight cast dtype=bf16
ups.embed.* cast dtype=f32
ups.*.emb_layers.* cast dtype=f32
+135
View File
@@ -0,0 +1,135 @@
# P2 port note — the VAE encode, from ComfyUI source
Read directly from `/home/dustin/AI/ComfyUI/comfy/ldm/minimax/vae.py` and `audio_vae.py`
(2026-10 install) so the Radiance port is source-faithful rather than doc-derived. Line numbers
below are those files'. §5.5 of `PORT-REF2VA.md` scoped the whole of P2 (kernels, graphs,
declare, re-convert); this note is the extraction underneath it, and the **host half has
landed**: `arch/minimaxh3/rad_vae_geom.{h,cpp}` + `tests/vae_geom_test.cpp` (bottom section).
## Video encoder — `EncoderFCN3D` (vae.py :176-228) and its blocks
Constructor arguments (`MiniMaxH3VideoVAE.__init__` :409-441): `ch=128`, `ch_mult=(1,2,2,4,4,8)`,
`space_down=(2,2,2,2,1,1)`, `time_down=(1,2,2,1,1,1)`, `num_res_blocks=2`, `z_channels=24`,
`double_z=True` (moments = 2·24 = 48 channels). Derived: `vae_ratio=16`, `vae_ratio_t=8`,
`clip_length=17`, `token_drop=3`, `tile_size=256`, `tile_overlap_min=64` — and the decode-side
`frame_pre_padding=7`, `tokens_chunk_size=3`, `token_overlap=0`, `frame_overlap=0` (the engine's
decode driver already encodes these; not re-ported).
- `CausalConv3d` (:72-118): spatial **reflect** pad `(w,w,h,h)` (or explicit `spatial_pad`),
temporal **front-only zero pad** `2*pad_t`, stride-s conv with no further padding. The single
exception: when the input has one frame (`x.shape[2]==1`) the physical pad is skipped
(`front = 0`) and the temporal taps are truncated instead (`autopad="causal_zero"` :101-103) —
semantically a front zero pad of `k_t − 1`, so T=1 in ⇒ T=1 out at every layer. The 1×1
shortcut conv has nothing to fold (:87, pads stay off). The kitchen fused pad/GN paths
(:41-70, :75-86) are CUDA-only fast paths; the CPU path is exactly pad → conv.
- `TemporalIsolatedGroupNorm` (:122-130): GroupNorm **statistics per frame** (time folded into
batch), 32 groups, `eps=1e-6`, affine — libr4d's `group_norm` (OPS.md:1276) reduces over ALL
rows, so the encode variant must fold T into N.
- `Downsample3D` (:137-152): `CausalConv3d` k3 `padding=(1,0,0)` stride `(time_stride, s, s)`,
called with `spatial_pad=(0,1,0,1)` when s=2 — **right/bottom-only** spatial pad, not centered.
Temporally it is exactly `L → ceil(L / time_stride)` (front pad 2, k3: `(L+2−3)/t+1`);
spatially `(L + 0 + 1 − 3)/2 + 1 = ceil(L/2)` too, but the pad asymmetry matters for values.
- `ResnetBlock3D` (:155-173): silu→GN→conv1 k3p1; 1×1 shortcut if channels differ;
silu→GN→conv2 k3p1 + residual. All stride 1 ⇒ **length-preserving** (taps: k3 p1 front pad 2).
- Graph (:218-228): `conv_in` k3p1 → per level (2 × ResnetBlock, then `Downsample3D` wherever
`space_down[i]*time_down[i] > 1`) → `conv_out` with `pre_norm=norm_out` (GN+silu folded).
Lengths: temporal `17 → ceil(17/2)=9 → ceil(9/2)=5` (only two levels time-downsample), then
levels 3-5 stride 1 in time; spatial 16× at levels 0-3.
## Video encode — chunking, tiling, normalization
- `_normalize_pixels` (:485-486): pixels in [−1,1] → `((x+1)/2 − IMAGENET_MEAN)/IMAGENET_STD`
with `IMAGENET_MEAN=(0.485,0.456,0.406)`, `IMAGENET_STD=(0.229,0.224,0.225)`.
`_encode_moments` (:479-480) = `quant_conv(encoder(x))` (1×1 to 48ch).
- `encode` (:775-792): T=1 encodes alone and takes `moments[:,:,-1:]` — one latent; T≥2 goes
through `encode_temporal` (:647-661): `ceil(T/17)` clips, the short last clip **padded by
repeating its final frame** to 17, each clip → 5 latents, cat, **drop the last 3** ⇒
**L(T) = 5·ceil(T/17) − 3**. Mean only — `chunk(moments.float(), 2, dim=1)[0]`, **no sampling**,
then `(mean − LATENTS_MEAN)/LATENTS_STD` (:20-38, 24 doubles each, transcribed into
`kVaeLatentsMean/Std`). Deterministic ⇒ golden parity against the reference is well-defined.
- `split_tiles` (:514-536), per axis, always on (per `encode_tiled`'s comment :794-796): if 256 ≥ len, one
tile; else `N = ceil(len/256)` grown until `256N − 64(N−1) − len ≥ 0`; slack
`remaining // 16` is spread **+16 px round-robin over the overlaps**; starts cumulate
`256 − overlap`. Worked 1344: N=7, overlaps [80,80,80,80,64,64], starts
[0,176,352,528,704,896,1088], last window ends exactly at 1344. Tile slices clamp at the axis
end (`x[..., pos:pos+256]`), so the last tile can be short.
- `tiled_encode` (:563-590): per-tile `_encode_moments`; latent overlaps = overlap//16; the
blend (:538-561) is a **linear ramp** `pos/blend_extent` over the overlap (extent clamped to
both tiles), blending top-of-prev with top-of-current, **cutting** the trailing overlaps from
each tile before concatenation. Net effect: the moments grid is exactly `len/16` per axis —
verified end to end by golden runs (320→20, 512→32, 288→18, 192→12 latents).
## Audio encoder — DAC strided stack (audio_vae.py) + posterior head
- `ResidualUnit` (:155-172): Snake → conv k7 dil `d`, symmetric pad `(7−1)d/2` → Snake → conv
k1; **length-preserving** (pad = exactly the dilation slack), residual add.
`EncoderBlock` (:174-192): 3 ResidualUnits (dil 1,3,9) → Snake → conv `k=2s, p=ceil(s/2)`,
stride s — exact division at lengths divisible by s (the wrapper's right pad guarantees it).
- `Encoder` (:195-209): conv k7 p3 in (length-preserving) → blocks at dims 128…2048, strides
**(2,4,4,5,5)** → Snake → conv k3 p1 to 2048. Hop = 2·4·4·5·5 = **800** samples (40 latent
frames/s at 32 kHz). Stereo is split to mono streams (`reshape(b*s, 1, −1)`) — the encoder is
mono; channels rejoin only in the output reshape.
- `encode` (:427-443): **right-pad zeros to a multiple of 800** ⇒ `T = ceil(samples/800)`
exactly (verified against the real chain at 13 lengths); `pre_block` `AttnProjection`
(:253-269) = LayerNorm + causal 8-head attention + Linear + GeGluMlp on the **time axis as
sequence** — no strided op, time-preserving; `mean_proj` 1×1; normalize by the stored
`latents_mean/std`; out `[B, 32, 2, T]`. Mean only again.
- `Snake1d` (:30-40): `x + sin²(αx)/α`, per-channel α — libr4d already has `snake` (OPS.md).
## Landed 2026-10-19 — `arch/minimaxh3/rad_vae_geom.{h,cpp}` (the host half)
The sizing questions the kernels and the driver will ask, answered as a device-free TU:
`vae_latent_frames` (the clip plan incl. the T=1 case), `vae_clip_latents` (the raw causal
chain — `ceil(T/4)` for T≥2, the nested ceil collapsing), `vae_audio_latents` (the hop rule),
`vae_split_tiles` (the tile plan: starts, real clamped slice lengths, pixel overlaps), and the
verbatim constant tables (`kVaeLatentsMean/Std`, `kVaePixelMean/Std`).
`tests/vae_geom_test.cpp` compiles the TU directly (no core, no device) against
`tests/data/vae_geom/golden.json`, which `gen_golden.py` produces **by running the reference's
real encoders on CPU**: the video `EncoderFCN3D` with the reference constructor arguments plus
the wrapper's own `encode()/encode_temporal()/split_tiles()/tiled_encode()` bound to a shim
self, and the audio DAC encoder. The shims are exactly the pieces the CPU guards keep off the
fast paths (`comfy.quant_ops` without `ck`; `Conv3d.forward` accepting `autopad="causal_zero"`
as the implicit front zero pad). 408 checks, 7 cases: the latent-count lattice through
`encode()` end to end (it reproduces the continuity snaps {5,22,39,56,73} ↔ {2,7,12,17,22} as
the network's own output), the clip chain composing with the encode count, tile plans against
the reference's literal returns, the blended tile grids keeping exact size, audio latents at 13
lengths, and the constant tables bit for bit. The one claim not executed is the audio
posterior head being time-preserving — every op in it is Linear/LayerNorm/attention/MLP over
the time axis, no strided op.
## What P2 still owes (the device half)
1. **Kernels — DONE 2026-10-19** (§5.5 list, four deltas, all landed):
- **conv3d_ndhwc** grew the `CausalConv3d` forms (PORT-REF2VA §5.15): optional
`stride`/`stride_t`/`causal`/`pad`(`same`|`down`)/`reflect`, 3×3×3-only, defaults byte-identical
to the shipped upscaller conv (the `GEN` template path only for non-defaults; the T=1 tap
truncation is subsumed by the front-only causal pad). Device/libref/avx + tests all landed.
- **The AttnProjection "reduce" resolved 2026-10-19 as ZERO new kernels** (PORT-REF2VA
§5.14): `layernorm` ×3, `gemm_nt_bias` for the fused qkv (bias = `q_bias|zeros|v_bias` concat
at convert), `attn_dense` causal (q/k/v take the `[tokens, heads, head_dim]` fused-slice form),
head-mean = `pool_rows(k=8)` on the token-major output rows, and the `adaptive_avg_pool1d(256
→ 32)` is a constant block-mean matrix that FOLDS into the attention `proj` at convert
(`W' = W_proj @ M_pool`); mlp = concat gemm + `gelu_mul` + gemm, residuals = `add`.
- **The per-frame GroupNorm resolved 2026-10-19 as ZERO new op** (PORT-REF2VA §5.13): launch
`group_norm` once per frame — slice `x`/`y` at frame boundaries (NDHWC frames are contiguous
row blocks; the launcher takes `M` from `y`'s rows and honours both pitches), one shared
`stats` scratch, `eps` 1e-6 as the parameter. The only kernel change: the encoder's level-0
groups are 4 channels wide (128 ch / 32 groups) and the device GN kernels chunked 8 channels
a thread — the chunk width is now a template parameter (8, or 4 when the group is 4 wide;
narrower still refuses; the spec never promised %8, libref/avx always answered).
- **The strided even-kernel conv1d landed 2026-10-19** (PORT-REF2VA §5.12): `conv1d` gained
optional `stride`/`pad` (bf16 rows only, one sequence `[0, rows of x)`, any `k`, output row
`m` reading `x[m·stride + tap·dil − pad]` with the sequence bounds zeroing — PyTorch's
zero-padded strided conv, `k = 2·stride`/`pad = ceil(stride/2)` giving exactly `L/stride`
rows, the y length rule checked exactly on the host in all three plugins; `r4d_selftest`
pins the tiled and direct kernels' numerics and the refusals).
The graph order is in the sections above; nothing here needs a new math op.
2. **Declare + re-convert**: encoder weights are absent from containers (§5.5) — declare the
118 video-encoder + 173 audio-encoder tensors (w/norm folds via `map_wnorm`) and re-convert
the P5 container; the recipe carries the constants above in meta already.
3. **Value parity**: golden *values* against ComfyUI encodes at real shapes on device (shape
parity is pinned today). Deterministic encoders ⇒ strict comparison, per-tensor tolerances
only as far as fp8 storage forces.
4. **Driver**: the encode pass enum entry, per-request ref encode, and the tail ingest — the
last gated on the FFmpeg dev packages (`core/mm/mp4.cpp`, P2b).
+237
View File
@@ -0,0 +1,237 @@
# P3/P4 port note — the exact Ref2VA packing, from ComfyUI source
Read directly from `/home/dustin/AI/ComfyUI/comfy/ldm/minimax/model.py` (2026-10 install) so the
Radiance port is source-faithful rather than doc-derived. Line numbers below are that file's.
Everything here is **pure host arithmetic** — the port is a new TU (proposed
`arch/minimaxh3/rad_ref2va_pack.{h,cpp}`, device-free, unit-testable) that emits the segment
table + per-row (t,h,w) positions + update flags; consuming them is the P3 engine wiring, and
keeping the non-update rows dense is P4.
## Constants (`:30-33`)
```
FRAME_PER_TOKEN = (1, 4, 4, 4, 4) # pixel frames covered by each successive video latent
FRAME_RESCALE = 5/3 # pixel frames -> audio-latent units (40/24 fps ratio)
VISUAL_COND_TIMESTEP = 0.999
AUDIO_COND_TIMESTEP = 1.0
```
## Row shapes
- video rows: patchify (1,2,2) → `latent_t * (h/2) * (w/2)` rows; time grid per latent frame k is
`origin + FRAME_RESCALE * Σ FRAME_PER_TOKEN[k'%5], k'<k` (`_video_t_grid` `:101-104`).
- audio rows: `pack_audio` `:59-62` — `[C=32, ch=2, T]` → `[2T, 32]` **channel-major**: ch0 all
T frames then ch1 all T frames. `rt` audio latent frames ⇒ `rt*2` rows.
- spatial frame grid `_frame_grid(h,w)` `:94-99`: `area=sqrt(h*w)`; per axis
`linspace`-like `(i*(ratio/n) + (1-ratio)/2)*32` with `ratio=dim/area`, `n=dim/2` — area-
normalized h/w coords of the 2×2 patch rows (h rows major). Audio grid `_audio_grid` `:106-113`:
`t = cursor + arange(T)` repeated for both channels, `w` pinned per channel to the **target**
grid's first/last w coord (`target_audio_w = (w_grid[0], w_grid[-1])`), `h=0`.
- `_ref_t_span` `:115-122`: image `1.0`; audio `ref_audio_t`; video/video_audio
`max(ref_audio_t, Σ_{k<latent_t} FRAME_RESCALE*FRAME_PER_TOKEN[k%5])`.
## Segment order (`PackedLayout.__init__` `:351-471`)
`[text | (keyframe cond | cond_audio)* | per-ref blocks in request order | audio | video]`
- `cursor = text_len + Σ _ref_t_span(all refs)` — the **target timeline origin**; computed in a
first pass before keyframes (`:364-366`). Keyframes pack right after text, each at
`cond_t = cursor + FRAME_RESCALE*resolved_frame_index` (frame 0 ⇒ shares the target origin and
overlaps its head in RoPE time — continuity comes from post-sampling trim, not placement).
- ref block per kind (`:394-441`), all rows **update=False** (pinned, never denoised):
- `image`: `ref_img` n=`(h/2)*(w/2)` rows, t=cursor, then `cursor += 1.0`
- `audio`: `ref_audio` `rt*2` rows (only if rt>0) at `_audio_grid(cursor,...)`, then
`cursor += rt`
- `video`/`video_audio`: **its `ref_audio` rows pack immediately BEFORE its `ref_img` rows**,
both at the same cursor origin; ref_audio uses the **ref's own** w-grid extremes
`(r_w_grid[0], r_w_grid[-1])` (target extremes only for target/cond audio); then
`cursor += max(rt, Σ video_t_spans(latent_t))` (== `_ref_t_span`, the second pass re-cums).
- targets (`:443-454`): `audio` `audio_t*2` rows then `video` `latent_t*(h/2)*(w/2)` rows, both
update=True, both at cursor. **Always the last two segments** — the sampler state is exactly
these (update mask = the sampler's x).
## Timesteps & mod rows (`_forward` `:667-712`)
- `t_v = 1 - sigma_v`, `t_a = 1 - time_shift_sigma(sigma_v, shift_v, shift_a)` (audio sigma
derived from video sigma via `time_shift_sigma` `:36-39`).
- per-kind timestep labels: `text/video → t_v`, `audio → t_a`,
`cond|ref_img → max(t_v, 0.999)`, `cond_audio|ref_audio → max(t_a, 1.0)` (pinned near-clean).
- `unique_t` = sorted distinct labels actually present; `t_row[t]` = index.
- mod tags: `{text:1, video:0, audio:2, cond:0, ref_img:0, cond_audio:2, ref_audio:2}`;
**mod-row index = `t_row(label) * 3 + tag`** — refs ride the video/audio modulation streams.
- denoise masks (`:683-699`): per-row `m` puts a row at `sigma = m*sigma_stream`, label
`clamp(1-m*sigma, max=pin)`; all-equal collapses to the segment label. Radiance's tail uses no
partial mask (full rows) — port masks only if partial-row conditioning ever lands.
## Cond-row content + the 0.1% augmentation (`:532-558`)
Cond rows are rebuilt **every step** from stored clean latents (never from sampler state):
`r = aug*z + (1-aug)*randn` with a **CPU RNG re-seeded per step per block-kind**: visual block
seed = run seed, audio block seed = run seed **+ 1**, `aug` = 0.999/1.0. Re-seeded ⇒ identical
noise every step; but it must be the **same stream every step** — port with a seeded CPU PRNG
matching torch's `randn` only if bit-parity is demanded (else document deviation: same-shape
deterministic-noise with Radiance's Philox, parity gate = "cond rows never change across steps").
## Sampler contract (`forward` `:603-643`)
- Sampler x = `[video_latents, audio_latents]` — **targets only** (update rows); the net returns
velocity for those rows only. Pinned rows are input-only context.
- audio scale-carry (`:605-614`, `:637-641`): sampler carries audio as `(sigma_a/sigma_v)*x_a`;
undo before the net, re-scale velocity out: `out_a = (1-scale)*(carry*x_a) + (1+(scale-1)*sigma_a)*v_a`.
- guidance-distilled: CFG 1.0; sigma-shift per stream (`MiniMaxH3SigmaShift` node).
## P4 — dense sinks
Sparsity (sol-attn) hooks the layout out-of-band via `transformer_options["minimax_h3_layout"]`
(vendored model code is fully dense, `optimized_attention(..., mask=None)` `:200`); the sparse
node keeps **cond+ref+audio rows** exact (`sink_conditioning=exact_kv_and_rows`) and sparsifies
the update rows only. Radiance parity: the sink rule takes `img_update/audio_update` (P3 output) —
dense set = complement of update set ∪ text — NOT a static prompt-span rule. Keep the split
(pack emits the table; sparsity is the attention backend's concern).
## Landed 2026-10-19 — `arch/minimaxh3/rad_ref2va_pack.{h,cpp}`
The port exists and is tested against the reference's own output. `ref2va_build()` emits the
segment table (start, end, kind, update), the planar `[3, rows]` f32 positions (the exact shape
R_ROPE holds, so staging is a copy), and `ref2va_mod_rows()` does the per-step `t_row * 3 + tag`
numbering (sorted distinct labels, exact-equality collapse when the live timestep passes a pin).
The test binary `tests/ref2va_pack_test.cpp` compiles the TU directly (no rad_core, no device);
`tests/data/ref2va/golden.json` is generated by `gen_golden.py <ComfyUI>/comfy/ldm/minimax/model.py`,
which AST-extracts the reference's constants + grid helpers + `PackedLayout` and execs them on
torch alone — every expectation is the reference's own float64 output. The positions compare
**bit-exact** after the float cast: both sides run identical IEEE double arithmetic, so a ULP
drift means the port reordered its arithmetic, and the test says so. Five golden cases (t2va,
fl2va keyframes at the origin and mid-timeline, all four reference kinds with a silent target, a
realistic chain signature, empty prompt) x three timestep probes (labels apart, collapsed past
both pins, far apart).
Parity with the plain generator: with no refs the pack reduces to `[text | audio | video]` —
same segment order, same row counts, the same planar shape — and `positions()` is now *this
code*: `minimaxh3.cpp` calls `ref2va_build(text_len, geom, {}, {}, &pack)` and copies
`pack.pos` (the first consumption point landed, 2026-10-19). The row contract the hand-rolled
version computed — text counting up, the soundtrack channel-major at the width extremes, the
1,4,4,4,4 time pattern — is pinned in `tests/ref2va_pack_test.cpp`
(`pack_plain_matches_the_three_segment_order`). One honest byte-level footnote: the old
`positions()` recovered the axis step as `((1-ratio)/2 + ratio) - (1-ratio)/2`, and on the grid
row whose coordinate is mathematically 0 the cancellation came out *exactly* 0, where the
reference's `arange*ratio/n` form leaves a float64 residue of ~1e-15. A sweep of all 1242 legal
sizes (multiples of 32, >= 256 a side, area <= 1344x768, aspect <= 4) found exactly 10 axes on
10 sizes where the f32 coordinate differed — one centre row each, the last bit of one rope
angle. The reference's form is authoritative, and the pack implements it verbatim.
## P4 sinks, concretely
`libr4d/r4d_vsa.hip`'s `vsa_geom()` makes **every segment before the video grid a dense 64-row
prefix** (the visibility walk then lets every query tile see all prefix tiles). The pack's order —
keyframes and reference blocks between the prompt and the targets — therefore makes every pinned
row an automatic sink the moment the driver lists it in `seg_cu` ahead of the video segment: no
kernel change. Two footnotes for the wiring: (a) ComfyUI's sparse node sparsifies the *target
audio* rows too, while Radiance's prefix rule keeps them dense — parity watch for P6, cheap to
split if the benchmark shows it matters; (b) `R_SEG`'s staged `seg_cu` is 4 i32 today and a full
presentation needs about two dozen (text, keyframe pairs, up to two segments per reference, the
two targets), so the register's
capacity grows with the wiring, along with `vsa_geom`'s `nd`.
## What the engine wiring still owes (P3 proper)
The pack answers "where do the rows sit"; consuming it touches four places the map found, of
which two have landed:
- **`positions()` now *is* the pack** (`ref2va_build` with no refs, copied straight into R_ROPE's
buffer — landed 2026-10-19, drift audit above).
- **`seg_cu` stages the pack's table** (landed 2026-10-19): a new *optional* plugin export,
`rad_arch_video_segs(g, cu, cap)` (documented in `rad_builder.h` — an additive export,
`RAD_ABI_VERSION` does not move; threaded through `loader.cpp` → `startup.{h,cpp}` →
`VideoDriver::init`), which for the plain geometry writes exactly `[0, n_text,
n_text + 2·n_audio, rows]`. `stage_geom` prefers it and **validates**: a plugin that exports
nothing, a table that disagrees with the geometry, or more segments than `R_SEG`'s four
int32s — any of those stages the driver's own table instead, byte-identical.
`video_gen_test`'s `the_plugin_segment_table_is_staged_and_a_disagreeing_one_falls_back`
drives all three. When refs arrive, `rows` itself comes from the pack, the local table
disappears, and `R_SEG`'s carve (`carve()`'s `4 * 4` — see P4 footnote (b)) grows with the
wiring.
What remains: `step_dit`'s row assembly (scatter pinned latents per `img_pos`/`audio_pos` —
rebuild the cond rows from the clean latents each step with the re-seeded 0.1% augmentation);
the modulation table (today `[lane*S, L*3*Ws]` = two timesteps x three tags, and the pack can
present up to four distinct labels x three tags = twelve columns, with the pinned labels
recomputed from `t_v`/`t_a` each step). The sampler already owns exactly the update rows once
they are last — no sampler change.
## Golden test vectors (hand-check against the formulas)
- tail 3.0 s: 73 px frames ⇒ `FRAME_RESCALE*73 = 121.67` audio units ≈ 121-122 rows/channel;
latent grid legal snaps {5,22,39,56,73}px ↔ {2,7,12,17,22} latent (`continuation_nodes.py:180-189`).
- video latent L frames span `5/3*(1+4(L-1))` audio units: L=22 ⇒ 141.67 (> its 121 audio span ⇒
the `max()` picks the video span).
- stereo ref audio rt=60 ⇒ 120 rows; rows 0-59 ch0 (w=low), 60-119 ch1 (w=high).
- image ref 1024×1024 target grid h=w=64 patch rows ⇒ n=4096? (h/2·w/2 — the ref's OWN latent_h/w:
`_frame_grid(latent_h, latent_w)` of the ref, not the target's).
## Landing plan for the rest of P3 (2026-10-19, after the encode device half)
Everything below was scouted against the tree, not from memory; every cited line is as of the
P2-device-half build. Increments are ordered so each one builds+tests green on its own; none
removes the submit-time refusals until the whole path works end-to-end (phased acceptance).
### 13a — ref-aware geometry (host, no behavior change, testable with fakes)
- **ABI trailing block** on `RadVideoGenBatch` (ABI 23 is unreleased — no bump): `const int32_t*
ref_tab` — NULL when the request carries no VAE references; else self-describing
`[0]=n_refs, [1]=n_keys`, then `n_refs × 6` words
`{kind(Ref2VARefKind), slot(1-based within kind), lat_h, lat_w, latent_t, audio_t}`, then
`n_keys × 3` `{frame, video_t, audio_t}`. HOST-pinned (step_dit reads it host-side exactly as
it reads `V->geom` by value — no device staging of the table itself).
- **New optional export** `rad_arch_video_pack(g, n_text, ref_tab, seg, cap_seg, pos, cap_pos)` →
rows (negative = refusal; `seg`/`pos` NULL → count only). Thin wrapper over `ref2va_build` —
the plugin stays the authority (segs_ precedent). Driver threads it beside `segs_`
(`loader.cpp` dlsym → `startup.{h,cpp}` → `VideoDriver::init(PackFn, ...)`, defaulted).
- **Carve widen**: `R_SEG` 4→**64** i32 rows (worst pack: text + ≤15 ref segs + 2 targets +
keyframes headroom). Kernel side needs NOTHING: `vsa_geom` loops `n_seg-1` generically
(r4d_vsa.hip:66-101) and the launcher takes `n_seg = numel(segs)-1`, cap 4096
(r4d_vsa.hip:1009-1011). `b_modg`/`b_sel` tile caps: `P = min(P, tiles_cap)` already clamps.
- `stage_geom` stages the pack's full boundary table when `ref_tab` is set (validation flips:
the local 4-boundary table is only reconstructible for no-refs requests).
- `video_gen_test`: fake `PackFn` cases mirroring the segs_ trio (staged / disagreeing falls
back / short cap refuses) + `ref2va_pack_test` needs no change (pack unchanged).
### 13b — step_dit consumes the pack (arch; green = compiles + selftest + fakes)
- Rebuild the pack HOST-side inside `step_dit` from `ref_tab` (the TU is in the plugin — the
driver staged from the same code via 13a's export, so segment starts agree by construction).
- **Row assembly** (minimaxh3.cpp:2939-2944 today): `op_text` already reads `seg[0..1]` from
`seg_cu`; replace the fixed `nt`/`nt+arows` offsets of `op_ain`/`op_vin` with the pack's audio
and video segment starts. Then per img-latent segment (cond/ref_img, ≤12 issues) issue
`op_vin` with `x = brow_slice(b_evc, venc_slot_row(kind,slot), seg_rows, kPatchVals)` — the
encoder's fold already emits patch-folded rows, so **no gather kernel**: slot slices feed the
embedder directly. `op_ain` likewise over `b_enca` slices. Target rows unchanged.
- **0.1% re-seeded aug** per pinned img/audio segment, rebuilt from CLEAN slot rows every step
(never in place into `b_evc`/`b_enca`): draw into scratch (rnd-op form, seed staged per step —
`build_step` already stages `R_SEED` per pass: bake step in), scale 0.001 via `chan_affine`,
`add` slot+noise → scratch, embed from scratch. Seeds: visual = seed words 0/1, audio = 2/3
(already the split in `stage_seed`).
- **Mod table**: `b_ada` per lane-step grows `kSegs`→**12 columns** (≤4 distinct labels × 3
tags): temb rows 2·S→2·S+2 (two constant pinned timesteps 0.999 video / 1.0 audio —
`ref2va_t_label` gives the labels; `ref2va_mod_rows` gives each segment's `t_row·3+tag`).
`step_ada`'s block×segment loop iterates the label cells; `step_dit`'s `mod()`/`modh()` view
column `(l, mod_row)` instead of `(l, e)`, and per-segment blocks take their mod row from the
rebuilt pack. TP2 half-split: `cut` moves to the VIDEO segment's middle row and `segh[1]=cu`
still stands only when the second half is video-only — with refs keep the half inside the
video segment (`hr0[1] = vseg.start + vrows/2`), and half 0's mod view takes the segment rows
for its range; `ref2va_mod_rows` order pins which cells it needs.
- Heads/Euler: the two target segments stay LAST, so the heads and both Euler steps keep working
with the views re-anchored at `aseg.start`/`vseg.start` — sampler state = update rows only.
- `b_sel`/`b_coarse` sizing: prefix tiles P grow with ref rows (each ≤64-row chunk adds a
tile); declare capacities already take the probe's widened `gen_rows`; re-check
`tiles_cap` math against a worst-case 9/3/3 presentation.
### 13c — driver media decode + encode scheduling (FFmpeg-gated for real bytes)
- Decode in the driver (bytes already in `VideoRefMedia::data`, in-memory `core/mm/mp4.cpp`
path): frames → f32 0..255 + clip repeat-pad to entry 23; samples → channel-major f32
right-padded to entry 0; ref sizes capped by `rad_arch_encode_geom` BEFORE decoding fully
(probe the export, bound the decode). Images: policy = resize to ≤256 side (the encode
ceiling) for the VAE view; the TE view keeps `media`'s own pixels.
- New job phase before cond: per ref, one V_ENCODE/A_ENCODE pass (order: tail, images, videos,
vaudios, audios — tail only for P2b requests); `next()` slot in the pipeline before
`build_cond`, gated on `decl_.encodes`; refusal removal is HERE (13c), not 13a/13b.
- P2b tail: `RAD_ENC_TAIL` slot 0 rides V_ENCODE from the ClipStore's sampled latents — but the
tail is ALREADY latents, so the tail path issues no V_ENCODE; it scatters the slice straight
(see NOTE-CONTINUITY); only its AUDIO tail needs A_ENCODE? — decide when P2b starts.
+42 -9
View File
@@ -200,6 +200,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
| `pool_cols` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean column a window of k columns) |
| `relu` | `M`(range) `n` `dtype` | `x` → `y` |
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
@@ -266,6 +267,14 @@ op; the segment count is `cu_seqlens`' length less one. An empty segment is a ze
of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and
rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`.
**`pool_cols`** is its transpose-sibling, pooling along the width: column `c` of row `m` of `y` is
the mean of `x[m]`'s columns `[c*k, c*k + k)`, with the same f32 sum, the same two roundings and the
same optional `mult`. `n` is the input width, a multiple of `k`; `y` has `n / k` columns. An audio
encoder's attention head pooling needs it because its `adaptive_avg_pool1d` runs across the feature
axis of a single row, where `pool_rows` can only reach across rows — a `pool_cols` then a row
reinterpretation then a `pool_rows` is what folds a head-major attention output to its mean pooled
form.
**`fill`** writes `y = value` over the extent (`value` 0 when absent). A rank issues it where it
computes nothing but a downstream reader still expects a defined buffer: an attention-zero rank's
block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce. A wire shared across
@@ -858,7 +867,7 @@ says which (`libref/ref_gen.cpp`).
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `dtype` | `t` → `y` |
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
| `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` |
| `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout |
@@ -891,7 +900,9 @@ source into every listed lane (a repainted picture's latent into each of its ima
store would round it, so the bytes are the three ops'.
- `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32,
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
diffusers' pipeline hands its transformer. `t` is f32 `[M]`.
diffusers' pipeline hands its transformer. `t` is f32 `[M]`. With `clamp_min`, each `t` is first
raised to that floor (`t = max(t, clamp_min)`) -- the reference conditioning's near-clean pin
timesteps, which sit above the sampler's decaying schedule. `0` (default) leaves `t` untouched.
- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
- `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's
standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is
@@ -956,7 +967,7 @@ libref function says which (`libref/ref_audio.cpp`).
| op | params | operands |
|---|---|---|
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `pad`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
@@ -1031,7 +1042,13 @@ input reads zero outside it.
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
clamp; a NaN stays NaN). f32 accumulation, one rounding.
clamp; a NaN stays NaN). f32 accumulation, one rounding. With `stride` > 1 (bf16 rows only: the
encoder's downsample) `pad` is required, `k` is any size, and the op is one sequence
`cu_seqlens` = `[0, rows of x]`: output row `m` reads `x[m stride + tap dil - pad]` with zeros
outside, PyTorch's zero-padded strided conv exactly (`k = 2 stride`, `pad = ceil(stride / 2)`
gives `M / stride` rows), and `y` has
`(rows + 2 pad - dil (k - 1) - 1) / stride + 1` rows exactly. An explicit `pad` without a
stride, and an even `k` with neither, are refused.
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
@@ -1260,7 +1277,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`).
| op | params | operands |
|---|---|---|
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `stride`/opt `stride_t`/opt `causal`/opt `pad`/opt `reflect`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` |
| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` |
| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` |
@@ -1272,10 +1289,10 @@ innermost (NDHWC). `geom` is the request's volume, i32 on the device (the parame
declare). An output holds at least the rows the volume writes; rows past them are not written.
Every op honours its activation operands' row pitches. `rd` is a rounding into the output's dtype.
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= T H W, cout]`, `geom = (T, H, W)`; `w` is
PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. Stride 1, zero padding `kt/2` frames and `k/2`
rows and columns on each side (`same`; `k` and `kt` odd):
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= rows out, cout]`, `geom = (T, H, W)`;
`w` is PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. The defaults are stride 1 with zero padding
`kt/2` frames and `k/2` rows and columns on each side (`pad` `same`; `k` and `kt` odd):
`y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw]
x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation
in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's
@@ -1284,6 +1301,22 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also
f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`,
`(512, 24)`.
The optional `stride` (rows and columns), `stride_t` (frames), `causal`, `pad` and `reflect`
give the video encoder's `CausalConv3d` forms; they are accepted for `k = kt = 3` only. The
padding is computed first — front/back frame pad `ft`/`bk` and top/bottom/left/right spatial pad
— then one strided pass: output `(t, i, j)` reads
`x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci]` (the same tap order),
and `y` holds `((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
((W + pl + pr - k) / stride + 1)` rows — PyTorch's length rule, which the plugins check the
operand rows against. The defaults give `ft = bk = kt/2` and `pt = pb = pl = pr = k/2`.
`causal` 1 zeroes `ft = kt - 1` frames in front and none behind (`bk = 0`), so one frame in
gives one frame out at any temporal stride — the reference's `T == 1` tap truncation included.
`pad` `down` (which needs `k = 3`) pads none above and left and one below and right
(`pt = pl = 0`, `pb = pr = 1`); the name and orientation are `conv2d_nhwc`'s. `reflect` 1
mirrors the *spatial* pads instead of zeroing them — torch `F.pad` mode `reflect`: a mirror
with no repeated edge, `x[-n] = x[n]`, `x[D + n] = x[D - 2 - n]` — so a padded dimension must
exceed its pad (`H, W >= 2` for the one-px pads). The frame pad is always zeros. MiniMax-H3's
encoder uses `reflect` 1 `causal` 1 everywhere, `pad` `down` plus `stride` 2 in `Downsample3D`.
- `group_norm` is PyTorch's `nn.GroupNorm(groups, n)` on `[1, n, T, H, W]`: `x` and `y`
`[>= M, n]` (`M` is `y`'s rows), group `g` the channels `[g n/groups, (g+1) n/groups)` of all
`M` rows. `mean_g` and the biased `var_g` are over the group's `M n/groups` values, accumulated in
+27 -13
View File
@@ -235,20 +235,32 @@ AVX_KERNEL(conv1d) {
if (!Y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), ep = p_int(a, "pad", -1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1)
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || ep < 0)) ||
(st <= 1 && ep >= 0))
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
if (r0 < 0 || r1 <= r0 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2, KK = k * cin;
/* The strided form (libref's rule): bf16, one full sequence, y the formula's rows. */
int64_t hi = r1;
if (st > 1) {
if (X->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(X, cin)) return RAD_E_SHAPE;
hi = (r1 + 2 * ep - dil * (k - 1) - 1) / st + 1;
if (hi <= 0 || rows_of(Y, cout) != hi) return RAD_E_SHAPE;
} else if (rows_of(Y, cout) < r1) {
return RAD_E_SHAPE;
}
if (res && rows_of(res, cout) < hi) return RAD_E_SHAPE;
const int64_t pad = ep >= 0 ? ep : (causal ? dil * (k - 1) : dil * (k - 1) / 2), KK = k * cin;
static thread_local std::vector<uint8_t> wbuf, pbuf;
static thread_local std::vector<float> ybuf;
@@ -263,16 +275,18 @@ AVX_KERNEL(conv1d) {
const bool b16 = X->dtype == RAD_BF16 && laststride(X) == 1;
const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32;
const size_t ael = b16 ? 2 : 4;
/* A 1-wide kernel's patch row is x's own row. */
const bool direct = k == 1 && X->rank == 2 && X->shape[1] == cin && X->stride[1] == 1 &&
(X->dtype == RAD_BF16 || X->dtype == RAD_F32);
const int64_t band = band_rows(KK, cout, r1 - r0);
/* A 1-wide kernel's patch row is x's own row; a strided op reads rows `stride` apart, so it
* always builds patches. */
const bool direct = k == 1 && st == 1 && X->rank == 2 && X->shape[1] == cin &&
X->stride[1] == 1 && (X->dtype == RAD_BF16 || X->dtype == RAD_F32);
const int64_t lo = st > 1 ? 0 : r0; /* a strided op's rows are output rows from 0 */
const int64_t band = band_rows(KK, cout, hi - lo);
if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64);
ybuf.resize((size_t)(band * cout) + 16);
char* pp = (char*)pbuf.data();
float* yp = ybuf.data();
for (int64_t b0 = r0; b0 < r1; b0 += band) {
const int64_t nb = std::min(band, r1 - b0);
for (int64_t b0 = lo; b0 < hi; b0 += band) {
const int64_t nb = std::min(band, hi - b0);
RadTensor pt;
if (direct) {
pt = mat_view((char*)X->data + (size_t)(b0 * X->stride[0]) * rad_dtype_bits(X->dtype) / 8,
@@ -282,10 +296,10 @@ AVX_KERNEL(conv1d) {
pt = mat_view(pp, adt, nb, KK);
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
for (int64_t p = 0; p < nb; ++p) {
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r);
const int64_t r = b0 + p, e = seq_of(cu, n_seq, st > 1 ? r * st : r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
for (int64_t t = 0; t < k; ++t) {
const int64_t ir = r + t * dil - pad;
const int64_t ir = r * st + t * dil - pad;
patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16,
pp + (size_t)(p * KK + t * cin) * ael);
}
+19
View File
@@ -97,6 +97,10 @@ std::vector<Case> build_cases() {
HS("dtype", dt) });
add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035),
HS("dtype", dt) }, EB(27, 645, w, 1));
add("pool_cols", { HI("M", 27), HI("n", 648), HI("k", 9), HF("mult", 27.712812921102035),
HS("dtype", dt) }, EB(27, 648, w, 1));
add("pool_cols", { HI("M", 40), HI("n", 256), HI("k", 8), HS("dtype", dt) },
EB(40, 256, w, 1));
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
EB(6, 645, w, 2));
@@ -317,6 +321,11 @@ std::vector<Case> build_cases() {
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("block", 7) });
/* An audio encoder's own-heads attention: head_dim 256, no GQA, causal with a window. */
for (const char* dt : { "f32", "bf16" })
add("attn_dense", { HI("M", 24), HI("head_dim", 256), HI("gqa", 1), HI("causal", 1),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("window", 8) });
for (const char* dt : { "f32", "bf16" })
add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) });
/* Gemma 4's audio attention: left 12, over segments longer than the window. */
@@ -768,6 +777,9 @@ std::vector<Case> build_cases() {
HS("act", act), HS("dtype", dt) });
add("group_norm", { HI("M", 150), HI("n", 96), HI("groups", 4), HF("eps", 1e-5),
HS("act", "silu"), HS("dtype", dt) });
/* Four channels a group at the video encoder's first level, its eps. */
add("group_norm", { HI("M", 130), HI("n", 128), HI("groups", 32), HF("eps", 1e-6),
HS("act", "silu"), HS("dtype", dt) });
add("tconv_dw", { HI("M", 27), HI("n", 645), HI("k", 5), HS("dtype", dt) });
add("tconv_dw", { HI("M", 64), HI("n", 37), HI("k", 3), HS("dtype", dt) });
add("resize_bilinear", { HI("M", 27), HI("n", 645), HS("dtype", dt) });
@@ -829,6 +841,13 @@ std::vector<Case> build_cases() {
for (int dil : { 1, 3 })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
HI("dil", dil), HI("causal", 1), HS("dtype", dt) });
/* The strided downsample (a DAC encoder block's): kernel 2 stride, pad ceil(stride / 2),
* one sequence. The form is bf16-only, so it rides the bf16 arm alone. */
if (std::strcmp(dt, "bf16") == 0)
for (int s : { 2, 4, 5 })
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
HI("dil", 1), HI("stride", s), HI("pad", (s + 1) / 2),
HS("dtype", dt) });
for (int s : { 2, 4, 8 })
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
HS("dtype", dt) });
+98
View File
@@ -2266,6 +2266,84 @@ void upscaler_cases(std::vector<Hand>& hs) {
.pi("M", R).pi("cin", ci).pi("cout", co).pi("k", 2).pi("kt", 3).ps("dtype", dn)
.refuses(RAD_E_SHAPE);
hs.push_back(std::move(e));
/* The video encoder's CausalConv3d forms: the cube's geoms never stride, never
* mirror and never pad one side, so the downsample, a mirror-everywhere res block
* and the one-frame case are built by hand. */
{
/* (3 + 2 - 3) / 2 + 1 = 2 frames, (4 + 1 - 3) / 2 + 1 = 2 rows, (5 + 1 - 3) / 2
* + 1 = 2 columns: the bottom/right-only pad and both stride axes, with the
* frame drop and a column of reflected taps. */
Hand h(("3 x 4 x 5 causal, stride 2 down reflect" + sfx).c_str(),
"conv3d_ndhwc", tol);
h.dense(dt, { 3 * 4 * 5, ci }, hfill(960))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(961, 0.3f))
.dense(dt, { co }, hfill(962, 0.5f))
.idx({ 3, 4, 5 })
.none()
.dense(dt, { 8, co }, hfill(963), true)
.pi("M", 8).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("stride", 2).pi("stride_t", 2).pi("causal", 1).ps("pad", "down")
.pi("reflect", 1);
hs.push_back(std::move(h));
Hand g(("2 x 2 x 3 causal reflect, a mirror on every edge" + sfx).c_str(),
"conv3d_ndhwc", tol);
g.dense(dt, { 12, ci }, hfill(964))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(965, 0.3f))
.dense(dt, { co }, hfill(966, 0.5f))
.idx({ 2, 2, 3 })
.none()
.dense(dt, { 12, co }, hfill(967), true)
.pi("M", 12).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("causal", 1).pi("reflect", 1);
hs.push_back(std::move(g));
/* One frame in, one out: the causal pad's front zeros are the reference's tap
* truncation; the residual is the output itself. */
Hand q(("one frame, causal reflect, residual in place" + sfx).c_str(),
"conv3d_ndhwc", tol);
q.dense(dt, { 4, ci }, hfill(968))
.dense(dt, { co, ci, 3, 3, 3 }, hfill(969, 0.3f))
.dense(dt, { co }, hfill(970, 0.5f))
.idx({ 1, 2, 2 })
.dense(dt, { 4, co }, hfill(971), true)
.alias(4)
.pi("M", 4).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
.pi("causal", 1).pi("reflect", 1);
hs.push_back(std::move(q));
/* The refusals, held to libref's error codes: a 5-wide kernel with a stride, a
* pad that is neither `same` nor `down`, a reflect whose one-px pad reaches an
* axis of 1, y short of the strided output and a zero stride. */
const auto refusal = [&](const char* what, const std::vector<int64_t>& g3,
int k, const char* pad, int stride, int causal,
int reflect, int64_t yrows) {
Hand z((std::string(what) + sfx).c_str(), "conv3d_ndhwc", tol);
z.dense(dt, { 12, ci }, hfill(972))
.dense(dt, { co, ci, (uint32_t)k, (uint32_t)k, (uint32_t)k }, hfill(973))
.dense(dt, { co }, hfill(974))
.idx(g3)
.none()
.dense(dt, { yrows, co }, zero, true)
.pi("M", yrows).pi("cin", ci).pi("cout", co).pi("k", k).pi("kt", k)
.ps("dtype", dn);
if (stride != 1) z.pi("stride", stride);
if (pad && *pad) z.ps("pad", pad);
if (causal) z.pi("causal", causal);
if (reflect) z.pi("reflect", reflect);
z.refuses(RAD_E_SHAPE);
hs.push_back(std::move(z));
};
refusal("a stride with a 5-wide kernel is refused", { 2, 2, 3 }, 5, nullptr, 2, 0,
0, 12);
refusal("a reflect pad reaching an axis of 1 is refused", { 2, 1, 2 }, 3, nullptr,
1, 1, 1, 4);
refusal("a mirror pad is refused", { 2, 2, 3 }, 3, "mirror", 1, 0, 0, 12);
refusal("y short of the strided output is refused", { 3, 4, 5 }, 3, "down", 2, 1,
1, 7);
refusal("a zero stride is refused", { 2, 2, 3 }, 3, nullptr, 0, 0, 0, 12);
}
}
/* ---- group_norm: stats f32 of exactly groups (2 + 3 1024) values --------------------- */
@@ -3782,6 +3860,26 @@ void audio_cases(std::vector<Hand>& hs) {
.pi("causal", 1).ps("dtype", dn);
hs.push_back(std::move(h));
}
if (dt == (uint32_t)RAD_BF16) {
/* The strided downsample (an encoder's), bf16 only: one sequence, kernel 2 stride,
* pad stride / 2, so 16 input rows give exactly 16 / stride output rows. */
const int64_t cin = 20, cout = 13;
for (const int64_t s : { 2, 4 }) {
const int64_t k = 2 * s, in = 16, out = in / s;
Hand h(("stride " + std::to_string(s) + ", even kernel, one sequence" + sfx)
.c_str(),
"conv1d", norm_tol);
h.dense(dt, { in, cin }, hfill(350 + s))
.dense(dt, { cout, cin, k }, hfill(356, 0.3f))
.idx({ 0, in })
.none()
.dense(dt, { out, cout }, zero, true)
.dense(dt, { cout }, hfill(357, 0.5f))
.pi("M", in).pi("cin", cin).pi("cout", cout).pi("k", k).pi("dil", 1)
.pi("stride", s).pi("pad", s / 2).ps("dtype", dn);
hs.push_back(std::move(h));
}
}
for (const int64_t s : { 5, 3 }) {
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
* from row 1. */
+31
View File
@@ -555,6 +555,37 @@ AVX_KERNEL(pool_rows) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_cols */
/* As libref: the mean of every k consecutive columns of each row, summed in f32 and rounded to
* y's dtype, then the multiplier and a second rounding (the unfused pair). pool_rows' dual.
* Parallel over rows. */
AVX_KERNEL(pool_cols) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0 || n % k) return RAD_E_SHAPE;
const int64_t M = rows_of(X, n), nw = n / k;
if (M <= 0 || numel(Y) < M * nw) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
AVX_PARALLEL_FOR_IF(M * nw * k >= AVX_PAR_MIN)
for (int64_t r = 0; r < M; ++r) {
float* acc = scratch_f32((size_t)nw);
float* sx = scratch_f32_b((size_t)n);
const float* v = in_row(X, rowoff(X, r, n), n, sx);
for (int64_t c = 0; c < nw; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < k; ++j) s += v[c * k + j];
acc[c] = s * inv;
}
roundtrip(Y->dtype, acc, nw, sx);
for (int64_t c = 0; c < nw; ++c) acc[c] *= mult;
out_row(Y, rowoff(Y, r, nw), nw, acc);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when the optional residual is passed.
*
+2 -1
View File
@@ -414,6 +414,7 @@ AVX_KERNEL(timestep_embed) {
const float scale = p_f32(a, "scale", 1000.0f);
const double mp = p_f32(a, "max_period", 10000.0f);
const int round = (int)p_int(a, "round", 0);
const float clamp = p_f32(a, "clamp_min", 0.0f);
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE;
@@ -423,7 +424,7 @@ AVX_KERNEL(timestep_embed) {
float *f = buf, *row = buf + n;
for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h);
for (int64_t m = 0; m < rows; ++m) {
const float tv = ldt(T, offlin(T, m));
const float tv = std::fmax(ldt(T, offlin(T, m)), clamp); /* ref pins are floors */
const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
: scale * tv;
for (int64_t i = 0; i < h; ++i) {
+2 -1
View File
@@ -77,7 +77,8 @@ int avx_par_force(int threads);
X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
X(scale_rows) X(scale) X(fill) X(act_mul) \
X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \
X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \
X(relu) \
X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
X(seg_sinusoid) X(conv2d_unfold) \
/* ---- quantisation and rotation */ \
+15 -5
View File
@@ -486,7 +486,7 @@ static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_STR("dtype") };
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
@@ -554,7 +554,9 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
/* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes
* patch_unfold's parameters and operands ------------------------------------------------------ */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
P_INTO("reflect") };
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
OPD_O("res"), OUT("y") };
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
@@ -571,7 +573,7 @@ static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT(
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -737,6 +739,9 @@ static const RadOpSchema kSchemas[] = {
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
"y[m][c] = the mean of x[m]'s columns [c*k, c*k + k), rounded to y's dtype, times mult, rounded "
"again." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
{ "gelu_mul", ARR(pMnD), ARR(oGateUp),
@@ -952,8 +957,11 @@ static const RadOpSchema kSchemas[] = {
"and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded "
"to its dtype." },
{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d),
"a 3-D convolution over voxel rows, `same` zero padding, PyTorch's [cout, cin, kt, k, k] "
"weight, as GEMMs over bands of patch rows; with `res` (possibly y) rd(rd(acc + b) + res)." },
"a 3-D convolution over voxel rows, defaults `same` zero padding, PyTorch's "
"[cout, cin, kt, k, k] weight, as GEMMs over bands of patch rows. `stride`/`stride_t` pad "
"then stride (3x3x3 only), `causal` 1 pads time front-only with kt - 1 zeros, `pad` `down` "
"pads none above/left and one below/right, `reflect` 1 mirrors the spatial padding. With "
"`res` (possibly y) rd(rd(acc + b) + res)." },
{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm),
"a group norm over all rows, its statistics in f64 over fixed row blocks combined in order, "
"then the optional [scale | shift] row and silu, one rounding; stats[0, 2 groups) the mean "
@@ -1183,6 +1191,8 @@ SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's ro
L(seg_mean)),
SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, L(pool_rows)),
SIMPLE("avx_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
"multiplier", DT_FLOAT, L(pool_cols)),
SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)),
SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)),
SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
+52 -20
View File
@@ -443,16 +443,26 @@ AVX_KERNEL(vtile_stitch) {
/* ================================================================== the latent upscaler
* Voxel rows (t, i, j) of a T x H x W volume, channels innermost, the volume in `geom`. */
/* Floor division, Python-style, for the output lengths' PyTorch rule. */
static int64_t idiv_floor(int64_t x, int64_t d) {
const int64_t q = x / d;
return (x % d && (x < 0) != (d < 0)) ? q - 1 : q;
}
/* ------------------------------------------------------------------ conv3d_ndhwc */
/* A 3-D convolution as GEMMs over bands of patch rows, as conv2d_nhwc and conv1d take theirs. The
* weight [cout, cin, kt, k, k] is re-laid once a launch as [cout][dt][kh][kw][cin] (bf16 copies
* when it is bf16, f32 otherwise), so an output voxel's patch row is its kt k k input voxels'
* channel runs back to back, zeros outside the volume: bf16 copies when x is bf16 with dense
* rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias added there; each row
* is then rounded once into y, or with `res` rounded to y's dtype, its residual row added and
* rounded again. A band's residual rows are read before its rows of y are written, row by row,
* so `res` may be y. The patches and the weight live in thread_local vectors that keep their
* high-water size, leaving the GEMM's scratch arenas to it. */
* channel runs back to back, zeros outside the volume (or `reflect`'s mirror): bf16 copies when x
* is bf16 with dense rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias
* added there; each row is then rounded once into y, or with `res` rounded to y's dtype, its
* residual row added and rounded again. A band's residual rows are read before its rows of y are
* written, row by row, so `res` may be y. The patches and the weight live in thread_local vectors
* that keep their high-water size, leaving the GEMM's scratch arenas to it.
*
* The optional `stride`/`stride_t`/`causal`/`pad`/`reflect` are libref's CausalConv3d forms (its
* comment and docs/OPS.md); an output voxel is read from `stride`-spaced, pad-shifted input
* voxels of the (T2, H2, W2) output grid. */
AVX_KERNEL(conv3d_ndhwc) {
if (a->n_t < 6 || !rad_args_have(a, 4) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3];
@@ -461,10 +471,27 @@ AVX_KERNEL(conv3d_ndhwc) {
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3)
return RAD_E_SHAPE;
const int64_t sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
const char* pads = p_str(a, "pad", "same");
const bool down = pads && !std::strcmp(pads, "down");
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
!(!pads || !std::strcmp(pads, "same") || down))
return RAD_E_SHAPE;
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2);
if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * Wd, taps = kt * k * k, KK = taps * cin;
if (rows_of(Y, cout) < rows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < rows) ||
const int64_t ft = causal ? kt - 1 : kt / 2, bk = causal ? 0 : kt / 2;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= Wd)) return RAD_E_SHAPE;
const int64_t T2 = idiv_floor(T + ft + bk - kt, st) + 1;
const int64_t H2 = idiv_floor(H + pt + pb - k, sp) + 1;
const int64_t W2 = idiv_floor(Wd + pl + pr - k, sp) + 1;
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * Wd, orows = T2 * H2 * W2, taps = kt * k * k, KK = taps * cin;
if (rows_of(Y, cout) < orows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < orows) ||
numel(W) < cout * KK || numel(B) < cout)
return RAD_E_SHAPE;
static thread_local std::vector<uint8_t> wbuf, pbuf;
@@ -490,22 +517,27 @@ AVX_KERNEL(conv3d_ndhwc) {
const size_t ael = x16 ? 2 : 4;
const int64_t want = std::min<int64_t>((int64_t)1 << 25,
std::max<int64_t>((int64_t)1 << 23, 8 * cout * KK));
const int64_t band = std::max<int64_t>(1, std::min(rows, want / KK));
const int64_t band = std::max<int64_t>(1, std::min(orows, want / KK));
pbuf.resize((size_t)(band * KK) * ael + 64);
ybuf.resize((size_t)(band * cout) + 16);
char* pp = (char*)pbuf.data();
float* yp = ybuf.data();
const int64_t pz = kt / 2, ps = k / 2;
for (int64_t r0 = 0; r0 < rows; r0 += band) {
const int64_t nb = std::min(band, rows - r0);
for (int64_t r0 = 0; r0 < orows; r0 += band) {
const int64_t nb = std::min(band, orows - r0);
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
for (int64_t pr = 0; pr < nb; ++pr) {
const int64_t r = r0 + pr, t = r / (H * Wd), i = (r / Wd) % H, j = r % Wd;
char* d = pp + (size_t)(pr * KK) * ael;
for (int64_t br = 0; br < nb; ++br) {
const int64_t r = r0 + br, t = r / (H2 * W2), i = (r / W2) % H2, j = r % W2;
char* d = pp + (size_t)(br * KK) * ael;
for (int64_t dz = 0; dz < kt; ++dz)
for (int64_t kh = 0; kh < k; ++kh)
for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) {
const int64_t tz = t + dz - pz, iy = i + kh - ps, ix = j + kw - ps;
const int64_t tz = t * st + dz - ft;
int64_t iy = i * sp + kh - pt;
int64_t ix = j * sp + kw - pl;
if (reflect) { /* torch's mirror, no repeated edge, then the bounds */
if (iy < 0) iy = -iy; else if (iy >= H) iy = 2 * H - 2 - iy;
if (ix < 0) ix = -ix; else if (ix >= Wd) ix = 2 * Wd - 2 - ix;
}
if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) {
std::memset(d, 0, (size_t)cin * ael);
continue;
@@ -524,16 +556,16 @@ AVX_KERNEL(conv3d_ndhwc) {
const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK);
if (st < 0) return st;
AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN)
for (int64_t pr = 0; pr < nb; ++pr) {
float* row = yp + pr * cout;
for (int64_t br = 0; br < nb; ++br) {
float* row = yp + br * cout;
if (R) {
float* buf = scratch_f32((size_t)(2 * cout + 32));
float *tmp = buf, *rs = buf + cout + 16;
narrow_row(Y->dtype, row, cout, tmp);
const float* rr = in_row(R, rowoff(R, r0 + pr, cout), cout, rs);
const float* rr = in_row(R, rowoff(R, r0 + br, cout), cout, rs);
for (int64_t c = 0; c < cout; ++c) row[c] += rr[c];
}
out_row(Y, rowoff(Y, r0 + pr, cout), cout, row);
out_row(Y, rowoff(Y, r0 + br, cout), cout, row);
}
}
return RAD_OK;
+6
View File
@@ -301,6 +301,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
// ---- launch ----------------------------------------------------------------------------------
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
// h256 gqa1: 8 query blocks of 16, tiles of 32 (LDS: 37 KiB) — an encoder's own heads
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB)
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
@@ -344,6 +345,11 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
n_head_kv, scale, window, wright, block,
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
if (head_dim == 256 && gqa == 1)
return r4d_attn_dense_launch<256, 1, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
if (head_dim == 256 && gqa == 2)
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window,
+37 -15
View File
@@ -55,7 +55,7 @@ __device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) {
// ---------------------------------------------------------------------------- conv1d
// An implicit GEMM, r4d_gen.hip's conv_igemm_kernel cut to one dimension: y[row][cout] = sum
// over (tap, cin) of x[row + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored
// over (tap, cin) of x[row * stride + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored
// tap-major (r4d_layout.cpp relayouts PyTorch's [cout][cin][k] at load), so a 64-wide K tile is
// eight 16-byte reads of input rows. A chunk outside its row's sequence reads zeros, which is the
// per-sequence padding. Eight waves, BP rows x BC output channels a block, the next K tile's
@@ -71,12 +71,14 @@ __device__ __forceinline__ float conv_act(float v, int act) {
return v;
}
/* `st` is the stride: row * st + tap * dil - pad is the input row, the sequence bounds zeroing
* outside keeps the stride 1 and (single-sequence) stride > 1 forms the same gather. */
template <int TP, int TC>
__global__ __launch_bounds__(256) void conv1d_igemm_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
int cin, int cout, int k, int dil, int pad, int st, int x_ld, int y_ld, int res_ld, int act) {
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
constexpr int CPR = C1_BK / 8;
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
@@ -121,7 +123,7 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
const r4d_u32x4 zero = {0u, 0u, 0u, 0u};
auto loadA = [&](int i) -> r4d_u32x4 {
if (!a_ok[i] || a_t[i] >= k) return zero;
const int ir = a_row[i] + a_t[i] * dil - pad;
const int ir = a_row[i] * st + a_t[i] * dil - pad;
if (ir < a_s0[i] || ir >= a_s1[i]) return zero;
return *(const r4d_u32x4*)(x + (size_t)ir * x_ld + a_ci[i]);
};
@@ -213,7 +215,7 @@ __global__ __launch_bounds__(kT) void conv1d_direct_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
int cin, int cout, int k, int dil, int pad, int st, int x_ld, int y_ld, int res_ld, int act) {
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
const int64_t total = (int64_t)(r_end - r_beg) * cout;
if (t >= total) return;
@@ -223,7 +225,7 @@ __global__ __launch_bounds__(kT) void conv1d_direct_kernel(
const int s0 = cu[sq], s1 = cu[sq + 1];
float acc = 0.0f;
for (int kk = 0; kk < k; ++kk) {
const int ir = row + kk * dil - pad;
const int ir = row * st + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const uint16_t* xp = x + (size_t)ir * x_ld;
const uint16_t* wp = w + ((size_t)co * k + kk) * cin;
@@ -1061,10 +1063,15 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
const long long causal = r4d_geti_or(a, "causal", 0);
/* The strided form: `stride` > 1 with `pad` explicit, any k, a single sequence covering all of
* x (the encoder's downsample, k = 2 stride and pad ceil(stride / 2)). `pad` means nothing
* without a stride, and the causal form keeps its own left-only padding. */
const long long st = r4d_geti_or(a, "stride", 1), pp = r4d_geti_or(a, "pad", -1);
const int act = conv1d_act(r4d_gets(a, "act"));
if (act < 0) return R4D_NO(RAD_E_INVAL);
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
causal > 1)
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || pp < 0)) ||
(st <= 1 && pp >= 0))
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, ry = 0, rr = 0;
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
@@ -1074,10 +1081,20 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k ||
(b && r4d_numel(b) < cout))
return R4D_NO(RAD_E_SHAPE);
/* The strided output length is PyTorch's, exactly (rx and ry are the row counts; xl and yl
* are the pitches): a graph that wants a truncated floor drops the last output row itself.
* One sequence, and cu_seqlens covers every input row (libref, which reads cu, checks its
* ends; the zeroing gather below makes those ends the whole padding, so the length rule is
* the part checkable here). */
if (st > 1) {
if (n_seq != 1 || rx + 2 * pp < dil * (k - 1) + 1 ||
ry != (rx + 2 * pp - dil * (k - 1) - 1) / st + 1)
return R4D_NO(RAD_E_SHAPE);
}
const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr;
/* Both kernels read input row row + tap * dil - pad: half the reach a side, or all of it on
* the left for the causal form. */
const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2);
/* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, all of
* it on the left for the causal form, or the explicit `pad` around the strided gather. */
const int pad = (int)(pp >= 0 ? pp : (causal ? dil * (k - 1) : dil * (k - 1) / 2));
const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 &&
((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0;
const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr;
@@ -1090,8 +1107,8 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
(const uint16_t*)w->data, bp, rp,
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl,
(int)rl, act);
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)xl,
(int)yl, (int)rl, act);
} else {
constexpr int TP = 4, TC = 1, BP = 128, BC = 64;
hipLaunchKernelGGL((conv1d_igemm_kernel<TP, TC>),
@@ -1099,15 +1116,15 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
(const uint16_t*)w->data, bp, rp,
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl,
(int)rl, act);
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)xl,
(int)yl, (int)rl, act);
}
} else {
hipLaunchKernelGGL(conv1d_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data,
bp, rp, (const int*)cu->data, (uint16_t*)y->data,
(int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad,
(int)xl, (int)yl, (int)rl, act);
(int)st, (int)xl, (int)yl, (int)rl, act);
}
return st_of(hipGetLastError());
}
@@ -1174,6 +1191,11 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
const long long causal = r4d_geti_or(a, "causal", 0);
const int act = conv1d_act(r4d_gets(a, "act"));
if (act < 0) return R4D_NO(RAD_E_INVAL);
/* The strided form lives on the bf16 rows (the DAC encoder it serves runs there); the f32
* vocoder is stride 1 with the derived padding, so a stride or an explicit pad is refused
* as a dtype choice rather than silently ignored. */
if (r4d_geti_or(a, "stride", 1) != 1 || r4d_geti_or(a, "pad", -1) >= 0)
return R4D_NO(RAD_E_DTYPE);
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
causal > 1)
return R4D_NO(RAD_E_SHAPE);
+49
View File
@@ -336,6 +336,24 @@ __global__ __launch_bounds__(kThreads) void pool_rows_kernel(
}
}
// ---------------------------------------------------------------------------- pool_cols
// ref_pool_cols: column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in
// f32 and rounded to bf16, then times `mult` and rounded again — pool_rows' dual, pooling the
// columns (an encoder posterior's adaptive_avg_pool1d over the feature axis). One thread per
// output element.
__global__ __launch_bounds__(kThreads) void pool_cols_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t k, float mult,
uint32_t x_ld, uint32_t y_ld, uint32_t M) {
const uint32_t i = blockIdx.x * kThreads + threadIdx.x;
if (i >= n / k) return;
for (uint32_t r = blockIdx.y; r < M; r += gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < k; ++j) acc += bf2f(x[(size_t)r * x_ld + (size_t)i * k + j]);
const float mean = bf2f(f32_to_bf16(acc * (1.0f / (float)k)));
y[(size_t)r * y_ld + i] = f32_to_bf16(mean * mult);
}
}
// ---------------------------------------------------------------------------- cast bf16 -> f32
__global__ __launch_bounds__(kThreads) void widen_kernel(
const uint16_t* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld,
@@ -857,6 +875,18 @@ extern "C" int r4d_pool_rows_bf16(long x, long y, int rows, int n, int k, float
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_pool_cols_bf16(long x, long y, int rows, int n, int k, float mult, int x_ld,
int y_ld, long stream) {
if (!x || !y) return -1;
if (rows <= 0 || n <= 0 || k <= 0 || n % k) return -2;
hipLaunchKernelGGL(pool_cols_kernel,
dim3((uint32_t)((n / k + kThreads - 1) / kThreads), grid_rows(rows)),
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y,
(uint32_t)n, (uint32_t)k, mult, (uint32_t)x_ld, (uint32_t)y_ld,
(uint32_t)rows);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -1202,6 +1232,25 @@ extern "C" int r4d_rad_pool_rows(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ pool_cols */
extern "C" int r4d_rad_pool_cols(const RadArgs* a, RadStream s) {
const RadTensor* X = r4d_opt(a, 0);
const RadTensor* Y = r4d_opt(a, 1);
if (!X || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(X));
R4D_NEED(dt_bf16(Y));
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
if (n <= 0 || k <= 0 || n % k) return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(X, n, &M);
const long long y_ld = r4d_rows_pitch(Y, n / k, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
return enc_status(r4d_pool_cols_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)k,
(float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld,
(long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ cast bf16 -> f32 */
extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
+5 -4
View File
@@ -204,9 +204,9 @@ __device__ __forceinline__ void st1(float* p, float v) { *p = v; }
template <typename TY>
__global__ __launch_bounds__(kT) void timestep_kernel(
const float* __restrict__ t, TY* __restrict__ y, int h, float scale, float coef,
int round, int y_ld) {
int round, float clamp_min, int y_ld) {
const int m = blockIdx.x;
const float tv = t[m];
const float tv = fmaxf(t[m], clamp_min); /* ref pins are floors; 0 -> identity */
const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
for (int i = threadIdx.x; i < h; i += kT) {
const float f = expf(coef * (float)i / (float)h);
@@ -769,14 +769,15 @@ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
const float coef = (float)(-std::log((double)mp));
const float scale = (float)r4d_getf(a, "scale", 1000.0);
const int round = (int)r4d_geti_or(a, "round", 0);
const float clamp = (float)r4d_getf(a, "clamp_min", 0.0);
if (y->dtype == RAD_F32)
hipLaunchKernelGGL(timestep_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)t->data, (float*)y->data, (int)(n / 2),
scale, coef, round, (int)yl);
scale, coef, round, clamp, (int)yl);
else
hipLaunchKernelGGL(timestep_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)t->data, (uint16_t*)y->data, (int)(n / 2),
scale, coef, round, (int)yl);
scale, coef, round, clamp, (int)yl);
return st_of(hipGetLastError());
}
+1
View File
@@ -575,6 +575,7 @@ int r4d_rad_cast_widen (const RadArgs*, RadStream);
int r4d_rad_cast_f16 (const RadArgs*, RadStream);
int r4d_rad_cast_bf16 (const RadArgs*, RadStream);
int r4d_rad_pool_rows (const RadArgs*, RadStream);
int r4d_rad_pool_cols (const RadArgs*, RadStream);
int r4d_rad_relu (const RadArgs*, RadStream);
int r4d_rad_silu (const RadArgs*, RadStream);
int r4d_rad_gelu (const RadArgs*, RadStream);
+44 -8
View File
@@ -2132,8 +2132,8 @@ static const RadOperandSpec oGateAdd[] = {
{ "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "x", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"),
P_F64("max_period"), P_INTO("round"), P_STR("dtype") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
static const RadOperandSpec oGather2[] = {
{ "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
@@ -2194,7 +2194,7 @@ static const RadOperandSpec oAttnPS[] = {
/* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
static const RadOperandSpec oConv1d[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, { "b", RAD_OPD_WEIGHT, 1 },
@@ -2334,7 +2334,9 @@ static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the
* request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
P_INTO("reflect") };
static const RadOperandSpec oConv3d[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 },
@@ -2432,6 +2434,10 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("pool_rows", pPoolRows, oUnary,
"Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded, then "
"times `mult` and rounded again."),
SCHEMA("pool_cols", pPoolRows, oUnary,
"Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and "
"rounded, then times `mult` and rounded again. n, the input width, is a multiple of k; "
"y has n / k columns."),
SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."),
SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."),
SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."),
@@ -2990,7 +2996,10 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("conv1d", pConv1d, oConv1d,
"a 1-D convolution over the sequences cu_seqlens bounds, channels innermost, zeros outside "
"each; dilation `dil`, padding dil (k - 1) / 2 a side or, with `causal`, dil (k - 1) on "
"the left; `res` added after the bias, then `act`."),
"the left; `res` added after the bias, then `act`. bf16 only with `stride` > 1: one "
"sequence [0, rows of x], an explicit `pad` and any k, output row m reading "
"x[m * stride + tap * dil - pad], the output rows (rows + 2 pad - dil (k - 1) - 1) / "
"stride + 1."),
SCHEMA("conv_t1d", pConvT1d, oConvT1d,
"a transposed 1-D convolution of kernel `k` (2 stride by default, or stride), padding "
"`pad` ((k - stride) / 2 by default, 0 the causal form): each sequence grows `stride` "
@@ -3046,9 +3055,13 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("grid_pos3", pGridPos3, oGridPos3,
"a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."),
SCHEMA("conv3d_ndhwc", pConv3d, oConv3d,
"a stride-1 `same` 3D convolution over NDHWC voxel rows of the device volume geom = "
"(T, H, W), PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; with `res`, "
"y = rd(rd(acc + b) + res), res may alias y."),
"a 3D convolution over NDHWC voxel rows of the device volume geom = (T, H, W), "
"PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; default stride 1 with "
"`same` zero padding; `stride`/`stride_t` > 1 (3x3x3 only) pad first then stride, "
"`causal` 1 takes the temporal padding front-only (kt - 1 zeros, none behind), `pad` "
"`down` pads none above and left and one below and right, `reflect` 1 mirrors the "
"spatial padding instead of zeroing it; with `res`, y = rd(rd(acc + b) + res), res "
"may alias y."),
SCHEMA("group_norm", pGroupNorm, oGroupNorm,
"nn.GroupNorm over all of y's rows (biased variance, rstd in f32), then the optional "
"modulation v (1 + mod[0:n]) + mod[n:2n] and `act` (none or silu), one rounding; "
@@ -3370,6 +3383,10 @@ static const RadConstraint cCastNarrow[] = {
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
/* head_dim 256 with no GQA (an encoder's own heads), sequences past the small kernel's LDS. */
static const RadConstraint cAttnDenseH256G1[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 1), C_GE("max_seqlen", 33), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH256G2[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
@@ -4563,6 +4580,15 @@ static const RadKernelInfo kKernels[] = {
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_pool_rows },
{ "pool_cols_bf16", "pool_cols", "elem",
"mean of every k consecutive columns within a row, then a multiplier: an encoder posterior's "
"adaptive-average pooling over the feature axis",
"any n and k with n % k == 0; a thread an output column",
"bf16 in and out, f32 sum, two roundings",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_pool_cols },
{ "rmsnorm_bf16", "rmsnorm", "norm",
"root-mean-square norm with a gain, two passes over the row",
"any n; the sum of squares accumulates in f32 and only the store narrows",
@@ -5397,6 +5423,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cAttnDenseH64), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense },
{ "attn_dense_h256_bf16", "attn_dense", "attn",
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or "
"blocks, or causal with an optional window behind",
"head_dim 256, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a "
"fused projection allowed), sequences past the small kernel's 32-row LDS bound",
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH256G1), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense },
{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn",
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
"head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window",
+208 -25
View File
@@ -5256,7 +5256,50 @@ void conv1d_cases(const Plugin& pl) {
}
check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2);
}
/* An even kernel is causal only. */
/* The strided downsample (a DAC encoder block's): kernel 2 stride, pad ceil(stride / 2),
* one sequence, rows 8 * stride halved to exactly 8, on the tiled and the direct kernels. */
struct D { int64_t cin, cout, s, pad; };
for (const D& c : { D{ 16, 32, 2, 1 }, D{ 16, 128, 4, 2 }, D{ 5, 9, 2, 1 },
D{ 6, 3, 5, 3 } }) {
const int64_t in = 8 * c.s, k = 2 * c.s, out = 8;
const std::vector<int32_t> cu = { 0, (int32_t)in };
std::vector<float> x = randv((size_t)(in * c.cin), 1.0f);
std::vector<float> w = randv((size_t)(c.cout * c.cin * k), 0.3f);
for (auto& v : w) v = bfr(v);
std::vector<RadParam> ps = { PI("M", in), PI("cin", c.cin), PI("cout", c.cout),
PI("k", k), PI("dil", 1), PS("dtype", "bf16"),
PI("causal", 0), PI("stride", c.s), PI("pad", c.pad) };
const std::string nm = fmt("conv1d_bf16 strided cin %lld cout %lld k %lld stride %lld",
(long long)c.cin, (long long)c.cout, (long long)k,
(long long)c.s);
void* dx = up_bf16(x);
void* dw = stored_weight(r, ps, w, c.cout, c.cin * k, nm.c_str());
void* dcu = up_i32(cu);
void* dy = dalloc((size_t)(out * c.cout) * 2);
if (!dw) continue;
RadTensor tres = TA(RAD_BF16, { out, c.cout }), tb = TA(RAD_BF16, { c.cout });
absent(tres); absent(tb);
const int rc = launch(r, { T(dx, RAD_BF16, { in, c.cin }),
T(dw, RAD_BF16, { c.cout, c.cin, k }), T(dcu, RAD_I32, { 2 }),
tres, T(dy, RAD_BF16, { out, c.cout }), tb }, ps);
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
std::vector<float> want((size_t)(out * c.cout));
for (int64_t m = 0; m < out; ++m)
for (int64_t co = 0; co < c.cout; ++co) {
float acc = 0.0f;
for (int64_t kk = 0; kk < k; ++kk) {
const int64_t ir = m * c.s + kk - c.pad;
if (ir < 0 || ir >= in) continue;
for (int64_t ci = 0; ci < c.cin; ++ci)
acc += w[(size_t)((co * c.cin + ci) * k + kk)] *
x[(size_t)(ir * c.cin + ci)];
}
want[(size_t)(m * c.cout + co)] = acc;
}
check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2);
}
/* An even kernel is causal only; a stride needs its pad and its one sequence; and the
* strided form refuses the f32 rows. */
std::vector<RadParam> ps = { PI("M", 4), PI("cin", 8), PI("cout", 16), PI("k", 4), PI("dil", 1),
PS("dtype", "bf16") };
const int rc = launch(r, { TA(RAD_BF16, { 4, 8 }), TA(RAD_BF16, { 16, 8, 4 }),
@@ -5265,6 +5308,30 @@ void conv1d_cases(const Plugin& pl) {
ps);
ok("conv1d_bf16 refuses an even symmetric kernel", rc == RAD_E_SHAPE,
"rc " + std::to_string(rc));
const std::vector<RadParam> nopad = { PI("M", 8), PI("cin", 8), PI("cout", 16), PI("k", 4),
PI("dil", 1), PS("dtype", "bf16"), PI("stride", 2) };
const int rn = launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 16, 8, 4 }),
TI32({ 2 }, { 0, 8 }), TA(RAD_BF16, { 4, 16 }),
TA(RAD_BF16, { 4, 16 }), TA(RAD_BF16, { 16 }) }, nopad);
ok("conv1d_bf16 refuses a stride without pad", rn == RAD_E_SHAPE, "rc " + std::to_string(rn));
const std::vector<RadParam> two = { PI("M", 8), PI("cin", 8), PI("cout", 16), PI("k", 4),
PI("dil", 1), PS("dtype", "bf16"), PI("stride", 2),
PI("pad", 1) };
const int rt = launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 16, 8, 4 }),
TI32({ 3 }, { 0, 4, 8 }), TA(RAD_BF16, { 4, 16 }),
TA(RAD_BF16, { 4, 16 }), TA(RAD_BF16, { 16 }) }, two);
ok("conv1d_bf16 refuses a stride over two sequences", rt == RAD_E_SHAPE,
"rc " + std::to_string(rt));
if (const RadKernelInfo* f = find(pl, "conv1d_f32")) {
/* Odd k so the refusal comes from the stride, not from the even-kernel rule. */
const std::vector<RadParam> f32 = { PI("M", 8), PI("cin", 8), PI("cout", 16), PI("k", 3),
PI("dil", 1), PS("dtype", "f32"), PI("stride", 2),
PI("pad", 1) };
const int rf = launch(f, { TA(RAD_F32, { 8, 8 }), TA(RAD_F32, { 16, 8, 3 }),
TI32({ 2 }, { 0, 8 }), TA(RAD_F32, { 4, 16 }),
TA(RAD_F32, { 4, 16 }), TA(RAD_F32, { 16 }) }, f32);
ok("conv1d_f32 refuses a stride", rf == RAD_E_DTYPE, "rc " + std::to_string(rf));
}
}
/* conv_t1d: kernel 2 stride or stride, any padding below stride, an odd stride. */
@@ -5792,13 +5859,14 @@ void rope_llama3_case(const Plugin& pl) {
ok("rope_bf16 refuses llama3 beside YaRN", rc2 == RAD_E_INVAL, "rc " + std::to_string(rc2));
}
/* attn_dense causal at head_dim 64 over a fused [rows, 3 * 16 * 64] row (a codec transformer's
* sliding layers), with a window behind and without, one sequence or two, against libref's mask. */
void attn_causal_h64_case(const Plugin& pl, int64_t window, std::vector<int32_t> cu) {
const char* name = "attn_dense_h64_bf16";
/* attn_dense causal over a fused [rows, 3 * nh * hd] row (a codec transformer's sliding layers,
* an audio encoder's own-heads attention), with a window behind and without, one sequence or
* two, against libref's mask. */
void attn_causal_case(const Plugin& pl, const char* name, int64_t hd, int64_t nh,
int64_t window, std::vector<int32_t> cu) {
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
const int64_t hd = 64, nh = 16, total = cu.back(), wq = nh * hd, width = 3 * wq;
const int64_t total = cu.back(), wq = nh * hd, width = 3 * wq;
std::vector<float> qkv = randv((size_t)(total * width), 1.0f);
void* d = up_bf16(qkv);
auto col = [&](int64_t first, int64_t w) {
@@ -6498,18 +6566,32 @@ std::vector<int64_t> conv_rows(const Vol& v, int64_t M, int64_t want) {
return rows;
}
/* Floor division for the CausalConv3d output lengths (PyTorch's rule). */
int64_t idiv_fl(int64_t a, int64_t b) {
return a >= 0 ? a / b : -((-a + b - 1) / b);
}
/* libref's conv3d_ndhwc at output row r: the products (exact in f32) summed in f64, rounded to f32,
* the bias added in f32 and rounded; with a residual, that plus the residual, rounded. `wt` is the
* weight tap-major, as the row stores it. */
* weight tap-major, as the row stores it. `vo` is the output volume; the classic form is
* sp = st = 1 with the symmetric pads (causal = down = refl = 0), `vi` the input volume. */
void conv3d_row(const std::vector<float>& x, int64_t cin, const std::vector<float>& wt,
const std::vector<float>& b, const float* res, const Vol& v, int64_t cout,
int64_t r, float* out) {
const int64_t HW = v.H * v.W, t = r / HW, y = (r / v.W) % v.H, xx = r % v.W;
const std::vector<float>& b, const float* res, const Vol& vi, const Vol& vo,
int64_t sp, int64_t st, int64_t causal, int64_t down, int64_t refl,
int64_t cout, int64_t r, float* out) {
const int64_t OHW = vo.H * vo.W, HW = vi.H * vi.W;
const int64_t t = r / OHW, y = (r / vo.W) % vo.H, xx = r % vo.W;
const int64_t ft = causal ? 2 : 1, pt = down ? 0 : 1, pl = down ? 0 : 1;
std::vector<double> acc((size_t)cout, 0.0);
for (int64_t tap = 0; tap < 27; ++tap) {
const int64_t nt = t + tap / 9 - 1, ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1;
if (nt < 0 || nt >= v.T || ny < 0 || ny >= v.H || nx < 0 || nx >= v.W) continue;
const float* xr = &x[(size_t)((nt * HW + ny * v.W + nx) * cin)];
const int64_t nt = t * st + tap / 9 - ft;
int64_t ny = y * sp + (tap / 3) % 3 - pt, nx = xx * sp + tap % 3 - pl;
if (refl) { /* torch's mirror, no repeated edge, then the bounds */
if (ny < 0) ny = -ny; else if (ny >= vi.H) ny = 2 * vi.H - 2 - ny;
if (nx < 0) nx = -nx; else if (nx >= vi.W) nx = 2 * vi.W - 2 - nx;
}
if (nt < 0 || nt >= vi.T || ny < 0 || ny >= vi.H || nx < 0 || nx >= vi.W) continue;
const float* xr = &x[(size_t)((nt * HW + ny * vi.W + nx) * cin)];
for (int64_t o = 0; o < cout; ++o) {
const float* wr = &wt[(size_t)((o * 27 + tap) * cin)];
double s = 0.0;
@@ -6531,20 +6613,31 @@ struct ConvCase {
int res; /* 0 none, 1 its own operand, 2 the output itself */
bool bf32; /* an f32 bias */
int64_t xpad, ypad, yextra; /* pitch padding, output rows past the volume */
int64_t mshort; /* the M parameter this short of T H W: the volume's rows are written */
int64_t mshort; /* the M parameter this short of the output rows: those are written */
int64_t sample; /* rows checked besides the faces; 0 every row */
/* The CausalConv3d forms; the defaults are the stride-1 `same` padding. */
int64_t sp = 1, st = 1, causal = 0, down = 0, refl = 0;
};
void conv3d_case(const RadKernelInfo* r, const ConvCase& c) {
const Vol& v = c.v;
const int64_t vol = v.T * v.H * v.W, M = vol, K = 27 * c.cin;
const int64_t ft = c.causal ? 2 : 1, bk = c.causal ? 0 : 1;
const int64_t pt = c.down ? 0 : 1, pb = c.down ? 1 : 1, pl = c.down ? 0 : 1, pr = c.down ? 1 : 1;
const Vol vo{ idiv_fl(v.T + ft + bk - 3, c.st) + 1, idiv_fl(v.H + pt + pb - 3, c.sp) + 1,
idiv_fl(v.W + pl + pr - 3, c.sp) + 1 };
const int64_t vol = v.T * v.H * v.W, M = vo.T * vo.H * vo.W, K = 27 * c.cin;
const bool gen = c.sp != 1 || c.st != 1 || c.causal || c.down || c.refl;
const int64_t ldx = c.cin + c.xpad, ldy = c.cout + c.ypad, yrows = M + c.yextra;
const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s",
const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s%s",
c.what, (long long)c.cin, (long long)c.cout, (long long)v.H,
(long long)v.W, (long long)v.T,
c.res == 2 ? ", res in place" : c.res ? ", res" : "",
c.bf32 ? ", f32 bias" : "",
c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : "");
c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : "",
gen ? fmt(", stride %lld t %lld%s%s%s", (long long)c.sp,
(long long)c.st, c.causal ? " causal" : "",
c.down ? " down" : "", c.refl ? " reflect" : "").c_str()
: "");
g_seed = 0xc03dull + (uint64_t)(c.cin * 131 + c.cout * 7 + v.T);
std::vector<float> x = randv((size_t)(vol * c.cin), 1.0f);
std::vector<float> w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K));
@@ -6559,6 +6652,9 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) {
wt[(size_t)((o * 27 + t) * c.cin + ci)] = w[(size_t)((o * c.cin + ci) * 27 + t)];
std::vector<RadParam> ps = { PI("M", M - c.mshort), PI("cin", c.cin), PI("cout", c.cout),
PI("k", 3), PI("kt", 3), PS("dtype", "bf16") };
if (gen)
ps.insert(ps.end(), { PI("stride", c.sp), PI("stride_t", c.st), PI("causal", c.causal),
PS("pad", c.down ? "down" : "same"), PI("reflect", c.refl) });
void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str());
void* dx = up_rows(x, vol, c.cin, ldx, vol);
std::vector<float> bb = b;
@@ -6583,15 +6679,15 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) {
const std::vector<uint16_t> yb = down_u16(dy, (size_t)(yrows * ldy));
std::vector<int64_t> rows;
if (c.sample) {
rows = conv_rows(v, M, c.sample);
rows = conv_rows(vo, M, c.sample);
} else {
for (int64_t i = 0; i < M; ++i) rows.push_back(i);
}
std::vector<float> want(rows.size() * (size_t)c.cout), got(want.size());
par_for((int64_t)rows.size(), [&](int64_t i) {
const int64_t rr = rows[(size_t)i];
conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, c.cout, rr,
&want[(size_t)i * c.cout]);
conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, vo, c.sp,
c.st, c.causal, c.down, c.refl, c.cout, rr, &want[(size_t)i * c.cout]);
for (int64_t o = 0; o < c.cout; ++o)
got[(size_t)i * c.cout + o] = h_bf16(yb[(size_t)(rr * ldy + o)]);
});
@@ -6624,7 +6720,31 @@ void conv3d_cases(const Plugin& pl) {
/* A 15 s clip at the target size: 411264 rows, the largest volume the model runs. */
conv3d_case(r, ConvCase{ "102 frames", Vol{ 102, 84, 48 }, 512, 512, 2, false, 0, 0, 0, 0, 2000 });
/* Refusals: a 5-wide kernel, a channel count off the 16-byte chunk. */
/* The video encoder's CausalConv3d forms: a res block (causal, reflect), the downsample
* (per-axis stride 2 with the `down` pad and a reflect), the first conv on a 24-channel
* input (the non-C64 K walk), one frame in (the reference's T == 1 truncation is subsumed),
* the `down` pad at stride 1, a temporal-only stride and a pitched two-channel-tiles-a-tap
* downsample with the residual in place. */
for (const ConvCase& c : {
ConvCase{ "encoder block", Vol{ 5, 5, 7 }, 64, 64, 1, false, 0, 0, 0, 0, 0,
1, 1, 1, 0, 1 },
ConvCase{ "encoder downsample", Vol{ 4, 6, 6 }, 64, 32, 0, false, 0, 0, 0, 0, 0,
2, 2, 1, 1, 1 },
ConvCase{ "encoder conv_in", Vol{ 3, 4, 5 }, 24, 64, 0, false, 0, 0, 0, 0, 0,
1, 1, 1, 0, 1 },
ConvCase{ "one frame causal", Vol{ 1, 3, 3 }, 16, 16, 0, false, 0, 0, 0, 0, 0,
1, 1, 1, 0, 1 },
ConvCase{ "down no stride", Vol{ 2, 4, 4 }, 8, 8, 0, false, 0, 0, 0, 0, 0,
1, 1, 0, 1, 1 },
ConvCase{ "temporal stride", Vol{ 6, 3, 4 }, 16, 24, 0, true, 0, 0, 0, 0, 0,
1, 2, 1, 0, 1 },
ConvCase{ "down pitched two tiles", Vol{ 3, 5, 5 }, 128, 136, 2, false, 8, 8, 4, 0, 0,
2, 1, 1, 1, 1 },
})
conv3d_case(r, c);
/* Refusals: a 5-wide kernel, a channel count off the 16-byte chunk, a zero stride, a causal
* that is neither 0 nor 1 and a pad that is neither `same` nor `down`. */
ok("conv3d_ndhwc_bf16 refuses k 5",
launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 1000 }), TA(RAD_BF16, { 8 }),
TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) },
@@ -6635,6 +6755,18 @@ void conv3d_cases(const Plugin& pl) {
TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) },
{ PI("M", 8), PI("cin", 12), PI("cout", 8), PI("k", 3), PI("kt", 3),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
for (const auto& bad : { std::pair<const char*, RadParam>{ "stride 0", PI("stride", 0) },
{ "stride_t -1", PI("stride_t", -1) },
{ "causal 2", PI("causal", 2) }, { "reflect 3", PI("reflect", 3) },
{ "pad mirror", PS("pad", "mirror") } }) {
std::vector<RadParam> ps = { PI("M", 8), PI("cin", 8), PI("cout", 8), PI("k", 3),
PI("kt", 3), PS("dtype", "bf16"), bad.second };
ok((std::string("conv3d_ndhwc_bf16 refuses ") + bad.first).c_str(),
launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 216 }), TA(RAD_BF16, { 8 }),
TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) },
ps) == RAD_E_SHAPE,
"launched");
}
}
/* ------------------------------------------------------------------ group_norm */
@@ -6697,6 +6829,12 @@ void group_norm_cases(const Plugin& pl) {
G{ "f32 in, bf16 out", 101, 512, 32, true, false, false, 0, false, false, -3.0f, 16 },
G{ "one row", 1, 512, 32, false, false, false, 1, true, false, 0.0f, 0 },
G{ "64 channels", 1000, 64, 8, false, true, false, 0, true, false, 0.0f, 8 },
/* Four channels a group (the video encoder's first level, 128 in 32): four-channel
* chunks. Pitched bf16 with SiLU; then f32 output, f32 gain and bias and a bf16
* modulation, so every narrow vector load runs. */
G{ "128 in 32 groups", 130, 128, 32, false, false, false, 0, true, false, 0.0f, 8 },
G{ "64 in 16 groups, modulated", 41, 64, 16, false, true, true, 1, false, false,
0.0f, 0 },
}) {
const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2;
const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what,
@@ -7430,6 +7568,28 @@ void timestep_f32_case(const Plugin& pl) {
want[(size_t)(m * n + h + i)] = (float)std::sin((double)arg);
}
check_f32("timestep_embed_f32 numerics", down_f32(dy, want.size()), want, 1e-6);
/* clamp_min raises every below-floor timestep to the floor before embedding -- the device
* mirror of the ref pins. Rows whose t already sits at or above the floor are untouched. */
void* dy2 = dalloc((size_t)(M * n) * 4);
const float floor_t = 0.9f;
const int rc2 = launch(r, { T(dt, RAD_F32, { M }), T(dy2, RAD_F32, { M, n }) },
{ PI("M", M), PI("n", n), PF("scale", 1.0), PF("max_period", 10000.0),
PF("clamp_min", floor_t), PS("dtype", "f32") });
if (rc2 != RAD_OK) { ok("timestep_embed_f32 clamp_min", false, "rc " + std::to_string(rc2)); }
else {
std::vector<float> want2((size_t)(M * n));
for (int64_t m = 0; m < M; ++m) {
const float tv = t[(size_t)m] > floor_t ? t[(size_t)m] : floor_t;
for (int64_t i = 0; i < h; ++i) {
const float f = (float)std::exp((double)(coef * (float)i / (float)h));
const float arg = tv * f;
want2[(size_t)(m * n + i)] = (float)std::cos((double)arg);
want2[(size_t)(m * n + h + i)] = (float)std::sin((double)arg);
}
}
check_f32("timestep_embed_f32 clamp_min numerics", down_f32(dy2, want2.size()), want2, 1e-6);
}
}
void randn_f32_case(const Plugin& pl) {
@@ -17836,6 +17996,24 @@ static void device_phase(const Plugin& pl) {
run_case(r, ts, ps);
}
}
if (sel("pool_cols_bf16")) {
const RadKernelInfo* r = find(pl, "pool_cols_bf16");
if (!r) ok("pool_cols_bf16", false, "row absent");
else {
/* The audio encoder posterior head's two column poolings: 2048 -> 256 and 256 -> 32,
* eight a group, the second carrying a multiplier. */
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 17, 2048 }),
T(nullptr, RAD_BF16, { 17, 256 }) };
std::vector<RadParam> ps = { PI("M", 17), PI("n", 2048), PI("k", 8),
PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<RadTensor> ts2 = { T(nullptr, RAD_BF16, { 137, 256 }),
T(nullptr, RAD_BF16, { 137, 32 }) };
std::vector<RadParam> ps2 = { PI("M", 137), PI("n", 256), PI("k", 8),
PF("mult", 0.125), PS("dtype", "bf16") };
run_case(r, ts2, ps2);
}
}
/* --- the audio tower's ops, numerically: each kernel against the formula libref implements,
* computed on the host from the same bf16 inputs (rad-kbench's replay fixture predates these
* ops). Relative L2 against a bf16 rounding of the answer. */
@@ -19242,10 +19420,15 @@ static void device_phase(const Plugin& pl) {
if (sel("mul_weight_bf16")) au::mul_weight_f32_case(pl);
if (sel("qk_norm_rope_bf16")) au::qk_norm_rope_f32_gain_case(pl);
if (sel("attn_dense_h64_bf16")) {
au::attn_causal_h64_case(pl, 72, { 0, 89 });
au::attn_causal_h64_case(pl, 0, { 0, 89 });
au::attn_causal_h64_case(pl, 72, { 0, 13, 89 });
au::attn_causal_h64_case(pl, 9, { 0, 40, 200 });
au::attn_causal_case(pl, "attn_dense_h64_bf16", 64, 16, 72, { 0, 89 });
au::attn_causal_case(pl, "attn_dense_h64_bf16", 64, 16, 0, { 0, 89 });
au::attn_causal_case(pl, "attn_dense_h64_bf16", 64, 16, 72, { 0, 13, 89 });
au::attn_causal_case(pl, "attn_dense_h64_bf16", 64, 16, 9, { 0, 40, 200 });
}
if (sel("attn_dense_h256_bf16")) {
au::attn_causal_case(pl, "attn_dense_h256_bf16", 256, 8, 72, { 0, 137 });
au::attn_causal_case(pl, "attn_dense_h256_bf16", 256, 8, 0, { 0, 137 });
au::attn_causal_case(pl, "attn_dense_h256_bf16", 256, 8, 9, { 0, 40, 200 });
}
if (sel("conv1d_dw_bf16")) au::conv1d_dw_bias_cases(pl);
if (sel("attn_dense_h256_gqa4_bf16")) {
+201 -71
View File
@@ -56,6 +56,51 @@ __device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) {
if (f32) ld8((const float*)p + c, f);
else ld8((const uint16_t*)p + c, f);
}
// Four consecutive values, the chunk a group narrower than eight channels has (see group_norm):
// an 8-byte bf16 or 16-byte f32 access at the same alignment argument, rows pitching a multiple
// of eight and a chunk starting on a multiple of four.
__device__ __forceinline__ void ld4(const uint16_t* p, float* f) {
const uint2 u = *(const uint2*)p;
f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y);
}
__device__ __forceinline__ void ld4(const float* p, float* f) {
const float4 a = *(const float4*)p;
f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w;
}
__device__ __forceinline__ void st4(uint16_t* p, const float* f) {
uint2 u;
u.x = bf16x2_rne(f[0], f[1]);
u.y = bf16x2_rne(f[2], f[3]);
*(uint2*)p = u;
}
__device__ __forceinline__ void st4(float* p, const float* f) {
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
}
__device__ __forceinline__ void ld4w(const void* p, bool f32, int c, float* f) {
if (f32) ld4((const float*)p + c, f);
else ld4((const uint16_t*)p + c, f);
}
// A thread's chunk load: eight channels, or four when a group is that wide.
template <int CS>
__device__ __forceinline__ void ldchunk(const uint16_t* p, float* f) {
if constexpr (CS == 8) ld8(p, f); else ld4(p, f);
}
template <int CS>
__device__ __forceinline__ void ldchunk(const float* p, float* f) {
if constexpr (CS == 8) ld8(p, f); else ld4(p, f);
}
template <int CS>
__device__ __forceinline__ void stchunk(uint16_t* p, const float* f) {
if constexpr (CS == 8) st8(p, f); else st4(p, f);
}
template <int CS>
__device__ __forceinline__ void stchunk(float* p, const float* f) {
if constexpr (CS == 8) st8(p, f); else st4(p, f);
}
template <int CS>
__device__ __forceinline__ void ldchunkw(const void* p, bool f32, int c, float* f) {
if constexpr (CS == 8) ld8w(p, f32, c, f); else ld4w(p, f32, c, f);
}
// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands
// cannot hold (`rows` rows of the input).
@@ -131,15 +176,27 @@ __device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsig
return t;
}
/* Floor division (b > 0) for the output lengths' PyTorch rule; the numerator may be negative. */
__device__ __forceinline__ int idiv_dev(int a, int b) {
return a >= 0 ? a / b : -((-a + b - 1) / b);
}
/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary.
* `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob)
* and `Mcap` bounds the rows written. */
template <bool C64, bool RES, bool BF32>
* and `Mcap` bounds the rows written.
*
* `GEN` (host-set: any non-default stride / causal / `down` / reflect, the 3x3x3 encoder forms)
* generalises the gather: a staged voxel is one of the (T2, H2, W2) output grid, its base source
* coordinate carries the stride and the negative pad, and a tap's neighbour is mirrored into the
* volume first when `refl` (torch's reflect, which the launcher has checked the volume against).
* The classic path is untouched — same register allocation and measured bandwidth. */
template <bool C64, bool RES, bool BF32, bool GEN>
__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt,
const void* __restrict__ bias, const unsigned short* R, unsigned short* C,
const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows,
unsigned xbytes, int cin, int N, unsigned vec) {
unsigned xbytes, int cin, int N, unsigned vec, int st, int sp, int ft, int bk, int pt,
int pb, int pl, int pr, int refl) {
typedef r4d_u32x4 U4;
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB];
@@ -147,7 +204,17 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
long long vol;
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
const int HW = gH * gW;
const int Mv = vol < (long long)Mcap ? (int)vol : Mcap;
int H2 = gH, W2 = gW;
long long Mv64 = vol;
if constexpr (GEN) {
const int T2 = idiv_dev(gT + ft + bk - 3, st) + 1;
H2 = idiv_dev(gH + pt + pb - 3, sp) + 1;
W2 = idiv_dev(gW + pl + pr - 3, sp) + 1;
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return;
Mv64 = (long long)T2 * H2 * W2;
}
const int OHW = H2 * W2;
const int Mv = Mv64 < (long long)Mcap ? (int)Mv64 : Mcap;
const uint32_t tid = threadIdx.x, lane = tid & 31u;
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5);
@@ -168,6 +235,7 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
if (m0 >= (uint32_t)Mv) return;
// This thread's staged rows and their voxels; a row past the volume sits outside every frame.
// Classic keeps the voxel row (its taps are row deltas); GEN the base source coordinate.
const uint32_t ch = tid % kCCPR;
int vm[kCSPT], vt[kCSPT], vy[kCSPT], vx[kCSPT];
uint32_t adst[kCSPT];
@@ -176,15 +244,27 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const uint32_t r = tid / kCCPR + kCRS * i;
const int m = (int)(m0 + r);
adst[i] = r * kCPB + ch * 16u;
vm[i] = m;
vt[i] = -4;
vy[i] = 0;
vx[i] = 0;
if (m < Mv) {
vt[i] = m / HW;
const int rem = m - vt[i] * HW;
vy[i] = rem / gW;
vx[i] = rem - vy[i] * gW;
if constexpr (GEN) {
vm[i] = -4; // base frame; negative, it fails every tap's frame bounds
vt[i] = 0; // base row
vy[i] = 0; // base column
if (m < Mv) {
const int t = m / OHW, rem = m - t * OHW, yy = rem / W2;
vm[i] = t * st - ft;
vt[i] = yy * sp - pt;
vy[i] = (rem - yy * W2) * sp - pl;
}
} else {
vm[i] = m;
vt[i] = -4;
vy[i] = 0;
vx[i] = 0;
if (m < Mv) {
vt[i] = m / HW;
const int rem = m - vt[i] * HW;
vy[i] = rem / gW;
vx[i] = rem - vy[i] * gW;
}
}
}
// The four neighbours' byte offsets at a tap, kOob outside the volume; with C64 they include
@@ -193,14 +273,33 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
__builtin_amdgcn_make_buffer_rsrc(const_cast<unsigned short*>(X), 0, (int)xbytes, kBufWord3);
uint32_t off[kCSPT];
auto at_tap = [&](int tap) {
const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1;
const int delta = dt * HW + dy * gW + dx;
if constexpr (GEN) {
const int dt = tap / 9, dy = (tap / 3) % 3, dx = tap % 3; // the pads ride in the base
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT &&
(unsigned)(vy[i] + dy) < (unsigned)gH &&
(unsigned)(vx[i] + dx) < (unsigned)gW;
off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
for (uint32_t i = 0; i < kCSPT; ++i) {
const int tz = vm[i] + dt;
int sy = vt[i] + dy, sx = vy[i] + dx;
if (refl) { // torch's mirror, no repeated edge; then the ordinary bounds
if (sy < 0) sy = -sy; else if (sy >= gH) sy = 2 * gH - 2 - sy;
if (sx < 0) sx = -sx; else if (sx >= gW) sx = 2 * gW - 2 - sx;
}
const bool ok = tap < kTaps && (unsigned)tz < (unsigned)gT &&
(unsigned)sy < (unsigned)gH && (unsigned)sx < (unsigned)gW;
off[i] = ok
? (uint32_t)(((long long)tz * gH + sy) * gW + sx) * ldx * 2u +
(C64 ? ch * 16u : 0u)
: kOob;
}
} else {
const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1;
const int delta = dt * HW + dy * gW + dx;
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT &&
(unsigned)(vy[i] + dy) < (unsigned)gH &&
(unsigned)(vx[i] + dx) < (unsigned)gW;
off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
}
}
};
@@ -363,13 +462,14 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
// give the same bytes:
//
// 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2)
// of them to the scratch. A thread keeps one 8-channel chunk of one group over every
// of them to the scratch. A thread keeps one chunk of one group (eight channels, or four
// when a group is four channels wide) over every
// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of
// squares from cancelling against a large mean); the block merges its threads' triples per
// group in thread order (Chan's parallel update).
// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps).
// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// 3. apply: a thread one chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// f32, one rounding.
//
// The scratch beyond the 2 groups leading values holds part p of group g at 3 (g kGnParts + p).
@@ -387,12 +487,12 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo
n = nab;
}
/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks
* a group. */
template <typename TX>
/* `CS` the channels a thread's chunk: 8, or 4 when the group is exactly that wide. `cpr_log`:
* log2 of the chunks a row (n / CS, a power of two dividing the block); `gs` the chunks a group. */
template <typename TX, int CS>
__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
float* __restrict__ stats, int M, int groups,
int cpr_log, int gs8, int ldx, int rpp) {
int cpr_log, int gs, int ldx, int rpp) {
__shared__ float sh[3][kT];
const int tid = threadIdx.x;
const int cpr = 1 << cpr_log, slots = kT >> cpr_log;
@@ -401,16 +501,16 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
const int r0 = p * rpp, r1 = min(M, r0 + rpp);
float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f;
for (int r = r0 + slot; r < r1; r += slots) {
float v[8];
ld8(x + (size_t)r * ldx + c * 8, v);
float v[CS];
ldchunk<CS>(x + (size_t)r * ldx + c * CS, v);
if (cnt == 0.0f) shift = v[0];
#pragma unroll
for (int j = 0; j < 8; ++j) {
for (int j = 0; j < CS; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += 8.0f;
cnt += (float)CS;
}
float mean = 0.0f, m2 = 0.0f;
if (cnt > 0.0f) {
@@ -425,8 +525,8 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
for (int g = tid; g < groups; g += kT) {
float N = 0.0f, Mn = 0.0f, Q = 0.0f;
for (int s = 0; s < slots; ++s)
for (int k = 0; k < gs8; ++k) {
const int t = (s << cpr_log) + g * gs8 + k;
for (int k = 0; k < gs; ++k) {
const int t = (s << cpr_log) + g * gs + k;
chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]);
}
float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3;
@@ -466,36 +566,36 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats,
/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32
* one. x and y may be the same memory: a thread reads its chunk before it writes it. */
template <typename TX, typename TY>
template <typename TX, typename TY, int CS>
__global__ __launch_bounds__(kT) void gn_apply_kernel(
const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log,
int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) {
int gs, int ldx, int ldy, int wf, int bf, int modk, int silu) {
const int slots = kT >> cpr_log;
const int tid = threadIdx.x;
const int r = blockIdx.x * slots + (tid >> cpr_log);
if (r >= M) return;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8;
const int g = ck / gs8;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * CS;
const int g = ck / gs;
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
float v[8], wv[8], bv[8];
ld8(x + (size_t)r * ldx + c, v);
ld8w(w, wf != 0, c, wv);
ld8w(b, bf != 0, c, bv);
float v[CS], wv[CS], bv[CS];
ldchunk<CS>(x + (size_t)r * ldx + c, v);
ldchunkw<CS>(w, wf != 0, c, wv);
ldchunkw<CS>(b, bf != 0, c, bv);
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
for (int j = 0; j < CS; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
if (modk) {
float sc[8], sf[8];
ld8w(mod, modk == 2, c, sc);
ld8w(mod, modk == 2, n + c, sf);
float sc[CS], sf[CS];
ldchunkw<CS>(mod, modk == 2, c, sc);
ldchunkw<CS>(mod, modk == 2, n + c, sf);
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
for (int j = 0; j < CS; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
}
if (silu) {
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
for (int j = 0; j < CS; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
}
st8(y + (size_t)r * ldy + c, v);
stchunk<CS>(y + (size_t)r * ldy + c, v);
}
// ---------------------------------------------------------------------------- tconv_dw
@@ -716,6 +816,21 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
/* 3 x 3 x 3 only: the tap decode is the kernel's constant. */
if (r4d_geti_or(a, "k", 3) != 3 || r4d_geti_or(a, "kt", 3) != 3) return R4D_NO(RAD_E_SHAPE);
if (cin <= 0 || cout <= 0 || (cin & 7)) return R4D_NO(RAD_E_SHAPE);
/* The video encoder's CausalConv3d forms: per-axis strides, the time pad front-only, the
* `down` spatial pad and a spatial reflect. The defaults take the classic gather; every form
* is 3x3x3, which the check above already forces. The pads and the kernel's constant:
* kt / 2 = k / 2 = 1, kt - 1 = 2. */
const long long sp = r4d_geti_or(a, "stride", 1), st = r4d_geti_or(a, "stride_t", 1);
const long long causal = r4d_geti_or(a, "causal", 0), reflect = r4d_geti_or(a, "reflect", 0);
const char* pads = r4d_gets(a, "pad");
if (pads && std::strcmp(pads, "same") && std::strcmp(pads, "down")) return R4D_NO(RAD_E_SHAPE);
const bool down = pads && !std::strcmp(pads, "down");
if (sp <= 0 || st <= 0 || sp > (1ll << 30) || st > (1ll << 30) || (causal && causal != 1) ||
(reflect && reflect != 1))
return R4D_NO(RAD_E_SHAPE);
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
const int ft = causal ? 2 : 1, bk = causal ? 0 : 1;
const int pt = down ? 0 : 1, pl = down ? 0 : 1, pb = 1, pr = 1;
const long long K = (long long)kTaps * cin;
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
@@ -744,14 +859,17 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
(!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16)));
const dim3 grid((unsigned)((Mcap + kCBM - 1) / kCBM), (unsigned)((cout + kCBN - 1) / kCBN));
const bool c64 = cin % kCFK == 0, bf32 = is_f32(b);
#define C3_L(C6, RS, BF) \
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF>), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \
Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \
(int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec)
#define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0)
#define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0)
if (c64) C3_BF(true);
C3_BF(false);
#define C3_L(G, C6, RS, BF) \
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF, G>), grid, dim3(kCThreads), 0, Xp, Wp, \
Bp, Rp, Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, \
(unsigned)ldy, (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, \
vec, (int)st, (int)sp, ft, bk, pt, pb, pl, pr, (int)reflect)
#define C3_RES(G, C6, BF) do { if (res) C3_L(G, C6, true, BF); C3_L(G, C6, false, BF); } while (0)
#define C3_BF(G, C6) do { if (bf32) C3_RES(G, C6, true); C3_RES(G, C6, false); } while (0)
#define C3_C6(G) do { if (c64) C3_BF(G, true); C3_BF(G, false); } while (0)
if (gen) C3_C6(true);
C3_C6(false);
#undef C3_C6
#undef C3_BF
#undef C3_RES
#undef C3_L
@@ -774,11 +892,13 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
if (!std::strcmp(act, "silu")) silu = 1;
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
}
/* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the
* 256-thread block. */
const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1;
if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups ||
(n / groups) % 8)
/* A thread one chunk inside one group — 8 channels, or 4 when a group is exactly that wide
* (the video encoder's first level: 128 channels in 32 groups) — a row's chunks a power of
* two dividing the 256-thread block. */
const long long cg = (n > 0 && groups > 0 && !(n % groups)) ? n / groups : 0;
const int cs = (cg % 8 == 0) ? 8 : (cg == 4 ? 4 : 0);
const int cpr_log = (cs && n > 0 && !(n & 7)) ? log2_exact(n / cs) : -1;
if (cs == 0 || cpr_log < 0 || n / cs > kT || groups > kT)
return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) ||
r4d_numel(st) < groups * (2 + 3 * kGnParts))
@@ -797,18 +917,24 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
long long rpp = (M + kGnParts - 1) / kGnParts;
rpp = (rpp + slots - 1) / slots * slots;
const int parts = (int)((M + rpp - 1) / rpp);
const int gs8 = (int)(n / groups / 8);
const int gs = (int)(cg / cs);
float* S = (float*)r4d_wp(st);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
int rc;
if (is_f32(x))
rc = R4D_EMIT(stream, gn_part_kernel<float>, dim3((unsigned)parts), dim3(kT), 0,
(const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
(int)rpp);
rc = cs == 8 ? R4D_EMIT(stream, (gn_part_kernel<float, 8>), dim3((unsigned)parts),
dim3(kT), 0, (const float*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp)
: R4D_EMIT(stream, (gn_part_kernel<float, 4>), dim3((unsigned)parts),
dim3(kT), 0, (const float*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp);
else
rc = R4D_EMIT(stream, gn_part_kernel<uint16_t>, dim3((unsigned)parts), dim3(kT), 0,
(const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
(int)rpp);
rc = cs == 8 ? R4D_EMIT(stream, (gn_part_kernel<uint16_t, 8>), dim3((unsigned)parts),
dim3(kT), 0, (const uint16_t*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp)
: R4D_EMIT(stream, (gn_part_kernel<uint16_t, 4>), dim3((unsigned)parts),
dim3(kT), 0, (const uint16_t*)r4d_p(x), S, (int)M, (int)groups,
cpr_log, gs, (int)ldx, (int)rpp);
if (rc != RAD_OK) return R4D_NO(rc);
rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups,
parts, eps);
@@ -816,10 +942,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1;
const dim3 grid((unsigned)((M + slots - 1) / slots));
#define GN_A(TX, TY) \
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY>), grid, dim3(kT), 0, (const TX*)r4d_p(x), \
(TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \
(int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
modk, silu)
return cs == 8 ? R4D_EMIT(stream, (gn_apply_kernel<TX, TY, 8>), grid, dim3(kT), 0, \
(const TX*)r4d_p(x), (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), \
r4d_p(mod), (const float*)S, (int)M, (int)n, cpr_log, gs, \
(int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), modk, silu) \
: R4D_EMIT(stream, (gn_apply_kernel<TX, TY, 4>), grid, dim3(kT), 0, \
(const TX*)r4d_p(x), (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), \
r4d_p(mod), (const float*)S, (int)M, (int)n, cpr_log, gs, \
(int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), modk, silu)
if (is_f32(x)) {
if (is_f32(y)) GN_A(float, float);
GN_A(float, uint16_t);
+28 -11
View File
@@ -50,8 +50,12 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
* them), outside of which the input reads zero (each sequence is padded on its own). w is
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
* dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none,
* tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */
* dil (k - 1), on the left (any k). With `stride` > 1 - bf16 only, the encoder's downsample - the
* op is one sequence [0, rows of x], `pad` explicit and any k, and output row m reads
* x[m * stride + tap * dil - pad]: PyTorch's zero-padded strided conv, whose output length
* (rows + 2 pad - dil (k - 1) - 1) / stride + 1 the y operand must have exactly. `res`, when
* bound, is added after the bias; then `act` (none, tanh, or clamp to [-1, 1], a vocoder's output
* clamp). f32 accumulation, one rounding. */
int ref_conv1d(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2];
@@ -59,29 +63,42 @@ int ref_conv1d(const RadArgs* a, RadStream) {
if (!y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), pp = p_int(a, "pad", -1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1)
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || pp < 0)) ||
(st <= 1 && pp >= 0))
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
if (r0 < 0 || r1 <= r0 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2;
REF_PAR_FOR((r1 - r0) * cout * cin * k)
for (int64_t r = r0; r < r1; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
/* The strided form: one full sequence, bf16, and y exactly the formula's rows. */
int64_t hi = r1;
if (st > 1) {
if (x->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(x, cin)) return RAD_E_SHAPE;
hi = (r1 + 2 * pp - dil * (k - 1) - 1) / st + 1;
if (hi <= 0 || rows_of(y, cout) != hi) return RAD_E_SHAPE;
} else if (rows_of(y, cout) < r1) {
return RAD_E_SHAPE;
}
if (res && rows_of(res, cout) < hi) return RAD_E_SHAPE;
const int64_t pad = pp >= 0 ? pp : (causal ? dil * (k - 1) : dil * (k - 1) / 2);
const int64_t lo = st > 1 ? 0 : r0; /* a strided op starts at row 0 of its one sequence */
REF_PAR_FOR((hi - lo) * cout * cin * k)
for (int64_t r = lo; r < hi; ++r) {
const int64_t e = seq_of(cu, n_seq, st > 1 ? r * st : r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
for (int64_t co = 0; co < cout; ++co) {
float acc = 0.0f;
for (int64_t kk = 0; kk < k; ++kk) {
const int64_t ir = r + kk * dil - pad;
const int64_t ir = r * st + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const int64_t xb = rowoff(x, ir, cin), xs = laststride(x);
for (int64_t ci = 0; ci < cin; ++ci)
+28
View File
@@ -460,6 +460,34 @@ int ref_pool_rows(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_cols */
/* Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and rounded
* to y's dtype, then multiplied by `mult` and rounded again — pool_rows' dual: it pools the
* columns, what a torch adaptive_avg_pool1d over the feature axis of an encoder's posterior head
* computes. */
int ref_pool_cols(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0 || n % k) return RAD_E_SHAPE;
const int64_t M = rows_of(X, n), nw = n / k;
if (M <= 0 || numel(Y) < M * nw) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
REF_PAR_FOR(M * nw * k)
for (int64_t r = 0; r < M; ++r) {
const int64_t yb = rowoff(Y, r, nw), ys = laststride(Y), xs = laststride(X);
for (int64_t c = 0; c < nw; ++c) {
float acc = 0.0f;
for (int64_t j = 0; j < k; ++j) acc += ldt(X, rowoff(X, r, n) + (c * k + j) * xs);
stt(Y, yb + c * ys, acc * inv);
stt(Y, yb + c * ys, ldt(Y, yb + c * ys) * mult);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ relu */
/* y = max(x, 0) over [M, n], each operand at its own row pitch. */
int ref_relu(const RadArgs* a, RadStream) {
+2 -1
View File
@@ -276,13 +276,14 @@ int ref_timestep_embed(const RadArgs* a, RadStream) {
const float scale = p_f32(a, "scale", 1000.0f);
const double mp = p_f32(a, "max_period", 10000.0f);
const int round = (int)p_int(a, "round", 0);
const float clamp = p_f32(a, "clamp_min", 0.0f);
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE;
const int64_t h = n / 2;
const float coef = (float)(-std::log(mp));
for (int64_t m = 0; m < rows; ++m) {
const float tv = ldt(t, offlin(t, m));
const float tv = std::fmax(ldt(t, offlin(t, m)), clamp); /* ref pins are floors */
const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv;
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
for (int64_t i = 0; i < h; ++i) {
+2
View File
@@ -73,6 +73,7 @@ int ref_act_mul (const RadArgs*, RadStream);
int ref_mul_weight (const RadArgs*, RadStream);
int ref_seg_mean (const RadArgs*, RadStream);
int ref_pool_rows (const RadArgs*, RadStream);
int ref_pool_cols (const RadArgs*, RadStream);
int ref_relu (const RadArgs*, RadStream);
int ref_clamp (const RadArgs*, RadStream);
int ref_conv2d (const RadArgs*, RadStream);
@@ -280,6 +281,7 @@ REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
REF_SHAPE_FN(ref_seg_mean);
REF_SHAPE_FN(ref_pool_rows);
REF_SHAPE_FN(ref_pool_cols);
REF_SHAPE_FN(ref_relu);
REF_SHAPE_FN(ref_clamp);
REF_SHAPE_FN(ref_conv2d);
+25 -8
View File
@@ -678,7 +678,7 @@ static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_STR("dtype") };
P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
@@ -753,8 +753,12 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
/* ---- the latent upscaler (ref_video.cpp). `geom` is the request's volume, i32 on the device:
* (T, H, W) for conv3d_ndhwc and tconv_dw, (T, h, w, H, W) for resize_bilinear and (F, Hp, Wp)
* for patch_fold, which shares patch_unfold's parameters and operands. */
/* `stride`/`stride_t`/`causal`/`pad`/`reflect`: the video encoder's CausalConv3d forms; the
* defaults are the stride-1 `same` zero padding of everything shipped before them. */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
P_INTO("reflect") };
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
OPD_O("res"), OUT("y") };
/* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */
@@ -773,7 +777,7 @@ static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT(
/* ---- audio generation (ref_audio.cpp) */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -899,6 +903,10 @@ static const RadOpSchema kSchemas[] = {
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then "
"times `mult` (default 1) and rounded again. M, the input rows, is a multiple of k." },
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
"Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and rounded "
"to y's dtype, then times `mult` (default 1) and rounded again. n, the input width, is a "
"multiple of k." },
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0), each operand at its own row pitch." },
{ "clamp", ARR(pMnD), ARR(oClamp),
"y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." },
@@ -1463,10 +1471,15 @@ static const RadOpSchema kSchemas[] = {
"max subtracted. With `coarse` and `gate`: out = rd(rd(o) + coarse[h][tile] gate), rd the "
"output's dtype." },
{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d),
"a 3-D convolution over voxel rows [T H W, cin] -> [T H W, cout] (geom = (T, H, W)): "
"PyTorch's Conv3d weight [cout, cin, kt, k, k] and bias, stride 1, `same` zero padding (kt/2 "
"frames, k/2 rows and columns a side; k and kt odd), f32 accumulation, rd(acc + b); with `res`, "
"rd(rd(acc + b) + res), `res` possibly y itself." },
"a 3-D convolution over voxel rows of geom = (T, H, W) -> [rows out, cout]: "
"PyTorch's Conv3d weight [cout, cin, kt, k, k] and bias, f32 accumulation, rd(acc + b). "
"Defaults are stride 1 with `same` zero padding (kt/2 frames, k/2 rows and columns a side; "
"k and kt odd). `stride` (spatial) and `stride_t` > 1 pad then stride (3x3x3 only); `causal` "
"1 pads the time axis front-only with kt - 1 zeros and none behind (so one frame in gives "
"one frame out at any stride, the reference's T==1 tap truncation); `pad` `down` pads none "
"above and left and one below and right; `reflect` 1 mirrors the spatial padding (torch "
"mode `reflect`, a mirror with no repeated edge, so the padded dimension must exceed the "
"pad). With `res`, rd(rd(acc + b) + res), `res` possibly y itself." },
{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm),
"PyTorch's GroupNorm over all M rows: group g is channels [g n/groups, (g+1) n/groups), its "
"biased mean and variance in f64, rstd = 1 / sqrt(var + eps) in f32; v = (x - mean) rstd w + b, "
@@ -1492,7 +1505,9 @@ static const RadOpSchema kSchemas[] = {
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], "
"y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding "
"dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each "
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1])." },
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). bf16 only "
"with `stride` > 1: one sequence [0, rows of x], an explicit `pad` and any k, output row m "
"reading x[m * stride + tap * dil - pad] — PyTorch's zero-padded strided conv exactly." },
{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d),
"a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` "
"((k - stride) / 2 by default, 0 the causal form): each sequence of x [rows, cin] grows "
@@ -1713,6 +1728,8 @@ SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's ro
ref_seg_mean),
SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, ref_pool_rows),
SIMPLE("ref_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
"multiplier", DT_FLOAT, ref_pool_cols),
SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu),
SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp),
SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
+22 -4
View File
@@ -459,6 +459,16 @@ int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("pool_rows", operand, out);
}
int ref_pool_cols_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0), M = gi(p, n_p, "M", 0);
if (M <= 0 || n <= 0 || k <= 0 || n % k) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { M, n / k }); /* y */
return o.finish("pool_cols", operand, out);
}
int ref_relu_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
@@ -2765,19 +2775,27 @@ int ref_attn_vsa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
* REF_LANES lanes, as the image generator's are. */
static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; }
/* `M` is the input rows; with `stride` > 1 (bf16, one sequence, explicit `pad`) the output is
* PyTorch's strided length, `M` being the rows of the one sequence `cu_seqlens` must cover. */
int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0))
const int64_t st = gi(p, n_p, "stride", 1), pp = gi(p, n_p, "pad", -1);
const int64_t dil = gi(p, n_p, "dil", 1);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) ||
st < 1 || (st > 1 && (causal || pp < 0)) || (st <= 1 && pp >= 0))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const int64_t S = two_seqs(M);
if (st > 1 && D != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED;
const int64_t S = st > 1 ? 1 : two_seqs(M);
const int64_t O = st > 1 ? (M + 2 * pp - dil * (k - 1) - 1) / st + 1 : M;
if (O <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, cin }); /* x */
o.t(D, { cout, cin, k }); /* w */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, cout }); /* res */
o.t(D, { M, cout }); /* y */
o.t(D, { O, cout }); /* res */
o.t(D, { O, cout }); /* y */
o.t(D, { cout }); /* b */
return o.finish("conv1d", operand, out);
}
+52 -14
View File
@@ -346,9 +346,10 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
* `geom` carries the request's volume; an output holds at least the rows the volume writes. */
/* ------------------------------------------------------------------ conv3d_ndhwc */
/* A 3-D convolution, stride 1 with `same` zero padding: kt / 2 frames and k / 2 rows and columns
* on each side (kt and k odd). x [>= T H W, cin], y and `res` [>= T H W, cout], geom = (T, H, W);
* w is PyTorch's Conv3d weight [cout, cin, kt, k, k] and b [cout]:
/* A 3-D convolution over the volume geom = (T, H, W). The defaults are stride 1 with `same` zero
* padding: kt / 2 frames and k / 2 rows and columns on each side (kt and k odd); x
* [>= T H W, cin] and y and `res` [>= rows out, cout]; w is PyTorch's Conv3d weight
* [cout, cin, kt, k, k] and b [cout]:
*
* acc = sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw] x[(t + dt - kt/2, i + kh - k/2,
* j + kw - k/2), ci]
@@ -357,7 +358,25 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
* terms outside the volume zero. acc is f32, the taps in (dt, kh, kw) order and each tap's
* channels ascending; rd is y's dtype. With `res` the convolution's output is rounded before the
* residual is added, as a residual block's skip(x) + h adds two bf16 tensors. `res` may be y
* itself: each output element reads its own residual before its write, and no other. */
* itself: each output element reads its own residual before its write, and no other.
*
* The optional `stride` (spatial) and `stride_t` pad first and then stride, `causal` 1 takes the
* temporal padding front-only (kt - 1 zeros, none behind), `pad` `down` pads none above and left
* and one below and right, and `reflect` 1 mirrors the spatial padding instead of zeroing it;
* these CausalConv3d forms need k = kt = 3. Output (t, i, j) then reads
* x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci] over the lengths
*
* ((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
* ((W + pl + pr - k) / stride + 1) (floor divisions)
*
* with ft / bk and pt / pb / pl / pr the front / back and top / bottom / left / right pads. The
* time axis is always zero-padded; `reflect` mirrors each spatial axis once, torch's `reflect`
* (x[-n] = x[n], x[D + n] = x[D - 2 - n]), so each pad must be below the axis it pads. */
static int64_t idiv_floor(int64_t a, int64_t b) {
const int64_t q = a / b;
return (a % b && (a < 0) != (b < 0)) ? q - 1 : q;
}
int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
if (a->n_t < 6 || !have(a, 4) || !t_in(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3];
@@ -366,29 +385,48 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(geom) < 3)
return RAD_E_SHAPE;
const int64_t sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
const char* pads = p_str(a, "pad", "same");
const bool down = pads && !std::strcmp(pads, "down");
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
!(!pads || !std::strcmp(pads, "same") || down))
return RAD_E_SHAPE;
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2);
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * W, taps = kt * k * k;
if (rows_of(y, cout) < rows || rows_of(x, cin) < rows || (res && rows_of(res, cout) < rows) ||
numel(w) < cout * cin * taps || numel(b) < cout)
const int64_t ft = causal ? kt - 1 : kt / 2, bk = causal ? 0 : kt / 2;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= W)) return RAD_E_SHAPE;
const int64_t T2 = idiv_floor(T + ft + bk - kt, st) + 1;
const int64_t H2 = idiv_floor(H + pt + pb - k, sp) + 1;
const int64_t W2 = idiv_floor(W + pl + pr - k, sp) + 1;
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * W, orows = T2 * H2 * W2, taps = kt * k * k;
if (rows_of(y, cout) < orows || rows_of(x, cin) < rows ||
(res && rows_of(res, cout) < orows) || numel(w) < cout * cin * taps || numel(b) < cout)
return RAD_E_SHAPE;
const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y);
const int64_t xs = laststride(x), ys = laststride(y);
const int64_t rs = res ? laststride(res) : 0;
const uint32_t dt = y->dtype;
REF_PAR_FOR(rows * cout * cin * taps)
for (int64_t r = 0; r < rows; ++r) {
const int64_t t = r / (H * W), i = (r / W) % H, j = r % W;
REF_PAR_FOR(orows * cout * cin * taps)
for (int64_t r = 0; r < orows; ++r) {
const int64_t t = r / (H2 * W2), i = (r / W2) % H2, j = r % W2;
const int64_t yb = rowoff(y, r, cout), rb = res ? rowoff(res, r, cout) : 0;
for (int64_t o = 0; o < cout; ++o) {
float acc = 0.0f;
for (int64_t dz = 0; dz < kt; ++dz) {
const int64_t tz = t + dz - pz;
const int64_t tz = t * st + dz - ft;
if (tz < 0 || tz >= T) continue;
for (int64_t kh = 0; kh < k; ++kh) {
const int64_t iy = i + kh - ps;
int64_t iy = i * sp + kh - pt;
if (reflect) iy = iy < 0 ? -iy : (iy >= H ? 2 * H - 2 - iy : iy);
if (iy < 0 || iy >= H) continue;
for (int64_t kw = 0; kw < k; ++kw) {
const int64_t ix = j + kw - ps;
int64_t ix = j * sp + kw - pl;
if (reflect) ix = ix < 0 ? -ix : (ix >= W ? 2 * W - 2 - ix : ix);
if (ix < 0 || ix >= W) continue;
const int64_t xb = rowoff(x, (tz * H + iy) * W + ix, cin);
const int64_t wb = o * cin * taps + (dz * k + kh) * k + kw;
+23
View File
@@ -47,6 +47,17 @@ set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test)
# with -ffp-contract=off as libr4d uses, so scale conversions round identically.
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test)
# ref2va_pack_test checks the Ref2VA sequence packing (arch/minimaxh3/rad_ref2va_pack.cpp, a
# device-free TU of the plugin) against golden vectors generated from the reference implementation
# by tests/data/ref2va/gen_golden.py. It is pure host arithmetic, so like arch_test it links no
# core; nlohmann comes straight from vendor/, which core reaches the same way.
set(RAD_TESTS_WITH_PACK ref2va_pack_test)
# vae_geom_test checks the encode geometry (arch/minimaxh3/rad_vae_geom.cpp) the same way: golden
# vectors generated by running the reference VAEs' own encoders on CPU
# (tests/data/vae_geom/gen_golden.py). Also device-free, also links no core.
set(RAD_TESTS_WITH_VAE_GEOM vae_geom_test)
# Chat templates (copied from the model repositories) and media samples, passed by absolute path so
# test binaries can run from anywhere.
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
@@ -171,6 +182,18 @@ foreach(t ${RAD_TESTS})
target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS})
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d)
target_compile_options(${n} PRIVATE -ffp-contract=off)
elseif(n IN_LIST RAD_TESTS_WITH_PACK)
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_ref2va_pack.cpp)
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
${CMAKE_SOURCE_DIR}/vendor)
target_compile_definitions(${n} PRIVATE
RAD_REF2VA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/ref2va")
elseif(n IN_LIST RAD_TESTS_WITH_VAE_GEOM)
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_vae_geom.cpp)
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
${CMAKE_SOURCE_DIR}/vendor)
target_compile_definitions(${n} PRIVATE
RAD_VAE_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/vae_geom")
elseif(n IN_LIST RAD_TESTS_WHOLE_CORE)
add_executable(${n} ${t})
target_link_libraries(${n} PRIVATE stdc++ "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
+20
View File
@@ -613,6 +613,17 @@ ABI_FIELD(RadVideoGenBatch, n_frames_out)
ABI_FIELD(RadVideoGenBatch, n_samples)
ABI_FIELD(RadVideoGenBatch, geom_from)
ABI_FIELD(RadVideoGenBatch, upscale)
ABI_FIELD(RadVideoGenBatch, enc_pixels)
ABI_FIELD(RadVideoGenBatch, enc_frames)
ABI_FIELD(RadVideoGenBatch, enc_height)
ABI_FIELD(RadVideoGenBatch, enc_width)
ABI_FIELD(RadVideoGenBatch, enc_samples)
ABI_FIELD(RadVideoGenBatch, enc_n_samples)
ABI_FIELD(RadVideoGenBatch, enc_channels)
ABI_FIELD(RadVideoGenBatch, enc_slot)
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
ABI_FIELD(RadVideoGenBatch, enc_kind)
ABI_FIELD(RadVideoGenBatch, ref_tab)
ABI_STRUCT(RadVideoGenDecl)
ABI_FIELD(RadVideoGenDecl, name)
ABI_FIELD(RadVideoGenDecl, tmpl)
@@ -651,6 +662,15 @@ ABI_FIELD(RadVideoGenDecl, n_rungs)
ABI_FIELD(RadVideoGenDecl, rungs)
ABI_FIELD(RadVideoGenDecl, upscale_max)
ABI_FIELD(RadVideoGenDecl, upscale_refine)
ABI_FIELD(RadVideoGenDecl, max_ref_images)
ABI_FIELD(RadVideoGenDecl, max_ref_videos)
ABI_FIELD(RadVideoGenDecl, max_ref_audios)
ABI_FIELD(RadVideoGenDecl, encodes)
ABI_FIELD(RadVideoGenDecl, max_enc_frames)
ABI_FIELD(RadVideoGenDecl, max_enc_side)
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
ABI_FIELD(RadVideoGenDecl, enc_ratio)
ABI_FIELD(RadVideoGenDecl, ref_rows)
ABI_STRUCT(RadVideoGeom)
ABI_FIELD(RadVideoGeom, n_text)
ABI_FIELD(RadVideoGeom, frames)
+21 -3
View File
@@ -1,4 +1,4 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 21 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 23 and
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
* from the test's printout only together with a version bump. */
@@ -588,7 +588,7 @@
{ "RadTunable", "n_values", 16, 4 },
{ "RadTunable", "deflt", 24, 8 },
{ "RadTunable", "doc", 32, 8 },
{ "RadVideoGenBatch", "", 0, 192 },
{ "RadVideoGenBatch", "", 0, 248 },
{ "RadVideoGenBatch", "lane", 0, 4 },
{ "RadVideoGenBatch", "geom", 4, 24 },
{ "RadVideoGenBatch", "geom_d", 32, 8 },
@@ -610,7 +610,16 @@
{ "RadVideoGenBatch", "n_samples", 152, 8 },
{ "RadVideoGenBatch", "geom_from", 160, 24 },
{ "RadVideoGenBatch", "upscale", 184, 8 },
{ "RadVideoGenDecl", "", 0, 288 },
{ "RadVideoGenBatch", "enc_pixels", 192, 8 },
{ "RadVideoGenBatch", "enc_frames", 200, 4 },
{ "RadVideoGenBatch", "enc_height", 204, 4 },
{ "RadVideoGenBatch", "enc_width", 208, 4 },
{ "RadVideoGenBatch", "enc_samples", 216, 8 },
{ "RadVideoGenBatch", "enc_n_samples", 224, 8 },
{ "RadVideoGenBatch", "enc_channels", 232, 4 },
{ "RadVideoGenBatch", "enc_slot", 236, 4 },
{ "RadVideoGenBatch", "enc_geom_d", 240, 8 },
{ "RadVideoGenDecl", "", 0, 352 },
{ "RadVideoGenDecl", "name", 0, 8 },
{ "RadVideoGenDecl", "tmpl", 8, 8 },
{ "RadVideoGenDecl", "max_text", 16, 8 },
@@ -648,6 +657,15 @@
{ "RadVideoGenDecl", "rungs", 264, 8 },
{ "RadVideoGenDecl", "upscale_max", 272, 8 },
{ "RadVideoGenDecl", "upscale_refine", 280, 4 },
{ "RadVideoGenDecl", "max_ref_images", 288, 8 },
{ "RadVideoGenDecl", "max_ref_videos", 296, 8 },
{ "RadVideoGenDecl", "max_ref_audios", 304, 8 },
{ "RadVideoGenDecl", "encodes", 312, 4 },
{ "RadVideoGenDecl", "max_enc_frames", 320, 8 },
{ "RadVideoGenDecl", "max_enc_side", 328, 8 },
{ "RadVideoGenDecl", "max_enc_samples", 336, 8 },
{ "RadVideoGenDecl", "enc_ratio", 344, 4 },
{ "RadVideoGenDecl", "ref_rows", 348, 4 },
{ "RadVideoGeom", "", 0, 24 },
{ "RadVideoGeom", "n_text", 0, 4 },
{ "RadVideoGeom", "frames", 4, 4 },
+3 -3
View File
@@ -8,7 +8,7 @@
*
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
* the layout agrees with the table below, taken at RAD_ABI_VERSION 22 and RAD_FORMAT_VER 2. Under
* the layout agrees with the table below, taken at RAD_ABI_VERSION 23 and RAD_FORMAT_VER 2. Under
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
* headers: nothing else states the layout. When it disagrees the test prints the live table.
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 22 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 22, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 23 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 23, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
+287
View File
@@ -326,6 +326,293 @@ TEST(changed_is_refused_without_reuse_or_for_a_tensor_nothing_reads) {
}
}
/* ================================================================== --lora */
namespace {
/* A PEFT adapter file: `<module>.lora_A.weight` [r,K] of 0.25 and `<module>.lora_B.weight`
* [N,r] of 0.5 -- so B @ A is 0.25 * r everywhere -- and, when `alpha` is given, a rank-0
* `<module>.alpha` scalar. */
bool write_lora(const std::string& path, const std::string& module, int64_t N, int64_t K,
int64_t r, const float* alpha) {
std::vector<tiny::Tensor> ts;
tiny::Tensor A{ module + ".lora_A.weight", "F32", { r, K }, {} };
A.bytes.resize((size_t)(r * K) * 4);
for (int64_t i = 0; i < r * K; ++i) rad_store_f32(A.bytes.data(), RAD_F32, i, 0.25f);
tiny::Tensor B{ module + ".lora_B.weight", "F32", { N, r }, {} };
B.bytes.resize((size_t)(N * r) * 4);
for (int64_t i = 0; i < N * r; ++i) rad_store_f32(B.bytes.data(), RAD_F32, i, 0.5f);
ts.push_back(std::move(A));
ts.push_back(std::move(B));
if (alpha) {
tiny::Tensor s{ module + ".alpha", "F32", {}, std::vector<uint8_t>(4, 0) };
rad_store_f32(s.bytes.data(), RAD_F32, 0, *alpha);
ts.push_back(std::move(s));
}
return tiny::write_safetensors(path, ts);
}
/* A copy of the world's checkpoint with each named tensor raised everywhere by its delta, in
* the same f32 arithmetic add_lora does. */
bool copy_ckpt_bumped(World& w, const std::string& ck,
const std::vector<std::pair<std::string, float>>& bumps) {
if (mkdir(ck.c_str(), 0755) != 0) return false;
for (const char* f : { "config.json", "tokenizer.json" })
if (!copy_file(w.ckpt + "/" + f, ck + "/" + f)) return false;
std::vector<tiny::Tensor> ts = tiny::read_safetensors(w.ckpt + "/model.safetensors");
size_t hits = 0;
for (tiny::Tensor& t : ts)
for (const std::pair<std::string, float>& b : bumps)
if (t.name == b.first) {
++hits;
for (size_t i = 0; i < t.bytes.size() / 2; ++i)
rad_store_f32(t.bytes.data(), RAD_BF16, (int64_t)i,
rad_load_f32(t.bytes.data(), RAD_BF16, (int64_t)i) + b.second);
}
return hits == bumps.size() && tiny::write_safetensors(ck + "/model.safetensors", ts);
}
bool copy_ckpt_raised(World& w, const std::string& ck, const std::string& target, float delta) {
return copy_ckpt_bumped(w, ck, { { target, delta } });
}
} /* namespace */
/* --lora merges W + B @ A into the tensor the module names, and the merge marks that tensor
* changed: --reuse converts the weights reading it and copies the rest untouched. The merged
* container is byte-identical to one converted from a hand-raised checkpoint -- same f32
* arithmetic, same recipe. */
TEST(lora_merges_into_its_target_and_reconverts_the_weights_that_read_it) {
World& w = world();
REQUIRE(w.ok);
const std::string target = "model.layers.0.mlp.down_proj.weight";
const auto it = w.src.find(target);
REQUIRE(it != w.src.end());
REQUIRE_EQ(it->second.dtype, std::string("BF16"));
REQUIRE_EQ(it->second.shape.size(), (size_t)2);
const int64_t N = it->second.shape[0], K = it->second.shape[1];
/* PEFT names the module, without the target's `.weight`. */
const std::string mod = target.substr(0, target.size() - 7);
tiny::TempDir d("convert_l");
REQUIRE(write_lora(d / "lora.safetensors", mod, N, K, 2, nullptr));
std::string log;
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe, "--reuse", w.base,
"--lora", d / "lora.safetensors" }, &log), 0);
CHECK(has(log, "merged at strength 1"));
RadFile m;
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
RadFile base;
REQUIRE_EQ(base.open(w.base.c_str()), RAD_OK);
const std::vector<std::string> diff = differing_weights(base, m);
CHECK_EQ(diff.size(), (size_t)1);
CHECK(!diff.empty() && diff[0] == "blk.0.ffn_down.weight");
REQUIRE(copy_ckpt_raised(w, d / "ref", target, 0.5f * 0.25f * 2.f));
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
RadFile rf;
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
const RadFileEntry* a = m.find("blk.0.ffn_down.weight");
const RadFileEntry* b = rf.find("blk.0.ffn_down.weight");
REQUIRE(a && b);
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
}
/* A module spelled under a wrapper prefix resolves to the checkpoint's tensor, and an .alpha
* states the scale: alpha 4 at rank 2 doubles the merge. */
TEST(lora_strips_wrapper_prefixes_and_scales_by_alpha) {
World& w = world();
REQUIRE(w.ok);
const std::string target = "model.layers.0.mlp.down_proj.weight";
const auto it = w.src.find(target);
REQUIRE(it != w.src.end());
const int64_t N = it->second.shape[0], K = it->second.shape[1];
tiny::TempDir d("convert_lp");
const std::string mod = target.substr(0, target.size() - 7);
const float alpha = 4.f;
REQUIRE(write_lora(d / "lora.safetensors", "diffusion_model." + mod, N, K, 2, &alpha));
std::string log;
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe,
"--lora", d / "lora.safetensors" }, &log), 0);
REQUIRE(copy_ckpt_raised(w, d / "ref", target, 0.5f * 0.25f * 2.f * 2.f));
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
RadFile m, rf;
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
const RadFileEntry* a = m.find("blk.0.ffn_down.weight");
const RadFileEntry* b = rf.find("blk.0.ffn_down.weight");
REQUIRE(a && b);
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
/* And --lora-strength scales the whole merge: 0.5 of an alpha/r of 2 is a scale of 1. */
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "half.rad", "--recipe", w.recipe,
"--lora", d / "lora.safetensors", "--lora-strength", "0.5" },
nullptr), 0);
REQUIRE(copy_ckpt_raised(w, d / "ref_half", target, 0.5f * 0.25f * 2.f));
REQUIRE_EQ(convert(d / "ref_half", { "-o", d / "ref_half.rad", "--recipe", w.recipe },
nullptr), 0);
RadFile h, rh;
REQUIRE_EQ(h.open((d / "half.rad").c_str()), RAD_OK);
REQUIRE_EQ(rh.open((d / "ref_half.rad").c_str()), RAD_OK);
const RadFileEntry* c = h.find("blk.0.ffn_down.weight");
const RadFileEntry* e = rh.find("blk.0.ffn_down.weight");
REQUIRE(c && e);
CHECK(entry_bytes(h, *c) == entry_bytes(rh, *e));
}
/* A module the checkpoint does not ship is refused by name; A and B that do not fit the target
* are refused with the shapes; --lora with --in-place is refused where --changed is. */
TEST(lora_refusals_name_the_module_the_shapes_or_the_flag) {
World& w = world();
REQUIRE(w.ok);
const std::string target = "model.layers.0.mlp.down_proj.weight";
const auto it = w.src.find(target);
REQUIRE(it != w.src.end());
const int64_t N = it->second.shape[0], K = it->second.shape[1];
tiny::TempDir d("convert_lf");
std::string log;
REQUIRE(write_lora(d / "nope.safetensors", "model.layers.0.mlp.nope_proj", N, K, 2, nullptr));
CHECK(convert(w.ckpt, { "-o", d / "a.rad", "--recipe", w.recipe,
"--lora", d / "nope.safetensors" }, &log) != 0);
CHECK(has(log, "nope_proj"));
CHECK(!exists(d / "a.rad"));
{
std::vector<tiny::Tensor> ts;
const std::string mod = target.substr(0, target.size() - 7);
tiny::Tensor A{ mod + ".lora_A.weight", "F32", { 2, K + 3 }, {} };
A.bytes.assign((size_t)(2 * (K + 3)) * 4, 0);
tiny::Tensor B{ mod + ".lora_B.weight", "F32", { N + 1, 2 }, {} };
B.bytes.assign((size_t)((N + 1) * 2) * 4, 0);
ts.push_back(std::move(A));
ts.push_back(std::move(B));
REQUIRE(tiny::write_safetensors(d / "bad.safetensors", ts));
}
CHECK(convert(w.ckpt, { "-o", d / "b.rad", "--recipe", w.recipe,
"--lora", d / "bad.safetensors" }, &log) != 0);
CHECK(has(log, "does not fit"));
CHECK(!exists(d / "b.rad"));
CHECK(convert(w.ckpt, { "--recipe", w.recipe, "--reuse", w.base, "--in-place",
"--lora", d / "nope.safetensors" }, &log) != 0);
CHECK(has(log, "--lora merges into the source"));
}
/* A --lora-map rule lands one fused module on several checkpoint tensors: B's rows split
* along the targets in the order listed, each taking its own row count, and every target
* joins the changed set. */
TEST(lora_map_fuses_one_module_into_several_targets_by_row_window) {
World& w = world();
REQUIRE(w.ok);
const std::string q = "model.layers.0.self_attn.q_proj.weight";
const std::string k = "model.layers.0.self_attn.k_proj.weight";
const std::string v = "model.layers.0.self_attn.v_proj.weight";
const auto qq = w.src.find(q), qk = w.src.find(k), qv = w.src.find(v);
REQUIRE(qq != w.src.end() && qk != w.src.end() && qv != w.src.end());
const int64_t Nq = qq->second.shape[0], Nk = qk->second.shape[0], Nv = qv->second.shape[0],
K = qq->second.shape[1];
REQUIRE(qk->second.shape[1] == K && qv->second.shape[1] == K);
REQUIRE(Nq != Nk); /* an asymmetric split can only come from the targets' own row counts */
tiny::TempDir d("convert_lm");
REQUIRE(tiny::write_text(d / "map.json",
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
"model.layers.*.self_attn.q_proj.weight",
"model.layers.*.self_attn.k_proj.weight",
"model.layers.*.self_attn.v_proj.weight"]}})"));
/* A [2,K] of 0.25; B's three windows read 0.5, 1.0 and 2.0 -- so with no .alpha the
* merge must raise q, k and v by 0.25, 0.5 and 1.0 (r * b * 0.25 each). No other
* attribution of B's rows -- one size for all, or the windows in another order --
* produces those three deltas on those three tensors. */
const int64_t r = 2, N = Nq + Nk + Nv;
std::vector<tiny::Tensor> ts;
tiny::Tensor A{ "diffusion_model.layers.0.attn.qkv.lora_A.weight", "F32", { r, K }, {} };
A.bytes.resize((size_t)(r * K) * 4);
for (int64_t i = 0; i < r * K; ++i) rad_store_f32(A.bytes.data(), RAD_F32, i, 0.25f);
tiny::Tensor B{ "diffusion_model.layers.0.attn.qkv.lora_B.weight", "F32", { N, r }, {} };
B.bytes.resize((size_t)(N * r) * 4);
for (int64_t n = 0; n < N; ++n) {
const float b = n < Nq ? 0.5f : n < Nq + Nk ? 1.0f : 2.0f;
for (int64_t j = 0; j < r; ++j) rad_store_f32(B.bytes.data(), RAD_F32, n * r + j, b);
}
ts.push_back(std::move(A));
ts.push_back(std::move(B));
REQUIRE(tiny::write_safetensors(d / "qkv.safetensors", ts));
std::string log;
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "merged.rad", "--recipe", w.recipe, "--reuse", w.base,
"--lora", d / "qkv.safetensors", "--lora-map", d / "map.json" },
&log), 0);
CHECK(has(log, "merged at strength 1"));
RadFile m, base;
REQUIRE_EQ(m.open((d / "merged.rad").c_str()), RAD_OK);
REQUIRE_EQ(base.open(w.base.c_str()), RAD_OK);
const std::vector<std::string> diff = differing_weights(base, m);
CHECK_EQ(diff.size(), (size_t)1); /* all three merged, and only the weight reading them */
CHECK(!diff.empty() && diff[0] == "blk.0.attn_qkv.weight");
REQUIRE(copy_ckpt_bumped(w, d / "ref", { { q, 0.25f }, { k, 0.5f }, { v, 1.0f } }));
REQUIRE_EQ(convert(d / "ref", { "-o", d / "ref.rad", "--recipe", w.recipe }, nullptr), 0);
RadFile rf;
REQUIRE_EQ(rf.open((d / "ref.rad").c_str()), RAD_OK);
const RadFileEntry* a = m.find("blk.0.attn_qkv.weight");
const RadFileEntry* b = rf.find("blk.0.attn_qkv.weight");
REQUIRE(a && b);
CHECK(entry_bytes(m, *a) == entry_bytes(rf, *b));
}
/* A rule whose target the checkpoint lacks is a refusal, not a miss; a B whose rows do not
* sum to its targets' rows is a refusal; --lora-map without --lora is a refusal. */
TEST(lora_map_refusals_name_the_target_the_sums_or_the_flag) {
World& w = world();
REQUIRE(w.ok);
const int64_t Nq = w.src["model.layers.0.self_attn.q_proj.weight"].shape[0];
const int64_t Nk = w.src["model.layers.0.self_attn.k_proj.weight"].shape[0];
const int64_t K = w.src["model.layers.0.self_attn.q_proj.weight"].shape[1];
tiny::TempDir d("convert_lmr");
/* One pair of the fused module's name, B of any row count. */
const std::string mod = "diffusion_model.layers.0.attn.qkv";
const auto pair = [&](int64_t rows) {
std::vector<tiny::Tensor> ts;
tiny::Tensor A{ mod + ".lora_A.weight", "F32", { 2, K }, {} };
A.bytes.assign((size_t)(2 * K) * 4, 0);
tiny::Tensor B{ mod + ".lora_B.weight", "F32", { rows, 2 }, {} };
B.bytes.assign((size_t)(rows * 2) * 4, 0);
ts.push_back(std::move(A));
ts.push_back(std::move(B));
return tiny::write_safetensors(d / "p.safetensors", ts);
};
std::string log;
REQUIRE(tiny::write_text(d / "ghost.json",
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
"model.layers.*.self_attn.q_proj.weight",
"model.layers.*.self_attn.ghost_proj.weight"]}})"));
REQUIRE(pair(Nq + Nk));
CHECK(convert(w.ckpt, { "-o", d / "a.rad", "--recipe", w.recipe, "--lora", d / "p.safetensors",
"--lora-map", d / "ghost.json" }, &log) != 0);
CHECK(has(log, "ghost_proj"));
CHECK(has(log, "does not ship"));
CHECK(!exists(d / "a.rad"));
REQUIRE(tiny::write_text(d / "ok.json",
R"({"strip": ["diffusion_model."], "modules": {"layers.*.attn.qkv": [
"model.layers.*.self_attn.q_proj.weight",
"model.layers.*.self_attn.k_proj.weight"]}})"));
REQUIRE(pair(Nq + Nk + 1)); /* one row past the two targets */
CHECK(convert(w.ckpt, { "-o", d / "b.rad", "--recipe", w.recipe, "--lora", d / "p.safetensors",
"--lora-map", d / "ok.json" }, &log) != 0);
CHECK(has(log, "rows sum to"));
CHECK(!exists(d / "b.rad"));
CHECK(convert(w.ckpt, { "-o", d / "c.rad", "--recipe", w.recipe,
"--lora-map", d / "ok.json" }, &log) != 0);
CHECK(has(log, "--lora-map renames"));
CHECK(!exists(d / "c.rad"));
}
/* ================================================================== --in-place */
/* Extending a container with nothing new keeps every weight at its offset, and the .pre-append
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Regenerate golden.json -- the reference numbers arch/minimaxh3/rad_ref2va_pack.cpp is tested
against (tests/ref2va_pack_test.cpp).
gen_golden.py /path/to/ComfyUI/comfy/ldm/minimax/model.py [out.json]
The reference implementation lives in the ComfyUI tree; importing its package pulls the whole
device stack, so this extracts exactly the layout's source -- the four constants, the grid helpers
and the PackedLayout class -- with `ast`, execs them on torch alone, and runs the cases below.
Nothing here is a re-derivation: every number in golden.json is computed by the reference code
itself, at float64, from the file you point it at. If a radiance bump changes golden.json, the port
must change with it.
The `mod` entries are NOT produced by the reference class (its _forward folds them into per-row
mask tensors); they are the reference's segment-level rule -- the seg_tag table and the
{stream, pin} timestep labels transcribed from _forward -- applied to self.segments here, which is
the arithmetic the port replicates (sorted distinct labels, collapse on equality, t_row * 3 + tag).
"""
import ast
import json
import sys
NEED = ["_axis_from_sqrt_area", "_frame_grid", "_video_t_spans", "_video_t_grid", "_ref_t_span",
"_audio_grid", "_video_grid", "PackedLayout"]
NEED_ASSIGN = ["FRAME_PER_TOKEN", "FRAME_RESCALE", "VISUAL_COND_TIMESTEP", "AUDIO_COND_TIMESTEP"]
def extract(path):
"""The reference's layout source, exec'd with torch/math only."""
import math
import torch
with open(path) as f:
src = f.read()
tree = ast.parse(src)
picked, got = [], set()
for node in tree.body:
names = ([t.id for t in node.targets if isinstance(t, ast.Name)]
if isinstance(node, ast.Assign) else
[node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef)) else [])
if any(n in NEED or n in NEED_ASSIGN for n in names):
picked.append(ast.get_source_segment(src, node))
got.update(names)
missing = (set(NEED) | set(NEED_ASSIGN)) - got
if missing:
sys.exit(f"{path} does not define: {sorted(missing)} -- reference moved?")
ns = {"math": math, "torch": torch}
exec("\n\n".join(picked), ns)
return ns
# The reference _forward's per-kind (timestep label, modality tag), transcribed.
SEG_TAG = {"text": 1, "video": 0, "audio": 2, "cond": 0, "ref_img": 0, "cond_audio": 2,
"ref_audio": 2}
def t_label(kind, t_v, t_a):
if kind in ("cond", "ref_img"):
return max(t_v, 0.999)
if kind in ("cond_audio", "ref_audio"):
return max(t_a, 1.0)
if kind == "audio":
return t_a
return t_v
def mod_rows(layout, t_v, t_a):
# non-empty segments only: the reference derives labels from mask TENSORS, so a zero-row
# segment contributes no rows to the distinct-label set. An empty segment's own row index has
# no defined value -- 0 by convention, matching the port.
uniq = sorted({t_label(k, t_v, t_a) for (s, e, k) in layout.segments if e > s})
return [uniq.index(t_label(k, t_v, t_a)) * 3 + SEG_TAG[k] if e > s else 0
for (s, e, k) in layout.segments]
CASES = {
# plain t2va: the pack must reproduce the old three-segment shape exactly
"t2va": dict(text_len=5, target=(3, 8, 10, 4), keyframes=[], refs=[]),
# fl2va keyframes at frame 0 (shares the target origin) and mid-timeline, video-only and both
"fl2va": dict(text_len=4, target=(3, 8, 8, 3),
keyframes=[dict(frame=0, video_t=1, audio_t=2), dict(frame=7, video_t=2, audio_t=0)],
refs=[]),
# every reference kind in one request: a photo, a standalone soundtrack, a silent clip, and a
# clip with sound (its audio packs before its video, at the clip's own width extremes); a
# second photo after them; audio_t=0 targets the silent-video edge
"ref2va_all": dict(text_len=6, target=(2, 8, 8, 0),
keyframes=[],
refs=[dict(kind="image", latent_h=6, latent_w=10, latent_t=0, ref_audio_t=0),
dict(kind="audio", latent_h=0, latent_w=0, latent_t=0, ref_audio_t=3),
dict(kind="video", latent_h=4, latent_w=6, latent_t=2, ref_audio_t=0),
dict(kind="video_audio", latent_h=5, latent_w=7, latent_t=3,
ref_audio_t=4),
dict(kind="image", latent_h=4, latent_w=4, latent_t=0, ref_audio_t=0)]),
# a realistic signature: keyframes + a big photo + a clip with sound, real-ish sizes
"chain": dict(text_len=32, target=(7, 16, 24, 6),
keyframes=[dict(frame=0, video_t=1, audio_t=2)],
refs=[dict(kind="image", latent_h=8, latent_w=12, latent_t=0, ref_audio_t=0),
dict(kind="video_audio", latent_h=4, latent_w=6, latent_t=5,
ref_audio_t=20)]),
# degenerate prompt: text_len 0, nothing but targets
"no_text": dict(text_len=0, target=(2, 4, 6, 1), keyframes=[], refs=[]),
}
# (t_v, t_a) probes: apart (four distinct labels), and past both pins (every label collapses to
# two, and cond/ref share the video row, cond_audio/ref_audio the audio row)
SIGMAS = [(0.5, 0.45), (0.9995, 0.999), (0.2, 0.15)]
def main():
import torch
model_py = sys.argv[1]
out = sys.argv[2] if len(sys.argv) > 2 else "golden.json"
ns = extract(model_py)
PackedLayout = ns["PackedLayout"]
golden = {}
for name, c in CASES.items():
t, ah, aw, at = c["target"]
refs = [dict(kind=r["kind"], latent_h=r["latent_h"], latent_w=r["latent_w"],
latent_t=r["latent_t"], ref_audio_t=r["ref_audio_t"]) for r in c["refs"]]
# the class reads only the latents' shapes (video .shape[2], audio .shape[-1]); zeros do
kfs = [dict(resolved_frame_index=k["frame"],
latent=torch.zeros(1, 24, k["video_t"], ah, aw) if k["video_t"] else None,
audio_latent=torch.zeros(1, 32, 2, k["audio_t"]) if k["audio_t"] else None)
for k in c["keyframes"]]
lay = PackedLayout(c["text_len"], t, ah, aw, at, keyframes=kfs or None, refs=refs or None)
golden[name] = {
"text_len": c["text_len"], "latent_t": t, "latent_h": ah, "latent_w": aw,
"audio_t": at,
"keyframes": c["keyframes"], "refs": c["refs"],
"seq_len": lay.seq_len,
"segments": [[s, e, k] for (s, e, k) in lay.segments],
"positions": [[float(x) for x in row] for row in lay.position_ids.tolist()],
"img_update": [bool(b) for b in lay.img_update.tolist()],
"audio_update": [bool(b) for b in lay.audio_update.tolist()],
"img_pos": [int(i) for i in lay.img_pos.tolist()],
"audio_pos": [int(i) for i in lay.audio_pos.tolist()],
"mod": [dict(t_v=tv, t_a=ta, rows=mod_rows(lay, tv, ta)) for tv, ta in SIGMAS],
}
with open(out, "w") as f:
json.dump(golden, f, indent=1)
print(f"{out}: " + ", ".join(f"{n} {g['seq_len']} rows" for n, g in golden.items()))
main()
File diff suppressed because it is too large. Load diff
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Generate tests/data/vae_geom/golden.json from the REFERENCE VAEs themselves.
Same discipline as tests/data/ref2va/gen_golden.py: the module source is AST-parsed and only the
needed classes/helpers are extracted and exec'd on torch alone -- importing the comfy package
dies on this machine (aiter JIT build failure). Unlike the pack golden this one runs real CPU
networks, so expectations are the encoders' own output shapes:
* the video encoder (EncoderFCN3D with the reference's exact constructor arguments) + the
reference's own encode()/encode_temporal()/split_tiles()/tiled_encode() methods bound to a
shim self -> latent counts, per-axis tile plans, and blended tile-grid shapes;
* the audio DAC encoder -> latent frames for a sweep of sample counts (its posterior head,
AttnProjection + 1x1 mean_proj, applies no strided op, so it cannot change the frame count;
NOTE-P2-ENCODE.md makes that argument explicitly).
Only shims: comfy.quant_ops must exist without `ck` (the fused-pad fast path then self-disables
and the CPU path is the plain torch one), and Conv3d must accept the reference's autopad kwarg --
on CPU the only use is the single-frame causal case ("causal_zero" = implicit front zero pad of
kernel_t - 1, which is what physically skipping the pad means for a causal conv).
Usage: python gen_golden.py <ComfyUI>/comfy/ldm/minimax/vae.py <...>/audio_vae.py golden.json
"""
import ast
import json
import math
import sys
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
# ----------------------------------------------------------------------------- shims
class _Ops:
class Conv3d(nn.Conv3d):
def forward(self, x, autopad=None, **kw):
if autopad == "causal_zero":
k = self.kernel_size[0]
x = F.pad(x, (0, 0, 0, 0, k - 1, 0))
return super().forward(x)
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
GroupNorm = nn.GroupNorm
LayerNorm = nn.LayerNorm
Linear = nn.Linear
class _QuantOps:
pass
def _cast_to_input(w, x):
return w.to(device=x.device, dtype=x.dtype)
class _ComfyOpsNs:
"""what the extracted code reaches for as bare `comfy.ops.*`: cast_to_input is the real
semantics (a plain device/dtype cast); the kitchen fast paths are never reached on CPU, so
placeholders are enough there"""
cast_bias_weight = None
uncast_bias_weight = None
cast_to_input = staticmethod(_cast_to_input)
comfy = types.ModuleType("comfy")
comfy.quant_ops = _QuantOps()
comfy.ops = _ComfyOpsNs()
ops = _Ops
# --------------------------------------------------------------------------- extract
def top_level(path, names):
src = open(path).read()
tree = ast.parse(src)
out = {}
for node in tree.body:
key = getattr(node, "name", None)
if key is None and isinstance(node, ast.Assign):
key = [t.id for t in node.targets if isinstance(t, ast.Name)]
else:
key = [key]
for k in key:
if k in names:
out[k] = ast.get_source_segment(src, node)
missing = set(names) - set(out)
if missing:
raise SystemExit(f"not found in {path}: {sorted(missing)}")
return out
def class_methods(path, cls_name, method_names):
src = open(path).read()
tree = ast.parse(src)
for node in tree.body:
if isinstance(node, ast.ClassDef) and node.name == cls_name:
found = {m.name: ast.get_source_segment(src, m) for m in node.body
if isinstance(m, ast.FunctionDef) and m.name in method_names}
missing = set(method_names) - set(found)
if missing:
raise SystemExit(f"{cls_name} methods not found: {sorted(missing)}")
return found
raise SystemExit(f"class {cls_name} not found in {path}")
ns = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
# --- video: the encoder chain classes + module constants
VIDEO_NEED = [
"IMAGENET_MEAN", "IMAGENET_STD", "LATENTS_MEAN", "LATENTS_STD",
"_kitchen_ndhwc", "_fused_norm_pad", "_fp16_accum_conv",
"CausalConv3d", "TemporalIsolatedGroupNorm", "group_norm_3d",
"Downsample3D", "ResnetBlock3D", "EncoderFCN3D",
]
_vsrc = top_level(sys.argv[1], VIDEO_NEED)
for name in VIDEO_NEED:
exec(_vsrc[name], ns)
# --- video: the wrapper methods, bound to a shim self (no decoder, no checkpoint)
VIDEO_METHODS = ["_encode_moments", "_normalize_pixels", "split_tiles", "blend",
"tiled_encode", "_adaptive_encode", "encode_temporal", "encode"]
mns = dict(ns)
for name, code in class_methods(sys.argv[1], "MiniMaxH3VideoVAE", VIDEO_METHODS).items():
exec(code, mns)
def make_video_vae():
self = types.SimpleNamespace()
self.vae_ratio = 16
self.vae_ratio_t = 8
self.clip_length = 17
self.token_drop = 3
self.tile_size = 256
self.tile_overlap_min = 64
self.tiling = True
self.encoder = ns["EncoderFCN3D"](
ch=128, ch_mult=[1, 2, 2, 4, 4, 8], space_down=[2, 2, 2, 2, 1, 1],
time_down=[1, 2, 2, 1, 1, 1], num_res_blocks=2, in_channels=3, z_channels=24,
double_z=True)
self.quant_conv = nn.Conv3d(48, 48, 1)
self.latents_mean = torch.tensor(ns["LATENTS_MEAN"])
self.latents_std = torch.tensor(ns["LATENTS_STD"])
self.pixel_mean = torch.tensor(ns["IMAGENET_MEAN"]).view(1, 3, 1, 1, 1)
self.pixel_std = torch.tensor(ns["IMAGENET_STD"]).view(1, 3, 1, 1, 1)
for name in VIDEO_METHODS:
setattr(self, name, types.MethodType(mns[name], self))
return self
golden = {"video": {}, "audio": {}}
golden["video"]["constants"] = {
"latents_mean": list(ns["LATENTS_MEAN"]), "latents_std": list(ns["LATENTS_STD"]),
"pixel_mean": list(ns["IMAGENET_MEAN"]), "pixel_std": list(ns["IMAGENET_STD"]),
}
vae = make_video_vae()
# --- 1. latent count per frame count, from the reference encode() end to end
FRAME_COUNTS = [1, 2, 3, 5, 8, 16, 17, 18, 22, 34, 39, 40, 56, 72, 73, 90]
cases = []
with torch.no_grad():
for t in FRAME_COUNTS:
x = torch.zeros(1, 3, t, 32, 32)
z = vae.encode(x)
cases.append({"T": t, "z_shape": list(z.shape)})
print(f"video encode T={t:3d} -> z {list(z.shape)}", file=sys.stderr)
golden["video"]["encode"] = cases
# --- 2. split_tiles raw output (the pure arithmetic, exact reference return values)
TILE_LENS = [1, 16, 64, 128, 255, 256, 257, 272, 320, 448, 512, 640, 720, 768, 1024, 1088, 1344, 2048]
golden["video"]["split_tiles"] = [
{"input_len": L, "starts": starts, "lens": lens, "overlaps": ovl}
for L in TILE_LENS
for starts, lens, ovl in [vae.split_tiles(L)]
]
# --- 3. the tile grid end to end: the blend/cut keeps the moments at exactly ratio-reduced size
with torch.no_grad():
tiled = []
for x_shape in [(1, 3, 5, 320, 320), (1, 3, 2, 512, 256), (1, 3, 17, 288, 192)]:
moments = vae.tiled_encode(torch.zeros(*x_shape))
tiled.append({"x_shape": list(x_shape), "moments_shape": list(moments.shape)})
print(f"video tiled {list(x_shape)} -> moments {list(moments.shape)}", file=sys.stderr)
golden["video"]["tiled_encode"] = tiled
# --- 4. audio DAC encoder: latent frames for a sweep of (padded) sample counts
AUDIO_NEED = ["snake", "Snake1d", "ResidualUnit", "EncoderBlock", "Encoder"]
ans = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
for name in AUDIO_NEED:
exec(top_level(sys.argv[2], [name])[name], ans)
with torch.no_grad():
enc = ans["Encoder"](64, (2, 4, 4, 5, 5), 2048)
samples_cases = []
for s in [1, 2, 400, 799, 800, 801, 1599, 1600, 1601, 4000, 32000, 32001, 96000]:
hop = 800
padded = math.ceil(s / hop) * hop
out = enc(torch.zeros(2, 1, padded)) # b*s = 2 stereo streams, mono encoder
samples_cases.append({"samples": s, "padded": padded, "T": out.shape[2]})
print(f"audio encode {s:6d} (pad {padded}) -> T {out.shape[2]}", file=sys.stderr)
golden["audio"]["latents"] = samples_cases
json.dump(golden, open(sys.argv[3], "w"), indent=1)
print(f"wrote {sys.argv[3]}", file=sys.stderr)
+660
View File
@@ -0,0 +1,660 @@
{
"video": {
"constants": {
"latents_mean": [
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
],
"latents_std": [
1.2223774194717407,
1.2767263650894165,
1.6831774711608887,
1.7549455165863037,
1.5636216402053833,
2.194143533706665,
0.9653137922286987,
1.0569885969161987,
0.841948926448822,
0.7729952931404114,
1.8955937623977661,
0.946841835975647,
0.7996809482574463,
0.44988900423049927,
0.7197399735450745,
0.6936293244361877,
2.961095094680786,
2.7694199085235596,
3.0496184825897217,
2.1088054180145264,
3.276226282119751,
3.1627357006073,
2.2816812992095947,
2.6127843856811523
],
"pixel_mean": [
0.485,
0.456,
0.406
],
"pixel_std": [
0.229,
0.224,
0.225
]
},
"encode": [
{
"T": 1,
"z_shape": [
1,
24,
1,
2,
2
]
},
{
"T": 2,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 3,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 5,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 8,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 16,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 17,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 18,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 22,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 34,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 39,
"z_shape": [
1,
24,
12,
2,
2
]
},
{
"T": 40,
"z_shape": [
1,
24,
12,
2,
2
]
},
{
"T": 56,
"z_shape": [
1,
24,
17,
2,
2
]
},
{
"T": 72,
"z_shape": [
1,
24,
22,
2,
2
]
},
{
"T": 73,
"z_shape": [
1,
24,
22,
2,
2
]
},
{
"T": 90,
"z_shape": [
1,
24,
27,
2,
2
]
}
],
"split_tiles": [
{
"input_len": 1,
"starts": [
0
],
"lens": [
1
],
"overlaps": []
},
{
"input_len": 16,
"starts": [
0
],
"lens": [
16
],
"overlaps": []
},
{
"input_len": 64,
"starts": [
0
],
"lens": [
64
],
"overlaps": []
},
{
"input_len": 128,
"starts": [
0
],
"lens": [
128
],
"overlaps": []
},
{
"input_len": 255,
"starts": [
0
],
"lens": [
255
],
"overlaps": []
},
{
"input_len": 256,
"starts": [
0
],
"lens": [
256
],
"overlaps": []
},
{
"input_len": 257,
"starts": [
0,
16
],
"lens": [
256,
256
],
"overlaps": [
240
]
},
{
"input_len": 272,
"starts": [
0,
16
],
"lens": [
256,
256
],
"overlaps": [
240
]
},
{
"input_len": 320,
"starts": [
0,
64
],
"lens": [
256,
256
],
"overlaps": [
192
]
},
{
"input_len": 448,
"starts": [
0,
192
],
"lens": [
256,
256
],
"overlaps": [
64
]
},
{
"input_len": 512,
"starts": [
0,
128,
256
],
"lens": [
256,
256,
256
],
"overlaps": [
128,
128
]
},
{
"input_len": 640,
"starts": [
0,
192,
384
],
"lens": [
256,
256,
256
],
"overlaps": [
64,
64
]
},
{
"input_len": 720,
"starts": [
0,
144,
304,
464
],
"lens": [
256,
256,
256,
256
],
"overlaps": [
112,
96,
96
]
},
{
"input_len": 768,
"starts": [
0,
160,
336,
512
],
"lens": [
256,
256,
256,
256
],
"overlaps": [
96,
80,
80
]
},
{
"input_len": 1024,
"starts": [
0,
192,
384,
576,
768
],
"lens": [
256,
256,
256,
256,
256
],
"overlaps": [
64,
64,
64,
64
]
},
{
"input_len": 1088,
"starts": [
0,
160,
320,
480,
656,
832
],
"lens": [
256,
256,
256,
256,
256,
256
],
"overlaps": [
96,
96,
96,
80,
80
]
},
{
"input_len": 1344,
"starts": [
0,
176,
352,
528,
704,
896,
1088
],
"lens": [
256,
256,
256,
256,
256,
256,
256
],
"overlaps": [
80,
80,
80,
80,
64,
64
]
},
{
"input_len": 2048,
"starts": [
0,
176,
352,
528,
704,
880,
1056,
1232,
1408,
1600,
1792
],
"lens": [
256,
256,
256,
256,
256,
256,
256,
256,
256,
256,
256
],
"overlaps": [
80,
80,
80,
80,
80,
80,
80,
80,
64,
64
]
}
],
"tiled_encode": [
{
"x_shape": [
1,
3,
5,
320,
320
],
"moments_shape": [
1,
48,
2,
20,
20
]
},
{
"x_shape": [
1,
3,
2,
512,
256
],
"moments_shape": [
1,
48,
1,
32,
16
]
},
{
"x_shape": [
1,
3,
17,
288,
192
],
"moments_shape": [
1,
48,
5,
18,
12
]
}
]
},
"audio": {
"latents": [
{
"samples": 1,
"padded": 800,
"T": 1
},
{
"samples": 2,
"padded": 800,
"T": 1
},
{
"samples": 400,
"padded": 800,
"T": 1
},
{
"samples": 799,
"padded": 800,
"T": 1
},
{
"samples": 800,
"padded": 800,
"T": 1
},
{
"samples": 801,
"padded": 1600,
"T": 2
},
{
"samples": 1599,
"padded": 1600,
"T": 2
},
{
"samples": 1600,
"padded": 1600,
"T": 2
},
{
"samples": 1601,
"padded": 2400,
"T": 3
},
{
"samples": 4000,
"padded": 4000,
"T": 5
},
{
"samples": 32000,
"padded": 32000,
"T": 40
},
{
"samples": 32001,
"padded": 32800,
"T": 41
},
{
"samples": 96000,
"padded": 96000,
"T": 120
}
]
}
}
+265
View File
@@ -0,0 +1,265 @@
/* ref2va_pack_test.cpp -- the Ref2VA packing against golden vectors produced by the reference
* implementation itself.
*
* arch/minimaxh3/rad_ref2va_pack.cpp is pure host arithmetic, so it is compiled straight in here --
* no rad_core, no device. tests/data/ref2va/golden.json is generated by gen_golden.py, which runs
* the reference PackedLayout (from the MiniMax-H3 model file of a ComfyUI install) over the cases;
* every expectation below is the reference's own output, not a re-derivation. The positions are
* compared after a float64 -> float cast, bit for bit: both sides run the same IEEE double
* operations, so an exact match is the contract -- a ULP drift would mean the port reordered the
* arithmetic.
*/
#include "rad_test.h"
#include "rad_ref2va_pack.h"
#include <nlohmann/json.hpp>
#include <fstream>
#include <string>
using namespace minimaxh3;
namespace {
nlohmann::json& golden() {
static nlohmann::json g = [] {
std::ifstream f(std::string(RAD_REF2VA_GOLDEN) + "/golden.json");
if (!f.is_open()) {
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
"tests/data/ref2va/gen_golden.py\n");
std::exit(1);
}
return nlohmann::json::parse(f);
}();
return g;
}
int ref_kind(const std::string& s) {
if (s == "image") return kR2VRefImage;
if (s == "audio") return kR2VRefAudioOnly;
if (s == "video") return kR2VRefVideo;
if (s == "video_audio") return kR2VRefVideoAudio;
return -1;
}
/* The pack `name`'s case asks for, built. */
Ref2VAPack build_case(const nlohmann::json& c) {
Ref2VAGeom g{ c["latent_t"], c["latent_h"], c["latent_w"], c["audio_t"] };
std::vector<Ref2VAKeyframe> kfs;
for (const auto& k : c["keyframes"])
kfs.push_back({ k["frame"], k["video_t"], k["audio_t"] });
std::vector<Ref2VARef> refs;
for (const auto& r : c["refs"])
refs.push_back({ ref_kind(r["kind"].get<std::string>()), r["latent_h"], r["latent_w"],
r["latent_t"], r["ref_audio_t"] });
Ref2VAPack p;
CHECK_EQ(ref2va_build(c["text_len"], g, kfs, refs, &p), 0);
return p;
}
void check_case(const std::string& name) {
const nlohmann::json& c = golden()[name];
const Ref2VAPack p = build_case(c);
CHECK_EQ(p.rows, c["seq_len"].get<int64_t>());
CHECK_EQ((int64_t)p.pos.size(), p.rows * 3);
const auto& segs = c["segments"];
CHECK_EQ(p.segs.size(), segs.size());
for (size_t i = 0; i < p.segs.size() && i < segs.size(); ++i) {
CHECK_EQ(p.segs[i].start, segs[i][0].get<int64_t>());
CHECK_EQ(p.segs[i].end, segs[i][1].get<int64_t>());
CHECK(std::string(ref2va_kind_name(p.segs[i].kind)) == segs[i][2].get<std::string>());
const std::string kind = segs[i][2].get<std::string>();
CHECK_EQ(p.segs[i].update, kind == "audio" || kind == "video" ? 1 : 0);
}
/* Positions, bit for bit after the float cast: a coordinate drawn a different way in double
* can round to the same f32 and still bend a rotary the next latent over. */
const auto& gp = c["positions"];
for (size_t i = 0; i < gp.size(); ++i)
for (int j = 0; j < 3; ++j) {
const float want = (float)gp[i][j].get<double>();
if (p.pos[(int64_t)j * p.rows + i] != want) {
::radtest::fail(__FILE__, __LINE__,
std::string(name) + ": row " + std::to_string(i) + " axis "
+ std::to_string(j) + " is "
+ std::to_string(p.pos[(int64_t)j * p.rows + i])
+ ", want " + std::to_string(want));
return;
}
}
/* The two latent spaces' row index lists and their update flags, rebuilt from the pack's
* segments the way the sampler scatters them, against the reference's concatenated lists. */
std::vector<int64_t> img_pos, audio_pos;
std::vector<int> img_up, audio_up;
for (const Ref2VASeg& s : p.segs) {
for (int64_t r = s.start; r < s.end; ++r) {
if (ref2va_is_img(s.kind)) { img_pos.push_back(r); img_up.push_back(s.update); }
if (ref2va_is_audio(s.kind)) { audio_pos.push_back(r); audio_up.push_back(s.update); }
}
}
CHECK(img_pos == c["img_pos"].get<std::vector<int64_t>>());
CHECK(audio_pos == c["audio_pos"].get<std::vector<int64_t>>());
std::vector<int> giu, gau;
for (const auto& b : c["img_update"]) giu.push_back(b.get<int>());
for (const auto& b : c["audio_update"]) gau.push_back(b.get<int>());
CHECK(img_up == giu);
CHECK(audio_up == gau);
/* Modulation rows at probe timesteps -- including the probes past both pins, where the pins
* collapse onto the streams' own labels and the row numbering must collapse with them. */
for (const auto& m : c["mod"]) {
std::vector<int> rows;
CHECK_EQ(ref2va_mod_rows(p, m["t_v"].get<double>(), m["t_a"].get<double>(), &rows), 0);
CHECK(rows == m["rows"].get<std::vector<int>>());
/* The same cells as step_ada will fill them: (md, trow). md must equal the reference
* encoding's tag (its row's low digits), and the timestep row the cell reads must carry
* exactly the label ref2va_mod_rows compacted -- i.e. the schedule row when the reference
* label IS the stream's current timestep, and a pin otherwise. Checked pin-value-free. */
std::vector<int> md, trow;
ref2va_ada_cell(p, m["t_v"].get<double>(), m["t_a"].get<double>(), &md, &trow);
CHECK_EQ(md.size(), p.segs.size());
for (size_t i = 0; i < p.segs.size(); ++i) {
CHECK_EQ(md[i], rows[i] % 3); /* the modality column agrees */
if (p.segs[i].end <= p.segs[i].start) continue; /* empty cell, never read */
const double tv = m["t_v"].get<double>(), ta = m["t_a"].get<double>();
const double lbl = ref2va_t_label(p.segs[i].kind, tv, ta);
/* The modality picks the schedule row; the label decides schedule vs pin -- decided
* by modality, not by the bare label, so it holds even if a probe sets tv == ta. */
if (md[i] == 2) CHECK_EQ(trow[i], (lbl == ta) ? kR2VTAudio : kR2VTPinAudio);
else CHECK_EQ(trow[i], (lbl == tv) ? kR2VTVideo : kR2VTPinVideo);
}
}
}
} /* namespace */
TEST(pack_golden_t2va) { check_case("t2va"); }
TEST(pack_golden_fl2va) { check_case("fl2va"); }
TEST(pack_golden_ref2va_all) { check_case("ref2va_all"); }
TEST(pack_golden_chain) { check_case("chain"); }
TEST(pack_golden_no_text) { check_case("no_text"); }
TEST(pack_rejects_negative_dims) {
Ref2VAPack p;
Ref2VAGeom g{ 2, 4, 4, 1 };
CHECK_EQ(ref2va_build(-1, g, {}, {}, &p), -1);
CHECK_EQ(ref2va_build(0, Ref2VAGeom{ -1, 4, 4, 1 }, {}, {}, &p), -1);
CHECK_EQ(ref2va_build(0, g, { { -1, 1, 0 } }, {}, &p), -1);
CHECK_EQ(ref2va_build(0, g, {}, { { kR2VRefImage, -4, 4, 0, 0 } }, &p), -1);
CHECK_EQ(ref2va_build(0, g, {}, { { 7, 4, 4, 0, 0 } }, &p), -1);
}
TEST(pack_plain_matches_the_three_segment_order) {
/* With no references the pack must reduce to the engine's historical [text | audio | video]
* -- exactly the seg_cu table the driver stages today -- with the sampler owning the audio
* and video rows and nobody else owning the prompt. */
Ref2VAPack p;
Ref2VAGeom g{ 3, 8, 10, 4 };
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
CHECK_EQ(p.segs.size(), 3u);
CHECK_EQ(p.segs[0].kind, kR2VText);
CHECK_EQ(p.segs[1].kind, kR2VAudio);
CHECK_EQ(p.segs[2].kind, kR2VVideo);
CHECK_EQ(p.segs[0].update, 0);
CHECK_EQ(p.segs[1].update, 1);
CHECK_EQ(p.segs[2].update, 1);
CHECK_EQ(p.segs[0].start, 0);
CHECK_EQ(p.segs[0].end, 5); /* the prompt */
CHECK_EQ(p.segs[1].start, 5); /* 2 channels x 4 audio latents */
CHECK_EQ(p.segs[1].end, 5 + 8);
CHECK_EQ(p.segs[2].start, 5 + 8); /* 3 latents x (8/2)(10/2) patches */
CHECK_EQ(p.segs[2].end, 5 + 8 + 60);
CHECK_EQ(p.rows, 5 + 8 + 60);
CHECK_EQ(p.pos.size(), (size_t)(3 * p.rows)); /* planar, the shape R_ROPE stages */
/* The row contract positions() used to compute by hand, axis by axis: the prompt counts up
* on time and ignores space; the soundtrack runs channel-major (all of the left, then the
* right) at height 0 on the width axis' two ends; every video row carries its frame's time. */
const int64_t rows = p.rows;
for (int64_t i = 0; i < 5; ++i) {
CHECK_EQ(p.pos[(size_t)i], (float)i);
CHECK_EQ(p.pos[(size_t)rows + i], 0.0f);
CHECK_EQ(p.pos[(size_t)(2 * rows) + i], 0.0f);
}
for (int ch = 0; ch < 2; ++ch)
for (int k = 0; k < 4; ++k) {
const size_t r = (size_t)(5 + ch * 4 + k);
CHECK_EQ(p.pos[r], (float)(5 + k)); /* time counts per channel, not per row */
CHECK_EQ(p.pos[rows + r], 0.0f);
}
/* The channels sit at the opposite ends of the width axis, and they are different. */
CHECK(p.pos[2 * rows + 5] != p.pos[2 * rows + 9]);
/* Video rows: the first frame's time is the timeline origin (text_len + all reference
* spans -- none here); 20 rows (4x5 patches) per frame, h-major; and frame k+1's time is
* frame k's plus 5/3 * kPattern[k % 5]. */
const size_t v0 = 5 + 8;
const int64_t fpp = 4 * 5;
CHECK_EQ(p.pos[v0], 5.0f);
CHECK_EQ(p.pos[v0 + 1], 5.0f); /* still frame 0 */
CHECK_EQ(p.pos[v0 + fpp], (float)(5.0 + 5.0 / 3.0)); /* frame 1, span 1 · 5/3 */
CHECK_EQ(p.pos[(size_t)(rows + v0)], p.pos[(size_t)(rows + v0 + 1)]); /* same patch row */
CHECK(p.pos[(size_t)(rows + v0)] != p.pos[(size_t)(rows + v0 + 5)]); /* y = 1 begins */
}
TEST(pack_ada_cell_plain_is_the_shipped_three_cell_plan) {
/* No references -> the cell plan must be byte-identical to the modulation step_ada builds
* today: md == the kSegMod column {text 1, audio 2, video 0}, and every cell reads a schedule
* row (the plain path has no pins), i.e. the row base r0 = e == audio ? S : 0. This holds at
* every probe, because a plain segment's label is always its stream's own timestep. */
Ref2VAPack p;
Ref2VAGeom g{ 3, 8, 10, 4 };
CHECK_EQ(ref2va_build(5, g, {}, {}, &p), 0);
for (double tv : { 0.9995, 0.5, 0.001, 0.999, 1.0 }) {
for (double ta : { 1.0, 0.5, 0.001, 0.999 }) {
std::vector<int> md, trow;
ref2va_ada_cell(p, tv, ta, &md, &trow);
const std::vector<int> want_md{ 1, 2, 0 }; /* == kSegMod */
const std::vector<int> want_tr{ kR2VTVideo, kR2VTAudio, kR2VTVideo };
CHECK(md == want_md);
CHECK(trow == want_tr);
}
}
}
TEST(pack_ada_cell_pinned_rows_collapse_onto_the_schedule) {
/* One reference photo and one standalone audio, over a video+audio target. Well under both
* pins the reference rows read the pinned embedding rows; at or above a pin (the sampler's
* early, near-clean steps) the pin is the stream's own timestep and the row collapses onto it,
* exactly as ref2va_mod_rows' row numbering collapses. Pins: visual 0.999, audio 1.0. */
Ref2VAPack p;
Ref2VAGeom g{ 3, 8, 10, 4 };
std::vector<Ref2VARef> refs = { { kR2VRefImage, 4, 4, 0, 0 }, { kR2VRefAudioOnly, 0, 0, 0, 2 } };
CHECK_EQ(ref2va_build(5, g, {}, refs, &p), 0);
/* [text, ref_img, ref_audio, audio(target), video(target)] */
CHECK_EQ(p.segs.size(), 5u);
std::vector<int> md, trow;
ref2va_ada_cell(p, 0.5, 0.5, &md, &trow);
const std::vector<int> want_md{ 1, 0, 2, 2, 0 }; /* text, ref_img, ref_audio, audio, video */
const std::vector<int> want_tr{ kR2VTVideo, kR2VTPinVideo, kR2VTPinAudio, kR2VTAudio,
kR2VTVideo };
CHECK(md == want_md);
CHECK(trow == want_tr);
ref2va_ada_cell(p, 0.9995, 1.0, &md, &trow); /* schedule at/above both pins */
const std::vector<int> collapse{ kR2VTVideo, kR2VTVideo, kR2VTAudio, kR2VTAudio, kR2VTVideo };
CHECK(trow == collapse);
}
TEST(pack_ref_kinds_predicates) {
CHECK_EQ(ref2va_seg_tag(kR2VText), 1);
CHECK_EQ(ref2va_seg_tag(kR2VVideo), 0);
CHECK_EQ(ref2va_seg_tag(kR2VAudio), 2);
CHECK_EQ(ref2va_seg_tag(kR2VCond), 0);
CHECK_EQ(ref2va_seg_tag(kR2VCondAudio), 2);
CHECK_EQ(ref2va_is_img(kR2VText), 0);
CHECK(ref2va_is_img(kR2VCond) && ref2va_is_img(kR2VRefImg) && ref2va_is_img(kR2VVideo));
CHECK(ref2va_is_audio(kR2VCondAudio) && ref2va_is_audio(kR2VRefAudio)
&& ref2va_is_audio(kR2VAudio));
CHECK(!ref2va_is_audio(kR2VRefImg) && !ref2va_is_img(kR2VRefAudio));
}
RAD_TEST_MAIN()
+118 -2
View File
@@ -256,7 +256,8 @@ TEST(op_vocabulary) {
static const char* kOps[] = {
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
"pool_rows", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw", "rel_sinusoid",
"pool_rows", "pool_cols", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw",
"rel_sinusoid",
"seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale",
"fill",
"gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "causal_conv1d",
@@ -2633,6 +2634,18 @@ TEST(op_pool_rows) {
CHECK(run("pool_rows", bad) < 0);
}
/* pool_cols: the mean of every k columns of a row, rounded, then the multiplier. */
TEST(op_pool_cols) {
T x(RAD_F32, {2, 4}); x.f({ 1, 2, 3, 4, 5, 6, 7, 9 });
T y(RAD_F32, {2, 2});
A a; a.t(x).t(y).i("M", 2).i("n", 4).i("k", 2).d("mult", 2.0).s("dtype", "f32");
CHECK_OK(run("pool_cols", a));
CHECK_NEAR(y.at(0), 3.0f, 1e-6); CHECK_NEAR(y.at(1), 7.0f, 1e-6);
CHECK_NEAR(y.at(2), 11.0f, 1e-6); CHECK_NEAR(y.at(3), 16.0f, 1e-6);
A bad; bad.t(x).t(y).i("M", 2).i("n", 4).i("k", 3).s("dtype", "f32");
CHECK(run("pool_cols", bad) < 0);
}
/* rmsnorm with no gain: a unit gain. */
TEST(op_rmsnorm_no_gain) {
T x(RAD_F32, {1, 2}); x.f({ 3, 4 });
@@ -4775,6 +4788,17 @@ TEST(timestep_embed_is_cos_then_sin_of_the_scaled_time) {
CHECK_OK(run("timestep_embed", b));
CHECK_NEAR(y2.at(0), std::cos(300.78125), 1e-5);
CHECK_NEAR(y2.at(1), std::sin(300.78125), 1e-5);
/* clamp_min raises a timestep below the floor -- the reference conditioning's near-clean pin --
* before embedding. h = n/2 = 1 so f_0 = 1 and the row is just [cos | sin](t'). Row 0's t is
* below the floor and rides it; row 1's is above and rides itself. */
T t3(RAD_F32, {2}); t3.f({0.05f, 1.0f});
T y3(RAD_F32, {2, 2});
A c; c.t(t3).t(y3).i("M", 2).i("n", 2).d("scale", 1.0).d("max_period", 100.0)
.d("clamp_min", 0.999).s("dtype", "f32");
CHECK_OK(run("timestep_embed", c));
CHECK_NEAR(y3.at(0), std::cos(0.999), 1e-6); CHECK_NEAR(y3.at(1), std::sin(0.999), 1e-6);
CHECK_NEAR(y3.at(2), std::cos(1.0), 1e-6); CHECK_NEAR(y3.at(3), std::sin(1.0), 1e-6);
}
/* gather_rows2: idx >= 0 reads a, idx < 0 reads b[-1 - idx], and a row past either source is
@@ -5531,6 +5555,59 @@ TEST(conv3d_ndhwc_rounds_the_conv_before_the_residual_in_place) {
CHECK_EQ(y2.at(0), 1.0078125f);
}
/* The CausalConv3d forms: `stride`/`stride_t` pad then stride, `causal` 1 takes the time pad
* front-only, `pad` `down` pads none above and left and one below and right, and `reflect` 1
* mirrors the spatial pads. Three frames of 2 x 2, causal, spatial stride 2 with `down` and a
* reflect: the output is one voxel a frame, and frame t reads frames t - 2, t - 1 and t. With
* the weight taps w[(1,0,0)] = 1, w[(2,1,1)] = 3, w[(0,2,2)] = 100, w[(0,0,2)] = 10 and
* w[(0,2,0)] = 20 (the three dt = 0 taps mirror (row 2 or column 2 back to (0, 0)), output t is
* 3 x x[(t,1,1)] + x[(t - 1,0,0)] + 130 x[(t - 2,0,0)] + b, the frame terms zero outside:
* 120.5, 250.5 and 120 x 3 + 50 + 10 x 13 + 0.5 = 1710.5. Refused: `stride` with a 5-wide
* kernel, a `pad` that is neither `same` nor `down`, a reflect whose pad reaches the axis at
* H 1, a zero stride, a causal that is neither 0 nor 1, and y short of the strided output. */
TEST(conv3d_ndhwc_causal_forms_stride_mirror_and_pad_front_only) {
T x(RAD_F32, {12, 1}); x.f({10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120});
std::vector<float> wv(27, 0.0f);
wv[9] = 1.0f; /* (dt 1, kh 0, kw 0): the previous frame's (0, 0) */
wv[22] = 3.0f; /* (dt 2, kh 1, kw 1): this frame's (1, 1) */
wv[8] = 100.0f; /* (dt 0, kh 2, kw 2): both axes reflect to (0, 0) */
wv[2] = 10.0f; /* (dt 0, kh 0, kw 2): the column reflects to 0 */
wv[6] = 20.0f; /* (dt 0, kh 2, kw 0): the row reflects to 0 */
T w(RAD_F32, {1, 1, 3, 3, 3}); w.f(wv);
T b(RAD_F32, {1}); b.f({0.5f});
T geom(RAD_I32, {3}); geom.n({3, 2, 2});
T y(RAD_F32, {3, 1});
A a; a.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 3).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").i("stride", 2).i("stride_t", 1).i("causal", 1)
.s("pad", "down").i("reflect", 1);
CHECK_OK(run("conv3d_ndhwc", a));
CHECK_EQ(y.at(0), 120.5f);
CHECK_EQ(y.at(1), 250.5f);
CHECK_EQ(y.at(2), 1710.5f);
A e5; e5.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 3).i("cin", 1).i("cout", 1).i("k", 5)
.i("kt", 3).s("dtype", "f32").i("stride", 2);
CHECK_EQ(run("conv3d_ndhwc", e5), RAD_E_SHAPE);
A ep; ep.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 3).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").s("pad", "mirror");
CHECK_EQ(run("conv3d_ndhwc", ep), RAD_E_SHAPE);
T g1(RAD_I32, {3}); g1.n({2, 1, 2});
A eh; eh.t(x).t(w).t(b).t(g1).tnull().t(y).i("M", 4).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").i("causal", 1).i("reflect", 1);
CHECK_EQ(run("conv3d_ndhwc", eh), RAD_E_SHAPE);
A e0; e0.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 3).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").i("stride", 0);
CHECK_EQ(run("conv3d_ndhwc", e0), RAD_E_SHAPE);
A e2; e2.t(x).t(w).t(b).t(geom).tnull().t(y).i("M", 3).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").i("causal", 2);
CHECK_EQ(run("conv3d_ndhwc", e2), RAD_E_SHAPE);
T y2(RAD_F32, {2, 1});
A es; es.t(x).t(w).t(b).t(geom).tnull().t(y2).i("M", 2).i("cin", 1).i("cout", 1).i("k", 3)
.i("kt", 3).s("dtype", "f32").i("stride", 2).i("stride_t", 1).i("causal", 1)
.s("pad", "down").i("reflect", 1);
CHECK_EQ(run("conv3d_ndhwc", es), RAD_E_SHAPE);
}
/* group_norm's statistics are over every row of a group's channels. Two rows of four channels in
* two groups: group 0 (channels 0 and 1) holds 1, 1, 3, 3, so mean 2 and var 1 (a per-row mean
* would make row 0 constant); group 1 holds 8, 12, 12, 8, mean 10 and var 4, rstd 0.5 (eps 0).
@@ -6119,6 +6196,44 @@ TEST(conv_t1d_takes_any_kernel_of_at_least_a_stride) {
CHECK_EQ(run("conv_t1d", e), RAD_E_SHAPE);
}
/* conv1d's strided form (a DAC encoder's downsample): kernel 2 stride, pad stride / 2, one
* sequence. x rows [1 .. 8], w [1, 2, 3, 4], stride 2, pad 1: output row m reads
* x[2m - 1 + t] (zeros outside [0, 8)): 20, 40, 60, 44 — 8 rows halve to exactly 4. */
TEST(conv1d_strided_downsamples_one_sequence) {
T x(RAD_BF16, {8, 1}); x.f({1, 2, 3, 4, 5, 6, 7, 8});
T w(RAD_BF16, {1, 1, 4}); w.f({1, 2, 3, 4});
T cu(RAD_I32, {2}); cu.n({0, 8});
T y(RAD_BF16, {4, 1});
A a; a.t(x).t(w).t(cu).tnull().t(y).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("stride", 2).i("pad", 1).s("dtype", "bf16");
CHECK_OK(run("conv1d", a));
CHECK_EQ(y.at(0), 20.0f); CHECK_EQ(y.at(1), 40.0f);
CHECK_EQ(y.at(2), 60.0f); CHECK_EQ(y.at(3), 44.0f);
/* The refusals: `pad` without a stride, a stride without `pad`, a stride over more than
* one sequence, a y that is not the formula's rows, and a stride on the f32 rows. */
A p; p.t(x).t(w).t(cu).tnull().t(y).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("pad", 1).s("dtype", "bf16");
CHECK_EQ(run("conv1d", p), RAD_E_SHAPE);
A q; q.t(x).t(w).t(cu).tnull().t(y).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("stride", 2).s("dtype", "bf16");
CHECK_EQ(run("conv1d", q), RAD_E_SHAPE);
T cu2(RAD_I32, {3}); cu2.n({0, 4, 8});
A m; m.t(x).t(w).t(cu2).tnull().t(y).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("stride", 2).i("pad", 1).s("dtype", "bf16");
CHECK_EQ(run("conv1d", m), RAD_E_SHAPE);
T y5(RAD_BF16, {5, 1});
A r; r.t(x).t(w).t(cu).tnull().t(y5).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("stride", 2).i("pad", 1).s("dtype", "bf16");
CHECK_EQ(run("conv1d", r), RAD_E_SHAPE);
T xf(RAD_F32, {8, 1}); xf.f({1, 2, 3, 4, 5, 6, 7, 8});
T wf(RAD_F32, {1, 1, 4}); wf.f({1, 2, 3, 4});
T yf(RAD_F32, {4, 1});
A f; f.t(xf).t(wf).t(cu).tnull().t(yf).tnull().i("M", 8).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("stride", 2).i("pad", 1).s("dtype", "f32");
CHECK_EQ(run("conv1d", f), RAD_E_DTYPE);
}
/* conv1d `act` clamp: min(max(y, -1), 1) after the bias. */
TEST(conv1d_act_clamp_bounds_the_output) {
T x(RAD_F32, {4, 1}); x.f({0.5f, 2, -3, -1});
@@ -6866,6 +6981,7 @@ std::vector<Geo> geometries() {
G("act_mul", "M", 3, a.i("M", R).i("n", 8).s("act", "silu").s("dtype", "f32")),
G("seg_mean", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32").i("n_seq", 2)),
G("pool_rows", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")),
G("pool_cols", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")),
G("relu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("clamp", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("conv2d", "M", 8, a.i("M", R).i("width", 4).i("cin", 2).i("cout", 3).i("kh", 3).i("kw", 3)
@@ -7006,7 +7122,7 @@ std::vector<Geo> geometries() {
.i("gated", 1).s("dtype", "bf16")),
G("gate_add", "M", 4, a.i("M", R).i("n", 8).s("dtype", "bf16")),
G("timestep_embed", "M", 3, a.i("M", R).i("n", 8).d("scale", 1000.0)
.d("max_period", 10000.0).s("dtype", "f32")),
.d("max_period", 10000.0).d("clamp_min", 0.3).s("dtype", "f32")),
G("gather_rows2", "M", 4, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("lane_gather", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")),
G("lane_store", "M", 4, a.i("M", R).i("n", 8).i("stride", 8).s("dtype", "bf16")),
+169
View File
@@ -0,0 +1,169 @@
/* vae_geom_test.cpp -- the encode geometry (arch/minimaxh3/rad_vae_geom.cpp) against golden vectors
* produced by the reference VAEs themselves.
*
* The TU is pure host arithmetic, so it is compiled straight in here -- no rad_core, no device.
* tests/data/vae_geom/golden.json comes from gen_golden.py, which runs the reference's real
* encoders on CPU (video: EncoderFCN3D + the wrapper's own encode()/encode_temporal()/
* split_tiles()/tiled_encode() with the reference constructor arguments; audio: the DAC encoder):
* the latent counts below are the networks' own output shapes, the tile plans the reference's own
* returns, and the constants its own tables. A mismatch is the port disagreeing with the model.
*/
#include "rad_test.h"
#include "rad_vae_geom.h"
#include <nlohmann/json.hpp>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
using namespace minimaxh3;
namespace {
nlohmann::json& golden() {
static nlohmann::json g = [] {
std::ifstream f(std::string(RAD_VAE_GOLDEN) + "/golden.json");
if (!f.is_open()) {
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
"tests/data/vae_geom/gen_golden.py\n");
std::exit(1);
}
return nlohmann::json::parse(f);
}();
return g;
}
} /* namespace */
TEST(vae_encode_latent_counts) {
/* Every frame count goes through the reference encode() end to end: chunking, the padded last
* clip, the trailing drop. The spatial entries pin the ratio (generated at 32x32) and the
* latent width pins z_channels. */
for (const auto& c : golden()["video"]["encode"]) {
const int64_t t = c["T"];
const auto& z = c["z_shape"];
CHECK_EQ(vae_latent_frames(t), z[2].get<int64_t>());
CHECK_EQ(z[1].get<int64_t>(), 24);
CHECK_EQ(z[3].get<int64_t>() * kVaeRatio, 32);
CHECK_EQ(z[4].get<int64_t>() * kVaeRatio, 32);
}
}
TEST(vae_clip_chain_composes_with_encode) {
/* A full clip's latents times the clip count, minus the drop, is the encode count -- and the
* causal chain the golden's tiled_encode cases pin (no chunking, no drop: the raw clip) is
* vae_clip_latents of the pixel frames. */
for (const auto& c : golden()["video"]["encode"]) {
const int64_t t = c["T"];
if (t < 2) continue;
const int64_t clips = (t + kVaeClipLength - 1) / kVaeClipLength;
CHECK_EQ(clips * vae_clip_latents(kVaeClipLength) - kVaeTokenDrop, c["z_shape"][2].get<int64_t>());
}
for (const auto& c : golden()["video"]["tiled_encode"])
CHECK_EQ(vae_clip_latents(c["x_shape"][2].get<int64_t>()), c["moments_shape"][2].get<int64_t>());
/* A single frame truncates its temporal taps instead of padding them. */
CHECK_EQ(vae_clip_latents(1), 1);
}
TEST(vae_split_tiles_matches_reference) {
for (const auto& c : golden()["video"]["split_tiles"]) {
const int64_t len = c["input_len"];
std::vector<VaeTile> tiles;
vae_split_tiles(len, &tiles);
const auto& gs = c["starts"];
const auto& go = c["overlaps"];
CHECK_EQ(tiles.size(), gs.size());
if (tiles.size() != gs.size()) continue;
for (size_t i = 0; i < tiles.size(); ++i) {
CHECK_EQ(tiles[i].start, gs[i].get<int64_t>());
CHECK_EQ(tiles[i].overlap, i < go.size() ? go[i].get<int64_t>() : 0);
/* The reference slices [start, start+256) and lets the slice clamp at the axis end --
* that clamped length is what the tile encoder really receives. */
CHECK_EQ(tiles[i].len, std::min<int64_t>(kVaeTileSize, len - tiles[i].start));
}
/* Consecutive windows share exactly their overlap, so the latents the blend keeps sum to
* the axis when the encoder's own 16 px alignment holds. */
if (len % kVaeRatio == 0) {
int64_t covered = 0;
for (const VaeTile& t : tiles) covered += t.len - t.overlap;
CHECK_EQ(covered, len);
}
}
}
TEST(vae_tiled_encode_grid_keeps_size) {
/* The reference always tiles; the blend cuts keep the moments at exactly ratio-reduced size.
* That is the tile plan plus arithmetic -- the same statement the real network run above
* makes, port-side. */
for (const auto& c : golden()["video"]["tiled_encode"]) {
const auto& x = c["x_shape"];
const auto& m = c["moments_shape"];
for (int axis = 0; axis < 2; ++axis) {
const int64_t px = axis == 0 ? x[3].get<int64_t>() : x[4].get<int64_t>();
const int64_t lat = axis == 0 ? m[3].get<int64_t>() : m[4].get<int64_t>();
std::vector<VaeTile> tiles;
vae_split_tiles(px, &tiles);
int64_t total = 0;
for (const VaeTile& t : tiles) {
CHECK_EQ(t.len % kVaeRatio, 0); /* whole latents, or the cut would slice one */
CHECK_EQ(t.overlap % kVaeRatio, 0);
total += t.len / kVaeRatio - t.overlap / kVaeRatio;
}
CHECK_EQ(total, lat);
}
}
}
TEST(vae_audio_latents_match_encoder) {
/* The wrapper right-pads to the hop and the stride chain divides exactly: the reference
* encoder's own frame count is ceil(samples / 800). */
for (const auto& c : golden()["audio"]["latents"]) {
const int64_t s = c["samples"];
CHECK_EQ(vae_audio_latents(s), c["T"].get<int64_t>());
CHECK_EQ(vae_audio_latents(s) * kAudioHop, c["padded"].get<int64_t>());
}
}
TEST(vae_constants_are_the_reference_tables) {
/* The de-normalization the latents carry: doubles compare bit for bit, since the golden
* carries the same decimal literals. */
const auto& k = golden()["video"]["constants"];
const auto mean = k["latents_mean"].get<std::vector<double>>();
const auto stdv = k["latents_std"].get<std::vector<double>>();
CHECK_EQ(mean.size(), 24u);
CHECK_EQ(stdv.size(), 24u);
for (size_t i = 0; i < mean.size() && i < 24; ++i) {
CHECK(kVaeLatentsMean[i] == mean[i]);
CHECK(kVaeLatentsStd[i] == stdv[i]);
}
const auto pm = k["pixel_mean"].get<std::vector<double>>();
const auto ps = k["pixel_std"].get<std::vector<double>>();
for (size_t i = 0; i < 3; ++i) {
CHECK(kVaePixelMean[i] == pm[i]);
CHECK(kVaePixelStd[i] == ps[i]);
}
}
TEST(vae_geom_rejects_nonsense_and_covers_small_axes) {
CHECK_EQ(vae_latent_frames(0), -1);
CHECK_EQ(vae_latent_frames(-5), -1);
CHECK_EQ(vae_clip_latents(0), -1);
CHECK_EQ(vae_audio_latents(-1), -1);
CHECK_EQ(vae_audio_latents(0), 0);
std::vector<VaeTile> tiles;
vae_split_tiles(1, &tiles);
CHECK_EQ(tiles.size(), 1u);
CHECK_EQ(tiles[0].start, 0);
CHECK_EQ(tiles[0].len, 1);
CHECK_EQ(tiles[0].overlap, 0);
vae_split_tiles(kVaeTileSize, &tiles);
CHECK_EQ(tiles.size(), 1u);
CHECK_EQ(tiles[0].len, kVaeTileSize);
}
RAD_TEST_MAIN()
+480
View File
@@ -68,6 +68,133 @@ int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap
return rows;
}
/* The pack's boundary table for this fake's layout: [0 | text | text + stereo | total]. */
int64_t fake_segs(const RadVideoGeom* g, int32_t* cu, int64_t cap) {
const int64_t audio = 2 * (int64_t)g->n_audio;
const int64_t rows = g->n_text + audio +
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
const int32_t t[4] = { 0, g->n_text, (int32_t)(g->n_text + audio), (int32_t)rows };
if (!cu) return 4;
if (cap < 4) return RAD_E_INVAL;
for (int i = 0; i < 4; ++i) cu[i] = t[i];
return 4;
}
/* Same count, wrong boundaries -- the driver must stage its own table, not this one. */
int64_t fake_segs_wrong(const RadVideoGeom* g, int32_t* cu, int64_t cap) {
if (!cu) return 4;
if (cap < 4) return RAD_E_INVAL;
cu[0] = 0; cu[1] = g->n_text + 1; cu[2] = 999999; cu[3] = 12345;
return 4;
}
/* A segmentation R_SEG cannot hold -- also falls back to the driver's own table. */
int64_t fake_segs_more(const RadVideoGeom* g, int32_t* cu, int64_t cap) {
if (!cu) return 5;
if (cap < 5) return RAD_E_INVAL;
cu[0] = 0; cu[1] = g->n_text; cu[2] = g->n_text + 4; cu[3] = g->n_text + 8; cu[4] = 99;
return 5;
}
/* The reference-aware layout export for this fake: it lays out the plain sequence only (a
* reference table would be the real plugin's to present), answering with the rows and writing
* the boundaries and positions when roomy. */
int64_t fake_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg, int64_t cap_seg,
float* pos, int64_t cap_pos) {
if (ref_tab) return RAD_E_INVAL;
const int64_t audio = 2 * (int64_t)g->n_audio;
const int64_t rows = g->n_text + audio +
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
if (seg) {
if (cap_seg < 4) return RAD_E_INVAL;
seg[0] = 0; seg[1] = g->n_text; seg[2] = (int32_t)(g->n_text + audio);
seg[3] = (int32_t)rows;
}
if (pos) {
if (cap_pos < rows) return RAD_E_INVAL;
for (int64_t c = 0; c < 3; ++c)
for (int64_t i = 0; i < rows; ++i) pos[c * rows + i] = (float)(c * 1000 + i);
}
return rows;
}
/* Right-shaped but the rows do not match the geometry -- the driver stages its own table. */
int64_t fake_pack_wrong(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg,
int64_t cap_seg, float* pos, int64_t cap_pos) {
(void)ref_tab; (void)pos; (void)cap_pos;
if (!seg) return 999999;
if (cap_seg < 4) return RAD_E_INVAL;
seg[0] = 0; seg[1] = g->n_text + 1; seg[2] = 999999; seg[3] = 12345;
return 12345;
}
/* A plain table with an entry past the fourth: the rows are right and the first boundaries
* match, but the extra word poisons the table the geometry backs -- fallback again. */
int64_t fake_pack_more(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg,
int64_t cap_seg, float* pos, int64_t cap_pos) {
(void)ref_tab; (void)pos; (void)cap_pos;
const int64_t audio = 2 * (int64_t)g->n_audio;
const int64_t rows = g->n_text + audio +
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
if (!seg) return rows;
if (cap_seg < 5) return RAD_E_INVAL;
seg[0] = 0; seg[1] = g->n_text; seg[2] = (int32_t)(g->n_text + audio);
seg[3] = (int32_t)rows; seg[4] = 99;
return rows;
}
/* The reference-aware layout: when a reference table rides, lay out
* [text | one block per reference | audio target | video target] -- boundaries are segment starts
* with the total rows last, so the video target runs [seg[nseg-2], seg[nseg-1]). Each picture
* contributes a fixed 4 rows: this fake lays out the structure the driver stages, not the
* reference's real visual-token arithmetic. With no table it lays the plain sequence, so the
* encode/decode passes that call the pack without references get their plain table. */
int64_t fake_pack_ref(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg, int64_t cap_seg,
float* pos, int64_t cap_pos) {
const int64_t audio = 2 * (int64_t)g->n_audio;
const int64_t vtarget = (int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
if (!ref_tab) {
const int64_t rows = g->n_text + audio + vtarget;
if (seg) {
if (cap_seg < 4) return RAD_E_INVAL;
seg[0] = 0; seg[1] = g->n_text; seg[2] = (int32_t)(g->n_text + audio);
seg[3] = (int32_t)rows;
}
if (pos) {
if (cap_pos < 3 * rows) return RAD_E_INVAL;
for (int64_t c = 0; c < 3; ++c)
for (int64_t i = 0; i < rows; ++i) pos[c * rows + i] = (float)(c * 1000 + i);
}
return rows;
}
const int32_t nr = ref_tab[0], nk = ref_tab[1];
const int64_t rper = 4;
const int64_t rows = g->n_text + (int64_t)nr * rper + audio + vtarget;
const int64_t nseg = (int64_t)nr + 4;
if (!seg) return rows;
if (cap_seg < nseg || nk != 0) return RAD_E_INVAL;
seg[0] = 0;
for (int32_t r = 0; r < nr; ++r) seg[1 + r] = (int32_t)(g->n_text + (int64_t)r * rper);
seg[1 + nr] = (int32_t)(g->n_text + (int64_t)nr * rper); /* audio target start */
seg[2 + nr] = (int32_t)(seg[1 + nr] + audio); /* video target start */
seg[3 + nr] = (int32_t)(seg[2 + nr] + vtarget); /* total rows */
if (pos) {
if (cap_pos < 3 * rows) return RAD_E_INVAL;
for (int64_t c = 0; c < 3; ++c)
for (int64_t i = 0; i < rows; ++i) pos[c * rows + i] = (float)(c * 1000 + i);
}
return rows;
}
/* The encode-geometry export for this fake: it agrees with what the driver staged — a video is
* padded to its own frame count (gd[23]), an audio to its own sample count (gd[0]) — so an encode
* pass accepts the staged volume and moves on. Only what the driver validates matters here. */
int64_t fake_encode_geom(int32_t kind, const int64_t* in, int32_t* gd, int64_t cap) {
if (!gd) return kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
const int64_t need = kind == RAD_GEN_PASS_AENCODE ? 13 : 25;
if (cap < need) return RAD_E_INVAL;
for (int64_t i = 0; i < need; ++i) gd[i] = 0;
if (kind == RAD_GEN_PASS_AENCODE) gd[0] = (int32_t)in[0]; /* n_pad = the sample count */
else gd[23] = (int32_t)in[0]; /* T_pad = the frame count */
return need;
}
struct VideoFixture {
Program prog;
gen::VideoDriver drv;
@@ -79,6 +206,19 @@ struct VideoFixture {
prog.ctx.max_seqs = 1;
}
int start() { return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }); }
int start_with(gen::VideoDriver::SegsFn segs) {
return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }, segs);
}
int start_with_pack(gen::VideoDriver::PackFn pack) {
return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }, nullptr, pack);
}
int start_with_encode_gen(gen::VideoDriver::EncodeGeomFn enc) {
return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }, nullptr, nullptr,
enc);
}
int start_with_pack_encode(gen::VideoDriver::PackFn pack, gen::VideoDriver::EncodeGeomFn enc) {
return drv.init(prog, fake_positions, { gen::VideoDriver::RankIO{} }, nullptr, pack, enc);
}
std::unique_ptr<gen::VideoRequest> req(int32_t chunks = 2, int32_t steps = 0) {
auto r = std::make_unique<gen::VideoRequest>();
r->tokens = { 1, 2, 3 };
@@ -302,6 +442,74 @@ TEST(the_small_size_is_each_side_over_the_factor_at_the_multiple) {
CHECK_EQ(h, 64);
}
/* A plugin exporting the pack's boundary table stages it into R_SEG; one exporting a table the
* geometry does not back, or more segments than the register holds, does not -- the driver's own
* plain table goes instead. All three stage the same bytes for a plain request. */
TEST(the_plugin_segment_table_is_staged_and_a_disagreeing_one_falls_back) {
const gen::VideoDriver::SegsFn fns[3] = { fake_segs, fake_segs_wrong, fake_segs_more };
for (gen::VideoDriver::SegsFn fn : fns) {
VideoFixture f;
f.build();
CHECK_OK(f.start_with(fn));
std::string why;
auto r = f.req(1);
CHECK_OK(f.drv.submit(std::move(r), &why));
bool saw_step = false;
for (int i = 0; i < 20 && !saw_step; ++i) {
const RadBatch* b = f.drv.next(i);
if (!b) break;
if (b->gen == RAD_GEN_PASS_VSTEP) {
const RadVideoGenBatch* V = b->vgen_b;
REQUIRE(V != nullptr);
const int32_t audio = 2 * V->geom.n_audio;
CHECK_EQ(V->seg_cu[0], 0);
CHECK_EQ(V->seg_cu[1], V->geom.n_text);
CHECK_EQ(V->seg_cu[2], (int32_t)(V->geom.n_text + audio));
CHECK_EQ(V->seg_cu[3], (int32_t)b->n_tok);
saw_step = true;
}
f.answer(10 * i);
CHECK_OK(f.drv.done());
}
CHECK(saw_step);
}
}
/* The reference-aware export is preferred over rad_arch_video_segs for the plain sequence it
* also lays out; a pack whose rows the geometry does not back, or that writes past the plain
* table's fourth boundary, falls back -- and a plain request stages the same bytes in every
* case. The batch carries no reference table: the driver's is empty until references ride. */
TEST(the_reference_aware_pack_is_preferred_and_a_disagreeing_one_falls_back) {
const gen::VideoDriver::PackFn fns[3] = { fake_pack, fake_pack_wrong, fake_pack_more };
for (gen::VideoDriver::PackFn fn : fns) {
VideoFixture f;
f.build();
CHECK_OK(f.start_with_pack(fn));
std::string why;
auto r = f.req(1);
CHECK_OK(f.drv.submit(std::move(r), &why));
bool saw_step = false;
for (int i = 0; i < 20 && !saw_step; ++i) {
const RadBatch* b = f.drv.next(i);
if (!b) break;
if (b->gen == RAD_GEN_PASS_VSTEP) {
const RadVideoGenBatch* V = b->vgen_b;
REQUIRE(V != nullptr);
const int32_t audio = 2 * V->geom.n_audio;
CHECK_EQ(V->seg_cu[0], 0);
CHECK_EQ(V->seg_cu[1], V->geom.n_text);
CHECK_EQ(V->seg_cu[2], (int32_t)(V->geom.n_text + audio));
CHECK_EQ(V->seg_cu[3], (int32_t)b->n_tok);
CHECK(V->ref_tab == nullptr);
saw_step = true;
}
f.answer(10 * i);
CHECK_OK(f.drv.done());
}
CHECK(saw_step);
}
}
/* An upscaled request: its first evaluations at the small size, the last of them stepping to the
* clean estimate, then the upscale pass with both geometries, the factor and the first full-size
* step's sigmas, then the full-size steps and the decodes at the full size. */
@@ -443,4 +651,276 @@ TEST(a_request_that_cannot_run_is_refused_at_submit) {
refused(f.req(1, 1), "num_inference_steps");
}
namespace {
/* A synthetic picture as the processor hands one over: eight patches in one temporal group,
* merged two by two into two output rows. `expand` is the two placeholder tokens the driver's
* rope layout sits on; `pixels` are an index pattern so a byte-parity check has something to
* check against when the tower path is exercised end to end. */
std::shared_ptr<mm::Item> synthetic_picture(int64_t patch_dim) {
auto it = std::make_shared<mm::Item>();
it->kind = mm::Kind::Image;
it->grid_t = 1;
it->grid_h = 2;
it->grid_w = 4;
it->n_patch = 8;
it->patch_dim = patch_dim;
it->pixels.resize((size_t)(it->n_patch * patch_dim));
for (size_t i = 0; i < it->pixels.size(); ++i) it->pixels[i] = (uint16_t)i;
it->n_seg = 1;
it->seg_rows = 2;
it->rows_h = 1;
it->rows_w = 2;
it->expand = { 700, 701 };
it->seg_at = { 0 };
return it;
}
gen::VideoRefMedia ref_part(gen::VideoRefMedia::Kind kind, const char* name, int32_t index) {
gen::VideoRefMedia m;
m.kind = kind;
m.index = index;
m.name = name;
m.data = "x";
return m;
}
/* The encoder view of a request whose prompt is { 1, expand..., 2, 3 }. */
std::shared_ptr<mm::PromptMedia> picture_media(int64_t patch_dim, int32_t tok) {
auto pm = std::make_shared<mm::PromptMedia>();
mm::Placed pl;
pl.item = synthetic_picture(patch_dim);
pl.tok = tok;
pm->items.push_back(std::move(pl));
pm->layout();
return pm;
}
void with_tower(VideoFixture& f, int64_t max_enc) {
f.prog.encoder.modalities = RAD_MM_IMAGE;
f.prog.encoder.patch_dim = 6;
f.prog.ctx.max_enc_patches = max_enc;
}
} /* namespace */
/* A reference picture's conditioning pass carries the tower's input and the M-RoPE grid exactly
* as the image driver stages them, and nothing of it leaks into the step passes that follow. */
TEST(a_reference_image_conditions_the_video_prompt) {
VideoFixture f;
f.build();
with_tower(f, 16);
CHECK_OK(f.start());
std::string why;
auto r = f.req(2);
r->tokens = { 1, 700, 701, 2, 3 };
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
r->media = picture_media(6, 1);
CHECK_OK(f.drv.submit(std::move(r), &why));
/* The first pass conditions: its media fields carry the picture. */
const RadBatch* b = f.drv.next(0);
REQUIRE(b != nullptr);
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VCOND);
CHECK_EQ(b->n_tok, (int64_t)5);
CHECK_EQ(b->rope_mixed, 1);
CHECK(b->rope_pos != nullptr);
CHECK_EQ(b->n_mm_rows, (int64_t)2);
CHECK(b->mm_rows != nullptr);
CHECK_EQ(b->enc, 0);
CHECK_EQ(b->enc_n_patch, (int64_t)8);
CHECK(b->enc_pixels != nullptr);
CHECK(b->enc_coord != nullptr);
CHECK_EQ(b->enc_n_seg, 1);
CHECK(b->enc_cu != nullptr);
CHECK_EQ(b->enc_max_seg, 8);
CHECK(b->vgen_b != nullptr);
f.answer(0);
CHECK_OK(f.drv.done());
/* The steps after it carry no media: every pass starts from a zeroed batch, so the tower
* never sees a stale conditioning. */
std::string kinds = "C";
for (int i = 1; i < 10; ++i) {
b = f.drv.next(i);
if (!b) break;
kinds += kind_of(b->gen);
if (b->gen == RAD_GEN_PASS_VSTEP) {
CHECK(b->rope_pos == nullptr);
CHECK_EQ(b->rope_mixed, 0);
CHECK_EQ(b->n_mm_rows, (int64_t)0);
CHECK_EQ(b->enc_n_patch, (int64_t)0);
CHECK_EQ(b->n_tok, (int64_t)(5 + 100 + 6));
}
f.answer(0);
CHECK_OK(f.drv.done());
}
CHECK_EQ(kinds, std::string("CSSADD"));
}
/* With the encoders declared, a reference picture queues a Vencode pass and enters the pack's
* reference table: the picture in its OWN latent grid (the encoder's sides over the VAE ratio), at
* the slot its encode pass numbers, one latent frame, no soundtrack. Until step_dit consumes it the
* table rides the batch untouched, but it must be exactly what the pack scatters from. */
TEST(a_reference_picture_fills_the_pack_reference_table) {
VideoFixture f;
f.build();
with_tower(f, 16);
RadVideoGenDecl& d = f.prog.video_gen;
d.encodes = 1;
d.enc_ratio = 16;
d.max_enc_frames = 1;
d.max_enc_side = 16;
CHECK_OK(f.start_with_encode_gen(fake_encode_geom));
std::string why;
auto r = f.req(2);
r->tokens = { 1, 700, 701, 2, 3 };
gen::VideoRefMedia m = ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1);
m.enc_frames = 1;
m.enc_h = 16;
m.enc_w = 16;
m.enc_pixels.assign(16 * 16 * 3, 1.0f);
r->refs.push_back(m);
r->media = picture_media(6, 1);
CHECK_OK(f.drv.submit(std::move(r), &why));
/* The first pass encodes the picture, before any conditioning or denoising. */
const RadBatch* b = f.drv.next(0);
REQUIRE(b != nullptr);
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VENCODE);
CHECK(b->vgen_b != nullptr);
CHECK(b->vgen_b->ref_tab != nullptr);
CHECK_EQ(b->vgen_b->enc_kind, (int32_t)RAD_ENC_IMAGE);
CHECK_EQ(b->vgen_b->enc_slot, (int32_t)1);
CHECK_OK(f.drv.done());
/* The reference table: {n_refs, n_keys} then one 6-word picture row {kind, slot, h, w, frames,
* audio} — a picture (kind 0), slot 1, a 1x1 latent grid (16/16), one latent frame, no sound. */
const int32_t* tab = b->vgen_b->ref_tab;
CHECK_EQ(tab[0], 1);
CHECK_EQ(tab[1], 0);
CHECK_EQ(tab[2], 0);
CHECK_EQ(tab[3], 1);
CHECK_EQ(tab[4], 1);
CHECK_EQ(tab[5], 1);
CHECK_EQ(tab[6], 1);
CHECK_EQ(tab[7], 0);
}
/* A generator whose denoiser consumes the reference table lays each conditioned step at the pack's
* widened layout: the reference block rides between the text and the target streams, the step
* stages the pack's full segment-boundary table (video grid last) and its [3, rows] positions, and
* the sampler's target counts are the pack's video and audio segments -- not the whole widened
* step (the reference rows are pinned, never sampled). The encode pass that precedes it keeps its
* plain table; only the step is widened. */
TEST(a_reference_conditioned_step_widens_to_the_pack_layout) {
VideoFixture f;
f.build();
with_tower(f, 16);
RadVideoGenDecl& d = f.prog.video_gen;
d.encodes = 1;
d.enc_ratio = 16;
d.max_enc_frames = 1;
d.max_enc_side = 16;
d.ref_rows = 1; // the denoiser consumes the table: turn the widening on
CHECK_OK(f.start_with_pack_encode(fake_pack_ref, fake_encode_geom));
std::string why;
auto r = f.req(2);
r->tokens = { 1, 700, 701, 2, 3 }; /* 5 text tokens */
gen::VideoRefMedia m = ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1);
m.enc_frames = 1;
m.enc_h = 16;
m.enc_w = 16;
m.enc_pixels.assign(16 * 16 * 3, 1.0f);
r->refs.push_back(m);
r->media = picture_media(6, 1);
CHECK_OK(f.drv.submit(std::move(r), &why));
const gen::VideoShape s = gen::video_shape(d, 64, 32, 2);
const int64_t n_text = 5, audio = 2 * s.n_audio, vtarget = s.video_rows, rper = 4;
const int64_t widened = n_text + rper + audio + vtarget;
bool saw_step = false, saw_encode = false;
for (int i = 0; i < 20; ++i) {
const RadBatch* b = f.drv.next(i);
if (!b) break;
if (b->gen == RAD_GEN_PASS_VSTEP) {
const RadVideoGenBatch* V = b->vgen_b;
REQUIRE(V != nullptr);
saw_step = true;
CHECK(V->ref_tab != nullptr);
CHECK_EQ(b->n_tok, widened); /* widened by the reference block */
CHECK_EQ(V->seg_cu[0], 0);
CHECK_EQ(V->seg_cu[1], (int32_t)n_text); /* text | reference */
CHECK_EQ(V->seg_cu[2], (int32_t)(n_text + rper)); /* audio target start */
CHECK_EQ(V->seg_cu[3], (int32_t)(n_text + rper + audio)); /* video target start */
CHECK_EQ(V->seg_cu[4], (int32_t)widened);
CHECK_EQ(V->lat_cu[1], (int32_t)vtarget); /* sampler owns the target streams */
CHECK_EQ(V->lat_cu[3], (int32_t)audio); /* only, not the reference rows */
} else if (b->gen == RAD_GEN_PASS_VENCODE) {
saw_encode = true;
}
f.answer(10 * i);
CHECK_OK(f.drv.done());
}
CHECK(saw_step);
CHECK(saw_encode);
}
/* What the video path cannot consume is refused at submit, naming the part or the budget it
* breaks — never silently dropped into a weaker video. */
TEST(reference_media_the_generator_cannot_consume_are_refused_naming_the_part) {
std::string why;
/* A container converted without its tower takes no reference media at all. */
VideoFixture f;
f.build();
CHECK_OK(f.start());
auto r = f.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
CHECK(has(why, "vision tower"));
VideoFixture g;
g.build();
with_tower(g, 16);
CHECK_OK(g.start());
auto refused = [&](std::unique_ptr<gen::VideoRequest> q, const char* what) {
why.clear();
CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
CHECK(has(why, what));
};
/* Videos and audios reach the model through the VAEs, which the video path does not run. */
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::VIDEO, "ref_video_1", 1));
refused(std::move(r), "ref_video_1");
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
r->refs.push_back(ref_part(gen::VideoRefMedia::VIDEO_AUDIO, "ref_video_audio_1", 1));
refused(std::move(r), "ref_video_audio_1");
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::AUDIO, "ref_audio_2", 2));
refused(std::move(r), "ref_audio_2");
/* An image part with nothing behind it would become a text-only video. */
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
refused(std::move(r), "no processed media");
/* A run placed past the prompt, and more patches than one conditioning pass encodes. */
r = g.req();
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
r->media = picture_media(6, 3); /* expand would run to token 5, past the 3-token prompt */
refused(std::move(r), "past the end");
VideoFixture h;
h.build();
with_tower(h, 4);
CHECK_OK(h.start());
r = h.req();
r->tokens = { 1, 700, 701, 2, 3 };
r->refs.push_back(ref_part(gen::VideoRefMedia::IMAGE, "ref_image_1", 1));
r->media = picture_media(6, 1);
why.clear();
CHECK_EQ(h.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
CHECK(has(why, "at most 4"));
}
RAD_TEST_MAIN()
+183
View File
@@ -45,6 +45,9 @@ struct FakeVideoGen : IVideoGen {
inf.default_steps = 50;
inf.max_steps = 65;
inf.max_lanes = 2;
inf.max_ref_images = 9;
inf.max_ref_videos = 3;
inf.max_ref_audios = 3;
}
const VideoGenInfo& info() const override { return inf; }
int submit(std::unique_ptr<gen::VideoRequest> r, std::string*) override {
@@ -328,6 +331,11 @@ TEST(a_failed_generation_is_a_failed_job_with_its_reason) {
HttpResponse r = v.create(Videos::body());
REQUIRE_EQ(r.status, 200);
json o = v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
/* The job's thread opens the MP4 writer before it draws a step, so without a codec it fails
* the write before the generator is asked to fail -- the reason under test is unreachable.
* Same guard as the completion case above. */
if (str_at(o, "status") == "failed" && has(str_at(o["error"], "message"), "no libavcodec"))
SKIP("this build has no libavcodec to reach the generator with");
CHECK_EQ(str_at(o, "status"), std::string("failed"));
CHECK_EQ(str_at(o["error"], "code"), std::string("generation_failed"));
CHECK(has(str_at(o["error"], "message"), "the engine stopped"));
@@ -340,4 +348,179 @@ TEST(the_video_routes_are_501_without_a_video_model) {
CHECK_EQ(f.get("/v1/videos").status, 501);
}
/* ref2va: the reference file parts are read from the form, and the generator gets them bounded,
* numbered and paired — sorted by (kind, number), images first, a soundtrack after its video. */
TEST(ref2va_reference_media_reach_the_generator) {
Videos v;
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "a fox in the snow" },
FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" },
FormPart{ "ref_video_audio_1", "tail.wav", "audio/wav", "RIFF" },
FormPart{ "ref_image_2", "b.jpg", "image/jpeg", "JPEG" },
FormPart{ "ref_audio_1", "song.mp3", "audio/mpeg", "ID3" },
FormPart{ "ref_video_1", "tail.mp4", "video/mp4", "ftyp" },
FormPart{ "ref_image_1", "a.png", "image/png", "png" } };
HttpResponse r = v.f->srv->router().dispatch(q);
REQUIRE_EQ(r.status, 200);
const gen::VideoRequest& g = v.gen.last();
REQUIRE_EQ(g.refs.size(), (size_t)5);
CHECK_EQ((int)g.refs[0].kind, (int)gen::VideoRefMedia::IMAGE);
CHECK_EQ(g.refs[0].index, 1);
CHECK_EQ(g.refs[0].name, std::string("ref_image_1"));
CHECK_EQ(g.refs[0].data, std::string("png"));
CHECK_EQ((int)g.refs[1].kind, (int)gen::VideoRefMedia::IMAGE);
CHECK_EQ(g.refs[1].index, 2);
CHECK_EQ((int)g.refs[2].kind, (int)gen::VideoRefMedia::VIDEO);
CHECK_EQ(g.refs[2].filename, std::string("tail.mp4"));
CHECK_EQ(g.refs[2].data, std::string("ftyp"));
CHECK_EQ((int)g.refs[3].kind, (int)gen::VideoRefMedia::VIDEO_AUDIO);
CHECK_EQ(g.refs[3].index, 1);
CHECK_EQ((int)g.refs[4].kind, (int)gen::VideoRefMedia::AUDIO);
CHECK_EQ(g.refs[4].filename, std::string("song.mp3"));
json o = json::parse(r.body, nullptr, false);
CHECK_EQ(str_at(o, "task"), std::string("ref2va"));
REQUIRE(o["refs"].is_array());
REQUIRE_EQ(o["refs"].size(), (size_t)5);
CHECK_EQ(o["refs"][0].get<std::string>(), std::string("ref_image_1"));
CHECK_EQ(o["refs"][4].get<std::string>(), std::string("ref_audio_1"));
v.wait(str_at(o, "id"));
}
/* ref2va with a vision encoder loaded: the pictures are decoded and processed, then presented
* between the template's head and the prompt — each `<Picture k>: ` label (its own tokenised
* string) followed by the picture's token run, in part order — and the placed media rides the
* request to the generator (docs/PORT-REF2VA.md §3's presentation order). */
TEST(ref2va_pictures_are_presented_before_the_prompt) {
FakeMultimodal mm;
mm.expand = { 900, 901, 902 };
FakeVideoGen gen;
std::unique_ptr<Fixture> f(new Fixture(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
d.videos = &gen;
d.mm = &mm;
o.video_model = true;
} }));
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "a fox" },
FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" },
FormPart{ "ref_image_2", "b.png", "image/png", "PB" },
FormPart{ "ref_image_1", "a.png", "image/png", "PA" } };
HttpResponse r = f->srv->router().dispatch(q);
REQUIRE_EQ(r.status, 200);
/* Both parts were decoded as images, in presentation order. */
REQUIRE_EQ(mm.got.size(), (size_t)2);
CHECK(mm.got[0].first == MediaKind::Image);
CHECK(mm.got[0].second == std::vector<uint8_t>({ 'P', 'A' }));
CHECK(mm.got[1].second == std::vector<uint8_t>({ 'P', 'B' }));
const gen::VideoRequest& g = gen.last();
REQUIRE(g.media != nullptr);
REQUIRE_EQ(g.media->items.size(), (size_t)2);
CHECK_EQ(g.media->items[0].tok, 16); /* "<v>" + "<Picture 1>: " */
CHECK_EQ(g.media->items[1].tok, 32); /* + the first run + "<Picture 2>: " */
/* The token stream exactly: head, label and run per picture in part order, the prompt last.
* The fake tokenizer turns a character into its code and leaves other ids as sent. */
std::vector<int32_t> want;
auto chars = [&](const std::string& s) {
for (unsigned char c : s) want.push_back((int32_t)c);
};
chars("<v>");
chars("<Picture 1>: ");
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
chars("<Picture 2>: ");
want.insert(want.end(), mm.expand.begin(), mm.expand.end());
chars("a fox");
CHECK(g.tokens == want);
}
/* Everything about the parts that cannot be right is refused naming the part (or `task` when
* the media themselves are the question), before anything is queued. */
TEST(ref2va_requests_are_refused_naming_the_part) {
Videos v;
auto refused = [&](const std::vector<FormPart>& media, const std::string& param) {
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" } };
for (const FormPart& m : media) q.form.push_back(m);
HttpResponse r = v.f->srv->router().dispatch(q);
CHECK_EQ(r.status, 400);
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"), param);
};
/* The task without any media (and JSON alone cannot carry the bytes). */
refused({}, "task");
CHECK_EQ(v.refused(Videos::body({ { "task", "ref2va" } })), std::string("task"));
/* Empty bytes, an extension the media readers do not take. */
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "" } }, "ref_image_1");
refused({ FormPart{ "ref_image_1", "notes.txt", "text/plain", "x" } }, "ref_image_1");
/* Numbering with a gap or a repeat. */
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "x" },
FormPart{ "ref_image_3", "b.png", "image/png", "x" } }, "ref_image_2");
refused({ FormPart{ "ref_image_1", "a.png", "image/png", "x" },
FormPart{ "ref_image_1", "b.png", "image/png", "y" } }, "ref_image_1");
/* A soundtrack with no video of its number; ten images over the API's nine. */
refused({ FormPart{ "ref_video_audio_1", "s.wav", "audio/wav", "x" } }, "ref_video_audio_1");
{
std::vector<FormPart> ten;
for (int i = 1; i <= 10; ++i)
ten.push_back(FormPart{ "ref_image_" + std::to_string(i), "p.png", "image/png", "x" });
refused(ten, "ref_image_10");
}
/* Reference files with no task, and with t2va: the task is the mistake. */
for (const char* task : { (const char*)nullptr, "t2va" }) {
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" } };
if (task) q.form.push_back(FormPart{ "task", "", "", task });
q.form.push_back(FormPart{ "ref_image_1", "a.png", "image/png", "x" });
HttpResponse r = v.f->srv->router().dispatch(q);
CHECK_EQ(r.status, 400);
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"),
std::string("task"));
}
/* The caps ride the capability block /v1/models and /server_info share, so a client can
* gate on them without probing a refusal. This fake declares 9/3/3 and a 64-token prompt,
* all at or under the API's caps, so the declaration shows through. */
auto caps = [&](json* out) {
HttpRequest mq;
mq.method = "GET";
mq.path = "/v1/models";
HttpResponse mr = v.f->srv->router().dispatch(mq);
CHECK_EQ(mr.status, 200);
*out = json::parse(mr.body, nullptr, false)["data"][0]["capabilities"];
};
json c;
caps(&c);
CHECK_EQ(c["video_generation"], true);
CHECK_EQ(c["video_max_text"], 64);
CHECK_EQ(c["video_max_ref_images"], 9);
CHECK_EQ(c["video_max_ref_videos"], 3);
CHECK_EQ(c["video_max_ref_audios"], 3);
/* A model that declares no reference media does not take the task at all. */
v.gen.inf.max_ref_images = v.gen.inf.max_ref_videos = v.gen.inf.max_ref_audios = 0;
HttpRequest q;
q.method = "POST";
q.path = "/v1/videos";
q.form = { FormPart{ "prompt", "", "", "a fox" }, FormPart{ "size", "", "", "256x256" },
FormPart{ "task", "", "", "ref2va" },
FormPart{ "ref_image_1", "a.png", "image/png", "x" } };
HttpResponse r = v.f->srv->router().dispatch(q);
CHECK_EQ(r.status, 400);
CHECK_EQ(str_at(json::parse(r.body, nullptr, false)["error"], "param"), std::string("task"));
CHECK_EQ(v.gen.got.size(), (size_t)0); /* nothing was ever queued */
/* And the caps the model now reports match what it refuses: zero counts say the same thing
* the refusal does, before a client spends a request on it. */
caps(&c);
CHECK_EQ(c["video_max_ref_images"], 0);
CHECK_EQ(c["video_max_ref_videos"], 0);
CHECK_EQ(c["video_max_ref_audios"], 0);
CHECK_EQ(c["video_max_text"], 64);
}
RAD_TEST_MAIN()
+53 -1
View File
@@ -34,6 +34,7 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <cstring>
@@ -145,6 +146,20 @@ void usage() {
" --changed FILE with --reuse: checkpoint tensors (one name a line) that differ from\n"
" the checkpoint the --reuse container was converted from. Every\n"
" weight that reads one is converted; the rest are copied\n"
" --lora FILE|DIR a PEFT adapter (.safetensors file or directory of them) merged\n"
" into the checkpoint tensors it names before they are converted:\n"
" W + strength * (alpha/r where the adapter states one) * B @ A.\n"
" Repeatable, merged in the order given; each merged tensor joins\n"
" the --changed set, so --reuse never copies an unmerged weight\n"
" --lora-strength F\n"
" the strength of every --lora (default 1)\n"
" --lora-map FILE with --lora: a JSON map for adapters trained on module names this\n"
" checkpoint does not use. {\"strip\": [\"prefix\", ...], \"modules\":\n"
" {\"<pat>\": [\"<target>\", ...]}}: a pattern holds at most one '*',\n"
" which matches one run (the block index) and is substituted into\n"
" every target; several targets mean the module is their concate-\n"
" nation (a fused qkv), and the adapter's rows split along them\n"
" in the order listed\n"
" --in-place with --reuse: EXTEND that container instead of writing a new one.\n"
" Its weights stay where they are; new ones are written past its\n"
" end and the header last. Refused when a weight it holds would\n"
@@ -191,6 +206,9 @@ int main(int argc, char** argv) {
int report_n = 20;
bool verbose = false, plan_only = false, list_quant = false;
std::string reuse_path, changed_path;
std::vector<std::string> lora_paths;
double lora_strength = 1.0;
std::string lora_map;
bool in_place = false;
int kv_dtype = RAD_DT_INVALID;
std::vector<std::pair<std::string, std::string>> set_kv;
@@ -233,6 +251,18 @@ int main(int argc, char** argv) {
else if (a == "--report") report_n = (int)num("--report", 0, INT32_MAX);
else if (a == "--reuse") reuse_path = next("--reuse");
else if (a == "--changed") changed_path = next("--changed");
else if (a == "--lora") lora_paths.push_back(next("--lora"));
else if (a == "--lora-strength") {
const char* v = next("--lora-strength");
char* end = nullptr;
lora_strength = std::strtod(v, &end);
if (!end || *end || end == v) {
std::fprintf(stderr, "rad-convert: --lora-strength wants a number, got '%s'\n",
v);
return 2;
}
}
else if (a == "--lora-map") lora_map = next("--lora-map");
else if (a == "--in-place") in_place = true;
else if (a == "--kv-cache-dtype") {
const std::string v = next("--kv-cache-dtype");
@@ -291,6 +321,16 @@ int main(int argc, char** argv) {
"weight cannot be replaced in place)\n");
return 2;
}
if (!lora_paths.empty() && in_place) {
std::fprintf(stderr, "rad-convert: --lora merges into the source, whose weights "
"--in-place copies from --reuse unchanged; convert to a new file\n");
return 2;
}
if (!lora_map.empty() && lora_paths.empty()) {
std::fprintf(stderr, "rad-convert: --lora-map renames the modules --lora merges; give "
"a --lora to go with it\n");
return 2;
}
if (in_place) {
if (reuse_path.empty()) {
std::fprintf(stderr, "rad-convert: --in-place extends the container --reuse names\n");
@@ -378,6 +418,17 @@ int main(int argc, char** argv) {
return 1;
}
}
/* Adapters merge into the source tensors before anything reads them -- the declare's
* name-map probes, every weight's plan, every quantiser -- and each merged tensor joins
* the changed set: --reuse matches on how a weight was converted, not on its source
* bytes, so without the mark it would copy back exactly the bytes the merge moved. */
for (const std::string& lp : lora_paths) {
std::vector<std::string> merged;
if (ck.add_lora(lp, lora_strength, &merged,
lora_map.empty() ? nullptr : &lora_map) < 0)
return 1;
for (std::string& m : merged) changed.insert(std::move(m));
}
/* --in-place inherits the container's radiance.* keys (the convert-time choices its weights
* were made under), except `radiance.encoder`, which this run derives. */
int inherited = 0;
@@ -852,7 +903,8 @@ int main(int argc, char** argv) {
if (!changed_read.count(n)) unread.push_back(n);
if (!unread.empty()) {
std::sort(unread.begin(), unread.end());
RAD_ERR("--changed names %zu tensor(s) no weight of this conversion reads, e.g. '%s'",
RAD_ERR("the changed set (--changed and merged adapters) names %zu tensor(s) no "
"weight of this conversion reads, e.g. '%s'",
unread.size(), unread[0].c_str());
w.abort();
return 1;