Skip to content

Metal residency-set OOM during LoRA backward on qwen3_5 at --max-seq-length > 512 (M4 Max 36 GB) #3539

Closed

Description

@festusje8-eng

Environment

  • mlx 0.31.2
  • mlx-lm 0.31.3
  • Hardware: Apple M4 Max, 36 GB unified memory
  • macOS 26.2 (25C56)
  • Model: mlx-community/Qwen3.5-4B-MLX-4bit (qwen3_5 arch — Gated DeltaNet hybrid + sparse MoE, 4-bit)

Summary

LoRA training on qwen3_5 fails with a hard Metal-level OOM (kIOGPUCommandBufferCallbackErrorOutOfMemory) at --max-seq-length 1024 on a 36 GB machine, despite the same configuration succeeding at --max-seq-length 512 with only 10.9 GB peak. The 2× context bump produces a >3× memory footprint and a Metal residency-set commit failure, not a graceful allocator-side error. Suggests buffers (likely KV-cache slice writes) are accumulating in the residency set rather than being reused across steps.

Minimal repro

python3 -m mlx_lm.lora \
  --model mlx-community/Qwen3.5-4B-MLX-4bit \
  --train --data <dir-with-8-jsonl-records> \
  --num-layers 4 --batch-size 1 \
  --max-seq-length 1024 --grad-checkpoint \
  --iters 5

Observed behavior

--max-seq-length Result Peak memory
512 ✅ succeeds 10.92 GB
1024 ❌ Metal OOM, SIGABRT after first val pass during backward >32 GB before crash

All other flags held constant. --grad-checkpoint is on. Batch size is 1. Only 4 LoRA layers attached. Disk-resident model is ~2.4 GB.

Crash frame chain (relevant excerpt)

mlx::core::gpu::check_error
  → mlx::core::SliceUpdate::eval_gpu
    → mlx::core::metal::MetalAllocator::malloc
      → AGXG16XFamilyResidencySet::_commitAddedAllocations
        → IOGPUResource::commit  (kernel rejects)

Failure site is inside SliceUpdate::eval_gpu, consistent with KV-cache slice writes during the attention forward/backward path.

Hypothesis

Per-step buffer allocation in slice updates accumulates in the Metal residency set without being recycled. At ctx=512 the working set fits regardless; at ctx=1024 the per-step growth exceeds the OS-allowed residency commit before any allocator-level eviction can fire. May be qwen3_5-specific — Gated DeltaNet's linear-attention path has a different per-step KV write pattern than vanilla transformers and may interact poorly with the slice-update allocation strategy.

What would help

  • Confirmation of whether SliceUpdate is expected to reuse buffers across training steps on the qwen3_5 codepath
  • Guidance on whether mx.metal.set_cache_limit / clear_cache would mitigate, or whether the issue is upstream of the allocator cache
  • Whether the qwen3_5 attention impl has a known higher residency footprint than qwen3

Happy to attach the full Apple crash report and a tcmalloc-style allocation trace if useful.

Activity

  1. festusje8-eng commented on May 13, 2026

    @festusje8-eng
    Author

    Update: hit this twice more, with two new data points that narrow the root cause.

    Data point 2 — inference-time crash, no LoRA training involved

    Running a standard mlx_lm inference loop (benchmark eval over a model with adapter loaded) crashed at the same site. Same frame chain on the completion-handler thread:

    mlx::core::gpu::check_error
      → invocation function for block in MTL::CommandBuffer::addCompletedHandler
    

    This rules out the LoRA backward path as a necessary condition. The bug fires under plain inference when prompts are long and varied (benchmark suite has prompts up to several KB).

    Data point 3 — main-thread frame caught in the act

    Third crash captured the actual allocating frame on the main thread (not just the completion handler):

    mlx::core::SliceUpdate::eval_gpu
      → mlx::core::copy_gpu
        → mlx::core::set_copy_output_data
          → mlx::core::metal::MetalAllocator::malloc           (+264)
            → -[AGXBuffer initWithDevice:length:alignment:...]  (brand-new buffer)
              → -[IOGPUMetalBuffer initWith...]
                → IOGPUResourceCreate                           (kernel-side alloc)
    

    SliceUpdate::eval_gpu is going through copy_gpu → set_copy_output_data → MetalAllocator::malloc, and the allocator is reaching past its cache to IOGPUResourceCreate — i.e., a fresh kernel-side IOGPU resource per slice update. The residency set grows monotonically until the OS rejects the next commit.

    Refined hypothesis

    It looks less like "big working set on qwen3_5" and more like SliceUpdate output buffers aren't being recycled through the allocator cache on the qwen3_5 codepath. The first crash's SliceUpdate frame, the inference-time crash, and this third crash showing set_copy_output_data allocating fresh all point at the same shape: per-slice-update buffer allocation accumulating in the residency set across both training and inference.

    Tried / planning to try

    • mx.metal.clear_cache() between inference samples — about to add. Likely won't help if the issue is the residency set (above the allocator cache), but cheap to try.
    • mx.metal.set_cache_limit(...) — any guidance on whether forcing a smaller cache changes residency-set growth?

    Happy to capture an Instruments allocations trace or a MTL_DEBUG_LAYER=1 log if that would help. Three crash reports archived; can attach.

  2. festusje8-eng commented on May 13, 2026

    @festusje8-eng
    Author

    Adding a 4th data point — same root cause, different op:

    Crash signature: Negative::eval_gpu during inference (mlx_lm.generate)

    3  AGXMetalG16X  -[AGXG16XFamilyResidencySet _commitAddedAllocations:count:removedAllocations:count:] + 1312
    4  libmlx        mlx::core::metal::MetalAllocator::malloc(unsigned long) + 328
    5  libmlx        mlx::core::set_unary_output_data(...) + 124
    6  libmlx        mlx::core::Negative::eval_gpu(...) + 120
    7  libmlx        mlx::core::gpu::eval(...) + 200
    

    Triggered Metal completion handler abort:

    Thread 27 Crashed:  Dispatch queue: com.Metal.CompletionQueueDispatch
    9  libmlx  mlx::core::gpu::check_error(MTL::CommandBuffer*) + 244
    

    Hardware: M4 Max, 36 GB UMA, macOS 26.2.

    This means the residency-set leak hits within a single generate() call, not just across calls — so the per-prompt mx.metal.clear_cache() workaround from my earlier comment isn't sufficient for longer generations. Working around it now by switching to stream_generate and calling clear_cache() every 32 tokens.

    Summary of repro paths observed so far on qwen3_5 / 4B class:

    1. SliceUpdate::eval_gpu during LoRA backward (training, original report)
    2. copy_gpu during inference cold-start after adapter load
    3. Negative::eval_gpu during streaming generation (this report)

    All three terminate in _commitAddedAllocations → IOGPUResourceGroupUpdateResources abort, which strongly suggests the IOGPU resource group is unbounded as ops queue up, rather than per-op allocator misbehavior.

  3. zcbenz commented on May 13, 2026

    @zcbenz
    Member

    The RAM needed for training grows quadratically as sequence length increases, so I'm afraid the OOM is not something we can simply solve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions