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

fix: mitigate MLX video GPU watchdogs (#5553)

[._.]/ Adam Eivydfa31570774f
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 7421660ae0..fe302282b9 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -110,6 +110,7 @@ export function ImageGenTab() {
// never rendered, only round-tripped at save time so sibling keys
// (defaultModelId) survive the settings PUT's wholesale slice replace.
const [videoGenMode, setVideoGenMode] = useState('');
+ const [videoGenDisplaySleep, setVideoGenDisplaySleep] = useState(true);
const videoGenSliceRef = useRef({});
const [sdapiUrl, setSdapiUrl] = useState('');
const [pythonPath, setPythonPath] = useState('');
@@ -174,6 +175,7 @@ export function ImageGenTab() {
denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false },
renderDefaultsJson: '{}',
videoGenMode: '',
+ videoGenDisplaySleep: true,
});
const [status, setStatus] = useState(null);
@@ -245,6 +247,7 @@ export function ImageGenTab() {
// ('auto'/blank → '', i.e. no pin) for the select.
const vg = (s?.videoGen && typeof s.videoGen === 'object') ? s.videoGen : {};
const vgMode = normalizeRenderPinValue(vg.mode) || '';
+ const vgDisplaySleep = vg.displaySleep !== false;
const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;
const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);
const py = ig.local?.pythonPath || '';
@@ -279,6 +282,7 @@ export function ImageGenTab() {
setMode(m);
setRenderDefaults(rd);
setVideoGenMode(vgMode);
+ setVideoGenDisplaySleep(vgDisplaySleep);
videoGenSliceRef.current = vg;
setSdapiUrl(url);
setPythonPath(py);
@@ -306,6 +310,7 @@ export function ImageGenTab() {
cleanC2PAByMode: c2, denoiseByMode: dn,
renderDefaultsJson: JSON.stringify(rd),
videoGenMode: vgMode,
+ videoGenDisplaySleep: vgDisplaySleep,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -396,7 +401,8 @@ export function ImageGenTab() {
|| denoiseByMode.local !== saved.denoiseByMode.local
|| denoiseByMode.external !== saved.denoiseByMode.external
|| JSON.stringify(renderDefaults) !== saved.renderDefaultsJson
- || videoGenMode !== saved.videoGenMode;
+ || videoGenMode !== saved.videoGenMode
+ || videoGenDisplaySleep !== saved.videoGenDisplaySleep;
const handleSave = async () => {
setSaving(true);
@@ -441,7 +447,7 @@ export function ImageGenTab() {
),
// Install-wide video pin (#3231 Phase 4). Spread over the loaded slice so
// sibling keys (defaultModelId) survive the wholesale slice replace.
- videoGen: { ...videoGenSliceRef.current, mode: videoGenMode || null },
+ videoGen: { ...videoGenSliceRef.current, mode: videoGenMode || null, displaySleep: videoGenDisplaySleep },
};
try {
await updateSettings(patch, { silent: true });
@@ -458,6 +464,7 @@ export function ImageGenTab() {
cleanC2PAByMode, denoiseByMode,
renderDefaultsJson: JSON.stringify(patch.renderDefaults),
videoGenMode,
+ videoGenDisplaySleep,
});
// Reflect the pruned no-op entries back into the editor state so the
// dirty check compares like against like after a save.
@@ -749,6 +756,18 @@ export function ImageGenTab() {
</select>
</FormField>
</div>
+ <label className="flex items-start gap-3 border border-port-border rounded-lg px-3 py-3 text-sm text-gray-300 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={videoGenDisplaySleep}
+ onChange={(e) => setVideoGenDisplaySleep(e.target.checked)}
+ className="mt-0.5 accent-port-accent"
+ />
+ <span>
+ <span className="block font-medium text-white">Sleep display during local MLX video renders</span>
+ <span className="block text-xs text-gray-500 mt-0.5">Keeps the system awake while reducing WindowServer GPU contention on affected Apple silicon. Turn off only when another headless workflow manages display power.</span>
+ </span>
+ </label>
<div className="space-y-3">
{RENDER_TARGET_OPTIONS.map(({ id, label, video }) => {
const entry = renderDefaults[id] || {};
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 462d40b6fc..1644e91f04 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -244,7 +244,7 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(updateSettings).toHaveBeenCalled());
const patch = updateSettings.mock.calls[0][0];
- expect(patch.videoGen).toEqual({ mode: 'local', defaultModelId: 'ltx23_distilled_q4' });
+ expect(patch.videoGen).toEqual({ mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: true });
});
});
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index a54fee9260..839b66bb69 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -430,7 +430,8 @@ silicon to the full `watchdogd` kernel panic above; and a separate IOGPU
memory-management panic ([mlx #3186](https://github.com/ml-explore/mlx/issues/3186),
filed with Apple as FB22091885). The MLX maintainer's confirmed workaround is the
`AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` env var — **PortOS now sets this automatically**
-for the trainer (`scripts/train_mflux_lora.py`). Note per #3267 the kill is at the
+for the trainer and FastVideo MLX runner (`scripts/train_mflux_lora.py`,
+`scripts/generate_fastvideo.py`). Note per #3267 the kill is at the
IOGPU layer *above* the process boundary, so process-teardown segmentation alone
does not prevent it; the env var attacks the actual cause.
@@ -462,6 +463,10 @@ to protect and largely stops firing.
maintainer-confirmed workaround for mlx #3267); the run log shows
`STATUS:watchdog mitigation · AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` so a paniclog
records whether it was active. Set it to `0` in the environment to disable.
+- Video Gen sleeps the display automatically for local MLX runtimes (FastVideo,
+ Wan 2.2, MiniMax H3, and LTX) while keeping the system awake. This is on by
+ default; disable **Sleep display during local MLX video renders** in Settings
+ > Image Gen > Defaults only when another headless workflow manages it.
- The mlx/mlx-metal backend is pinned to the validated 0.31.2 trio in
`scripts/setup-image-video.sh` (the original panics were on 0.30.6).
- Training checkpoints at least every `ceil(totalSteps/4)` steps
diff --git a/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.py
index 44efaf389d..678a87806a 100755
--- a/scripts/generate_fastvideo.py
+++ b/scripts/generate_fastvideo.py
@@ -126,6 +126,15 @@ def main() -> int:
env = os.environ.copy()
env["PYTHONPATH"] = f"{str(repo_dir)}:{env.get('PYTHONPATH', '')}".rstrip(":")
+ # Mirrors train_mflux_lora.py's M5 Metal-watchdog mitigation. Preserve an
+ # explicit caller override, but make the validated safe value the default
+ # for the sustained FastMetal denoise child.
+ env.setdefault("AGX_RELAX_CDM_CTXSTORE_TIMEOUT", "1")
+ print(
+ f"STATUS:watchdog mitigation · AGX_RELAX_CDM_CTXSTORE_TIMEOUT={env['AGX_RELAX_CDM_CTXSTORE_TIMEOUT']}",
+ file=sys.stderr,
+ flush=True,
+ )
proc = subprocess.Popen(
cmd,
diff --git a/server/lib/validation.js b/server/lib/validation.js
index eb2205df6c..f042345ac3 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1817,6 +1817,9 @@ export const renderDefaultsSettingsSchema = z.object(
export const videoGenSettingsSchema = z.object({
mode: videoModePinSchema,
defaultModelId: z.preprocess(emptyToNull, z.string().trim().max(64).nullable().optional()),
+ // Default-on macOS GPU-watchdog mitigation for sustained MLX video renders.
+ // Set false for a headless display workflow that manages display power itself.
+ displaySleep: z.boolean().optional(),
// Install-wide acknowledgement of restricted-model license gates, stored as
// the exact reviewed-license ids (`termsGate.id`). Written through
// POST /api/video-gen/model-terms; typed here so a Settings save can't put
diff --git a/server/services/displayPower.js b/server/services/displayPower.js
new file mode 100644
index 0000000000..1ca01c7b9e
--- /dev/null
+++ b/server/services/displayPower.js
@@ -0,0 +1,34 @@
+/**
+ * Best-effort macOS display power controls for sustained GPU work.
+ *
+ * Sleeping the display stops WindowServer from competing with Metal command
+ * buffers on affected Apple silicon. These helpers deliberately take a
+ * settings slice so each long-running workload can expose its own opt-out.
+ */
+import { spawn } from '../lib/childProcess.js';
+import { platform } from 'os';
+
+export const isDisplaySleepEnabled = (settings) => (
+ platform() === 'darwin' && settings?.displaySleep !== false
+);
+
+function runPowerCmd(cmd, args) {
+ const proc = spawn(cmd, args, { stdio: 'ignore' });
+ proc.on('error', () => {});
+ proc.unref();
+ return proc;
+}
+
+export function sleepDisplay(settings, workload) {
+ if (!isDisplaySleepEnabled(settings)) return false;
+ runPowerCmd('pmset', ['displaysleepnow']);
+ console.log(`🌙 ${workload}: slept the display to avoid the GPU-watchdog panic (mlx #3267)`);
+ return true;
+}
+
+export function wakeDisplay(settings, workload) {
+ if (!isDisplaySleepEnabled(settings)) return false;
+ runPowerCmd('caffeinate', ['-u', '-t', '5']);
+ console.log(`☀️ ${workload} finished: woke the display`);
+ return true;
+}
diff --git a/server/services/loraTraining/displayPower.js b/server/services/loraTraining/displayPower.js
index 1f8c1c47e4..45e4059ee5 100644
--- a/server/services/loraTraining/displayPower.js
+++ b/server/services/loraTraining/displayPower.js
@@ -17,41 +17,28 @@
* lifecycle), so per the repo convention the spawn boundary is wrapped and never
* throws into the event loop.
*/
-import { spawn } from '../../lib/childProcess.js';
-import { platform } from 'os';
+import {
+ isDisplaySleepEnabled as sharedDisplaySleepEnabled,
+ sleepDisplay,
+ wakeDisplay as sharedWakeDisplay,
+} from '../displayPower.js';
// Whether auto display-sleep is enabled for this host. Apple Silicon only (the
// panic is macOS-specific) and opt-out via settings.loraTraining.displaySleep.
export function isDisplaySleepEnabled(settings) {
- return platform() === 'darwin' && settings?.loraTraining?.displaySleep !== false;
-}
-
-// Best-effort spawn of a short macOS power command. Detached + unref'd so it
-// can't block or outlive its purpose; errors are swallowed (telemetry-grade,
-// never fatal to a training run).
-function runPowerCmd(cmd, args) {
- const proc = spawn(cmd, args, { stdio: 'ignore' });
- proc.on('error', () => {}); // command missing / not permitted → ignore
- proc.unref();
- return proc;
+ return sharedDisplaySleepEnabled(settings?.loraTraining);
}
// Sleep the display now (the system stays awake — the trainer's `caffeinate -is`
// holds idle/system sleep off; only the *display* goes dark so WindowServer
// stops contending for the GPU). No-op off darwin or when disabled.
export function sleepDisplayForTraining(settings) {
- if (!isDisplaySleepEnabled(settings)) return false;
- runPowerCmd('pmset', ['displaysleepnow']);
- console.log('🌙 LoRA training: slept the display to avoid the GPU-watchdog panic (mlx #3267)');
- return true;
+ return sleepDisplay(settings?.loraTraining, 'LoRA training');
}
// Wake the display so the user sees the finished run. `caffeinate -u` asserts
// user activity for a few seconds, which lights the panel back up. Gated the
// same way as sleep so we don't wake a display we never slept.
export function wakeDisplay(settings) {
- if (!isDisplaySleepEnabled(settings)) return false;
- runPowerCmd('caffeinate', ['-u', '-t', '5']);
- console.log('☀️ LoRA training finished: woke the display');
- return true;
+ return sharedWakeDisplay(settings?.loraTraining, 'LoRA training');
}
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 51e4760f0b..e0d307f7e4 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -52,6 +52,7 @@ import {
byovRuntimeExpectedRevision,
isByovRuntimeCurrent,
} from './runtimes.js';
+import { getSettings } from '../settings.js';
import { loadHistory, saveHistory, mutateVideoHistory, getHistoryItem } from './history.js';
import { VIDEO_MODE_GATED_RUNTIMES } from './modeContract.js';
import { videoJobState } from './jobState.js';
@@ -895,6 +896,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
height: h,
numFrames: parsedNumFrames,
steps: actualSteps,
+ videoGenSettings: (await getSettings())?.videoGen,
});
return { jobId, generationId: jobId, filename, mode: 'local', model: modelId };
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 3a6d1bfcdd..824f933bc6 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -329,6 +329,14 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(Object.keys(BYOV_RUNTIME_INFO)));
+// Only these BYOV runtimes drive MLX/Metal on macOS. Keep this execution fact
+// here with the runtime registry, rather than teaching each spawn site which
+// model names need the M5 GPU-watchdog mitigation.
+export const BYOV_MLX_VIDEO_RUNTIMES = Object.freeze(new Set([
+ 'wan22', 'ltx2', 'ltx25', 'fastvideo', 'minimax_h3',
+]));
+export const runtimeUsesMlx = (runtime) => BYOV_MLX_VIDEO_RUNTIMES.has(runtime);
+
// Per-runtime EXECUTION facts, read off the registry rather than re-derived from
// a runtime id at the spawn site. Both are "key absent means off", the same
// convention `loraProbeArgs` / `expectedRevision` already use here — so the next
diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.js
index a96a68e430..12628d2599 100644
--- a/server/services/videoGen/runtimes.test.js
+++ b/server/services/videoGen/runtimes.test.js
@@ -23,7 +23,7 @@ import {
BYOV_RUNTIME_INFO, BYOV_VIDEO_RUNTIMES, MINIMAX_H3_CUDA_OFFLOAD_PROFILES,
byovRuntimeLoraCapable, invalidateByovLoraCapabilityCache, invalidateByovReadyCache,
isByovRuntimeCurrent, isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,
- resolveByovRuntimeLoraCapable, runtimeIsCacheOnly, runtimeNeedsProcessGroupKill,
+ resolveByovRuntimeLoraCapable, runtimeIsCacheOnly, runtimeNeedsProcessGroupKill, runtimeUsesMlx,
routesToWindowsHelper, LTX25_EXPECTED_REVISION,
} from './runtimes.js';
@@ -495,6 +495,15 @@ describe('runtime execution flags', () => {
expect(runtimeNeedsProcessGroupKill('ltx2')).toBe(false);
expect(runtimeNeedsProcessGroupKill('nope')).toBe(false);
});
+
+ it('identifies exactly the Apple MLX runners that need display-watchdog mitigation', () => {
+ for (const runtime of ['wan22', 'ltx2', 'ltx25', 'fastvideo', 'minimax_h3']) {
+ expect(runtimeUsesMlx(runtime)).toBe(true);
+ }
+ for (const runtime of ['wan22_cuda', 'ltx25_cuda', 'minimax_h3_cuda', 'nope', undefined]) {
+ expect(runtimeUsesMlx(runtime)).toBe(false);
+ }
+ });
});
// A pin bump is where the frame-one anchor silently breaks: the LTX-2.5 fork
diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.js
index d67497f456..fdc024e829 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -28,9 +28,11 @@ import {
BYOV_RUNTIME_INFO,
runtimeIsCacheOnly,
runtimeNeedsProcessGroupKill,
+ runtimeUsesMlx,
invalidateByovReadyCache,
pickDeathFingerprint,
} from './runtimes.js';
+import { sleepDisplay, wakeDisplay } from '../displayPower.js';
import { loadHistory, mutateVideoHistory } from './history.js';
import { estimateRenderMs } from './eta.js';
import { videoJobState } from './jobState.js';
@@ -63,6 +65,7 @@ export async function spawnAndWatchVideo({
height: h,
numFrames: parsedNumFrames,
steps: actualSteps,
+ videoGenSettings,
}) {
const heavyClaim = await claimHeavyLocalJob({ kind: 'local video generation', id: jobId });
if (!heavyClaim.ok) {
@@ -192,8 +195,15 @@ export async function spawnAndWatchVideo({
// from the Apple menu. `-w` makes caffeinate self-exit when our pid does, so
// no manual cleanup is needed and a server crash mid-render still releases
// the assertion. macOS-only — `caffeinate` is a darwin binary.
+ const sleepDisplayForRender = runtimeUsesMlx(model.runtime) && videoGenSettings?.displaySleep !== false;
+ let displaySlept = false;
if (process.platform === 'darwin' && proc.pid) {
- spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});
+ // MLX renders must keep the system awake but let the display sleep: `-d`
+ // forces WindowServer to contend with Metal and can trigger the M5 GPU
+ // watchdog. Other runtimes keep their existing display-awake behavior.
+ const caffeineArgs = sleepDisplayForRender ? ['-is', '-w', String(proc.pid)] : ['-dis', '-w', String(proc.pid)];
+ spawn('caffeinate', caffeineArgs, { stdio: 'ignore', detached: false }).on('error', () => {});
+ displaySlept = sleepDisplayForRender && sleepDisplay(videoGenSettings, 'Video generation');
}
// Guards the ONE terminal run of this child's teardown, across BOTH terminal
// paths ('error' and 'close'). The caller may have to replay a terminal
@@ -215,6 +225,7 @@ export async function spawnAndWatchVideo({
broadcastSse(job, { type: 'error', error: reason });
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
videoJobState.activeProcess = null;
+ if (displaySlept) wakeDisplay(videoGenSettings, 'Video generation');
void releaseHeavyClaim();
// Spawn failed, so proc.on('close') will never fire — clean up every
// temp file we own here, including the multipart upload, otherwise
@@ -378,6 +389,9 @@ export async function spawnAndWatchVideo({
broadcastSse(job, { type: 'error', error: `Generation failed: ${err.message}` });
videoGenEvents.emit('failed', { generationId: jobId, error: err.message });
} finally {
+ // A prompt-encode relaunch returns before this finalizer, deliberately
+ // leaving the display asleep while its replacement owns the GPU.
+ if (displaySlept) wakeDisplay(videoGenSettings, 'Video generation');
closeJobAfterDelay(videoJobState.jobs, jobId);
}
};