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

+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()