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
perf: reuse MiniMax H3 MLX prompt embeddings across renders of the same request (#5443)
[._.]/ Adam Eivyc93b06f44463
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex 4e700ad260..a03fa73cc0 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -10,6 +10,14 @@ Conditioning is H3's own `fl2va` keyframe path: zero images is text-to-video,one `--image first` is image-to-video, and a `first` + `last` pair is FFLF.Each `--image` needs its own `--anchor`, in the same order.+Prompt embeddings: the Qwen3-VL conditioning pass is deterministic in the+prompt, the keyframes and the conditioner, so `--prompt-embedding-cache-dir`+lets a re-render of the same request reuse it. Entries are keyed on the prompt+plus the CONTENT digest of each conditioning image, held under a byte ceiling+with least-recently-used eviction, and every failure — a corrupt entry, an+unwritable directory — falls back to recomputing rather than to a failed+render.+Memory: unified memory means this render and the rest of the machine draw on onepool. PortOS passes the host floor its declared placement profile needs(`--min-system-memory-gb`) and the reserve it holds back for the operating@@ -22,12 +30,15 @@ render that overruns fails as a job instead of wedging the machine.from __future__ import annotationsimport argparse+import hashlibimport importlib.utilimport json+import osimport reimport shutilimport subprocessimport sys+import timefrom contextlib import redirect_stdoutfrom pathlib import Pathfrom types import SimpleNamespace@@ -85,6 +96,9 @@ def parse_args() -> argparse.Namespace:help="cache-resolved weight file for the draft decoder (repeatable)")parser.add_argument("--draft-decoder-shim-root",help="directory the composed draft-decoder checkpoint root is built under")+ parser.add_argument("--prompt-embedding-cache-dir",+ help="directory holding reusable prompt embeddings, keyed by prompt text and "+ "conditioning-image content (omit to recompute on every render)")return parser.parse_args()@@ -394,6 +408,274 @@ def install_vision_embed_merge() -> None:encoder.encode = encode+# --- Prompt-embedding cache (PortOS #5443) -----------------------------------++# A byte ceiling rather than an entry cap: one H3 embedding is+# `(1, tokens, 5120)` bfloat16, and an image-conditioned request carries+# hundreds of extra vision rows on top of the prompt's, so entries differ in+# size by more than an order of magnitude and a count cap would bound the wrong+# quantity. 2 GB holds dozens of typical entries and is a rounding error beside+# the tens of GB of weights every render already reads.+PROMPT_EMBEDDING_CACHE_BYTES = 2 * 1024 ** 3++# A half-written entry only exists when a render was killed between the save and+# the rename. Swept on a TTL rather than on sight, and one comfortably longer+# than any encode, so a sibling render's in-flight temp is never pulled out from+# under it.+PROMPT_EMBEDDING_PARTIAL_TTL_SECONDS = 3600.0++# Entries are named for their key digest. Anything else in the directory — an+# in-flight `<key>.partial-<pid>.safetensors`, a stray file — is not one, which+# is what keeps a partial from ever being read as a complete entry.+PROMPT_EMBEDDING_ENTRY_RE = re.compile(r"^[0-9a-f]{64}\.safetensors$")+++def hash_conditioning_image(image) -> str:+ """Identify a conditioning keyframe by the PIXELS the vision tower will see.++ A content digest rather than path plus size and mtime, because PortOS writes+ ffmpeg-normalized keyframes into job-scoped scratch directories: the same+ source frame reaches two renders under two paths with two mtimes, so a path+ identity would essentially never hit — which is the whole point of the cache+ — and because those scratch paths are REUSED across jobs it can also ALIAS,+ serving another image's embedding for a rewritten file whose size and mtime+ happen to match. That failure is a silently wrong render rather than an+ error.++ Taken off the decoded image rather than the file, so the digest describes+ exactly what `encode` is about to consume: `load_keyframes` has already+ converted to RGB and applied the EXIF rotation, and the same pixels+ delivered as a JPEG and as a PNG condition the DiT identically. Hashing the+ pixel buffer of a keyframe costs milliseconds against a render's minutes.+ """+ digest = hashlib.sha256(f"{image.mode}:{image.size[0]}x{image.size[1]}:".encode("utf-8"))+ digest.update(image.tobytes())+ return digest.hexdigest()+++def prompt_embedding_identity(args: argparse.Namespace) -> dict:+ """Everything BUT the prompt and keyframes that changes what `encode` returns.++ The conditioner is the pin plus whatever PortOS substituted for it, so a+ runtime bump, a different checkpoint or a swapped text encoder must not read+ the previous one's entries — an embedding is only reusable against the exact+ stack that produced it.++ The substitute is named by its declared id and its shards' SNAPSHOT paths+ rather than by hashing multi-GB weights, which would cost more than the+ encode the cache exists to skip. The snapshot segment is what carries the+ revision — PortOS resolves these out of the Hugging Face cache as+ `…/snapshots/<revision>/<shard>` — so a release that repins an existing+ catalog id onto new weights writes a new identity instead of silently+ serving the previous revision's embeddings.+ """+ return {+ "runtime_revision": args.runtime_revision,+ "checkpoint": f"{args.checkpoint_repo}@{args.checkpoint_revision}",+ "text_encoder_id": args.text_encoder_id or "",+ "text_encoder_files": sorted(+ f"{Path(f).parent.name}/{Path(f).name}" for f in args.text_encoder_file+ ),+ "text_encoder_key_prefix": sorted(args.text_encoder_key_prefix),+ "text_encoder_final_norm_key": args.text_encoder_final_norm_key or "",+ }+++def prompt_embedding_key(identity: dict, prompt: str, image_digests: list[str]) -> str:+ """Digest one encode request: the conditioner, the prompt AND the keyframes.++ `image_digests` is an ordered list and it is EMPTY for a text-to-video+ request, so text-only, first-frame and first+last requests over one prompt+ each land on their own entry, and swapping the two keyframes of an FFLF+ render lands on another again (the order here is anchor order).+ """+ payload = {**identity, "prompt": prompt, "images": list(image_digests)}+ return hashlib.sha256(+ json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")+ ).hexdigest()+++def prepare_prompt_embedding_cache(cache_dir: Path) -> Path | None:+ """Return the cache directory once it is proven writable, else None.++ Proven by an actual write rather than by `os.access`, which reports the+ permission bits and not what the filesystem will do (a read-only mount, a+ full disk, a sandbox). A cache that cannot be written to is not a render+ failure — the runner recomputes, which is exactly what it did before this+ existed — so every failure here degrades and says so instead of raising.+ """+ probe = cache_dir / f".portos-write-probe-{os.getpid()}"+ try:+ cache_dir.mkdir(parents=True, exist_ok=True)+ probe.write_bytes(b"")+ probe.unlink()+ except OSError as exc:+ print(+ f"⚠️ MiniMax H3 prompt-embedding cache disabled, recomputing every embedding "+ f"({cache_dir}): {type(exc).__name__}: {exc}",+ file=sys.stderr, flush=True,+ )+ return None+ return cache_dir+++def read_prompt_embedding(entry: Path):+ """Load one cached embedding, discarding an entry that cannot be read.++ A truncated, corrupt or half-keyed entry is a cache MISS, never a render+ failure: it is unlinked so the next render does not pay for it again, and+ the caller recomputes. That is also the only recovery path for an entry left+ behind by a render killed between the save and the rename.+ """+ if not entry.is_file():+ return None++ import mlx.core as mx+ import numpy as np++ try:+ cached = mx.load(str(entry))+ hidden_states = cached["hidden_states"]+ # Forced here rather than at the call site: a lazily-materialized load+ # would otherwise raise deep inside the DiT instead of being caught as+ # the bad entry it is.+ mx.eval(hidden_states)+ # Back to the exact numpy int64 the pinned `encode` returns — the DiT+ # layout reads `token_tags` as an ndarray, not an mx.array.+ token_tags = np.asarray(cached["token_tags"]).astype(np.int64, copy=False)+ except Exception as exc: # noqa: BLE001 — a bad entry is a miss, not a failure+ print(+ f"⚠️ Discarding an unreadable MiniMax H3 prompt-embedding cache entry "+ f"({entry.name}): {type(exc).__name__}: {exc}",+ file=sys.stderr, flush=True,+ )+ _unlink_quietly(entry)+ return None+ return hidden_states, token_tags+++def write_prompt_embedding(entry: Path, hidden_states, token_tags) -> bool:+ """Publish one entry atomically, or report that the cache took nothing.++ `mx.save_safetensors` appends `.safetensors` when the name lacks it, so the+ temp already carries the suffix and the rename moves the file that was+ actually written. The `.partial-<pid>` infix keeps that temp outside+ PROMPT_EMBEDDING_ENTRY_RE, so a reader can never pick up a half-written file+ as a complete entry.+ """+ import mlx.core as mx++ temp = entry.with_name(f"{entry.stem}.partial-{os.getpid()}.safetensors")+ try:+ mx.save_safetensors(+ str(temp),+ {"hidden_states": hidden_states, "token_tags": mx.array(token_tags)},+ )+ os.replace(temp, entry)+ except Exception as exc: # noqa: BLE001 — a cache that cannot be written still renders+ print(+ f"⚠️ MiniMax H3 prompt embedding not cached ({entry.name}): "+ f"{type(exc).__name__}: {exc}",+ file=sys.stderr, flush=True,+ )+ _unlink_quietly(temp)+ return False+ return True+++def prune_prompt_embedding_cache(+ cache_dir: Path,+ ceiling_bytes: int = PROMPT_EMBEDDING_CACHE_BYTES,+) -> list[str]:+ """Hold the cache under its byte ceiling, evicting least-recently-used first.++ Recency is the entry's mtime, which every hit stamps, and the tiebreak is+ the file NAME — the key digest — so two entries written inside one mtime+ tick still evict in one fixed order rather than in whatever order the+ directory happens to list. Once an entry does not fit, every entry after it+ in that order goes too: keeping a small older entry over a large newer one+ would make retention depend on size instead of on use.++ Returns the names it removed, in eviction order, so a caller can report the+ decision rather than infer it from the directory.+ """+ try:+ listing = list(cache_dir.iterdir())+ except OSError:+ return []++ entries = []+ now = time.time()+ for path in listing:+ try:+ stat = path.stat()+ except OSError:+ continue+ if PROMPT_EMBEDDING_ENTRY_RE.match(path.name):+ entries.append((stat.st_mtime_ns, path.name, stat.st_size, path))+ elif (+ path.name.endswith(".safetensors")+ and now - stat.st_mtime > PROMPT_EMBEDDING_PARTIAL_TTL_SECONDS+ ):+ _unlink_quietly(path)++ entries.sort(key=lambda entry: (entry[0], entry[1]), reverse=True)+ kept = 0+ evicted: list[str] = []+ for _, name, size, path in entries:+ if not evicted and kept + size <= ceiling_bytes:+ kept += size+ continue+ _unlink_quietly(path)+ evicted.append(name)+ return evicted+++def _unlink_quietly(path: Path) -> None:+ """Remove a cache file, treating a failure to as nothing worth reporting."""+ try:+ path.unlink(missing_ok=True)+ except OSError:+ pass+++def install_prompt_embedding_cache(cache_dir: Path, identity: dict) -> None:+ """Serve `encode` from disk when this prompt already met these keyframes.++ Installed LAST of the encoder patches so it WRAPS the keyframe corrections+ rather than being wrapped by them: `install_vision_embed_merge` verifies the+ digest of the implementation it copies, and it has to see the pinned+ `encode`, not this one.++ The keyframes are digested from the images this call actually receives, not+ from the paths PortOS passed on the command line — so the key describes the+ request being encoded rather than what those paths held some minutes and+ several load stages earlier, and a call the runner did not anticipate keys+ itself correctly instead of needing to be recognized and bypassed.+ """+ encoder, original = pinned_encoder_hook("encode")++ def encode(self, prompt: str, images: list | None = None):+ digests = [hash_conditioning_image(image) for image in images or []]+ entry = cache_dir / f"{prompt_embedding_key(identity, prompt, digests)}.safetensors"+ cached = read_prompt_embedding(entry)+ if cached is not None:+ # The sweep below ranks on mtime, so a hit has to stamp it or a+ # constantly-reused prompt evicts ahead of one nobody renders.+ try:+ os.utime(entry)+ except OSError:+ pass+ print("STATUS:Reusing the cached MiniMax H3 prompt embedding", file=sys.stderr, flush=True)+ return cached+ hidden_states, token_tags = original(self, prompt, images)+ if write_prompt_embedding(entry, hidden_states, token_tags):+ prune_prompt_embedding_cache(cache_dir)+ return hidden_states, token_tags++ encoder.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.@@ -850,6 +1132,15 @@ def main() -> int:except Exception as exc: # noqa: BLE001 — degrade, never fail the renderfall_back_to_full_decoder(exc)+ # Prompt-embedding cache (PortOS #5443). Installed last of the encoder+ # patches so it wraps the keyframe corrections above, and only once the+ # directory has proven writable — an unusable cache degrades to the plain+ # recompute this runner did before it existed, never to a failed render.+ if args.prompt_embedding_cache_dir:+ prompt_cache_dir = prepare_prompt_embedding_cache(Path(args.prompt_embedding_cache_dir))+ if prompt_cache_dir is not None:+ install_prompt_embedding_cache(prompt_cache_dir, prompt_embedding_identity(args))+print("STAGE:load-pipeline", file=sys.stderr, flush=True)def load_pipeline(root: Path):diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsindex 3698f9e1c9..d76774e709 100644--- a/scripts/generate_minimax_h3.test.js+++ b/scripts/generate_minimax_h3.test.js@@ -32,6 +32,29 @@ const hasMlx = (() => {}})();+// The served-embedding cases below round-trip real tensors AND describe them+// through numpy, so an interpreter carrying mlx but not numpy would fail them+// rather than skip. Probed together for that reason — hasMlx alone gates the+// final-norm case above, which genuinely needs only mlx.+const hasEmbeddingStack = (() => {+ try {+ execFileSync(pyBin, ['-c', 'import mlx.core, numpy'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();++// A stand-in for the decoded PIL keyframe `encode` receives: the cache reads+// only the three attributes the digest is taken from, so the suite can exercise+// keying without Pillow (which CI's bare python3 does not have either).+const stubImage = [+ 'class StubImage:',+ ' def __init__(self, mode, size, data):',+ ' self.mode, self.size, self._data = mode, size, data',+ ' def tobytes(self): return self._data',+].join('\n');+// The pin facts these corrections guard against moved to `_minimax_h3_mlx_pins.py`// so the install-time probe and these render-time guards read one copy. Reach the// module the RUNNER imported rather than loading a second one by spec: a private@@ -70,6 +93,11 @@ const VALIDATE_ARGS_DEFAULTS = {draft_decoder_id: null,draft_decoder_file: [],draft_decoder_shim_root: null,+ // Not read by validate_args — prompt_embedding_identity (#5443) reads these+ // off the same Namespace, and one builder keeps both from drifting.+ runtime_revision: "runtime-revision",+ checkpoint_repo: "example/checkpoint",+ checkpoint_revision: "checkpoint-revision",};const argsExpr = (overrides = {}) => {const fields = Object.entries({ ...VALIDATE_ARGS_DEFAULTS, ...overrides })@@ -864,4 +892,323 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {].join('\n')}`);expect(output).toMatch(expected);});++ // --- Prompt-embedding cache (#5443) ---------------------------------------++ it('parses the optional prompt-embedding cache directory', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys',+ 'sys.argv = ["generate_minimax_h3.py", "--model-repo", "example/model", "--model-revision", "revision",',+ ' "--runtime-dir", "/tmp/runtime", "--runtime-revision", "revision",',+ ' "--checkpoint-repo", "example/checkpoint", "--checkpoint-revision", "revision",',+ ' "--prompt", "a test prompt", "--width", "1344", "--height", "768", "--num-frames", "124",',+ ' "--output", "test.mp4", "--prompt-embedding-cache-dir", "/tmp/embeddings"]',+ 'print(runner.parse_args().prompt_embedding_cache_dir)',+ ].join('\n')}`);+ expect(output.trim()).toBe('/tmp/embeddings');+ });++ // The whole point of the key: an embedding is only reusable against the exact+ // request that produced it. Two renders sharing a prompt but conditioned on+ // different keyframes must not share an entry — and because the keyframes are+ // identified by their PIXELS, the same frame decoded again from another+ // job-scoped scratch path still hits.+ it('keys an embedding on the prompt, the conditioner and each keyframe content digest', () => {+ const output = runPython(`${importRunner}\n${stubImage}\n${[+ 'import json',+ 'first = StubImage("RGB", (2, 2), b"IMAGE-A")',+ '# A second decode of the same source frame — what a re-render actually',+ '# hands `encode` once the scratch copy has moved.',+ 'replayed = StubImage("RGB", (2, 2), b"IMAGE-A")',+ '# Different pixels at the SAME byte length, which a size-based identity',+ '# could not tell apart from the pair above.',+ 'other = StubImage("RGB", (2, 2), b"IMAGE-B")',+ '# Same buffer, different geometry: the vision tower sees another request.',+ 'reshaped = StubImage("RGB", (4, 1), b"IMAGE-A")',+ 'identity = {"runtime_revision": "rev", "checkpoint": "example/checkpoint@rev",',+ ' "text_encoder_id": "", "text_encoder_files": [],',+ ' "text_encoder_key_prefix": [], "text_encoder_final_norm_key": ""}',+ 'digest = runner.hash_conditioning_image',+ 'key = runner.prompt_embedding_key',+ 'print(json.dumps({',+ ' "textOnly": key(identity, "a prompt", []),',+ ' "imageA": key(identity, "a prompt", [digest(first)]),',+ ' "imageAReplayed": key(identity, "a prompt", [digest(replayed)]),',+ ' "imageB": key(identity, "a prompt", [digest(other)]),',+ ' "imageAReshaped": key(identity, "a prompt", [digest(reshaped)]),',+ ' "bothFrames": key(identity, "a prompt", [digest(first), digest(other)]),',+ ' "bothFramesSwapped": key(identity, "a prompt", [digest(other), digest(first)]),',+ ' "otherPrompt": key(identity, "another prompt", [digest(first)]),',+ ' "substitutedEncoder": key({**identity, "text_encoder_id": "example-abliterated"},',+ ' "a prompt", [digest(first)]),',+ '}))',+ ].join('\n')}`);+ const keys = JSON.parse(output);+ // The same frame decoded again is the SAME request.+ expect(keys.imageAReplayed).toBe(keys.imageA);+ // Everything else names a different one, text-to-video included.+ const distinct = Object.entries(keys).filter(([name]) => name !== 'imageAReplayed');+ expect(new Set(distinct.map(([, value]) => value)).size).toBe(distinct.length);+ for (const value of Object.values(keys)) expect(value).toMatch(/^[0-9a-f]{64}$/);+ });++ // The identity is what makes an entry unreadable by a DIFFERENT stack: a pin+ // bump, another checkpoint or a swapped conditioner all produce different+ // embeddings for one prompt, and serving the previous one would be a silently+ // wrong render rather than an error.+ it('folds the pinned runtime, the checkpoint and any substituted conditioner into the identity', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json',+ 'from types import SimpleNamespace',+ argsExpr({+ runtime_revision: 'runtime-revision',+ checkpoint_repo: 'example/checkpoint',+ checkpoint_revision: 'checkpoint-revision',+ text_encoder_id: 'example-abliterated',+ text_encoder_file: [+ '/hf/models--example--encoder/snapshots/encoder-revision/shard-2.safetensors',+ '/hf/models--example--encoder/snapshots/encoder-revision/shard-1.safetensors',+ ],+ text_encoder_key_prefix: ['visual.=model.visual.', 'model.layers.=model.language_model.layers.'],+ text_encoder_final_norm_key: 'model.norm.weight',+ }),+ 'print(json.dumps(runner.prompt_embedding_identity(args)))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual({+ runtime_revision: 'runtime-revision',+ checkpoint: 'example/checkpoint@checkpoint-revision',+ text_encoder_id: 'example-abliterated',+ // The snapshot segment, not just the basename: a release that repins an+ // existing catalog id onto new weights keeps the id and the shard names,+ // so dropping the revision would serve the old weights' embeddings.+ // Sorted, so the order PortOS happened to pass the shards in cannot split+ // one conditioner across two entries.+ text_encoder_files: ['encoder-revision/shard-1.safetensors', 'encoder-revision/shard-2.safetensors'],+ text_encoder_key_prefix: ['model.layers.=model.language_model.layers.', 'visual.=model.visual.'],+ text_encoder_final_norm_key: 'model.norm.weight',+ });+ });++ // Retention: a render session that keeps changing prompt would otherwise grow+ // the directory without bound, and each entry is tens of megabytes.+ it('evicts least-recently-used entries, and everything below the first that does not fit', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, os, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' for name, size, mtime in (("a" * 64, 300, 3000), ("b" * 64, 500, 2000), ("c" * 64, 100, 1000)):',+ ' entry = root / f"{name}.safetensors"',+ ' entry.write_bytes(b"x" * size)',+ ' os.utime(entry, (mtime, mtime))',+ ' evicted = runner.prune_prompt_embedding_cache(root, 700)',+ ' print(json.dumps({"evicted": [name[0] for name in evicted],',+ ' "left": sorted(path.name[0] for path in root.iterdir())}))',+ ].join('\n')}`);+ // "a" fits (300), "b" does not (800 > 700) — and "c" goes with it even+ // though 400 bytes were free, because retention ranks on use, not on size.+ expect(JSON.parse(output)).toEqual({ evicted: ['b', 'c'], left: ['a'] });+ });++ // mtime has coarse enough resolution that two entries written in one render+ // can share a tick; without the name tiebreak the survivor would be whichever+ // one the filesystem happened to list first.+ it('breaks an eviction tie on the key digest rather than on directory order', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, os, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' for name in ("a" * 64, "b" * 64, "c" * 64):',+ ' entry = root / f"{name}.safetensors"',+ ' entry.write_bytes(b"x" * 300)',+ ' os.utime(entry, (2000, 2000))',+ ' print(json.dumps([name[0] for name in runner.prune_prompt_embedding_cache(root, 700)]))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual(['a']);+ });++ // A temp only outlives its own render when that render was killed between the+ // save and the rename. It is never a readable entry, so it is swept — but on a+ // TTL, so a sibling render's in-flight write is not pulled out from under it.+ it('sweeps a stranded partial write past its TTL and leaves a fresh one alone', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, os, tempfile, time',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' stale = root / f\'{"a" * 64}.partial-101.safetensors\'',+ ' stale.write_bytes(b"x" * 4000)',+ ' old = time.time() - runner.PROMPT_EMBEDDING_PARTIAL_TTL_SECONDS - 60',+ ' os.utime(stale, (old, old))',+ ' fresh = root / f\'{"b" * 64}.partial-102.safetensors\'',+ ' fresh.write_bytes(b"x" * 4000)',+ ' entry = root / f\'{"c" * 64}.safetensors\'',+ ' entry.write_bytes(b"x" * 100)',+ ' evicted = runner.prune_prompt_embedding_cache(root, 200)',+ ' print(json.dumps({"evicted": evicted, "left": sorted(path.name for path in root.iterdir())}))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ // Neither partial counts against the ceiling — 8000 bytes of them would+ // otherwise have evicted the one real 100-byte entry.+ expect(result.evicted).toEqual([]);+ expect(result.left).toEqual([`${'b'.repeat(64)}.partial-102.safetensors`, `${'c'.repeat(64)}.safetensors`]);+ });++ // An unusable cache directory is not a render failure: the runner recomputes,+ // which is exactly what it did before the cache existed.+ it('disables the cache when its directory cannot be created', () => {+ const output = runPython(`${importRunner}\n${[+ 'import sys, tempfile',+ 'sys.stderr = sys.stdout',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' blocker = Path(temp) / "embeddings"',+ ' blocker.write_bytes(b"not a directory")',+ ' print(repr(runner.prepare_prompt_embedding_cache(blocker)))',+ ].join('\n')}`);+ expect(output).toMatch(/prompt-embedding cache disabled, recomputing every embedding/);+ expect(output.trim().split(/\r?\n/).pop()).toBe('None');+ });++ // The directory already exists and only the WRITE fails — a read-only mount,+ // a sandbox, a full disk. `os.access` reports the permission bits rather than+ // what the filesystem will do, so readiness is proven by an actual write.+ // POSIX-only: `os.chmod` on Windows toggles a file's read-only bit and cannot+ // make a directory unwritable.+ it.skipIf(process.platform === 'win32')('disables the cache when its existing directory refuses a write', () => {+ const output = runPython(`${importRunner}\n${[+ 'import os, sys, tempfile',+ 'sys.stderr = sys.stdout',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' readonly = Path(temp) / "embeddings"',+ ' readonly.mkdir()',+ ' os.chmod(readonly, 0o500)',+ ' try:',+ ' print(repr(runner.prepare_prompt_embedding_cache(readonly)))',+ ' finally:',+ ' os.chmod(readonly, 0o700)',+ ].join('\n')}`);+ expect(output).toMatch(/prompt-embedding cache disabled, recomputing every embedding/);+ expect(output.trim().split(/\r?\n/).pop()).toBe('None');+ });++ // Everything above is key and retention arithmetic, which needs neither mlx+ // nor numpy. These last cases round-trip real tensors and describe them+ // through numpy, so they run only where both import (CI's bare python3 is+ // Linux, which has no mlx wheel).+ describe.skipIf(!hasEmbeddingStack)('served embeddings', () => {+ // The stand-in encoder returns the same shape the pinned `encode` does —+ // `(mx.array, np.ndarray[int64])` — and records every call, which is how a+ // hit is told from a recompute.+ const stubEncoder = stubPin([+ ' calls = []',+ ' def encode(self, prompt, images=None):',+ ' MiniMaxH3TextEncoder.calls.append((prompt, len(images or [])))',+ ' return (mx.arange(12).reshape(1, 3, 4).astype(mx.bfloat16),',+ ' np.array([0, 1, 0], dtype=np.int64))',+ ], ['import mlx.core as mx', 'import numpy as np']);++ // Reported as a float32 view: bfloat16 widens to it losslessly, so equal+ // float32 bytes mean bit-identical bfloat16 — and numpy has no bfloat16 of+ // its own to hash directly.+ const describeResult = [+ 'def describe(pair):',+ ' hidden, tags = pair',+ ' return {"dtype": str(hidden.dtype), "shape": list(hidden.shape),',+ ' "bytes": hashlib.sha256(np.asarray(hidden.astype(mx.float32)).tobytes()).hexdigest(),',+ ' "tagsDtype": str(tags.dtype), "tags": tags.tolist()}',+ ];++ it('serves a second render of the same request byte-identically, without re-encoding', () => {+ const output = runPython(`${importRunner}\n${stubEncoder}\n${stubImage}\n${[+ 'import hashlib, json, mlx.core as mx, numpy as np, tempfile',+ 'sys.stderr = sys.stdout',+ ...describeResult,+ 'with tempfile.TemporaryDirectory() as temp:',+ ' cache = runner.prepare_prompt_embedding_cache(Path(temp) / "embeddings")',+ ' runner.install_prompt_embedding_cache(cache, {"runtime_revision": "rev"})',+ ' encoder = MiniMaxH3TextEncoder()',+ ' keyframe = StubImage("RGB", (2, 2), b"IMAGE-A")',+ ' cold = describe(encoder.encode("a prompt", [keyframe]))',+ ' # A second decode of the same frame, as a re-render would hand it over.',+ ' hit = describe(encoder.encode("a prompt", [StubImage("RGB", (2, 2), b"IMAGE-A")]))',+ ' print(json.dumps({"cold": cold, "hit": hit, "calls": MiniMaxH3TextEncoder.calls,',+ ' "entries": [path.name for path in cache.iterdir()]}))',+ ].join('\n')}`);+ const result = JSON.parse(output.trim().split(/\r?\n/).pop());+ expect(result.hit).toEqual(result.cold);+ expect(result.hit.dtype).toBe('mlx.core.bfloat16');+ // The DiT reads `token_tags` as a numpy ndarray, so a hit has to hand back+ // one rather than the mx.array the entry stores.+ expect(result.hit.tagsDtype).toBe('int64');+ // One encode for two renders.+ expect(result.calls).toEqual([['a prompt', 1]]);+ expect(result.entries).toEqual([expect.stringMatching(/^[0-9a-f]{64}\.safetensors$/)]);+ });++ // The same prompt against a different keyframe is a different request, and+ // serving the first one's embedding would be a silently wrong render.+ it('re-encodes the same prompt when the keyframe changes', () => {+ const output = runPython(`${importRunner}\n${stubEncoder}\n${stubImage}\n${[+ 'import json, mlx.core as mx, numpy as np, tempfile',+ 'sys.stderr = sys.stdout',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' cache = runner.prepare_prompt_embedding_cache(Path(temp) / "embeddings")',+ ' runner.install_prompt_embedding_cache(cache, {"runtime_revision": "rev"})',+ ' encoder = MiniMaxH3TextEncoder()',+ ' encoder.encode("a prompt", [StubImage("RGB", (2, 2), b"IMAGE-A")])',+ ' encoder.encode("a prompt", [StubImage("RGB", (2, 2), b"IMAGE-B")])',+ ' # And text-to-video, which shares neither entry.',+ ' encoder.encode("a prompt")',+ ' print(json.dumps({"calls": len(MiniMaxH3TextEncoder.calls),',+ ' "entries": len(list(cache.iterdir()))}))',+ ].join('\n')}`);+ expect(JSON.parse(output.trim().split(/\r?\n/).pop())).toEqual({ calls: 3, entries: 3 });+ });++ it('discards a truncated entry and recomputes instead of failing the render', () => {+ const output = runPython(`${importRunner}\n${stubEncoder}\n${[+ 'import hashlib, json, mlx.core as mx, numpy as np, tempfile',+ 'sys.stderr = sys.stdout',+ ...describeResult,+ 'with tempfile.TemporaryDirectory() as temp:',+ ' cache = runner.prepare_prompt_embedding_cache(Path(temp) / "embeddings")',+ ' runner.install_prompt_embedding_cache(cache, {"runtime_revision": "rev"})',+ ' encoder = MiniMaxH3TextEncoder()',+ ' cold = describe(encoder.encode("a prompt"))',+ ' entry = next(cache.iterdir())',+ ' entry.write_bytes(entry.read_bytes()[:16])',+ ' recovered = describe(encoder.encode("a prompt"))',+ ' print(json.dumps({"cold": cold, "recovered": recovered,',+ ' "calls": MiniMaxH3TextEncoder.calls,',+ ' "rewritten": entry.stat().st_size > 16}))',+ ].join('\n')}`);+ expect(output).toMatch(/Discarding an unreadable MiniMax H3 prompt-embedding cache entry/);+ const result = JSON.parse(output.trim().split(/\r?\n/).pop());+ expect(result.recovered).toEqual(result.cold);+ expect(result.calls).toHaveLength(2);+ // The bad entry is replaced, not merely skipped, so the next render hits.+ expect(result.rewritten).toBe(true);+ });++ // A cache that stops being writable mid-render still must not cost the+ // render — the embedding is already computed by the time the store fails.+ it.skipIf(process.platform === 'win32')('returns the freshly-encoded embedding when the entry cannot be stored', () => {+ const output = runPython(`${importRunner}\n${stubEncoder}\n${[+ 'import hashlib, json, mlx.core as mx, numpy as np, os, tempfile',+ 'sys.stderr = sys.stdout',+ ...describeResult,+ 'with tempfile.TemporaryDirectory() as temp:',+ ' cache = runner.prepare_prompt_embedding_cache(Path(temp) / "embeddings")',+ ' runner.install_prompt_embedding_cache(cache, {"runtime_revision": "rev"})',+ ' os.chmod(cache, 0o500)',+ ' try:',+ ' result = describe(MiniMaxH3TextEncoder().encode("a prompt"))',+ ' finally:',+ ' os.chmod(cache, 0o700)',+ ' print(json.dumps({"result": result, "entries": [path.name for path in cache.iterdir()]}))',+ ].join('\n')}`);+ expect(output).toMatch(/prompt embedding not cached/);+ const result = JSON.parse(output.trim().split(/\r?\n/).pop());+ expect(result.result.tags).toEqual([0, 1, 0]);+ expect(result.entries).toEqual([]);+ });+ });});diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 66fd9e1a5a..3c81fd75ac 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -3051,6 +3051,40 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {else expect(args).not.toContain('--memory-profile');});+ // Reusable prompt embeddings (#5443). The keying, retention and every+ // degradation path are unit-tested against the runner in+ // scripts/generate_minimax_h3.test.js; what this pins is that the render+ // boundary WIRES the cache at all, and that it stays on the MLX lane — the+ // diffusers CUDA runner has no such flag and would exit on an unknown one.+ it.each([+ ['minimax_h3_8bit', 'generate_minimax_h3.py', true],+ ['minimax_h3_cuda', 'generate_minimax_h3_cuda.py', false],+ ])('gives %s a prompt-embedding cache only where the runner has one', async (modelId, helper, cached) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ // Imported here rather than at the top of the file: this module is vi.mocked+ // above, and a static import would read it before the mock is installed.+ const { MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR } = await import('./runtimes.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();++ await generateVideo({+ jobId: `h3-embed-cache-${modelId}`,+ modelId,+ prompt: 'a fox watches the rain',+ width: 1344, height: 768, numFrames: 124, fps: 24, mode: 'text',+ });++ const [, args] = spawnMock.mock.calls.find(([, childArgs]) => (+ Array.isArray(childArgs) && childArgs.some((arg) => basename(String(arg)) === helper)+ ));+ if (cached) {+ expect(args[args.indexOf('--prompt-embedding-cache-dir') + 1])+ .toBe(MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR);+ } else {+ expect(args).not.toContain('--prompt-embedding-cache-dir');+ }+ });+it('refuses a render this machine cannot hold, before any child is spawned', async () => {const mediaModels = await import('../../lib/mediaModels.js');const { spawnDetached } = await import('../../lib/detachedSpawn.js');diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex da562b6cc3..2235b7475a 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -40,6 +40,7 @@ import {MINIMAX_H3_REPO_DIR,MINIMAX_H3_ENCODER_SHIM_DIR,MINIMAX_H3_DRAFT_DECODER_SHIM_DIR,+ MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR,MINIMAX_H3_EXPECTED_REVISION,MINIMAX_H3_CUDA_VENV_PYTHON,MINIMAX_H3_CUDA_HELPER_SCRIPT,@@ -706,6 +707,12 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF'--seed', String(seed),'--output', outputPath,...miniMaxH3HostMemoryArgs(model),+ // Reusable prompt embeddings (#5443). The runner keys entries on the prompt+ // plus the content digest of each conditioning image, so a re-render of the+ // same request skips the Qwen3-VL conditioning pass while a different image+ // under the same prompt still gets its own. Always passed: an unwritable or+ // corrupt cache degrades to a plain recompute inside the runner.+ '--prompt-embedding-cache-dir', MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR,];// The MLX lane's placement is unified-memory only, so the server picks the// profile and the runner enforces its limit against the machine's own RAM.diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 9dd8e5850e..95ea6d005c 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -71,6 +71,14 @@ export const MINIMAX_H3_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h// directory so removing one substitution never disturbs the other.export const MINIMAX_H3_DRAFT_DECODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h3-decoder-shims');+// Reusable Qwen3-VL prompt embeddings (#5443). The MLX runner keys each entry+// on the prompt text plus the CONTENT digest of every conditioning image and+// holds the directory under its own byte ceiling, so this is a plain cache the+// user can delete at any time. Outside MINIMAX_H3_REPO_DIR for the same reason+// the shim roots are: a file written inside the checkout reads as untracked in+// the pin verification /status and the render helper both run.+export const MINIMAX_H3_PROMPT_EMBEDDING_CACHE_DIR = join(homedir(), '.portos', 'minimax-h3-prompt-embeddings');+// MiniMax H3 on CUDA — the diffusers `MiniMaxH3ModularPipeline` rather than a// pinned source checkout, so this runtime is a plain pip venv with no revision// to verify and no source package to keep clean.