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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test: prove H3's PIL image processor matches the reference on canvases (#8867)
[._.]/ Adam Eivy1911c3f331fe
diff --git a/docs/research/minimax-h3-continuity.md b/docs/research/minimax-h3-continuity.mdindex 44367f10f0..b7e6ec4c82 100644--- a/docs/research/minimax-h3-continuity.md+++ b/docs/research/minimax-h3-continuity.md@@ -81,9 +81,58 @@ of the scene change: no render has compared the two inputs. The synthetic sourcefrom the diagnostic is already 768×1344, so its native cases never took thispath. VAE normalization/posterior sampling, packed tags and rotary positionsmatched 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.+tests. The only other difference found was the image-processor backend,+examined next.++## Reference parity finding: image-processor backends++The reference encodes keyframes with the checkpoint-declared torchvision+`Qwen2VLImageProcessor`. The MLX runner has no PyTorch, so it binds that+processor's PIL twin, `Qwen2VLImageProcessorPil`. At the pinned transformers+5.14.1, the two share `smart_resize`, BICUBIC resampling, RGB conversion, the+checkpoint's configuration (patch 16, merge 2, temporal patch 2, 65,536 to+16,777,216 pixels, mean and std 0.5) and the patch flattening order. They differ+in two ways. The twin resamples through Pillow on `uint8` and normalizes as+`(x / 255 - 0.5) / 0.5`. The reference resamples with antialiased torchvision+bicubic and normalizes as a fused `(x - 127.5) / 127.5`. Both return float32+arrays with an identical `[1, h/16, w/16]` grid.++`scripts/diagnose_minimax_h3_processor.py` runs both backends on the CPU over+deterministic synthetic images. The images are half gradient and half full-band+noise, the worst case for a resampler. The script reads only the cached+checkpoint's `FL2VA/processor` directory and never loads a model. Run it with+an existing interpreter that has transformers at the H3 lock's version, torch+and torchvision. The H3 venv has no torch, so it cannot run this check.++```sh+<python-with-torch> scripts/diagnose_minimax_h3_processor.py \+ --processor-dir <hf-cache>/models--MiniMaxAI--MiniMax-H3/snapshots/<revision>/FL2VA/processor+```++A run at transformers 5.14.1, torch 2.13 and torchvision 0.28, against checkpoint+revision `6818f6c3`, produced:++| Input (w×h) | Processor resamples | Max abs diff | bfloat16 mismatch |+| --- | --- | --- | --- |+| 576×1024, 768×1344, 1344×768, 512×288 (canvases) | no | 5.9e-8 | 0 |+| 1080×1920, 720×1280 (raw frames) | yes | 1/127.5 (one 8-bit level) | 0.1–0.2% |+| 128×256 (below the pixel floor) | yes | 2/127.5 | 10.7% |++Every H3 canvas is a multiple of 32, which is the processor's resize factor.+Canvases at H3's released sizes are also well inside its pixel bounds. After+the runner places keyframes on the canvas, the processor therefore never+resamples them. The twin's output then matches the reference to float32+rounding. After the port casts it to the vision tower's bfloat16, it is+bit-identical. The backend difference is real only for inputs the processor+resamples: raw uploads before the vision-geometry correction, or a custom canvas+smaller than 65,536 pixels. In this run that gap was at most two 8-bit levels,+and the reference resamples those inputs too. The PIL twin is **excluded as a cause** of the scene+change on the production path. No correction is warranted. The script exits+nonzero if a future transformers pin breaks this parity on a canvas.++The continuity harness now records the backend class and keyframe input sizes as+`vision_processor` in each `report.json`. A render can then show which processor+read its keyframes and whether they arrived canvas-sized.## What remains to establish@@ -92,9 +141,14 @@ explicit even after rendering: inspect the sampled frames and full clip, lookingfor the colored room and objects beyond frame 12. Record whether a scene changeoccurs and when; first-frame resemblance alone cannot pass the comparison.-Compare VAE normalization/posterior sampling, vision features, token tags and-rotary positions against the pinned FL2VA reference before changing the adapter.-Matching shapes cannot prove those numerical contracts. Repeat the synthetic+Image-processor features are now established as matching on the production+path; see above. VAE normalization/posterior sampling, vision-tower features,+token tags and rotary positions still need a numerical comparison against the+pinned FL2VA reference. That needs the reference's PyTorch weights on a+CUDA or large-memory host. Matching shapes cannot prove those contracts. The+`small-motion` case stretches the 768×1344 source onto 576×1024, so it+exercises the vision-geometry correction. For a before/after comparison, render+it once from this tree and once with `place_keyframes_on_canvas` reverted. Repeat the syntheticsource and motion prompt on an installed image-capable LTX model, with its nativecanvas, frame grid and stock encoder; record that model's pins and separate phasetimings. The H3 script intentionally does not imply that an LTX run occurred.diff --git a/scripts/diagnose_minimax_h3.py b/scripts/diagnose_minimax_h3.pyindex a0af1d36d1..1d89457514 100644--- a/scripts/diagnose_minimax_h3.py+++ b/scripts/diagnose_minimax_h3.py@@ -69,13 +69,21 @@ def instrument(pipe, report, clock=time.perf_counter):keyframes = pipe._encode_keyframesdit = pipe.dit- def encode_observed(*args, **kwargs):- result = encode(*args, **kwargs)+ def encode_observed(prompt, images=None, *args, **kwargs):+ result = encode(prompt, images, *args, **kwargs)features, tags = resultreport["vision_conditioning"] = {"embedding_shape": list(features.shape),"token_tag_counts": dict(Counter(str(tag) for tag in tags.tolist())),}+ if images:+ # Which backend read the keyframes (the torch-free runner binds the+ # PIL twin), and at what size: a canvas-sized input is the one both+ # backends process identically.+ report["vision_processor"] = {+ "class": type(pipe.text_encoder.processor.image_processor).__name__,+ "input_sizes": [list(image.size) for image in images],+ }return resultdef keyframes_observed(*args, **kwargs):diff --git a/scripts/diagnose_minimax_h3.test.js b/scripts/diagnose_minimax_h3.test.jsindex 52b841c0e3..9da95f663c 100644--- a/scripts/diagnose_minimax_h3.test.js+++ b/scripts/diagnose_minimax_h3.test.js@@ -52,13 +52,16 @@ def fail_decode(*args):raise ValueError('decode failed')def dit(*args, **kwargs):return rows-pipe = SimpleNamespace(text_encoder=SimpleNamespace(encode=lambda *a: encode_result),+class ExampleImageProcessorPil:+ pass+processor = SimpleNamespace(image_processor=ExampleImageProcessorPil())+pipe = SimpleNamespace(text_encoder=SimpleNamespace(encode=lambda *a: encode_result, processor=processor),_encode_keyframes=lambda *a: rows, dit=dit,_decode_video=fail_decode, _decode_audio=lambda *a: rows)report = {'timings': {}}ticks = iter([10, 13])restore = d.instrument(pipe, report, clock=lambda: next(ticks))-assert pipe.text_encoder.encode('motion', [object()]) is encode_result+assert pipe.text_encoder.encode('motion', [SimpleNamespace(size=(576, 1024))]) is encode_resultassert pipe._encode_keyframes([object()], 1024, 576) is rowsvideo = SimpleNamespace(shape=(1, 1000, 96))audio = SimpleNamespace(shape=(1, 414, 32))@@ -76,6 +79,7 @@ assert report['timings']['decode_video_seconds'] == 3assert report['vae_conditioning_shape'] == [576, 96]assert report['packed_conditioning']['position_shape'] == [1500, 3]assert report['vision_conditioning']['token_tag_counts'] == {'0': 1, '1': 2}+assert report['vision_processor'] == {'class': 'ExampleImageProcessorPil', 'input_sizes': [[576, 1024]]}print('ok')`)).toContain('ok');});diff --git a/scripts/diagnose_minimax_h3_processor.py b/scripts/diagnose_minimax_h3_processor.pynew file mode 100644index 0000000000..04ba277809--- /dev/null+++ b/scripts/diagnose_minimax_h3_processor.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""Compare H3's two Qwen2-VL image-processor backends on synthetic keyframes (#8867).++The FL2VA reference encodes keyframes with the checkpoint's torchvision+processor; the torch-free MLX runner binds its PIL twin instead. This runs both+on the same deterministic synthetic images, on the CPU, and reports token-grid,+float32 and bfloat16 agreement. It never loads a model or downloads anything.++Run it with an interpreter that has transformers (at the H3 lock's version),+torch and torchvision; see docs/research/minimax-h3-continuity.md.+"""++import argparse+import json+import os+from pathlib import Path+import sys++# A production keyframe is already on a canvas the runner validated: both axes+# multiples of 32 and, at H3's released sizes, far above the processor's+# 65,536-pixel floor. The processor must not resample those. The other cases+# show what resampling would cost if a keyframe ever reached it off-canvas.+CASES = [+ dict(id="canvas-576x1024", width=576, height=1024, production=True),+ dict(id="canvas-768x1344", width=768, height=1344, production=True),+ dict(id="canvas-1344x768", width=1344, height=768, production=True),+ dict(id="canvas-512x288", width=512, height=288, production=True),+ dict(id="raw-1080x1920", width=1080, height=1920, production=False),+ dict(id="raw-720x1280", width=720, height=1280, production=False),+ dict(id="undersized-128x256", width=128, height=256, production=False),+]+# Float32 rounding of (x/255 - 0.5)/0.5 versus the fused (x - 127.5)/127.5.+FLOAT32_TOLERANCE = 1e-6+++def synthetic_image(width, height, seed=8867):+ """Left half a smooth gradient, right half full-band noise: the resamplers' worst case."""+ import numpy as np+ from PIL import Image++ y, x = np.mgrid[0:height, 0:width]+ smooth = np.stack([x * 255 // max(width - 1, 1), y * 255 // max(height - 1, 1), (x + y) * 3 % 256], -1)+ noise = np.random.default_rng(seed).integers(0, 256, size=(height, width, 3))+ return Image.fromarray(np.where((x < width // 2)[..., None], smooth, noise).astype(np.uint8), "RGB")+++def bfloat16_bits(values):+ """Round float32 to bfloat16 (nearest, ties to even), as `.astype(bfloat16)` does."""+ import numpy as np++ bits = np.ascontiguousarray(values, dtype=np.float32).view(np.uint32).astype(np.uint64)+ return ((bits + 0x7FFF + ((bits >> 16) & 1)) >> 16).astype(np.uint16)+++def compare(case, reference, twin, patch_size):+ """One case's agreement; a production case fails on any grid or bfloat16 difference."""+ import numpy as np++ ref_values, twin_values = np.asarray(reference["pixel_values"]), np.asarray(twin["pixel_values"])+ ref_grid = np.asarray(reference["image_grid_thw"]).tolist()+ twin_grid = np.asarray(twin["image_grid_thw"]).tolist()+ _, grid_h, grid_w = ref_grid[0]+ result = {+ **case,+ "reference_grid": ref_grid,+ "twin_grid": twin_grid,+ "resampled": [grid_h * patch_size, grid_w * patch_size] != [case["height"], case["width"]],+ "shapes_match": ref_values.shape == twin_values.shape,+ }+ if result["shapes_match"] and ref_grid == twin_grid:+ difference = np.abs(ref_values.astype(np.float64) - twin_values.astype(np.float64))+ result.update(+ max_abs=float(difference.max()),+ mean_abs=float(difference.mean()),+ bfloat16_mismatch=float(np.mean(bfloat16_bits(ref_values) != bfloat16_bits(twin_values))),+ )+ result["parity"] = (+ result["shapes_match"] and ref_grid == twin_grid and not result["resampled"]+ and result["max_abs"] <= FLOAT32_TOLERANCE and result["bfloat16_mismatch"] == 0+ )+ return result+++def run(processor_dir, cases=CASES):+ config = json.loads((processor_dir / "preprocessor_config.json").read_text(encoding="utf-8"))+ declared = config["image_processor_type"]+ import transformers++ # The same derivation generate_minimax_h3.load_pil_image_processor uses.+ reference_class = getattr(transformers, declared.removesuffix("Fast"))+ twin_class = getattr(transformers, declared.removesuffix("Fast") + "Pil")+ reference = reference_class.from_pretrained(str(processor_dir))+ twin = twin_class.from_pretrained(str(processor_dir))+ results = []+ for case in cases:+ image = synthetic_image(case["width"], case["height"])+ results.append(compare(+ case,+ reference(images=[image], return_tensors="np"),+ twin(images=[image], return_tensors="np"),+ config["patch_size"],+ ))+ return {+ "transformers": transformers.__version__,+ "reference_processor": reference_class.__name__,+ "twin_processor": twin_class.__name__,+ "production_parity": all(result["parity"] for result in results if result["production"]),+ "cases": results,+ }+++def main():+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--processor-dir", required=True, type=Path,+ help="the cached checkpoint's FL2VA/processor directory")+ args = parser.parse_args()+ if not (args.processor_dir / "preprocessor_config.json").is_file():+ raise SystemExit(f"No preprocessor_config.json under {args.processor_dir}; nothing is downloaded.")+ os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1")+ report = run(args.processor_dir)+ print(json.dumps(report, indent=2))+ return 0 if report["production_parity"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/diagnose_minimax_h3_processor.test.js b/scripts/diagnose_minimax_h3_processor.test.jsnew file mode 100644index 0000000000..ccae0bb42d--- /dev/null+++ b/scripts/diagnose_minimax_h3_processor.test.js@@ -0,0 +1,122 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const python = resolveTestPython();+const hasImageStack = (() => {+ if (!python) return false;+ try {+ execFileSync(python, ['-c', 'import numpy, PIL'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();+const script = fileURLToPath(new URL('./diagnose_minimax_h3_processor.py', import.meta.url));+const run = (source) => execFileSync(python, ['-c', source, script], { encoding: 'utf8' });++// A stand-in transformers exposing the checkpoint-declared processor and its+// PIL twin. Both normalize the way the real backends do — fused+// (x - 127.5) / 127.5 versus (x / 255 - 0.5) / 0.5 — so the production cases+// differ only by float32 rounding, and "resample" any axis off the 32px grid.+const load = `+import importlib.util, json, sys, tempfile, types+from pathlib import Path+import numpy as np++class ExampleImageProcessor:+ reorder = False+ @classmethod+ def from_pretrained(cls, path):+ assert Path(path, 'preprocessor_config.json').is_file()+ return cls()+ def normalize(self, pixels):+ return (pixels - np.float32(127.5)) / np.float32(127.5)+ def __call__(self, images, return_tensors):+ assert return_tensors == 'np'+ pixels = np.asarray(images[0], dtype=np.float32)+ height, width = (max(32, round(size / 32) * 32) for size in pixels.shape[:2])+ resampled = (height, width) != pixels.shape[:2]+ pixels = np.pad(pixels, ((0, max(0, height - pixels.shape[0])), (0, max(0, width - pixels.shape[1])), (0, 0)),+ mode='edge')[:height, :width]+ values = self.normalize(pixels).reshape(-1, 16 * 16 * 3)+ if resampled:+ values = values + np.float32(self.resample_bias)+ if self.reorder:+ values = values[::-1]+ return {'pixel_values': values, 'image_grid_thw': np.array([[1, height // 16, width // 16]])}+ resample_bias = 0.0++class ExampleImageProcessorPil(ExampleImageProcessor):+ resample_bias = 1 / 127.5+ def normalize(self, pixels):+ return (pixels / np.float32(255) - np.float32(0.5)) / np.float32(0.5)++stub = types.ModuleType('transformers')+stub.__version__ = 'stub'+stub.ExampleImageProcessor, stub.ExampleImageProcessorPil = ExampleImageProcessor, ExampleImageProcessorPil+sys.modules['transformers'] = stub+spec = importlib.util.spec_from_file_location('processor_parity', sys.argv[1])+d = importlib.util.module_from_spec(spec)+spec.loader.exec_module(d)+cases = [+ dict(id='canvas', width=96, height=64, production=True),+ dict(id='raw', width=90, height=70, production=False),+]+def processor_dir(root):+ Path(root, 'preprocessor_config.json').write_text(json.dumps({+ 'image_processor_type': 'ExampleImageProcessorFast', 'patch_size': 16}))+ return Path(root)+`;++describe.skipIf(!hasImageStack)('H3 image-processor parity diagnostic', () => {+ // Catches a checker that fails on the expected off-canvas resampling gap, or+ // that treats fused-normalization rounding as divergence.+ it('passes when production canvases agree in bfloat16 and only reports off-canvas resampling', () => {+ expect(run(`${load}+with tempfile.TemporaryDirectory() as root:+ report = d.run(processor_dir(root), cases)+canvas, raw = report['cases']+assert report['production_parity'] is True, report+assert report['reference_processor'] == 'ExampleImageProcessor', report+assert report['twin_processor'] == 'ExampleImageProcessorPil', report+assert canvas['resampled'] is False and canvas['parity'] is True, canvas+assert 0 < canvas['max_abs'] <= d.FLOAT32_TOLERANCE and canvas['bfloat16_mismatch'] == 0, canvas+assert raw['resampled'] is True and raw['parity'] is False and raw['bfloat16_mismatch'] > 0, raw+print('ok')+`)).toContain('ok');+ });++ // Catches the regression the checker exists for: a twin (for example after a+ // transformers bump) that lays out patches differently on a production canvas.+ it('fails production parity and exits nonzero when the twin reorders patches', () => {+ expect(run(`${load}+ExampleImageProcessorPil.reorder = True+with tempfile.TemporaryDirectory() as root:+ report = d.run(processor_dir(root), cases)+ sys.argv = [sys.argv[0], '--processor-dir', root]+ status = d.main()+assert report['production_parity'] is False and report['cases'][0]['bfloat16_mismatch'] > 0, report+assert status == 1, status+print('ok')+`)).toContain('ok');+ });++ it('refuses a directory without a processor config instead of fetching one', () => {+ expect(run(`${load}+def forbidden(*args):+ raise AssertionError('processor loaded')+ExampleImageProcessor.from_pretrained = ExampleImageProcessorPil.from_pretrained = classmethod(forbidden)+with tempfile.TemporaryDirectory() as root:+ sys.argv = [sys.argv[0], '--processor-dir', root]+ try:+ d.main()+ except SystemExit as error:+ assert 'nothing is downloaded' in str(error), error+ else:+ raise AssertionError('missing config was accepted')+print('ok')+`)).toContain('ok');+ });+});