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
fix MiniMax H3 image-to-video, which died in the text encoder before any DiT step
[._.]/ Adam Eivyf59a7abb1651
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex b5a9ab4165..9c56cb4194 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -14,6 +14,7 @@ Each `--image` needs its own `--anchor`, in the same order.from __future__ import annotationsimport argparse+import importlib.utilimport jsonimport reimport shutil@@ -21,6 +22,7 @@ import subprocessimport sysfrom contextlib import redirect_stdoutfrom pathlib import Path+from types import SimpleNamespacesys.path.insert(0, str(Path(__file__).resolve().parent))from _runner_common import ( # noqa: E402@@ -147,6 +149,217 @@ def install_key_prefix_map(rules: list[tuple[str, str]]) -> None:MiniMaxH3TextEncoder._wanted = _wanted+def torch_image_stack_available() -> bool:+ """Whether the pinned runtime's own `AutoProcessor` path can load at all.++ transformers 5 dropped the numpy image processors: every class the auto path+ resolves is torchvision-backed, and importing one without torch raises rather+ than degrading. The MLX runtime lock deliberately ships neither+ (`requirements-minimax-h3-mlx.lock.txt`), so this is False for a stock PortOS+ install and True only if the user added torch to that venv themselves.+ """+ return all(importlib.util.find_spec(module) is not None for module in ("torch", "torchvision"))+++def load_pil_image_processor(processor_dir: Path):+ """Load the PIL-backed sibling of the image processor the checkpoint declares.++ transformers keeps a `…Pil` twin of each torchvision image processor for+ exactly the environment this runner lives in. The checkpoint names its class+ in `preprocessor_config.json` — `Qwen2VLImageProcessorFast` for H3 — and the+ `Fast` suffix is transformers-5-deprecated on the base name, so the twin is+ derived off the stripped name rather than hardcoded to one checkpoint.+ """+ config_path = processor_dir / "preprocessor_config.json"+ if not config_path.is_file():+ raise RuntimeError(f"Checkpoint processor config is missing: {config_path}")+ declared = json.loads(config_path.read_text(encoding="utf-8")).get("image_processor_type")+ if not declared:+ raise RuntimeError(f"{config_path} names no image_processor_type, so a keyframe cannot be encoded.")++ import transformers++ name = declared.removesuffix("Fast") + "Pil"+ processor_class = getattr(transformers, name, None)+ if processor_class is None:+ raise RuntimeError(+ f"transformers {transformers.__version__} exposes no {name}, the PIL-backed twin of the "+ f"checkpoint's {declared}. Install torch and torchvision into the MiniMax H3 runtime venv "+ "to condition on a keyframe with this transformers version."+ )+ return processor_class.from_pretrained(str(processor_dir))+++def install_pil_image_processor() -> None:+ """Let an image-conditioned render work in a runtime with no PyTorch.++ The pinned port reads its vision inputs from+ `AutoProcessor.from_pretrained(<checkpoint>/processor).image_processor`, and+ transformers 5's auto path builds the WHOLE Qwen3-VL processor — video+ processor included — before handing back the one sub-processor the encoder+ uses. That video processor is torchvision-backed, so with the MLX lock's+ torch-free venv every keyframed render died in `from_pretrained` with+ "Qwen3VLVideoProcessor requires the Torchvision library"; text-only renders+ never touch the property and kept working, which is why image-to-video was+ the only broken mode.++ Binding the PIL twin to the single attribute the encoder reads loads nothing+ it doesn't use and — deliberately, like the key-prefix map above — leaves the+ pinned checkout untouched, because it is verified clean before this runs.+ """+ from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder++ if not isinstance(getattr(MiniMaxH3TextEncoder, "processor", None), property):+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder.processor, so a "+ "keyframe cannot be encoded without PyTorch. Render text-only, install torch and "+ "torchvision into the runtime venv, or update PortOS for the new pin."+ )++ def processor(self):+ if self._processor is None:+ # Resolved from the encoder's own model dir rather than a captured+ # path, so a composed text-encoder shim root keeps pointing at the+ # processor it linked through.+ self._processor = SimpleNamespace(+ image_processor=load_pil_image_processor(self._model_dir.parent / "processor"),+ )+ return self._processor++ MiniMaxH3TextEncoder.processor = property(processor)+++def install_vision_weight_sanitizer() -> None:+ """Put the loaded vision tower into the layout MLX's conv3d reads.++ The pinned port loads Qwen3-VL's weights straight out of the safetensors into+ the mlx-vlm module tree, which skips the `sanitize()` mlx-vlm applies through+ its own loader. Only one tensor cares: `patch_embed.proj.weight` ships in+ torch's `(C_out, C_in, kD, kH, kW)` and MLX's conv3d wants `C_in` last, so an+ unsanitized load reaches the first keyframe as+ "[conv] Expect the input channels ... to match". Text-only renders never build+ the tower, which is why only image conditioning saw it.++ The correction is mlx-vlm's OWN `sanitize`, called on the module's loaded+ parameters rather than reimplemented here: its shape check already treats a+ correctly-laid-out tensor as a no-op, so this stays right if a later pin (or a+ later mlx-vlm) starts handing the tower a sanitized weight.+ """+ from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder++ original = getattr(MiniMaxH3TextEncoder, "_load_weights", None)+ if original is None:+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder._load_weights, "+ "so its vision tower cannot be laid out for MLX. Render text-only, or update PortOS "+ "for the new pin."+ )++ def _load_weights(self, model_dir, dtype, verbose):+ original(self, model_dir, dtype, verbose)+ sanitize_vision_weights(self.vision)++ MiniMaxH3TextEncoder._load_weights = _load_weights+++def sanitize_vision_weights(vision) -> None:+ """Run mlx-vlm's `sanitize` over an already-loaded vision module, in place."""+ if vision is None:+ return+ import mlx.core as mx+ from mlx.utils import tree_flatten, tree_unflatten++ sanitized = vision.sanitize(dict(tree_flatten(vision.parameters())))+ vision.update(tree_unflatten(list(sanitized.items())))+ mx.eval(vision.parameters())+++# The merge the pinned port performs instead of a scatter. Asserted before the+# replacement below is installed, so the day upstream fixes this the patch says+# so loudly rather than shadowing a working implementation forever.+PINNED_BROADCAST_MERGE = "mx.where(image_mask[..., None], hidden.astype(inputs_embeds.dtype)[None], inputs_embeds)"+++def install_vision_embed_merge() -> None:+ """Scatter a keyframe's vision rows into the tokens that stand for them.++ `<|image_pad|>` rows are a minority of the request — the port's own+ `build_request` wraps them in vision-start/end markers, a `<Picture N>:` label+ and then the whole prompt — but the pinned encode merges them with+ `mx.where(image_mask, hidden, inputs_embeds)`, which broadcasts and therefore+ only lines up when the sequence is nothing BUT image tokens. Any real+ prompt + keyframe pair dies in `[broadcast_shapes]` before a single DiT step.++ The replacement re-runs the pinned encode's own steps and swaps that one line+ for mlx-vlm's `merge_input_ids_with_image_features`, the scatter this is+ modelled on (it also raises when the token and feature counts disagree, which+ the broadcast could never check). A text-only request never reaches the merge,+ so it is handed straight back to the pinned implementation untouched.+ """+ import inspect++ from minimax_h3_mlx.text_encoder import MiniMaxH3TextEncoder++ original = getattr(MiniMaxH3TextEncoder, "encode", None)+ if original is None:+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer exposes MiniMaxH3TextEncoder.encode, so a "+ "keyframe cannot be merged into the prompt. Render text-only, or update PortOS for "+ "the new pin."+ )+ if PINNED_BROADCAST_MERGE not in inspect.getsource(original):+ raise RuntimeError(+ "The pinned MiniMax H3 runtime no longer merges keyframe embeddings the way PortOS "+ "corrects for; re-check the pin before rendering with a keyframe."+ )++ def encode(self, prompt: str, images: list | None = None):+ # A text-only request never reaches the merge, so it goes back to the+ # pinned implementation before this even imports what the fix needs.+ if not images:+ return original(self, prompt, images)++ import mlx.core as mx+ import numpy as np+ from mlx_vlm.models.qwen3_vl.language import LanguageModel+ from mlx_vlm.models.qwen3_vl.qwen3_vl import Model++ if self.vision is None:+ raise ValueError("This encoder was built with `load_vision=False`; it cannot take images.")++ input_ids, token_tags, vision_inputs = self.build_request(prompt, images)+ pixel_values, grid_np = vision_inputs+ grid_thw = mx.array(grid_np.astype(np.int32))+ hidden, deepstack_embeds = self.vision(+ mx.array(pixel_values).astype(self.dtype), grid_thw, output_hidden_states=True+ )+ inputs_embeds = self.language.embed_tokens(input_ids)+ # H3 emits no `<|video_pad|>`: its keyframes are image tokens that the DiT+ # layout later tags as video rows, so both token ids the merge ORs over are+ # the image one.+ inputs_embeds, image_mask = Model.merge_input_ids_with_image_features(+ hidden.astype(inputs_embeds.dtype),+ inputs_embeds,+ input_ids,+ self.image_token_id,+ self.image_token_id,+ )+ position_ids, _ = LanguageModel.get_rope_index(+ self, input_ids, image_grid_thw=grid_thw, video_grid_thw=None, attention_mask=None+ )+ hidden_states = self._hidden_states(+ input_ids,+ position_ids,+ inputs_embeds=inputs_embeds,+ visual_pos_masks=image_mask[..., 0],+ deepstack_visual_embeds=deepstack_embeds,+ )+ mx.eval(hidden_states)+ return hidden_states, token_tags++ MiniMaxH3TextEncoder.encode = encode++def write_final_norm_shard(path: Path, key: str, hidden_size: int) -> None:"""Write the one tensor a norm-less conditioner is missing.@@ -358,6 +571,15 @@ def main() -> int:from minimax_h3_mlx.media import save_mp4from minimax_h3_mlx.pipeline import MiniMaxH3Pipeline+ # The three keyframe-path corrections, installed before the pipeline is built+ # so the encoder is already patched when it loads and first reads a keyframe.+ # Only an image-conditioned render needs them, and only it ever hit the bugs.+ if images:+ install_vision_weight_sanitizer()+ install_vision_embed_merge()+ if not torch_image_stack_available():+ install_pil_image_processor()+# Substituted prompt conditioner. H3 reads the unnormalized hidden state# after Qwen3-VL language layer 49, so any checkpoint carrying the same# embedding + layers 0-49 + vision tower conditions the DiT identically indiff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsindex d45fe9396d..a2515eef70 100644--- a/scripts/generate_minimax_h3.test.js+++ b/scripts/generate_minimax_h3.test.js@@ -498,4 +498,246 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {].join('\n')}`);expect(output.trim()).toBe('10');});++ // Keyframe conditioning is the one path with no torch under it: the MLX lock+ // ships neither torch nor torchvision, and transformers 5 routes every auto+ // image-processor load through them. Text-only renders never touch it, which+ // is why image-to-video was the only mode that failed.+ it('reads the runtime for the torch stack the auto processor needs', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json',+ 'present = {"torch": object(), "torchvision": object(), "numpy": object()}',+ 'def fake_find_spec(name):',+ ' return present.get(name)',+ 'runner.importlib.util.find_spec = fake_find_spec',+ 'both = runner.torch_image_stack_available()',+ 'present.pop("torchvision")',+ 'vision_only = runner.torch_image_stack_available()',+ 'present.pop("torch")',+ 'neither = runner.torch_image_stack_available()',+ 'print(json.dumps([both, vision_only, neither]))',+ ].join('\n')}`);+ // torch alone is not enough: it is the torchvision-backed video processor+ // that `AutoProcessor.from_pretrained` builds and dies on.+ expect(JSON.parse(output)).toEqual([true, false, false]);+ });++ it('loads the PIL twin of the image processor the checkpoint declares', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, sys, tempfile, types',+ 'loaded = {}',+ 'class FakePil:',+ ' @classmethod',+ ' def from_pretrained(cls, path):',+ ' loaded["path"] = path',+ ' return "pil-image-processor"',+ 'transformers = types.ModuleType("transformers")',+ 'transformers.__version__ = "5.14.1"',+ 'transformers.Qwen2VLImageProcessorPil = FakePil',+ 'sys.modules["transformers"] = transformers',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' processor = Path(temp) / "processor"',+ ' processor.mkdir()',+ // The checkpoint names the torchvision class; the twin is derived off the+ // `Fast`-stripped base name rather than hardcoded to one checkpoint.+ ' (processor / "preprocessor_config.json").write_text(json.dumps({"image_processor_type": "Qwen2VLImageProcessorFast"}))',+ ' result = runner.load_pil_image_processor(processor)',+ ' print(json.dumps({"result": result, "path": loaded["path"] == str(processor)}))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual({ result: 'pil-image-processor', path: true });+ });++ it.each([+ ['{}', /names no image_processor_type/],+ ['{"image_processor_type": "InventedImageProcessor"}', /exposes no InventedImageProcessorPil/],+ ])('refuses a processor config it cannot resolve a PIL twin from (%s)', (config, expected) => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, tempfile, types',+ 'transformers = types.ModuleType("transformers")',+ 'transformers.__version__ = "5.14.1"',+ 'sys.modules["transformers"] = transformers',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' processor = Path(temp) / "processor"',+ ' processor.mkdir()',+ ` (processor / "preprocessor_config.json").write_text(${JSON.stringify(config)})`,+ ' try:',+ ' runner.load_pil_image_processor(processor)',+ ' except RuntimeError as exc:',+ ' print(str(exc))',+ ' else:',+ ' raise SystemExit("an unresolvable processor config was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(expected);+ });++ // The encoder reads exactly one thing off its processor, so the twin is bound+ // to that one attribute: building the rest is what pulls in the video+ // processor nothing here uses.+ it('binds the PIL twin to the only sub-processor the pinned encoder reads', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, sys, types',+ 'class FakeEncoder:',+ ' def __init__(self, model_dir):',+ ' self._model_dir = Path(model_dir)',+ ' self._processor = None',+ ' @property',+ ' def processor(self):',+ ' raise AssertionError("the pinned auto-processor property must not run")',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = FakeEncoder',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'seen = []',+ 'runner.load_pil_image_processor = lambda directory: seen.append(directory) or "pil-image-processor"',+ 'runner.install_pil_image_processor()',+ 'encoder = FakeEncoder("/checkpoint/text_encoder")',+ 'first = encoder.processor',+ 'print(json.dumps({',+ ' "image_processor": first.image_processor,',+ ' "cached": encoder.processor is first,',+ ' "loads": [str(p) for p in seen],',+ '}))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ expect(result.image_processor).toBe('pil-image-processor');+ // One load per encoder — the pinned property memoizes on `_processor` and+ // the twin has to keep doing that or every keyframe re-reads the config.+ expect(result.cached).toBe(true);+ // Resolved off the encoder's own model dir, so a composed text-encoder shim+ // root keeps pointing at the processor it linked through.+ expect(result.loads).toEqual([join('/checkpoint', 'processor')]);+ });++ it('refuses to bind a twin onto a pin with no processor property', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, types',+ 'class Bare: pass',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = Bare',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'try:',+ ' runner.install_pil_image_processor()',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("a pin with no processor property was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\.processor/);+ });++ // mlx-vlm's loader sanitizes `patch_embed.proj.weight` into MLX's conv layout;+ // the pinned port loads the safetensors itself and skips it, so the tower gets+ // torch's `(C_out, C_in, kD, kH, kW)` and conv3d rejects the first keyframe.+ it('sanitizes the vision tower after the pinned load, not instead of it', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, sys, types',+ 'order = []',+ 'class FakeEncoder:',+ ' def _load_weights(self, model_dir, dtype, verbose):',+ ' order.append(("pinned load", str(model_dir), str(dtype), verbose))',+ ' self.vision = "vision-tower"',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = FakeEncoder',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'runner.sanitize_vision_weights = lambda vision: order.append(("sanitize", vision))',+ 'runner.install_vision_weight_sanitizer()',+ 'FakeEncoder()._load_weights(Path("/checkpoint/text_encoder"), "bfloat16", False)',+ 'print(json.dumps(order))',+ ].join('\n')}`);+ // The pinned load runs first and unchanged — the correction is applied to+ // what it produced, so a pin that starts loading a sanitized weight keeps+ // working (mlx-vlm's own shape check makes the second pass a no-op).+ expect(JSON.parse(output)).toEqual([+ ['pinned load', join('/checkpoint', 'text_encoder'), 'bfloat16', false],+ ['sanitize', 'vision-tower'],+ ]);+ });++ it('refuses to sanitize a pin with no _load_weights hook', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, types',+ 'class Bare: pass',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = Bare',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'try:',+ ' runner.install_vision_weight_sanitizer()',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("a pin with no _load_weights hook was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\._load_weights/);+ });++ it('leaves the vision tower alone when the encoder built none', () => {+ const output = runPython(`${importRunner}\n${[+ 'runner.sanitize_vision_weights(None)',+ 'print("ok")',+ ].join('\n')}`);+ // Reached on a text-only encoder (`load_vision=False`); importing mlx to+ // sanitize nothing would cost a load the run does not need.+ expect(output.trim()).toBe('ok');+ });++ // The pinned encode merges the keyframe's vision rows with a BROADCAST, which+ // only lines up when the request is nothing but image tokens — every real+ // prompt + keyframe pair dies in `[broadcast_shapes]`. The correction is+ // asserted against the pin so it retires itself if upstream ever fixes it.+ it.each([+ ['inputs_embeds = mx.where(image_mask[..., None], hidden.astype(inputs_embeds.dtype)[None], inputs_embeds)', null],+ ['inputs_embeds = merge(image_mask, hidden, inputs_embeds)', /no longer merges keyframe embeddings/],+ ])('installs the scatter only over a pin that still merges by broadcast (%s)', (merge, expected) => {+ const output = runPython(`${importRunner}\n${[+ 'import importlib.util, sys, tempfile, types',+ 'with tempfile.TemporaryDirectory() as temp:',+ // inspect.getsource needs a real file, so the stand-in pin is written out+ // and imported rather than declared inline.+ ' pin = Path(temp) / "pinned_text_encoder.py"',+ ' pin.write_text("\\n".join([',+ ' "class MiniMaxH3TextEncoder:",',+ ' " def encode(self, prompt, images=None):",',+ // Carried as a comment: the stand-in only has to look like the pin to+ // `inspect.getsource`, not run its body.+ ` " # ${merge}",`,+ ' " return (\'pinned\', prompt, images)",',+ ' ]))',+ ' spec = importlib.util.spec_from_file_location("minimax_h3_mlx.text_encoder", pin)',+ ' module = importlib.util.module_from_spec(spec)',+ ' sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ ' sys.modules["minimax_h3_mlx.text_encoder"] = module',+ ' spec.loader.exec_module(module)',+ ' try:',+ ' runner.install_vision_embed_merge()',+ ' except RuntimeError as exc:',+ ' print("REFUSED", str(exc))',+ ' else:',+ // A text-only request has no merge to correct, so it must come back from+ // the pinned implementation untouched.+ ' print("INSTALLED", module.MiniMaxH3TextEncoder().encode("a prompt"))',+ ].join('\n')}`);+ if (expected) expect(output).toMatch(expected);+ else expect(output.trim()).toBe("INSTALLED ('pinned', 'a prompt', None)");+ });++ it('refuses to correct a pin with no encode hook', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, types',+ 'class Bare: pass',+ 'module = types.ModuleType("minimax_h3_mlx.text_encoder")',+ 'module.MiniMaxH3TextEncoder = Bare',+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',+ 'sys.modules["minimax_h3_mlx.text_encoder"] = module',+ 'try:',+ ' runner.install_vision_embed_merge()',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("a pin with no encode hook was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/no longer exposes MiniMaxH3TextEncoder\.encode/);+ });});