mlx icon indicating copy to clipboard operation
mlx copied to clipboard

[BUG] Metal GPU watchdog kills LoRA training when display is active

Open zackedds opened this issue 8 months ago • 9 comments

Describe the bug

LoRA fine-tuning crashes with kIOGPUCommandBufferCallbackErrorImpactingInteractivity when the laptop display is active. The macOS Metal GPU watchdog kills the training process because GPU command buffers from MLX block WindowServer display compositing. The crash is 100% reproducible with the display on (4/4 runs across macOS 26.2 and 26.3.1) and 100% avoidable with the display off (closing the lid with caffeinate -s to prevent sleep, this eliminates WindowServer GPU compositing, so the watchdog's "impacting interactivity" check has nothing to protect and never fires).

The workload is minimal: 2.75GB peak memory on a 16GB system (17% utilization), batch_size=1, max_seq_length=256, every parameter at or more conservative than mlx-lm defaults.

To Reproduce

pip install mlx-lm

# Training data: 105 JSONL chat examples, ~256 tokens each
# (Qwen format with system/user/assistant messages containing <think> + <tool_call> blocks)
# Short examples (~40 tokens, ~3.0 it/sec) do NOT crash
# Long examples (~256 tokens, ~0.8 it/sec) crash every time

python -m mlx_lm lora \
  --model mlx-community/Qwen3.5-2B-OptiQ-4bit \
  --train --data ./data \
  --config lora_config.yaml \
  --adapter-path ./adapters

# Crashes within 1-5 minutes:
# libc++abi: terminating due to uncaught exception of type std::runtime_error:
# [METAL] Command buffer execution failed: Impacting Interactivity
# (0000000e:kIOGPUCommandBufferCallbackErrorImpactingInteractivity)

lora_config.yaml:

model: mlx-community/Qwen3.5-2B-OptiQ-4bit
fine_tune_type: lora
batch_size: 1
num_layers: 8
lora_parameters:
  rank: 8
  scale: 20.0
  dropout: 0.0
iters: 500
steps_per_eval: 500
learning_rate: 1e-5
grad_checkpoint: true
mask_prompt: true
max_seq_length: 256

Results across 5 runs:

Run macOS Display Background Result
1 26.2 Open Minimal Crashed iter ~180
2 26.2 Open Normal OS activity Crashed iter ~53
3 26.2 Open Normal OS activity Crashed iter ~43
4 26.3.1 Open Normal OS activity Crashed iter ~1
5 26.3.1 Closed caffeinate -s Completed 500/500

Expected behavior

Training completes all 500 iterations. The workload uses 17% of available GPU memory with the most conservative possible settings.

Desktop (please complete the following information):

  • OS Version: macOS 26.2 Tahoe and macOS 26.3.1 Tahoe
  • MLX Version: 0.31.1
  • mlx-lm Version: 0.31.1
  • Hardware: MacBook Pro M2 Pro, 16GB unified memory
  • Python: 3.14.3

Additional context

  • MLX_MAX_OPS_PER_BUFFER=1 and MLX_MAX_MB_PER_BUFFER=10 do not prevent the crash with the display active
  • Normal background OS activity and rendering windows accelerates the crash, more GPU contention from WindowServer compositing means earlier crashes
  • The crash does not occur with short training examples (~40 tokens, 1.75GB peak, ~3.0 it/sec), only with longer sequences (~256 tokens, 2.75GB peak, ~0.8 it/sec) where individual GPU operations take ~1.2 seconds
  • Workaround: caffeinate -s & then close the laptop lid. With no active display, WindowServer does not need GPU time for compositing, so the watchdog never triggers. Training completes normally.
  • Training data and config available on request for reproduction

zackedds avatar Mar 16 '26 22:03 zackedds

Thanks for the detailed report, can you try if setting environment variable AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 makes things better?

zcbenz avatar Mar 17 '26 05:03 zcbenz

Completely resolved with AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 Thank you!!

zackedds avatar Mar 17 '26 06:03 zackedds

I hope there is a way to fix this without setting an env, but this behavior is controlled by OS, we could try to re-submit the command buffer but it would be a complicated solution and might not work for larger works.

So I'm marking this as won't fix because we don't really have a fix.

zcbenz avatar Mar 17 '26 07:03 zcbenz

We've added detection for this exact error pattern in MetalGuard v0.4.0.

is_metal_oom() now detects kIOGPUCommandBufferCallbackErrorImpactingInteractivity alongside the existing OOM patterns, so you can catch it programmatically and respond gracefully instead of losing your training run:

from metal_guard import metal_guard, MetalOOMError

try:
    result = metal_guard.oom_protected(train_step, model, batch)
except MetalOOMError as e:
    # Save checkpoint before the watchdog kills us
    save_checkpoint(model, optimizer, step)
    log.error("GPU watchdog triggered: %s", e)

Additionally, MetalGuard sets AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 at import time (the workaround @zcbenz suggested), so importing MetalGuard automatically applies that fix.

For MacBook users specifically, the new recommended_config() detects your hardware tier and returns conservative thresholds appropriate for lower-memory machines:

config = MetalGuard.recommended_config()
# On 16GB MacBook: tier="low", watchdog_warn_pct=60%, critical_pct=75%

Single file, zero dependencies, MIT licensed: https://github.com/Harperbot/metal-guard

Harperbot avatar Apr 12 '26 16:04 Harperbot

Adding a user-space mitigation data point for anyone landing here.

This kIOGPUCommandBufferCallbackErrorImpactingInteractivity watchdog kill is orthogonal to model / quant / framework — it fires on any LoRA training that competes with the active display for GPU time. We just shipped a WORKLOAD_ADVISORIES entry for this in Harperbot/metal-guard v0.11.6 (MIT) precisely because subprocess isolation does not help — the kill is at IOGPU layer above the process boundary, so respawning the worker just gets killed again.

What works in production:

  • caffeinate -s — keeps the system awake without forcing the display on. Run training under it.
  • Display sleep (System Settings → Lock Screen → "Turn display off when inactive: 1 minute"). Once the display sleeps, WindowServer yields GPU and the watchdog stops firing.
  • SSH from another machine — same effect; no WindowServer competition.
  • Brightness 0 — partial workaround on some setups; YMMV.

What does not work:

  • Subprocess isolation (kill is above process boundary).
  • mx.metal.set_memory_limit() (memory isn't the issue).
  • Lower batch size (latency is, watchdog measures interactivity-impacting commands).

If anyone wants the registry pattern in their own code:

import metal_guard
advisory = metal_guard.check_workload_advisory("lora_with_display_active")
if advisory:
    log.warning("LoRA training launching with display active: %s",
                advisory["workaround"])

Install (no PyPI yet):

pip install "git+https://github.com/Harperbot/[email protected]"

Doesn't fix the IOGPU watchdog policy — that's an Apple-side tuning decision — but surfaces the mitigation before users hit the kill mid-training. Happy to take registry contributions if your workload is similarly orthogonal-to-model.

Harperbot avatar Apr 28 '26 02:04 Harperbot

Quick follow-up — meant to mention this in my earlier comment but missed it: metal-guard auto-sets AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 at import per @zcbenz's suggestion earlier in this thread. So users who import metal_guard get the env var workaround for free without having to remember to set it themselves.

Code reference (metal_guard.py:94-100):

# Suggested by @zcbenz (MLX maintainer) in mlx#3267:
# Relaxes the command buffer context store timeout to reduce kernel panics
# on long-running GPU workloads.  Zero-cost — just an env var hint to the
# IOGPUFamily driver.  Safe to set unconditionally.
if "AGX_RELAX_CDM_CTXSTORE_TIMEOUT" not in os.environ:
    os.environ["AGX_RELAX_CDM_CTXSTORE_TIMEOUT"] = "1"

We also classify the corresponding panic signature (ctxstore_timeout) so when a kernel.log post-mortem shows IOGPUCommandQueue ... context store timeout, our detect_panic_signature() flags it specifically rather than lumping it under generic "panic". Linked back to mlx#3267 in the comment so future maintainers can trace the rationale.

Doesn't fix the root cause — Apple-side as you noted — but pairing the env var with caffeinate -s / display-sleep / SSH-from-another-machine seems to cover most of the user-space surface.

Harperbot avatar Apr 28 '26 12:04 Harperbot

Data point: on Apple M5 Max this watchdog kill escalates from a catchable process exception to a full watchdogd kernel panic + hard reboot during sustained FLUX.2 LoRA training — and AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 looks like the right lever here too.

Environment

  • Hardware: Apple M5 Max, Mac17,7, SoC T6050, 128 GB unified memory
  • OS: macOS 26.5.1 (25F80), kernel Darwin 25.5.0 … xnu-12377.121.6~2/RELEASE_ARM64_T6050
  • Originally on mlx / mlx-metal 0.30.6, mflux 0.17.5, mlx-lm 0.29.1, Python 3.14
  • Workload: mflux-train FLUX.2 Klein LoRA — 25-image dataset, 768px, batch_size 1, quantize: null (bf16 base), low_ram: true, 600 steps

Symptom (differs from the OP — worse) Instead of the catchable kIOGPUCommandBufferCallbackErrorImpactingInteractivity exception, the machine hard-reboots mid-training. Three reproductions, all kernel watchdog-timeout panics with an identical signature (caller addresses differ only by ASLR slide):

panic(cpu N caller 0x…): watchdog timeout: no checkins from watchdogd in 90 seconds

(third occurrence said …in 93 seconds). Top backtrace frames are in com.apple.driver.AppleARMWatchdogTimer / AppleInterruptControllerV3 — i.e. the watchdog firing, not the originating fault. A watchdogd timeout means nothing could be scheduled for ~90 s, so the whole system stalled rather than a single process being killed. Crashes occur a fairly consistent depth into the run (sustained GPU compute), consistent with this thread's "latency / interactivity-impacting commands" framing rather than a memory ceiling (memory pressure was elevated-but-not-critical at panic time).

This looks like the same GPU-watchdog mechanism described here, just escalating past a process kill to a system reboot on this newer silicon — which also means subprocess isolation / process-teardown between training segments does not prevent it (matching @Harperbot's note that the kill is above the process boundary).

Applying the fix We've adopted @zcbenz's AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 (set automatically before our trainer initializes Metal) plus the display-asleep / caffeinate -s guidance from this thread, and pinned mlx/mlx-metal to 0.31.2 (off the 0.30.6 the panics happened on). A sustained segmentation-off bf16 validation run on the M5 Max with the env var set is in progress; happy to report back whether it clears the panic window.

Possibly related (same hardware class, IOGPU kernel panics under sustained MLX load, different signature): #3186.

atomantic avatar Jun 27 '26 17:06 atomantic

Reporting back as promised — and with the first telemetry-captured panic, which points squarely at this issue's active-display mechanism.

On the M5 Max (Mac17,7/T6050, 128 GB, macOS 26.5.1), a sustained segmentation-off 9B-bf16 FLUX.2 LoRA training run with AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 set still hard-rebooted ~11 minutes in (right as the first training step began), with the same watchdog timeout: no checkins from watchdogd in 93 seconds panic (AppleARMWatchdogTimer / AppleInterruptControllerV3). The env var alone did not prevent it here — but importantly, the display was active for this run (caffeinate -s keeps the system awake but does not put the display to sleep).

The captured telemetry (powermetrics, 5 s cadence) makes the mechanism unambiguous:

  • Thermal pressure: Nominal right up to the end, GPU pegged at ~1592 MHz / 97% active / 24.4 W — so this is not thermal throttling.
  • The powermetrics log goes silent ~3 minutes before the watchdog fires (last sample 10:12:19, panic 10:15:18) → a GPU driver hang / whole-system stall, not a long single kernel.
  • The paniclog's busiest thread in the panicked task is WindowServer (top cpu_usage), and memory was fine (compressor 13%, swap OK) — i.e. active-display GPU compositing contending with the training command buffers, exactly the failure this issue describes, just escalated from a process kill to a full reboot on this newer/heavier config.

So on M5-class silicon with a large (9B bf16) model, AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 is necessary but not sufficient when the display is live. What does survive on this box: keeping the display genuinely off (lid closed / display asleep / SSH headless) and/or chunking the work so no single sustained-GPU stretch is long enough to starve the scheduler. Next test on our side is 9B seg-off with the display actually asleep, to confirm display-off alone clears it. Sharing the telemetry signature in case it's useful corroboration that the trigger is WindowServer contention rather than memory or heat.

atomantic avatar Jun 27 '26 17:06 atomantic

Following up with the clean A/B result — display-off fully clears it on the M5 Max, confirming this issue's root cause.

Same config both runs (mflux FLUX.2 Klein 9B bf16, 768px, batch 1, segmentation off, sustained), AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 set in both. The only variable was the display:

Display Result
active (caffeinate -s, panel on) hard reboot at step 0, ~11 min — watchdog timeout … watchdogd in 93 s
asleep (pmset displaysleepnow, lid open) reached step 302/600, cleared the panic window cleanly, no panic (box up 5h20m)

So on this hardware the env var alone is necessary-but-not-sufficient for a heavy (9B bf16) sustained workload, but AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1 + display asleep is a reliable combination. Telemetry on the failed run had Current pressure level: Nominal (not thermal) and WindowServer as the top-CPU thread, exactly matching the active-display-compositing mechanism described here — just escalated to a full reboot rather than a catchable exception on this newer/heavier config. pmset displaysleepnow (display sleep, system stays awake) is a convenient programmatic way to get the display-off state without closing the lid (which would sleep the whole machine). Thanks @zcbenz / @Harperbot — the env var + display-off guidance from this thread is what got a previously-100%-panicking run to complete.

atomantic avatar Jun 27 '26 22:06 atomantic