Skip to content

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

perf: cap the MLX allocator cache for the whole LTX2 render, reasserted per render (#5421)

[._.]/ Adam Eivyf174689dafad
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index f30e6498cd..2da013308c 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -715,6 +715,11 @@ def parse_args() -> argparse.Namespace:
"relaunch after the macOS Metal command-buffer watchdog aborts "
"the prompt encoder. An explicit value always wins over the "
"ambient environment.")
+ p.add_argument("--mlx-cache-limit-mb", default=None,
+ help="Cap the MLX allocator cache at this many MB for the whole run, "
+ "reasserted before every render. Omit to derive a conservative "
+ "ceiling from physical memory. PORTOS_MLX_CACHE_LIMIT_MB sets the "
+ "same knob ambiently; this flag wins over it.")
return p.parse_args()
@@ -1082,6 +1087,10 @@ def _install_ltx_stepwise_preview(pipe, args: argparse.Namespace):
def _run_with_ltx_stepwise_preview(pipe, args: argparse.Namespace, render):
+ # Every mode routes its render through here, so this is where the allocator
+ # cache ceiling is reasserted: loading weights resets it, and a two-stage or
+ # chained job renders more than once inside one process.
+ apply_mlx_cache_policy(_MLX_CACHE_POLICY)
restore = _install_ltx_stepwise_preview(pipe, args)
try:
return render()
@@ -1667,6 +1676,165 @@ def maybe_strip_audio(output_path: str) -> None:
emit_status(f"ffmpeg audio-strip skipped: {e}")
+# MLX keeps freed Metal buffers in an allocator cache so the next allocation of
+# that size is free. Left uncapped, that cache competes with the LIVE tensors of
+# a long video render: a 22B DiT plus a decode pass can push the machine into
+# swap (or a Metal OOM abort) purely because the allocator is still holding
+# buffers this render no longer needs. Capping it costs a little allocation
+# throughput and buys headroom, so PortOS derives a conservative ceiling from
+# physical memory and reasserts it before every render.
+#
+# The ceiling is a fixed fraction of physical memory clamped at both ends: the
+# floor keeps a small machine from thrashing against a near-zero cache, the cap
+# keeps a very large machine from parking tens of GB in the allocator "just in
+# case". 1/8 of RAM lands at 2 GB on a 16 GB box, 8 GB on a 64 GB box, and hits
+# the cap at 96 GB.
+MLX_CACHE_FRACTION = 0.125
+MLX_CACHE_FLOOR_MB = 1024
+MLX_CACHE_CEILING_MB = 12288
+MLX_CACHE_LIMIT_ENV = "PORTOS_MLX_CACHE_LIMIT_MB"
+
+_MLX_CACHE_POLICY: dict = {}
+
+
+def derive_mlx_cache_limit_mb(physical_bytes) -> int | None:
+ """Conservative allocator-cache ceiling in MB for a machine that size.
+
+ Pure — no MLX, no environment, no I/O. Returns None when the caller could
+ not determine physical memory; resolve_mlx_cache_policy turns that into "no
+ policy" rather than a guess.
+ """
+ if isinstance(physical_bytes, bool) or not isinstance(physical_bytes, (int, float)):
+ return None
+ if physical_bytes <= 0:
+ return None
+ derived = int(physical_bytes * MLX_CACHE_FRACTION) // (1024 * 1024)
+ return max(MLX_CACHE_FLOOR_MB, min(MLX_CACHE_CEILING_MB, derived))
+
+
+def validate_mlx_cache_limit_mb(raw, source: str) -> int | None:
+ """Parse an explicit cache-limit override in MB; None when unset.
+
+ An override REPLACES the derived ceiling rather than being clamped into it —
+ a caller naming a number knows this machine better than a blanket fraction
+ does — so validation only rejects values that cannot mean anything. A bad
+ value is fatal rather than ignored: falling back to the derived ceiling
+ would report a policy the caller never asked for.
+ """
+ if raw is None or raw == "":
+ return None
+ try:
+ limit = int(str(raw).strip())
+ except ValueError:
+ limit = 0
+ if limit < 1:
+ raise SystemExit(f"{source} must be a positive whole number of MB; got {raw!r}.")
+ return limit
+
+
+def physical_memory_bytes() -> int | None:
+ """Total physical RAM in bytes, or None where the platform will not say.
+
+ Windows has no ``os.sysconf``; the helper is import-safe there and simply
+ reports "unknown", which is also what the LTX runtime itself is on that OS.
+ """
+ sysconf = getattr(os, "sysconf", None)
+ names = getattr(os, "sysconf_names", {})
+ if sysconf is None or "SC_PHYS_PAGES" not in names or "SC_PAGE_SIZE" not in names:
+ return None
+ try:
+ total = sysconf("SC_PHYS_PAGES") * sysconf("SC_PAGE_SIZE")
+ except (OSError, ValueError): # pragma: no cover - platform dependent
+ return None
+ return total if total > 0 else None
+
+
+def resolve_mlx_cache_policy(physical_bytes, override_raw=None, env_raw=None) -> dict:
+ """Effective cache policy as ``{"limitMb": int | None, "source": str}``.
+
+ Precedence mirrors --gemma-max-length: an explicit flag beats the ambient
+ environment, which beats the ceiling derived from physical memory. A machine
+ whose memory could not be read gets ``limitMb: None`` and MLX's own default
+ stands — a blind floor would throttle a large box exactly as readily as it
+ would protect a small one.
+ """
+ override = validate_mlx_cache_limit_mb(override_raw, "--mlx-cache-limit-mb")
+ if override is not None:
+ return {"limitMb": override, "source": "flag"}
+ ambient = validate_mlx_cache_limit_mb(env_raw, MLX_CACHE_LIMIT_ENV)
+ if ambient is not None:
+ return {"limitMb": ambient, "source": "env"}
+ derived = derive_mlx_cache_limit_mb(physical_bytes)
+ if derived is None:
+ return {"limitMb": None, "source": "unknown-memory"}
+ return {"limitMb": derived, "source": "derived"}
+
+
+def _mlx_cache_limit_setter():
+ """The installed MLX's cache-limit entry point, or None when it has none.
+
+ Probed rather than assumed, the same shape as _resolve_pipeline: the API
+ moved from ``mx.metal.set_cache_limit`` to ``mx.set_cache_limit`` and the
+ legacy spelling is deprecated on new wheels, while installs upgrade on their
+ own schedule. New name first, legacy second.
+ """
+ try:
+ import mlx.core as mx
+ except Exception:
+ return None
+ setter = getattr(mx, "set_cache_limit", None)
+ if callable(setter):
+ return setter
+ setter = getattr(getattr(mx, "metal", None), "set_cache_limit", None)
+ return setter if callable(setter) else None
+
+
+def apply_mlx_cache_policy(policy: dict, announce: bool = False) -> bool:
+ """Push `policy` at the installed MLX. True when the limit actually took.
+
+ Called before pipeline construction and again before every render: loading
+ weights (and some pins' own setup) resets the allocator limit, so a
+ once-at-startup cap quietly stops holding partway through a long job. Only
+ the startup call announces — a per-render status line would be noise.
+ """
+ limit_mb = (policy or {}).get("limitMb")
+ if limit_mb is None:
+ if announce:
+ emit_status("MLX allocator cache left at its default — physical memory unknown")
+ return False
+ setter = _mlx_cache_limit_setter()
+ if setter is None:
+ if announce:
+ emit_status("Installed MLX exposes no cache-limit API — allocator cache left at its default")
+ return False
+ try:
+ setter(limit_mb * 1024 * 1024)
+ except Exception as err:
+ if announce:
+ emit_status(f"MLX allocator cache could not be capped ({err}) — left at its default")
+ return False
+ if announce:
+ emit_status(f"MLX allocator cache capped at {limit_mb} MB ({policy.get('source')})")
+ return True
+
+
+def configure_mlx_cache(args: argparse.Namespace) -> dict:
+ """Resolve this run's allocator-cache ceiling and install it. Returns the policy.
+
+ Called once before any pipeline is constructed — the first weight load is
+ already large enough to strand buffers in the cache for the rest of the run.
+ _run_with_ltx_stepwise_preview reasserts the same policy per render.
+ """
+ global _MLX_CACHE_POLICY
+ _MLX_CACHE_POLICY = resolve_mlx_cache_policy(
+ physical_memory_bytes(),
+ args.mlx_cache_limit_mb,
+ os.environ.get(MLX_CACHE_LIMIT_ENV),
+ )
+ apply_mlx_cache_policy(_MLX_CACHE_POLICY, announce=True)
+ return _MLX_CACHE_POLICY
+
+
def main() -> NoReturn:
args = parse_args()
validate_text_encoder_args(args)
@@ -1696,6 +1864,7 @@ def main() -> NoReturn:
configure_negative_prompt(args.negative_prompt)
configure_gemma_max_length(args.gemma_max_length)
install_prompt_encode_markers()
+ configure_mlx_cache(args)
runners = {
"text": run_text,
diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.js
index 326543515f..3a6e350328 100644
--- a/scripts/generate_ltx2.test.js
+++ b/scripts/generate_ltx2.test.js
@@ -803,3 +803,228 @@ describe.skipIf(!pyBin)('generate_ltx2.py speed-profile reporting', () => {
expect(outLines(out)).toEqual(expected);
});
});
+
+// The allocator-cache ceiling is what keeps MLX's freed-buffer cache from
+// competing with a long render's live tensors. Every case here runs against the
+// module's own helpers rather than a real MLX: the policy has to be right on a
+// machine size the test host does not have, and the "installed MLX has no such
+// API" branch cannot be produced by an install that does.
+describe.skipIf(!pyBin)('generate_ltx2.py MLX allocator-cache policy', () => {
+ const GB = 1024 * 1024 * 1024;
+ const runJson = (body) => JSON.parse(runPython(`${importRunner}\n${body.join('\n')}`));
+
+ // A fake mlx.core planted in sys.modules, so the probe sees exactly the API
+ // surface each case is about — and never the host's real wheel.
+ const fakeMlx = (attrs) => [
+ 'import sys, types',
+ 'CALLS = []',
+ 'core = types.ModuleType("mlx.core")',
+ ...attrs,
+ 'pkg = types.ModuleType("mlx")',
+ 'pkg.core = core',
+ 'sys.modules["mlx"] = pkg',
+ 'sys.modules["mlx.core"] = core',
+ ];
+ const MODERN_MLX = fakeMlx(['core.set_cache_limit = lambda n: CALLS.append(("modern", n))']);
+ const LEGACY_MLX = fakeMlx([
+ 'core.metal = types.SimpleNamespace(set_cache_limit=lambda n: CALLS.append(("legacy", n)))',
+ ]);
+ const NO_CACHE_API = fakeMlx(['core.metal = types.SimpleNamespace()']);
+ // A venv with no MLX at all reaches the same branch through the import.
+ const NO_MLX = ['import sys', 'sys.modules["mlx"] = None', 'sys.modules.pop("mlx.core", None)'];
+
+ it.each([
+ // Under the floor a proportional cap would leave the allocator thrashing,
+ // so a small machine still gets the 1 GB floor rather than 512 MB.
+ ['a machine below the floor', 4 * GB, 1024],
+ ['a 16 GB machine', 16 * GB, 2048],
+ ['a 64 GB machine', 64 * GB, 8192],
+ // 1/8 hits the ceiling exactly at 96 GB; past it the cap holds, so a very
+ // large box does not park tens of GB in the cache "just in case".
+ ['the machine where the ceiling starts biting', 96 * GB, 12288],
+ ['a 512 GB machine', 512 * GB, 12288],
+ ])('derives a bounded ceiling for %s', (_label, bytes, expected) => {
+ const result = runJson([
+ 'import json',
+ `print(json.dumps(runner.derive_mlx_cache_limit_mb(${bytes})))`,
+ ]);
+ expect(result).toBe(expected);
+ });
+
+ // An unreadable machine gets NO policy rather than the floor: a blind 1 GB
+ // cap would throttle a large box exactly as readily as it protects a small
+ // one, and MLX's own default is the known-safe behavior.
+ it.each([['unknown', 'None'], ['zero', '0'], ['negative', '-1'], ['non-numeric', '"lots"']])(
+ 'derives no ceiling from %s physical memory',
+ (_label, expr) => {
+ const result = runJson(['import json', `print(json.dumps(runner.derive_mlx_cache_limit_mb(${expr})))`]);
+ expect(result).toBeNull();
+ },
+ );
+
+ it('prefers an explicit flag over the environment, and both over the derived ceiling', () => {
+ const result = runJson([
+ 'import json',
+ 'physical = 64 * 1024 ** 3',
+ 'print(json.dumps({',
+ ' "flag": runner.resolve_mlx_cache_policy(physical, "2048", "3072"),',
+ ' "env": runner.resolve_mlx_cache_policy(physical, None, "3072"),',
+ ' "derived": runner.resolve_mlx_cache_policy(physical, None, None),',
+ ' "unknown": runner.resolve_mlx_cache_policy(None, None, None),',
+ '}))',
+ ]);
+ // An override REPLACES the derived ceiling — 2048 is below what a 64 GB box
+ // would derive, and it still wins.
+ expect(result.flag).toEqual({ limitMb: 2048, source: 'flag' });
+ expect(result.env).toEqual({ limitMb: 3072, source: 'env' });
+ expect(result.derived).toEqual({ limitMb: 8192, source: 'derived' });
+ expect(result.unknown).toEqual({ limitMb: null, source: 'unknown-memory' });
+ });
+
+ // Silently ignoring a bad override would report a ceiling the caller never
+ // asked for, which is worse than refusing the run.
+ it.each([
+ ['a word', '"lots"', /--mlx-cache-limit-mb must be a positive whole number/],
+ ['zero', '"0"', /--mlx-cache-limit-mb must be a positive whole number/],
+ ['a negative count', '"-512"', /--mlx-cache-limit-mb must be a positive whole number/],
+ ['a fraction', '"2048.5"', /--mlx-cache-limit-mb must be a positive whole number/],
+ ])('rejects %s as an override', (_label, expr, pattern) => {
+ const output = runPython(`${importRunner}\n${[
+ 'try:',
+ ` runner.resolve_mlx_cache_policy(64 * 1024 ** 3, ${expr}, None)`,
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("a bad cache-limit override was accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(pattern);
+ });
+
+ it('rejects a bad ambient override by its environment-variable name', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'try:',
+ ' runner.resolve_mlx_cache_policy(64 * 1024 ** 3, None, "not-a-number")',
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("a bad ambient cache limit was accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(/PORTOS_MLX_CACHE_LIMIT_MB must be a positive whole number/);
+ });
+
+ it.each([
+ ['the modern spelling', MODERN_MLX, 'modern'],
+ // A pin predating the move still has to be capped, so the legacy spelling
+ // is probed rather than assumed gone.
+ ['the legacy mx.metal spelling', LEGACY_MLX, 'legacy'],
+ ])('applies the limit through %s', (_label, mlx, expectedSpelling) => {
+ const result = runJson([
+ ...mlx,
+ 'import json',
+ 'applied = runner.apply_mlx_cache_policy({"limitMb": 2048, "source": "flag"})',
+ 'print(json.dumps({"applied": applied, "calls": CALLS}))',
+ ]);
+ expect(result.applied).toBe(true);
+ // MB in the policy, BYTES at the MLX boundary.
+ expect(result.calls).toEqual([[expectedSpelling, 2048 * 1024 * 1024]]);
+ });
+
+ it.each([
+ ['exposes no cache-limit API', NO_CACHE_API],
+ ['is not installed at all', NO_MLX],
+ ])('degrades with a status line when the MLX %s', (_label, mlx) => {
+ const result = runJson([
+ ...mlx,
+ 'import contextlib, io, json',
+ 'err = io.StringIO()',
+ 'with contextlib.redirect_stderr(err):',
+ ' applied = runner.apply_mlx_cache_policy({"limitMb": 2048, "source": "flag"}, announce=True)',
+ 'print(json.dumps({"applied": applied, "stderr": err.getvalue()}))',
+ ]);
+ expect(result.applied).toBe(false);
+ expect(result.stderr).toMatch(/^STATUS:Installed MLX exposes no cache-limit API/);
+ });
+
+ it('reports the effective policy on the existing STATUS channel', () => {
+ const result = runJson([
+ ...MODERN_MLX,
+ 'import contextlib, io, json',
+ 'err = io.StringIO()',
+ 'with contextlib.redirect_stderr(err):',
+ ' runner.apply_mlx_cache_policy({"limitMb": 8192, "source": "derived"}, announce=True)',
+ ' runner.apply_mlx_cache_policy({"limitMb": None, "source": "unknown-memory"}, announce=True)',
+ 'print(json.dumps({"stderr": err.getvalue()}))',
+ ]);
+ expect(result.stderr.split(/\r?\n/).filter(Boolean)).toEqual([
+ 'STATUS:MLX allocator cache capped at 8192 MB (derived)',
+ 'STATUS:MLX allocator cache left at its default — physical memory unknown',
+ ]);
+ });
+
+ // Loading weights resets the allocator limit, and a two-stage or chained job
+ // renders more than once inside one process — so the cap has to be reasserted
+ // per render, not just at startup.
+ it('reasserts the ceiling before every render', () => {
+ const result = runJson([
+ ...MODERN_MLX,
+ 'import json',
+ 'from types import SimpleNamespace',
+ 'runner._MLX_CACHE_POLICY = {"limitMb": 4096, "source": "flag"}',
+ 'runner._install_ltx_stepwise_preview = lambda pipe, args: (lambda: None)',
+ 'rendered = []',
+ 'for _ in range(3):',
+ ' runner._run_with_ltx_stepwise_preview(object(), SimpleNamespace(), lambda: rendered.append(1))',
+ 'print(json.dumps({"renders": len(rendered), "calls": CALLS}))',
+ ]);
+ expect(result.renders).toBe(3);
+ expect(result.calls).toEqual(Array.from({ length: 3 }, () => ['modern', 4096 * 1024 * 1024]));
+ });
+
+ // The reassertion must never be what fails a render: an MLX that raises from
+ // the setter still lets the render proceed uncapped.
+ it('lets the render proceed when the MLX setter raises', () => {
+ const result = runJson([
+ ...fakeMlx(['def boom(_n): raise RuntimeError("metal is busy")', 'core.set_cache_limit = boom']),
+ 'import contextlib, io, json',
+ 'err = io.StringIO()',
+ 'with contextlib.redirect_stderr(err):',
+ ' applied = runner.apply_mlx_cache_policy({"limitMb": 2048, "source": "flag"}, announce=True)',
+ 'print(json.dumps({"applied": applied, "stderr": err.getvalue()}))',
+ ]);
+ expect(result.applied).toBe(false);
+ expect(result.stderr).toMatch(/metal is busy/);
+ });
+
+ // The startup call and the per-render reassertion have to read the SAME
+ // policy, so the one main() installs is the one the render path picks up.
+ it('installs the run policy the render path then reasserts', () => {
+ const result = runJson([
+ ...MODERN_MLX,
+ 'import json',
+ 'from types import SimpleNamespace',
+ 'policy = runner.configure_mlx_cache(SimpleNamespace(mlx_cache_limit_mb="2048"))',
+ 'runner._install_ltx_stepwise_preview = lambda pipe, args: (lambda: None)',
+ 'runner._run_with_ltx_stepwise_preview(object(), SimpleNamespace(), lambda: None)',
+ 'print(json.dumps({"policy": policy, "stored": runner._MLX_CACHE_POLICY, "calls": CALLS}))',
+ ]);
+ expect(result.policy).toEqual({ limitMb: 2048, source: 'flag' });
+ expect(result.stored).toEqual(result.policy);
+ // Once at startup, once more for the render.
+ expect(result.calls).toEqual([
+ ['modern', 2048 * 1024 * 1024],
+ ['modern', 2048 * 1024 * 1024],
+ ]);
+ });
+
+ it('parses the override flag and defaults it to absent', () => {
+ const out = runPython(`${importRunner}\n${[
+ 'import sys',
+ 'base = ["generate_ltx2.py", "--mode", "text", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m"]',
+ 'sys.argv = base',
+ 'print(runner.parse_args().mlx_cache_limit_mb)',
+ 'sys.argv = base + ["--mlx-cache-limit-mb", "2048"]',
+ 'print(runner.parse_args().mlx_cache_limit_mb)',
+ ].join('\n')}`);
+ expect(out.trim().split(/\r?\n/).map((l) => l.trimEnd())).toEqual(['None', '2048']);
+ });
+});