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
feat: apply MiniMax H3 LoRAs on quantized MLX runtime
[._.]/ Adam Eivyb6672921af58
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex a8fd156088..7d205b1c45 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -510,8 +510,8 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled, r// model's runtime would use, silently hiding it reads as a bug — say why, and// say the right why. The two cases need different advice, so the hint carries// its own copy: a quantized mlx_video LTX-2.x model is fixed by switching- // models, while H3 is blocked by its pinned runner and switching models is- // wrong advice. `null` when there is nothing useful to explain.+ // models, while H3 is blocked by its installed runtime plus adapter probe and+ // switching models is wrong advice. `null` when there is nothing useful to explain.const loraUnavailableHint = useMemo(() => {if (loraFamily) return null;const ltxCount = installedVideoLorasByFamily.get(VIDEO_LORA_FAMILIES.LTX_VIDEO) || 0;diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex e862ce1fd6..b205ad0dc2 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -1313,7 +1313,7 @@ export default function VideoGen() {{loraUnavailableHint.kind === 'ltx' ? (<>You have {loraUnavailableHint.count} LTX video LoRA{loraUnavailableHint.count === 1 ? '' : 's'} installed, but <strong className="font-semibold">{currentModel?.name}</strong> can't fuse LoRAs (its quantized <code>mlx_video</code> runtime isn't supported yet). Switch to the <strong className="font-semibold">LTX-2.3 Unified Beta</strong> (bf16) or an <strong className="font-semibold">LTX-2.3 dgrauet (Q4/Q8)</strong> model to use them.</>) : (- <>You have {loraUnavailableHint.count} MiniMax H3 LoRA{loraUnavailableHint.count === 1 ? '' : 's'} installed, but the installed H3 runtime can't apply them — its DiT is quantized, so LoRAs need a runner that applies them at render time from quantization metadata. Upgrade the <strong className="font-semibold">MiniMax H3</strong> runtime from the model setup panel once a build that supports it is pinned.</>+ <>You have {loraUnavailableHint.count} MiniMax H3 LoRA{loraUnavailableHint.count === 1 ? '' : 's'} installed, but this H3 runtime did not pass PortOS's quantization-aware LoRA probe. Repair the <strong className="font-semibold">MiniMax H3</strong> runtime from the model setup panel, then retry.</>)}</div>)}diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex 36a655532c..e6315d65c2 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -661,14 +661,14 @@ def main() -> int:# applicator has to take each layer's logical dims from the quantization# metadata (packed-uint32 storage shapes match no LoRA) and add the deltas# during the forward pass. PortOS only ever passes --lora when its capability- # probe has already confirmed this module exists, so an ImportError here is a- # real contract violation and should surface, not be swallowed.+ # probe has already exercised this local applicator, so an import or shape+ # error here is a real contract violation and should surface, not be swallowed.if args.lora:print("STAGE:apply-loras", file=sys.stderr, flush=True)- from minimax_h3_mlx.lora import apply_loras+ from minimax_h3_lora import apply_lorasapply_loras(- pipe.transformer,+ pipe.dit,[{"path": p, "scale": s} for p, s in zip(args.lora, args.lora_scale)],)diff --git a/scripts/minimax_h3_lora.py b/scripts/minimax_h3_lora.pynew file mode 100644index 0000000000..6e8b4cee46--- /dev/null+++ b/scripts/minimax_h3_lora.py@@ -0,0 +1,386 @@+#!/usr/bin/env python3+"""Apply LoRAs to the MiniMax H3 MLX DiT without rewriting quantized weights.++MiniMax H3's main DiT linears are stored as MLX packed ``uint32`` weights. A+normal LoRA merge cannot use those storage shapes, and replacing the packed+weights would also discard the quantization metadata that MLX needs to run+them. This adapter keeps each base module intact and adds the low-rank delta+to its activation output instead:++ quantized_linear(x) + (x @ lora_down.T) @ lora_up.T * scale++The adapter is deliberately local to PortOS rather than imported from the+runtime checkout. The source checkout is pinned for the H3 model itself; this+small integration layer owns the LoRA file-format and quantization contract.+"""++from __future__ import annotations++import math+from pathlib import Path+from typing import Any++import mlx.core as mx+import mlx.nn as nn+++_QKV_TARGET_SUFFIX = ".attn.qkv_proj"+_QKV_STORAGE_HINTS = ("contiguous", "turbo")+_QKV_NATIVE_HINTS = ("native", "interleaved")+_DIFFUSERS_H3_DEFAULT_ALPHA = 8.0++# Common safetensors exports use one of these suffix pairs. Keeping the parser+# here format-focused means target names can be normalized independently.+_LORA_SUFFIXES = (+ (".lora_A.default.weight", "down"),+ (".lora_B.default.weight", "up"),+ (".lora_A.default", "down"),+ (".lora_B.default", "up"),+ (".lora_A.weight", "down"),+ (".lora_B.weight", "up"),+ (".lora_down.weight", "down"),+ (".lora_up.weight", "up"),+ (".lora_A", "down"),+ (".lora_B", "up"),+ (".lora_down", "down"),+ (".lora_up", "up"),+ (".lora_alpha", "alpha"),+ (".alpha", "alpha"),+)+++class _LoRAProjection(nn.Module):+ """One low-rank activation-space projection."""++ def __init__(self, down: mx.array, up: mx.array, scale: float):+ super().__init__()+ self.down = down+ self.up = up+ self.scale = float(scale)++ def __call__(self, value: mx.array) -> mx.array:+ # Match the adapter's own precision for the matrix products. The base+ # quantized projection remains responsible for its own scales/biases;+ # this only prevents MLX from promoting a low-rank delta unexpectedly.+ delta = value.astype(self.down.dtype) @ self.down.T+ delta = delta @ self.up.T+ return delta.astype(self.up.dtype) * self.scale+++class LoRALinear(nn.Module):+ """A base linear plus one or more runtime LoRA deltas.++ Attribute forwarding is intentional. H3's AdaLN cache builder and its+ memory-saving ``drop_adaln_weights`` helper inspect ``weight``, ``scales``+ and ``biases`` on the projection. Forwarding those attributes to the base+ lets a wrapped AdaLN projection participate in the cache and still release+ its large base arrays afterward.+ """++ def __init__(self, base: nn.Module, adapters: list[_LoRAProjection]):+ super().__init__()+ self.base = base+ self.adapters = adapters++ def __getattr__(self, name: str) -> Any:+ try:+ return super().__getattr__(name)+ except AttributeError:+ base = self.get("base")+ if base is not None:+ return getattr(base, name)+ raise++ def __delattr__(self, name: str) -> None:+ # Parameters stored on this wrapper are normal Module entries. Missing+ # projection attributes belong to the wrapped base and must be deleted+ # there so H3's post-cache memory release keeps working.+ if name in self:+ super().__delattr__(name)+ return+ base = self.get("base")+ if base is not None and hasattr(base, name):+ delattr(base, name)+ return+ super().__delattr__(name)++ def add_adapter(self, adapter: _LoRAProjection) -> None:+ self.adapters = [*self.adapters, adapter]++ def __call__(self, value: mx.array) -> mx.array:+ output = self.base(value)+ for adapter in self.adapters:+ output = output + adapter(value).astype(output.dtype)+ return output+++def _normalize_target(target: str) -> tuple[str, str]:+ """Map common diffusers/ComfyUI H3 prefixes to PortOS's DiT tree."""+ prefixes = (+ "base_model.model.",+ "model.diffusion_model.",+ "diffusion_model.",+ "transformer.",+ "model.",+ )+ for prefix in prefixes:+ if target.startswith(prefix):+ target = target[len(prefix):]+ break+ if target.startswith("transformer_blocks."):+ target = "blocks." + target[len("transformer_blocks."):]+ if target.startswith("token_refiner.refiner_blocks."):+ target = "token_refiner.blocks." + target[len("token_refiner.refiner_blocks."):]+ target = target.replace(".attention.", ".attn.")+ if target.endswith(".attn.to_q"):+ return target[:-len(".attn.to_q")] + ".attn.qkv_proj", "split_q"+ if target.endswith(".attn.to_k"):+ return target[:-len(".attn.to_k")] + ".attn.qkv_proj", "split_k"+ if target.endswith(".attn.to_v"):+ return target[:-len(".attn.to_v")] + ".attn.qkv_proj", "split_v"+ if target.endswith(".attn.to_out.0"):+ return target[:-len(".attn.to_out.0")] + ".attn.out_proj", "diffusers"+ if target.endswith(".ff.net.0.proj"):+ return target[:-len(".ff.net.0.proj")] + ".mlp.fc1", "diffusers_fc1"+ if target.endswith(".ff.net.2"):+ return target[:-len(".ff.net.2")] + ".mlp.fc2", "diffusers"+ if target == "norm_out.linear":+ return "final_layer.adaln_proj.linear", "diffusers"+ if target.endswith(".to_qkv"):+ return target[:-len(".to_qkv")] + ".qkv_proj", "contiguous_qkv"+ return target, "reference"+++def _parse_tensor_key(key: str) -> tuple[str, str, str] | None:+ for suffix, kind in _LORA_SUFFIXES:+ if key.endswith(suffix):+ target = key[:-len(suffix)]+ target, source_layout = _normalize_target(target)+ return target, kind, source_layout+ return None+++def _logical_shape(module: nn.Module) -> tuple[int, int]:+ """Return ``(output_dims, input_dims)`` including packed quantized dims."""+ weight = getattr(module, "weight", None)+ if weight is None or len(weight.shape) != 2:+ raise ValueError(f"LoRA target {type(module).__name__} has no rank-2 weight.")+ output_dims, stored_input_dims = (int(value) for value in weight.shape)++ # Newer MLX versions expose the logical dimensions directly. The pinned+ # MLX 0.32 QuantizedLinear does not, so recover the input width from its+ # packed uint32 storage and quantization bit width.+ input_dims = getattr(module, "input_dims", None)+ output_dims_attr = getattr(module, "output_dims", None)+ if input_dims is not None and output_dims_attr is not None:+ return int(output_dims_attr), int(input_dims)+ if weight.dtype == mx.uint32:+ bits = int(getattr(module, "bits", 0) or 0)+ if bits <= 0 or 32 % bits:+ raise ValueError(f"LoRA target {type(module).__name__} has unknown quantization bits.")+ return output_dims, stored_input_dims * 32 // bits+ return output_dims, stored_input_dims+++def _target_module(root: nn.Module, target: str) -> tuple[nn.Module, str, nn.Module]:+ parts = target.split(".")+ if not parts or any(not part for part in parts):+ raise ValueError(f"Invalid MiniMax H3 LoRA target {target!r}.")+ parent: Any = root+ for part in parts[:-1]:+ try:+ parent = parent[int(part)] if part.isdigit() else getattr(parent, part)+ except (AttributeError, IndexError, KeyError, TypeError) as error:+ raise ValueError(f"MiniMax H3 LoRA target {target!r} is not present in the DiT.") from error+ leaf = parts[-1]+ try:+ module = parent[int(leaf)] if leaf.isdigit() else getattr(parent, leaf)+ except (AttributeError, IndexError, KeyError, TypeError) as error:+ raise ValueError(f"MiniMax H3 LoRA target {target!r} is not present in the DiT.") from error+ if not callable(module):+ raise ValueError(f"MiniMax H3 LoRA target {target!r} is not callable.")+ return parent, leaf, module+++def _transpose_if_needed(value: mx.array, expected: tuple[int, int], label: str) -> mx.array:+ if len(value.shape) != 2:+ raise ValueError(f"MiniMax H3 LoRA {label} must be rank 2, got {value.shape}.")+ if tuple(int(item) for item in value.shape) == expected:+ return value+ transposed = tuple(reversed(int(item) for item in value.shape))+ if transposed == expected:+ return value.T+ raise ValueError(f"MiniMax H3 LoRA {label} shape {value.shape} does not match {expected}.")+++def _prepare_down(value: mx.array, input_dims: int) -> mx.array:+ if len(value.shape) != 2:+ raise ValueError(f"MiniMax H3 LoRA lora_down must be rank 2, got {value.shape}.")+ shape = tuple(int(item) for item in value.shape)+ if shape[1] == input_dims:+ return value+ if shape[0] == input_dims:+ return value.T+ raise ValueError(+ f"MiniMax H3 LoRA lora_down shape {value.shape} does not match input width {input_dims}."+ )+++def _qkv_layout(path: Path, source_layout: str) -> str:+ if source_layout in ("split_q", "split_k", "split_v", "contiguous_qkv", "native_interleaved"):+ return source_layout+ name = path.name.lower()+ if any(hint in name for hint in _QKV_NATIVE_HINTS):+ return "native_interleaved"+ if any(hint in name for hint in _QKV_STORAGE_HINTS):+ return "contiguous_qkv"+ # Public H3 reference-tree exports use [q_all; k_all; v_all] rows. The+ # MLX port's raw qkv_proj is per-head interleaved, so treat an unannotated+ # H3 export as reference layout; native MLX exports can opt out by naming+ # the file native/interleaved.+ return "contiguous_qkv"+++def _prepare_up(+ path: Path,+ target: str,+ parent: nn.Module,+ module: nn.Module,+ up: mx.array,+ output_dims: int,+ rank: int,+ source_layout: str,+) -> mx.array:+ qkv_target = target.endswith(_QKV_TARGET_SUFFIX)+ expected_output_dims = output_dims+ if qkv_target and source_layout in ("split_q", "split_k", "split_v"):+ expected_output_dims //= 3+ up = _transpose_if_needed(up, (expected_output_dims, rank), "lora_up")+ if not qkv_target:+ if source_layout == "diffusers_fc1":+ half = output_dims // 2+ if output_dims % 2:+ raise ValueError(f"MiniMax H3 LoRA target {target!r} has an odd fc1 width.")+ return mx.concatenate([up[half:], up[:half]], axis=0)+ return up+ layout = _qkv_layout(path, source_layout)+ heads = int(getattr(parent, "heads", 0) or 0)+ head_dim = int(getattr(parent, "head_dim", 0) or 0)+ if heads <= 0 or head_dim <= 0 or heads * head_dim * 3 != output_dims:+ raise ValueError(+ f"MiniMax H3 LoRA target {target!r} cannot infer its interleaved QKV layout "+ f"from {type(module).__name__}."+ )+ if layout == "native_interleaved":+ return up+ if layout == "contiguous_qkv":+ return up.reshape(3, heads, head_dim, rank).transpose(1, 0, 2, 3).reshape(output_dims, rank)+ if layout in ("split_q", "split_k", "split_v"):+ selected = up.reshape(heads, head_dim, rank)+ zeros = mx.zeros_like(selected)+ parts = {+ "split_q": (selected, zeros, zeros),+ "split_k": (zeros, selected, zeros),+ "split_v": (zeros, zeros, selected),+ }[layout]+ return mx.stack(parts, axis=2).transpose(0, 2, 1, 3).reshape(output_dims, rank)+ raise ValueError(f"MiniMax H3 LoRA target {target!r} has unknown QKV layout {layout!r}.")+++def _scalar(value: mx.array, target: str) -> float:+ if value.size != 1:+ raise ValueError(f"MiniMax H3 LoRA alpha for {target!r} must be scalar, got {value.shape}.")+ return float(value.item())+++def _adapter_for(+ path: Path,+ target: str,+ tensors: dict[str, Any],+ parent: nn.Module,+ module: nn.Module,+ external_scale: float,+ source_layout: str,+) -> _LoRAProjection:+ if "down" not in tensors or "up" not in tensors:+ raise ValueError(f"MiniMax H3 LoRA target {target!r} needs both down and up tensors.")+ output_dims, input_dims = _logical_shape(module)+ down = _prepare_down(tensors["down"], input_dims)+ rank = int(down.shape[0])+ if rank <= 0:+ raise ValueError(f"MiniMax H3 LoRA rank for {target!r} must be positive.")+ up = _prepare_up(path, target, parent, module, tensors["up"], output_dims, rank, source_layout)+ if int(up.shape[1]) != rank:+ raise ValueError(f"MiniMax H3 LoRA up rank for {target!r} does not match down rank {rank}.")+ if "alpha" in tensors:+ alpha = _scalar(tensors["alpha"], target)+ elif source_layout.startswith("diffusers") or source_layout.startswith("split_"):+ # LightX2V's published H3 PEFT files use alpha=8 but omit an alpha+ # tensor; their `.default` suffix identifies that Diffusers format.+ alpha = _DIFFUSERS_H3_DEFAULT_ALPHA+ else:+ alpha = float(rank)+ scale = external_scale * alpha / rank+ if not math.isfinite(scale):+ raise ValueError(f"MiniMax H3 LoRA scale for {target!r} must be finite.")+ return _LoRAProjection(down, up, scale)+++def apply_lora(transformer: nn.Module, path: str | Path, scale: float = 1.0) -> None:+ """Load and attach one MiniMax H3 LoRA to a DiT in place."""+ adapter_path = Path(path)+ if not adapter_path.is_file():+ raise ValueError(f"MiniMax H3 LoRA file does not exist: {adapter_path.name}")+ external_scale = float(scale)+ if not math.isfinite(external_scale):+ raise ValueError(f"MiniMax H3 LoRA scale must be finite: {scale!r}")++ groups: dict[tuple[str, str], dict[str, Any]] = {}+ unrecognized: list[str] = []+ for key, value in mx.load(str(adapter_path)).items():+ parsed = _parse_tensor_key(key)+ if parsed is None:+ unrecognized.append(key)+ continue+ target, kind, source_layout = parsed+ group = groups.setdefault((target, source_layout), {})+ if kind in group:+ raise ValueError(f"MiniMax H3 LoRA target {target!r} has duplicate {kind} tensors.")+ group[kind] = value+ if unrecognized:+ names = ", ".join(unrecognized[:3])+ suffix = "..." if len(unrecognized) > 3 else ""+ raise ValueError(f"MiniMax H3 LoRA has unsupported tensor keys: {names}{suffix}")+ if not groups:+ raise ValueError(f"MiniMax H3 LoRA contains no recognized adapter tensors: {adapter_path.name}")++ # Resolve and validate every target before replacing any module. A malformed+ # multi-target file therefore cannot leave a half-attached adapter behind.+ planned: list[tuple[nn.Module, str, _LoRAProjection]] = []+ for target, source_layout in sorted(groups):+ parent, leaf, module = _target_module(transformer, target)+ adapter = _adapter_for(+ adapter_path,+ target,+ groups[(target, source_layout)],+ parent,+ module,+ external_scale,+ source_layout,+ )+ planned.append((parent, leaf, adapter))++ for parent, leaf, adapter in planned:+ current = parent[int(leaf)] if leaf.isdigit() else getattr(parent, leaf)+ if isinstance(current, LoRALinear):+ current.add_adapter(adapter)+ else:+ setattr(parent, leaf, LoRALinear(current, [adapter]))+++def apply_loras(transformer: nn.Module, loras: list[dict[str, Any]]) -> None:+ """Attach the ordered ``[{path, scale}]`` adapters used by the H3 runner."""+ for spec in loras:+ if not isinstance(spec, dict) or not spec.get("path"):+ raise ValueError("Each MiniMax H3 LoRA must provide a path.")+ apply_lora(transformer, spec["path"], spec.get("scale", 1.0))diff --git a/scripts/minimax_h3_lora.test.js b/scripts/minimax_h3_lora.test.jsnew file mode 100644index 0000000000..f3c0d8de2d--- /dev/null+++ b/scripts/minimax_h3_lora.test.js@@ -0,0 +1,150 @@+import { execFileSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const here = dirname(fileURLToPath(import.meta.url));+const script = join(here, 'minimax_h3_lora.py');+const loraProbe = join(here, 'minimax_h3_lora_probe.py');+const runtimeDir = join(homedir(), '.portos', 'minimax-h3-mlx');+const hasPinnedRuntime = existsSync(join(runtimeDir, 'minimax_h3_mlx', 'pipeline.py'));+const candidates = [+ join(homedir(), '.portos', 'minimax-h3-mlx', '.venv', 'bin', 'python3'),+ resolveTestPython(),+].filter((candidate, index, all) => candidate && all.indexOf(candidate) === index && existsSync(candidate));+const pyBin = candidates.find((candidate) => {+ try {+ execFileSync(candidate, ['-c', 'import mlx.core'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+}) || null;++const runPython = (lines) => execFileSync(pyBin, ['-c', [+ 'import sys',+ 'from pathlib import Path',+ 'sys.path.insert(0, str(Path(sys.argv[1]).parent))',+ ...lines,+].join('\n'), script], { encoding: 'utf8' });++describe.skipIf(!pyBin)('minimax_h3_lora.py', () => {+ it.skipIf(!hasPinnedRuntime)('capability-probes the installed quantized H3 runtime', () => {+ expect(execFileSync(pyBin, [loraProbe, runtimeDir], { encoding: 'utf8' })).toBe('');+ });++ it('adds an activation-space delta after a packed uint32 projection', () => {+ const output = runPython([+ 'import mlx.core as mx, mlx.nn as nn, tempfile',+ 'from minimax_h3_lora import LoRALinear, apply_loras',+ 'class Attention(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.heads = 2; self.head_dim = 4; self.qkv_proj = nn.Linear(32, 24, bias=False)',+ 'class Block(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.attn = Attention()',+ 'class DiT(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.blocks = [Block()]',+ 'model = DiT()',+ 'nn.quantize(model, group_size=32, bits=8, class_predicate=lambda path, module: path.endswith("qkv_proj"))',+ 'x = mx.arange(32, dtype=mx.float32).reshape(1, 1, 32) / 32',+ 'before = model.blocks[0].attn.qkv_proj(x); mx.eval(before)',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' path = Path(temp) / "adapter_native.safetensors"',+ ' down = mx.arange(32, dtype=mx.float32).reshape(1, 32) / 32',+ ' up = mx.arange(24, dtype=mx.float32).reshape(24, 1) / 24',+ ' mx.save_safetensors(str(path), {"blocks.0.attn.qkv_proj.lora_A.weight": down, "blocks.0.attn.qkv_proj.lora_B.weight": up, "blocks.0.attn.qkv_proj.alpha": mx.array([1.0])})',+ ' apply_loras(model, [{"path": str(path), "scale": 0.5}])',+ ' after = model.blocks[0].attn.qkv_proj(x)',+ ' expected = before + ((x @ down.T) @ up.T) * 0.5',+ ' mx.eval(after, expected)',+ ' error = float(mx.max(mx.abs(after - expected)))',+ ' if error >= 1e-5: raise AssertionError(f"delta mismatch: {error}")',+ ' if not isinstance(model.blocks[0].attn.qkv_proj, LoRALinear): raise AssertionError("projection was not wrapped")',+ 'print("ok")',+ ]);+ expect(output.trim()).toBe('ok');+ });++ it('normalizes H3 prefixes and converts reference-layout QKV rows', () => {+ const output = runPython([+ 'import mlx.core as mx, mlx.nn as nn, tempfile',+ 'from minimax_h3_lora import apply_loras',+ 'class Attention(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.heads = 2; self.head_dim = 4; self.qkv_proj = nn.Linear(32, 24, bias=False)',+ 'class Block(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.attn = Attention()',+ 'class DiT(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.blocks = [Block()]',+ 'model = DiT()',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' path = Path(temp) / "wushu_spatial_physics_pruned.safetensors"',+ ' down = mx.zeros((1, 32))',+ ' up = mx.arange(24, dtype=mx.float32).reshape(24, 1)',+ ' mx.save_safetensors(str(path), {"model.diffusion_model.transformer_blocks.0.attention.to_qkv.lora_A.weight": down, "model.diffusion_model.transformer_blocks.0.attention.to_qkv.lora_B.weight": up})',+ ' apply_loras(model, [{"path": str(path), "scale": 1.0}])',+ ' attached = model.blocks[0].attn.qkv_proj.adapters[0].up',+ ' expected = up.reshape(3, 2, 4, 1).transpose(1, 0, 2, 3).reshape(24, 1)',+ ' mx.eval(attached, expected)',+ ' if not bool(mx.all(attached == expected)): raise AssertionError("QKV rows were not converted")',+ 'print("ok")',+ ]);+ expect(output.trim()).toBe('ok');+ });++ it('maps Diffusers split-QKV and gated-MLP exports onto the MLX tree', () => {+ const output = runPython([+ 'import mlx.core as mx, mlx.nn as nn, tempfile',+ 'from minimax_h3_lora import apply_loras',+ 'class Attention(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.heads = 2; self.head_dim = 4; self.qkv_proj = nn.Linear(32, 24, bias=False)',+ 'class Mlp(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.fc1 = nn.Linear(32, 16, bias=False)',+ 'class Block(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.attn = Attention(); self.mlp = Mlp()',+ 'class DiT(nn.Module):',+ ' def __init__(self):',+ ' super().__init__(); self.blocks = [Block()]',+ 'model = DiT()',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' path = Path(temp) / "lightx2v-turbo.safetensors"',+ ' down = mx.zeros((1, 32))',+ ' q = mx.arange(8, dtype=mx.float32).reshape(8, 1)',+ ' k = mx.ones((8, 1))',+ ' v = mx.ones((8, 1)) * 2',+ ' mlp_up = mx.arange(16, dtype=mx.float32).reshape(16, 1)',+ ' mx.save_safetensors(str(path), {',+ ' "transformer_blocks.0.attn.to_q.lora_A.default.weight": down,',+ ' "transformer_blocks.0.attn.to_q.lora_B.default.weight": q,',+ ' "transformer_blocks.0.attn.to_q.alpha": mx.array([2.0]),',+ ' "transformer_blocks.0.attn.to_k.lora_A.default.weight": down,',+ ' "transformer_blocks.0.attn.to_k.lora_B.default.weight": k,',+ ' "transformer_blocks.0.attn.to_v.lora_A.default.weight": down,',+ ' "transformer_blocks.0.attn.to_v.lora_B.default.weight": v,',+ ' "transformer_blocks.0.ff.net.0.proj.lora_A.default.weight": down,',+ ' "transformer_blocks.0.ff.net.0.proj.lora_B.default.weight": mlp_up,',+ ' })',+ ' apply_loras(model, [{"path": str(path), "scale": 1.0}])',+ ' qkv = model.blocks[0].attn.qkv_proj.adapters',+ ' expected_q = mx.stack([q.reshape(2, 4, 1), mx.zeros((2, 4, 1)), mx.zeros((2, 4, 1))], axis=2).transpose(0, 2, 1, 3).reshape(24, 1)',+ ' expected_fc1 = mx.concatenate([mlp_up[8:], mlp_up[:8]], axis=0)',+ ' mx.eval(*(adapter.up for adapter in qkv), expected_q, expected_fc1)',+ ' if len(qkv) != 3: raise AssertionError(f"expected 3 QKV adapters, got {len(qkv)}")',+ ' if not any(bool(mx.all(adapter.up == expected_q)) and adapter.scale == 2.0 for adapter in qkv): raise AssertionError("Q adapter was not expanded or alpha-scaled")',+ ' if not any(adapter.scale == 8.0 for adapter in qkv): raise AssertionError("Diffusers default alpha was not applied")',+ ' if not any(bool(mx.all(adapter.up == expected_fc1)) and adapter.scale == 8.0 for adapter in model.blocks[0].mlp.fc1.adapters): raise AssertionError("fc1 gate/value order or alpha was not applied")',+ 'print("ok")',+ ]);+ expect(output.trim()).toBe('ok');+ });+});diff --git a/scripts/minimax_h3_lora_probe.py b/scripts/minimax_h3_lora_probe.pyindex d38409882f..d28269b252 100644--- a/scripts/minimax_h3_lora_probe.py+++ b/scripts/minimax_h3_lora_probe.py@@ -1,18 +1,17 @@#!/usr/bin/env python3-"""Probe whether a pinned MiniMax H3 checkout can apply LoRAs at runtime.+"""Probe whether PortOS can apply LoRAs to a pinned MiniMax H3 checkout.-H3's shipped DiT is quantized, so a LoRA can only be applied the way the-reference implementation does it: read each target layer's *logical* dimensions-from the quantization metadata (the packed-uint32 storage shapes never match a-LoRA's) and add the deltas during the forward pass, never fusing them into the-quantized weights.+H3's shipped DiT is quantized, so a LoRA must read each target layer's logical+dimensions from the quantization metadata (the packed-uint32 storage shapes+never match a LoRA's) and add the deltas during the forward pass, never fusing+them into the quantized weights.-PortOS does not implement that applicator — it consumes one. The contract is a-`minimax_h3_mlx.lora` module exposing a callable `apply_loras(transformer,-loras)`, where `loras` is a list of `{"path": str, "scale": float}` mappings.-Exit 0 means the installed checkout satisfies the contract and PortOS may offer-LoRAs on this runtime; any non-zero exit means it does not, and the render path-keeps rejecting them with a precise reason.+PortOS owns the applicator in scripts/minimax_h3_lora.py. This probe imports+the pinned H3 DiT and applies a tiny real LoRA to a quantized MLX projection, so+it verifies both sides of the integration without loading the 33B checkpoint.+Exit 0 means the installed checkout and the local applicator satisfy the+contract and PortOS may offer LoRAs on this runtime; any non-zero exit means it+does not, and the render path keeps rejecting them with a precise reason.Kept separate from minimax_h3_runtime_probe.py so a runtime that is perfectlyhealthy for plain renders is never marked unready just because it predates the@@ -23,6 +22,7 @@ from __future__ import annotationsimport importlibimport sys+import tempfilefrom pathlib import Pathfrom _runner_common import register_source_namespace@@ -36,11 +36,50 @@ def main() -> int:if not (package_dir / "pipeline.py").is_file():raise RuntimeError(f"MiniMax H3 runtime source is missing under {runtime_dir}.")register_source_namespace("minimax_h3_mlx", package_dir)- lora = importlib.import_module("minimax_h3_mlx.lora")- if not callable(getattr(lora, "apply_loras", None)):- raise RuntimeError(- "minimax_h3_mlx.lora does not expose a callable apply_loras(transformer, loras)."+ importlib.import_module("minimax_h3_mlx.dit")+ from minimax_h3_lora import apply_loras+ import mlx.core as mx+ import mlx.nn as nn++ class Attention(nn.Module):+ def __init__(self):+ super().__init__()+ self.heads = 2+ self.head_dim = 4+ self.qkv_proj = nn.Linear(32, 24, bias=False)++ class Block(nn.Module):+ def __init__(self):+ super().__init__()+ self.attn = Attention()++ class ProbeDiT(nn.Module):+ def __init__(self):+ super().__init__()+ self.blocks = [Block()]++ transformer = ProbeDiT()+ nn.quantize(+ transformer,+ group_size=32,+ bits=8,+ class_predicate=lambda path, module: path.endswith("qkv_proj"),+ )+ with tempfile.TemporaryDirectory(prefix="portos-h3-lora-probe-") as temp:+ lora_path = Path(temp) / "probe.safetensors"+ mx.save_safetensors(+ str(lora_path),+ {+ "blocks.0.attn.qkv_proj.lora_A.weight": mx.zeros((1, 32)),+ "blocks.0.attn.qkv_proj.lora_B.weight": mx.zeros((24, 1)),+ "blocks.0.attn.qkv_proj.alpha": mx.array([1.0]),+ },)+ apply_loras(transformer, [{"path": str(lora_path), "scale": 1.0}])+ output = transformer.blocks[0].attn.qkv_proj(mx.zeros((1, 1, 32)))+ mx.eval(output)+ if tuple(output.shape) != (1, 1, 24):+ raise RuntimeError(f"MiniMax H3 LoRA probe produced an unexpected shape: {output.shape}")return 0diff --git a/server/lib/huggingfaceLora.js b/server/lib/huggingfaceLora.jsindex 44108b0cfd..06d61e00ef 100644--- a/server/lib/huggingfaceLora.js+++ b/server/lib/huggingfaceLora.js@@ -244,8 +244,9 @@ export const looksLikeMiniMaxH3 = (blob) => MINIMAX_H3_RE.test(blob);// Detect the PortOS video-LoRA family for an HF repo. LTX-2 / LTX-Video LoRAs// (fal, Lightricks) map to `ltx-video`; MiniMax H3 LoRAs map to `minimax-h3`,-// which only renders once the installed H3 runtime proves it can apply LoRAs to-// its quantized DiT (see services/videoGen/runtimes.js). Looks at the repo id,+// which only renders once the installed H3 runtime plus PortOS's adapter proves+// it can apply LoRAs to its quantized DiT (see services/videoGen/runtimes.js).+// Looks at the repo id,// HF tags, and the card's `base_model`. Returns a VIDEO_LORA_FAMILIES value or// null (unrecognized → the installer surfaces a clear error rather than// mis-tagging it).diff --git a/server/lib/runners.js b/server/lib/runners.jsindex 00640c0e49..1ff5916f56 100644--- a/server/lib/runners.js+++ b/server/lib/runners.js@@ -103,9 +103,10 @@ export const isMlxVideoLtxLoraCapable = (model) => {// - notapalindrome's `mlx_video` on a non-quantized LTX-2.x model — fused// offline into the transformer weights (see isMlxVideoLtxLoraCapable +// scripts/generate_av_lora.py).-// - `minimax_h3`, but ONLY when the installed runner can apply LoRAs to the-// quantized DiT at runtime. That is a property of the pinned checkout, not-// of the model entry, so it can't be derived here: listVideoModels()+// - `minimax_h3`, but ONLY when the installed runner plus PortOS's+// activation-space adapter can apply LoRAs to the quantized DiT at runtime.+// That is a property of the installed checkout, not of the model entry, so+// it can't be derived here: listVideoModels()// decorates each model with `runtimeLoraCapable` from the probe in// services/videoGen/runtimes.js and this reads it off the payload (the same// shape as `lastFrameAnchored`). An undecorated model therefore reads asdiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex e41a61f39e..6c0394b45b 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -914,10 +914,10 @@ describe('videoGen routes', () => {expect(r.body.code).toBe('LORAS_REQUIRE_LTX2');});- // H3 CAN take LoRAs — it's the pinned runner that can't apply them to the- // quantized DiT. "Use an LTX-2.x model" would be wrong advice, so the- // rejection carries its own code and reason.- it('rejects LoRAs on an H3 model whose runtime has no applicator, with an H3-specific code', async () => {+ // H3 CAN take LoRAs — it is the installed runner plus adapter capability+ // that is unavailable in this case. "Use an LTX-2.x model" would be wrong+ // advice, so the rejection carries its own code and reason.+ it('rejects LoRAs on an H3 model whose adapter probe fails, with an H3-specific code', async () => {videoGenService.listVideoModels.mockReturnValueOnce([{ id: 'minimax_h3_8bit', name: 'MiniMax H3', runtime: 'minimax_h3', defaultFrames: 141, frameOptions: [141], fpsOptions: [24], runtimeLoraCapable: false },]);diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex c4789d1874..fe29ff1801 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -103,7 +103,8 @@ export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id// Attach the runtime capabilities a model entry can't express on its own:// whether an FFLF last frame is a real anchor, and whether the *installed* BYOV// runner can apply user LoRAs (H3's DiT is quantized, so that depends on the-// pinned checkout — see runtimes.js `loraProbeArgs`). Both are declared in+// pinned checkout plus PortOS's activation-space adapter — see runtimes.js+// `loraProbeArgs`). Both are declared in// runtimes.js and surfaced here so the Video Gen form and videoLoraFamily() read// them off the model instead of keeping their own lists. Applied by BOTH model// resolvers, so the render path and the API payload can never disagree aboutdiff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 90fdcdfaee..8dca72b5ba 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -3267,8 +3267,9 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {// H3's DiT is quantized, so LoRAs ride along only if the installed runner// applies them at render time from quantization metadata. That is a property of-// the pinned checkout, so the verdict comes from a probe — and the render path-// must honor it in both directions rather than blanket-rejecting the runtime.+// the installed runtime plus adapter, so the verdict comes from a probe — and+// the render path must honor it in both directions rather than blanket-rejecting+// the runtime.describe.skipIf(process.platform === 'win32')('MiniMax H3 user LoRAs', () => {const h3Render = (jobId) => generateVideo({jobId,@@ -3300,7 +3301,7 @@ describe.skipIf(process.platform === 'win32')('MiniMax H3 user LoRAs', () => {expect(args).toContain('--lora');});- it('rejects LoRAs with an H3-specific reason when the runner has no applicator', async () => {+ it('rejects LoRAs with an H3-specific reason when the adapter probe fails', async () => {h3LoraState.capable = false;await expect(h3Render('h3-lora-blocked')).rejects.toMatchObject({code: 'MINIMAX_H3_LORA_UNSUPPORTED',diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex a5a97362b0..58ab170f7c 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -956,8 +956,8 @@ async function resolvePreparedParams({// _pending_loras hook, see scripts/generate_ltx2.py) and non-quantized// LTX-2.x `mlx_video` models (merged offline by scripts/generate_av_lora.py).// `minimax_h3` applies them at runtime, but only if the installed checkout- // implements a quant-aware applicator — listVideoModels() decorates that- // probe result as `runtimeLoraCapable`, which videoLoraFamily() reads.+ // passes PortOS's quant-aware adapter probe — listVideoModels() decorates that+ // result as `runtimeLoraCapable`, which videoLoraFamily() reads.// videoLoraFamily() returns null for everything else (wan22 / hunyuan /// quantized mlx_video) — reject up-front so a bad modelId can't enqueue a// doomed job that only fails in the worker.diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex 3e5d80ae06..4f17a5c65d 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -648,8 +648,9 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFif (lastImagePath) args.push('--image', lastImagePath, '--anchor', 'last');// Runtime (never fused) application — each --lora needs its own --lora-scale,// in the same order, mirroring the --image/--anchor pairing above. buildArgs- // has already rejected LoRAs unless the probe proved this checkout can apply- // them to the quantized DiT (see runtimes.js `loraProbeArgs`).+ // has already rejected LoRAs unless the probe proved this checkout plus the+ // PortOS adapter can apply them to the quantized DiT (see runtimes.js+ // `loraProbeArgs`).for (const l of loras ?? []) args.push('--lora', l.path, '--lora-scale', String(l.strength));// Substituted prompt conditioner (lib/videoTextEncoders.js). Absent for the// stock choice, so the argv of an unswapped render is byte-identical to whatdiff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 2a4aaa5096..335cda598a 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -143,16 +143,13 @@ export const BYOV_RUNTIME_INFO = Object.freeze({// Install / Repair passes the flag (scripts/setup-image-video.sh), which is// where a pin bump is actionable.probeArgs: [MINIMAX_H3_RUNTIME_PROBE_SCRIPT, MINIMAX_H3_REPO_DIR],- // Separate, OPTIONAL capability probe: can this checkout apply LoRAs to the- // quantized DiT at runtime? H3's shipped weights are 8-bit, so a LoRA can- // only ride along if the runner reads logical layer dims from the- // quantization metadata and adds deltas in the forward pass (fusing into- // packed-uint32 weights is not possible). The pinned revision has no LoRA- // code at all, so this probe fails today and LoRAs stay rejected with a- // precise reason — advancing the pin to a revision that satisfies the- // contract (see scripts/minimax_h3_lora_probe.py) opens the gate with no- // code change here. Absence of this key means "runtime can never take- // LoRAs", which is the correct answer for wan22 / hunyuan.+ // Separate, OPTIONAL capability probe: can PortOS apply LoRAs to this+ // checkout's quantized DiT at runtime? H3's shipped weights are 8-bit, so+ // the applicator must read logical layer dims from quantization metadata+ // and add deltas in the forward pass (fusing into packed-uint32 weights is+ // not possible). The probe exercises the local adapter against the pinned+ // runtime without loading the model. Absence of this key means "runtime can+ // never take LoRAs", which is the correct answer for wan22 / hunyuan.loraProbeArgs: [MINIMAX_H3_LORA_PROBE_SCRIPT, MINIMAX_H3_REPO_DIR],fingerprintPackages: ['mlx', 'mlx-metal', 'mlx-vlm', 'transformers', 'huggingface-hub'],},@@ -344,11 +341,11 @@ const summarizeProbeStderr = (stderr) => stderr.replace(/\s+/g, ' ').trim() || '// unread pipe can fill and block the child.//// Two negative outcomes, deliberately different icons: a non-zero exit is the-// probe ANSWERING — for the LoRA probe, "this checkout has no applicator" is-// the documented normal verdict (see scripts/minimax_h3_lora_probe.py), cached-// as a legitimate `false` — while a spawn error or timeout means it never-// answered at all. Calling the first one a failure cries wolf on every healthy-// install that predates the applicator.+// probe ANSWERING — for the LoRA probe, "the runtime plus adapter cannot apply"+// is the documented normal verdict (see scripts/minimax_h3_lora_probe.py),+// cached as a legitimate `false` — while a spawn error or timeout means it+// never answered at all. Calling the first one a failure cries wolf on every+// healthy install with an incompatible runtime.//// `label` names the runtime and which probe ran, so a status request that fans// out over several runtimes produces attributable lines. It must never carry a@@ -451,7 +448,7 @@ export function byovRuntimeLoraCapable(runtimeId) {export function videoLoraUnsupportedError(model, modelId) {if (model?.runtime === 'minimax_h3') {return new ServerError(- `The installed MiniMax H3 runtime cannot apply LoRAs. Model "${modelId}" has a quantized DiT, so LoRAs need a runner that applies them at render time from quantization metadata — the pinned checkout has no such applicator. Upgrade the H3 runtime from Video Gen once a build that supports it is pinned.`,+ `The installed MiniMax H3 runtime cannot apply LoRAs. Model "${modelId}" has a quantized DiT, so PortOS needs its quantization-aware render-time adapter to pass the runtime capability probe. Repair the H3 runtime from Video Gen, then retry.`,{ status: 400, code: 'MINIMAX_H3_LORA_UNSUPPORTED' },);}diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.jsindex 8831e1ebfc..9b371c8560 100644--- a/server/services/videoGen/runtimes.test.js+++ b/server/services/videoGen/runtimes.test.js@@ -162,16 +162,17 @@ describe('venv probe diagnostics', () => {it('attributes the line to the LoRA probe without calling its verdict a fault', async () => {runtimeMocks.spawn.mockImplementationOnce(() => exitChild(- 1, 'ModuleNotFoundError: No module named "minimax_h3_mlx.lora"\n',+ 1, 'ImportError: PortOS MiniMax H3 LoRA adapter is unavailable\n',));const { result, lines } = await captureProbeLogs(() => resolveByovRuntimeLoraCapable('minimax_h3'));- // A checkout with no applicator is the documented normal answer, not a- // broken install — so the reason is surfaced, but not under the failure icon.+ // A runtime that fails the optional applicator probe is the documented+ // normal answer, not a broken install — so the reason is surfaced, but not+ // under the failure icon.expect(result).toBe(false);expect(lines[0]).toContain('minimax_h3 LoRA-capability');- expect(lines[0]).toContain('No module named "minimax_h3_mlx.lora"');+ expect(lines[0]).toContain('PortOS MiniMax H3 LoRA adapter is unavailable');expect(lines[0].startsWith('❌')).toBe(false);});});@@ -180,13 +181,13 @@ describe('venv probe diagnostics', () => {// installed checkout, not the model entry — hence a probe rather than a// hardcoded predicate. The gate must fail CLOSED until that probe has answered.describe('MiniMax H3 LoRA capability', () => {- it('reports capable when the runner exposes a quant-aware applicator', async () => {+ it('reports capable when the runtime plus adapter pass the quant-aware probe', async () => {runtimeMocks.spawn.mockImplementationOnce(() => exitChild(0));await expect(resolveByovRuntimeLoraCapable('minimax_h3')).resolves.toBe(true);expect(byovRuntimeLoraCapable('minimax_h3')).toBe(true);});- it('reports not capable when the pinned checkout has no LoRA applicator', async () => {+ it('reports not capable when the runtime fails the LoRA applicator probe', async () => {runtimeMocks.spawn.mockImplementationOnce(() => exitChild(1));// Captured, not asserted on: the verdict now writes a line, and letting it// through would print a scary-looking probe log during an unrelated test.