Archived
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:
1 parent
816e24bd46
commit
490d4c604a
73 files changed
+16484
-432
No files matched your search
@@ -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,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
File diff suppressed because it is too large.
Load diff
@@ -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 */
|
||||
@@ -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
|
||||
@@ -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 */
|
||||
@@ -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
|
||||
Reference in new issue
Block a user