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

run LoRA training in GPU-cooldown segments to survive the macOS watchdog kernel panic

[._.]/ Adam Eivy66aa4ce1a902
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 98240999b9..6557ab8af7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,8 @@
## Changed
+- **LoRA training runs in GPU-cooldown segments to survive the macOS watchdog kernel panic** — Three separate FLUX.2 LoRA training runs hard-rebooted this machine with an identical `watchdog timeout: no checkins from watchdogd` kernel panic, each a couple of checkpoints into sustained GPU compute (the new-silicon GPU-driver hang tracked in `docs/research/2026-06-13-mflux-training-watchdog-panic.md`) — so no run had ever completed. The mflux trainer now runs in **checkpoint-sized segments** (default ON): it trains one save interval, **terminates the mflux child so its Metal/GPU context is fully torn down**, idles the GPU for a cooldown (default 90 s), then `--resume`s the newest checkpoint for the next segment. mflux resume reads `num_epochs` from the checkpoint (the config value is ignored on resume), so segmentation is numerically equivalent to one continuous run — it just never lets sustained GPU pressure span the whole run, and resets any accumulated driver/thermal state between segments. The child is killed only *after* the trainer steps past the boundary, so the boundary checkpoint is guaranteed fully flushed (no truncation) and resume loses at most one in-flight step. Disable globally — e.g. once a macOS/mflux update fixes the driver hang — with `settings.loraTraining.segmentation = false`; tune the gap with `segmentCooldownSec`. (`scripts/train_mflux_lora.py`, `server/services/loraTraining/runtimes.js`, `server/services/loraTraining/index.js`, `server/lib/validation.js`)
+
- **Reassign a LoRA training dataset to a different universe character** — A dataset was permanently bound to the character you picked when you created it — a mis-pick (or a character you later renamed/restructured) meant deleting the dataset and rebuilding all its images from scratch. The dataset workbench header (`/media/training/:id`) now has a **Reassign** button next to the character name: pick a different universe + character and the dataset's images, captions, and trigger word all move with it (the trigger word is left as-is — edit it separately if the new character needs its own token, which re-prefixes captions as before). Reassigning onto a character that already owns a dataset is refused (one dataset per character), reassignment is blocked while a training run is in flight, and the picker is the same universe→character cascade the "New dataset" dialog uses, factored into a shared `UniverseCharacterPicker`. (`server/services/loraDatasets.js`, `server/routes/loraDatasets.js`, `client/src/pages/LoraDatasetDetail.jsx`, `client/src/components/loraTraining/UniverseCharacterPicker.jsx`, `client/src/pages/LoraTraining.jsx`)
- **LoRA dataset workbench now coaches toward a quality target, not just the 10-image floor** — The readiness summary only knew two states ("add more" / "ready to train"), so a barely-trainable 10-image dataset looked just as finished as a strong 25-image one. The workbench now tracks a recommended quality target (~20, sweet spot 20–30) alongside the hard `MIN_TRAINING_IMAGES` floor: the count badge turns amber while trainable-but-thin and green once it clears the target, the sub-label tells you exactly how many more captioned images are recommended, and the Train panel echoes the same nudge. A new collapsible **"Tips for a strong character dataset"** panel spells out the variety that actually matters — vary angle, framing (face close-ups + full-body), pose, expression, outfit, lighting, and background; keep it single-subject and on-model; drop blurry/near-duplicate frames. The **Generate** batch dialog now defaults to 20 images (was 12) and notes the sweet spot inline. Advisory only — the server still trains any dataset that clears the 10-image gate. (`server/lib/loraDataset.js`, `client/src/pages/LoraDatasetDetail.jsx`, `client/src/components/loraTraining/TrainingPanel.jsx`, `client/src/components/loraTraining/GenerateBatchDialog.jsx`)
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 bf52aab6b4..325e9749e2 100644
--- a/docs/research/2026-06-13-mflux-training-watchdog-panic.md
+++ b/docs/research/2026-06-13-mflux-training-watchdog-panic.md
@@ -1,7 +1,7 @@
# Incident: GPU watchdog-timeout kernel panic during mflux LoRA training
**Status:** Open — monitoring for recurrence
-**First observed:** 2026-06-13 (two panics same day)
+**First observed:** 2026-06-13 (two panics same day; a third on 2026-06-14)
**Affected:** `Mac17,7` (Apple Silicon, `T6050` SoC), macOS 26.5 (`Darwin 25.5.0`, `xnu-12377.121.6~2`)
**Trigger:** Sustained GPU compute during mflux FLUX.2 LoRA training (`scripts/train_mflux_lora.py` → `mflux-train`)
@@ -22,11 +22,18 @@ Two panic reports under `/Library/Logs/DiagnosticReports/`, identical signature:
| Time (local) | panicString | product | caller |
|---|---|---|---|
-| 06:28:45 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…40a65d8c` |
-| 20:49:36 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…477fdd8c` |
-
-The two caller addresses differ **only by the ASLR kernel slide** — i.e. it is
-the same code path firing both times.
+| 06-13 06:28:45 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…40a65d8c` |
+| 06-13 20:49:36 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…477fdd8c` |
+| 06-14 07:26:47 | `watchdog timeout: no checkins from watchdogd in 93 seconds` | `Mac17,7` | `0x…49c65d8c` |
+
+The caller addresses differ **only by the ASLR kernel slide** (all three share
+the `…65d8c` low bytes) — i.e. it is the same code path firing every time. The
+06-14 recurrence happened with the 2026-06-13 mitigations (checkpoint floor,
+memory-pressure reclaim) already shipped, and **no `powermetrics.log` was
+captured on any of the three** — the telemetry sidecar no-ops because
+passwordless `sudo` for `powermetrics` was never configured, so all three
+crashes are still blind on the thermal-vs-driver question. Enabling the sidecar
+(below) is the top priority before the next run.
Key fields from the 20:49 paniclog:
@@ -89,6 +96,43 @@ swap thrash if a run oversubscribes unified memory.
to start (`failBeforeSpawn`) below `TRAINING_MIN_HEADROOM_GB` (24 GB)
rather than swap-thrashing the machine into another reboot.
+## Mitigations shipped (2026-06-14, after crash #3)
+
+4. **Segmented training + GPU cooldown** (default ON) — the strongest lever
+ short of an OS fix, and a direct response to crashes #1–3 all happening
+ *during sustained GPU compute* a fairly consistent depth into the run (a
+ signature of a cumulative thermal/driver trigger). Instead of one mflux
+ process held open for the whole run, `scripts/train_mflux_lora.py` now trains
+ in **checkpoint-sized segments**: train one save interval → **terminate the
+ mflux child so its Metal/GPU context is fully torn down** → idle the GPU for a
+ cooldown (default 90 s) → `--resume` the newest checkpoint → repeat. mflux
+ resume reads `num_epochs` from the checkpoint (the config value is ignored on
+ resume), so each segment continues toward the *same* total — segmentation is
+ numerically equivalent to one continuous run, just with periodic full-process
+ teardown. Sustained GPU pressure therefore never spans more than one segment,
+ and any accumulated driver/thermal state resets between segments while the GPU
+ clocks down.
+ - The child is killed only *after* the trainer steps **past** the boundary,
+ guaranteeing the boundary checkpoint zip is fully flushed (no truncation
+ from a mid-write kill); resume loses at most the one in-flight step.
+ - Wiring: `buildMfluxTrainArgs` emits `--segment-steps <save_frequency>
+ --cooldown-sec <n>`; segment size is exactly the config's effective
+ `save_frequency` so each segment ends on a checkpoint (no extra checkpoints,
+ no lost steps). `server/services/loraTraining/index.js` derives both from
+ `settings.loraTraining`.
+ - **Globally disable-able** once a macOS/mflux update fixes the underlying
+ GPU-driver hang: set `settings.loraTraining.segmentation = false` (or tune
+ `segmentCooldownSec`). With segmentation off the wrapper runs as a single
+ sustained process again (`--segment-steps 0`).
+ - Cost: each segment reloads the (quantized) base model and re-encodes the
+ dataset (low_ram wipes+re-encodes on every launch), so a 4-segment run pays
+ ~3 extra model loads + cooldowns. Acceptable vs. never completing a run. To
+ trade fewer reloads for a longer sustained window, raise `checkpointEvery`
+ (which raises `save_frequency` = segment size) — but keep it below the
+ ~150–300-step crash window.
+ - The 30-min training idle watchdog (`WATCHDOG_TRAINING_MS`) comfortably
+ covers a cooldown + model reload, so segmentation does not trip it.
+
### Enabling the telemetry sidecar (passwordless powermetrics)
`powermetrics` needs root. To let training capture telemetry without a prompt,
diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.py
index c68a607716..a0b4985421 100644
--- a/scripts/train_mflux_lora.py
+++ b/scripts/train_mflux_lora.py
@@ -24,6 +24,22 @@ Verified against mflux 0.17.5:
SIGTERM → forwarded to the mflux child; exit 143 after it stops (mflux
checkpoints at save_frequency boundaries; mid-interval cancels keep the
last saved checkpoint).
+
+Segmented training (watchdog-panic mitigation). When `--segment-steps N`
+is passed (>0), the run is broken into N-step segments instead of one
+sustained mflux process: train to a checkpoint boundary, **terminate the
+mflux child so its Metal/GPU context is fully torn down**, sleep
+`--cooldown-sec` to let the GPU clock down + the system settle, then
+`--resume` the newest checkpoint for the next segment. mflux resume reads
+`num_epochs` from the checkpoint (the config value is ignored on resume),
+so each segment continues toward the *same* total — segmentation is
+numerically equivalent to one continuous run, just with periodic
+full-process teardown. This directly attacks the macOS GPU
+watchdog-timeout kernel panics that hard-reboot the machine during long
+sustained mflux runs (see docs/research/2026-06-13-mflux-training-watchdog-panic.md):
+sustained GPU pressure never spans more than one segment, and any
+accumulated driver/thermal state resets between segments. `--segment-steps 0`
+(the default) restores the single-process behavior.
"""
import argparse
@@ -36,6 +52,7 @@ import signal
import subprocess
import sys
import threading
+import time
import zipfile
from collections import deque
from datetime import datetime
@@ -70,11 +87,65 @@ def parse_args():
p.add_argument("--config", required=True, help="mflux-train config JSON")
p.add_argument("--output-dir", required=True, help="PortOS run dir (samples/ lives here)")
p.add_argument("--total-steps", type=int, default=1000,
- help="expected total iterations — used only for logging sanity")
+ help="expected total iterations — segment planning + logging sanity")
p.add_argument("--resume-checkpoint", default=None, help="checkpoint zip to resume from")
+ p.add_argument("--segment-steps", type=int, default=0,
+ help="0 = single sustained run; >0 = train in N-step segments, tearing "
+ "down the GPU child + cooling down between each (watchdog-panic mitigation)")
+ p.add_argument("--cooldown-sec", type=int, default=90,
+ help="seconds to idle the GPU between segments (only with --segment-steps>0)")
return p.parse_args()
+# Checkpoint zips are named NNNNNNN_checkpoint.zip where NNNNNNN is the
+# trainer's cumulative iteration count — the canonical "where did we get to".
+CKPT_RE = re.compile(r"(\d+)_checkpoint\.zip$")
+
+
+def _checkpoint_step(path) -> int:
+ if not path:
+ return 0
+ m = CKPT_RE.search(Path(path).name)
+ return int(m.group(1)) if m else 0
+
+
+def newest_checkpoint(configured_output: Path):
+ """Newest checkpoint zip under the (possibly timestamp-suffixed) mflux
+ output dir. mflux `--resume` writes back to the SAME output_path
+ (new_folder=False), so checkpoints accumulate in one dir across segments;
+ ranking by embedded step keeps the pick monotonic even if mtimes tie."""
+ cdir = resolve_mflux_output(configured_output) / "checkpoints"
+ if not cdir.is_dir():
+ return None
+ zips = list(cdir.glob("*_checkpoint.zip"))
+ if not zips:
+ return None
+ return max(zips, key=lambda z: (_checkpoint_step(z), z.stat().st_mtime))
+
+
+def _terminate_child(timeout: float = 15.0) -> None:
+ """SIGTERM the mflux child and reap it (escalate to SIGKILL if it lingers).
+ Used at segment boundaries to fully release the Metal/GPU context."""
+ global CHILD
+ if CHILD and CHILD.poll() is None:
+ CHILD.terminate()
+ try:
+ CHILD.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ CHILD.kill()
+
+
+def interruptible_sleep(seconds: float) -> None:
+ """Sleep up to `seconds`, returning early if a SIGTERM cancel arrives —
+ so the inter-segment cooldown never delays a user-requested stop."""
+ end = time.monotonic() + seconds
+ while not STOP_REQUESTED:
+ remaining = end - time.monotonic()
+ if remaining <= 0:
+ return
+ time.sleep(min(1.0, remaining))
+
+
def build_command(config_path: str, resume: str | None) -> list:
"""`mflux-train` console script next to THIS interpreter (no PATH
ambiguity); fallback to the module behind it."""
@@ -313,28 +384,22 @@ def stream_lines(pipe):
buf = buf[cut + 1:]
-def main():
- global CHILD
- args = parse_args()
- output_dir = Path(args.output_dir)
- samples_dir = output_dir / "samples"
- samples_dir.mkdir(parents=True, exist_ok=True)
- config = json.loads(Path(args.config).read_text())
- configured_output = Path(config["checkpoint"]["output_path"])
-
- state = {"step": 0, "total": max(1, args.total_steps), "loss": None}
- last_reported = {"step": -1}
+def run_segment(cmd, *, segment_target, state, last_reported, output_tail,
+ fatal_holder, configured_output, cooldown):
+ """Run ONE mflux invocation and stream its output.
- watcher = ArtifactWatcher(configured_output, samples_dir, lambda: state["step"])
- watcher.start()
+ Returns a dict with `reason`:
+ - 'segment' — reached `segment_target`; the child was terminated after
+ the boundary checkpoint was confirmed on disk. `checkpoint`
+ holds the zip to resume the next segment from.
+ - 'completed' — the child exited 0 on its own (training finished).
+ - 'stopped' — a SIGTERM cancel arrived; caller should exit 143.
+ - 'error' — the child exited non-zero; `code` carries the exit code.
- cmd = build_command(args.config, args.resume_checkpoint)
- # Start telemetry only once we know the trainer command resolved (build_command
- # exits early on a missing mflux) so we never leave an orphaned root process.
- telemetry = TelemetrySidecar(output_dir)
- telemetry.start()
- log("STAGE:load-model")
- log(f"STATUS:launching {Path(cmd[0]).name}")
+ `segment_target=None` means "let mflux run to completion" (final/only
+ segment) — no boundary kill is armed.
+ """
+ global CHILD
CHILD = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
@@ -342,15 +407,6 @@ def main():
CHILD.terminate()
in_training = False
- fatal_emitted = False
- # Ring buffer of the trainer's recent non-progress output. mflux's stderr
- # is merged into its stdout (so tqdm stays in order), which means the Node
- # side tags every line `stream='stdout'` and the JS classifier's stderr
- # tail — its only window into *why* a run died — stays empty. On a non-zero
- # exit we replay this buffer to stderr so argparse errors, tracebacks, and
- # version-mismatch complaints actually reach the classifier instead of the
- # run failing with a bare "exited with code N".
- output_tail = deque(maxlen=OUTPUT_TAIL_LINES)
for raw in stream_lines(CHILD.stdout):
line = raw.strip()
if not line or NOISE_RE.search(line):
@@ -358,11 +414,11 @@ def main():
# Surface the first fatal error in a structured form the Node
# classifier can read (once — don't spam if it repeats in a traceback).
- if not fatal_emitted:
+ if not fatal_holder["v"]:
for code, pat in FATAL_PATTERNS:
if pat.search(line):
print(f"USER_ERROR:{code}:{line[:300]}", file=sys.stderr, flush=True)
- fatal_emitted = True
+ fatal_holder["v"] = True
break
m = STEP_LOSS_RE.search(line) or TQDM_RE.search(line)
@@ -382,6 +438,18 @@ def main():
if cur != last_reported["step"]:
last_reported["step"] = cur
log(f"STEP:{cur}:{total}:{state['loss'] if state['loss'] is not None else 'nan'}")
+ # Segment boundary: wait until the trainer has stepped PAST the
+ # target before killing, so mflux's save at the boundary (which
+ # runs synchronously before the next step is emitted) has fully
+ # flushed the zip — killing the instant the file appears could
+ # truncate a half-written checkpoint.
+ if segment_target is not None and state["step"] > segment_target:
+ ck = newest_checkpoint(configured_output)
+ if ck and _checkpoint_step(ck) >= segment_target:
+ log(f"STATUS:segment checkpoint @ step {_checkpoint_step(ck)} saved — "
+ f"tearing down GPU + cooling {cooldown}s (watchdog-panic mitigation)")
+ _terminate_child()
+ return {"reason": "segment", "checkpoint": ck, "code": 0}
continue
# Forward everything else (truncated) — keeps the JS idle watchdog
@@ -390,6 +458,96 @@ def main():
log(f"STATUS:{line[:300]}")
code = CHILD.wait()
+ if STOP_REQUESTED:
+ return {"reason": "stopped", "code": 143}
+ if code != 0:
+ return {"reason": "error", "code": code}
+ return {"reason": "completed", "checkpoint": newest_checkpoint(configured_output), "code": 0}
+
+
+def main():
+ args = parse_args()
+ output_dir = Path(args.output_dir)
+ samples_dir = output_dir / "samples"
+ samples_dir.mkdir(parents=True, exist_ok=True)
+ config = json.loads(Path(args.config).read_text())
+ configured_output = Path(config["checkpoint"]["output_path"])
+
+ total = max(1, args.total_steps)
+ seg = max(0, args.segment_steps)
+ cooldown = max(0, args.cooldown_sec)
+ segmented = seg > 0
+
+ state = {"step": 0, "total": total, "loss": None}
+ last_reported = {"step": -1}
+
+ watcher = ArtifactWatcher(configured_output, samples_dir, lambda: state["step"])
+ watcher.start()
+
+ # Resolve the trainer command up front so a missing mflux exits before we
+ # start telemetry (build_command exits early) — never leave an orphaned
+ # root powermetrics process. One telemetry sidecar + one watcher span ALL
+ # segments so the forensic log and artifact stream stay continuous.
+ _ = build_command(args.config, args.resume_checkpoint)
+ telemetry = TelemetrySidecar(output_dir)
+ telemetry.start()
+
+ fatal_holder = {"v": False}
+ # Ring buffer of the trainer's recent non-progress output. mflux's stderr
+ # is merged into its stdout (so tqdm stays in order), which means the Node
+ # side tags every line `stream='stdout'` and the JS classifier's stderr
+ # tail — its only window into *why* a run died — stays empty. On a non-zero
+ # exit we replay this buffer to stderr so argparse errors, tracebacks, and
+ # version-mismatch complaints actually reach the classifier instead of the
+ # run failing with a bare "exited with code N".
+ output_tail = deque(maxlen=OUTPUT_TAIL_LINES)
+
+ resume = args.resume_checkpoint # None on a fresh run; a zip on resume
+ final_code = 0
+ segment_index = 0
+ if segmented:
+ log(f"STATUS:segmented training enabled — {seg}-step segments, {cooldown}s GPU cooldown between each")
+ while True:
+ start_step = _checkpoint_step(resume) if resume else 0
+ if start_step >= total:
+ break # nothing left to train (resumed past the end)
+ # Final/only segment runs to natural completion (no boundary kill); the
+ # estimate `total` may differ slightly from mflux's epoch-rounded total,
+ # so the last segment always lets mflux decide when it's done.
+ segment_target = start_step + seg if segmented else None
+ if segment_target is not None and segment_target >= total:
+ segment_target = None
+
+ cmd = build_command(args.config, resume)
+ log("STAGE:load-model")
+ log(f"STATUS:launching {Path(cmd[0]).name}"
+ + (f" (segment {segment_index + 1} from step {start_step})" if segmented else ""))
+
+ result = run_segment(
+ cmd, segment_target=segment_target, state=state, last_reported=last_reported,
+ output_tail=output_tail, fatal_holder=fatal_holder,
+ configured_output=configured_output, cooldown=cooldown,
+ )
+ segment_index += 1
+
+ if result["reason"] == "stopped":
+ break
+ if result["reason"] == "error":
+ final_code = result["code"] or 1
+ break
+ if result["reason"] == "completed":
+ break
+
+ # reason == 'segment' — cool down, then resume from the boundary checkpoint.
+ resume = str(result["checkpoint"]) if result.get("checkpoint") else resume
+ new_step = _checkpoint_step(resume)
+ if new_step >= total:
+ break
+ log(f"STATUS:segment {segment_index} complete at step {new_step}/{total} — cooling down {cooldown}s")
+ interruptible_sleep(cooldown)
+ if STOP_REQUESTED:
+ break
+
watcher.stop_event.set()
watcher.join(timeout=10)
telemetry.stop()
@@ -398,15 +556,15 @@ def main():
log("STATUS:canceled — last saved checkpoint retained")
sys.exit(143)
- if code != 0:
+ if final_code != 0:
# Replay the trainer's tail to stderr so the Node classifier sees the
# real error. Skip when a structured USER_ERROR already pinned the
# cause (its message is more actionable than raw tail lines).
- if not fatal_emitted:
+ if not fatal_holder["v"]:
for tail_line in output_tail:
print(f"mflux: {tail_line}", file=sys.stderr, flush=True)
- print(f"❌ mflux trainer exited with code {code}", file=sys.stderr, flush=True)
- sys.exit(code or 1)
+ print(f"❌ mflux trainer exited with code {final_code}", file=sys.stderr, flush=True)
+ sys.exit(final_code or 1)
checkpoints_dir = resolve_mflux_output(configured_output) / "checkpoints"
adapter = find_adapter(checkpoints_dir, output_dir)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 03ad1e55cf..1a5a978a6e 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -850,6 +850,12 @@ export const loraTrainingConfigSchema = z.object({
captionProviderId: z.string().max(128).nullable().optional(),
captionModel: z.string().max(256).nullable().optional(),
defaults: loraTrainingParamsSchema.optional(),
+ // Segmented mflux training (watchdog-panic mitigation, default ON in
+ // services/loraTraining/runtimes.js). Setting this false runs the trainer as
+ // one sustained process again — flip it once a macOS/mflux update resolves
+ // the GPU-driver hang. Cooldown is the GPU idle gap (seconds) between segments.
+ segmentation: z.boolean().optional(),
+ segmentCooldownSec: z.number().int().min(0).max(3600).optional(),
});
// POST /api/lora-training/runs — start a training run for a dataset.
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 254de1584b..eaec834a8a 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -36,6 +36,7 @@ import {
buildMfluxTrainArgs,
buildMfluxTrainConfig,
resolveTrainingRuntime,
+ MFLUX_DEFAULT_COOLDOWN_SEC,
} from './runtimes.js';
import { makeTrainingLineHandler } from './progress.js';
import { prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } from './memoryPrep.js';
@@ -342,6 +343,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
const run = await runsDb.getRun(runId);
if (!run) return fail(`run record missing: ${runId}`);
+ const settings = await getSettings();
// Terminal failure BEFORE the child spawns: flip the run record to failed
// AND release the dataset's `training` status, then emit the failed event.
@@ -465,12 +467,23 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
});
const configPath = join(dir, 'mflux-train.json');
await atomicWrite(configPath, config);
+ // Segmented training (watchdog-panic mitigation): default ON, globally
+ // disable-able via settings.loraTraining.segmentation = false once a
+ // macOS/mflux update fixes the underlying GPU-driver hang. Segment size
+ // is the config's effective save_frequency so each segment ends exactly
+ // on a checkpoint — no extra checkpoints, no lost steps on resume.
+ const segCfg = settings?.loraTraining || {};
+ const segmentationOn = segCfg.segmentation !== false;
+ const cooldownSec = Number.isFinite(segCfg.segmentCooldownSec)
+ ? segCfg.segmentCooldownSec : MFLUX_DEFAULT_COOLDOWN_SEC;
args = buildMfluxTrainArgs({
scriptPath: TRAINER_SCRIPTS.mflux,
configPath,
runDir: dir,
totalSteps: run.params?.steps || TRAINING_DEFAULTS.steps,
resumeCheckpoint,
+ segmentSteps: segmentationOn ? config.checkpoint.save_frequency : 0,
+ cooldownSec,
});
}
} catch (err) {
diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.js
index 9bf3d66bbe..79b2590656 100644
--- a/server/services/loraTraining/runtimes.js
+++ b/server/services/loraTraining/runtimes.js
@@ -221,14 +221,39 @@ export function buildMfluxTrainConfig({
};
}
-/** Argv for the mflux wrapper script. */
-export function buildMfluxTrainArgs({ scriptPath, configPath, runDir, totalSteps, resumeCheckpoint = null }) {
+// Default GPU cooldown (seconds) between training segments — long enough for
+// the GPU to clock down and the system to settle after a full Metal-context
+// teardown, short relative to a segment's compute. See the segmentation block
+// in scripts/train_mflux_lora.py and the watchdog-panic incident record.
+export const MFLUX_DEFAULT_COOLDOWN_SEC = 90;
+
+/**
+ * Argv for the mflux wrapper script.
+ *
+ * `segmentSteps > 0` enables segmented training (watchdog-panic mitigation):
+ * the wrapper trains one checkpoint interval, tears down the GPU child, cools
+ * down `cooldownSec`, then resumes — so sustained GPU pressure never spans the
+ * whole run. Pass `segmentSteps = the effective save_frequency` so each segment
+ * ends exactly on a checkpoint. `segmentSteps = 0` keeps the single-process run.
+ */
+export function buildMfluxTrainArgs({
+ scriptPath,
+ configPath,
+ runDir,
+ totalSteps,
+ resumeCheckpoint = null,
+ segmentSteps = 0,
+ cooldownSec = MFLUX_DEFAULT_COOLDOWN_SEC,
+}) {
const args = [
scriptPath,
'--config', configPath,
'--output-dir', runDir,
'--total-steps', String(totalSteps),
];
+ if (segmentSteps > 0) {
+ args.push('--segment-steps', String(segmentSteps), '--cooldown-sec', String(Math.max(0, cooldownSec)));
+ }
if (resumeCheckpoint) args.push('--resume-checkpoint', resumeCheckpoint);
return args;
}
diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.js
index 619cb33502..40aa4af721 100644
--- a/server/services/loraTraining/runtimes.test.js
+++ b/server/services/loraTraining/runtimes.test.js
@@ -7,6 +7,7 @@ import {
buildMfluxTrainConfig,
deriveMfluxMemoryConfig,
resolveTrainingRuntime,
+ MFLUX_DEFAULT_COOLDOWN_SEC,
} from './runtimes.js';
const MODELS = [
@@ -181,6 +182,38 @@ describe('buildMfluxTrainArgs / buildFlux2TrainArgs', () => {
expect(args).not.toContain('--resume-checkpoint');
});
+ it('omits segment flags when segmentSteps is 0 (single-process run)', () => {
+ const args = buildMfluxTrainArgs({
+ scriptPath: '/x.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 500, segmentSteps: 0,
+ });
+ expect(args).not.toContain('--segment-steps');
+ expect(args).not.toContain('--cooldown-sec');
+ });
+
+ it('emits segment + cooldown flags when segmentation is enabled', () => {
+ const args = buildMfluxTrainArgs({
+ scriptPath: '/x.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 600,
+ segmentSteps: 150, cooldownSec: 120,
+ });
+ expect(args[args.indexOf('--segment-steps') + 1]).toBe('150');
+ expect(args[args.indexOf('--cooldown-sec') + 1]).toBe('120');
+ });
+
+ it('defaults the cooldown when only segmentSteps is given', () => {
+ const args = buildMfluxTrainArgs({
+ scriptPath: '/x.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 600, segmentSteps: 150,
+ });
+ expect(args[args.indexOf('--cooldown-sec') + 1]).toBe(String(MFLUX_DEFAULT_COOLDOWN_SEC));
+ });
+
+ it('clamps a negative cooldown to 0', () => {
+ const args = buildMfluxTrainArgs({
+ scriptPath: '/x.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 600,
+ segmentSteps: 150, cooldownSec: -5,
+ });
+ expect(args[args.indexOf('--cooldown-sec') + 1]).toBe('0');
+ });
+
it('refuses non-bf16 train repos', () => {
expect(() => buildFlux2TrainArgs({
scriptPath: '/x.py', trainRepo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',