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

auto-sleep the Mac display during LoRA training + fix the caffeinate -d flag that was causing the watchdog panic

[._.]/ Adam Eivy18a280540853
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 638c190ddb..e27e124f23 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,7 @@
- **[issue-1329] Pinned a validated mlx/mlx-metal trio for LoRA training so the GPU-watchdog stack can't silently drift back to the known-bad build.** The three M5 Max kernel panics during FLUX.2 LoRA training all happened on mlx/mlx-metal 0.30.6, but `setup-image-video.sh` installed `mflux>=0.17` as a *floor* and let pip resolve mlx under mflux's `mlx<0.32` cap — so a reinstall could land back on a panicking build. The setup script now pins the bisect-validated trio **mflux 0.17.5 · mlx 0.31.2 · mlx-metal 0.31.2**, proven by run `d36562a0` completing a full LoRA training to adapter extraction (flux2-klein-4b, bf16, 768px, segmentation on) on the panicking M5 Max with no panic or reboot. The runtime-fingerprint half shipped earlier (#1406). (`scripts/setup-image-video.sh`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
- **[issue-1329] Applied the upstream-confirmed fix for the LoRA-training GPU watchdog panic.** A search of the MLX tracker turned up the root cause: [mlx #3267](https://github.com/ml-explore/mlx/issues/3267) — the Metal GPU watchdog kills sustained LoRA training whose command buffers compete with active-display compositing (escalating to a `watchdogd` kernel panic + hard reboot on M5-class silicon). The MLX maintainer's confirmed workaround is the `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` env var, which PortOS now sets automatically in the trainer (it propagates to the `mflux-train` child; set it to `0` to disable). The trainer logs `STATUS:watchdog mitigation · AGX_RELAX_CDM_CTXSTORE_TIMEOUT=…` so a paniclog records whether it was active. Notably, per #3267 the kill is at the IOGPU layer *above* the process boundary — so process-teardown segmentation alone does not prevent it, and the strongest user-side mitigation is to keep the display off (SSH headless or `pmset displaysleepnow`) for heavy sustained runs. Our data points were posted to #3267 rather than filed as a duplicate. (`scripts/train_mflux_lora.py`, `docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
- **[issue-1329] Confirmed on the M5 Max what actually stops the watchdog panic: keeping the display off.** A clean A/B on the *same* 9B-bf16 segmentation-OFF config (the heaviest, most panic-prone) — both with `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` set — settled it: with the **display active** the box hard-rebooted at step 0 within minutes (first telemetry-captured panic showed Nominal thermal pressure, i.e. a GPU **driver hang** not heat, with `WindowServer` the top-CPU thread); with the **display asleep** (`pmset displaysleepnow`) the identical run reached **step 302**, clearing the documented 150–300 panic window with no panic. So the env var is necessary but not sufficient for heavy runs — for a 9B/heavy bf16 job, drive the box over SSH or sleep the display, and keep segmentation on. `caffeinate -s` does not sleep the display, and closing the lid suspends the whole machine. TROUBLESHOOTING now documents the working recipe. (`docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)
+- **[issue-1329] Fixed a bug that was *causing* the training GPU-watchdog crash, and made PortOS auto-sleep the Mac's display during training (then wake it after).** The trainer spawned `caffeinate -dis` to keep the machine awake — but the `-d` flag *forces the display to stay on*, the exact WindowServer-GPU-contention state that triggers the watchdog kernel panic. (The code comment even said "display can sleep"; the flag did the opposite.) The flag is now `-is` so the display can sleep, and on Apple Silicon PortOS proactively runs `pmset displaysleepnow` when a run starts and wakes the display (`caffeinate -u`) when it finishes — so a run you kick off and walk away from (or trigger remotely) protects the box automatically, and you see the result when it's done. On by default; opt out with `loraTraining.displaySleep: false` (e.g. headless). The training panel now explains the crash risk and recommends letting big runs go overnight. (`server/services/loraTraining/index.js`, `server/services/loraTraining/displayPower.js`, `server/lib/validation.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)
## Mood boards
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index 7a5950fdb4..e27ba21388 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -9,7 +9,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
-import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw } from 'lucide-react';
+import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw, Moon } from 'lucide-react';
import toast from '../ui/Toast';
import { useSseProgress } from '../../hooks/useSseProgress';
import CheckpointPicker from './CheckpointPicker';
@@ -350,6 +350,24 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
</div>
)}
</div>
+ {status?.runtimes?.mflux?.ready && (
+ <div className="flex items-start gap-2 rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-xs text-gray-400">
+ <Moon className="w-3.5 h-3.5 mt-0.5 shrink-0 text-port-accent" />
+ <div className="space-y-1">
+ <div className="text-gray-300">
+ This Mac's display sleeps automatically while training, then wakes when the run finishes.
+ </div>
+ <div>
+ On Apple Silicon, an <span className="text-gray-300">active display can crash the whole machine</span>{' '}
+ (GPU watchdog kernel panic) during heavy LoRA training — so PortOS puts the display to sleep for you
+ and the system keeps running underneath. Big runs (9B, bf16) can take hours: start one and{' '}
+ <span className="text-gray-300">let it run overnight</span>. Don't close the lid (that sleeps the
+ whole Mac and pauses the run); just leave it be, or drive it over SSH. On by default; set
+ <code className="text-gray-300">loraTraining.displaySleep: false</code> to opt out if you run headless.
+ </div>
+ </div>
+ </div>
+ )}
<div className="flex items-center justify-between gap-2">
<span className={`text-xs ${!disabledReason && readiness?.quality === 'minimum' ? 'text-port-warning' : 'text-gray-500'}`}>
{disabledReason
diff --git a/docs/research/2026-06-13-mflux-training-watchdog-panic.md b/docs/research/2026-06-13-mflux-training-watchdog-panic.md
index 1a62515e04..130420b2ca 100644
--- a/docs/research/2026-06-13-mflux-training-watchdog-panic.md
+++ b/docs/research/2026-06-13-mflux-training-watchdog-panic.md
@@ -72,6 +72,20 @@ segmentation-on by default; the remaining user action is to keep the display off
(SSH headless or `pmset displaysleepnow`) for big sustained runs — documented in
TROUBLESHOOTING.
+**Productized (#1329, 2026-06-27) — and a contributing bug fixed.** While wiring
+the display-off mitigation into the app, found that the trainer spawned
+`caffeinate -dis` to keep the Mac awake — and `-d` **forces the display to stay
+on** (the comment claimed "display can sleep"; the flag did the opposite). So
+PortOS was actively holding the box in the WindowServer-contention state that
+triggers the panic — a contributing cause, not just a missing nicety. Fixed to
+`-is` (idle+system sleep held, display free to sleep). On top of that, the LoRA
+trainer now **auto-sleeps the display when a run starts and wakes it when the run
+finishes** on Apple Silicon (`server/services/loraTraining/displayPower.js`,
+gated by `settings.loraTraining.displaySleep`, default on; wake skipped on a
+stall-watchdog auto-resume since that re-sleeps). The training panel surfaces the
+crash risk + the overnight recommendation. So the validated mitigation is now the
+default behavior, not a manual checklist item.
+
## Summary
The machine hard-rebooted twice in one day, both times while a LoRA training run
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 682e667840..7c5f1fe484 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -889,6 +889,13 @@ export const loraTrainingConfigSchema = z.object({
// from the newest checkpoint. Set false to fall back to only the flat 30-min
// idle watchdog (e.g. if a future driver fix makes soft hangs impossible).
stallWatchdog: z.boolean().optional(),
+ // Auto display-sleep during training on Apple Silicon (default ON in
+ // services/loraTraining/index.js). Sleeps the Mac's display when a run starts
+ // and wakes it when it finishes. This is the validated mitigation for the GPU
+ // watchdog kernel panic (mlx #3267): an active display makes WindowServer
+ // contend for the GPU, which hard-reboots the box during heavy sustained
+ // training. Set false if you drive the display some other way (SSH headless).
+ displaySleep: z.boolean().optional(),
});
// POST /api/lora-training/runs — start a training run for a dataset.
diff --git a/server/services/loraTraining/displayPower.js b/server/services/loraTraining/displayPower.js
new file mode 100644
index 0000000000..0ea4d0f2ea
--- /dev/null
+++ b/server/services/loraTraining/displayPower.js
@@ -0,0 +1,57 @@
+/**
+ * macOS display power control for LoRA training (GPU-watchdog mitigation).
+ *
+ * The validated root cause of the macOS GPU-watchdog kernel panic during heavy
+ * sustained mflux LoRA training is an *active display*: WindowServer compositing
+ * contends with the training command buffers for the GPU, and on M5-class
+ * silicon that escalates to a `watchdogd` timeout that hard-reboots the box
+ * (upstream mlx #3267; see docs/research/2026-06-13-mflux-training-watchdog-panic.md).
+ * The clean A/B on the M5 Max: display ON → reboot at step 0; display asleep →
+ * cleared the panic window (step 302).
+ *
+ * So PortOS sleeps the Mac's display when a run starts and wakes it when the run
+ * finishes. Both are best-effort and macOS-only — a failure (or a non-darwin
+ * host) must never affect the training run, so every call swallows its errors.
+ *
+ * These run *outside* the Express request lifecycle (spawned from the training
+ * lifecycle), so per the repo convention the spawn boundary is wrapped and never
+ * throws into the event loop.
+ */
+import { spawn } from 'child_process';
+import { platform } from 'os';
+
+// 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;
+}
+
+// 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;
+}
+
+// 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;
+}
diff --git a/server/services/loraTraining/displayPower.test.js b/server/services/loraTraining/displayPower.test.js
new file mode 100644
index 0000000000..aa4327a6c6
--- /dev/null
+++ b/server/services/loraTraining/displayPower.test.js
@@ -0,0 +1,75 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Hoisted mock state so the os/child_process factories can reach it.
+const h = vi.hoisted(() => ({
+ platform: 'darwin',
+ spawned: [], // [{ cmd, args }]
+}));
+
+vi.mock('os', () => ({ platform: () => h.platform }));
+vi.mock('child_process', () => ({
+ spawn: (cmd, args) => {
+ h.spawned.push({ cmd, args });
+ return { on: () => {}, unref: () => {} };
+ },
+}));
+
+const { isDisplaySleepEnabled, sleepDisplayForTraining, wakeDisplay } = await import('./displayPower.js');
+
+beforeEach(() => {
+ h.platform = 'darwin';
+ h.spawned = [];
+});
+
+describe('displayPower', () => {
+ describe('isDisplaySleepEnabled', () => {
+ it('is on by default on darwin (absent slice / absent flag)', () => {
+ expect(isDisplaySleepEnabled(undefined)).toBe(true);
+ expect(isDisplaySleepEnabled({})).toBe(true);
+ expect(isDisplaySleepEnabled({ loraTraining: {} })).toBe(true);
+ });
+
+ it('respects an explicit false', () => {
+ expect(isDisplaySleepEnabled({ loraTraining: { displaySleep: false } })).toBe(false);
+ });
+
+ it('honors an explicit true', () => {
+ expect(isDisplaySleepEnabled({ loraTraining: { displaySleep: true } })).toBe(true);
+ });
+
+ it('is off on non-darwin regardless of the setting', () => {
+ h.platform = 'linux';
+ expect(isDisplaySleepEnabled({ loraTraining: { displaySleep: true } })).toBe(false);
+ });
+ });
+
+ describe('sleepDisplayForTraining', () => {
+ it('runs `pmset displaysleepnow` when enabled', () => {
+ expect(sleepDisplayForTraining({ loraTraining: {} })).toBe(true);
+ expect(h.spawned).toEqual([{ cmd: 'pmset', args: ['displaysleepnow'] }]);
+ });
+
+ it('is a no-op (no spawn) when disabled', () => {
+ expect(sleepDisplayForTraining({ loraTraining: { displaySleep: false } })).toBe(false);
+ expect(h.spawned).toEqual([]);
+ });
+
+ it('is a no-op off darwin', () => {
+ h.platform = 'win32';
+ expect(sleepDisplayForTraining({ loraTraining: {} })).toBe(false);
+ expect(h.spawned).toEqual([]);
+ });
+ });
+
+ describe('wakeDisplay', () => {
+ it('runs `caffeinate -u -t 5` when enabled', () => {
+ expect(wakeDisplay({ loraTraining: {} })).toBe(true);
+ expect(h.spawned).toEqual([{ cmd: 'caffeinate', args: ['-u', '-t', '5'] }]);
+ });
+
+ it('is a no-op when disabled (so we never wake a display we did not sleep)', () => {
+ expect(wakeDisplay({ loraTraining: { displaySleep: false } })).toBe(false);
+ expect(h.spawned).toEqual([]);
+ });
+ });
+});
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 6de74a332d..45f79653b7 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -30,6 +30,7 @@ import { getSettings } from '../settings.js';
import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateDataset } from '../loraDatasets.js';
import { trainingEvents } from './events.js';
+import { sleepDisplayForTraining, wakeDisplay } from './displayPower.js';
import {
TRAINING_DEFAULTS,
TRAINING_RUNTIMES,
@@ -609,13 +610,24 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
activeProcess = proc;
activeJobId = jobId;
- // Keep the Mac awake for the duration of the training child (display can
- // sleep; system must not). Best-effort — caffeinate exits with the child.
+ // Keep the Mac awake for the duration of the training child (idle + system
+ // sleep held off) — but DELIBERATELY let the *display* sleep. An active
+ // display makes WindowServer contend for the GPU, which triggers the watchdog
+ // kernel panic during heavy training (mlx #3267; see the incident doc). The
+ // flags are `-is`, NOT `-dis`: `-d` would force the display awake and is what
+ // was crashing the box. We then proactively sleep the display below so the
+ // protection doesn't wait on the OS idle timeout. Best-effort — caffeinate
+ // exits with the child.
if (platform() === 'darwin' && proc.pid) {
- const caf = spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore' });
+ const caf = spawn('caffeinate', ['-is', '-w', String(proc.pid)], { stdio: 'ignore' });
caf.on('error', () => {});
caf.unref();
}
+ // Sleep the display now (Apple Silicon, opt-out via settings.loraTraining
+ // .displaySleep) so sustained GPU training never competes with the display.
+ // Woken again in the close handler when the run finishes. No-op on reattach
+ // would re-sleep an already-protected run, which is harmless.
+ sleepDisplayForTraining(settings);
// Debounced run-record progress mirror (~2s). Per-step DB writes from a
// hot loop are the high-frequency-write anti-pattern; SSE is the live
@@ -782,6 +794,12 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
// escape the event handler (unhandled rejection kills the process on Node ≥15).
Promise.resolve(flushProgress())
.then(() => finalizeTraining({ jobId, runId, code, signal, state: getState(), stallKilled }))
+ .then(() => {
+ // Wake the display now the run is over so the user sees the result —
+ // but NOT on a stall-watchdog auto-resume (stallKilled), which re-spawns
+ // and re-sleeps the display for the next attempt. Best-effort, darwin-only.
+ if (!stallKilled) wakeDisplay(settings);
+ })
.catch((err) => {
console.error(`❌ training [${shortId(jobId)}] finalize failed: ${err?.message}`);
fail(`finalize failed: ${err?.message}`);