From 69087ce77314b77db614d0aae4be6f3201cdc136 Mon Sep 17 00:00:00 2001 From: gearwave00001 Date: Sun, 25 Oct 2026 09:52:15 -0500 Subject: [PATCH] minimaxh3+ops: a picture too big for one volume encodes tile-by-tile, as the reference does vae.py's tiled_encode cuts a picture bigger than tile_size (256 px, 16 latents) into overlapping tiles, encodes each tile alone, and blends every tile's RAW moments with its raw top and left neighbours -- top first, then left, never an already-blended neighbour -- into the whole latent canvas. GroupNorm normalises inside the volume it sees, so the tile seams are observable: our port ran the whole canvas through the trunk at once, and a photo or keyframe over 256 px a side drifted from the reference's look. Three ops, libref/avx/r4d alike. vtile_plan lays each tile's geometry rows the way vae.py splits -- round-robin slack, and one short tile on an axis no longer than a tile. vtile_crop cuts the picture's pixels tile-major. vtile_join blends the tile-major moments into the plain pass's b_eq2 with vae.py's weights, every product and sum rounding through x's dtype. The split carries one structural gift: with the slack fully distributed, start[last] = len - tile, so every band is exactly a tile, and a short band exists only in the single-band branch -- whose axis has no neighbour to blend against. The join can therefore fetch the left neighbour always at the full tile width while own and top fetch at the owner's own column width, and vae.py's min() clamp inside blend is provably dead code. step_venc_tiled runs the plain trunk once a tile: pixels from b_vtile, moments out to one slice of b_eqt, the tile's six level geometries read back off b_tplan (PERSIST) through raw pointers, exactly as every clip's geometries come off enc_geom_d. The arena packs by declared lifetime, so op_ve_q moved ahead of the trunk and the tiled ops sit last: b_vtile must span op_ve_pix's first read to op_vt_crop at the tail and b_eqt must span op_ve_q to op_vt_join, bracketing every trunk op the tiled pass re-runs. b_vtile and b_eqt size tile-major at the declared tile cap; a picture splitting past the cap step-fails by name. Clips never tile -- their volume forces each side back to kEncMaxSide. OPS.md documents all three. Verified: ref_test 264 cases (plan pins the round-robin overlaps {6,5,5} and a short lone row with column neighbours; crop walks a short band at ratio 4; join checks a 6x9 canvas with uneven round-robin splits point by point, and a 32x32 eighths-exact f32 blend that must land bit-identical); rad-avx-check scalar/avx/avx2 on all three ops; device r4d_selftest plan 4 / crop 8 (f32+bf16) / join 5 cases ok. Full ctest 123/123. ABI unchanged at 28. Co-Authored-By: Claude --- arch/minimaxh3/minimaxh3.cpp | 181 +++++++++++++++++++++++++-- docs/OPS.md | 38 ++++++ libavx/avx_cases.cpp | 16 +++ libavx/avx_isa.h | 1 + libavx/avx_registry.cpp | 31 +++++ libavx/avx_video.cpp | 166 ++++++++++++++++++++++++- libr4d/r4d_plugin.h | 3 + libr4d/r4d_rows.cpp | 51 ++++++++ libr4d/r4d_selftest.cpp | 231 +++++++++++++++++++++++++++++++++++ libr4d/r4d_video.hip | 199 +++++++++++++++++++++++++++++- libref/ref_ops.h | 6 + libref/ref_registry.cpp | 31 +++++ libref/ref_shapes.cpp | 60 +++++++++ libref/ref_video.cpp | 190 ++++++++++++++++++++++++++++ tests/ref_test.cpp | 217 ++++++++++++++++++++++++++++++++ 15 files changed, 1407 insertions(+), 14 deletions(-) diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index c6587f99..81655cc6 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -555,6 +555,13 @@ 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 */ + /* The tiled encode of one-frame media too big for one volume (comfy/ldm/minimax/vae.py's + * `tiled_encode`, step_venc_tiled): `b_tplan` the per-tile geometry table (PERSIST: every + * tile's level geometries are read back off it through raw pointers, so it lives the whole + * pass, not the plan op), `b_vtile` the picture's pixels cut tile-major, `b_eqt` the + * quant_conv moments tile-major (its rows can exceed the canvas: overlaps are kept twice). */ + rad_buf b_tplan = 0, b_vtile = 0, b_eqt = 0; + rad_op op_vt_plan = 0, op_vt_crop = 0, op_vt_join = 0; /* 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 @@ -2582,6 +2589,32 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 }); m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) }); const rad_buf st = m.b_egn; + /* The tiled encode's two scratch planes and the quant_conv, declared AHEAD of the trunk on + * purpose. The arena packs by declared lifetime (core/build/rad_bufplan.cpp), and the tiled + * pass runs the whole trunk once a tile: `b_vtile` holds every tile's pixels while the trunk + * buffers are rewritten tile after tile, and `b_eqt` holds the finished tiles' moments while + * the next tile's trunk runs. So both must overlap the trunk's every declared use, or the + * packer may place a trunk buffer right on top of them: `b_vtile`'s lifetime spans the first + * trunk op that reads it (op_ve_pix below, whose reads declare it) to op_vt_crop at the tail, + * `b_eqt`'s spans op_ve_q here to op_vt_join at the tail -- the trunk's whole op range sits + * inside both. The tiled ops themselves are therefore declared last. */ + m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 }, RAD_BUF_PERSIST); + m.b_vtile = decl_b(b, nm.f("venc.vtile"), RAD_F32, + { m.tiles * (int64_t)kEncMaxSide * kEncMaxSide, 3 }); + m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 }); + m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 }); + m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 }); + m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 }); + m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 }); + /* The whole-canvas pass writes b_eq2 (then the fold reads it); the tiled pass writes one + * tile's slice of b_eqt, and op_vt_join blends the whole tile-major plane into b_eq2. */ + m.op_ve_q = rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("cin", 48), + RAD_INT("cout", 48), RAD_INT("k", 1), RAD_INT("kt", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.ve_qw, m.ve_qb)), + { m.b_eq48 }, { m.b_eq2, m.b_eqt }); + if (!m.op_ve_q) return RAD_E_INVAL; m.op_ve_pix = rw(b, RAD_OP(b, "chan_affine", RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), RAD_STR("mul", m.ve_pix_mul.c_str()), @@ -2589,7 +2622,7 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_STR("mode", "fma"), RAD_INT("round", 0), RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), - {}, { m.b_epix32 }); + { m.b_vtile }, { m.b_epix32 }); m.op_ve_pcast = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), RAD_STR("from", "f32"), RAD_STR("to", "bf16")), @@ -2691,23 +2724,13 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { m.ve_now = wt(nm.f("venc.nout.weight"), nm.ckpt("vae.encoder.norm_out.weight"), { (int64_t)dims[5] }); m.ve_nob = wt(nm.f("venc.nout.bias"), nm.ckpt("vae.encoder.norm_out.bias"), { (int64_t)dims[5] }); - m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 }); - m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 }); m.op_ve_nout = venc_gn(b, R[5], (int64_t)dims[5], G, eps, m.ve_now, m.ve_nob, m.v_lv[5].a, m.v_lv[5].b, st); m.ve_coutw = wb(nm.f("venc.cout.weight"), nm.ckpt("vae.encoder.conv_out.weight"), { 48, (int64_t)dims[5], 3, 3, 3 }); m.ve_coutb = wt(nm.f("venc.cout.bias"), nm.ckpt("vae.encoder.conv_out.bias"), { 48 }); - m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 }); - m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 }); m.op_ve_cout = venc_conv(b, R[5], (int64_t)dims[5], 48, 3, m.ve_coutw, m.ve_coutb, m.v_lv[5].b, 0, m.b_eq48); - m.op_ve_q = rw(b, RAD_OP(b, "conv3d_ndhwc", - RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("cin", 48), - RAD_INT("cout", 48), RAD_INT("k", 1), RAD_INT("kt", 1), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(m.ve_qw, m.ve_qb)), - { m.b_eq48 }, { m.b_eq2 }); m.b_evc = decl_b(b, nm.f("lane.evc"), RAD_F32, { (int64_t)kEncSlotsV * kEncSlotRowsV, kPatchVals }, RAD_BUF_PERSIST); m.op_ve_fold = rw(b, RAD_OP(b, "patch_fold", @@ -2794,6 +2817,29 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { if (!m.op_ve_ldbg[L]) return RAD_E_INVAL; m.ve_l_bytes[L] = (int64_t)PF[L] * (int64_t)dims[L] * 4; } + /* The tiled encode's three ops, declared LAST so their buffers' lifetimes (b_vtile from + * op_ve_pix's reads to op_vt_crop's write, b_eqt from op_ve_q's writes to op_vt_join's read) + * bracket the whole trunk above -- the tiled pass runs that trunk once a tile, so neither + * plane may share arena bytes with any of it. See step_venc_tiled. */ + m.op_vt_plan = rw(b, RAD_OP(b, "vtile_plan", + RAD_PARAMS(RAD_RANGE("M", 1, m.tiles), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), + RAD_INT("ratio", kVaeRatio)), + RAD_NOWEIGHTS), + {}, { m.b_tplan }); + m.op_vt_crop = rw(b, RAD_OP(b, "vtile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, m.tiles * (int64_t)kEncMaxSide * kEncMaxSide), + RAD_INT("tile", kTile), RAD_INT("overlap", kOverlap), + RAD_INT("ratio", kVaeRatio), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_vtile }); + m.op_vt_join = rw(b, RAD_OP(b, "vtile_join", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), RAD_INT("n", 48), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eqt }, { m.b_eq2 }); + if (!m.op_vt_plan || !m.op_vt_crop || !m.op_vt_join) return RAD_E_INVAL; return RAD_OK; } @@ -4285,6 +4331,112 @@ static bool venc_dbg_shadows() { * through the six levels to the 48-column moments, the first 24 quantised and folded into the * lane's `b_evc` at the media's slot. The volumes come from the same geometry the driver staged * — re-derived here, which is also the batch's validation. */ +/* The tiled encode of a one-frame media -- comfy/ldm/minimax/vae.py's `tiled_encode`. A picture + * wider than a tile's side cannot ride the level buffers as one volume, so the reference cuts it + * into overlapping tiles, encodes each tile alone, and blends every tile's RAW moments with its + * raw top and left neighbours -- top first, then left, never an already-blended neighbour -- + * into the whole latent canvas. The three tiled ops above do exactly that: vtile_plan lays each + * tile's geometry rows the way vae.py splits, vtile_crop cuts the pixels tile-major, and + * vtile_join blends the tile-major moments into b_eq2. The loop here runs one tile through the + * plain trunk -- pixels in b_vtile, moments out to one slice of b_eqt, and the tile's own + * geometries read back off b_tplan through raw pointers, the same way every clip's geometries + * come off enc_geom_d. No debug shadows ride a tile: they shadow the whole canvas. The split is + * tile_starts' (diffusers' _split_tiles) with vae.py's one-tile answer -- an axis no longer than + * a tile is one tile, and the min() below lets that one tile be short. Returns the slot row one + * past this media's latents, like the clip loop below. */ +static int64_t step_venc_tiled(RadCtx* c, const RadVideoGenBatch* V, const Model& m, + const int32_t* gd, int64_t H, int64_t W, int64_t ppc, + const RadOperand st, int64_t row0) { + const int64_t lat_h = H / kVaeRatio, lat_w = W / kVaeRatio; + const std::vector ty = tile_starts(lat_h), tx = tile_starts(lat_w); + const int64_t nh = (int64_t)ty.size(), nw = (int64_t)tx.size(), nt = nh * nw; + if (nt > m.tiles) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose picture splits into more tiles than " + "the encoder declares room for"); + return row0; + } + /* The host mirror of vtile_plan: each tile's side in latents and its first row in each of + * the two tile-major planes. */ + struct Tile { int64_t prow, mrow, ny, nx; }; + std::vector tl; + tl.reserve((size_t)nt); + int64_t spx = 0, smom = 0; + for (int64_t i = 0; i < nh; ++i) + for (int64_t j = 0; j < nw; ++j) { + const int64_t ny = std::min((int64_t)kTile, lat_h - ty[(size_t)i]), + nx = std::min((int64_t)kTile, lat_w - tx[(size_t)j]); + tl.push_back({ spx, smom, ny, nx }); + spx += ny * nx * (int64_t)kVaeRatio * kVaeRatio; + smom += ny * nx; + } + RAD_ISSUE_N(c, m.op_vt_plan, nt, praw(gd, RAD_I32, 3), brows(m.b_tplan, nt)); + RAD_ISSUE_N(c, m.op_vt_crop, spx, praw2(V->enc_pixels, RAD_F32, H * W, 3), + praw(gd, RAD_I32, 3), brows(m.b_vtile, spx)); + const int32_t* tp = static_cast(rad_buf_ptr(c, m.b_tplan)); + for (size_t t = 0; t < tl.size(); ++t) { + const Tile& T = tl[t]; + const int64_t th = T.ny * kVaeRatio, tw = T.nx * kVaeRatio; /* the tile, in pixels */ + const int64_t Rpix = th * tw, R5 = T.ny * T.nx; + int64_t R[6]; + for (int L = 0; L < 6; ++L) { + const int64_t d = 1 << std::min(L, 4); /* the level's spatial divisor */ + R[L] = (th / d) * (tw / d); + } + /* The tile's plan row: its six {1, side, side} geometry entries, one frame deep. */ + const int32_t* tr = tp + 22 * (int64_t)t; + const RadOperand gg[6] = { praw(tr + 4, RAD_I32, 3), praw(tr + 7, RAD_I32, 3), + praw(tr + 10, RAD_I32, 3), praw(tr + 13, RAD_I32, 3), + praw(tr + 16, RAD_I32, 3), praw(tr + 19, RAD_I32, 3) }; + RAD_ISSUE_N(c, m.op_ve_pix, Rpix, brow_slice(m.b_vtile, T.prow, Rpix, 3), + brows(m.b_epix32, Rpix)); + RAD_ISSUE_N(c, m.op_ve_pcast, Rpix, brows(m.b_epix32, Rpix), brows(m.b_epix, Rpix)); + RAD_ISSUE_N(c, m.op_ve_cin, Rpix, brows(m.b_epix, Rpix), RAD_W(m.ve_cinw), + RAD_W(m.ve_cinb), gg[0], RAD_NONE, brows(m.v_lv[0].a, Rpix)); + for (int L = 0; L < 6; ++L) { + const Model::VEncLevel& E = m.v_lv[(size_t)L]; + const bool sc = E.op_sc; + for (int blk = 0; blk < 2; ++blk) { + const Model::VEncBlock& B = E.blk[blk]; + const bool f0 = blk == 0 && sc; + const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b; + /* The shortcut convolves the raw input, before norm1 normalises it -- exactly + * the ordering note of the plain loop. */ + if (f0) + RAD_ISSUE_N(c, E.op_sc, R[L], brows(E.in, R[L]), RAD_W(E.scw), RAD_W(E.scb), + gg[L], RAD_NONE, brows(E.a, R[L])); + RAD_ISSUE_N(c, B.op_n1, R[L], brows(xa, R[L]), RAD_W(B.n1w), RAD_W(B.n1b), + RAD_NONE, st, brows(nb, R[L])); + RAD_ISSUE_N(c, B.op_c1, R[L], brows(nb, R[L]), RAD_W(B.c1w), RAD_W(B.c1b), + gg[L], RAD_NONE, brows(E.c, R[L])); + RAD_ISSUE_N(c, B.op_n2, R[L], brows(E.c, R[L]), RAD_W(B.n2w), RAD_W(B.n2b), + RAD_NONE, st, brows(E.b, R[L])); + RAD_ISSUE_N(c, B.op_c2, R[L], brows(E.b, R[L]), RAD_W(B.c2w), RAD_W(B.c2b), + gg[L], brows(E.a, R[L]), brows(E.a, R[L])); + } + if (L < 4) { + const Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const rad_buf y = X.op_sc ? X.in : X.a; + RAD_ISSUE_N(c, E.op_dn, R[L + 1], brows(E.a, R[L]), RAD_W(E.dnw), RAD_W(E.dnb), + gg[L], RAD_NONE, brows(y, R[L + 1])); + } + } + 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_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, brow_slice(m.b_eqt, T.mrow, R5, 48)); + } + /* The blend over the whole canvas (gd's level-4/5 volume entry gives it in latents), then + * the plain path's fold -- the canvas is byte-identical in form to a one-clip encode's + * b_eq2, so nothing past here can tell the two paths apart. */ + RAD_ISSUE_N(c, m.op_vt_join, lat_h * lat_w, brows(m.b_eqt, smom), praw(gd + 12, RAD_I32, 3), + brows(m.b_eq2, lat_h * lat_w)); + RAD_ISSUE_N(c, m.op_ve_fold, ppc, bcol(m.b_eq2, 0, kC, lat_h * lat_w), + praw(gd + 18, RAD_I32, 3), brow_slice(m.b_evc, row0, ppc, kPatchVals)); + return row0 + ppc; +} + static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { const RadVideoGenBatch* V = batch->vgen_b; int32_t g[25]; @@ -4318,6 +4470,13 @@ static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { * there is no downsampler between the 512- and the 1024-wide level. */ static const int kVOrg[6] = { 0, 3, 6, 9, 12, 12 }; int64_t frow = row0; + /* A one-frame media wider than a tile's side (the reference's own condition: vae.py tiles + * its image encodes at exactly this size) goes through the tiled path; a clip never can, + * its volume forcing each side back to kEncMaxSide in venc_geom. */ + const bool tiled = V->enc_frames == 1 && (H / kVaeRatio > kTile || W / kVaeRatio > kTile); + if (tiled) + frow = step_venc_tiled(c, V, m, gd, H, W, ppc, st, row0); + else for (int64_t cc = 0; cc < n_clips; ++cc) { const bool last = cc == n_clips - 1; const int64_t R0 = (int64_t)g[0] * H * W; diff --git a/docs/OPS.md b/docs/OPS.md index eeb43cdf..a50cbc3f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1452,6 +1452,9 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi | `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` | +| `vtile_plan` | `M`(range) `tile` `overlap` `ratio` | `geom` → `y` | +| `vtile_crop` | `M`(range) `tile` `overlap` `ratio` `dtype` | `x`, `geom` → `y` | +| `vtile_join` | `M`(range) `tile` `overlap` `n` `dtype` | `x`, `geom` → `y` | | `grid_pos3` | `M`(range) `T` `H` `W` `period` `scale`:f64 | → `y` | **The transformer.** `cu_seqlens` partitions the rows into entries as for `ln_mod`, and each row @@ -1550,6 +1553,41 @@ written. `axial` then reads as f32 positions. MiniMax-H3: `T` 7, `H` 16, `W` 16, `period` 1797, `scale` `2 pi`. +**The tiled encoder** encodes a one-frame media bigger than the encoder's per-volume side the way +vae.py's `tiled_encode` encodes it (`comfy/ldm/minimax/vae.py`): the pixel plane is cut into tiles, +every tile goes through the whole encoder on its own, and the tiles' moments are blended back into +one latent plane. The encoder itself is the existing per-level ops, issued per tile at the plan's +geometries; these three ops are the plan, the cut and the blend. Their axis split is vae.py's +`split_tiles`, whose multi-tile branch is the decoder's rule above exactly but whose single-tile +branch answers one tile `[0, L)` even when `tile > L` -- a lone short tile, which the decoder's +exact-fit split refuses. MiniMax-H3: `tile` 16 latents, `overlap` 4, `ratio` 16. + +- `vtile_plan`: the plan for one frame of `geom` = `(clip, H, W)` pixels, split in latent units + over the spatial axes and numbered row-major over (row band, column band). Row `t` of the i32 + `y [M, 22]`: the tile's first pixel `(y0, x0)` at [0] [1], its pixel extent `(th, tw)` at + [2] [3] (`tile ratio`, save the lone short tile), and level `L`'s volume + `(1, th / 2^min(L, 4), tw / 2^min(L, 4))` at `3 L + 4` for `L = 0..5` -- the encoder's five + levels and the deepest one's repeat, which shares it. `M` is the tile count. +- `vtile_crop`: the frame's pixel plane `x [>= H W, 3]` (pixel `(Y, X)` at row `Y W + X`) cut into + the plan's tiles: `y [M, 3]` holds the tiles' pixels tile-major, tile `t`'s `(th, tw)` rows in + plane order at their offset in the sum; `M` is the tiles' pixel count. The tiles' union covers + the plane but their sum may exceed it, so `y` is its own buffer. +- `vtile_join`: the tiles' `n`-channel moments (`vtile_crop`'s row layout at latent extent) + blended into the canvas `y [M, n]` of `geom` = `(clip, lat_h, lat_w)` in latent units, `M` + `lat_h lat_w`. As in the stitch, canvas position `(Y, X)` belongs to the tile `(i, j)` whose + kept range holds it, `[start_i, start_{i+1})` (the last band to its end), at `(ly, lx)` within + it, `T(i, j, ly, lx)` that tile's stored value; but unlike the stitch the neighbours are **raw** + -- the encoder's output, never already blended -- and `rd`, `wa` and `wb` are as defined there, + rounding to `x`'s dtype: + + V = rd(rd(T(i-1, j, ly + tile - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev))) + when i > 0 and ly < ev = ov_y[i-1], else T(i, j, ly, lx) + y[(Y, X)] = rd(rd(T(i, j-1, ly, lx + tile - eh) wa(lx, eh)) + rd(V wb(lx, eh))) + when j > 0 and lx < eh = ov_x[j-1], else V + + Only a lone tile is short, and it has no neighbour, so a neighbour's extent along the blended + axis is always `tile`. + ### Video sparse attention MiniMax-H3's step-distilled form (FastH3) was trained with FastVideo's video sparse attention: a diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 6bb3773a..519a7b94 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -897,6 +897,22 @@ std::vector build_cases() { add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27), HF("scale", 6.283185307179586) }); + /* The tiled encoder over the shape functions' 20 x 20 latent plane: the encoder's tile 16 + * with its 4 overlap (two tiles an axis), and a 3-overlap-1 split (ten tiles an axis, one of + * slack round-robin) that puts a live blend on every interior row and column. crop is drawn + * at ratio 1 -- the plane is 20 x 20 pixels, its tiles' sum 30 x 30 either way; join reads + * the moments' 30 x 30 rows into the 400-row canvas. */ + add("vtile_plan", { HI("M", 4), HI("tile", 16), HI("overlap", 4), HI("ratio", 16) }); + add("vtile_plan", { HI("M", 100), HI("tile", 3), HI("overlap", 1), HI("ratio", 1) }); + add("vtile_crop", { HI("M", 1024), HI("tile", 16), HI("overlap", 4), HI("ratio", 1), + HS("dtype", "f32") }); + add("vtile_crop", { HI("M", 900), HI("tile", 3), HI("overlap", 1), HI("ratio", 1), + HS("dtype", "bf16") }); + add("vtile_join", { HI("M", 400), HI("tile", 16), HI("overlap", 4), HI("n", 48), + HS("dtype", "bf16") }); + add("vtile_join", { HI("M", 400), HI("tile", 3), HI("overlap", 1), HI("n", 5), + HS("dtype", "f32") }); + /* The latent upscaler over libref's cube volumes (c x c x c, the largest M holds; every geom * entry c, so the resize is the identity here): the 3-D convolution at odd channel counts, * kernels 3 x 3 x 3 and 3 x 1 x 1, with the residual (a separate buffer), and at MiniMax-H3's diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 4364d0d1..f15a5206 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -128,6 +128,7 @@ int avx_par_force(int threads); X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \ X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \ X(resize_bilinear) X(patch_fold) X(flow_renoise) X(cond_aug) \ + X(vtile_plan) X(vtile_crop) X(vtile_join) \ /* ---- LTX-2 */ \ X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \ X(d2s3d) X(s2d3d) X(pix_patch) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 189de75d..d992c776 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -634,6 +634,17 @@ static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("o P_INT("keep"), P_INT("blend"), P_INT("period"), P_STR("mean"), P_STR("std") }; static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") }; +/* The tiled encoder (avx_video.cpp), as libref declares it: `geom` is the request's + * (clip, H, W); plan and crop take it in pixels, join in latent units. */ +static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio") }; +static const RadOperandSpec oVtilePlan[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio"), P_STR("dtype") }; +static const RadOperandSpec oVtileCrop[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oVtileJoin[] = { OPD("x"), OPD("geom"), OUT("y") }; static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), P_INT("period"), P_F64("scale") }; static const RadOperandSpec oGridPos3[] = { OUT("y") }; @@ -1183,6 +1194,20 @@ static const RadOpSchema kSchemas[] = { { "vtile_stitch", ARR(pVtileStitch), ARR(oVtileStitch), "decoded tiles blended into frames, the chunk overlap blended and kept, RGB bytes out; bit for " "bit libref's." }, +{ "vtile_plan", ARR(pVtilePlan), ARR(oVtilePlan), + "the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: split_tiles_axis over " + "the spatial axes in latent units (tile, overlap, pixels per latent ratio), tiles row-major; " + "row t of the i32 [M, 22] y is the tile's first pixel (y0, x0), its pixel extent (th, tw) and " + "level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)) for L = 0..5; M is the tile count." }, +{ "vtile_crop", ARR(pVtileCrop), ARR(oVtileCrop), + "one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into vtile_plan's tiles: " + "y [M, 3] the tiles' pixels tile-major, M the tiles' pixel count (sum of th tw)." }, +{ "vtile_join", ARR(pVtileJoin), ARR(oVtileJoin), + "the tiled encoder's per-tile moments (vtile_crop's row layout at latent extent) blended into " + "the canvas y [M, n], M = geom's (clip, lat_h, lat_w) lat_h lat_w: a canvas position's tile " + "kept range, blended with the tile above and then the tile to the left, both RAW (never " + "already blended), the products and sums rounding to x's dtype as the reference's bf16 blends " + "do." }, { "grid_pos3", ARR(pGridPos3), ARR(oGridPos3), "a video decoder's rotary positions over its tiles, [3, >= M] at the operand's row pitch, bit " "for bit libref's." }, @@ -1764,6 +1789,12 @@ SIMPLE("avx_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out SIMPLE("avx_vtile_stitch", "vtile_stitch", "elem", "decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT, L(vtile_stitch)), +SIMPLE("avx_vtile_plan", "vtile_plan", "elem", "the tiled encoder's per-tile geometry table", + DT_ANY, L(vtile_plan)), +SIMPLE("avx_vtile_crop", "vtile_crop", "elem", "a frame's pixel plane cut into encode tiles", + DT_FLOAT, L(vtile_crop)), +SIMPLE("avx_vtile_join", "vtile_join", "elem", + "per-tile encoder moments blended into the latent canvas", DT_FLOAT, L(vtile_join)), SIMPLE("avx_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles", DT_FLOAT, L(grid_pos3)), SIMPLE("avx_vsa_select", "vsa_select", "attn", diff --git a/libavx/avx_video.cpp b/libavx/avx_video.cpp index 16d07281..f0b28523 100644 --- a/libavx/avx_video.cpp +++ b/libavx/avx_video.cpp @@ -1,7 +1,9 @@ /* avx_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video * generation"): the latent's patch rows unfolded to voxels, the tiles a video decoder runs over, * gathered from the latent and stitched back into frames, and the rotary positions of a tile's - * tokens; and its latent upscaler's (docs/OPS.md, "The latent upscaler"): the 3-D convolution, + * tokens; the encoder's plan, cut and blend for a picture too big for one volume (docs/OPS.md, + * "Video generation"); and its latent upscaler's (docs/OPS.md, "The latent upscaler"): the 3-D + * convolution, * the group norm, the temporal depthwise convolution, the per-frame resize, the fold back into * patch rows and the re-noising. * @@ -123,6 +125,19 @@ bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector* start, + std::vector* ov) { + if (tile >= len) { + start->clear(); + ov->clear(); + start->push_back(0); + return len > 0 && tile > 0 && overlap >= 0 && overlap < tile; + } + return split_tiles(len, tile, overlap, start, ov); +} + /* A row copied between operands, converted through f32 as libref's element loop is. Whole-byte * float rows of one dtype are copied as bytes, which is the same thing for every non-NaN value. */ inline void copy_row(const RadTensor* src, int64_t sb, const RadTensor* dst, int64_t db, int64_t n, @@ -440,6 +455,155 @@ AVX_KERNEL(vtile_stitch) { return RAD_OK; } +/* ================================================================== the tiled encoder + * A one-frame media bigger than the encoder's per-volume side is encoded the way vae.py's + * `tiled_encode` encodes it (libref's section comment): the plan, the cut, and the blend; the + * encoder itself is the existing per-level ops, issued per tile at the plan's geometries. */ + +/* ------------------------------------------------------------------ vtile_plan */ +/* The plan one frame's encode runs over (libref): geom = (clip, H, W) the frame's extent in + * pixels, split by split_tiles_axis over the spatial axes in latent units; row t of y (i32 + * [M, 22]) the tile's first pixel, its pixel extent, and the six level volumes. */ +AVX_KERNEL(vtile_plan) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *Y = &a->t[1]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t H = at(G, 1), W = at(G, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || H % ratio || W % ratio || + !split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) || + !split_tiles_axis(W / ratio, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + if (M != nh * nw || rows_of(Y, 22) < M) return RAD_E_SHAPE; + const int64_t* psy = sy.data(), *psx = sx.data(); + AVX_PARALLEL_FOR_IF(M >= AVX_PAR_MIN) + for (int64_t t = 0; t < M; ++t) { + const int64_t i = t / nw, j = t % nw; + const int64_t th = std::min(tile, H / ratio - psy[(size_t)i]) * ratio; + const int64_t tw = std::min(tile, W / ratio - psx[(size_t)j]) * ratio; + const int64_t yb = rowoff(Y, t, 22), ys = laststride(Y); + const int64_t v[22] = { psy[(size_t)i] * ratio, psx[(size_t)j] * ratio, th, tw, + 1, th, tw, 1, th / 2, tw / 2, 1, th / 4, tw / 4, + 1, th / 8, tw / 8, 1, th / 16, tw / 16, 1, th / 16, tw / 16 }; + for (int64_t c = 0; c < 22; ++c) st_int_dt(Y->dtype, Y->data, yb + c * ys, v[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_crop */ +/* One frame's pixel plane cut into the plan's tiles (libref): y f32 [M, 3] holds the tiles' + * pixels tile-major, M the tiles' pixel count. Only the row the tile stands on is read. */ +AVX_KERNEL(vtile_crop) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t H = at(G, 1), W = at(G, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || H % ratio || W % ratio || + !split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) || + !split_tiles_axis(W / ratio, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + std::vector off((size_t)(nh * nw + 1), 0); + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio; + for (int64_t j = 0; j < nw; ++j) + off[(size_t)(i * nw + j + 1)] = + off[(size_t)(i * nw + j)] + + th * std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + } + if (M != off.back() || rows_of(X, 3) < H * W || rows_of(Y, 3) < M) return RAD_E_SHAPE; + const int64_t* psy = sy.data(), *psx = sx.data(), *poff = off.data(); + AVX_PARALLEL_FOR_IF(M * 3 >= AVX_PAR_MIN) + for (int64_t r = 0; r < M; ++r) { + const int64_t t = + (int64_t)(std::upper_bound(poff, poff + nh * nw + 1, r) - poff) - 1; + const int64_t i = t / nw, j = t % nw; + const int64_t tw = std::min(tile, W / ratio - psx[(size_t)j]) * ratio; + const int64_t k = r - poff[t]; + const int64_t src = (psy[(size_t)i] * ratio + k / tw) * W + psx[(size_t)j] * ratio + k % tw; + const int64_t xb = rowoff(X, src, 3), yb = rowoff(Y, r, 3), xs = laststride(X); + const int64_t ys = laststride(Y); + for (int64_t c = 0; c < 3; ++c) stt(Y, yb + c * ys, ldt(X, xb + c * xs)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_join */ +/* The per-tile moments blended back into one latent plane (libref, vae.py's `tiled_encode` + * blend): RAW neighbours, the top blend before the left one, every product and sum a pass + * through x's dtype. */ +AVX_KERNEL(vtile_join) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), n = p_int(a, "n", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t H = at(G, 1), W = at(G, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || !split_tiles_axis(H, tile, overlap, &sy, &oy) || + !split_tiles_axis(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + if (M != H * W) return RAD_E_SHAPE; + std::vector off((size_t)(nh * nw + 1), 0); + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H - sy[(size_t)i]); + for (int64_t j = 0; j < nw; ++j) + off[(size_t)(i * nw + j + 1)] = + off[(size_t)(i * nw + j)] + th * std::min(tile, W - sx[(size_t)j]); + } + if (rows_of(X, n) < off.back() || rows_of(Y, n) < M) return RAD_E_SHAPE; + /* The owner tile of every canvas row and column. */ + std::vector own_y((size_t)H), own_x((size_t)W); + for (int64_t Yp = 0, i = 0; Yp < H; ++Yp) { + while (i + 1 < nh && Yp >= sy[(size_t)(i + 1)]) ++i; + own_y[(size_t)Yp] = i; + } + for (int64_t X0 = 0, j = 0; X0 < W; ++X0) { + while (j + 1 < nw && X0 >= sx[(size_t)(j + 1)]) ++j; + own_x[(size_t)X0] = j; + } + const uint32_t dt = X->dtype; + auto rd = [dt](float v) { return narrow1(dt, v); }; + auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); }; + auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); }; + const int64_t* psy = sy.data(), *psx = sx.data(), *poff = off.data(); + const int64_t* pown_y = own_y.data(), *pown_x = own_x.data(); + const int64_t xs = laststride(X), ys = laststride(Y); + auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) { + const int64_t row = poff[i * nw + j] + ly * std::min(tile, W - psx[(size_t)j]) + lx; + return ldt(X, rowoff(X, row, n) + c * xs); + }; + AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < M; ++r) { + const int64_t Yp = r / W, X0 = r % W; + const int64_t i = pown_y[Yp], j = pown_x[X0]; + const int64_t ly = Yp - psy[(size_t)i], lx = X0 - psx[(size_t)j]; + const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] : 0, eh = j > 0 ? ox[(size_t)(j - 1)] : 0; + const int64_t yb = rowoff(Y, r, n); + for (int64_t c = 0; c < n; ++c) { + float v = T(i, j, ly, lx, c); + if (ly < ev) + v = rd(rd(T(i - 1, j, ly + tile - ev, lx, c) * wa(ly, ev)) + + rd(v * wb(ly, ev))); + if (lx < eh) + v = rd(rd(T(i, j - 1, ly, lx + tile - eh, c) * wa(lx, eh)) + + rd(v * wb(lx, eh))); + stt(Y, yb + c * ys, v); + } + } + return RAD_OK; +} + /* ================================================================== the latent upscaler * Voxel rows (t, i, j) of a T x H x W volume, channels innermost, the volume in `geom`. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 41cf4bf5..9b6b3c92 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -260,6 +260,9 @@ int r4d_rad_flow_res_multistep (const RadArgs*, RadStream); int r4d_rad_patch_unfold (const RadArgs*, RadStream); int r4d_rad_vtile_gather (const RadArgs*, RadStream); int r4d_rad_vtile_stitch (const RadArgs*, RadStream); +int r4d_rad_vtile_plan (const RadArgs*, RadStream); +int r4d_rad_vtile_crop (const RadArgs*, RadStream); +int r4d_rad_vtile_join (const RadArgs*, RadStream); int r4d_rad_grid_pos3 (const RadArgs*, RadStream); int r4d_rad_snake_aa (const RadArgs*, RadStream); /* r4d_upscaler.hip: a video latent upscaler's 3D convolution, group norm, temporal depthwise diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index f8a3486d..03ede0b6 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2660,6 +2660,23 @@ static const RadOperandSpec oVtileStitch[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "prev", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +/* The tiled encoder (r4d_video.hip): the plan, the cut and the blend. `geom` is the request's + * (clip, H, W); plan and crop take it in pixels, join in latent units. */ +static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio") }; +static const RadOperandSpec oVtilePlan[] = { + { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio"), P_STR("dtype") }; +static const RadOperandSpec oVtileCrop[] = { + { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oVtileJoin[] = { + { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), P_INT("period"), P_F64("scale") }; static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } }; @@ -3600,6 +3617,19 @@ static const RadOpSchema kSchemas[] = { SCHEMA("vtile_stitch", pVtileStitch, oVtileStitch, "a decoded chunk's tiles stitched into RGB bytes, blended with the previous chunk's " "tail."), + SCHEMA("vtile_plan", pVtilePlan, oVtilePlan, + "the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: the encoder's " + "tile split over the spatial axes in latent units, tiles row-major; row t of the " + "i32 [M, 22] y is the tile's first pixel, its pixel extent and the six level " + "volumes (1, th / 2^min(L, 4), tw / 2^min(L, 4)); M is the tile count."), + SCHEMA("vtile_crop", pVtileCrop, oVtileCrop, + "one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into " + "vtile_plan's tiles: y [M, 3] the tiles' pixels tile-major, M the tiles' pixel " + "count."), + SCHEMA("vtile_join", pVtileJoin, oVtileJoin, + "the tiled encoder's per-tile moments blended into the canvas y [M, n] of " + "geom = (clip, lat_h, lat_w): each position blended with the tile above and then " + "the tile to the left, both RAW, the products and sums rounding to x's dtype."), SCHEMA("grid_pos3", pGridPos3, oGridPos3, "a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."), SCHEMA("conv3d_ndhwc", pConv3d, oConv3d, @@ -9313,6 +9343,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, 0, NOTUNE, nullptr, nullptr, r4d_rad_vtile_stitch }, +{ "vtile_plan", "vtile_plan", "elem", + "the tiled encoder's per-tile geometry table: a thread a (tile, entry)", + "any M; the split reads geom on the device", "i32 table, i32 geom", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_vtile_plan }, + +{ "vtile_crop", "vtile_crop", "elem", + "a frame's pixel plane cut into the encode tiles: a thread a tile pixel row", + "row pitches honoured", "f32 or bf16 plane and tiles", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_vtile_crop }, + +{ "vtile_join", "vtile_join", "elem", + "the encode tiles' moments blended into the latent canvas: a thread a canvas row", + "row pitches honoured", "f32 or bf16 moments and canvas", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_vtile_join }, + { "grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles", "a [3, M] view at its own pitch", "f32", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 67f3b460..5faadcfe 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -7493,6 +7493,234 @@ void vtile_stitch_cases(const Plugin& pl) { } } +/* libref's split_tiles_axis: the ENCODER's split, vae.py's `split_tiles` -- like `split` above, + * but a single axis no longer than the tile is one short tile rather than a refusal. */ +bool split_axis(int64_t len, int64_t tile, int64_t overlap, std::vector* st, + std::vector* ov) { + if (len > 0 && tile >= len) { + st->clear(); + ov->clear(); + st->push_back(0); + return overlap >= 0 && overlap < tile; + } + return split(len, tile, overlap, st, ov); +} + +/* The tiles' tile-major row offsets and per-band extents over a latent plane (libref's + * ref_vtile_join prefix sum; ref_vtile_crop's is the same with each extent ratio-squared). */ +void tile_offsets(const std::vector& sy, const std::vector& sx, int64_t H, + int64_t W, int64_t tile, std::vector* off) { + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + off->assign((size_t)(nh * nw + 1), 0); + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H - sy[(size_t)i]); + for (int64_t j = 0; j < nw; ++j) + (*off)[(size_t)(i * nw + j + 1)] = + (*off)[(size_t)(i * nw + j)] + th * std::min(tile, W - sx[(size_t)j]); + } +} + +/* vtile_plan: real H3 canvases and their encoder tiling -- 640 x 320 (2 x 2 ... 6 full tiles), + * a 128 x 96 lone short tile, 96 x 768 (one short row band, four columns whose overlaps 6, 5, 5 + * come out of the round-robin), and 320 x 560 (rows at 0, 4 with overlap 12, columns at 0, 9, 19 + * with overlaps 7 and 6). */ +void vtile_plan_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vtile_plan"); + if (!r) { ok("vtile_plan", false, "row absent"); return; } + const int64_t gs[][2] = { { 640, 320 }, { 128, 96 }, { 96, 768 }, { 320, 560 } }; + for (const auto& g : gs) { + const int64_t H = g[0], W = g[1]; + std::vector sy, sx, oy, ox; + split_axis(H / 16, 16, 4, &sy, &oy); + split_axis(W / 16, 16, 4, &sx, &ox); + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(), M = nh * nw; + void* dy = dalloc((size_t)(M * 22) * 4); + const std::string nm = fmt("vtile_plan %lld x %lld in %lld x %lld tiles", (long long)H, + (long long)W, (long long)nh, (long long)nw); + const int rc = launch(r, { TI32({ 3 }, { 1, (int32_t)H, (int32_t)W }), + T(dy, RAD_I32, { M, 22 }) }, + { PI("M", M), PI("tile", 16), PI("overlap", 4), PI("ratio", 16) }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * 22)); + for (int64_t i = 0; i < nh; ++i) + for (int64_t j = 0; j < nw; ++j) { + const int64_t th = std::min((int64_t)16, H / 16 - sy[(size_t)i]) * 16; + const int64_t tw = std::min((int64_t)16, W / 16 - sx[(size_t)j]) * 16; + int32_t* w = want.data() + (size_t)(i * nw + j) * 22; + w[0] = (int32_t)(sy[(size_t)i] * 16); + w[1] = (int32_t)(sx[(size_t)j] * 16); + w[2] = (int32_t)th; + w[3] = (int32_t)tw; + for (int L = 0; L < 6; ++L) { + const int64_t d = (int64_t)1 << std::min(L, 4); + w[4 + 3 * L] = 1; + w[5 + 3 * L] = (int32_t)(th / d); + w[6 + 3 * L] = (int32_t)(tw / d); + } + } + const int64_t bad = differ(down_i32(dy, want.size()), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld ints differ", (long long)bad)); + } +} + +/* vtile_crop: the plane cut tile-major over ratio-4 test shapes and the encoder's real ratio 16 + * -- a 96 x 768 short-row plane (the overlap column cut twice) and 320 x 560 -- in f32 and bf16. + * The crop is a copy, so both dtypes compare bit for bit. */ +void vtile_crop_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vtile_crop"); + if (!r) { ok("vtile_crop", false, "row absent"); return; } + const int64_t gs[][4] = { { 20, 20, 3, 1 }, { 8, 20, 3, 1 }, { 96, 768, 16, 4 }, + { 320, 560, 16, 4 } }; + for (const auto& g : gs) { + const int64_t H = g[0], W = g[1], tile = g[2], ov = g[3]; + const int64_t ratio = tile > 4 ? 16 : 4; + std::vector sy, sx, oy, ox, off; + split_axis(H / ratio, tile, ov, &sy, &oy); + split_axis(W / ratio, tile, ov, &sx, &ox); + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + off.assign((size_t)(nh * nw + 1), 0); /* pixel counts: tile t covers th tw pixels */ + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio; + for (int64_t j = 0; j < nw; ++j) + off[(size_t)(i * nw + j + 1)] = + off[(size_t)(i * nw + j)] + + th * std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + } + const int64_t M = off.back(); + for (const bool bf : { false, true }) { + std::vector x = randv((size_t)(H * W * 3), 2.0f); + void* dx = bf ? up_bf16(x) : up_f32(x); + const uint32_t dt = bf ? RAD_BF16 : RAD_F32; + void* dy = dalloc((size_t)(M * 3) * (bf ? 2 : 4)); + const std::string nm = fmt("vtile_crop %lld x %lld %s tile %lld", (long long)H, + (long long)W, bf ? "bf16" : "f32", (long long)tile); + const int rc = launch(r, { T(dx, dt, { H * W, 3 }), TI32({ 3 }, { 1, (int32_t)H, (int32_t)W }), + T(dy, dt, { M, 3 }) }, + { PI("M", M), PI("tile", tile), PI("overlap", ov), + PI("ratio", ratio), PS("dtype", bf ? "bf16" : "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * 3)); + for (int64_t rr = 0; rr < M; ++rr) { + int64_t t = 0; + while (t + 1 < (int64_t)off.size() && rr >= off[(size_t)(t + 1)]) ++t; + const int64_t k = rr - off[(size_t)t], i = t / nw, j = t % nw; + const int64_t tw = std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + const int64_t src = (sy[(size_t)i] * ratio + k / tw) * W + sx[(size_t)j] * ratio + k % tw; + for (int64_t c = 0; c < 3; ++c) + want[(size_t)(rr * 3 + c)] = x[(size_t)(src * 3 + c)]; + } + const std::vector got = bf ? down_bf16(dy, want.size()) : down_f32(dy, want.size()); + const int64_t bad = differ(got, want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld values differ", (long long)bad)); + } + } +} + +/* vtile_join: the per-tile moments blended back, top then left, against RAW neighbours. bf16 over + * random values (the tile walks, the uneven 6 x 9 and 20 x 35 splits, a short lone row and a + * lone short tile), and one f32 geometry -- 32 x 32 in 3 x 3 tiles split at 0, 8, 16, where every + * weight is an eighth and every blend is exact to the last bit. */ +void vtile_join_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vtile_join"); + if (!r) { ok("vtile_join", false, "row absent"); return; } + const int64_t gs[][5] = { { 6, 9, 4, 1, 5 }, { 3, 3, 4, 2, 1 }, { 1, 20, 16, 4, 3 }, + { 20, 35, 16, 4, 48 } }; + for (const auto& g : gs) { + const int64_t H = g[0], W = g[1], tile = g[2], ov = g[3], n = g[4]; + std::vector sy, sx, oy, ox, off; + split_axis(H, tile, ov, &sy, &oy); + split_axis(W, tile, ov, &sx, &ox); + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + tile_offsets(sy, sx, H, W, tile, &off); + const int64_t Sm = off.back(), M = H * W; + std::vector x = randv((size_t)(Sm * n), 2.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(M * n) * 2); + const std::string nm = fmt("vtile_join %lld x %lld bf16 tile %lld", (long long)H, + (long long)W, (long long)tile); + const int rc = launch(r, { T(dx, RAD_BF16, { Sm, n }), TI32({ 3 }, { 1, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("tile", tile), PI("overlap", ov), PI("n", n), + PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + /* The blends round to bf16 at every step, as the kernel's rdv does. */ + auto rd = [](float v) { return bfr(v); }; + auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); }; + auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); }; + auto Tv = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) { + return x[(size_t)((off[(size_t)(i * nw + j)] + + ly * std::min(tile, W - sx[(size_t)j]) + lx) * n + c)]; + }; + std::vector want((size_t)(M * n)); + for (int64_t rr = 0; rr < M; ++rr) { + const int64_t Y = rr / W, X = rr % W; + int64_t i = 0, j = 0; + while (i + 1 < nh && Y >= sy[(size_t)(i + 1)]) ++i; + while (j + 1 < nw && X >= sx[(size_t)(j + 1)]) ++j; + const int64_t ly = Y - sy[(size_t)i], lx = X - sx[(size_t)j]; + const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] : 0; + const int64_t eh = j > 0 ? ox[(size_t)(j - 1)] : 0; + for (int64_t c = 0; c < n; ++c) { + float v = Tv(i, j, ly, lx, c); + if (ly < ev) + v = rd(rd(Tv(i - 1, j, ly + tile - ev, lx, c) * wa(ly, ev)) + + rd(v * wb(ly, ev))); + if (lx < eh) + v = rd(rd(Tv(i, j - 1, ly, lx + tile - eh, c) * wa(lx, eh)) + + rd(v * wb(lx, eh))); + want[(size_t)(rr * n + c)] = v; + } + } + const int64_t bad = differ(down_bf16(dy, want.size()), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld values differ", (long long)bad)); + } + /* 32 x 32 in 3 x 3 tiles split at 0, 8, 16 (the slack of 8 round-robin makes both overlaps + * 8): every weight is an eighth and every blend of these integer values is exact to the + * last bit, so f32 device and host must agree bit for bit. */ + { + const int64_t H = 32, W = 32, tile = 16, ov = 4, n = 3; + std::vector x((size_t)(9 * tile * tile * n)); + for (size_t i = 0; i < x.size(); ++i) x[i] = (float)(i % 5 + 1); + void* dx = up_f32(x); + void* dy = dalloc((size_t)(H * W * n) * 4); + const int rc = launch(r, { T(dx, RAD_F32, { 9 * tile * tile, n }), + TI32({ 3 }, { 1, (int32_t)H, (int32_t)W }), + T(dy, RAD_F32, { H * W, n }) }, + { PI("M", H * W), PI("tile", tile), PI("overlap", ov), PI("n", n), + PS("dtype", "f32") }); + if (rc != RAD_OK) { ok("vtile_join 32 x 32 exact f32", false, "rc " + std::to_string(rc)); } + else { + const int64_t st[3] = { 0, 8, 16 }; + auto Tv = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) { + return x[(size_t)(((i * 3 + j) * tile * tile + ly * tile + lx) * n + c)]; + }; + std::vector want((size_t)(H * W * n)); + for (int64_t Y = 0; Y < H; ++Y) + for (int64_t X = 0; X < W; ++X) { + int64_t i = 0, j = 0; + while (i + 1 < 3 && Y >= st[i + 1]) ++i; + while (j + 1 < 3 && X >= st[j + 1]) ++j; + const int64_t ly = Y - st[i], lx = X - st[j]; + const int64_t ev = i > 0 ? 8 : 0, eh = j > 0 ? 8 : 0; + for (int64_t c = 0; c < n; ++c) { + float v = Tv(i, j, ly, lx, c); + if (ly < ev) { + const float wa = 1.0f - (float)ly / 8.0f, wb = (float)ly / 8.0f; + v = (Tv(i - 1, j, ly + 16 - 8, lx, c) * wa) + (v * wb); + } + if (lx < eh) { + const float wa = 1.0f - (float)lx / 8.0f, wb = (float)lx / 8.0f; + v = (Tv(i, j - 1, ly, lx + 16 - 8, c) * wa) + (v * wb); + } + want[(size_t)((Y * W + X) * n + c)] = v; + } + } + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok("vtile_join 32 x 32 exact f32", bad == 0, fmt("%lld values differ", (long long)bad)); + } + } +} + /* rms_mod and rms_mod_quant_fp8 at the DiT's width over three segments, the table and the gate a * column slice of a wider row as the plugin reads them, gated and not. The residual is exact; the @@ -27892,6 +28120,9 @@ static void device_phase(const Plugin& pl) { if (sel("patch_unfold_f32")) vid::patch_unfold_cases(pl); if (sel("vtile_gather")) vid::vtile_gather_cases(pl); if (sel("vtile_stitch")) vid::vtile_stitch_cases(pl); + if (sel("vtile_plan")) vid::vtile_plan_cases(pl); + if (sel("vtile_crop")) vid::vtile_crop_cases(pl); + if (sel("vtile_join")) vid::vtile_join_cases(pl); if (sel("rms_mod_bf16")) vid::rms_mod_cases(pl, false); if (sel("rms_mod_quant_fp8_bf16")) vid::rms_mod_cases(pl, true); if (sel("flow_x0_step_f32")) vid::flow_x0_cases(pl); diff --git a/libr4d/r4d_video.hip b/libr4d/r4d_video.hip index e5091b39..a96d43f6 100644 --- a/libr4d/r4d_video.hip +++ b/libr4d/r4d_video.hip @@ -1,7 +1,8 @@ // R4D -- the video generator's ops (docs/OPS.md, "Video generation"): a diffusion transformer's // modulated RMS norm and its sampler step, the video decoder's patch unfold, the tiles it runs -// over, their stitch back into frames and their rotary positions; and its soundtrack decoder's -// alias-free SnakeBeta (docs/OPS.md, "Audio generation"). +// over, their stitch back into frames and their rotary positions; the video encoder's plan, cut +// and blend for a picture bigger than one volume; and its soundtrack decoder's alias-free +// SnakeBeta (docs/OPS.md, "Audio generation"). // // Each kernel rounds where its libref function does (libref/ref_gen.cpp, libref/ref_video.cpp, // libref/ref_audio.cpp), under the library's -ffp-contract=off. The norm's sum of squares is a @@ -277,6 +278,21 @@ __device__ __forceinline__ Tiles split_tiles(int len, int tile, int overlap) { return t; } +// The encoder's split over one axis (libref's split_tiles_axis, vae.py's `split_tiles`): a tile at +// least as long as the axis is ONE tile over the whole axis, short if need be, where the decoder's +// split above demands an exact fit. A lone tile reads no overlap and starts at 0, which the closed +// form above already gives at n = 1. +__device__ __forceinline__ Tiles split_tiles_axis(int len, int tile, int overlap) { + if (tile >= len && len > 0 && tile > 0 && overlap >= 0 && overlap < tile) { + Tiles t; + t.n = 1; + t.tile = tile; + t.overlap = overlap; + return t; + } + return split_tiles(len, tile, overlap); +} + // ---------------------------------------------------------------------------- vtile_gather // A workgroup a tile row: its voxel from x, a register token from `reg`, or zeros. template @@ -383,6 +399,119 @@ __global__ __launch_bounds__(kT) void vtile_stitch_kernel( } } +// ---------------------------------------------------------------------------- the tiled encoder +// A one-frame media bigger than the encoder's per-volume side is encoded the way vae.py's +// `tiled_encode` encodes it: the plan, the cut and the blend (libref's ref_vtile_plan/crop/join); +// the encoder itself is the existing per-level ops, issued per tile at the plan's geometries. + +// A thread a (tile, entry): the tile's first pixel, its pixel extent and the six level volumes, +// as ref_vtile_plan's row of 22 i32. +__global__ __launch_bounds__(kT) void vtile_plan_kernel( + const int* __restrict__ geom, int* __restrict__ y, int tile, int overlap, int ratio, int y_ld, + int64_t M, int64_t y_rows) { + const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x; + const int H = geom[1], W = geom[2]; + if (id >= M * 22 || id >= y_rows * 22 || H <= 0 || W <= 0 || H % ratio || W % ratio) return; + const Tiles ty = split_tiles_axis(H / ratio, tile, overlap); + const Tiles tx = split_tiles_axis(W / ratio, tile, overlap); + if (ty.n == 0 || tx.n == 0) return; + const int64_t t = id / 22; + const int c = (int)(id % 22); + const int nh = ty.n, nw = tx.n; + if (t >= (int64_t)nh * nw) return; + const int i = (int)(t / nw), j = (int)(t % nw); + const int th = min(tile, H / ratio - ty.start(i)) * ratio; + const int tw = min(tile, W / ratio - tx.start(j)) * ratio; + int v; + if (c < 4) { + v = c == 0 ? ty.start(i) * ratio : c == 1 ? tx.start(j) * ratio : c == 2 ? th : tw; + } else { + const int L = (c - 4) / 3, k = (c - 4) % 3, d = 1 << min(L, 4); + v = k == 0 ? 1 : k == 1 ? th / d : tw / d; + } + y[t * y_ld + c] = v; +} + +// A thread a tile pixel row: its plane row copied. The tile is found by walking the tiles' sizes, +// at most a hundred of them (libref's upper_bound over the same prefix sums). +template +__global__ __launch_bounds__(kT) void vtile_crop_kernel( + const T* __restrict__ x, const int* __restrict__ geom, T* __restrict__ y, int tile, + int overlap, int ratio, int x_ld, int y_ld, int64_t M, int64_t x_rows, int64_t y_rows) { + const int64_t r = (int64_t)blockIdx.x * kT + threadIdx.x; + const int H = geom[1], W = geom[2]; + if (r >= M || r >= y_rows || H <= 0 || W <= 0 || H % ratio || W % ratio) return; + const Tiles ty = split_tiles_axis(H / ratio, tile, overlap); + const Tiles tx = split_tiles_axis(W / ratio, tile, overlap); + if (ty.n == 0 || tx.n == 0 || (int64_t)H * W > x_rows) return; + const int nh = ty.n, nw = tx.n; + int t = -1; + int64_t acc = 0, k = 0; + for (int tt = 0; tt < nh * nw; ++tt) { + const int64_t sz = (int64_t)min(tile, H / ratio - ty.start(tt / nw)) * ratio * + min(tile, W / ratio - tx.start(tt % nw)) * ratio; + if (r < acc + sz) { t = tt; k = r - acc; break; } + acc += sz; + } + if (t < 0) return; // r past the tiles' sum: M was not it + const int tw = min(tile, W / ratio - tx.start(t % nw)) * ratio; + const int64_t src = ((int64_t)ty.start(t / nw) * ratio + k / tw) * W + + (int64_t)tx.start(t % nw) * ratio + k % tw; + for (int c = 0; c < 3; ++c) stv(y + r * (int64_t)y_ld, c, ldv(x + src * (int64_t)x_ld, c)); +} + +// A thread a canvas row: its three tiles' moments blended, top first then left, RAW neighbours, +// every product and sum rounded to x's dtype -- ref_vtile_join's rule, vae.py's `tiled_encode` +// blend. A thread per (row, channel) would recompute the tile walk n times. +template +__global__ __launch_bounds__(kT) void vtile_join_kernel( + const T* __restrict__ x, const int* __restrict__ geom, T* __restrict__ y, int tile, + int overlap, int n, int x_ld, int y_ld, int64_t M, int64_t x_rows, int64_t y_rows) { + const int64_t r = (int64_t)blockIdx.x * kT + threadIdx.x; + const int H = geom[1], W = geom[2]; + if (r >= M || r >= y_rows || r >= (int64_t)H * W || H <= 0 || W <= 0) return; + const Tiles ty = split_tiles_axis(H, tile, overlap), tx = split_tiles_axis(W, tile, overlap); + if (ty.n == 0 || tx.n == 0) return; + const int nh = ty.n, nw = tx.n; + // The tiles' row extents and their prefix sums, in tile-major order. + const int64_t ext_y = nh == 1 ? H : (int64_t)tile * nh, ext_x = nw == 1 ? W : (int64_t)tile * nw; + if (ext_y * ext_x > x_rows) return; + auto sz = [&](int ii, int jj) { + return (int64_t)min(tile, H - ty.start(ii)) * min(tile, W - tx.start(jj)); + }; + auto off = [&](int ii, int jj) { + int64_t a = 0; + for (int t = 0; t < ii * nw + jj; ++t) a += sz(t / nw, t % nw); + return a; + }; + const int Y = (int)(r / W), X = (int)(r % W); + int i = 0; + while (i + 1 < nh && Y >= ty.start(i + 1)) ++i; + int j = 0; + while (j + 1 < nw && X >= tx.start(j + 1)) ++j; + const int ly = Y - ty.start(i), lx = X - tx.start(j); + const int ev = i > 0 ? ty.ov(i - 1) : 0, eh = j > 0 ? tx.ov(j - 1) : 0; + const int64_t own = off(i, j), up = i > 0 ? off(i - 1, j) : 0, left = j > 0 ? off(i, j - 1) : 0; + // Each tile's own width: own and up share this tile's column (`own_w`, short only in the + // last column); the left neighbour sits in column j-1, never the last, so its width is the + // full `tile`. libref indexes every tile by its own column's width, and these are those. + const int own_w = min(tile, W - tx.start(j)); + const auto fetch = [&](int64_t base, int w, int ay, int ax, int c) { + return ldv(x, (base + (int64_t)ay * w + ax) * x_ld + c); + }; + auto rd = [&](float v) { return rdv(x, v); }; + auto wb = [&](int p, int e) { return rd((float)p / (float)e); }; + auto wa = [&](int p, int e) { return rd(1.0f - rd((float)p / (float)e)); }; + for (int c = 0; c < n; ++c) { + float v = fetch(own, own_w, ly, lx, c); + if (ly < ev) + v = rd(rd(fetch(up, own_w, ly + tile - ev, lx, c) * wa(ly, ev)) + rd(v * wb(ly, ev))); + if (lx < eh) + v = rd(rd(fetch(left, tile, ly, lx + tile - eh, c) * wa(lx, eh)) + rd(v * wb(lx, eh))); + stv(y + r * (int64_t)y_ld, c, v); + } +} + // ---------------------------------------------------------------------------- grid_pos3 // A thread a row: its token's three centred, scaled coordinates, or zeros past the tile's tokens. __global__ __launch_bounds__(kT) void grid_pos3_kernel( @@ -722,6 +851,72 @@ extern "C" int r4d_rad_vtile_stitch(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_vtile_plan(const RadArgs* a, RadStream s) { + const RadTensor *geom = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!geom || !y) return R4D_NO(RAD_E_INVAL); + if (!is_i32(geom) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE); + const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0); + const long long overlap = r4d_geti_or(a, "overlap", 0), ratio = r4d_geti_or(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || + r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + long long ry = 0; + const long long yl = r4d_rows_pitch(y, 22, &ry); + if (yl < 0 || !r4d_contig(geom) || ry < M) return R4D_NO(RAD_E_STRIDE); + const int64_t total = (int64_t)M * 22; + hipLaunchKernelGGL(vtile_plan_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, + (const int*)geom->data, (int*)y->data, (int)tile, (int)overlap, (int)ratio, + (int)yl, M, ry); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vtile_crop(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_f32(x) && !is_bf16(x)) || x->dtype != y->dtype || !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0); + const long long overlap = r4d_geti_or(a, "overlap", 0), ratio = r4d_geti_or(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || + r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, 3, &rx), yl = r4d_rows_pitch(y, 3, &ry); + if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + if (ry < M) return R4D_NO(RAD_E_SHAPE); +#define R4D_VTC(T) \ + hipLaunchKernelGGL((vtile_crop_kernel), dim3(blocks_for(M)), dim3(kT), 0, (hipStream_t)s, \ + (const T*)x->data, (const int*)geom->data, (T*)y->data, (int)tile, \ + (int)overlap, (int)ratio, (int)xl, (int)yl, M, rx, ry) + if (is_f32(x)) R4D_VTC(float); + else R4D_VTC(uint16_t); +#undef R4D_VTC + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vtile_join(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_f32(x) && !is_bf16(x)) || x->dtype != y->dtype || !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0); + const long long overlap = r4d_geti_or(a, "overlap", 0), n = r4d_geti_or(a, "n", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry); + if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + if (ry < M) return R4D_NO(RAD_E_SHAPE); +#define R4D_VTJ(T) \ + hipLaunchKernelGGL((vtile_join_kernel), dim3(blocks_for(M)), dim3(kT), 0, (hipStream_t)s, \ + (const T*)x->data, (const int*)geom->data, (T*)y->data, (int)tile, \ + (int)overlap, (int)n, (int)xl, (int)yl, M, rx, ry) + if (is_f32(x)) R4D_VTJ(float); + else R4D_VTJ(uint16_t); +#undef R4D_VTJ + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_grid_pos3(const RadArgs* a, RadStream s) { const RadTensor* y = r4d_opt(a, 0); if (!y) return R4D_NO(RAD_E_INVAL); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 8dca847f..c591893a 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -185,6 +185,9 @@ int ref_tconv_dw(const RadArgs*, RadStream); int ref_resize_bilinear(const RadArgs*, RadStream); int ref_flow_renoise(const RadArgs*, RadStream); int ref_cond_aug(const RadArgs*, RadStream); +int ref_vtile_plan(const RadArgs*, RadStream); +int ref_vtile_crop(const RadArgs*, RadStream); +int ref_vtile_join(const RadArgs*, RadStream); /* ref_ltx.cpp */ int ref_rope_split(const RadArgs*, RadStream); int ref_head_gate(const RadArgs*, RadStream); @@ -439,6 +442,9 @@ REF_SHAPE_FN(ref_tconv_dw); REF_SHAPE_FN(ref_resize_bilinear); REF_SHAPE_FN(ref_flow_renoise); REF_SHAPE_FN(ref_cond_aug); +REF_SHAPE_FN(ref_vtile_plan); +REF_SHAPE_FN(ref_vtile_crop); +REF_SHAPE_FN(ref_vtile_join); REF_SHAPE_FN(ref_rope_split); REF_SHAPE_FN(ref_head_gate); REF_SHAPE_FN(ref_ltx_guide); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 78f256c8..4cdf51e8 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -845,6 +845,17 @@ static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("o P_INT("keep"), P_INT("blend"), P_INT("period"), P_STR("mean"), P_STR("std") }; static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") }; +/* The tiled encoder (ref_video.cpp): the plan, the cut and the blend. `geom` is the request's + * (clip, H, W); plan and crop take it in pixels, join in latent units. */ +static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio") }; +static const RadOperandSpec oVtilePlan[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("ratio"), P_STR("dtype") }; +static const RadOperandSpec oVtileCrop[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oVtileJoin[] = { OPD("x"), OPD("geom"), OUT("y") }; /* `y` is [3, >= M], component-major at its own row pitch. */ static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), P_INT("period"), P_F64("scale") }; @@ -1764,6 +1775,20 @@ static const RadOpSchema kSchemas[] = { "with `prev` unless the chunk is first, prev refilled from the chunk's tail (also emitted " "when it is last), then bytes round(255 clamp(v std + mean, 0, 1)); geom = (frames, H, W, " "first, last), u8 out." }, +{ "vtile_plan", ARR(pVtilePlan), ARR(oVtilePlan), + "the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: split_tiles_axis over " + "the spatial axes in latent units (tile, overlap, pixels per latent ratio), tiles row-major; " + "row t of the i32 [M, 22] y is the tile's first pixel (y0, x0), its pixel extent (th, tw) and " + "level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)) for L = 0..5; M is the tile count." }, +{ "vtile_crop", ARR(pVtileCrop), ARR(oVtileCrop), + "one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into vtile_plan's tiles: " + "y [M, 3] the tiles' pixels tile-major, M the tiles' pixel count (sum of th tw)." }, +{ "vtile_join", ARR(pVtileJoin), ARR(oVtileJoin), + "the tiled encoder's per-tile moments (vtile_crop's row layout at latent extent) blended into " + "the canvas y [M, n], M = geom's (clip, lat_h, lat_w) lat_h lat_w: a canvas position's tile " + "kept range, blended with the tile above and then the tile to the left, both RAW (never " + "already blended), the products and sums rounding to x's dtype as the reference's bf16 blends " + "do." }, { "grid_pos3", ARR(pGridPos3), ARR(oGridPos3), "a video decoder's rotary positions over tiles of `period` rows: token (t, i, j) of a tile's " "T x H x W gets f32(scale) * (2 (c + 0.5) / n - 1) on each axis, in f32 as torch makes it, " @@ -2439,6 +2464,12 @@ SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out SIMPLE("ref_vtile_stitch", "vtile_stitch", "elem", "decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT, ref_vtile_stitch), +SIMPLE("ref_vtile_plan", "vtile_plan", "elem", "the tiled encoder's per-tile geometry table", + DT_ANY, ref_vtile_plan), +SIMPLE("ref_vtile_crop", "vtile_crop", "elem", "a frame's pixel plane cut into encode tiles", + DT_FLOAT, ref_vtile_crop), +SIMPLE("ref_vtile_join", "vtile_join", "elem", + "per-tile encoder moments blended into the latent canvas", DT_FLOAT, ref_vtile_join), SIMPLE("ref_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles", DT_FLOAT, ref_grid_pos3), SIMPLE("ref_vsa_select", "vsa_select", "attn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index b6414148..14fadb41 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -2991,6 +2991,22 @@ static int64_t tile_count(int64_t len, int64_t tile, int64_t overlap) { return nt; } +/* The encoder's split (ref_video.cpp split_tiles_axis) over one axis: the tile count and the + * tiles' extent sum along it, a lone tile short of `tile` if the axis is. -1 where the split + * refuses. The drawn encode planes are `axis_len` long, so the shape fns can size the tile + * operands exactly. */ +static int64_t axis_split(int64_t len, int64_t tile, int64_t overlap, int64_t* ext) { + if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return -1; + if (tile >= len) { + *ext = len; + return 1; + } + const int64_t nt = tile_count(len, tile, overlap); + /* The extents telescope: sum of the tiles = len + sum of the overlaps = `tile` nt. */ + *ext = tile * nt; + return nt; +} + /* A 2 x 2 x 2 grid of patches. */ int ref_patch_unfold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0); @@ -3154,6 +3170,50 @@ int ref_cond_aug_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("cond_aug", operand, out); } +/* ---- the tiled encoder. The drawn frame is 20 latent units a side; with the sweep's tile of + * 16 and overlap of 4 the split lays 2 x 2 full tiles over it, so the crops, the plan's level + * triples and the blends all draw non-trivial. The kernels size by the geom; these only draw a + * plane that one gives them. */ +int ref_vtile_plan_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t ov = gi(p, n_p, "overlap", 0), ratio = gi(p, n_p, "ratio", 0); + int64_t e = 0; + const int64_t nt = axis_split(20, tile, ov, &e); + if (M <= 0 || nt < 0 || ratio <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 3 }, 0, 20 * ratio, 0); /* geom: (_, H, W) pixels */ + o.t((uint32_t)RAD_I32, { M, 22 }); /* y: one row a tile */ + return o.finish("vtile_plan", operand, out); +} + +int ref_vtile_crop_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t ov = gi(p, n_p, "overlap", 0), ratio = gi(p, n_p, "ratio", 0); + int64_t e = 0; + const int64_t nt = axis_split(20, tile, ov, &e); + if (M <= 0 || nt < 0 || ratio <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { 20 * ratio * (20 * ratio), 3 }); /* x: the pixel plane */ + o.t_idx({ 3 }, 0, 20 * ratio, 0); /* geom: (_, H, W) pixels */ + o.t(D, { M, 3 }); /* y: the tiles' pixels */ + return o.finish("vtile_crop", operand, out); +} + +int ref_vtile_join_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t ov = gi(p, n_p, "overlap", 0), n = gi(p, n_p, "n", 0); + int64_t e = 0; + const int64_t nt = axis_split(20, tile, ov, &e); + if (M <= 0 || nt < 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { e * e, n }); /* x: the tiles' moments */ + o.t_idx({ 3 }, 0, 20, 0); /* geom: (_, lat_h, lat_w) */ + o.t(D, { M, n }); /* y: the canvas */ + return o.finish("vtile_join", operand, out); +} + /* ================================================================== video sparse attention * * The tiles come from the values of `segs` and `geom`, which a description draws only as diff --git a/libref/ref_video.cpp b/libref/ref_video.cpp index 9bd561c8..b94863b0 100644 --- a/libref/ref_video.cpp +++ b/libref/ref_video.cpp @@ -63,6 +63,21 @@ bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector* start, + std::vector* ov) { + if (tile >= len) { + start->clear(); + ov->clear(); + start->push_back(0); + return len > 0 && tile > 0 && overlap >= 0 && overlap < tile; + } + return split_tiles(len, tile, overlap, start, ov); +} + } /* namespace */ /* ------------------------------------------------------------------ patch_unfold */ @@ -695,3 +710,178 @@ int ref_cond_aug(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* ================================================================== the tiled encoder + * A one-frame media bigger than the encoder's per-volume side (a reference picture or an + * endpoint keyframe) is encoded the way vae.py's `tiled_encode` encodes it: the pixel plane is + * cut into `split_tiles_axis`' tiles, every tile goes through the whole encoder on its own, and + * the tiles' moments are blended back into one latent plane. The three ops below are the cut, + * the plan the cut and the per-tile volumes read, and the blend; the encoder itself is the + * existing per-level ops, issued per tile at the plan's geometries. `geom` is always the + * request's (clip, H, W) read off the device -- tile starts, extents and counts come from the + * split, never from the parameters, which are fixed at declare. */ + +/* ------------------------------------------------------------------ vtile_plan */ +/* The plan one frame's encode runs over: `geom` = (clip, H, W) the frame's extent in pixels, + * split by split_tiles_axis over the spatial axes in latent units -- `tile` a side, `overlap` + * its minimum blend, `ratio` the VAE's pixels per latent -- and the tiles numbered row-major + * over (row band, column band). Row t of y (i32 [M, 22]): + * + * [0] [1] the tile's first pixel (y0, x0) + * [2] [3] the tile's pixel extent (th, tw): `tile` ratio, save the lone short tile + * 3 L + 4..6 level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)) for L = 0..5 -- the + * encoder's five levels and the deepest one's repeat, which shares it (no + * downsampler between them), exactly venc_geom's level layout for one frame. + * + * M is the tile count; any other count is refused. */ +int ref_vtile_plan(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *geom = &a->t[0], *y = &a->t[1]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t H = ldi(geom, 1), W = ldi(geom, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || H % ratio || W % ratio || + !split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) || + !split_tiles_axis(W / ratio, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + if (M != nh * nw || rows_of(y, 22) < M) return RAD_E_SHAPE; + REF_PAR_FOR(M) + for (int64_t t = 0; t < M; ++t) { + const int64_t i = t / nw, j = t % nw; + const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio; + const int64_t tw = std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + const int64_t yb = rowoff(y, t, 22), ys = laststride(y); + const int64_t v[22] = { sy[(size_t)i] * ratio, sx[(size_t)j] * ratio, th, tw, + 1, th, tw, 1, th / 2, tw / 2, 1, th / 4, tw / 4, + 1, th / 8, tw / 8, 1, th / 16, tw / 16, 1, th / 16, tw / 16 }; + for (int64_t c = 0; c < 22; ++c) st_int(y->dtype, y->data, yb + c * ys, v[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_crop */ +/* One frame's pixel plane cut into vtile_plan's tiles: x f32 [>= H W, 3] is the plane (pixel + * (Y, X) at row Y W + X) of geom = (clip, H, W) in pixels; y f32 [M, 3] holds the tiles' pixels + * tile-major, tile t's (th, tw) rows in plane order at their offset in the sum. M is the tiles' + * pixel count, sum of th tw over the plan. Only the row the tile stands on is read; the tiles' + * union covers the plane, but their sum may exceed it -- that is why y is its own buffer. */ +int ref_vtile_crop(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t H = ldi(geom, 1), W = ldi(geom, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || H % ratio || W % ratio || + !split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) || + !split_tiles_axis(W / ratio, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + std::vector off((size_t)(nh * nw + 1), 0); + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio; + for (int64_t j = 0; j < nw; ++j) + off[(size_t)(i * nw + j + 1)] = + off[(size_t)(i * nw + j)] + + th * std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + } + if (M != off.back() || rows_of(x, 3) < H * W || rows_of(y, 3) < M) return RAD_E_SHAPE; + REF_PAR_FOR(M * 3) + for (int64_t r = 0; r < M; ++r) { + const int64_t t = (int64_t)(std::upper_bound(off.begin(), off.end(), r) - off.begin()) - 1; + const int64_t i = t / nw, j = t % nw; + const int64_t tw = std::min(tile, W / ratio - sx[(size_t)j]) * ratio; + const int64_t k = r - off[(size_t)t]; + const int64_t src = (sy[(size_t)i] * ratio + k / tw) * W + sx[(size_t)j] * ratio + k % tw; + const int64_t xb = rowoff(x, src, 3), yb = rowoff(y, r, 3), xs = laststride(x); + const int64_t ys = laststride(y); + for (int64_t c = 0; c < 3; ++c) stt(y, yb + c * ys, ldt(x, xb + c * xs)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_join */ +/* The per-tile moments blended back into one latent plane, vae.py's `tiled_encode` blend: x + * holds the tiles' n-channel moments tile-major (vtile_crop's row layout at latent extent), + * geom = (clip, lat_h, lat_w) in latent units, and y f32-or-bf16 [M, n] is the canvas, M + * lat_h lat_w. Canvas position (Y, X) belongs to the tile (i, j) whose kept range holds it, + * [start, next start) (the last band to the end), at (ly, lx) within it; T(i, j, ly, lx) is + * that tile's stored value. As in vae.py the neighbours are RAW (as the per-tile encoder left + * them, never already blended) and the top blend runs before the left one; every product and + * sum rounds to x's dtype (`rd`), as its bf16 blends round, with wa(p, e) = rd(1 - rd(p / e)) + * and wb(p, e) = rd(p / e): + * + * v = T(i, j, ly, lx) + * v = rd(rd(T(i - 1, j, ly + tile - ev) * wa(ly, ev)) + rd(v * wb(ly, ev))) ev = ov_y[i - 1] + * v = rd(rd(T(i, j - 1, lx + tile - eh) * wa(lx, eh)) + rd(v * wb(lx, eh))) eh = ov_x[j - 1] + * + * the first when i > 0 and ly < ev, the second when j > 0 and lx < eh. Only a lone tile is + * short, and it has no neighbour, so a neighbour's extent along the blended axis is always + * `tile`. */ +int ref_vtile_join(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2]; + const int64_t M = p_int(a, "M", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), n = p_int(a, "n", 0); + if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t H = ldi(geom, 1), W = ldi(geom, 2); + std::vector sy, sx, oy, ox; + if (H <= 0 || W <= 0 || !split_tiles_axis(H, tile, overlap, &sy, &oy) || + !split_tiles_axis(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(); + if (M != H * W) return RAD_E_SHAPE; + std::vector off((size_t)(nh * nw + 1), 0); + for (int64_t i = 0; i < nh; ++i) { + const int64_t th = std::min(tile, H - sy[(size_t)i]); + for (int64_t j = 0; j < nw; ++j) + off[(size_t)(i * nw + j + 1)] = + off[(size_t)(i * nw + j)] + th * std::min(tile, W - sx[(size_t)j]); + } + if (rows_of(x, n) < off.back() || rows_of(y, n) < M) return RAD_E_SHAPE; + /* The owner tile of every canvas row and column. */ + std::vector own_y((size_t)H), own_x((size_t)W); + for (int64_t Y = 0, i = 0; Y < H; ++Y) { + while (i + 1 < nh && Y >= sy[(size_t)(i + 1)]) ++i; + own_y[(size_t)Y] = i; + } + for (int64_t X = 0, j = 0; X < W; ++X) { + while (j + 1 < nw && X >= sx[(size_t)(j + 1)]) ++j; + own_x[(size_t)X] = j; + } + const uint32_t dt = x->dtype; + auto rd = [dt](float v) { return round_dt(dt, v); }; + auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); }; + auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); }; + auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) { + const int64_t row = off[(size_t)(i * nw + j)] + ly * std::min(tile, W - sx[(size_t)j]) + lx; + return ldt(x, rowoff(x, row, n) + c * laststride(x)); + }; + const int64_t ys = laststride(y); + REF_PAR_FOR(M * n) + for (int64_t r = 0; r < M; ++r) { + const int64_t Y = r / W, X = r % W; + const int64_t i = own_y[(size_t)Y], j = own_x[(size_t)X]; + const int64_t ly = Y - sy[(size_t)i], lx = X - sx[(size_t)j]; + const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] : 0, eh = j > 0 ? ox[(size_t)(j - 1)] : 0; + const int64_t yb = rowoff(y, r, n); + for (int64_t c = 0; c < n; ++c) { + float v = T(i, j, ly, lx, c); + if (ly < ev) + v = rd(rd(T(i - 1, j, ly + tile - ev, lx, c) * wa(ly, ev)) + + rd(v * wb(ly, ev))); + if (lx < eh) + v = rd(rd(T(i, j - 1, ly, lx + tile - eh, c) * wa(lx, eh)) + + rd(v * wb(lx, eh))); + stt(y, yb + c * ys, v); + } + } + return RAD_OK; +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 113d9936..de190f41 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -1034,6 +1034,9 @@ TEST(op_vocabulary) { * the fold back into patch rows and the re-noising. */ "conv3d_ndhwc", "group_norm", "tconv_dw", "resize_bilinear", "patch_fold", "flow_renoise", "cond_aug", + /* Its encoder's tiling for one-frame media bigger than a tile: the plan, the cut and + * the moments' blend back into the latent canvas. */ + "vtile_plan", "vtile_crop", "vtile_join", /* The joint image generators' (Krea 2, FLUX.3): attention over separate key bounds, a * per-layer table added to every row, a learned mix of consecutive rows, and the VAE's * channel statistics. */ @@ -6883,6 +6886,211 @@ TEST(grid_pos3_places_each_tile_token_and_zeroes_the_rest) { CHECK_EQ(at3(2, 29), 1.5f); } +/* ================================================================== the tiled encoder + * docs/OPS.md "Video generation", the tiled encoder: vae.py's split over a one-frame plane, the + * plane cut into tiles, and the per-tile moments blended back with the RAW neighbours. */ + +/* 640 x 320 px in latent units is 40 x 20: the rows split at 0, 12, 24 and the columns at 0, 4 + * -- six tiles, every one 16 latents a side (256 px). Level L's volume is the tile over + * 2^min(L,4) pixels a side, and a plane smaller than one tile is one short tile (vae.py's + * ([0], [len], [])), 128 x 96 px here with levels down to 8 x 6. */ +TEST(vtile_plan_plans_one_frame_the_way_vae_py_splits_it) { + T geom(RAD_I32, {3}); geom.n({1, 640, 320}); + T y(RAD_I32, {6, 22}); + A a; a.t(geom).t(y).i("M", 6).i("tile", 16).i("overlap", 4).i("ratio", 16); + CHECK_OK(run("vtile_plan", a)); + const int64_t y0[6] = { 0, 0, 192, 192, 384, 384 }, x0[6] = { 0, 64, 0, 64, 0, 64 }; + for (int64_t t = 0; t < 6; ++t) { + CHECK_EQ(y.iat(t * 22 + 0), y0[t]); + CHECK_EQ(y.iat(t * 22 + 1), x0[t]); + CHECK_EQ(y.iat(t * 22 + 2), 256); + CHECK_EQ(y.iat(t * 22 + 3), 256); + const int64_t d[6] = { 1, 2, 4, 8, 16, 16 }; + for (int L = 0; L < 6; ++L) { + CHECK_EQ(y.iat(t * 22 + 4 + 3 * L + 0), 1); + CHECK_EQ(y.iat(t * 22 + 4 + 3 * L + 1), 256 / d[L]); + CHECK_EQ(y.iat(t * 22 + 4 + 3 * L + 2), 256 / d[L]); + } + } + T g1(RAD_I32, {3}); g1.n({1, 128, 96}); + T y1(RAD_I32, {1, 22}); + A b; b.t(g1).t(y1).i("M", 1).i("tile", 16).i("overlap", 4).i("ratio", 16); + CHECK_OK(run("vtile_plan", b)); + const int64_t lone[22] = { 0, 0, 128, 96, 1, 128, 96, 1, 64, 48, 1, 32, 24, + 1, 16, 12, 1, 8, 6, 1, 8, 6 }; + for (int i = 0; i < 22; ++i) CHECK_EQ(y1.iat(i), lone[i]); + + /* A 96 x 768 px plane: one short row band (6 latents) and 48 latents a row, split at 0, 10, + * 21, 32 -- the slack of 4 going to the overlaps one at a time round-robin (6, 5, 5), + * so the last column still runs the full 16 latents to the plane's edge. A short band only + * ever stands alone on its axis, but it still has the other axis' neighbours. */ + T g3(RAD_I32, {3}); g3.n({1, 96, 768}); + T y3(RAD_I32, {4, 22}); + A e; e.t(g3).t(y3).i("M", 4).i("tile", 16).i("overlap", 4).i("ratio", 16); + CHECK_OK(run("vtile_plan", e)); + const int64_t x3[4] = { 0, 160, 336, 512 }; + for (int64_t t = 0; t < 4; ++t) { + CHECK_EQ(y3.iat(t * 22 + 0), 0); + CHECK_EQ(y3.iat(t * 22 + 1), x3[t]); + CHECK_EQ(y3.iat(t * 22 + 2), 96); + CHECK_EQ(y3.iat(t * 22 + 3), 256); + const int64_t d[6] = { 1, 2, 4, 8, 16, 16 }; + for (int L = 0; L < 6; ++L) { + CHECK_EQ(y3.iat(t * 22 + 4 + 3 * L + 0), 1); + CHECK_EQ(y3.iat(t * 22 + 4 + 3 * L + 1), 96 / d[L]); + CHECK_EQ(y3.iat(t * 22 + 4 + 3 * L + 2), 256 / d[L]); + } + } + + /* A row count that is not the tile count, and a plane the ratio does not divide. */ + T y2(RAD_I32, {5, 22}); + A c; c.t(geom).t(y2).i("M", 5).i("tile", 16).i("overlap", 4).i("ratio", 16); + CHECK_EQ(run("vtile_plan", c), RAD_E_SHAPE); + T g2(RAD_I32, {3}); g2.n({1, 100, 96}); + A d; d.t(g2).t(y1).i("M", 1).i("tile", 16).i("overlap", 4).i("ratio", 16); + CHECK_EQ(run("vtile_plan", d), RAD_E_SHAPE); +} + +/* A 20 x 20 px plane in ratio 4, tiles of 3 latents (12 px) with overlap 1: each axis splits at + * 0 and 2 -- four tiles of 12 x 12 px, 576 rows, tile-major (row band first). x holds + * (Y, X, Y W + X) per row, so every tile row says which plane pixel it cut. */ +TEST(vtile_crop_cuts_the_plane_tile_major) { + T x(RAD_F32, {400, 3}); + std::vector xv(1200); + for (int64_t i = 0; i < 400; ++i) + xv[(size_t)i * 3] = (float)(i / 20), xv[(size_t)i * 3 + 1] = (float)(i % 20), + xv[(size_t)i * 3 + 2] = (float)i; + x.f(xv); + T geom(RAD_I32, {3}); geom.n({1, 20, 20}); + T y(RAD_F32, {576, 3}); + A a; a.t(x).t(geom).t(y).i("M", 576).i("tile", 3).i("overlap", 1).i("ratio", 4); + CHECK_OK(run("vtile_crop", a)); + const int64_t sy[2] = { 0, 8 }, sx[2] = { 0, 8 }; /* latent starts 0 and 2, in px */ + for (int64_t i = 0; i < 2; ++i) + for (int64_t j = 0; j < 2; ++j) { + const int64_t off = (i * 2 + j) * 144; + for (int64_t k = 0; k < 144; ++k) { + const int64_t py = sy[i] + k / 12, pxx = sx[j] + k % 12; + CHECK_EQ(y.at((off + k) * 3 + 0), (float)py); + CHECK_EQ(y.at((off + k) * 3 + 1), (float)pxx); + CHECK_EQ(y.at((off + k) * 3 + 2), (float)(py * 20 + pxx)); + } + } + + /* A plane whose row axis is below one tile and whose column axis is not: one short row band + * with two column neighbours -- 8 x 20 px in ratio 4 is 2 x 5 latents, columns at 0 and 2 + * (8 px), so two tiles of 8 x 12 px, 192 rows, the overlap column range cut twice. */ + T g4(RAD_I32, {3}); g4.n({1, 8, 20}); + T x4(RAD_F32, {160, 3}); + std::vector x4v(480); + for (int64_t i = 0; i < 160; ++i) + x4v[(size_t)i * 3] = (float)(i / 20), x4v[(size_t)i * 3 + 1] = (float)(i % 20), + x4v[(size_t)i * 3 + 2] = (float)i; + x4.f(x4v); + T y4(RAD_F32, {192, 3}); + A e4; e4.t(x4).t(g4).t(y4).i("M", 192).i("tile", 3).i("overlap", 1).i("ratio", 4); + CHECK_OK(run("vtile_crop", e4)); + for (int64_t j = 0; j < 2; ++j) + for (int64_t k = 0; k < 96; ++k) { + const int64_t py = k / 12, pxx = 8 * j + k % 12; + CHECK_EQ(y4.at((j * 96 + k) * 3 + 0), (float)py); + CHECK_EQ(y4.at((j * 96 + k) * 3 + 1), (float)pxx); + CHECK_EQ(y4.at((j * 96 + k) * 3 + 2), (float)(py * 20 + pxx)); + } + + /* A plane below one tile is a lone tile -- the crop is the plane itself. */ + T g1(RAD_I32, {3}); g1.n({1, 8, 8}); + T x1(RAD_F32, {64, 3}); + std::vector x1v(192); + for (int64_t i = 0; i < 64; ++i) x1v[(size_t)i * 3] = (float)i; + x1.f(x1v); + T y1(RAD_F32, {64, 3}); + A b; b.t(x1).t(g1).t(y1).i("M", 64).i("tile", 3).i("overlap", 1).i("ratio", 4); + CHECK_OK(run("vtile_crop", b)); + for (int64_t i = 0; i < 64; ++i) CHECK_EQ(y1.at(i * 3), (float)i); + + /* A row count that is not the tiles' pixel sum, and a plane short of geom. */ + T y2(RAD_F32, {575, 3}); + A c; c.t(x).t(geom).t(y2).i("M", 575).i("tile", 3).i("overlap", 1).i("ratio", 4); + CHECK_EQ(run("vtile_crop", c), RAD_E_SHAPE); + T x2(RAD_F32, {399, 3}); + A d; d.t(x2).t(geom).t(y).i("M", 576).i("tile", 3).i("overlap", 1).i("ratio", 4); + CHECK_EQ(run("vtile_crop", d), RAD_E_SHAPE); +} + +/* A 6 x 6 latent canvas, tiles of 4 with overlap 2: each axis splits at 0 and 2, the kept ranges + * are [0, 2) and [2, 6), and the blends are two rows and two columns wide. Tile (i, j) is the + * constant 4 << (2 i + j) -- [[4, 8], [16, 32]] -- so every blend shows its two sources: (2, 0) + * is the top row of the bottom-left tile fully from the tile above (wb(0, 2) = 0), (3, 0) is its + * second row, half and half; (2, 2) is the bottom-right tile's corner blended up (8) and then + * left (16 -- the RAW tile to the left, never a blended one), and (3, 3) takes half of 8 up and + * then half of 16 left of that: rd(rd(8 0.5) + rd(32 0.5)) = 20, then rd(rd(16 0.5) + rd(20 0.5)) + * = 18. Blending across first, or reading a blended neighbour, gives other numbers. */ +TEST(vtile_join_blends_raw_neighbours_down_then_across) { + T x(RAD_BF16, {64, 1}); + std::vector xv(64); + const float base[4] = { 4, 8, 16, 32 }; + for (int64_t k = 0; k < 4; ++k) + for (int64_t r = 0; r < 16; ++r) xv[(size_t)(k * 16 + r)] = base[k]; + x.f(xv); + T geom(RAD_I32, {3}); geom.n({1, 6, 6}); + T y(RAD_BF16, {36, 1}); + A a; a.t(x).t(geom).t(y).i("M", 36).i("tile", 4).i("overlap", 2).i("n", 1).s("dtype", "bf16"); + CHECK_OK(run("vtile_join", a)); + auto px = [&](int64_t Y, int64_t X) { return y.at(Y * 6 + X); }; + CHECK_EQ(px(0, 0), 4.0f); CHECK_EQ(px(0, 2), 4.0f); /* left blend at wb(0, 2) = 0 */ + CHECK_EQ(px(0, 3), 6.0f); CHECK_EQ(px(2, 0), 4.0f); /* top blend at wa(0, 2) = 1 */ + CHECK_EQ(px(2, 2), 16.0f); CHECK_EQ(px(3, 0), 10.0f); + CHECK_EQ(px(4, 3), 24.0f); CHECK_EQ(px(3, 3), 18.0f); + CHECK_EQ(px(5, 5), 32.0f); CHECK_EQ(px(4, 0), 16.0f); + + /* A 6 x 9 latent canvas, tiles of 4 with overlap 1: rows split at 0, 2 (slack 1 -> overlap + * 2) and columns at 0, 2, 5 (slack 1 to the FIRST boundary: overlaps 2 then 1 -- distributing + * the slack to every boundary instead would start the columns at 0, 2, 4). Six tiles of 4 x 4, + * tile + * (i, j) the constant 1 << (2 i + j) -- [[1, 2, 4], [8, 16, 32]]. Top before left, RAW + * neighbours, in bf16 halves: (3, 0) is half of 1 up and half of 8 = 4.5; (3, 5) blends up to + * half of 4 and half of 8 = 6 and then fully to the RAW left 16; (1, 2) has no top (i = 0) + * and takes 1 fully left; (5, 3) takes half of 8 left of 16 = 12; (2, 5) takes 4 fully up, + * then 16 fully left; (3, 6) takes half of 4 up of its 32 = 18 and no left at lx = 1. + */ + T g5(RAD_I32, {3}); g5.n({1, 6, 9}); + T x5(RAD_BF16, {96, 1}); + std::vector x5v(96); + for (int64_t t = 0; t < 6; ++t) + for (int64_t r = 0; r < 16; ++r) x5v[(size_t)t * 16 + r] = (float)(1 << t); + x5.f(x5v); + T y5(RAD_BF16, {54, 1}); + A e5; e5.t(x5).t(g5).t(y5).i("M", 54).i("tile", 4).i("overlap", 1).i("n", 1).s("dtype", "bf16"); + CHECK_OK(run("vtile_join", e5)); + auto qx = [&](int64_t Y, int64_t X) { return y5.at(Y * 9 + X); }; + CHECK_EQ(qx(0, 0), 1.0f); CHECK_EQ(qx(1, 2), 1.0f); /* no top at i = 0; 1 fully left */ + CHECK_EQ(qx(0, 3), 1.5f); CHECK_EQ(qx(0, 5), 2.0f); /* half of 1 left of 2; 2 fully */ + CHECK_EQ(qx(3, 0), 4.5f); CHECK_EQ(qx(2, 5), 16.0f); /* half up, then RAW left overrides */ + CHECK_EQ(qx(3, 5), 16.0f); CHECK_EQ(qx(3, 6), 18.0f); /* left fully at lx = 0; half up at 1 */ + CHECK_EQ(qx(5, 2), 8.0f); CHECK_EQ(qx(5, 3), 12.0f); /* fully left at lx = 0, half at 1 */ + CHECK_EQ(qx(0, 8), 4.0f); CHECK_EQ(qx(4, 2), 8.0f); /* past every blend: own or fully left */ + + /* A canvas below one tile is a lone tile: the join is the copy. */ + T g1(RAD_I32, {3}); g1.n({1, 3, 3}); + T x1(RAD_BF16, {9, 1}); + std::vector x1v(9); + for (int64_t i = 0; i < 9; ++i) x1v[(size_t)i] = (float)(i + 1); + x1.f(x1v); + T y1(RAD_BF16, {9, 1}); + A b; b.t(x1).t(g1).t(y1).i("M", 9).i("tile", 4).i("overlap", 2).i("n", 1).s("dtype", "bf16"); + CHECK_OK(run("vtile_join", b)); + for (int64_t i = 0; i < 9; ++i) CHECK_EQ(y1.at(i), (float)(i + 1)); + + /* M is the canvas, x holds every tile. */ + T y2(RAD_BF16, {35, 1}); + A c; c.t(x).t(geom).t(y2).i("M", 35).i("tile", 4).i("overlap", 2).i("n", 1).s("dtype", "bf16"); + CHECK_EQ(run("vtile_join", c), RAD_E_SHAPE); + T x2(RAD_BF16, {63, 1}); + A d; d.t(x2).t(geom).t(y).i("M", 36).i("tile", 4).i("overlap", 2).i("n", 1).s("dtype", "bf16"); + CHECK_EQ(run("vtile_join", d), RAD_E_SHAPE); +} + /* ================================================================== the latent upscaler * docs/OPS.md "The latent upscaler": voxel rows (t, i, j) of a T x H x W volume, channels * innermost, the volume in `geom`. */ @@ -8964,6 +9172,15 @@ std::vector geometries() { G("flow_renoise", "M", 3, a.i("M", R).i("n", 8).i("stream", 1).s("dtype", "f32")), G("cond_aug", "M", 3, a.i("M", R).i("n", 8).i("stream", 2).d("aug", 0.999) .s("dtype", "f32")), + /* The drawn frame is 20 latent units a side (ref_shapes.cpp), so a tile of 16 with + * overlap 4 splits it 2 x 2: the plan has 4 rows, the crop (ratio 16) 4 tiles of 256 + * pixels -- 512 x 512 px of plane into 4 x 256 x 256 = 262144 rows -- and the join + * blends 4 x 16 x 16 = 1024 moment rows into the 400-row canvas. */ + G("vtile_plan", "M", 4, a.i("M", R).i("tile", 16).i("overlap", 4).i("ratio", 16)), + G("vtile_crop", "M", 262144, a.i("M", R).i("tile", 16).i("overlap", 4).i("ratio", 16) + .s("dtype", "f32")), + G("vtile_join", "M", 400, a.i("M", R).i("tile", 16).i("overlap", 4).i("n", 48) + .s("dtype", "bf16")), G("attn_cross", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 0) .s("dtype", "f32").i("n_head", 2)), G("table_add", "M", 3, a.i("M", R).i("n", 8).i("L", 3).s("dtype", "f32")),