Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: condition H3 vision encoder on canvas-prepared keyframes (#8867)

[._.]/ Adam Eivycd9ec78369eb
diff --git a/docs/research/minimax-h3-continuity.md b/docs/research/minimax-h3-continuity.md
index 2aa686ca8e..44367f10f0 100644
--- a/docs/research/minimax-h3-continuity.md
+++ b/docs/research/minimax-h3-continuity.md
@@ -53,6 +53,38 @@ Lazy work may be charged to the boundary that materializes it. Failed worker
runs retain a failed report and log; never interpret partial outputs as success.
Logs may contain local paths; redact them before publishing evidence.
+## Reference parity finding: vision input geometry
+
+A static comparison of the pinned MLX port against the vendored FL2VA reference
+(`reference/diffusers/modular/` in the runtime checkout) found one divergence
+on the image path. The reference setup step replaces its keyframes with
+canvas-prepared copies (`prepare_keyframe_image`: stretch the first keyframe,
+cover-crop a follower), and **both** the Qwen3-VL text encoder and the video VAE
+read those prepared images. The port prepares keyframes only inside
+`_encode_keyframes`; its text encoder received the raw upload.
+
+With the checkpoint's processor (patch 16, merge 2, up to 16.7M pixels) each
+vision token covers 32×32 pixels, the same footprint as a VAE latent patch. A
+canvas-prepared 576×1024 keyframe therefore yields an 18×32 vision grid that
+matches the 18×32 conditioning rows. A raw 3024×4032 photo yields about 11,800
+vision tokens, and a 1920×1080 frame roughly 2,000 tokens at the wrong aspect.
+Both are unlike anything the reference presents.
+
+`generate_minimax_h3.py` now places keyframes on the canvas before calling the
+pipeline, using the port's own `prepare_keyframe_image`. That function returns
+a canvas-sized image unchanged, so VAE conditioning is byte-for-byte what it was
+before. The vision features now follow the reference contract. Prompt-embedding
+cache keys follow the prepared pixels, so older raw-image entries age out.
+
+This fixes a real integration defect, but it is **not a confirmed root cause**
+of the scene change: no render has compared the two inputs. The synthetic source
+from the diagnostic is already 768×1344, so its native cases never took this
+path. VAE normalization/posterior sampling, packed tags and rotary positions
+matched the reference in structure and are covered by the runtime's own parity
+tests. The only other difference found is the PIL twin of the image processor,
+used when torch is absent, whose resampling differs numerically from the
+torchvision processor.
+
## What remains to establish
No real render results accompany this harness. `continuity: not_assessed` stays
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 0921e08c93..1d62b66c71 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -1036,6 +1036,27 @@ def validate_args(args: argparse.Namespace) -> None:
raise SystemExit(f"--draft-decoder-id must be a bare directory-safe name; got {args.draft_decoder_id!r}.")
+def place_keyframes_on_canvas(images: list, width: int, height: int) -> list:
+ """Put every keyframe onto the render canvas before the pipeline sees it.
+
+ The pinned FL2VA reference prepares keyframes onto the canvas in its setup
+ step, and BOTH consumers read those prepared images: the Qwen3-VL vision
+ tower (via the text encoder) and the video VAE. The pinned MLX port prepares
+ them only inside `_encode_keyframes`, so its text encoder receives the raw
+ upload — the vision tower then sees a different size, aspect and token grid
+ than the VAE rows it is paired with (#8867).
+
+ Uses the port's own `prepare_keyframe_image` (the reference algorithm:
+ stretch the first keyframe, cover-crop any follower), which returns an
+ already-canvas-sized image untouched, so the VAE path is unchanged.
+ """
+ if not images:
+ return images
+ from minimax_h3_mlx.packing import prepare_keyframe_image
+
+ return [prepare_keyframe_image(image, height, width, stretch=index == 0) for index, image in enumerate(images)]
+
+
def render_outputs(pipe, args, images, save_mp4, batch_seeds=None):
"""Render one at a time, retaining weights and only this request's conditioning.
@@ -1043,6 +1064,7 @@ def render_outputs(pipe, args, images, save_mp4, batch_seeds=None):
encoder's return in memory even when the optional disk cache is unavailable.
The closed-over prompt and images never change inside this workflow.
"""
+ images = place_keyframes_on_canvas(images, args.width, args.height)
preview = _install_h3_stepwise_preview(pipe, args)
encode = pipe.text_encoder.encode
encoded = None
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 3817cabc0b..30d380075b 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -1267,3 +1267,44 @@ print('OK')
`);
expect(output.trim()).toBe('OK');
});
+
+// #8867: the FL2VA reference feeds its vision tower the keyframes it already put
+// onto the canvas. The pinned port prepares them only for the VAE, so without
+// this the text encoder would read the raw upload at a different size and token
+// grid than the conditioning rows it is paired with.
+it.skipIf(!pyBin)('conditions the vision encoder on canvas-prepared keyframes, as the reference does', () => {
+ const output = runPython(`${importRunner}
+import contextlib, io, sys, tempfile, types
+from types import SimpleNamespace as NS
+runner.heartbeat = lambda *_: contextlib.nullcontext()
+runner._install_h3_stepwise_preview = lambda *_: None
+prepared = []
+def prepare_keyframe_image(image, height, width, stretch):
+ prepared.append((image.size, stretch))
+ return NS(size=(width, height), source=image.size)
+packing = types.ModuleType('minimax_h3_mlx.packing')
+packing.prepare_keyframe_image = prepare_keyframe_image
+sys.modules['minimax_h3_mlx'] = types.ModuleType('minimax_h3_mlx')
+sys.modules['minimax_h3_mlx.packing'] = packing
+seen = {}
+def encode(prompt, images):
+ seen['encoder'] = [(image.size, image.source) for image in images]
+ return ('embeddings', 'tags')
+class Pipe:
+ text_encoder = NS(encode=encode)
+ def __call__(self, prompt, **kwargs):
+ # The pinned pipeline hands its images to the text encoder unchanged.
+ self.text_encoder.encode(prompt, kwargs['images'])
+ return NS(video=NS(shape=[124]), fps=24, audio=None, sample_rate=32000)
+with tempfile.TemporaryDirectory() as tmp:
+ args = NS(output=str(Path(tmp) / 'clip.mp4'), seed=0, prompt='Example shot', num_frames=124, steps=8,
+ anchor=['first', 'last'], height=1344, width=768)
+ with contextlib.redirect_stdout(io.StringIO()):
+ runner.render_outputs(Pipe(), args, [NS(size=(3000, 4000)), NS(size=(1920, 1080))],
+ lambda path, *_: path.write_bytes(b'example-video'))
+assert prepared == [((3000, 4000), True), ((1920, 1080), False)], prepared
+assert seen['encoder'] == [((768, 1344), (3000, 4000)), ((768, 1344), (1920, 1080))], seen
+print('OK')
+`);
+ expect(output.trim()).toBe('OK');
+});