diff --git a/abi/rad_builder.h b/abi/rad_builder.h index ff0c968e..d52dc99f 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1019,6 +1019,24 @@ typedef struct RadVideoGenDecl { * per-frame (the reference is TemporalIsolatedGroupNorm, per-frame). Trailing debug field. */ rad_buf dbg_ve_trunk; int64_t dbg_ve_trunk_bytes; + /* frame-0 of the video encoder's conv_in output (v_lv[0].a) as an f32 PERSIST twin, read with + * R4D_ENC_SEL=cin; tests whether the trunk deficit is already present at conv_in (confined to the + * pixel/conv_in stage) or accumulates across the spatial downsamplers. Trailing debug field. */ + rad_buf dbg_ve_cin; + int64_t dbg_ve_cin_bytes; + /* frame-0 of each level's post-resnet output (v_lv[0..4].a) as an f32 PERSIST twin, read with + * R4D_ENC_SEL=all; with cin and trunk they bisect which stage introduces the trunk deficit. + * Trailing debug fields. */ + rad_buf dbg_ve_l0; + int64_t dbg_ve_l0_bytes; + rad_buf dbg_ve_l1; + int64_t dbg_ve_l1_bytes; + rad_buf dbg_ve_l2; + int64_t dbg_ve_l2_bytes; + rad_buf dbg_ve_l3; + int64_t dbg_ve_l3_bytes; + rad_buf dbg_ve_l4; + int64_t dbg_ve_l4_bytes; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index e7ea6ded..a9eb6538 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -546,6 +546,19 @@ struct Model { rad_buf b_vtrunk = 0; rad_op op_ve_trunkdbg = 0; int64_t ve_trunk_bytes = 0; + /* The first stage only: frame-0 of the conv_in output (v_lv[0].a), cast to f32, to test whether the + * structural trunk deficit is already present at conv_in (=> confined to the pixel/conv_in stage) or + * accumulates across the spatial downsamplers (=> shared downsample kernels). A single frame, so + * [PF[0], dims[0]] f32 ~= 33 MB. Debug-only, R4D_ENC_SEL=cin. */ + rad_buf b_vcin = 0; + rad_op op_ve_cindbg = 0; + int64_t ve_cin_bytes = 0; + /* Frame-0 of each level's post-resnet output (v_lv[1..4].a), cast to f32, to bisect which spatial + * downsample introduces the trunk deficit (conv_in and the deepest trunk already pinned: 0.999 and + * 0.49). frame-0 shrinks fast spatially, so all four together stay small. Debug-only, R4D_ENC_SEL=all. */ + rad_buf b_vl[6] = { 0 }; + rad_op op_ve_ldbg[6] = { 0 }; + int64_t ve_l_bytes[6] = { 0 }; /* ---- the audio VAE encoder, when the container carries it. f32 like its decoder: per * channel one sequence, conv_in and five strided blocks of three [snake, conv7, snake, @@ -2362,6 +2375,30 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { { m.v_lv[5].a }, { m.b_vtrunk }); if (!m.op_ve_trunkdbg) return RAD_E_INVAL; m.ve_trunk_bytes = (int64_t)R[5] * (int64_t)dims[5] * 4; + /* conv_in's output, first frame only (the buffer is frame-major, so frame 0 is the first PF[0] rows). */ + m.b_vcin = decl_b(b, nm.f("venc.cindbg"), RAD_F32, { PF[0], (int64_t)dims[0] }, RAD_BUF_PERSIST); + m.op_ve_cindbg = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, PF[0]), RAD_INT("n", (int64_t)dims[0]), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.v_lv[0].a }, { m.b_vcin }); + if (!m.op_ve_cindbg) return RAD_E_INVAL; + m.ve_cin_bytes = (int64_t)PF[0] * (int64_t)dims[0] * 4; + /* Post-resnet output of each intermediate level (v_lv[1..4].a), first frame only. Frame 0 shrinks + * as the spatial map downsamples, so these stay small; together with the trunk and cin they bisect + * which spatial downsample introduces the trunk's ~0.49x deficit. */ + for (int L = 0; L < 5; L++) { + char tag[32]; + snprintf(tag, sizeof tag, "venc.l%ddbg", L); + m.b_vl[L] = decl_b(b, nm.f(tag), RAD_F32, { PF[L], (int64_t)dims[L] }, RAD_BUF_PERSIST); + m.op_ve_ldbg[L] = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, PF[L]), RAD_INT("n", (int64_t)dims[L]), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.v_lv[L].a }, { m.b_vl[L] }); + if (!m.op_ve_ldbg[L]) return RAD_E_INVAL; + m.ve_l_bytes[L] = (int64_t)PF[L] * (int64_t)dims[L] * 4; + } return RAD_OK; } @@ -2984,6 +3021,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.dbg_ve_nout_bytes = m.venc ? m.ve_nout_bytes : 0; d.dbg_ve_trunk = m.b_vtrunk; d.dbg_ve_trunk_bytes = m.venc ? m.ve_trunk_bytes : 0; + d.dbg_ve_cin = m.b_vcin; + d.dbg_ve_cin_bytes = m.venc ? m.ve_cin_bytes : 0; + d.dbg_ve_l0 = m.b_vl[0]; d.dbg_ve_l0_bytes = m.venc ? m.ve_l_bytes[0] : 0; + d.dbg_ve_l1 = m.b_vl[1]; d.dbg_ve_l1_bytes = m.venc ? m.ve_l_bytes[1] : 0; + d.dbg_ve_l2 = m.b_vl[2]; d.dbg_ve_l2_bytes = m.venc ? m.ve_l_bytes[2] : 0; + d.dbg_ve_l3 = m.b_vl[3]; d.dbg_ve_l3_bytes = m.venc ? m.ve_l_bytes[3] : 0; + d.dbg_ve_l4 = m.b_vl[4]; d.dbg_ve_l4_bytes = m.venc ? m.ve_l_bytes[4] : 0; } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -3659,6 +3703,8 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, m.op_ve_pcast, R0, brows(m.b_epix32, R0), brows(m.b_epix, R0)); RAD_ISSUE_N(c, m.op_ve_cin, R0, brows(m.b_epix, R0), RAD_W(m.ve_cinw), RAD_W(m.ve_cinb), gg[0], RAD_NONE, brows(m.v_lv[0].a, R0)); + RAD_ISSUE_N(c, m.op_ve_cindbg, (int64_t)g[1] * g[2], + brows(m.v_lv[0].a, R0), brows(m.b_vcin, (int64_t)g[1] * g[2])); /* frame-0 shadow */ for (int L = 0; L < 6; ++L) { const Model::VEncLevel& E = m.v_lv[(size_t)L]; const int64_t R = (int64_t)g[kVOrg[L]] * g[kVOrg[L] + 1] * g[kVOrg[L] + 2]; @@ -3667,13 +3713,16 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { const Model::VEncBlock& B = E.blk[blk]; const bool f0 = blk == 0 && sc; const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b; - /* norm1 over the whole volume, SiLU'd; on a shortcut level that is `in` itself, - * in place, and the shortcut convolves the result into `a`. */ - RAD_ISSUE_N(c, B.op_n1, R, brows(xa, R), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st, - brows(nb, R)); + /* The shortcut convolves the RAW input -- the reference folds the channel change as + * `x = nin_shortcut(x)` before any norm touches x, and adds that to conv2's output. + * So it MUST be issued before norm1, which normalises `in` IN PLACE for conv1; issuing + * the shortcut after norm1 fed it silu(norm1(x)) instead of x, shrinking the residual + * term on every shortcut level (a ~0.45x trunk deficit, fixed here). */ if (f0) RAD_ISSUE_N(c, E.op_sc, R, brows(E.in, R), RAD_W(E.scw), RAD_W(E.scb), gg[L], RAD_NONE, brows(E.a, R)); + RAD_ISSUE_N(c, B.op_n1, R, brows(xa, R), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st, + brows(nb, R)); RAD_ISSUE_N(c, B.op_c1, R, brows(nb, R), RAD_W(B.c1w), RAD_W(B.c1b), gg[L], RAD_NONE, brows(E.c, R)); RAD_ISSUE_N(c, B.op_n2, R, brows(E.c, R), RAD_W(B.n2w), RAD_W(B.n2b), RAD_NONE, st, @@ -3681,6 +3730,10 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, B.op_c2, R, brows(E.b, R), RAD_W(B.c2w), RAD_W(B.c2b), gg[L], brows(E.a, R), brows(E.a, R)); } + if (L <= 4 && m.op_ve_ldbg[L]) { /* frame-0 post-resnet shadow (levels 0..4) */ + const int64_t pf = (int64_t)g[kVOrg[L] + 1] * g[kVOrg[L] + 2]; + RAD_ISSUE_N(c, m.op_ve_ldbg[L], pf, brows(E.a, R), brows(m.b_vl[L], pf)); + } if (L < 4) { const Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; const int64_t RX = (int64_t)g[3 * (L + 1)] * g[3 * (L + 1) + 1] * g[3 * (L + 1) + 2]; diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index be75a2b4..07a0bbc0 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -290,7 +290,13 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, * decl_.dbg_* or touches enc_dbg_host_. */ if (std::getenv("R4D_ENC_DEBUG") && (decl_.dbg_enca_bytes > 0 || decl_.dbg_evc_bytes > 0)) { - enc_dbg_bytes_ = std::max(decl_.dbg_enca_bytes, decl_.dbg_evc_bytes); + /* The slab must hold the largest single shadow AND the full "all" multi-shadow slab. */ + const int64_t all_sum = decl_.dbg_ve_trunk_bytes + decl_.dbg_ve_nout_bytes + + decl_.dbg_ve_q48_bytes + decl_.dbg_ve_q2_bytes + + decl_.dbg_ve_l0_bytes + decl_.dbg_ve_l1_bytes + + decl_.dbg_ve_l2_bytes + decl_.dbg_ve_l3_bytes + decl_.dbg_ve_l4_bytes; + enc_dbg_bytes_ = std::max( + { decl_.dbg_enca_bytes, decl_.dbg_evc_bytes, decl_.dbg_ve_cin_bytes, all_sum }); enc_dbg_host_ = static_cast(rad_dev_alloc(enc_dbg_bytes_, RAD_MEM_HOST_PINNED)); enc_dbg_ = enc_dbg_host_ != nullptr; if (!enc_dbg_) @@ -1245,32 +1251,46 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) { const bool q2 = sel && !audio && std::strcmp(sel, "q2") == 0 && decl_.dbg_ve_q2_bytes > 0; const bool q48 = sel && !audio && std::strcmp(sel, "q48") == 0 && decl_.dbg_ve_q48_bytes > 0; const bool nout = sel && !audio && std::strcmp(sel, "nout") == 0 && decl_.dbg_ve_nout_bytes > 0; + const bool cin = sel && !audio && std::strcmp(sel, "cin") == 0 && decl_.dbg_ve_cin_bytes > 0; /* "all" reads the three video shadows back in ONE pass into one slab (nout | q48 | q2), so a * single request localises a latent-scale gain across norm_out / conv_out / quant_conv. */ const bool all = sel && !audio && std::strcmp(sel, "all") == 0 && decl_.dbg_ve_trunk_bytes > 0 && decl_.dbg_ve_nout_bytes > 0 && - decl_.dbg_ve_q48_bytes > 0 && decl_.dbg_ve_q2_bytes > 0; + decl_.dbg_ve_q48_bytes > 0 && decl_.dbg_ve_q2_bytes > 0 && + decl_.dbg_ve_l0_bytes > 0 && decl_.dbg_ve_l1_bytes > 0 && + decl_.dbg_ve_l2_bytes > 0 && decl_.dbg_ve_l3_bytes > 0 && + decl_.dbg_ve_l4_bytes > 0; enc_dbg_used_ = 0; if (all && enc_dbg_bytes_ >= decl_.dbg_ve_trunk_bytes + decl_.dbg_ve_nout_bytes + - decl_.dbg_ve_q48_bytes + decl_.dbg_ve_q2_bytes) { - const int64_t nt = decl_.dbg_ve_trunk_bytes, nn = decl_.dbg_ve_nout_bytes; - const int64_t n48 = decl_.dbg_ve_q48_bytes, n2 = decl_.dbg_ve_q2_bytes; + decl_.dbg_ve_q48_bytes + decl_.dbg_ve_q2_bytes + + decl_.dbg_ve_l0_bytes + decl_.dbg_ve_l1_bytes + + decl_.dbg_ve_l2_bytes + decl_.dbg_ve_l3_bytes + decl_.dbg_ve_l4_bytes) { + /* One slab, fixed order: trunk | nout | q48 | q2 | l0 | l1 | l2 | l3 | l4. */ + const rad_buf hh[9] = { decl_.dbg_ve_trunk, decl_.dbg_ve_nout, decl_.dbg_ve_q48, + decl_.dbg_ve_q2, decl_.dbg_ve_l0, decl_.dbg_ve_l1, + decl_.dbg_ve_l2, decl_.dbg_ve_l3, decl_.dbg_ve_l4 }; + const int64_t nn[9] = { decl_.dbg_ve_trunk_bytes, decl_.dbg_ve_nout_bytes, + decl_.dbg_ve_q48_bytes, decl_.dbg_ve_q2_bytes, + decl_.dbg_ve_l0_bytes, decl_.dbg_ve_l1_bytes, + decl_.dbg_ve_l2_bytes, decl_.dbg_ve_l3_bytes, decl_.dbg_ve_l4_bytes }; char* p = enc_dbg_host_; - rb_.assign(4, Readback{decl_.dbg_ve_trunk, nt, p}); - rb_[1] = Readback{decl_.dbg_ve_nout, nn, p + nt}; - rb_[2] = Readback{decl_.dbg_ve_q48, n48, p + nt + nn}; - rb_[3] = Readback{decl_.dbg_ve_q2, n2, p + nt + nn + n48}; + int64_t off = 0; + rb_.clear(); + for (int i = 0; i < 9; ++i) { rb_.push_back(Readback{ hh[i], nn[i], p + off }); off += nn[i]; } enc_dbg_sel_ = "all"; - enc_dbg_used_ = nt + nn + n48 + n2; + enc_dbg_used_ = off; } else { const rad_buf h = mp ? decl_.dbg_ae_mp : amb ? decl_.dbg_ae_amb : pre ? decl_.dbg_ae_pre : nout ? decl_.dbg_ve_nout : q48 ? decl_.dbg_ve_q48 : q2 ? decl_.dbg_ve_q2 + : cin ? decl_.dbg_ve_cin : audio ? decl_.dbg_enca : decl_.dbg_evc; const int64_t n = mp ? decl_.dbg_ae_mp_bytes : amb ? decl_.dbg_ae_amb_bytes : pre ? decl_.dbg_ae_pre_bytes : nout ? decl_.dbg_ve_nout_bytes : q48 ? decl_.dbg_ve_q48_bytes : q2 ? decl_.dbg_ve_q2_bytes + : cin ? decl_.dbg_ve_cin_bytes : audio ? decl_.dbg_enca_bytes : decl_.dbg_evc_bytes; - enc_dbg_sel_ = mp ? "mp" : amb ? "amb" : pre ? "pre" : nout ? "nout" : q48 ? "q48" : q2 ? "q2" : ""; + enc_dbg_sel_ = mp ? "mp" : amb ? "amb" : pre ? "pre" : nout ? "nout" : q48 ? "q48" : q2 ? "q2" + : cin ? "cin" : ""; if (h && n > 0) { rb_.assign(1, Readback{h, n, enc_dbg_host_}); enc_dbg_used_ = n; @@ -1293,16 +1313,21 @@ int VideoDriver::done() { case RAD_GEN_PASS_AENCODE: /* The media's latents are now in the lane's slot rows; take the next reference, if any. */ if (enc_dbg_ && enc_dbg_used_ > 0 && enc_dbg_sel_ && std::strcmp(enc_dbg_sel_, "all") == 0) { - /* Four shadows in one slab (trunk | nout | q48 | q2) -> four files. */ - const int64_t nt = decl_.dbg_ve_trunk_bytes, nn = decl_.dbg_ve_nout_bytes; - const int64_t n48 = decl_.dbg_ve_q48_bytes, n2 = decl_.dbg_ve_q2_bytes; + /* Nine shadows in one slab -> nine files. */ + const char* nm8[9] = { "evctrunk", "evcnout", "evcq48", "evcq2", + "evcl0", "evcl1", "evcl2", "evcl3", "evcl4" }; + const int64_t nn8[9] = { decl_.dbg_ve_trunk_bytes, decl_.dbg_ve_nout_bytes, + decl_.dbg_ve_q48_bytes, decl_.dbg_ve_q2_bytes, + decl_.dbg_ve_l0_bytes, decl_.dbg_ve_l1_bytes, + decl_.dbg_ve_l2_bytes, decl_.dbg_ve_l3_bytes, decl_.dbg_ve_l4_bytes }; char* p = enc_dbg_host_; - enc_dbg_dump_file("evctrunk", p, (size_t)nt); - enc_dbg_dump_file("evcnout", p + nt, (size_t)nn); - enc_dbg_dump_file("evcq48", p + nt + nn, (size_t)n48); - enc_dbg_dump_file("evcq2", p + nt + nn + n48, (size_t)n2); - RAD_ERR("enc_dbg all: dumped trunk %lld + nout %lld + q48 %lld + q2 %lld bytes", - (long long)nt, (long long)nn, (long long)n48, (long long)n2); + int64_t off = 0; + for (int i = 0; i < 9; ++i) { + enc_dbg_dump_file(nm8[i], p + off, (size_t)nn8[i]); + off += nn8[i]; + } + RAD_ERR("enc_dbg all: dumped %lld bytes across trunk/nout/q48/q2/l0/l1/l2/l3/l4", + (long long)off); } else if (enc_dbg_ && enc_dbg_used_ > 0) { const int64_t nf = enc_dbg_used_ / 4; const float* z = reinterpret_cast(enc_dbg_host_); diff --git a/docs/NOTE-REF2VA.md b/docs/NOTE-REF2VA.md index 347d93ce..4b706234 100644 --- a/docs/NOTE-REF2VA.md +++ b/docs/NOTE-REF2VA.md @@ -382,46 +382,50 @@ as point 6 / point 4. Nothing here claims to match ComfyUI's timings. (video-ref determinism + content-control), `chain.sh` (tail-as-`ref_video` chaining), `fullshape.sh` (this max-shape control) under the build tree. -## #14 video-encoder value-parity — localized, not fixed (2026-10-19) +## #14 video-encoder value-parity — **RESOLVED** (2026-10-19): shortcut-after-norm1 ordering bug -The video/image VAE encoder is **device-live, deterministic and content-sensitive** (all three reference -kinds proven), but it is **not numerically equal to the ComfyUI fp16 reference**: for a 256×256 picture the -folded latent sits at roughly **0.37× the reference's scale** with a large **structural** residual. This is -the honest, still-open half of #14 (strict parity = #10/P6). This pass **localized** the gap and — finding no -confined, golden-verifiable defect — stopped short of a fix, per the standing rule against blind-fixing the -shared encoder kernels (they serve the live image and plain paths too). +The video/image VAE encoder was device-live and content-sensitive but its folded latent sat at roughly +**0.49× the reference's scale** with a large structural residual. Root cause found and **fixed**: in +`step_venc`, the shortcut convolution was issued **after** norm1, which normalizes the shortcut level's +input **in place**. So on every shortcut level (a level whose `cout != cin` — levels 1 and 3 here) the +residual was fed `silu(norm1(x))` instead of the **raw** `x` the reference uses +(`ResnetBlock3D.forward`: `x = self.nin_shortcut(x)` before any norm, added to conv2's output). Feeding the +normalized value into the 1×1 shortcut systematically shrank the residual term, giving the ~0.49× structural +deficit that accumulated from the first shortcut level down the trunk. The fix reorders the issue so +`op_sc` reads the raw `in` **before** `op_n1` overwrites it (`arch/minimaxh3/minimaxh3.cpp`, the `f0` +branch of the level/block loop). This is an op *reorder*, not a kernel change, and it corrects the **shared** +trunk — so it fixes the **image** encoder's fidelity too. -Method: **device-input-anchored** — feed the reference the device's own staged pixels (`encpx`), so -preprocessing cancels, and read the device's own intermediates back through `R4D_ENC_SEL=all` f32 PERSIST -shadows of the encoder tail (`trunk` = `v_lv[5].a`, `nout` = `v_lv[5].b`, `q48` = `conv_out` out, `q2` = -`quant_conv` out). Harness: `tests/data/ref2va/ref_venc_parity.py` (`--evctrunk/--evcnout`, `--expand`, -`--zeropad`). A 256×256 image encodes to `R[5]=tf[5]·PF[5]=5·256` trunk rows (the clip geometry keeps five -temporal slots even for a single frame). +**Method that cracked it — a frame-0 per-level bisection.** Extended `R4D_ENC_SEL=all` to dump, in one pass, +frame-0 f32 PERSIST shadows of *every* level's post-resnet output `v_lv[0..4].a` (fields `dbg_ve_l0..l4`) +alongside the existing tail (`trunk/nout/q48/q2`). Frame-0 shrinks fast spatially so all four level shadows +plus the trunk stay ~68 MB in one host slab. The reference side (`ref_level_outs`) captures `h` after each +level's block loop and before its downsample, on the device's **own** staged pixels. The std ratio walked the +deficit to its exact entry point: -What was **exonerated**, each against the reference on the device's own inputs: -- **Input normalization** — the device's first op `(px/255 − mean)/std` is *identical* to the reference - `_normalize_pixels(px·2/255−1)`, and `kVaePixelMean/Std` equal `IMAGENET_MEAN/STD` byte-for-byte, so the - trunk comparison is clean (not a preprocessing artifact). -- **`norm_out`** — faithful. Recomputing GroupNorm on the device trunk with the container's weight reproduces - the shadowed `nout` to `relFro 1.6e-3`; the gain is *already present in the trunk* it reads. -- **GroupNorm extent (was task #20)** — the device is **already per-frame**, matching the reference's - `TemporalIsolatedGroupNorm`: per-frame statistics reproduce device `nout` (1.6e-3); whole-volume gives - 1.457. Whole-volume-vs-per-frame is **not** the cause; no change needed. -- **Temporal handling** — the reference's frame-0 trunk std is a flat **8.986** at clip lengths 1, 2, 5, 9, - 17 under *both* frame-replication and zero-padding (a causal frame 0 sees only itself), while the device's - frame-0 trunk std is **4.40** and its last frame is exactly **0.0**. So the device's deficit is **not** a - temporal-expansion or zero-dilution effect; temporal staging is excluded. -- **A single confined multiplicative gain** — ruled out: after per-group normalization removes every group - scale, device `nout` still differs from the reference by **0.57 non-affinely**, so the trunk gap is - **structural**, not one mis-scaled factor to undo. -- **Weight precision** — ruled out: the video-encoder tensors were *not* in the convert log's worst-20 - (those were all `aenc.*` at ~1.6e-3 relative Frobenius), so the encoder weights are correctly rounded. +| stage | pre-fix ratio | post-fix ratio | +|---|---|---| +| conv_in out (frame0) | 0.999 | 0.999 | +| L0 post-resnet | 0.999 | 0.999 | +| **L1 post-resnet** | **0.455** | **1.000** | +| L2 | 0.466 | 1.000 | +| L3 | 0.380 | 1.000 | +| L4 | 0.331 | 1.000 | +| norm_out / conv_out / quant_conv (raw mu) | ~0.49 | **1.000 / 1.000 / 0.998** | -**Where it is.** A ~0.49× systematic, **structural** deviation on the deepest trunk activation, present at a -*causally-isolated* frame (so independent of temporal extent), with correct weights and a faithful tail — -i.e. in the **spatial** trunk (conv_in / resnet blocks / spatial downsampling) or its bf16 implicit-GEMM -kernels. Pinpointing it further means dumping every level's trunk and auditing each spatial kernel against -the reference — a multi-round device investigation whose fix would land in kernels shared by the live image -and plain encode paths. That is exactly the blind-fix hazard the workflow rule forbids without a confined, -golden-verifiable defect in hand, so it is left **open and precisely bounded**: #14-video = spatial-trunk -value-parity, #20 closed (norm already per-frame), temporal/GN/norm-out/input-norm all excluded. +conv_in and level-0 (no shortcut) stay faithful; the drop appears *exactly* at level 1 (first shortcut level) +— pinpointing the shortcut as the culprit, not the downsample, not a spatial kernel, not bf16 GEMM (the trunk +convs run **host-only** in this config anyway — `conv3d_ndhwc` resolves to a host kernel). Post-fix every +stage matches the reference to the **bf16 precision floor** (`relFro ~3–4e-3`, affine `1.000·ref + 0.000`). + +What the earlier pass had already correctly **exonerated** (still true, and why the bisection was the right +cut — the gap was upstream of all of them, at the shortcut): input normalization (byte-identical to +`_normalize_pixels`); `norm_out` (GroupNorm on the device trunk reproduces `nout` to 1.6e-3); GroupNorm extent +(was task #20 — device is **already per-frame**, matching `TemporalIsolatedGroupNorm`; no change); temporal +staging (a causal frame-0 sees only itself — excluded); weight precision (venc not in the convert worst-20). +The "structural spatial trunk / needs a golden box" read from the prior pass was wrong: it *was* structural, +but confined to one op-order, and the frame-0 bisection made it golden-verifiable. + +**Verified device-live**: a single-image `ref2va` encode generated cleanly with the fix loaded, and all level +shadows + the full tail now read ratio ~1.0 against the reference. Strict end-to-end numeric parity of the +whole pipeline (benchmarks, multi-frame) remains #10/P6. #20 stays closed (norm already per-frame). diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 3796b76e..07582204 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -691,6 +691,18 @@ ABI_FIELD(RadVideoGenDecl, dbg_ve_nout) ABI_FIELD(RadVideoGenDecl, dbg_ve_nout_bytes) ABI_FIELD(RadVideoGenDecl, dbg_ve_trunk) ABI_FIELD(RadVideoGenDecl, dbg_ve_trunk_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_cin) +ABI_FIELD(RadVideoGenDecl, dbg_ve_cin_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l0) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l0_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l1) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l1_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l2) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l2_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l3) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l3_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l4) +ABI_FIELD(RadVideoGenDecl, dbg_ve_l4_bytes) ABI_STRUCT(RadVideoGeom) ABI_FIELD(RadVideoGeom, n_text) ABI_FIELD(RadVideoGeom, frames) diff --git a/tests/data/ref2va/ref_venc_parity.py b/tests/data/ref2va/ref_venc_parity.py index a56dd9e3..dee2e3ea 100644 --- a/tests/data/ref2va/ref_venc_parity.py +++ b/tests/data/ref2va/ref_venc_parity.py @@ -268,6 +268,15 @@ def ref_encoder_out(m, encpx, H, W, which): def hook(mod, inp, out): cap["h"] = inp[0] hk = m.encoder.conv_out.register_forward_hook(hook) + if which == "cin": # conv_in OUTPUT (first stage), T==1 + hk.remove() + hk2 = m.encoder.conv_in.register_forward_hook(lambda md, i, o: cap.__setitem__("h", o)) + try: + with torch.no_grad(): + x = m._normalize_pixels(x); m.encoder(x) + finally: + hk2.remove() + return cap["h"].float().reshape(-1).double().numpy() try: with torch.no_grad(): x = m._normalize_pixels(x) @@ -462,6 +471,88 @@ def do_zeropad_test(m, trunk_f, encpx_f, encg_f): "the device => the gap is the single-frame temporal DILUTION (device averages zeros).") +def do_cin(m, dev_f, encpx_f, encg_f): + """conv_in output (first stage), frame-0, vs the reference's conv_in output on the same pixels. + If the ~0.49x deficit is ALREADY here it is confined to the pixel/conv_in stage (fixable); if it + matches (~1.0) the deficit accumulates downstream in the resnet blocks / spatial downsamplers.""" + gd = np.fromfile(encg_f, np.int32) + H, W = int(gd[1]), int(gd[2]) + if int(gd[23]) != 1: + sys.exit("conv_in stage targets a single reference IMAGE (T_pad=1)") + encpx = np.fromfile(encpx_f, np.float32).reshape(int(gd[23]), H, W, 3) + ref = ref_encoder_out(m, encpx[0], H, W, "cin") + dev = np.fromfile(dev_f, np.float32).reshape(-1) # frame-0: PF0 x dims0, all channels + if dev.size != ref.size: + sys.exit(f"conv_in shadow {dev.size} != reference {ref.size} (expect {H * W * 128}); " + "dims0/dump size?") + rf, mx = rel_frobenius_sorted(dev, ref) + sa, sb = np.sort(dev), np.sort(ref) + A = np.vstack([sb, np.ones_like(sb)]).T + (aa, bb), *_ = np.linalg.lstsq(A, sa, rcond=None) + resid = sa - (aa * sb + bb) + rf_aff = float(np.linalg.norm(resid)) / (float(np.linalg.norm(sb)) + 1e-12) + print(f"[cin] conv_in output (frame0) device vs reference: values={dev.size}") + print(f" sorted relFro={rf:.3e} maxabs={mx:.3e} dev std={dev.std():.4f} ref std={ref.std():.4f}") + print(f" affine dev ~ {aa:.4f}*ref {bb:+.4f} residual-after-affine={rf_aff:.3e} " + f"(std ratio dev/ref={dev.std() / ref.std():.3f})") + print(f" reading: std ratio ~1.0 => conv_in faithful, deficit accumulates downstream; " + f"~0.49 => the defect is at conv_in / pixel stage.") + + +def ref_level_outs(m, encpx, H, W): + """Reference h captured AFTER each level's resnet block loop and BEFORE that level's downsample, + for levels 1..4 -- exactly what the device frame-0 shadows b_vl[1..4] hold (v_lv[L].a post-resnet). + Order-free, so the device's spatial-major layout vs the reference's channel-major layout is fine.""" + px = torch.from_numpy(encpx).permute(2, 0, 1).unsqueeze(0).unsqueeze(2) # [1,3,1,H,W] + x = px.float() * (2.0 / 255.0) - 1.0 + outs = {} + with torch.no_grad(): + x = m._normalize_pixels(x) + enc = m.encoder + h = enc.conv_in(x) + for i in range(enc.num_levels): + for b in enc.down[i].block: + h = b(h) + if 0 <= i <= 4: + outs[i] = h.float().reshape(-1).double().numpy() + if hasattr(enc.down[i], "downsample"): + h = enc.down[i].downsample(h) + return outs + + +def do_levels(m, dev_files, encpx_f, encg_f): + """Per-level frame-0 device shadows (evcl1..evcl4) vs the reference level outputs on the SAME + pixels. The level where the std ratio first drops from ~1.0 toward 0.49 localises the structural + deficit to that level's resnet blocks or to the spatial downsample entering it.""" + gd = np.fromfile(encg_f, np.int32) + H, W = int(gd[1]), int(gd[2]) + if int(gd[23]) != 1: + sys.exit("level shadows target a single reference IMAGE (T_pad=1)") + encpx = np.fromfile(encpx_f, np.float32).reshape(int(gd[23]), H, W, 3) + refs = ref_level_outs(m, encpx[0], H, W) + print(f"[levels] frame-0 post-resnet, device vs reference (order-free)") + for L in range(0, 5): + f = dev_files[L] + if not f: + continue + dev = np.fromfile(f, np.float32).reshape(-1) + ref = refs[L] + if dev.size != ref.size: + print(f" L{L}: SKIP size dev={dev.size} ref={ref.size}") + continue + rf, mx = rel_frobenius_sorted(dev, ref) + sa, sb = np.sort(dev), np.sort(ref) + A = np.vstack([sb, np.ones_like(sb)]).T + (aa, bb), *_ = np.linalg.lstsq(A, sa, rcond=None) + resid = sa - (aa * sb + bb) + rf_aff = float(np.linalg.norm(resid)) / (float(np.linalg.norm(sb)) + 1e-12) + ratio = dev.std() / (ref.std() + 1e-12) + print(f" L{L}: n={dev.size} std dev={dev.std():.4f} ref={ref.std():.4f} ratio={ratio:.3f} " + f"relFro={rf:.3e} maxabs={mx:.3e} affine {aa:.3f}*ref{bb:+.3f} resid={rf_aff:.3e}") + print(" reading: the FIRST level whose ratio drops below ~1.0 (relative to the one before it) is " + "where the deficit enters -- that level's resnet blocks, or the downsample feeding it.") + + def do_selftest(m): """No device: build a 'device' region from the reference itself (perfect) and two corruptions (a dropped normalisation, and a spread-collapse), and confirm the sorted metric reads ~0 and gross. @@ -495,7 +586,13 @@ def main(): ap.add_argument("--evcq2", help="device f32 shadow of the quant_conv output b_eq2 (R4D_ENC_SEL=q2)") ap.add_argument("--evcq48", help="device f32 shadow of the conv_out output b_eq48 (R4D_ENC_SEL=q48)") ap.add_argument("--evcnout", help="device f32 shadow of the norm_out output b_vnout (R4D_ENC_SEL=nout)") + ap.add_argument("--evccin", help="device f32 shadow of conv_in output frame0 b_vcin (R4D_ENC_SEL=cin)") ap.add_argument("--evctrunk", help="device f32 shadow of the norm_out input v_lv[5].a (R4D_ENC_SEL=all)") + ap.add_argument("--evcl0", help="device f32 shadow of level-0 post-resnet frame0 (R4D_ENC_SEL=all)") + ap.add_argument("--evcl1", help="device f32 shadow of level-1 post-resnet frame0 (R4D_ENC_SEL=all)") + ap.add_argument("--evcl2", help="device f32 shadow of level-2 post-resnet frame0 (R4D_ENC_SEL=all)") + ap.add_argument("--evcl3", help="device f32 shadow of level-3 post-resnet frame0 (R4D_ENC_SEL=all)") + ap.add_argument("--evcl4", help="device f32 shadow of level-4 post-resnet frame0 (R4D_ENC_SEL=all)") ap.add_argument("--expand", action="store_true", help="with --evctrunk: test whether the trunk gap is just the T==1 clip expansion") ap.add_argument("--zeropad", action="store_true", @@ -509,6 +606,15 @@ def main(): if not (a.evctrunk and a.encpx and a.encg): sys.exit("--zeropad needs --evctrunk, --encpx and --encg") sys.exit(do_zeropad_test(m, a.evctrunk, a.encpx, a.encg)) + if a.evcl0 or a.evcl1 or a.evcl2 or a.evcl3 or a.evcl4: + if not (a.encpx and a.encg): + sys.exit("level shadows need --encpx and --encg") + sys.exit(do_levels(m, {0: a.evcl0, 1: a.evcl1, 2: a.evcl2, 3: a.evcl3, 4: a.evcl4}, + a.encpx, a.encg)) + if a.evccin: + if not (a.encpx and a.encg): + sys.exit("--evccin needs --encpx and --encg") + sys.exit(do_cin(m, a.evccin, a.encpx, a.encg)) if a.expand: if not (a.evctrunk and a.encpx and a.encg): sys.exit("--expand needs --evctrunk, --encpx and --encg")