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

+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Regenerate golden.json -- the reference numbers arch/minimaxh3/rad_ref2va_pack.cpp is tested
against (tests/ref2va_pack_test.cpp).
gen_golden.py /path/to/ComfyUI/comfy/ldm/minimax/model.py [out.json]
The reference implementation lives in the ComfyUI tree; importing its package pulls the whole
device stack, so this extracts exactly the layout's source -- the four constants, the grid helpers
and the PackedLayout class -- with `ast`, execs them on torch alone, and runs the cases below.
Nothing here is a re-derivation: every number in golden.json is computed by the reference code
itself, at float64, from the file you point it at. If a radiance bump changes golden.json, the port
must change with it.
The `mod` entries are NOT produced by the reference class (its _forward folds them into per-row
mask tensors); they are the reference's segment-level rule -- the seg_tag table and the
{stream, pin} timestep labels transcribed from _forward -- applied to self.segments here, which is
the arithmetic the port replicates (sorted distinct labels, collapse on equality, t_row * 3 + tag).
"""
import ast
import json
import sys
NEED = ["_axis_from_sqrt_area", "_frame_grid", "_video_t_spans", "_video_t_grid", "_ref_t_span",
"_audio_grid", "_video_grid", "PackedLayout"]
NEED_ASSIGN = ["FRAME_PER_TOKEN", "FRAME_RESCALE", "VISUAL_COND_TIMESTEP", "AUDIO_COND_TIMESTEP"]
def extract(path):
"""The reference's layout source, exec'd with torch/math only."""
import math
import torch
with open(path) as f:
src = f.read()
tree = ast.parse(src)
picked, got = [], set()
for node in tree.body:
names = ([t.id for t in node.targets if isinstance(t, ast.Name)]
if isinstance(node, ast.Assign) else
[node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef)) else [])
if any(n in NEED or n in NEED_ASSIGN for n in names):
picked.append(ast.get_source_segment(src, node))
got.update(names)
missing = (set(NEED) | set(NEED_ASSIGN)) - got
if missing:
sys.exit(f"{path} does not define: {sorted(missing)} -- reference moved?")
ns = {"math": math, "torch": torch}
exec("\n\n".join(picked), ns)
return ns
# The reference _forward's per-kind (timestep label, modality tag), transcribed.
SEG_TAG = {"text": 1, "video": 0, "audio": 2, "cond": 0, "ref_img": 0, "cond_audio": 2,
"ref_audio": 2}
def t_label(kind, t_v, t_a):
if kind in ("cond", "ref_img"):
return max(t_v, 0.999)
if kind in ("cond_audio", "ref_audio"):
return max(t_a, 1.0)
if kind == "audio":
return t_a
return t_v
def mod_rows(layout, t_v, t_a):
# non-empty segments only: the reference derives labels from mask TENSORS, so a zero-row
# segment contributes no rows to the distinct-label set. An empty segment's own row index has
# no defined value -- 0 by convention, matching the port.
uniq = sorted({t_label(k, t_v, t_a) for (s, e, k) in layout.segments if e > s})
return [uniq.index(t_label(k, t_v, t_a)) * 3 + SEG_TAG[k] if e > s else 0
for (s, e, k) in layout.segments]
CASES = {
# plain t2va: the pack must reproduce the old three-segment shape exactly
"t2va": dict(text_len=5, target=(3, 8, 10, 4), keyframes=[], refs=[]),
# fl2va keyframes at frame 0 (shares the target origin) and mid-timeline, video-only and both
"fl2va": dict(text_len=4, target=(3, 8, 8, 3),
keyframes=[dict(frame=0, video_t=1, audio_t=2), dict(frame=7, video_t=2, audio_t=0)],
refs=[]),
# every reference kind in one request: a photo, a standalone soundtrack, a silent clip, and a
# clip with sound (its audio packs before its video, at the clip's own width extremes); a
# second photo after them; audio_t=0 targets the silent-video edge
"ref2va_all": dict(text_len=6, target=(2, 8, 8, 0),
keyframes=[],
refs=[dict(kind="image", latent_h=6, latent_w=10, latent_t=0, ref_audio_t=0),
dict(kind="audio", latent_h=0, latent_w=0, latent_t=0, ref_audio_t=3),
dict(kind="video", latent_h=4, latent_w=6, latent_t=2, ref_audio_t=0),
dict(kind="video_audio", latent_h=5, latent_w=7, latent_t=3,
ref_audio_t=4),
dict(kind="image", latent_h=4, latent_w=4, latent_t=0, ref_audio_t=0)]),
# a realistic signature: keyframes + a big photo + a clip with sound, real-ish sizes
"chain": dict(text_len=32, target=(7, 16, 24, 6),
keyframes=[dict(frame=0, video_t=1, audio_t=2)],
refs=[dict(kind="image", latent_h=8, latent_w=12, latent_t=0, ref_audio_t=0),
dict(kind="video_audio", latent_h=4, latent_w=6, latent_t=5,
ref_audio_t=20)]),
# degenerate prompt: text_len 0, nothing but targets
"no_text": dict(text_len=0, target=(2, 4, 6, 1), keyframes=[], refs=[]),
}
# (t_v, t_a) probes: apart (four distinct labels), and past both pins (every label collapses to
# two, and cond/ref share the video row, cond_audio/ref_audio the audio row)
SIGMAS = [(0.5, 0.45), (0.9995, 0.999), (0.2, 0.15)]
def main():
import torch
model_py = sys.argv[1]
out = sys.argv[2] if len(sys.argv) > 2 else "golden.json"
ns = extract(model_py)
PackedLayout = ns["PackedLayout"]
golden = {}
for name, c in CASES.items():
t, ah, aw, at = c["target"]
refs = [dict(kind=r["kind"], latent_h=r["latent_h"], latent_w=r["latent_w"],
latent_t=r["latent_t"], ref_audio_t=r["ref_audio_t"]) for r in c["refs"]]
# the class reads only the latents' shapes (video .shape[2], audio .shape[-1]); zeros do
kfs = [dict(resolved_frame_index=k["frame"],
latent=torch.zeros(1, 24, k["video_t"], ah, aw) if k["video_t"] else None,
audio_latent=torch.zeros(1, 32, 2, k["audio_t"]) if k["audio_t"] else None)
for k in c["keyframes"]]
lay = PackedLayout(c["text_len"], t, ah, aw, at, keyframes=kfs or None, refs=refs or None)
golden[name] = {
"text_len": c["text_len"], "latent_t": t, "latent_h": ah, "latent_w": aw,
"audio_t": at,
"keyframes": c["keyframes"], "refs": c["refs"],
"seq_len": lay.seq_len,
"segments": [[s, e, k] for (s, e, k) in lay.segments],
"positions": [[float(x) for x in row] for row in lay.position_ids.tolist()],
"img_update": [bool(b) for b in lay.img_update.tolist()],
"audio_update": [bool(b) for b in lay.audio_update.tolist()],
"img_pos": [int(i) for i in lay.img_pos.tolist()],
"audio_pos": [int(i) for i in lay.audio_pos.tolist()],
"mod": [dict(t_v=tv, t_a=ta, rows=mod_rows(lay, tv, ta)) for tv, ta in SIGMAS],
}
with open(out, "w") as f:
json.dump(golden, f, indent=1)
print(f"{out}: " + ", ".join(f"{n} {g['seq_len']} rows" for n, g in golden.items()))
main()
File diff suppressed because it is too large. Load diff
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Generate tests/data/vae_geom/golden.json from the REFERENCE VAEs themselves.
Same discipline as tests/data/ref2va/gen_golden.py: the module source is AST-parsed and only the
needed classes/helpers are extracted and exec'd on torch alone -- importing the comfy package
dies on this machine (aiter JIT build failure). Unlike the pack golden this one runs real CPU
networks, so expectations are the encoders' own output shapes:
* the video encoder (EncoderFCN3D with the reference's exact constructor arguments) + the
reference's own encode()/encode_temporal()/split_tiles()/tiled_encode() methods bound to a
shim self -> latent counts, per-axis tile plans, and blended tile-grid shapes;
* the audio DAC encoder -> latent frames for a sweep of sample counts (its posterior head,
AttnProjection + 1x1 mean_proj, applies no strided op, so it cannot change the frame count;
NOTE-P2-ENCODE.md makes that argument explicitly).
Only shims: comfy.quant_ops must exist without `ck` (the fused-pad fast path then self-disables
and the CPU path is the plain torch one), and Conv3d must accept the reference's autopad kwarg --
on CPU the only use is the single-frame causal case ("causal_zero" = implicit front zero pad of
kernel_t - 1, which is what physically skipping the pad means for a causal conv).
Usage: python gen_golden.py <ComfyUI>/comfy/ldm/minimax/vae.py <...>/audio_vae.py golden.json
"""
import ast
import json
import math
import sys
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
# ----------------------------------------------------------------------------- shims
class _Ops:
class Conv3d(nn.Conv3d):
def forward(self, x, autopad=None, **kw):
if autopad == "causal_zero":
k = self.kernel_size[0]
x = F.pad(x, (0, 0, 0, 0, k - 1, 0))
return super().forward(x)
Conv1d = nn.Conv1d
ConvTranspose1d = nn.ConvTranspose1d
GroupNorm = nn.GroupNorm
LayerNorm = nn.LayerNorm
Linear = nn.Linear
class _QuantOps:
pass
def _cast_to_input(w, x):
return w.to(device=x.device, dtype=x.dtype)
class _ComfyOpsNs:
"""what the extracted code reaches for as bare `comfy.ops.*`: cast_to_input is the real
semantics (a plain device/dtype cast); the kitchen fast paths are never reached on CPU, so
placeholders are enough there"""
cast_bias_weight = None
uncast_bias_weight = None
cast_to_input = staticmethod(_cast_to_input)
comfy = types.ModuleType("comfy")
comfy.quant_ops = _QuantOps()
comfy.ops = _ComfyOpsNs()
ops = _Ops
# --------------------------------------------------------------------------- extract
def top_level(path, names):
src = open(path).read()
tree = ast.parse(src)
out = {}
for node in tree.body:
key = getattr(node, "name", None)
if key is None and isinstance(node, ast.Assign):
key = [t.id for t in node.targets if isinstance(t, ast.Name)]
else:
key = [key]
for k in key:
if k in names:
out[k] = ast.get_source_segment(src, node)
missing = set(names) - set(out)
if missing:
raise SystemExit(f"not found in {path}: {sorted(missing)}")
return out
def class_methods(path, cls_name, method_names):
src = open(path).read()
tree = ast.parse(src)
for node in tree.body:
if isinstance(node, ast.ClassDef) and node.name == cls_name:
found = {m.name: ast.get_source_segment(src, m) for m in node.body
if isinstance(m, ast.FunctionDef) and m.name in method_names}
missing = set(method_names) - set(found)
if missing:
raise SystemExit(f"{cls_name} methods not found: {sorted(missing)}")
return found
raise SystemExit(f"class {cls_name} not found in {path}")
ns = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
# --- video: the encoder chain classes + module constants
VIDEO_NEED = [
"IMAGENET_MEAN", "IMAGENET_STD", "LATENTS_MEAN", "LATENTS_STD",
"_kitchen_ndhwc", "_fused_norm_pad", "_fp16_accum_conv",
"CausalConv3d", "TemporalIsolatedGroupNorm", "group_norm_3d",
"Downsample3D", "ResnetBlock3D", "EncoderFCN3D",
]
_vsrc = top_level(sys.argv[1], VIDEO_NEED)
for name in VIDEO_NEED:
exec(_vsrc[name], ns)
# --- video: the wrapper methods, bound to a shim self (no decoder, no checkpoint)
VIDEO_METHODS = ["_encode_moments", "_normalize_pixels", "split_tiles", "blend",
"tiled_encode", "_adaptive_encode", "encode_temporal", "encode"]
mns = dict(ns)
for name, code in class_methods(sys.argv[1], "MiniMaxH3VideoVAE", VIDEO_METHODS).items():
exec(code, mns)
def make_video_vae():
self = types.SimpleNamespace()
self.vae_ratio = 16
self.vae_ratio_t = 8
self.clip_length = 17
self.token_drop = 3
self.tile_size = 256
self.tile_overlap_min = 64
self.tiling = True
self.encoder = ns["EncoderFCN3D"](
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, in_channels=3, z_channels=24,
double_z=True)
self.quant_conv = nn.Conv3d(48, 48, 1)
self.latents_mean = torch.tensor(ns["LATENTS_MEAN"])
self.latents_std = torch.tensor(ns["LATENTS_STD"])
self.pixel_mean = torch.tensor(ns["IMAGENET_MEAN"]).view(1, 3, 1, 1, 1)
self.pixel_std = torch.tensor(ns["IMAGENET_STD"]).view(1, 3, 1, 1, 1)
for name in VIDEO_METHODS:
setattr(self, name, types.MethodType(mns[name], self))
return self
golden = {"video": {}, "audio": {}}
golden["video"]["constants"] = {
"latents_mean": list(ns["LATENTS_MEAN"]), "latents_std": list(ns["LATENTS_STD"]),
"pixel_mean": list(ns["IMAGENET_MEAN"]), "pixel_std": list(ns["IMAGENET_STD"]),
}
vae = make_video_vae()
# --- 1. latent count per frame count, from the reference encode() end to end
FRAME_COUNTS = [1, 2, 3, 5, 8, 16, 17, 18, 22, 34, 39, 40, 56, 72, 73, 90]
cases = []
with torch.no_grad():
for t in FRAME_COUNTS:
x = torch.zeros(1, 3, t, 32, 32)
z = vae.encode(x)
cases.append({"T": t, "z_shape": list(z.shape)})
print(f"video encode T={t:3d} -> z {list(z.shape)}", file=sys.stderr)
golden["video"]["encode"] = cases
# --- 2. split_tiles raw output (the pure arithmetic, exact reference return values)
TILE_LENS = [1, 16, 64, 128, 255, 256, 257, 272, 320, 448, 512, 640, 720, 768, 1024, 1088, 1344, 2048]
golden["video"]["split_tiles"] = [
{"input_len": L, "starts": starts, "lens": lens, "overlaps": ovl}
for L in TILE_LENS
for starts, lens, ovl in [vae.split_tiles(L)]
]
# --- 3. the tile grid end to end: the blend/cut keeps the moments at exactly ratio-reduced size
with torch.no_grad():
tiled = []
for x_shape in [(1, 3, 5, 320, 320), (1, 3, 2, 512, 256), (1, 3, 17, 288, 192)]:
moments = vae.tiled_encode(torch.zeros(*x_shape))
tiled.append({"x_shape": list(x_shape), "moments_shape": list(moments.shape)})
print(f"video tiled {list(x_shape)} -> moments {list(moments.shape)}", file=sys.stderr)
golden["video"]["tiled_encode"] = tiled
# --- 4. audio DAC encoder: latent frames for a sweep of (padded) sample counts
AUDIO_NEED = ["snake", "Snake1d", "ResidualUnit", "EncoderBlock", "Encoder"]
ans = dict(torch=torch, nn=nn, F=F, math=math, comfy=comfy, ops=ops)
for name in AUDIO_NEED:
exec(top_level(sys.argv[2], [name])[name], ans)
with torch.no_grad():
enc = ans["Encoder"](64, (2, 4, 4, 5, 5), 2048)
samples_cases = []
for s in [1, 2, 400, 799, 800, 801, 1599, 1600, 1601, 4000, 32000, 32001, 96000]:
hop = 800
padded = math.ceil(s / hop) * hop
out = enc(torch.zeros(2, 1, padded)) # b*s = 2 stereo streams, mono encoder
samples_cases.append({"samples": s, "padded": padded, "T": out.shape[2]})
print(f"audio encode {s:6d} (pad {padded}) -> T {out.shape[2]}", file=sys.stderr)
golden["audio"]["latents"] = samples_cases
json.dump(golden, open(sys.argv[3], "w"), indent=1)
print(f"wrote {sys.argv[3]}", file=sys.stderr)
+660
View File
@@ -0,0 +1,660 @@
{
"video": {
"constants": {
"latents_mean": [
0.858090341091156,
-0.9606591463088989,
1.0661640167236328,
-0.5090325474739075,
-0.2727581858634949,
-1.3675414323806763,
-0.2553254961967468,
-0.26907554268836975,
-0.5376840829849243,
-0.0464097298681736,
0.6657370328903198,
0.19690127670764923,
-0.5460608005523682,
-0.4035342037677765,
-0.23683024942874908,
0.25928452610969543,
-0.30133944749832153,
0.211341992020607,
-1.1206848621368408,
0.3581933379173279,
-0.04225143790245056,
0.2604829967021942,
0.22864092886447906,
0.7056031823158264
],
"latents_std": [
1.2223774194717407,
1.2767263650894165,
1.6831774711608887,
1.7549455165863037,
1.5636216402053833,
2.194143533706665,
0.9653137922286987,
1.0569885969161987,
0.841948926448822,
0.7729952931404114,
1.8955937623977661,
0.946841835975647,
0.7996809482574463,
0.44988900423049927,
0.7197399735450745,
0.6936293244361877,
2.961095094680786,
2.7694199085235596,
3.0496184825897217,
2.1088054180145264,
3.276226282119751,
3.1627357006073,
2.2816812992095947,
2.6127843856811523
],
"pixel_mean": [
0.485,
0.456,
0.406
],
"pixel_std": [
0.229,
0.224,
0.225
]
},
"encode": [
{
"T": 1,
"z_shape": [
1,
24,
1,
2,
2
]
},
{
"T": 2,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 3,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 5,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 8,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 16,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 17,
"z_shape": [
1,
24,
2,
2,
2
]
},
{
"T": 18,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 22,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 34,
"z_shape": [
1,
24,
7,
2,
2
]
},
{
"T": 39,
"z_shape": [
1,
24,
12,
2,
2
]
},
{
"T": 40,
"z_shape": [
1,
24,
12,
2,
2
]
},
{
"T": 56,
"z_shape": [
1,
24,
17,
2,
2
]
},
{
"T": 72,
"z_shape": [
1,
24,
22,
2,
2
]
},
{
"T": 73,
"z_shape": [
1,
24,
22,
2,
2
]
},
{
"T": 90,
"z_shape": [
1,
24,
27,
2,
2
]
}
],
"split_tiles": [
{
"input_len": 1,
"starts": [
0
],
"lens": [
1
],
"overlaps": []
},
{
"input_len": 16,
"starts": [
0
],
"lens": [
16
],
"overlaps": []
},
{
"input_len": 64,
"starts": [
0
],
"lens": [
64
],
"overlaps": []
},
{
"input_len": 128,
"starts": [
0
],
"lens": [
128
],
"overlaps": []
},
{
"input_len": 255,
"starts": [
0
],
"lens": [
255
],
"overlaps": []
},
{
"input_len": 256,
"starts": [
0
],
"lens": [
256
],
"overlaps": []
},
{
"input_len": 257,
"starts": [
0,
16
],
"lens": [
256,
256
],
"overlaps": [
240
]
},
{
"input_len": 272,
"starts": [
0,
16
],
"lens": [
256,
256
],
"overlaps": [
240
]
},
{
"input_len": 320,
"starts": [
0,
64
],
"lens": [
256,
256
],
"overlaps": [
192
]
},
{
"input_len": 448,
"starts": [
0,
192
],
"lens": [
256,
256
],
"overlaps": [
64
]
},
{
"input_len": 512,
"starts": [
0,
128,
256
],
"lens": [
256,
256,
256
],
"overlaps": [
128,
128
]
},
{
"input_len": 640,
"starts": [
0,
192,
384
],
"lens": [
256,
256,
256
],
"overlaps": [
64,
64
]
},
{
"input_len": 720,
"starts": [
0,
144,
304,
464
],
"lens": [
256,
256,
256,
256
],
"overlaps": [
112,
96,
96
]
},
{
"input_len": 768,
"starts": [
0,
160,
336,
512
],
"lens": [
256,
256,
256,
256
],
"overlaps": [
96,
80,
80
]
},
{
"input_len": 1024,
"starts": [
0,
192,
384,
576,
768
],
"lens": [
256,
256,
256,
256,
256
],
"overlaps": [
64,
64,
64,
64
]
},
{
"input_len": 1088,
"starts": [
0,
160,
320,
480,
656,
832
],
"lens": [
256,
256,
256,
256,
256,
256
],
"overlaps": [
96,
96,
96,
80,
80
]
},
{
"input_len": 1344,
"starts": [
0,
176,
352,
528,
704,
896,
1088
],
"lens": [
256,
256,
256,
256,
256,
256,
256
],
"overlaps": [
80,
80,
80,
80,
64,
64
]
},
{
"input_len": 2048,
"starts": [
0,
176,
352,
528,
704,
880,
1056,
1232,
1408,
1600,
1792
],
"lens": [
256,
256,
256,
256,
256,
256,
256,
256,
256,
256,
256
],
"overlaps": [
80,
80,
80,
80,
80,
80,
80,
80,
64,
64
]
}
],
"tiled_encode": [
{
"x_shape": [
1,
3,
5,
320,
320
],
"moments_shape": [
1,
48,
2,
20,
20
]
},
{
"x_shape": [
1,
3,
2,
512,
256
],
"moments_shape": [
1,
48,
1,
32,
16
]
},
{
"x_shape": [
1,
3,
17,
288,
192
],
"moments_shape": [
1,
48,
5,
18,
12
]
}
]
},
"audio": {
"latents": [
{
"samples": 1,
"padded": 800,
"T": 1
},
{
"samples": 2,
"padded": 800,
"T": 1
},
{
"samples": 400,
"padded": 800,
"T": 1
},
{
"samples": 799,
"padded": 800,
"T": 1
},
{
"samples": 800,
"padded": 800,
"T": 1
},
{
"samples": 801,
"padded": 1600,
"T": 2
},
{
"samples": 1599,
"padded": 1600,
"T": 2
},
{
"samples": 1600,
"padded": 1600,
"T": 2
},
{
"samples": 1601,
"padded": 2400,
"T": 3
},
{
"samples": 4000,
"padded": 4000,
"T": 5
},
{
"samples": 32000,
"padded": 32000,
"T": 40
},
{
"samples": 32001,
"padded": 32800,
"T": 41
},
{
"samples": 96000,
"padded": 96000,
"T": 120
}
]
}
}