From cfbccb46dc67a35bb2ddb60e22d70aefaf3d6d1b Mon Sep 17 00:00:00 2001 From: gearwave00001 Date: Wed, 21 Oct 2026 13:31:38 -0500 Subject: [PATCH] minimaxh3: adaln_t_table curve-form checkpoints + an R4D_DIT_SEL step dump The DaSiWa overlay ships its modulation curve as a precomputed table (adaln_t_table [1025,8]): timestep_embed gains a curve mode -- y[m] = the table linearly sampled at the timestep, no sinusoid, no MLP -- in the HIP, AVX and ref tiers, and the arch drives the four timestep rows (video, audio, and each re-embedded with its reference pin) through it with the ada projections as plain bf16 K=8 lines. The dasiwa-w8a8 recipe carries the overlay. Device-verified at 512: T2VA, I2VA and FL2VA complete clean and the T2VA re-run is bit-identical; the fried look PERSISTS on the exact finetune the reference clips rendered from, which kills the checkpoint-style theory and pins the fork to Radiance's forward. For the value-parity localisation: R4D_DIT_SEL (env, driver and plugin) declares f32 PERSIST shadows of the stream entering block 0, the timestep table and the step-0 modulation, and the driver reads those plus the velocity head back on a plain request's step 0 into R4D_ENC_DUMPDIR, for the CPU reference DiT replay to diff against. Co-Authored-By: Claude --- abi/rad_builder.h | 16 + arch/minimaxh3/minimaxh3.cpp | 335 ++++++++++++++++----- core/gen/video_driver.cpp | 90 ++++++ core/gen/video_driver.h | 11 + data/recipes/minimax-h3-dasiwa-w8a8.recipe | 69 +++++ docs/OPS.md | 21 +- libavx/avx_cases.cpp | 2 + libavx/avx_gen.cpp | 31 +- libavx/avx_registry.cpp | 5 +- libr4d/r4d_gen.hip | 43 ++- libr4d/r4d_rows.cpp | 19 +- libr4d/r4d_selftest.cpp | 31 +- libref/ref_gen.cpp | 31 +- libref/ref_registry.cpp | 9 +- libref/ref_shapes.cpp | 3 +- tests/ref_test.cpp | 7 +- 16 files changed, 631 insertions(+), 92 deletions(-) create mode 100644 data/recipes/minimax-h3-dasiwa-w8a8.recipe diff --git a/abi/rad_builder.h b/abi/rad_builder.h index d52dc99f..a1b5610e 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1037,6 +1037,22 @@ typedef struct RadVideoGenDecl { int64_t dbg_ve_l3_bytes; rad_buf dbg_ve_l4; int64_t dbg_ve_l4_bytes; + /* #45 DiT value-parity: an f32 PERSIST twin of the DiT stream entering block 0 (b_h, post + * video_patch_proj / condition_proj / audio_patch_proj -- the JOINT [text|audio|video] rows), + * and of the velocity head output (b_vel), both written by debug-only cast ops so the bf16 arena + * scratch (b_h) lag does not corrupt the readback (the b_ax2 lesson). Read with R4D_DIT_SEL on a + * generation pass: replay the identical h0 through the reference DiT (comfy model.py) and compare + * the velocity to localize where Radiance's forward over-gains. The t_emb / modulation / rope the + * pass actually used are dumped alongside so the torch replay needs no re-derivation. Trailing + * debug fields; an older plugin declares none and keeps the 0 default. */ + rad_buf dbg_dit_h0; /* [T, D] f32: stream into block 0 */ + int64_t dbg_dit_h0_bytes; + rad_buf dbg_dit_vel; /* [maxV, kPatchVals] f32: velocity head output */ + int64_t dbg_dit_vel_bytes; + rad_buf dbg_dit_temb; /* [TT, td] f32: silu(t_emb) the adaln projections consume */ + int64_t dbg_dit_temb_bytes; + rad_buf dbg_dit_mod; /* modulation table (b_modg) f32, this step */ + int64_t dbg_dit_mod_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 ef2f84d2..7940823b 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -298,9 +298,10 @@ struct DitBlock { rad_op op_sel = 0; /* video sparse attention's tile selection */ rad_op op_kq = 0; /* the keys to int8 codes for the attention's scores */ rad_op op_vq = 0; /* the values to E4M3 codes for the attention's P.V */ - /* The three modulation projections, one a modality, this rank's share of their rows. */ + /* The three modulation projections, one a modality, this rank's share of their rows. A + * curve-form checkpoint's are plain bf16 K=8 lines (ada_w), not fp8-quantised. */ DenseFP8 ada[3]; - rad_weight ada_b[3] = {}; + rad_weight ada_w[3] = {}, ada_b[3] = {}; rad_op op_ada[3] = {}; }; @@ -419,8 +420,12 @@ struct Model { ActFP8 a_rh{}, a_rattn{}, a_rffn{}; RefBlock rb[2]; - /* ---- the timestep MLP and the per-step tables */ - rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_no = 0, b_no = 0; + /* ---- the timestep MLP and the per-step tables. A curve-form checkpoint replaces the sinusoid + * and the MLP with a precomputed adaln curve: `curve` is that table's row count (0 for the + * sinusoid + MLP path), `w_ttable` its f32 weight, and `temb_w` the embedding width (meta's + * time_embed_dim, whichever form produced it) every projection below reads. */ + int64_t curve = 0, temb_w = 2688; + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_no = 0, b_no = 0, w_ttable = 0; rad_op op_temb = 0, op_temb_pv = 0, op_temb_pa = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_ts2 = 0, op_no = 0; QuantFP8 q_temb{}; @@ -568,6 +573,24 @@ struct Model { rad_op op_ve_ldbg[6] = { 0 }; int64_t ve_l_bytes[6] = { 0 }; + /* ---- the DiT step dump (R4D_DIT_SEL): the f32 shadows that let a step be replayed on the CPU + * reference DiT. All declared only when the env is set, so a production run pays nothing. */ + bool dit_dbg = false; + /* b_h right after the input projections -- the stream entering block 0 -- cast to f32 before the + * block loop recycles the bf16 scratch. [cap, D] f32 PERSIST (capped: see declare_dit). */ + int64_t dit_h0cap = 0; + rad_buf b_dh0 = 0; + rad_op op_dh0 = 0; + /* The whole timestep-embedding table (b_temb, all 4*S rows), cast to f32 in the conditioning + * pass so the step pass can read it back without touching the arena. [4*S, td] f32 PERSIST. */ + rad_buf b_tembd = 0; + rad_op op_tembd = 0; + /* The step's gathered modulation table (b_modg) cast to f32: every block's and segment's cell, + * both ranks' column halves, the exact vectors the norms consume. PERSIST f32 twin of a bf16 + * scratch (the b_ax2 lesson). [world * L * kMaxSegs, Ws] f32. */ + rad_buf b_modd = 0; + rad_op op_modd = 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, * conv1 +res] units. The strided downsampler and the attention pre-block run in a bf16 @@ -999,9 +1022,12 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { const int64_t fd = rad_meta_geti(meta, "transformer.freq_dim", 256); const int64_t hd1 = rad_meta_geti(meta, "transformer.time_embed_hidden_dim", 5376); const int64_t td = rad_meta_geti(meta, "transformer.time_embed_dim", 2688); + const int64_t G = rad_meta_geti(meta, "transformer.adaln_curve_grid", 0); + m.curve = G; + m.temb_w = td; const int acc = RAD_ACCESS_PER_REQUEST; const int gx = kGrpTemb; - if (td % RAD_FP8_BLOCK) { + if (!G && td % RAD_FP8_BLOCK) { fprintf(stderr, "radiance: minimaxh3: the timestep embedding is %lld wide, not whole " "%d-column blocks\n", (long long)td, RAD_FP8_BLOCK); return RAD_E_INVAL; @@ -1016,45 +1042,90 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { * byte-identical -- just S*2 unused rows through the MLP. */ const int64_t TT = 4 * S; const double kVisualPin = 0.999, kAudioPin = 1.0; - m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { TT, fd }); - m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { TT, hd1 }); - m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { TT, hd1 }); - m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { TT, td }); - m.op_temb = rw(b, RAD_OP(b, "timestep_embed", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), - RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {}, { m.b_tproj }); - /* The two clamped schedule passes: the same op, the pin as `clamp_min`, into the pinned blocks. */ - m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), - RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), - RAD_F64("clamp_min", kVisualPin), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {}, { m.b_tproj }); - m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), - RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), - RAD_F64("clamp_min", kAudioPin), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {}, { m.b_tproj }); - m.op_t1 = dense_bias(b, nm, "tmb.l1", "transformer.time_embedder.linear_1", RAD_F32, "f32", hd1, - fd, TT, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); - m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s); - m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32", td, - hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); - /* silu(temb) in f32, rounded once to the bf16 the projections take. */ - Geom gs = g; - gs.max_tok = TT; - m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td }); - m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x); - RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT)); - RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td)); - if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2 - || !m.op_ts2) return RAD_E_INVAL; + if (G > 0) { + /* A curve-form checkpoint: a timestep's embedding is not computed but READ -- the f32 + * table the checkpoint ships, sampled at the timestep's sigma and lerped between the two + * rows around it. The four schedule blocks -- video, audio, and each re-embedded with its + * reference pin as a floor -- are four issues of the same op, and b_temb is written + * bf16 outright: what every projection below reads IS the op's output, so the MLP, the + * silus and the fp8 activation plane all vanish, and the activation alias a_temb.x is + * the buffer itself. */ + m.w_ttable = wcopy(b, nm.f("tmb.table"), nm.ckpt("transformer.adaln_t_table"), + RAD_F32, { G, td }, acc, gx); + m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_BF16, { TT, td }); + m.a_temb.x = m.b_temb; + if (!m.w_ttable || !m.b_temb) return RAD_E_INVAL; + /* scale/max_period stay on the schema's required-parameter list -- the sinusoid reads + * them -- but the curve branch of every kernel ignores them, so they are given as the + * sinusoid defaults and mean nothing. */ + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + /* The two clamped schedule passes: the same op, the pin as `clamp_min`, into the pinned + * blocks -- the same floors the sinusoid path gives the reference cells. */ + m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), + RAD_F64("clamp_min", kVisualPin), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), + RAD_F64("clamp_min", kAudioPin), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa) return RAD_E_INVAL; + } else { + m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { TT, fd }); + m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { TT, hd1 }); + m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { TT, hd1 }); + m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { TT, td }); + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + /* The two clamped schedule passes: the same op, the pin as `clamp_min`, into the pinned blocks. */ + m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kVisualPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kAudioPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense_bias(b, nm, "tmb.l1", "transformer.time_embedder.linear_1", RAD_F32, "f32", + hd1, fd, TT, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); + m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s); + m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32", + td, hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); + /* silu(temb) in f32, rounded once to the bf16 the projections take. */ + Geom gs = g; + gs.max_tok = TT; + m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td }); + m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x); + RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT)); + RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td)); + if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2 + || !m.op_ts2) return RAD_E_INVAL; + } /* The lane's tables: kMaxSegs segment columns so a reference-conditioned pack has a cell each; * the plain three fill columns 0,1,2 byte-identically and leave the rest unread. */ @@ -1076,17 +1147,32 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { const char* bn = nm.f("%s.bias", base); RAD_ARCH_TRY(map_rows(b, wn, { { src_w, (int)(md * ada_rows), ada_rows } })); RAD_ARCH_TRY(map_rows(b, bn, { { src_b, (int)(md * ada_rows), ada_rows } })); - B.ada[md].mapped = true; - RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW, - grp_layer(grp), { src_w })); B.ada_b[md] = decl_w(b, bn, RAD_BF16, { m.Ws }, acc, RAD_SHARD_ROW, grp_layer(grp)); if (!B.ada_b[md]) return RAD_E_INVAL; - B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), - RAD_INT("K", td), RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", "fp8a8")), - RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])), - { m.a_temb.q, m.a_temb.s }, { m.b_ada }); + if (G > 0) { + /* A curve checkpoint's modulation is an 8-column bf16 read of the embedding: the + * K=8 projection loses nothing to quantisation, so the weight stays plain bf16 and + * the activation is the curve's bf16 output itself -- no code planes either way. */ + B.ada_w[md] = decl_w(b, wn, RAD_BF16, { m.Ws, td }, acc, RAD_SHARD_ROW, + grp_layer(grp)); + if (!B.ada_w[md]) return RAD_E_INVAL; + B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), + RAD_INT("K", td), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.ada_w[md], B.ada_b[md])), + { m.a_temb.x }, { m.b_ada }); + } else { + B.ada[md].mapped = true; + RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW, + grp_layer(grp), { src_w })); + B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), + RAD_INT("K", td), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8")), + RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])), + { m.a_temb.q, m.a_temb.s }, { m.b_ada }); + } if (!B.op_ada[md]) return RAD_E_INVAL; } } @@ -1143,6 +1229,45 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { /* ---- the packed sequence: the lane's prompt rows, the soundtrack's and the video's latents * through their f32 projections, rounded to bf16 as the reference packs them */ m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + /* ---- the DiT step dump (R4D_DIT_SEL, #61): the f32 shadows a CPU reference replay reads + * back. Declared only when the driver-side env is set -- both halves read the same + * environment -- so a production run reserves nothing. All bf16→f32 casts (no f32→f32 cast + * row exists), hence the temb shadow is curve-form only, where b_temb is bf16. */ + m.dit_dbg = std::getenv("R4D_DIT_SEL") != nullptr; + if (m.dit_dbg) { + /* The h0 shadow is capped: max_tok is the whole batch ceiling (a video serve runs past a + * hundred thousand rows), and a full [max_tok, D] f32 twin is gigabytes the arena has no + * room for -- the KV budget resolver sees 0 and startup aborts. The dump request is a + * small plain render; anything wider than the cap fails the step below with a clear word. */ + const int64_t h0cap = std::min(T, (int64_t)8192); + m.b_dh0 = decl_b(b, nm.f("dit.h0dbg"), RAD_F32, { h0cap, D }, RAD_BUF_PERSIST); + m.op_dh0 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, h0cap), RAD_INT("n", D), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_h }, { m.b_dh0 }); + m.dit_h0cap = h0cap; + rad_note(b, "rank %d/%d: DiT step dump on (R4D_DIT_SEL): h0 shadow capped at %lld rows", + m.gt.rank, m.gt.world, (long long)h0cap); + m.b_modd = decl_b(b, nm.f("dit.moddbg"), RAD_F32, + { (int64_t)g.world * L * kMaxSegs, m.Ws }, RAD_BUF_PERSIST); + m.op_modd = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)g.world * L * kMaxSegs), + RAD_INT("n", m.Ws), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_modg }, { m.b_modd }); + if (m.curve > 0) { + m.b_tembd = decl_b(b, nm.f("dit.tembdbg"), RAD_F32, { 4 * m.S, m.temb_w }, + RAD_BUF_PERSIST); + m.op_tembd = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * m.S), RAD_INT("n", m.temb_w), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_temb }, { m.b_tembd }); + } + if (!m.op_dh0 || !m.op_modd || (m.curve > 0 && !m.op_tembd)) return RAD_E_INVAL; + } /* Learn the trunk's weight format from one linear before declaring the activation code planes. * An int8 (W8A8) denoiser quantises its per-token activations to int8 too -- E4M3's three * mantissa bits band the smooth activations that carry detail, and its 448 clamp clips @@ -3087,6 +3212,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c 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; + /* The DiT step dump (#61, R4D_DIT_SEL, read by BOTH halves -- the plugin declares the + * shadows only when it sees the env, so the driver must check dbg_dit_h0 is non-null + * before staging). All f32: + * dbg_dit_h0 -- b_dh0, the input projections' output (the stream entering block 0), + * plain requests only; the driver readbacks step 0's first R rows. + * dbg_dit_vel -- b_vel as-is: written by this step's head and read back in the same + * pass, so the arena cannot have moved under it. + * dbg_dit_temb-- b_tembd, the whole 4*S-row timestep table widened to f32 (curve form + * only -- the full form's b_temb is already f32; no f32->f32 cast). + * dbg_dit_mod -- b_modd, step 0's gathered modulation table: row + * rank * (L * kMaxSegs) + l * kMaxSegs + e, columns rank * Ws + c of + * the full-W cell, exactly the bf16 vectors the norms consumed. */ + d.dbg_dit_h0 = m.b_dh0; + d.dbg_dit_h0_bytes = m.b_dh0 ? m.dit_h0cap * m.D * 4 : 0; + d.dbg_dit_vel = m.b_vel; + d.dbg_dit_vel_bytes = m.maxV * kPatchVals * 4; + d.dbg_dit_temb = m.b_tembd; + d.dbg_dit_temb_bytes = m.b_tembd ? 4 * m.S * m.temb_w * 4 : 0; + d.dbg_dit_mod = m.b_modd; + d.dbg_dit_mod_bytes = + m.b_modd ? (int64_t)gd.world * gd.n_layer * kMaxSegs * m.Ws * 4 : 0; } RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -3247,21 +3393,41 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { /* ---- every step's timestep embedding: the two streams' schedules, then each re-embedded with * its reference pin as a floor (clamp_min) into the two pinned blocks the reference cells read. * At its own rows: QuantFP8::step bands by the rows it is issued for. */ - const int64_t fd = 256, td = 2688, TT = 4 * S; - RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), brow_slice(m.b_tproj, 0, S, fd)); - RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), brow_slice(m.b_tproj, S, S, fd)); - RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), - brow_slice(m.b_tproj, 2 * S, S, fd)); - RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), - brow_slice(m.b_tproj, 3 * S, S, fd)); - RAD_ISSUE_N(c, m.op_t1, TT, brows(m.b_tproj, TT), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, - brows(m.b_te1, TT)); - RAD_ISSUE_N(c, m.op_ts, TT, brows(m.b_te1, TT), brows(m.b_te1s, TT)); - RAD_ISSUE_N(c, m.op_t2, TT, brows(m.b_te1s, TT), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, - brows(m.b_temb, TT)); - RAD_ISSUE_N(c, m.op_ts2, TT, brows(m.b_temb, TT), brows(m.a_temb.x, TT)); - RAD_ISSUE_N(c, m.q_temb.op, TT, brows(m.a_temb.x, TT), brows(m.a_temb.cq(), TT), - brows(m.a_temb.cs(), TT)); + const int64_t fd = 256, td = m.temb_w, TT = 4 * S; + if (m.curve > 0) { + /* The curve form reads the embedding straight out of the checkpoint's table: one op per + * block, the table as its weight operand, b_temb as its bf16 output. Operand order follows + * the op's IN/OUT sequence -- t, y, table -- like every other op: the kernel reads the + * table at operand 2, after the output. */ + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_temb, 0, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_temb, S, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_temb, 2 * S, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_temb, 3 * S, S, td), RAD_W(m.w_ttable)); + } else { + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), brow_slice(m.b_tproj, 0, S, fd)); + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), brow_slice(m.b_tproj, S, S, fd)); + RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_tproj, 2 * S, S, fd)); + RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_tproj, 3 * S, S, fd)); + RAD_ISSUE_N(c, m.op_t1, TT, brows(m.b_tproj, TT), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, TT)); + RAD_ISSUE_N(c, m.op_ts, TT, brows(m.b_te1, TT), brows(m.b_te1s, TT)); + RAD_ISSUE_N(c, m.op_t2, TT, brows(m.b_te1s, TT), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, TT)); + RAD_ISSUE_N(c, m.op_ts2, TT, brows(m.b_temb, TT), brows(m.a_temb.x, TT)); + RAD_ISSUE_N(c, m.q_temb.op, TT, brows(m.a_temb.x, TT), brows(m.a_temb.cq(), TT), + brows(m.a_temb.cs(), TT)); + } + /* The dump's temb shadow (R4D_DIT_SEL, curve form -- the full form's b_temb is already f32 and + * has no f32→f32 cast row): every row of the table the adaln projections read, widened to f32 + * into a PERSIST buffer so the step pass can read it back without touching the arena. */ + if (m.dit_dbg && m.curve > 0) + RAD_ISSUE_N(c, m.op_tembd, TT, brows(m.b_temb, TT), brows(m.b_tembd, TT)); /* ---- the modulation table: block l, segment e from its modality's projection of its * timestep's rows, at the table's column block (l, e). A plain request has exactly the three @@ -3300,10 +3466,15 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { for (int64_t e = 0; e < ncell; ++e) { const int md = cell[(size_t)e].first; const int64_t r0 = cell[(size_t)e].second; - RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td), - brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w), - RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), - bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S)); + const RadOperand out = + bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S); + if (m.curve > 0) + RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.x, r0, S, td), + RAD_W(B.ada_w[md]), RAD_W(B.ada_b[md]), RAD_NONE, out); + else + RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td), + brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w), + RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), out); } } for (int64_t e = 0; e < ncell; ++e) { @@ -3375,6 +3546,13 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { else RAD_ISSUE_N(c, m.op_modg, 1, brow_slice(m.b_ada, ti, 1, row), RAD_P_T2(rad_buf_ptr(c, m.b_modg), RAD_BF16, 1, row)); + /* The dump's modulation shadow (R4D_DIT_SEL): the gathered table -- every block's and merged + * cell's vectors, both ranks' column halves -- widened to f32 into a PERSIST buffer. The step + * the driver readbacks on is the dump's step (0); the blocks below never touch b_modd. */ + if (m.dit_dbg && V->step == 0) + RAD_ISSUE_N(c, m.op_modd, (int64_t)g.world * L * kMaxSegs, + brows(m.b_modg, (int64_t)g.world * L * kMaxSegs), + brows(m.b_modd, (int64_t)g.world * L * kMaxSegs)); RAD_ISSUE_N(c, m.op_text, nt, brows(m.b_text, La * kMaxText), lane_d, praw(V->seg_cu, RAD_I32, 2), brows(m.b_h, nt)); @@ -3423,6 +3601,19 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { } } + /* The dump's h0 shadow (R4D_DIT_SEL): b_h exactly as the input projections and scatters left + * it -- the stream entering block 0 -- widened to f32 before the first block recycles the + * bf16 scratch. Plain requests only: the harness replays the fixed [text | audio | video] + * order, and the driver readbacks only plain step-0 requests (R4D_DIT_SEL). */ + if (m.dit_dbg && V->step == 0 && !refc) { + if (R > m.dit_h0cap) { + rad_step_fail(c, "minimaxh3: the DiT dump request packs more rows than the h0 shadow " + "holds (8192) -- render the dump smaller"); + return; + } + RAD_ISSUE_N(c, m.op_dh0, R, brows(m.b_h, R), brows(m.b_dh0, R)); + } + const RadOperand segs = praw(V->seg_cu, RAD_I32, nfine + 1); /* The modulated norm's boundaries: the merged GROUP table, a subset of `segs` -- attention * selects its per-reference prefix sinks from the fine `segs`, the norm selects its per-cell diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 05af456a..7645e0eb 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -308,6 +308,32 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, RAD_ERR("video generator: R4D_ENC_DEBUG set but no pinned host for the %lld-byte " "encoder readback", (long long)enc_dbg_bytes_); } + /* Debug-only DiT step dump (#61, R4D_DIT_SEL): the slab for the step-0 readback -- the plugin's + * f32 shadows (h0 | temb | mod) plus the step's velocity head output. The plugin declares the + * shadows only when it sees the same env, so a mismatch shows up as dbg_dit_h0 == 0 and simply + * disables the dump. The value of R4D_DIT_SEL names the step to dump; only step 0 (what the + * shadows carry) is honoured, anything else warns and stays off. */ + if (const char* sel = std::getenv("R4D_DIT_SEL")) { + const long want = std::strtol(sel, nullptr, 10); + if (want != 0) + RAD_ERR("video generator: R4D_DIT_SEL=%s: only step 0 is dumped (the shadows are " + "issued at step 0); ignoring", sel); + else if (decl_.dbg_dit_h0 && decl_.dbg_dit_vel) { + dit_h0_b_ = decl_.dbg_dit_h0_bytes; + dit_vel_b_ = decl_.dbg_dit_vel_bytes; + dit_temb_b_ = decl_.dbg_dit_temb_bytes; + dit_mod_b_ = decl_.dbg_dit_mod_bytes; + const int64_t sum = dit_h0_b_ + dit_vel_b_ + dit_temb_b_ + dit_mod_b_; + dit_host_ = static_cast(rad_dev_alloc(sum, RAD_MEM_HOST_PINNED)); + dit_dbg_ = dit_host_ != nullptr; + if (!dit_dbg_) + RAD_ERR("video generator: R4D_DIT_SEL set but no pinned host for the %lld-byte " + "DiT dump", (long long)sum); + } else { + RAD_ERR("video generator: R4D_DIT_SEL set but the plugin exported no DiT shadows -- " + "restart it with the same env so declare_dit sees it"); + } + } return RAD_OK; } @@ -323,10 +349,12 @@ void VideoDriver::fini() { if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED); if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED); if (enc_dbg_host_) rad_dev_free(enc_dbg_host_, RAD_MEM_HOST_PINNED); + if (dit_host_) rad_dev_free(dit_host_, RAD_MEM_HOST_PINNED); host_ = nullptr; frames_host_ = nullptr; audio_host_ = nullptr; enc_dbg_host_ = nullptr; + dit_host_ = nullptr; } /* ================================================================== requests */ @@ -1132,6 +1160,18 @@ void VideoDriver::stage_seed(const Job& j) { reg_[R_SEED].used = 4 * 4; } +/* DiT step dump (#61, R4D_DIT_SEL + R4D_ENC_DUMPDIR): write one raw file named verbatim. Separate + * from enc_dbg_dump_file because the harness names carry their own dtype suffixes (.f32 / .i32). */ +static void dit_dump_file(const std::string& name, const void* p, size_t bytes) { + const char* dir = std::getenv("R4D_ENC_DUMPDIR"); + if (!dir || !p || bytes == 0) return; + const std::string path = std::string(dir) + "/" + name; + if (std::FILE* f = std::fopen(path.c_str(), "wb")) { + std::fwrite(p, 1, bytes, f); + std::fclose(f); + } +} + const RadBatch* VideoDriver::build_step(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; const bool small = small_now(j); @@ -1154,6 +1194,28 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { if (upload() < 0) return nullptr; base_batches(j, g, rows, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; + /* DiT step dump (#61, R4D_DIT_SEL): the step-0 readback of the plugin's f32 shadows and the + * velocity head, plus the host-side bytes the CPU reference replay needs (the planar RoPE + * positions and the packed segment boundaries -- final in their regions since upload() ran). + * Plain step 0 only: the harness replays the fixed [text | audio | video] layout and the full + * grid, and the arch issues the shadows only under the same conditions. */ + dit_used_ = false; + if (dit_dbg_ && j.step == 0 && !small && !j.ref_wide && j.ref_tab.empty()) { + char* p = dit_host_; + int64_t off = 0; + const rad_buf hh[4] = { decl_.dbg_dit_h0, decl_.dbg_dit_temb, decl_.dbg_dit_mod, + decl_.dbg_dit_vel }; + const int64_t nn[4] = { dit_h0_b_, dit_temb_b_, dit_mod_b_, dit_vel_b_ }; + for (int i = 0; i < 4; ++i) + if (hh[i] && nn[i] > 0) { + rb_.push_back(Readback{ hh[i], nn[i], p + off }); + off += nn[i]; + } + dit_used_ = true; + dit_rows_ = rows; + dit_dump_file("dit_pos.f32", pos.data(), (size_t)pos.size() * 4); + dit_dump_file("dit_seg_cu.i32", hptr(R_SEG), (size_t)reg_[R_SEG].used); + } pass_.kind = RAD_GEN_PASS_VSTEP; pass_.job = j.id; return &out_[0]; @@ -1441,6 +1503,34 @@ int VideoDriver::done() { break; case RAD_GEN_PASS_VSTEP: { ++j->step; + if (dit_used_) { + /* The step-0 dump landed: slab (h0 | temb | mod | vel) to raw files, plus the few + * facts the driver knows (R4D_ENC_DUMPDIR; the prep script supplies D=5376 and the + * harness .meta files). */ + char* p = dit_host_; + dit_dump_file("dit_h0.f32", p, (size_t)dit_h0_b_); + p += dit_h0_b_; + dit_dump_file("dit_temb.f32", p, (size_t)dit_temb_b_); + p += dit_temb_b_; + dit_dump_file("dit_mod.f32", p, (size_t)dit_mod_b_); + p += dit_mod_b_; + dit_dump_file("dit_vel.f32", p, (size_t)dit_vel_b_); + if (std::getenv("R4D_ENC_DUMPDIR")) { + const std::string path = + std::string(std::getenv("R4D_ENC_DUMPDIR")) + "/dit_info.txt"; + if (std::FILE* f = std::fopen(path.c_str(), "w")) { + std::fprintf(f, "rows %lld\nn_text %lld\nn_audio %lld\nsteps %d\nseed %llu\n", + (long long)dit_rows_, (long long)j->geom.n_text, + (long long)j->geom.n_audio, (int)j->sched.steps, + (unsigned long long)j->req->seed); + std::fclose(f); + } + } + RAD_ERR("dit_dbg: dumped step 0 -- rows %lld h0 %lld temb %lld mod %lld vel %lld", + (long long)dit_rows_, (long long)dit_h0_b_, (long long)dit_temb_b_, + (long long)dit_mod_b_, (long long)dit_vel_b_); + dit_used_ = false; + } VideoEvent e; e.kind = VideoEvent::STEP; e.steps_done = j->step; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index 01f2d234..3a2c2531 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -226,6 +226,17 @@ private: int64_t enc_dbg_used_ = 0; /* bytes the last encode readback filled */ const char* enc_dbg_sel_ = ""; /* R4D_ENC_SEL: "", "mp" or "pre" (audio) */ + /* Debug-only (#61, R4D_DIT_SEL): a pinned slab holding the DiT step-0 dump -- the f32 shadows + * (h0 | temb | mod) the plugin declares when it sees the same env, plus the step's velocity + * head output b_vel -- so done() can write them to R4D_ENC_DUMPDIR for the CPU reference DiT + * replay. Staged only on a plain request's step 0; a plugin without the env leaves + * decl_.dbg_dit_h0 null and dit_dbg_ stays false, so a normal run never touches these. */ + bool dit_dbg_ = false; + char* dit_host_ = nullptr; + int64_t dit_h0_b_ = 0, dit_vel_b_ = 0, dit_temb_b_ = 0, dit_mod_b_ = 0; + bool dit_used_ = false; /* the running pass staged a dump */ + int64_t dit_rows_ = 0; /* packed rows R of the dumped step */ + std::vector out_; /* one per rank */ std::vector vout_; Pass pass_; diff --git a/data/recipes/minimax-h3-dasiwa-w8a8.recipe b/data/recipes/minimax-h3-dasiwa-w8a8.recipe new file mode 100644 index 00000000..4d6aeef7 --- /dev/null +++ b/data/recipes/minimax-h3-dasiwa-w8a8.recipe @@ -0,0 +1,69 @@ +# minimax-h3-dasiwa-w8a8.recipe -- the DaSiWa curve-form finetune, DiT linears at int8 (W8A8). +# +# minimax-h3-w8a8.recipe with its one modulation rule dropped. A curve-form checkpoint +# (config's adaln_curve_grid set) replaces the timestep sinusoid + MLP with the shipped +# adaln_t_table, and every modulation projection becomes a K=8 read of that table: an +# 8-column GEMM has nothing for a 128x128 E4M3 block to bite on, so the plugin declares +# the ada weights plain bf16 (arch/minimaxh3/minimaxh3.cpp, declare_tables' curve branch) +# and they must store as the checkpoint holds them. That is the ONLY rule difference -- +# the four per-token DiT linears stay symmetric int8 on a per-row 128-column grid, the +# text encoder and token refiner stay E4M3, and what is read once a step stays f32 or +# bf16, exactly as in minimax-h3-w8a8.recipe. Serve with the W8A8 DiT path. +# +# rad-convert \ +# --recipe data/recipes/minimax-h3-dasiwa-w8a8.recipe -o minimax-h3-dasiwa-w8a8.rad +# +# From a container of the base model nothing but the DiT changes, so reuse the rest: +# +# rad-convert --recipe data/recipes/minimax-h3-dasiwa-w8a8.recipe \ +# --reuse \ +# --changed \ +# -o minimax-h3-dasiwa-w8a8.rad +# +# The finetune itself is a ComfyUI-format convrot-int8 single file; convert-ref2va/ +# overlay-dasiwa.py dequantises it to the HF names and dtypes this recipe and the plugin +# expect, writes config.json with the two curve meta keys, and emits the --changed list. +# The directory otherwise needs the usual text-to-video-and-audio components: +# text_encoder/, vae/, audio_vae/, the processor or tokenizer, both scheduler folders and +# latent_upscaler/ -- transformer_ref/ and the original-layout FL2VA/ and Ref2VA/ are not +# read. +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_norm.weight cast dtype=f32 +te.blk.*.ffn_norm.weight cast dtype=f32 +ref.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_qkv.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +dit.blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +dit.blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +dit.blk.*.ffn_down.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +vae.blk.*.attn_qkv.weight cast dtype=bf16 +vae.blk.*.attn_out.weight cast dtype=bf16 +vae.blk.*.ffn_up.weight cast dtype=bf16 +vae.blk.*.ffn_down.weight cast dtype=bf16 +vae.proj_out.* cast dtype=bf16 +aud.*.weight cast dtype=f32 +# The audio encoder's strided downsamplers and its attention/MLP pre-block run in a bf16 island +# inside the f32 chain (arch/minimaxh3/minimaxh3.cpp, declare_aenc): conv1d, layernorm and gemm +# pin every operand to one dtype, so their weights cast; the chain's own f32 weights are stored +# folded from the checkpoint's weight-norm pairs. +aenc.d*.w cast dtype=bf16 +aenc.d*.b cast dtype=bf16 +aenc.pb.* cast dtype=bf16 +aenc.b*.u*.c1.weight cast dtype=f32 +aenc.b*.u*.c2.weight cast dtype=f32 +aenc.cin.weight cast dtype=f32 +aenc.fin.weight cast dtype=f32 +# The video encoder: the implicit-GEMM kernel stores its 3x3x3 weights bf16 tap-major, so those +# four name classes cast; conv_in (3 input channels) and the k=1 shortcut/quant convs run on the +# reference kernel with their f32 weights as they are, and the norms and biases need no rule. +venc.l*.b*.c1w cast dtype=bf16 +venc.l*.b*.c2w cast dtype=bf16 +venc.l*.dnw cast dtype=bf16 +venc.cout.weight cast dtype=bf16 +ups.embed.* cast dtype=f32 +ups.*.emb_layers.* cast dtype=f32 diff --git a/docs/OPS.md b/docs/OPS.md index f81a03a4..14bf2ff3 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -867,7 +867,7 @@ says which (`libref/ref_gen.cpp`). | `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` | | `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout | | `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | -| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `dtype` | `t` → `y` | +| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `curve`/opt `dtype` | `t` → `y`, `table`w? | | `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` | | `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` | | `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout | @@ -903,6 +903,11 @@ source into every listed lane (a repainted picture's latent into each of its ima diffusers' pipeline hands its transformer. `t` is f32 `[M]`. With `clamp_min`, each `t` is first raised to that floor (`t = max(t, clamp_min)`) -- the reference conditioning's near-clean pin timesteps, which sit above the sampler's decaying schedule. `0` (default) leaves `t` untouched. + With `curve` = G > 0 and the `table` weight (f32 `[G, n]`) bound, the sinusoid is replaced: + `y[m] = table` sampled at `clamp01(max(t[m], clamp_min)) * (G - 1)`, linearly between the two + rows around that position (the lower row index capped at `G - 2`), the precomputed adaln curve + a curve-form checkpoint ships in place of the sinusoid and its MLP. `scale`, `max_period` and + `round` are ignored in that mode, and `n` need not be even. - `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source. - `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is @@ -1097,7 +1102,9 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi |---|---|---| | `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `z` | | `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | +| `rms_mod_quant_i8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | | `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout | +| `flow_res_multistep` | `M`(range) `n` `dtype` | `v`, `x0`:inout, `sigma`, `r`, `hb1`, `hb2`, `order`, `x`:inout | | `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` | | `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` | | `vtile_stitch` | `M`(range) `tile` `overlap` `scale` `pt` `skip` `keep` `blend` `period` `mean` `std` | `x`, `geom`, `prev`:inout → `y` | @@ -1115,12 +1122,24 @@ reads its entry's rows of `s` and `g`. The residual rounds to `x`'s dtype and the norm chain to `z`'s. - `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16 row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound. +- `rms_mod_quant_i8` is the same with `quant_act_i8g` in place of `quant_act_fp8`: symmetric int8 + codes on a per-row `group` grid, a quarter of E4M3's quantisation error on the same one byte a + value; read by the int8 GEMMs. `z` written when bound. - `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`, `r = f32(sigma_next / sigma)`, `x = f32(f32(r x) + f32(f32(1 - r) d))`. `t` (the timestep the transformer was conditioned on), `sigma` and `sigma_next` (the schedule's entries) are one f32 value each; `v` is f32 or bf16, `x` f32. +- `flow_res_multistep` is the same sampler's second-order form (DPM-Solver++2M data-prediction, + k-diffusion's `res_multistep` at eta 0): the clean estimate `d = x + sigma v` again, but the step + also leans on the previous step's estimate, `x = r x + hb1 d + hb2 x0`, `r = sigma_next / sigma`. + `x0` is read then overwritten with this step's `d` (both f32, INOUT: the latent and its estimate + history). `order >= 1.5` selects the two-estimate form; below it the step is Euler, + `x = r x + (1 - r) d` -- the driver sets order 1 on the first step, after a schedule restart and + on the last. The driver's `hb1` and `hb2` keep `hb1 + hb2 == 1 - r` exactly, so the two branches + share the Euler limit and the difference is the second-order correction alone. `sigma`, `r`, + `hb1`, `hb2` and `order` are one f32 value each; `v` f32 or bf16. **The decoder** runs over a request's latent geometry, which `geom`, i32 on the device, carries (the parameters are fixed at declare). `mul`, `add`, `mean` and `std` are space-separated lists diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e61f3a6b..8044a11f 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -665,6 +665,8 @@ std::vector build_cases() { add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0), HF("max_period", 10000.0), HI("round", round), HS("dtype", dt) }); + for (int g : { 5, 1025 }) + add("timestep_embed", { HI("M", 3), HI("n", 8), HI("curve", g), HS("dtype", dt) }); add("lane_gather", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2), HS("dtype", dt) }); add("lane_store", { HI("M", 12), HI("n", 64), HI("stride", 16), HS("dtype", dt) }); diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index adca4328..d17d006c 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -406,7 +406,10 @@ AVX_KERNEL(rms_mod_quant_fp8) { return rms_mod_run(a, true); } /* ------------------------------------------------------------------ timestep_embed */ /* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})] with libref's libm - * calls: a pass embeds one row per entry, so this is a few thousand transcendentals. */ + * calls: a pass embeds one row per entry, so this is a few thousand transcendentals. With + * `curve` = G > 0 and a `table` [G, n] f32 operand, y[m] is that table sampled at + * clamp01(max(t[m], clamp_min)) * (G - 1) and lerped between the two rows around it instead -- + * the precomputed adaln curve a curve-form checkpoint ships in place of the sinusoid + MLP. */ AVX_KERNEL(timestep_embed) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *T = &a->t[0], *Y = &a->t[1]; @@ -415,9 +418,33 @@ AVX_KERNEL(timestep_embed) { const double mp = p_f32(a, "max_period", 10000.0f); const int round = (int)p_int(a, "round", 0); const float clamp = p_f32(a, "clamp_min", 0.0f); - if (n <= 0 || (n & 1)) return RAD_E_SHAPE; + const int64_t grid = p_int(a, "curve", 0); + if (n <= 0 || (!grid && (n & 1))) return RAD_E_SHAPE; const int64_t rows = rows_of(Y, n); if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE; + if (grid > 0) { + /* The precomputed adaln curve: y[m] = table sampled at clamp01(max(t, clamp_min)) * + * (grid - 1), lerped between the two rows around that position. */ + const RadTensor* tab = rad_arg_in(a, 2); + if (!tab) return RAD_E_INVAL; + if (tab->dtype != (uint32_t)RAD_F32 || numel(tab) < grid * n) return RAD_E_SHAPE; + float* buf = scratch_f32((size_t)n + 16); + for (int64_t m = 0; m < rows; ++m) { + const float tv = std::fmax(ldt(T, offlin(T, m)), clamp); + const float pos = std::fmin(std::fmax(tv, 0.0f), 1.0f) * (float)(grid - 1); + float i0f = std::floor(pos); + if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2); + const float fr = pos - i0f; + const int64_t i0 = (int64_t)i0f; + for (int64_t i = 0; i < n; ++i) { + const float a0 = ldt(tab, offlin(tab, i0 * n + i)); + const float a1 = ldt(tab, offlin(tab, (i0 + 1) * n + i)); + buf[i] = a0 + fr * (a1 - a0); + } + out_row(Y, rowoff(Y, m, n), n, buf); + } + return RAD_OK; + } const int64_t h = n / 2; const float coef = (float)(-std::log(mp)); float* buf = scratch_f32((size_t)(2 * n + 16)); diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 3c53e246..b0b4807f 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -488,8 +488,9 @@ static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD( static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"), OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") }; static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), - P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") }; -static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; + P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"), + P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y"), WGT_O("table") }; static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") }; static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") }; static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") }; diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index 870f0888..94295df0 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -216,6 +216,27 @@ __global__ __launch_bounds__(kT) void timestep_kernel( } } +// The curve form: y[m] = table sampled at clamp01(max(t[m], clamp_min)) * (grid - 1), lerped +// between the two rows around that position -- the precomputed adaln curve a curve-form +// checkpoint ships in place of the sinusoid + MLP. `table` is contiguous [grid, n] f32. +template +__global__ __launch_bounds__(kT) void timestep_curve_kernel( + const float* __restrict__ t, const float* __restrict__ table, TY* __restrict__ y, + int grid, int n, float clamp_min, int y_ld) { + const int m = blockIdx.x; + const float tv = fmaxf(t[m], clamp_min); + const float pos = fminf(fmaxf(tv, 0.0f), 1.0f) * (float)(grid - 1); + float i0f = floorf(pos); + if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2); /* torch lerp's clamp(max=G-2) */ + const float fr = pos - i0f; + const int i0 = (int)i0f; + for (int i = threadIdx.x; i < n; i += kT) { + const float a0 = table[(size_t)i0 * n + i]; + const float a1 = table[(size_t)(i0 + 1) * n + i]; + st1(y + (size_t)m * y_ld + i, a0 + fr * (a1 - a0)); + } +} + // ---------------------------------------------------------------------------- row moves __global__ __launch_bounds__(kT) void gather2_kernel( const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, const int* __restrict__ idx, @@ -753,18 +774,36 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) { } /* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep - * MLP kept in f32). */ + * MLP kept in f32). With `curve` = G > 0 and a `table` [G, n] f32 operand the sinusoid is replaced + * by a lerp over that precomputed adaln curve. */ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) { const RadTensor *t = r4d_opt(a, 0), *y = r4d_opt(a, 1); if (!t || !y) return R4D_NO(RAD_E_INVAL); if (t->dtype != RAD_F32 || !r4d_contig(t) || (!is_bf16(y) && y->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", 0); - if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE); + const long long grid = r4d_geti_or(a, "curve", 0); + if (n <= 0 || (!grid && (n & 1))) return R4D_NO(RAD_E_SHAPE); long long ry = 0; const long long yl = r4d_rows_pitch(y, n, &ry); if (yl < 0) return R4D_NO(RAD_E_STRIDE); if (ry <= 0 || r4d_numel(t) < ry) return R4D_NO(RAD_E_SHAPE); + if (grid > 0) { + const RadTensor* tab = r4d_opt(a, 2); + if (!tab) return R4D_NO(RAD_E_INVAL); + if (tab->dtype != RAD_F32 || !r4d_contig(tab) || r4d_numel(tab) < grid * n) + return R4D_NO(RAD_E_SHAPE); + const float clamp = (float)r4d_getf(a, "clamp_min", 0.0); + if (y->dtype == RAD_F32) + hipLaunchKernelGGL(timestep_curve_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const float*)t->data, (const float*)tab->data, + (float*)y->data, (int)grid, (int)n, clamp, (int)yl); + else + hipLaunchKernelGGL(timestep_curve_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const float*)t->data, (const float*)tab->data, + (uint16_t*)y->data, (int)grid, (int)n, clamp, (int)yl); + return st_of(hipGetLastError()); + } const float mp = (float)r4d_getf(a, "max_period", 10000.0); const float coef = (float)(-std::log((double)mp)); const float scale = (float)r4d_getf(a, "scale", 1000.0); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index dfcd270d..bd61ff19 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2133,8 +2133,10 @@ static const RadOperandSpec oGateAdd[] = { { "x", RAD_OPD_INOUT, 0 }, }; static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), - P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") }; -static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; + P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"), + P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, + { "table", RAD_OPD_WEIGHT, 1 } }; static const RadOperandSpec oGather2[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, }; @@ -2969,7 +2971,10 @@ static const RadOpSchema kSchemas[] = { "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; " "with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."), SCHEMA("timestep_embed", pTimestep, oTimestep, - "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2))."), + "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)). " + "With `curve` > 0 and a `table` [curve, n] f32 operand instead: y[m] is `table` sampled at " + "pos = clamp01(max(t[m], clamp_min)) * (curve - 1), linearly between the two rows around " + "pos -- an adaln time-embedding curve precomputed at convert."), SCHEMA("gather_rows2", pGenMn, oGather2, "y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]."), SCHEMA("lane_gather", pLane, oLaneGather, "y[cu[e] + k] = src[lane[e] * stride + k]."), @@ -4295,8 +4300,12 @@ static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") }; /* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */ static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) }; static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) }; -static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; -static const RadConstraint cGenTimestepF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; +/* No parity clause on `n` on either timestep row: a row's constraints are unconditional, and the + * sinusoid's parity floor (n is its angle pair count) would exclude a curve table, whose n is just + * the embedding's column count and can be odd. r4d_rad_timestep_embed checks parity itself when + * curve is 0, and returns RAD_E_SHAPE at issue for a sinusoid with odd n. */ +static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16") }; +static const RadConstraint cGenTimestepF32[] = { C_IN("dtype", "f32") }; /* The paged prefix at libr4d's block of 16, both caches bf16, up to eight query heads a KV head * (the shim takes 1, 2, 4 and 8). */ static const RadConstraint cAttnPrefixSelf[] = { diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 517fefaa..d2a8832c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -7638,6 +7638,35 @@ void timestep_f32_case(const Plugin& pl) { } } +/* The curve form: y[m] lerps the [G, n] f32 table at clamp01(max(t[m], clamp_min)) * (G - 1), + * clamping the lower row index to G - 2 -- the device mirror of comfy's adaln curve sampling. */ +void timestep_curve_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "timestep_embed_f32"); + if (!r) { ok("timestep_embed_f32 curve", false, "row absent"); return; } + const int64_t M = 33, n = 8, G = 1025; + std::vector t((size_t)M), tab = randv((size_t)(G * n), 1.0f); + for (int64_t m = 0; m < M; ++m) t[(size_t)m] = (float)m / (float)(M - 1); /* spans [0, 1] */ + void* dt = up_f32(t); + void* dtab = up_f32(tab); + void* dy = dalloc((size_t)(M * n) * 4); + const int rc = launch(r, { T(dt, RAD_F32, { M }), T(dy, RAD_F32, { M, n }), + T(dtab, RAD_F32, { G, n }) }, + { PI("M", M), PI("n", n), PI("curve", G), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok("timestep_embed_f32 curve", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + for (int64_t m = 0; m < M; ++m) { + const float pos = std::fmin(std::fmax(t[(size_t)m], 0.0f), 1.0f) * (float)(G - 1); + int64_t i0 = (int64_t)std::floor(pos); + if (i0 > G - 2) i0 = G - 2; + const float fr = pos - (float)i0; + for (int64_t i = 0; i < n; ++i) { + const float a0 = tab[(size_t)(i0 * n + i)], a1 = tab[(size_t)((i0 + 1) * n + i)]; + want[(size_t)(m * n + i)] = a0 + fr * (a1 - a0); + } + } + check_f32("timestep_embed_f32 curve numerics", down_f32(dy, want.size()), want, 1e-6); +} + void randn_f32_case(const Plugin& pl) { const RadKernelInfo* r = find(pl, "randn_lanes_f32"); if (!r) { ok("randn_lanes_f32", false, "row absent"); return; } @@ -19520,7 +19549,7 @@ static void device_phase(const Plugin& pl) { if (sel("silu_f32")) vg::silu_f32_cases(pl); if (sel("rmsnorm_bf16")) vg::norm_f32_rows_cases(pl, false); if (sel("layernorm_bf16")) vg::norm_f32_rows_cases(pl, true); - if (sel("timestep_embed_f32")) vg::timestep_f32_case(pl); + if (sel("timestep_embed_f32")) { vg::timestep_f32_case(pl); vg::timestep_curve_case(pl); } if (sel("randn_lanes_f32")) vg::randn_f32_case(pl); if (sel("interleave2_bf16")) vg::interleave2_f32_case(pl); if (sel("chan_affine_f32")) vg::chan_affine_cases(pl, "chan_affine_f32"); diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 82631361..bd0cce3c 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -268,7 +268,10 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { /* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where * f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value * diffusers' pipeline hands its transformer: t rounded to bf16 at scale, divided back and rounded - * again, then scaled: scale * bf16(bf16(t * scale) / scale). */ + * again, then scaled: scale * bf16(bf16(t * scale) / scale). + * With `curve` = G > 0 and a `table` [G, n] f32 operand instead: y[m] = table sampled at + * clamp01(max(t[m], clamp_min)) * (G - 1), lerped between the two rows around that position -- the + * precomputed adaln time curve a curve-form checkpoint ships in place of the sinusoid + MLP. */ int ref_timestep_embed(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *t = &a->t[0], *y = &a->t[1]; @@ -277,9 +280,33 @@ int ref_timestep_embed(const RadArgs* a, RadStream) { const double mp = p_f32(a, "max_period", 10000.0f); const int round = (int)p_int(a, "round", 0); const float clamp = p_f32(a, "clamp_min", 0.0f); - if (n <= 0 || (n & 1)) return RAD_E_SHAPE; + if (n <= 0) return RAD_E_SHAPE; + const int64_t grid = p_int(a, "curve", 0); + if (!grid && (n & 1)) return RAD_E_SHAPE; const int64_t rows = rows_of(y, n); if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE; + if (grid > 0) { + /* The precomputed adaln curve: y[m] = table sampled at clamp01(max(t, clamp_min)) * + * (grid - 1), lerped between the two rows around that position. */ + const RadTensor* tab = t_in(a, 2); + if (!tab) return RAD_E_INVAL; + if (tab->dtype != (uint32_t)RAD_F32 || numel(tab) < grid * n) return RAD_E_SHAPE; + for (int64_t m = 0; m < rows; ++m) { + const float tv = std::fmax(ldt(t, offlin(t, m)), clamp); + const float pos = std::fmin(std::fmax(tv, 0.0f), 1.0f) * (float)(grid - 1); + float i0f = std::floor(pos); + if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2); + const float fr = pos - i0f; + const int64_t i0 = (int64_t)i0f; + const int64_t yb = rowoff(y, m, n), ys = laststride(y); + for (int64_t i = 0; i < n; ++i) { + const float a0 = ldt(tab, offlin(tab, i0 * n + i)); + const float a1 = ldt(tab, offlin(tab, (i0 + 1) * n + i)); + stt(y, yb + i * ys, a0 + fr * (a1 - a0)); + } + } + return RAD_OK; + } const int64_t h = n / 2; const float coef = (float)(-std::log(mp)); for (int64_t m = 0; m < rows; ++m) { diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 26f53b0d..91e5bb73 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -680,8 +680,9 @@ static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD( static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"), OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") }; static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), - P_INTO("round"), P_F64O("clamp_min"), P_STR("dtype") }; -static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; + P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"), + P_STR("dtype") }; +static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y"), WGT_O("table") }; static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") }; static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") }; static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") }; @@ -1379,7 +1380,9 @@ static const RadOpSchema kSchemas[] = { { "timestep_embed", ARR(pTimestep), ARR(oTimestep), "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)) with " "t' = scale * t; `round` 1 takes t through bf16 at scale and back first, as diffusers' " - "pipeline hands it to its transformer." }, + "pipeline hands it to its transformer. With `curve` > 0 and a `table` [curve, n] f32 operand: " + "y[m] = table sampled at clamp01(max(t[m], clamp_min)) * (curve - 1), lerped between the two " + "rows around that position -- a precomputed adaln time-embedding curve." }, { "gather_rows2", ARR(pMnD), ARR(oGather2), "y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]: a sequence assembled from two sources." }, { "lane_gather", ARR(pLane), ARR(oLaneGather), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 780e272b..44302d3c 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2276,10 +2276,11 @@ int ref_gate_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("gate_add", operand, out); } int ref_timestep_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { - const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), G = gi(p, n_p, "curve", 0); Opd o; o.t_fill((uint32_t)RAD_F32, { M }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t: a sigma in (0, 1) */ o.t(act_dt(p, n_p), { M, n }); /* y */ + if (G > 0) o.t((uint32_t)RAD_F32, { G, n }); else o.skip(); /* table (curve mode) */ return o.finish("timestep_embed", operand, out); } int ref_gather_rows2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index f992ed5f..8311c7a2 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -305,7 +305,8 @@ TEST(op_vocabulary) { /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ - "rms_mod", "rms_mod_quant_fp8", "flow_x0_step", "patch_unfold", "vtile_gather", + "rms_mod", "rms_mod_quant_fp8", "flow_x0_step", "flow_res_multistep", "patch_unfold", + "vtile_gather", "vtile_stitch", "grid_pos3", "snake_aa", /* Its step-distilled form's video sparse attention: the tile selection and the * block-sparse attention over it. */ @@ -7123,6 +7124,9 @@ std::vector geometries() { 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).d("clamp_min", 0.3).s("dtype", "f32")), + /* The curve form: the same op over a precomputed table instead of the sinusoid. */ + G("timestep_embed", "M", 3, a.i("M", R).i("n", 8).i("curve", 5).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")), @@ -7169,6 +7173,7 @@ std::vector geometries() { G("rms_mod_quant_fp8", "M", 4, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16) .i("gated", 1).s("dtype", "bf16")), G("flow_x0_step", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("flow_res_multistep", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("patch_unfold", "M", 32, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2) .s("mul", "1 2 3").s("add", "0 1 2").s("dtype", "f32")), G("vtile_gather", "M", 60, a.i("M", R).i("n", 8).i("tile", 2).i("overlap", 1)