diff --git a/abi/rad_builder.h b/abi/rad_builder.h index e3fc97b8..b2a709b1 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -983,6 +983,22 @@ typedef struct RadVideoGenDecl { int64_t dbg_enca_bytes; rad_buf dbg_evc; int64_t dbg_evc_bytes; + /* The audio mean_proj OUTPUT (b_amb2), i.e. the latent BEFORE the fixed (z-mean)/std norm — + * the mono, last-channel slice of it. Read only when R4D_ENC_MP names it in place of b_enca, + * to split whether a latent-scale gap is introduced by the body or by the norm op. Trailing + * since ABI 23 with the fields above: an older plugin declares none and keeps the 0 default. */ + rad_buf dbg_ae_mp; + int64_t dbg_ae_mp_bytes; + /* The audio pre_block OUTPUT (b_ax2), one stage before mean_proj; bf16, the mono last channel. + * Read only when R4D_ENC_SEL=pre, to split a body-scale gap between pre_block and mean_proj. + * Trailing since ABI 23 with the fields above. */ + rad_buf dbg_ae_pre; + int64_t dbg_ae_pre_bytes; + /* The audio mean_proj INPUT (b_amb), i.e. the pre_block output cast to f32. Read with + * R4D_ENC_SEL=amb: it is the reliable f32 twin of the arena-rotated bf16 b_ax2, and splits a + * 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; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 862970d8..92f335ae 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -2898,6 +2898,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.dbg_enca_bytes = m.aenc ? (int64_t)kEncSlotsA * kEncSlotRowsA * kAudioC * 4 : 0; d.dbg_evc = m.b_evc; d.dbg_evc_bytes = m.venc ? (int64_t)kEncSlotsV * kEncSlotRowsV * kPatchVals * 4 : 0; + /* The audio final chain, for the R4D_ENC_SEL readback dump. All are the mono latent for + * the last channel; one channel's rows = kEncSlotRowsA / kAudioCh. + * dbg_ae_amb -- b_amb, the mean_proj INPUT (pre_block out cast to f32): the RELIABLE + * f32 twin of the arena-rotated bf16 b_ax2 below, so it is the stage to + * read to split a pre_block-vs-mean_proj scale gap. + * dbg_ae_mp -- b_amb2, the mean_proj output (pre-norm latent). + * dbg_ae_pre -- b_ax2, the raw bf16 pre_block buffer; its readback can lag the pass + * (arena-rotated scratch), so prefer dbg_ae_amb for the pre_block value. */ + d.dbg_ae_amb = m.b_amb; + d.dbg_ae_amb_bytes = m.aenc ? (int64_t)(kEncSlotRowsA / kAudioCh) * kAudioC * 4 : 0; + d.dbg_ae_mp = m.b_amb2; + 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; } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -3685,8 +3699,16 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_NONE, brows(m.b_ax6, rows), RAD_W(m.ae_finb)); RAD_ISSUE_N(c, m.op_ae_cast6, rows, brows(m.b_ax6, rows), brows(m.b_apb, rows)); /* The pre-block: the attention over the 2048-wide stream, its eight heads' mean pooled - * to 32 and projected; then the gated MLP, and the two residuals. */ - RAD_ISSUE_N(c, m.p_op_ln3, rows, brows(m.b_apb, rows), RAD_W(m.p_ln3w), RAD_W(m.p_ln3b), + * to 32 and projected; then the gated MLP, and the two residuals. The two 2048-wide + * LayerNorms are NOT interchangeable: the reference AttnProjection.forward (audio_vae.py + * 267) feeds the DOWN-PROJECTION from norm3 and the ATTENTION from norm1. Their learned + * affines differ (norm3 |w|mean 0.60, norm1 0.27), so the projection carries most of the + * block's output magnitude (std 6.6 vs 1.8); feeding them the other way shrinks the whole + * block to ~0.27x and every audio latent downstream with it. Hence the LayerNorm staged + * for the attention below (feeding p_op_qkv) is norm1, and the one staged for the + * projection (feeding p_op_proj) is norm3 -- each consumer reads the norm the reference + * gives it, even though both norms share the same b_aln3 scratch. */ + RAD_ISSUE_N(c, m.p_op_ln1, rows, brows(m.b_apb, rows), RAD_W(m.p_ln1w), RAD_W(m.p_ln1b), brows(m.b_aln3, rows)); RAD_ISSUE_N(c, m.p_op_qkv, rows, brows(m.b_aln3, rows), RAD_W(m.p_qkvw), RAD_W(m.p_qkvb), RAD_NONE, brows(m.b_aqkv, rows)); @@ -3704,7 +3726,7 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, m.p_op_pool, rows, brows(m.b_ahsum, rows), brows(m.b_apool, rows)); RAD_ISSUE_N(c, m.p_op_aproj, rows, brows(m.b_apool, rows), RAD_W(m.p_apw), RAD_W(m.p_apb), RAD_NONE, brows(m.b_a32a, rows)); - RAD_ISSUE_N(c, m.p_op_ln1, rows, brows(m.b_apb, rows), RAD_W(m.p_ln1w), RAD_W(m.p_ln1b), + RAD_ISSUE_N(c, m.p_op_ln3, rows, brows(m.b_apb, rows), RAD_W(m.p_ln3w), RAD_W(m.p_ln3b), brows(m.b_aln3, rows)); RAD_ISSUE_N(c, m.p_op_proj, rows, brows(m.b_aln3, rows), RAD_W(m.p_prw), RAD_W(m.p_prb), RAD_NONE, brows(m.b_eh, rows)); diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 8c58530c..99859d5c 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -1229,8 +1229,25 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) { pass_.kind = kind; pass_.job = j.id; if (enc_dbg_) { - const rad_buf h = audio ? decl_.dbg_enca : decl_.dbg_evc; - const int64_t n = audio ? decl_.dbg_enca_bytes : decl_.dbg_evc_bytes; + /* R4D_ENC_SEL picks which audio-pass buffer the readback names, so one binary can dump the + * whole final chain without a rebuild: "enca" (default, the normalised latent), "mp" (the + * mean_proj output, i.e. the latent before the fixed (z-mean)/std norm), "amb" (the mean_proj + * INPUT -- the pre_block output cast to f32), or "pre" (the raw bf16 pre_block buffer b_ax2). + * The split localises a latent-scale gap: if the gain is already present at "mp"/"amb", the + * norm op is innocent and the body carries it. "amb" is the RELIABLE f32 twin of "pre": the + * 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" : ""; enc_dbg_used_ = 0; if (h && n > 0) { rb_.assign(1, Readback{h, n, enc_dbg_host_}); @@ -1267,13 +1284,14 @@ int VideoDriver::done() { if (a > mx) mx = a; sum += z[i]; } - RAD_ERR("enc_dbg %s slot %d: fnv %016llx floats %lld nonzero %lld maxabs %.6g " + std::string tagstr = pass_.kind != RAD_GEN_PASS_AENCODE ? "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]", - pass_.kind == RAD_GEN_PASS_AENCODE ? "AENCA(b_enca)" : "VENCV(b_evc)", - (int)enc_dbg_used_, (unsigned long long)h, (long long)nf, (long long)nz, + tag, (unsigned long long)h, (long long)nf, (long long)nz, (double)mx, sum, (double)z[0], (double)z[1], (double)z[2], (double)z[3]); - enc_dbg_dump_file(pass_.kind == RAD_GEN_PASS_AENCODE ? "enca" : "evc", - enc_dbg_host_, (size_t)enc_dbg_used_); + enc_dbg_dump_file(tag, enc_dbg_host_, (size_t)enc_dbg_used_); } ++j->enc_next; break; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index 6e7fdd92..01f2d234 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -224,6 +224,7 @@ private: char* enc_dbg_host_ = nullptr; int64_t enc_dbg_bytes_ = 0; /* the slab's capacity */ int64_t enc_dbg_used_ = 0; /* bytes the last encode readback filled */ + const char* enc_dbg_sel_ = ""; /* R4D_ENC_SEL: "", "mp" or "pre" (audio) */ std::vector out_; /* one per rank */ std::vector vout_; diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 599fca56..5d909ea7 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -677,6 +677,12 @@ ABI_FIELD(RadVideoGenDecl, dbg_enca) ABI_FIELD(RadVideoGenDecl, dbg_enca_bytes) ABI_FIELD(RadVideoGenDecl, dbg_evc) ABI_FIELD(RadVideoGenDecl, dbg_evc_bytes) +ABI_FIELD(RadVideoGenDecl, dbg_ae_mp) +ABI_FIELD(RadVideoGenDecl, dbg_ae_mp_bytes) +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_STRUCT(RadVideoGeom) ABI_FIELD(RadVideoGeom, n_text) ABI_FIELD(RadVideoGeom, frames) diff --git a/tests/data/ref2va/ref_aenc_parity.py b/tests/data/ref2va/ref_aenc_parity.py index 7f98a971..42de4a7e 100644 --- a/tests/data/ref2va/ref_aenc_parity.py +++ b/tests/data/ref2va/ref_aenc_parity.py @@ -79,6 +79,35 @@ def ref_latent(model, staged, ch, T): return out[:ch * T].numpy() # used rows only +def ref_pre_norm_z(model, wave_ch, T): + """The reference mean_proj OUTPUT for one mono channel — the latent BEFORE the fixed + (z - latents_mean)/latents_std, exactly what the device's b_amb2 (aenc.mp) holds. encode() folds + the norm into its last line (audio_vae.py:439-442), so we reproduce the stages up to mean_proj + directly: encoder -> pre_block -> mean_proj. wave_ch: f32 [L] (already hop-padded). Returns + [T, 32] (row-major, to match the device's [rows, kAudioC]).""" + x = torch.from_numpy(wave_ch.reshape(1, 1, -1)) # [1, 1, L] + with torch.no_grad(): + h = model.encoder(x) # [1, latent_dim, T] + h = model.pre_block(h.transpose(1, 2)).transpose(1, 2) # [1, 32, T] + z = model.mean_proj(h) # [1, 32, T], pre-norm + return z[0].permute(1, 0).numpy() # [T, 32] + + +def ref_pre_block_out(model, wave_ch, T): + """The reference pre_block (AttnProjection) OUTPUT for one mono channel — one stage before + mean_proj, what the device's b_ax2 (aenc.xfin) holds: encoder -> pre_block, WITHOUT mean_proj.""" + x = torch.from_numpy(wave_ch.reshape(1, 1, -1)) # [1, 1, L] + with torch.no_grad(): + h = model.encoder(x) # [1, latent_dim, T] + h = model.pre_block(h.transpose(1, 2)).transpose(1, 2) # [1, 32, T] + return h[0].permute(1, 0).numpy() # [T, 32] + + +def _read_bf16(f): + u = np.fromfile(f, dtype=np.uint16) + return torch.from_numpy(u).view(torch.bfloat16).float().numpy() + + def slot_row(kind, slot): idx = (slot - 1) if kind == "vaudio" else (3 + slot - 1) return idx * SLOT_ROWS_A @@ -135,6 +164,70 @@ def do_parity(m, enca_f, encsm_f, kind, slot, n): return 0 if rf < floor else 1 +def _affine_report(dev, ref): + """Sorted-multiset relFro + best global affine fit dev ~ a*ref + b. SORTED so it is immune to the + row/channel packing (b_amb2 stores one channel's [rows,32]; the reference mean_proj returns + [32,T] transposed here) — only the value DISTRIBUTION is compared, which is what a scale gap is.""" + sa, sb = np.sort(dev.reshape(-1)), np.sort(ref.reshape(-1)) + if sa.size != sb.size: + sys.exit(f"multiset sizes differ: device {sa.size} vs reference {sb.size}; check T / channel") + rf = float(np.linalg.norm(sa - sb)) / (float(np.linalg.norm(sb)) + 1e-12) + 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) + r2 = 1.0 - float(np.sum(resid ** 2)) / (float(np.sum((sa - sa.mean()) ** 2) + 1e-30)) + return rf, rf_aff, aa, bb, r2 + + +def do_stage(m, dev_f, encsm_f, ch, T, stage): + """Walk the audio final chain backward to localise a latent-scale gap. Each stage compares the + DEVICE buffer (the last channel) against the reference at the SAME stage, pre-norm, so the fixed + (z-mean)/std is excluded and only the network is compared: + amb : device b_amb (f32) vs reference pre_block (AttnProjection) output [reliable] + mp : device b_amb2 (f32) vs reference mean_proj output (the latent before the fixed norm) + pre : device b_ax2 (bf16) vs reference pre_block output — the raw bf16 buffer, whose + readback lags the arena (non-finite stale rows); kept only to show the lag. 'amb' is + its f32 mean_proj-input twin and is what to trust for the pre_block value. + Because pre_block's LayerNorms reset the deep-encoder scale, a ratio ~ ref at 'amb' but a collapse + only at 'mp' implicates mean_proj; a ratio already collapsed at 'amb' implicates pre_block (its LN + affines / branches), since the encoder body's absolute scale is normalised away before it.""" + allsm = np.fromfile(encsm_f, dtype=np.float32) + stage_samples = allsm.size // AUDIO_CH + staged = allsm.reshape(AUDIO_CH, stage_samples) + ref_fn = ref_pre_norm_z if stage == "mp" else ref_pre_block_out + ref = ref_fn(m, staged[ch], T) # [T, 32] + # 'pre' reads the raw bf16 b_ax2 (arena-rotated, readback can lag -> untrustworthy); 'amb' reads + # b_amb, its f32 mean_proj-input twin, which is the reliable pre_block value. + raw = _read_bf16(dev_f) if stage == "pre" else np.fromfile(dev_f, dtype=np.float32) + dev = raw.reshape(-1, AUDIO_C)[:T] # last channel's used rows + if dev.shape != ref.shape: + sys.exit(f"device slice {dev.shape} vs reference {stage} {ref.shape}; check T / buffer rows") + nbad = int((~np.isfinite(dev)).sum()) + if nbad: + # A readback with non-finite values cannot go through the sorted-multiset fit (it would need + # equal, all-finite sizes). The bf16 b_ax2 ('pre') lags the arena this way; 'amb' is its + # reliable f32 twin, so just report the corruption and point at the right stage. + print(f"STAGE '{stage}' READBACK UNUSABLE: {nbad} non-finite device values " + f"(min {np.nanmin(dev):.4g} max {np.nanmax(dev):.4g}). " + + ("The bf16 b_ax2 readback lags the arena — re-run with R4D_ENC_SEL=amb " + "(--stage amb) for the reliable pre_block value." + if stage == "pre" else "unexpected: check the buffer size/dtype.")) + return + rf, rf_aff, aa, bb, r2 = _affine_report(dev, ref) + ratio = float(np.std(dev)) / (float(np.std(ref)) + 1e-12) + print(f"STAGE '{stage}' (device vs reference {stage} output, pre-norm), ch={ch} T={T}") + print(f" reference |mean|={ref.mean():.4f} std={ref.std():.4f}; " + f"device |mean|={dev.mean():.4f} std={dev.std():.4f}") + print(f" device/reference std ratio = {ratio:.4f}") + print(f" sorted relFro (dev vs ref) = {rf:.3e}") + print(f" global-affine dev ~ {aa:.4f}*ref {bb:+.4f}: R^2={r2:.3f} relFro after affine={rf_aff:.3e}") + verdict = ("MATCHES reference — this stage is fine; the collapse is at/before it only if an earlier stage differs" + if ratio > 0.85 else + "COLLAPSED here — the gain is introduced AT this stage or upstream of it") + print(f" verdict: {verdict}") + + def do_selftest(m): """No device: build a device-shaped b_enca from the reference itself (perfect) and a temporally-mis-pooled copy (a stand-in for the strided-conv bug #14 suspected), and confirm the @@ -171,13 +264,24 @@ def main(): ap.add_argument("--kind", choices=["audio", "vaudio"], default="audio") ap.add_argument("--slot", type=int, default=1) ap.add_argument("--n", type=int, help="raw enc_samples count (before hop padding)") + ap.add_argument("--dev", help="device stage readback (see --stage): 'mp'=b_amb2 f32, " + "'amb'=b_amb f32 (reliable pre_block out), 'pre'=b_ax2 bf16 (arena-laggy)") + ap.add_argument("--stage", choices=["mp", "amb", "pre"], default="mp", + help="which final-chain stage --dev is") + ap.add_argument("--ch", type=int, default=AUDIO_CH - 1, help="channel in --dev (device keeps the last)") ap.add_argument("--selftest", action="store_true") a = ap.parse_args() m = load_encoder() if a.selftest: sys.exit(do_selftest(m)) + if a.dev: + if not a.encsm: + sys.exit("--dev also needs --encsm (it gives T and the reference waveform)") + allsm = np.fromfile(a.encsm, dtype=np.float32) + T = (allsm.size // AUDIO_CH) // AUDIO_HOP + sys.exit(do_stage(m, a.dev, a.encsm, a.ch, T, a.stage)) if not (a.enca and a.encsm): - sys.exit("give --enca and --encsm (or --selftest); --n is optional/informational") + sys.exit("give --enca and --encsm, or --dev/--stage and --encsm (or --selftest); --n is informational") sys.exit(do_parity(m, a.enca, a.encsm, a.kind, a.slot, a.n))