PIN ref2va: verified device differential + ref-count gate (revert anchor)

Ref2VA ref-image conditioning verified on-device: ref step runs all steps no
fault; output differs ref-present vs ref-absent (by log). 6-9 images rejected
cleanly at submit (no engine crash). Merged-cell modulation (<=9) tracked next.
NOTE: placeholder author -- re-author before any push. Do NOT push this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-19 12:04:47 -05:00
1 parent 816e24bd46
commit 490d4c604a
73 files changed
+16484 -432

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
# P2 port note — the VAE encode, from ComfyUI source
Read directly from `/home/dustin/AI/ComfyUI/comfy/ldm/minimax/vae.py` and `audio_vae.py`
(2026-10 install) so the Radiance port is source-faithful rather than doc-derived. Line numbers
below are those files'. §5.5 of `PORT-REF2VA.md` scoped the whole of P2 (kernels, graphs,
declare, re-convert); this note is the extraction underneath it, and the **host half has
landed**: `arch/minimaxh3/rad_vae_geom.{h,cpp}` + `tests/vae_geom_test.cpp` (bottom section).
## Video encoder — `EncoderFCN3D` (vae.py :176-228) and its blocks
Constructor arguments (`MiniMaxH3VideoVAE.__init__` :409-441): `ch=128`, `ch_mult=(1,2,2,4,4,8)`,
`space_down=(2,2,2,2,1,1)`, `time_down=(1,2,2,1,1,1)`, `num_res_blocks=2`, `z_channels=24`,
`double_z=True` (moments = 2·24 = 48 channels). Derived: `vae_ratio=16`, `vae_ratio_t=8`,
`clip_length=17`, `token_drop=3`, `tile_size=256`, `tile_overlap_min=64` — and the decode-side
`frame_pre_padding=7`, `tokens_chunk_size=3`, `token_overlap=0`, `frame_overlap=0` (the engine's
decode driver already encodes these; not re-ported).
- `CausalConv3d` (:72-118): spatial **reflect** pad `(w,w,h,h)` (or explicit `spatial_pad`),
temporal **front-only zero pad** `2*pad_t`, stride-s conv with no further padding. The single
exception: when the input has one frame (`x.shape[2]==1`) the physical pad is skipped
(`front = 0`) and the temporal taps are truncated instead (`autopad="causal_zero"` :101-103) —
semantically a front zero pad of `k_t − 1`, so T=1 in ⇒ T=1 out at every layer. The 1×1
shortcut conv has nothing to fold (:87, pads stay off). The kitchen fused pad/GN paths
(:41-70, :75-86) are CUDA-only fast paths; the CPU path is exactly pad → conv.
- `TemporalIsolatedGroupNorm` (:122-130): GroupNorm **statistics per frame** (time folded into
batch), 32 groups, `eps=1e-6`, affine — libr4d's `group_norm` (OPS.md:1276) reduces over ALL
rows, so the encode variant must fold T into N.
- `Downsample3D` (:137-152): `CausalConv3d` k3 `padding=(1,0,0)` stride `(time_stride, s, s)`,
called with `spatial_pad=(0,1,0,1)` when s=2 — **right/bottom-only** spatial pad, not centered.
Temporally it is exactly `L → ceil(L / time_stride)` (front pad 2, k3: `(L+2−3)/t+1`);
spatially `(L + 0 + 1 − 3)/2 + 1 = ceil(L/2)` too, but the pad asymmetry matters for values.
- `ResnetBlock3D` (:155-173): silu→GN→conv1 k3p1; 1×1 shortcut if channels differ;
silu→GN→conv2 k3p1 + residual. All stride 1 ⇒ **length-preserving** (taps: k3 p1 front pad 2).
- Graph (:218-228): `conv_in` k3p1 → per level (2 × ResnetBlock, then `Downsample3D` wherever
`space_down[i]*time_down[i] > 1`) → `conv_out` with `pre_norm=norm_out` (GN+silu folded).
Lengths: temporal `17 → ceil(17/2)=9 → ceil(9/2)=5` (only two levels time-downsample), then
levels 3-5 stride 1 in time; spatial 16× at levels 0-3.
## Video encode — chunking, tiling, normalization
- `_normalize_pixels` (:485-486): pixels in [−1,1] → `((x+1)/2 − IMAGENET_MEAN)/IMAGENET_STD`
with `IMAGENET_MEAN=(0.485,0.456,0.406)`, `IMAGENET_STD=(0.229,0.224,0.225)`.
`_encode_moments` (:479-480) = `quant_conv(encoder(x))` (1×1 to 48ch).
- `encode` (:775-792): T=1 encodes alone and takes `moments[:,:,-1:]` — one latent; T≥2 goes
through `encode_temporal` (:647-661): `ceil(T/17)` clips, the short last clip **padded by
repeating its final frame** to 17, each clip → 5 latents, cat, **drop the last 3** ⇒
**L(T) = 5·ceil(T/17) − 3**. Mean only — `chunk(moments.float(), 2, dim=1)[0]`, **no sampling**,
then `(mean − LATENTS_MEAN)/LATENTS_STD` (:20-38, 24 doubles each, transcribed into
`kVaeLatentsMean/Std`). Deterministic ⇒ golden parity against the reference is well-defined.
- `split_tiles` (:514-536), per axis, always on (per `encode_tiled`'s comment :794-796): if 256 ≥ len, one
tile; else `N = ceil(len/256)` grown until `256N − 64(N−1) − len ≥ 0`; slack
`remaining // 16` is spread **+16 px round-robin over the overlaps**; starts cumulate
`256 − overlap`. Worked 1344: N=7, overlaps [80,80,80,80,64,64], starts
[0,176,352,528,704,896,1088], last window ends exactly at 1344. Tile slices clamp at the axis
end (`x[..., pos:pos+256]`), so the last tile can be short.
- `tiled_encode` (:563-590): per-tile `_encode_moments`; latent overlaps = overlap//16; the
blend (:538-561) is a **linear ramp** `pos/blend_extent` over the overlap (extent clamped to
both tiles), blending top-of-prev with top-of-current, **cutting** the trailing overlaps from
each tile before concatenation. Net effect: the moments grid is exactly `len/16` per axis —
verified end to end by golden runs (320→20, 512→32, 288→18, 192→12 latents).
## Audio encoder — DAC strided stack (audio_vae.py) + posterior head
- `ResidualUnit` (:155-172): Snake → conv k7 dil `d`, symmetric pad `(7−1)d/2` → Snake → conv
k1; **length-preserving** (pad = exactly the dilation slack), residual add.
`EncoderBlock` (:174-192): 3 ResidualUnits (dil 1,3,9) → Snake → conv `k=2s, p=ceil(s/2)`,
stride s — exact division at lengths divisible by s (the wrapper's right pad guarantees it).
- `Encoder` (:195-209): conv k7 p3 in (length-preserving) → blocks at dims 128…2048, strides
**(2,4,4,5,5)** → Snake → conv k3 p1 to 2048. Hop = 2·4·4·5·5 = **800** samples (40 latent
frames/s at 32 kHz). Stereo is split to mono streams (`reshape(b*s, 1, −1)`) — the encoder is
mono; channels rejoin only in the output reshape.
- `encode` (:427-443): **right-pad zeros to a multiple of 800** ⇒ `T = ceil(samples/800)`
exactly (verified against the real chain at 13 lengths); `pre_block` `AttnProjection`
(:253-269) = LayerNorm + causal 8-head attention + Linear + GeGluMlp on the **time axis as
sequence** — no strided op, time-preserving; `mean_proj` 1×1; normalize by the stored
`latents_mean/std`; out `[B, 32, 2, T]`. Mean only again.
- `Snake1d` (:30-40): `x + sin²(αx)/α`, per-channel α — libr4d already has `snake` (OPS.md).
## Landed 2026-10-19 — `arch/minimaxh3/rad_vae_geom.{h,cpp}` (the host half)
The sizing questions the kernels and the driver will ask, answered as a device-free TU:
`vae_latent_frames` (the clip plan incl. the T=1 case), `vae_clip_latents` (the raw causal
chain — `ceil(T/4)` for T≥2, the nested ceil collapsing), `vae_audio_latents` (the hop rule),
`vae_split_tiles` (the tile plan: starts, real clamped slice lengths, pixel overlaps), and the
verbatim constant tables (`kVaeLatentsMean/Std`, `kVaePixelMean/Std`).
`tests/vae_geom_test.cpp` compiles the TU directly (no core, no device) against
`tests/data/vae_geom/golden.json`, which `gen_golden.py` produces **by running the reference's
real encoders on CPU**: the video `EncoderFCN3D` with the reference constructor arguments plus
the wrapper's own `encode()/encode_temporal()/split_tiles()/tiled_encode()` bound to a shim
self, and the audio DAC encoder. The shims are exactly the pieces the CPU guards keep off the
fast paths (`comfy.quant_ops` without `ck`; `Conv3d.forward` accepting `autopad="causal_zero"`
as the implicit front zero pad). 408 checks, 7 cases: the latent-count lattice through
`encode()` end to end (it reproduces the continuity snaps {5,22,39,56,73} ↔ {2,7,12,17,22} as
the network's own output), the clip chain composing with the encode count, tile plans against
the reference's literal returns, the blended tile grids keeping exact size, audio latents at 13
lengths, and the constant tables bit for bit. The one claim not executed is the audio
posterior head being time-preserving — every op in it is Linear/LayerNorm/attention/MLP over
the time axis, no strided op.
## What P2 still owes (the device half)
1. **Kernels — DONE 2026-10-19** (§5.5 list, four deltas, all landed):
- **conv3d_ndhwc** grew the `CausalConv3d` forms (PORT-REF2VA §5.15): optional
`stride`/`stride_t`/`causal`/`pad`(`same`|`down`)/`reflect`, 3×3×3-only, defaults byte-identical
to the shipped upscaller conv (the `GEN` template path only for non-defaults; the T=1 tap
truncation is subsumed by the front-only causal pad). Device/libref/avx + tests all landed.
- **The AttnProjection "reduce" resolved 2026-10-19 as ZERO new kernels** (PORT-REF2VA
§5.14): `layernorm` ×3, `gemm_nt_bias` for the fused qkv (bias = `q_bias|zeros|v_bias` concat
at convert), `attn_dense` causal (q/k/v take the `[tokens, heads, head_dim]` fused-slice form),
head-mean = `pool_rows(k=8)` on the token-major output rows, and the `adaptive_avg_pool1d(256
→ 32)` is a constant block-mean matrix that FOLDS into the attention `proj` at convert
(`W' = W_proj @ M_pool`); mlp = concat gemm + `gelu_mul` + gemm, residuals = `add`.
- **The per-frame GroupNorm resolved 2026-10-19 as ZERO new op** (PORT-REF2VA §5.13): launch
`group_norm` once per frame — slice `x`/`y` at frame boundaries (NDHWC frames are contiguous
row blocks; the launcher takes `M` from `y`'s rows and honours both pitches), one shared
`stats` scratch, `eps` 1e-6 as the parameter. The only kernel change: the encoder's level-0
groups are 4 channels wide (128 ch / 32 groups) and the device GN kernels chunked 8 channels
a thread — the chunk width is now a template parameter (8, or 4 when the group is 4 wide;
narrower still refuses; the spec never promised %8, libref/avx always answered).
- **The strided even-kernel conv1d landed 2026-10-19** (PORT-REF2VA §5.12): `conv1d` gained
optional `stride`/`pad` (bf16 rows only, one sequence `[0, rows of x)`, any `k`, output row
`m` reading `x[m·stride + tap·dil − pad]` with the sequence bounds zeroing — PyTorch's
zero-padded strided conv, `k = 2·stride`/`pad = ceil(stride/2)` giving exactly `L/stride`
rows, the y length rule checked exactly on the host in all three plugins; `r4d_selftest`
pins the tiled and direct kernels' numerics and the refusals).
The graph order is in the sections above; nothing here needs a new math op.
2. **Declare + re-convert**: encoder weights are absent from containers (§5.5) — declare the
118 video-encoder + 173 audio-encoder tensors (w/norm folds via `map_wnorm`) and re-convert
the P5 container; the recipe carries the constants above in meta already.
3. **Value parity**: golden *values* against ComfyUI encodes at real shapes on device (shape
parity is pinned today). Deterministic encoders ⇒ strict comparison, per-tensor tolerances
only as far as fp8 storage forces.
4. **Driver**: the encode pass enum entry, per-request ref encode, and the tail ingest — the
last gated on the FFmpeg dev packages (`core/mm/mp4.cpp`, P2b).
+237
View File
@@ -0,0 +1,237 @@
# P3/P4 port note — the exact Ref2VA packing, from ComfyUI source
Read directly from `/home/dustin/AI/ComfyUI/comfy/ldm/minimax/model.py` (2026-10 install) so the
Radiance port is source-faithful rather than doc-derived. Line numbers below are that file's.
Everything here is **pure host arithmetic** — the port is a new TU (proposed
`arch/minimaxh3/rad_ref2va_pack.{h,cpp}`, device-free, unit-testable) that emits the segment
table + per-row (t,h,w) positions + update flags; consuming them is the P3 engine wiring, and
keeping the non-update rows dense is P4.
## Constants (`:30-33`)
```
FRAME_PER_TOKEN = (1, 4, 4, 4, 4) # pixel frames covered by each successive video latent
FRAME_RESCALE = 5/3 # pixel frames -> audio-latent units (40/24 fps ratio)
VISUAL_COND_TIMESTEP = 0.999
AUDIO_COND_TIMESTEP = 1.0
```
## Row shapes
- video rows: patchify (1,2,2) → `latent_t * (h/2) * (w/2)` rows; time grid per latent frame k is
`origin + FRAME_RESCALE * Σ FRAME_PER_TOKEN[k'%5], k'<k` (`_video_t_grid` `:101-104`).
- audio rows: `pack_audio` `:59-62` — `[C=32, ch=2, T]` → `[2T, 32]` **channel-major**: ch0 all
T frames then ch1 all T frames. `rt` audio latent frames ⇒ `rt*2` rows.
- spatial frame grid `_frame_grid(h,w)` `:94-99`: `area=sqrt(h*w)`; per axis
`linspace`-like `(i*(ratio/n) + (1-ratio)/2)*32` with `ratio=dim/area`, `n=dim/2` — area-
normalized h/w coords of the 2×2 patch rows (h rows major). Audio grid `_audio_grid` `:106-113`:
`t = cursor + arange(T)` repeated for both channels, `w` pinned per channel to the **target**
grid's first/last w coord (`target_audio_w = (w_grid[0], w_grid[-1])`), `h=0`.
- `_ref_t_span` `:115-122`: image `1.0`; audio `ref_audio_t`; video/video_audio
`max(ref_audio_t, Σ_{k<latent_t} FRAME_RESCALE*FRAME_PER_TOKEN[k%5])`.
## Segment order (`PackedLayout.__init__` `:351-471`)
`[text | (keyframe cond | cond_audio)* | per-ref blocks in request order | audio | video]`
- `cursor = text_len + Σ _ref_t_span(all refs)` — the **target timeline origin**; computed in a
first pass before keyframes (`:364-366`). Keyframes pack right after text, each at
`cond_t = cursor + FRAME_RESCALE*resolved_frame_index` (frame 0 ⇒ shares the target origin and
overlaps its head in RoPE time — continuity comes from post-sampling trim, not placement).
- ref block per kind (`:394-441`), all rows **update=False** (pinned, never denoised):
- `image`: `ref_img` n=`(h/2)*(w/2)` rows, t=cursor, then `cursor += 1.0`
- `audio`: `ref_audio` `rt*2` rows (only if rt>0) at `_audio_grid(cursor,...)`, then
`cursor += rt`
- `video`/`video_audio`: **its `ref_audio` rows pack immediately BEFORE its `ref_img` rows**,
both at the same cursor origin; ref_audio uses the **ref's own** w-grid extremes
`(r_w_grid[0], r_w_grid[-1])` (target extremes only for target/cond audio); then
`cursor += max(rt, Σ video_t_spans(latent_t))` (== `_ref_t_span`, the second pass re-cums).
- targets (`:443-454`): `audio` `audio_t*2` rows then `video` `latent_t*(h/2)*(w/2)` rows, both
update=True, both at cursor. **Always the last two segments** — the sampler state is exactly
these (update mask = the sampler's x).
## Timesteps & mod rows (`_forward` `:667-712`)
- `t_v = 1 - sigma_v`, `t_a = 1 - time_shift_sigma(sigma_v, shift_v, shift_a)` (audio sigma
derived from video sigma via `time_shift_sigma` `:36-39`).
- per-kind timestep labels: `text/video → t_v`, `audio → t_a`,
`cond|ref_img → max(t_v, 0.999)`, `cond_audio|ref_audio → max(t_a, 1.0)` (pinned near-clean).
- `unique_t` = sorted distinct labels actually present; `t_row[t]` = index.
- mod tags: `{text:1, video:0, audio:2, cond:0, ref_img:0, cond_audio:2, ref_audio:2}`;
**mod-row index = `t_row(label) * 3 + tag`** — refs ride the video/audio modulation streams.
- denoise masks (`:683-699`): per-row `m` puts a row at `sigma = m*sigma_stream`, label
`clamp(1-m*sigma, max=pin)`; all-equal collapses to the segment label. Radiance's tail uses no
partial mask (full rows) — port masks only if partial-row conditioning ever lands.
## Cond-row content + the 0.1% augmentation (`:532-558`)
Cond rows are rebuilt **every step** from stored clean latents (never from sampler state):
`r = aug*z + (1-aug)*randn` with a **CPU RNG re-seeded per step per block-kind**: visual block
seed = run seed, audio block seed = run seed **+ 1**, `aug` = 0.999/1.0. Re-seeded ⇒ identical
noise every step; but it must be the **same stream every step** — port with a seeded CPU PRNG
matching torch's `randn` only if bit-parity is demanded (else document deviation: same-shape
deterministic-noise with Radiance's Philox, parity gate = "cond rows never change across steps").
## Sampler contract (`forward` `:603-643`)
- Sampler x = `[video_latents, audio_latents]` — **targets only** (update rows); the net returns
velocity for those rows only. Pinned rows are input-only context.
- audio scale-carry (`:605-614`, `:637-641`): sampler carries audio as `(sigma_a/sigma_v)*x_a`;
undo before the net, re-scale velocity out: `out_a = (1-scale)*(carry*x_a) + (1+(scale-1)*sigma_a)*v_a`.
- guidance-distilled: CFG 1.0; sigma-shift per stream (`MiniMaxH3SigmaShift` node).
## P4 — dense sinks
Sparsity (sol-attn) hooks the layout out-of-band via `transformer_options["minimax_h3_layout"]`
(vendored model code is fully dense, `optimized_attention(..., mask=None)` `:200`); the sparse
node keeps **cond+ref+audio rows** exact (`sink_conditioning=exact_kv_and_rows`) and sparsifies
the update rows only. Radiance parity: the sink rule takes `img_update/audio_update` (P3 output) —
dense set = complement of update set ∪ text — NOT a static prompt-span rule. Keep the split
(pack emits the table; sparsity is the attention backend's concern).
## Landed 2026-10-19 — `arch/minimaxh3/rad_ref2va_pack.{h,cpp}`
The port exists and is tested against the reference's own output. `ref2va_build()` emits the
segment table (start, end, kind, update), the planar `[3, rows]` f32 positions (the exact shape
R_ROPE holds, so staging is a copy), and `ref2va_mod_rows()` does the per-step `t_row * 3 + tag`
numbering (sorted distinct labels, exact-equality collapse when the live timestep passes a pin).
The test binary `tests/ref2va_pack_test.cpp` compiles the TU directly (no rad_core, no device);
`tests/data/ref2va/golden.json` is generated by `gen_golden.py <ComfyUI>/comfy/ldm/minimax/model.py`,
which AST-extracts the reference's constants + grid helpers + `PackedLayout` and execs them on
torch alone — every expectation is the reference's own float64 output. The positions compare
**bit-exact** after the float cast: both sides run identical IEEE double arithmetic, so a ULP
drift means the port reordered its arithmetic, and the test says so. Five golden cases (t2va,
fl2va keyframes at the origin and mid-timeline, all four reference kinds with a silent target, a
realistic chain signature, empty prompt) x three timestep probes (labels apart, collapsed past
both pins, far apart).
Parity with the plain generator: with no refs the pack reduces to `[text | audio | video]` —
same segment order, same row counts, the same planar shape — and `positions()` is now *this
code*: `minimaxh3.cpp` calls `ref2va_build(text_len, geom, {}, {}, &pack)` and copies
`pack.pos` (the first consumption point landed, 2026-10-19). The row contract the hand-rolled
version computed — text counting up, the soundtrack channel-major at the width extremes, the
1,4,4,4,4 time pattern — is pinned in `tests/ref2va_pack_test.cpp`
(`pack_plain_matches_the_three_segment_order`). One honest byte-level footnote: the old
`positions()` recovered the axis step as `((1-ratio)/2 + ratio) - (1-ratio)/2`, and on the grid
row whose coordinate is mathematically 0 the cancellation came out *exactly* 0, where the
reference's `arange*ratio/n` form leaves a float64 residue of ~1e-15. A sweep of all 1242 legal
sizes (multiples of 32, >= 256 a side, area <= 1344x768, aspect <= 4) found exactly 10 axes on
10 sizes where the f32 coordinate differed — one centre row each, the last bit of one rope
angle. The reference's form is authoritative, and the pack implements it verbatim.
## P4 sinks, concretely
`libr4d/r4d_vsa.hip`'s `vsa_geom()` makes **every segment before the video grid a dense 64-row
prefix** (the visibility walk then lets every query tile see all prefix tiles). The pack's order —
keyframes and reference blocks between the prompt and the targets — therefore makes every pinned
row an automatic sink the moment the driver lists it in `seg_cu` ahead of the video segment: no
kernel change. Two footnotes for the wiring: (a) ComfyUI's sparse node sparsifies the *target
audio* rows too, while Radiance's prefix rule keeps them dense — parity watch for P6, cheap to
split if the benchmark shows it matters; (b) `R_SEG`'s staged `seg_cu` is 4 i32 today and a full
presentation needs about two dozen (text, keyframe pairs, up to two segments per reference, the
two targets), so the register's
capacity grows with the wiring, along with `vsa_geom`'s `nd`.
## What the engine wiring still owes (P3 proper)
The pack answers "where do the rows sit"; consuming it touches four places the map found, of
which two have landed:
- **`positions()` now *is* the pack** (`ref2va_build` with no refs, copied straight into R_ROPE's
buffer — landed 2026-10-19, drift audit above).
- **`seg_cu` stages the pack's table** (landed 2026-10-19): a new *optional* plugin export,
`rad_arch_video_segs(g, cu, cap)` (documented in `rad_builder.h` — an additive export,
`RAD_ABI_VERSION` does not move; threaded through `loader.cpp` → `startup.{h,cpp}` →
`VideoDriver::init`), which for the plain geometry writes exactly `[0, n_text,
n_text + 2·n_audio, rows]`. `stage_geom` prefers it and **validates**: a plugin that exports
nothing, a table that disagrees with the geometry, or more segments than `R_SEG`'s four
int32s — any of those stages the driver's own table instead, byte-identical.
`video_gen_test`'s `the_plugin_segment_table_is_staged_and_a_disagreeing_one_falls_back`
drives all three. When refs arrive, `rows` itself comes from the pack, the local table
disappears, and `R_SEG`'s carve (`carve()`'s `4 * 4` — see P4 footnote (b)) grows with the
wiring.
What remains: `step_dit`'s row assembly (scatter pinned latents per `img_pos`/`audio_pos` —
rebuild the cond rows from the clean latents each step with the re-seeded 0.1% augmentation);
the modulation table (today `[lane*S, L*3*Ws]` = two timesteps x three tags, and the pack can
present up to four distinct labels x three tags = twelve columns, with the pinned labels
recomputed from `t_v`/`t_a` each step). The sampler already owns exactly the update rows once
they are last — no sampler change.
## Golden test vectors (hand-check against the formulas)
- tail 3.0 s: 73 px frames ⇒ `FRAME_RESCALE*73 = 121.67` audio units ≈ 121-122 rows/channel;
latent grid legal snaps {5,22,39,56,73}px ↔ {2,7,12,17,22} latent (`continuation_nodes.py:180-189`).
- video latent L frames span `5/3*(1+4(L-1))` audio units: L=22 ⇒ 141.67 (> its 121 audio span ⇒
the `max()` picks the video span).
- stereo ref audio rt=60 ⇒ 120 rows; rows 0-59 ch0 (w=low), 60-119 ch1 (w=high).
- image ref 1024×1024 target grid h=w=64 patch rows ⇒ n=4096? (h/2·w/2 — the ref's OWN latent_h/w:
`_frame_grid(latent_h, latent_w)` of the ref, not the target's).
## Landing plan for the rest of P3 (2026-10-19, after the encode device half)
Everything below was scouted against the tree, not from memory; every cited line is as of the
P2-device-half build. Increments are ordered so each one builds+tests green on its own; none
removes the submit-time refusals until the whole path works end-to-end (phased acceptance).
### 13a — ref-aware geometry (host, no behavior change, testable with fakes)
- **ABI trailing block** on `RadVideoGenBatch` (ABI 23 is unreleased — no bump): `const int32_t*
ref_tab` — NULL when the request carries no VAE references; else self-describing
`[0]=n_refs, [1]=n_keys`, then `n_refs × 6` words
`{kind(Ref2VARefKind), slot(1-based within kind), lat_h, lat_w, latent_t, audio_t}`, then
`n_keys × 3` `{frame, video_t, audio_t}`. HOST-pinned (step_dit reads it host-side exactly as
it reads `V->geom` by value — no device staging of the table itself).
- **New optional export** `rad_arch_video_pack(g, n_text, ref_tab, seg, cap_seg, pos, cap_pos)` →
rows (negative = refusal; `seg`/`pos` NULL → count only). Thin wrapper over `ref2va_build` —
the plugin stays the authority (segs_ precedent). Driver threads it beside `segs_`
(`loader.cpp` dlsym → `startup.{h,cpp}` → `VideoDriver::init(PackFn, ...)`, defaulted).
- **Carve widen**: `R_SEG` 4→**64** i32 rows (worst pack: text + ≤15 ref segs + 2 targets +
keyframes headroom). Kernel side needs NOTHING: `vsa_geom` loops `n_seg-1` generically
(r4d_vsa.hip:66-101) and the launcher takes `n_seg = numel(segs)-1`, cap 4096
(r4d_vsa.hip:1009-1011). `b_modg`/`b_sel` tile caps: `P = min(P, tiles_cap)` already clamps.
- `stage_geom` stages the pack's full boundary table when `ref_tab` is set (validation flips:
the local 4-boundary table is only reconstructible for no-refs requests).
- `video_gen_test`: fake `PackFn` cases mirroring the segs_ trio (staged / disagreeing falls
back / short cap refuses) + `ref2va_pack_test` needs no change (pack unchanged).
### 13b — step_dit consumes the pack (arch; green = compiles + selftest + fakes)
- Rebuild the pack HOST-side inside `step_dit` from `ref_tab` (the TU is in the plugin — the
driver staged from the same code via 13a's export, so segment starts agree by construction).
- **Row assembly** (minimaxh3.cpp:2939-2944 today): `op_text` already reads `seg[0..1]` from
`seg_cu`; replace the fixed `nt`/`nt+arows` offsets of `op_ain`/`op_vin` with the pack's audio
and video segment starts. Then per img-latent segment (cond/ref_img, ≤12 issues) issue
`op_vin` with `x = brow_slice(b_evc, venc_slot_row(kind,slot), seg_rows, kPatchVals)` — the
encoder's fold already emits patch-folded rows, so **no gather kernel**: slot slices feed the
embedder directly. `op_ain` likewise over `b_enca` slices. Target rows unchanged.
- **0.1% re-seeded aug** per pinned img/audio segment, rebuilt from CLEAN slot rows every step
(never in place into `b_evc`/`b_enca`): draw into scratch (rnd-op form, seed staged per step —
`build_step` already stages `R_SEED` per pass: bake step in), scale 0.001 via `chan_affine`,
`add` slot+noise → scratch, embed from scratch. Seeds: visual = seed words 0/1, audio = 2/3
(already the split in `stage_seed`).
- **Mod table**: `b_ada` per lane-step grows `kSegs`→**12 columns** (≤4 distinct labels × 3
tags): temb rows 2·S→2·S+2 (two constant pinned timesteps 0.999 video / 1.0 audio —
`ref2va_t_label` gives the labels; `ref2va_mod_rows` gives each segment's `t_row·3+tag`).
`step_ada`'s block×segment loop iterates the label cells; `step_dit`'s `mod()`/`modh()` view
column `(l, mod_row)` instead of `(l, e)`, and per-segment blocks take their mod row from the
rebuilt pack. TP2 half-split: `cut` moves to the VIDEO segment's middle row and `segh[1]=cu`
still stands only when the second half is video-only — with refs keep the half inside the
video segment (`hr0[1] = vseg.start + vrows/2`), and half 0's mod view takes the segment rows
for its range; `ref2va_mod_rows` order pins which cells it needs.
- Heads/Euler: the two target segments stay LAST, so the heads and both Euler steps keep working
with the views re-anchored at `aseg.start`/`vseg.start` — sampler state = update rows only.
- `b_sel`/`b_coarse` sizing: prefix tiles P grow with ref rows (each ≤64-row chunk adds a
tile); declare capacities already take the probe's widened `gen_rows`; re-check
`tiles_cap` math against a worst-case 9/3/3 presentation.
### 13c — driver media decode + encode scheduling (FFmpeg-gated for real bytes)
- Decode in the driver (bytes already in `VideoRefMedia::data`, in-memory `core/mm/mp4.cpp`
path): frames → f32 0..255 + clip repeat-pad to entry 23; samples → channel-major f32
right-padded to entry 0; ref sizes capped by `rad_arch_encode_geom` BEFORE decoding fully
(probe the export, bound the decode). Images: policy = resize to ≤256 side (the encode
ceiling) for the VAE view; the TE view keeps `media`'s own pixels.
- New job phase before cond: per ref, one V_ENCODE/A_ENCODE pass (order: tail, images, videos,
vaudios, audios — tail only for P2b requests); `next()` slot in the pipeline before
`build_cond`, gated on `decl_.encodes`; refusal removal is HERE (13c), not 13a/13b.
- P2b tail: `RAD_ENC_TAIL` slot 0 rides V_ENCODE from the ClipStore's sampled latents — but the
tail is ALREADY latents, so the tail path issues no V_ENCODE; it scatters the slice straight
(see NOTE-CONTINUITY); only its AUDIO tail needs A_ENCODE? — decide when P2b starts.
+42 -9
View File
@@ -200,6 +200,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
| `pool_cols` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean column a window of k columns) |
| `relu` | `M`(range) `n` `dtype` | `x` → `y` |
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
@@ -266,6 +267,14 @@ op; the segment count is `cu_seqlens`' length less one. An empty segment is a ze
of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and
rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`.
**`pool_cols`** is its transpose-sibling, pooling along the width: column `c` of row `m` of `y` is
the mean of `x[m]`'s columns `[c*k, c*k + k)`, with the same f32 sum, the same two roundings and the
same optional `mult`. `n` is the input width, a multiple of `k`; `y` has `n / k` columns. An audio
encoder's attention head pooling needs it because its `adaptive_avg_pool1d` runs across the feature
axis of a single row, where `pool_rows` can only reach across rows — a `pool_cols` then a row
reinterpretation then a `pool_rows` is what folds a head-major attention output to its mean pooled
form.
**`fill`** writes `y = value` over the extent (`value` 0 when absent). A rank issues it where it
computes nothing but a downstream reader still expects a defined buffer: an attention-zero rank's
block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce. A wire shared across
@@ -858,7 +867,7 @@ says which (`libref/ref_gen.cpp`).
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `dtype` | `t` → `y` |
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
| `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` |
| `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout |
@@ -891,7 +900,9 @@ source into every listed lane (a repainted picture's latent into each of its ima
store would round it, so the bytes are the three ops'.
- `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32,
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
diffusers' pipeline hands its transformer. `t` is f32 `[M]`.
diffusers' pipeline hands its transformer. `t` is f32 `[M]`. With `clamp_min`, each `t` is first
raised to that floor (`t = max(t, clamp_min)`) -- the reference conditioning's near-clean pin
timesteps, which sit above the sampler's decaying schedule. `0` (default) leaves `t` untouched.
- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
- `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's
standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is
@@ -956,7 +967,7 @@ libref function says which (`libref/ref_audio.cpp`).
| op | params | operands |
|---|---|---|
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `pad`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
@@ -1031,7 +1042,13 @@ input reads zero outside it.
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
clamp; a NaN stays NaN). f32 accumulation, one rounding.
clamp; a NaN stays NaN). f32 accumulation, one rounding. With `stride` > 1 (bf16 rows only: the
encoder's downsample) `pad` is required, `k` is any size, and the op is one sequence
`cu_seqlens` = `[0, rows of x]`: output row `m` reads `x[m stride + tap dil - pad]` with zeros
outside, PyTorch's zero-padded strided conv exactly (`k = 2 stride`, `pad = ceil(stride / 2)`
gives `M / stride` rows), and `y` has
`(rows + 2 pad - dil (k - 1) - 1) / stride + 1` rows exactly. An explicit `pad` without a
stride, and an even `k` with neither, are refused.
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
@@ -1260,7 +1277,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`).
| op | params | operands |
|---|---|---|
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `stride`/opt `stride_t`/opt `causal`/opt `pad`/opt `reflect`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` |
| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` |
| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` |
@@ -1272,10 +1289,10 @@ innermost (NDHWC). `geom` is the request's volume, i32 on the device (the parame
declare). An output holds at least the rows the volume writes; rows past them are not written.
Every op honours its activation operands' row pitches. `rd` is a rounding into the output's dtype.
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= T H W, cout]`, `geom = (T, H, W)`; `w` is
PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. Stride 1, zero padding `kt/2` frames and `k/2`
rows and columns on each side (`same`; `k` and `kt` odd):
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= rows out, cout]`, `geom = (T, H, W)`;
`w` is PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. The defaults are stride 1 with zero padding
`kt/2` frames and `k/2` rows and columns on each side (`pad` `same`; `k` and `kt` odd):
`y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw]
x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation
in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's
@@ -1284,6 +1301,22 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also
f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`,
`(512, 24)`.
The optional `stride` (rows and columns), `stride_t` (frames), `causal`, `pad` and `reflect`
give the video encoder's `CausalConv3d` forms; they are accepted for `k = kt = 3` only. The
padding is computed first — front/back frame pad `ft`/`bk` and top/bottom/left/right spatial pad
— then one strided pass: output `(t, i, j)` reads
`x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci]` (the same tap order),
and `y` holds `((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
((W + pl + pr - k) / stride + 1)` rows — PyTorch's length rule, which the plugins check the
operand rows against. The defaults give `ft = bk = kt/2` and `pt = pb = pl = pr = k/2`.
`causal` 1 zeroes `ft = kt - 1` frames in front and none behind (`bk = 0`), so one frame in
gives one frame out at any temporal stride — the reference's `T == 1` tap truncation included.
`pad` `down` (which needs `k = 3`) pads none above and left and one below and right
(`pt = pl = 0`, `pb = pr = 1`); the name and orientation are `conv2d_nhwc`'s. `reflect` 1
mirrors the *spatial* pads instead of zeroing them — torch `F.pad` mode `reflect`: a mirror
with no repeated edge, `x[-n] = x[n]`, `x[D + n] = x[D - 2 - n]` — so a padded dimension must
exceed its pad (`H, W >= 2` for the one-px pads). The frame pad is always zeros. MiniMax-H3's
encoder uses `reflect` 1 `causal` 1 everywhere, `pad` `down` plus `stride` 2 in `Downsample3D`.
- `group_norm` is PyTorch's `nn.GroupNorm(groups, n)` on `[1, n, T, H, W]`: `x` and `y`
`[>= M, n]` (`M` is `y`'s rows), group `g` the channels `[g n/groups, (g+1) n/groups)` of all
`M` rows. `mean_g` and the biased `var_g` are over the group's `M n/groups` values, accumulated in