diff --git a/abi/rad_builder.h b/abi/rad_builder.h index b2a709b1..ff0c968e 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -999,6 +999,26 @@ typedef struct RadVideoGenDecl { * body-scale gap between pre_block and mean_proj. Trailing since ABI 23 with the fields above. */ rad_buf dbg_ae_amb; int64_t dbg_ae_amb_bytes; + /* The video encoder's RAW (pre-fold) latent: an f32 PERSIST twin of the bf16 quant_conv output + * b_eq2. Read with R4D_ENC_SEL=q2 on the video pass; splits a latent-scale gap between the + * encoder convs (norm_out/conv_out/quant_conv) and the fixed-norm fold -- the video analogue of + * dbg_ae_amb. Trailing since ABI 23 with the fields above. */ + rad_buf dbg_ve_q2; + int64_t dbg_ve_q2_bytes; + /* The video encoder's conv_out output (b_eq48) as an f32 PERSIST twin, read with R4D_ENC_SEL=q48; + * splits a raw-latent gain between conv_out (present here) and quant_conv (only in dbg_ve_q2). */ + rad_buf dbg_ve_q48; + int64_t dbg_ve_q48_bytes; + /* The video encoder's norm_out output (v_lv[5].b) as an f32 PERSIST twin, read with + * R4D_ENC_SEL=nout (or included in =all); splits a raw-latent gain between norm_out's own weight + * (present here) and the convs after it. */ + rad_buf dbg_ve_nout; + int64_t dbg_ve_nout_bytes; + /* The video encoder's norm_out INPUT (v_lv[5].a, the trunk) as an f32 PERSIST twin, read with + * R4D_ENC_SEL=all; with dbg_ve_nout it lets the norm's statistics be tested whole-volume vs + * per-frame (the reference is TemporalIsolatedGroupNorm, per-frame). Trailing debug field. */ + rad_buf dbg_ve_trunk; + int64_t dbg_ve_trunk_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 92f335ae..e7ea6ded 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -520,6 +520,32 @@ struct Model { std::string ve_pix_mul, ve_pix_add, ve_fold_mul, ve_fold_add; /* pixel and latent norms */ rad_buf b_epix32 = 0, b_epix = 0, b_eq48 = 0, b_eq2 = 0, b_egn = 0; rad_buf b_evc = 0; /* [kEncSlotsV * kEncSlotRowsV, kPatchVals] f32 PERSIST */ + /* A persistent f32 twin of the quant_conv output (b_eq2), written by a debug-only cast op so the + * R4D_ENC stage readback can observe the RAW (pre-fold) encoder latent reliably. b_eq2 itself is + * bf16 arena scratch whose readback lags the pass (the audio b_ax2 lesson); an f32 PERSIST copy is + * not arena-recycled, so it reads back true -- exactly the role b_amb plays for the audio encoder. + * [kEncMaxSide-sized R[5], 48] f32 PERSIST. Debug-only, gated on R4D_ENC_SEL=q2. */ + rad_buf b_evq2 = 0; + rad_op op_ve_q2 = 0; + int64_t ve_q2_bytes = 0; + /* The same f32 shadow for the conv_out output (b_eq48), so a raw-latent gain can be split between + * conv_out (already present in b_eq48) and quant_conv (only in b_eq2). Debug-only, R4D_ENC_SEL=q48. */ + rad_buf b_evq48 = 0; + rad_op op_ve_q48 = 0; + int64_t ve_q48_bytes = 0; + /* The same f32 shadow for the norm_out output (v_lv[5].b), so a raw-latent gain can be split + * between norm_out's own weight (present here) and the convs after it. [R[5], dims[5]] f32. */ + rad_buf b_vnout = 0; + rad_op op_ve_noutdbg = 0; + int64_t ve_nout_bytes = 0; + /* The same f32 shadow for norm_out's INPUT (v_lv[5].a, the trunk the norm reads). With the norm + * output also shadowed, one request shows whether norm_out's statistics are whole-volume over + * every temporal slot (the reference's is per-frame, TemporalIsolatedGroupNorm): recompute the + * per-frame and whole-volume norms of this trunk and see which one the shadow of v_lv[5].b equals. + * Debug-only, R4D_ENC_SEL=all. */ + rad_buf b_vtrunk = 0; + rad_op op_ve_trunkdbg = 0; + int64_t ve_trunk_bytes = 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, @@ -2302,6 +2328,40 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_NOWEIGHTS), { m.b_eq2 }, { m.b_evc }); if (!m.op_ve_nout || !m.op_ve_cout || !m.op_ve_q || !m.op_ve_fold) return RAD_E_INVAL; + /* Debug-only f32 shadow of the raw (pre-fold) quant_conv output, so the generator can read the + * encoder's latent BEFORE the fixed-norm fold and tell whether a latent-scale gap enters above + * the fold (encoder convs) or is introduced by the fold itself. A cast, not a math change. */ + m.b_evq2 = decl_b(b, nm.f("venc.q2dbg"), RAD_F32, { R[5], 48 }, RAD_BUF_PERSIST); + m.op_ve_q2 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("n", 48), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_eq2 }, { m.b_evq2 }); + m.b_evq48 = decl_b(b, nm.f("venc.q48dbg"), RAD_F32, { R[5], 48 }, RAD_BUF_PERSIST); + m.op_ve_q48 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("n", 48), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_eq48 }, { m.b_evq48 }); + if (!m.op_ve_q2 || !m.op_ve_q48) return RAD_E_INVAL; + m.ve_q2_bytes = m.ve_q48_bytes = (int64_t)R[5] * 48 * 4; + m.b_vnout = decl_b(b, nm.f("venc.noutdbg"), RAD_F32, { R[5], (int64_t)dims[5] }, RAD_BUF_PERSIST); + m.op_ve_noutdbg = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("n", (int64_t)dims[5]), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.v_lv[5].b }, { m.b_vnout }); + if (!m.op_ve_noutdbg) return RAD_E_INVAL; + m.ve_nout_bytes = (int64_t)R[5] * (int64_t)dims[5] * 4; + /* The norm_out input, so its own statistics can be tested against the shadowed output. */ + m.b_vtrunk = decl_b(b, nm.f("venc.trunkdbg"), RAD_F32, { R[5], (int64_t)dims[5] }, RAD_BUF_PERSIST); + m.op_ve_trunkdbg = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("n", (int64_t)dims[5]), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { 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; return RAD_OK; } @@ -2912,6 +2972,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.dbg_ae_mp_bytes = m.aenc ? (int64_t)(kEncSlotRowsA / kAudioCh) * kAudioC * 4 : 0; d.dbg_ae_pre = m.b_ax2; /* bf16, hence the *2 */ d.dbg_ae_pre_bytes = m.aenc ? (int64_t)(kEncSlotRowsA / kAudioCh) * kAudioC * 2 : 0; + /* The video encoder's RAW (pre-fold) latent: an f32 PERSIST twin of the bf16 quant_conv + * output b_eq2. Reading it back splits a latent-scale gap between the encoder convs + * (norm_out/conv_out/quant_conv) and the fixed-norm fold -- the video analogue of the + * audio dbg_ae_amb. R4D_ENC_SEL=q2 on the video pass selects it. Debug-only. */ + d.dbg_ve_q2 = m.b_evq2; + d.dbg_ve_q2_bytes = m.venc ? m.ve_q2_bytes : 0; + d.dbg_ve_q48 = m.b_evq48; + d.dbg_ve_q48_bytes = m.venc ? m.ve_q48_bytes : 0; + d.dbg_ve_nout = m.b_vnout; + 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; } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -3618,12 +3690,16 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { } } const int64_t R5 = (int64_t)g[12] * g[13] * g[14]; + RAD_ISSUE_N(c, m.op_ve_trunkdbg, R5, brows(m.v_lv[5].a, R5), brows(m.b_vtrunk, R5)); /* shadow */ RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob), RAD_NONE, st, brows(m.v_lv[5].b, R5)); + RAD_ISSUE_N(c, m.op_ve_noutdbg, R5, brows(m.v_lv[5].b, R5), brows(m.b_vnout, R5)); /* shadow */ RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw), RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5)); RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5], RAD_NONE, brows(m.b_eq2, R5)); + RAD_ISSUE_N(c, m.op_ve_q2, R5, brows(m.b_eq2, R5), brows(m.b_evq2, R5)); /* debug shadow */ + RAD_ISSUE_N(c, m.op_ve_q48, R5, brows(m.b_eq48, R5), brows(m.b_evq48, R5)); /* debug shadow */ const int64_t flat = last ? short_last : full; RAD_ISSUE_N(c, m.op_ve_fold, flat * ppc, bcol(m.b_eq2, 0, kC, flat * (H / kVaeRatio) * (W / kVaeRatio)), diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 99859d5c..be75a2b4 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -1238,20 +1238,43 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) { * bf16 b_ax2 is arena-rotated scratch whose readback can lag the pass (b_amb2 is finite while * b_ax2 dumps ±1e38 -- a stale read), so the f32 b_amb is what to trust for the pre_block * value. The video pass and the default audio pass are untouched; only an env var selects. */ - const char* sel = audio ? std::getenv("R4D_ENC_SEL") : nullptr; - const bool mp = sel && std::strcmp(sel, "mp") == 0 && decl_.dbg_ae_mp_bytes > 0; - const bool amb = sel && std::strcmp(sel, "amb") == 0 && decl_.dbg_ae_amb_bytes > 0; - const bool pre = sel && std::strcmp(sel, "pre") == 0 && decl_.dbg_ae_pre_bytes > 0; - const rad_buf h = mp ? decl_.dbg_ae_mp : amb ? decl_.dbg_ae_amb : pre ? decl_.dbg_ae_pre - : 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 - : audio ? decl_.dbg_enca_bytes : decl_.dbg_evc_bytes; - enc_dbg_sel_ = mp ? "mp" : amb ? "amb" : pre ? "pre" : ""; + const char* sel = std::getenv("R4D_ENC_SEL"); + const bool mp = sel && audio && std::strcmp(sel, "mp") == 0 && decl_.dbg_ae_mp_bytes > 0; + const bool amb = sel && audio && std::strcmp(sel, "amb") == 0 && decl_.dbg_ae_amb_bytes > 0; + const bool pre = sel && audio && std::strcmp(sel, "pre") == 0 && decl_.dbg_ae_pre_bytes > 0; + 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; + /* "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; enc_dbg_used_ = 0; - if (h && n > 0) { - rb_.assign(1, Readback{h, n, enc_dbg_host_}); - enc_dbg_used_ = n; + 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; + 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}; + enc_dbg_sel_ = "all"; + enc_dbg_used_ = nt + nn + n48 + n2; + } 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 + : 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 + : audio ? decl_.dbg_enca_bytes : decl_.dbg_evc_bytes; + enc_dbg_sel_ = mp ? "mp" : amb ? "amb" : pre ? "pre" : nout ? "nout" : q48 ? "q48" : q2 ? "q2" : ""; + if (h && n > 0) { + rb_.assign(1, Readback{h, n, enc_dbg_host_}); + enc_dbg_used_ = n; + } } } return &out_[0]; @@ -1269,7 +1292,18 @@ int VideoDriver::done() { case RAD_GEN_PASS_VENCODE: case RAD_GEN_PASS_AENCODE: /* The media's latents are now in the lane's slot rows; take the next reference, if any. */ - if (enc_dbg_ && enc_dbg_used_ > 0) { + 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; + 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); + } else if (enc_dbg_ && enc_dbg_used_ > 0) { const int64_t nf = enc_dbg_used_ / 4; const float* z = reinterpret_cast(enc_dbg_host_); uint64_t h = 1469598103934665603ULL; /* FNV-1a over the readback bytes */ @@ -1284,8 +1318,9 @@ int VideoDriver::done() { if (a > mx) mx = a; sum += z[i]; } - std::string tagstr = pass_.kind != RAD_GEN_PASS_AENCODE ? "evc" - : *enc_dbg_sel_ ? std::string("enc") + enc_dbg_sel_ : std::string("enca"); + std::string tagstr = pass_.kind != RAD_GEN_PASS_AENCODE + ? (*enc_dbg_sel_ ? std::string("evc") + enc_dbg_sel_ : std::string("evc")) + : (*enc_dbg_sel_ ? std::string("enc") + enc_dbg_sel_ : std::string("enca")); const char* tag = tagstr.c_str(); RAD_ERR("enc_dbg %s: fnv %016llx floats %lld nonzero %lld maxabs %.6g " "sum %.6g head[%.6g %.6g %.6g %.6g]", diff --git a/docs/NOTE-REF2VA.md b/docs/NOTE-REF2VA.md index b381d394..347d93ce 100644 --- a/docs/NOTE-REF2VA.md +++ b/docs/NOTE-REF2VA.md @@ -381,3 +381,47 @@ as point 6 / point 4. Nothing here claims to match ComfyUI's timings. denoise consumes the audio reference too, not just its count. Reproduction scripts: `refdet.sh` (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) + +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). + +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). + +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. + +**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. diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 5d909ea7..3796b76e 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -683,6 +683,14 @@ ABI_FIELD(RadVideoGenDecl, dbg_ae_pre) ABI_FIELD(RadVideoGenDecl, dbg_ae_pre_bytes) ABI_FIELD(RadVideoGenDecl, dbg_ae_amb) ABI_FIELD(RadVideoGenDecl, dbg_ae_amb_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_q2) +ABI_FIELD(RadVideoGenDecl, dbg_ve_q2_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ve_q48) +ABI_FIELD(RadVideoGenDecl, dbg_ve_q48_bytes) +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_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 db17b7ba..a56dd9e3 100644 --- a/tests/data/ref2va/ref_venc_parity.py +++ b/tests/data/ref2va/ref_venc_parity.py @@ -253,6 +253,215 @@ def do_parity(m, evc_f, encpx_f, encg_f, slot): return 0 if rf < floor else 1 +def ref_encoder_out(m, encpx, H, W, which): + """The reference RAW (pre-fold) latent values at a tail stage, as a value multiset (order-free). + 'nout' -> the norm_out output (silu(GroupNorm(h))) at the last level, ALL dims[5]=1024 channels + (h, the conv_out input, is captured by a forward hook; conv_out applies pre_norm inside). + 'q48' -> the conv_out output (encoder(x)), 48ch; first 24 = mu. + 'q2' -> the quant_conv output (moments), 48ch; first 24 = raw mu. + Each is exactly what the corresponding device f32 shadow (b_vnout/b_evq48/b_evq2) holds, so a gain + that is already present at 'nout' points at norm_out itself, one that first appears at 'q48' points + at conv_out, and one that first appears at 'q2' points at quant_conv.""" + 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 + cap = {} + def hook(mod, inp, out): + cap["h"] = inp[0] + hk = m.encoder.conv_out.register_forward_hook(hook) + try: + with torch.no_grad(): + x = m._normalize_pixels(x) + out = m.encoder(x) # conv_out output, [1,48,1,H/16,W/16] + if which == "q2": + out = m.quant_conv(out) # moments + if which == "trunk": + return cap["h"].float().reshape(-1).double().numpy() # norm_out INPUT (level-5 stream) + if which == "nout": + h = cap["h"] # the level-5 stream feeding conv_out + no = m.encoder.norm_out + g = F.group_norm(h.float(), no.num_groups, no.weight.float(), no.bias.float(), + eps=no.eps) # T==1: TemporalIsolated == plain GroupNorm + out = F.silu(g) # [1,1024,1,H/16,W/16] + return out.reshape(-1).double().numpy() + finally: + hk.remove() + out = out[:, :, -1:, :, :] # T==1 keep-last + mu = out.float()[:, :KC, ...] # first 24 channels = the latent mean + return mu.reshape(-1).double().numpy() + + +def do_stage_raw(m, dev_f, encpx_f, encg_f, which): + """Compare a device f32 shadow against the reference RAW latent at the same stage, to localise + where the ~0.37 network gain enters.""" + gd = np.fromfile(encg_f, dtype=np.int32) + H, W = int(gd[1]), int(gd[2]) + short_last = int(gd[18]) + if int(gd[23]) != 1: + sys.exit("these raw stages target a single reference IMAGE (T_pad=1)") + encpx = np.fromfile(encpx_f, dtype=np.float32).reshape(int(gd[23]), H, W, 3) + ref = ref_encoder_out(m, encpx[0], H, W, which) + rows = short_last * (H // KVAE_RATIO) * (W // KVAE_RATIO) # real rows the device wrote + ncol = 1024 if which == "nout" else 48 + sh = np.fromfile(dev_f, dtype=np.float32).reshape(-1, ncol) + dev = sh[:rows] if which == "nout" else sh[:rows, :KC] # nout: all 1024; mu: first 24 + if dev.size != ref.size: + sys.exit(f"device shadow region {dev.size} != reference {ref.size} (rows={rows}, ncol={ncol})") + rf, mx = rel_frobenius_sorted(dev.reshape(-1), ref) + sa, sb = np.sort(dev.reshape(-1)), 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"[{which}] device shadow 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"(gain {'PRESENT here' if abs(aa-1.0) > 0.1 else 'already ~1.0 here'})") + + +def _gn_on(trunk, w, b, G, eps, per_frame_rows): + """GroupNorm over a [rows, C] trunk. per_frame_rows>0 -> recompute statistics every that many + rows (per temporal frame, the reference's TemporalIsolatedGroupNorm); 0 -> one whole-volume + statistic over all rows (what the device group_norm kernel does, M=ry over the full buffer).""" + t = torch.from_numpy(trunk).double() # [rows, C] + rows, C = t.shape + w = torch.from_numpy(w).double(); b = torch.from_numpy(b).double() + cpg = C // G + tg = t.reshape(rows, G, cpg) # per row: G groups of cpg channels + if per_frame_rows: + nf = rows // per_frame_rows + # statistics over each frame's (per_frame_rows x cpg) block, per group + blocks = tg.reshape(nf, per_frame_rows, G, cpg) + mu = blocks.mean(dim=(1, 3), keepdim=True) + var = blocks.var(dim=(1, 3), unbiased=False, keepdim=True) + rstd = 1.0 / torch.sqrt(var + eps) + normed = (blocks - mu) * rstd + tg = normed.reshape(rows, G, cpg) + else: + mu = tg.mean(dim=(0, 2), keepdim=True) + var = tg.var(dim=(0, 2), unbiased=False, keepdim=True) + rstd = 1.0 / torch.sqrt(var + eps) + tg = (tg - mu) * rstd + y = tg.reshape(rows, C) * w + b + return (y * torch.sigmoid(y)).numpy() # SiLU + + +def do_gn_extent(m, trunk_f, nout_f, encpx_f, encg_f): + """Is the device norm_out whole-volume (over every temporal slot it materialises) while the + reference is per-frame? Dump the trunk (v_lv[5].a) AND its shadowed norm_out output, recompute + both statistics modes on the device's OWN trunk, and see which reproduces the device output -- + and which reproduces the reference. Confines a T==1 latent-scale gain to the norm extent (#20).""" + gd = np.fromfile(encg_f, np.int32) + H, W = int(gd[1]), int(gd[2]) + if int(gd[23]) != 1: + sys.exit("this test targets a single reference IMAGE (T_pad=1)") + C = 1024 + PF = (H // KVAE_RATIO) * (W // KVAE_RATIO) # rows per latent frame + trunk = np.fromfile(trunk_f, np.float32).reshape(-1, C) + nout = np.fromfile(nout_f, np.float32).reshape(-1, C) + nrow = trunk.shape[0] + ntf = nrow // PF # temporal frames the device materialised + no = m.encoder.norm_out + w = no.weight.float().double().detach().numpy(); b = no.bias.float().double().detach().numpy() + G = int(no.num_groups); eps = float(no.eps) + # reference trunk (norm_out input) -- reference processes 1 frame -> PF rows + encpx = np.fromfile(encpx_f, np.float32).reshape(1, H, W, 3) + ref_trunk = ref_encoder_out(m, encpx[0], H, W, "trunk") + ref_nout = ref_encoder_out(m, encpx[0], H, W, "nout") + print(f"device trunk rows={nrow} = {ntf} frames x PF={PF}; norm groups={G} eps={eps} C={C}") + rf_t, _ = rel_frobenius_sorted(trunk[:PF].reshape(-1), ref_trunk) + print(f"[A] device trunk frame0 vs reference trunk : relFro={rf_t:.3e} " + f"(dev std={trunk[:PF].std():.4f} ref std={ref_trunk.std():.4f})") + pred_whole = _gn_on(trunk, w, b, G, eps, 0) + pred_frame = _gn_on(trunk[:PF], w, b, G, eps, 0) # per-frame == whole on the single-frame slice + for name, pred, target in (("device nout", pred_whole[:PF], nout[:PF]), + ("reference nout", pred_frame[:PF], ref_nout)): + rf, _ = rel_frobenius_sorted(pred.reshape(-1), target.reshape(-1)) + print(f"[B] whole-volume-GN(trunk frame0) vs {name:14s}: relFro={rf:.3e}") + # and the per-frame reading of the device output: does the DEVICE output match a per-frame norm? + rf_dev_frame, _ = rel_frobenius_sorted(pred_frame.reshape(-1), nout[:PF].reshape(-1)) + print(f"[C] per-frame-GN(trunk frame0) vs device nout frame0: relFro={rf_dev_frame:.3e}") + print(" reading: [B device nout ~0] => device norm is WHOLE-VOLUME over all " + f"{ntf} frames; [B reference nout ~0] => reference is PER-FRAME; if both, the fix is " + "per-frame norm statistics (matches TemporalIsolatedGroupNorm).") + + +def do_expand_test(m, trunk_f, encpx_f, encg_f): + """Is the trunk divergence just the device's T==1->clip temporal EXPANSION (replicate the image + across the clip, temporal-downsample) rather than a trunk kernel/weight bug? Feed the reference the + image replicated to N frames; if its (per-frame-normed) trunk std drops to the device's, the whole + gap is the staging geometry, not the convs.""" + gd = np.fromfile(encg_f, np.int32) + H, W = int(gd[1]), int(gd[2]) + C = 1024 + PF = (H // KVAE_RATIO) * (W // KVAE_RATIO) + trunk = np.fromfile(trunk_f, np.float32).reshape(-1, C) + ntf = trunk.shape[0] // PF + encpx = np.fromfile(encpx_f, np.float32).reshape(1, H, W, 3)[0] + + def ref_trunk_std(nframes, keep): + px = torch.from_numpy(encpx).permute(2, 0, 1) # [3,H,W] + px = px.unsqueeze(0).unsqueeze(2).repeat(1, 1, nframes, 1, 1) # [1,3,nframes,H,W] + x = px.float() * (2.0 / 255.0) - 1.0 + cap = {} + hk = m.encoder.conv_out.register_forward_hook(lambda md, i, o: cap.__setitem__("h", i[0])) + try: + with torch.no_grad(): + x = m._normalize_pixels(x); m.encoder(x) + finally: + hk.remove() + h = cap["h"].float() # [1,1024,T,H/16,W/16] + t = h.shape[2] + fr = h[:, :, (t - 1) if keep == "last" else 0, ...] # one frame + return t, fr.reshape(-1).double().numpy() + + dev_f0 = trunk[:PF]; dev_fl = trunk[-PF:] + print(f"device trunk: {ntf} frames x PF={PF}; frame0 std={dev_f0.std():.4f} " + f"last-frame std={dev_fl.std():.4f}") + for n in (1, 4, 8, 17): + for keep in ("first", "last"): + t, r = ref_trunk_std(n, keep) + rf0, _ = rel_frobenius_sorted(r, dev_f0.reshape(-1)) + rfl, _ = rel_frobenius_sorted(r, dev_fl.reshape(-1)) + print(f" ref N={n:2d} -> T_out={t} keep={keep:5s}: std={r.std():.4f} " + f"relFro vs dev-frame0={rf0:.3e} vs dev-last={rfl:.3e}") + print(" reading: if some (N,keep) gives relFro ~0 to the device frame, the trunk gap is purely " + "the T==1 clip EXPANSION (staging), not the convs.") + + +def do_zeropad_test(m, trunk_f, encpx_f, encg_f): + """Confirm the single-frame trunk dilution: the device stages a picture as frame0 in a zero-padded + clip, so its temporal downsamplers average over ZERO future slots. Feed the reference a + [real,0,0,...] clip and see whether its frame0 trunk drops to the device's std / matches it. + Host-only; the decisive golden comparison for the temporal-padding root cause (no device change).""" + gd = np.fromfile(encg_f, np.int32) + H, W = int(gd[1]), int(gd[2]) + C = 1024 + PF = (H // KVAE_RATIO) * (W // KVAE_RATIO) + trunk = np.fromfile(trunk_f, np.float32).reshape(-1, C) + ntf = trunk.shape[0] // PF + encpx = np.fromfile(encpx_f, np.float32).reshape(1, H, W, 3)[0] + dev_f0 = trunk[:PF] + print(f"device trunk {ntf} frames x PF={PF}: frame0 std={dev_f0.std():.4f} last std={trunk[-PF:].std():.4f}") + px = torch.from_numpy(encpx).permute(2, 0, 1) # [3,H,W] + for n in (1, 2, 5, 9, 17): + clip = torch.zeros(1, 3, n, H, W) + clip[0, :, 0] = px.float() * (2.0 / 255.0) - 1.0 # real frame0, zeros after + cap = {} + hk = m.encoder.conv_out.register_forward_hook(lambda md, i, o: cap.__setitem__("h", i[0])) + try: + with torch.no_grad(): + x = m._normalize_pixels(clip); m.encoder(x) + finally: + hk.remove() + h = cap["h"].float() # [1,1024,T,H/16,W/16] + t = h.shape[2] + f0 = h[:, :, 0, ...].reshape(-1).double().numpy() + rf0, _ = rel_frobenius_sorted(f0, dev_f0.reshape(-1)) + print(f" ref clip N={n:2d} -> T_out={t}: frame0 std={f0.std():.4f} relFro vs dev-frame0={rf0:.3e}") + print(" reading: a ~0 relFro / matching std means the reference on a zero-padded clip reproduces " + "the device => the gap is the single-frame temporal DILUTION (device averages zeros).") + + 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. @@ -283,13 +492,44 @@ def main(): ap.add_argument("--encpx", help="staged enc_pixels readback (f32, [T_pad, H, W, 3])") ap.add_argument("--encg", help="staged enc_geom readback (i32, 25)") ap.add_argument("--slot", type=int, default=1) + 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("--evctrunk", help="device f32 shadow of the norm_out input v_lv[5].a (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", + help="with --evctrunk: feed the reference a [real,0,...] clip to confirm temporal dilution") ap.add_argument("--selftest", action="store_true") a = ap.parse_args() m = load_encoder() if a.selftest: sys.exit(do_selftest(m)) + if a.zeropad: + 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.expand: + if not (a.evctrunk and a.encpx and a.encg): + sys.exit("--expand needs --evctrunk, --encpx and --encg") + sys.exit(do_expand_test(m, a.evctrunk, a.encpx, a.encg)) + if a.evctrunk: + if not (a.evcnout and a.encpx and a.encg): + sys.exit("--evctrunk needs --evcnout, --encpx and --encg") + sys.exit(do_gn_extent(m, a.evctrunk, a.evcnout, a.encpx, a.encg)) + if a.evcq2 or a.evcq48 or a.evcnout: + if not (a.encpx and a.encg): + sys.exit("raw-latent stages need --encpx and --encg too") + # print the tail chain in order so a gain's entry point is visible top-to-bottom + if a.evcnout: + do_stage_raw(m, a.evcnout, a.encpx, a.encg, "nout") + if a.evcq48: + do_stage_raw(m, a.evcq48, a.encpx, a.encg, "q48") + if a.evcq2: + do_stage_raw(m, a.evcq2, a.encpx, a.encg, "q2") + sys.exit(0) if not (a.evc and a.encpx and a.encg): - sys.exit("give --evc, --encpx and --encg (or --selftest)") + sys.exit("give --evc, --encpx and --encg (or --evcq2/--evcq48, or --selftest)") sys.exit(do_parity(m, a.evc, a.encpx, a.encg, a.slot))