Skip to content

fix: periodically clear MLX cache in transcription loop to bound memory growth - #6

Merged
KalebJS merged 1 commit into
KalebJS:mainfrom
pimenoffd:fix/mlx-cache-growth-in-transcription-loop
Aug 7, 2026
Merged

KalebJS merged 1 commit into
KalebJS:mainfrom
pimenoffd:fix/mlx-cache-growth-in-transcription-loop

Conversation

@pimenoffd

@pimenoffd pimenoffd commented Aug 7, 2026 •

Copy link
Copy Markdown

Summary

Long transcriptions (many VAD segments) leak MLX GPU memory because DiarizationPipeline/asr.py's per-segment loop never calls mx.clear_cache(). On a ~5 hour recording (1415 VAD segments) this pushed a 32 GB Apple Silicon Mac into ~10 GB of swap.

Root cause

whispermlx/asr.py, the per-segment transcription loop, calls mlx_whisper.transcribe() once per VAD segment but never releases MLX's internal buffer cache between calls:

pbar = tqdm(total=total_segments, desc="Transcribing", unit="seg")
for idx, vad_seg in enumerate(vad_segments):
    ...
    mlx_result = _mlx_whisper_module.transcribe(...)
    ...
    pbar.update(1)

MLX exposes mx.clear_cache() / mx.get_cache_memory() / mx.set_cache_limit() specifically for long-running loops with varying input shapes (each VAD segment has a different duration → different array shape → MLX's allocator keeps caching new buffer sizes without bound).

Reproduction / evidence

Isolated test: 300 synthetic segments (2–8s, random durations — mimicking real VAD segment variability), mlx-community/whisper-large-v3-turbo, measuring mx.get_cache_memory():

clear_every time (s) peak active (MB) peak cache (MB) # clears
never (current behavior) 161.9 1618.5 1429.1 0
5 138.2 1618.3 955.0 60
10 136.8 1681.6 1045.3 30
20 135.5 1618.5 1174.2 15
50 150.5 1618.3 1342.2 6
100 144.3 1618.3 1403.5 3

Somewhat surprising: periodic clear_cache() isn't a memory/speed tradeoff here — every interval tested was faster than never clearing, on top of bounding peak cache. Single run per config (not averaged), so exact ranking among the clearing intervals is noisy, but "clearing beats never" held across all 5 configs.

Correctness check: transcribing the same fixed input before vs. after 40 unrelated transcribe() calls with periodic clear_cache() in between produces byte-identical output (text and per-segment text match exactly) — clear_cache() only affects buffer reuse, not computed results.

Proposed fix

 import contextlib
 import io
 
+import mlx.core as mx
 import mlx_whisper as _mlx_whisper_module
 import numpy as np
 from tqdm import tqdm
@@
             chunk_text = mlx_result.get("text", "").strip()
             avg_logprob = _compute_avg_logprob(mlx_result.get("segments", []))
 
+            if (idx + 1) % 20 == 0:
+                mx.clear_cache()
             pbar.update(1)

Interval (20) is a starting point, not a hard recommendation — happy to share the full tuning script if useful for picking a better default, or to make it configurable (e.g. a clear_cache_every param on DiarizationPipeline/load_model, default on).

Environment

  • macOS, Apple Silicon, 32 GB
  • whispermlx 3.13.0
  • Model: mlx-community/whisper-large-v3-turbo, --diarize

Summary by CodeRabbit

  • Performance
    • Improved long transcription sessions by periodically clearing the MLX cache, helping manage memory usage during processing.

…ry growth

- Each VAD segment has a different audio length/shape, and MLX's buffer
  cache grows unbounded across a long loop of transcribe() calls since
  nothing ever calls mx.clear_cache() between iterations
- On a ~5 hour recording (1415 VAD segments) this pushed a 32GB Apple
  Silicon Mac into ~10GB of swap
- Tested: 300-segment synthetic benchmark shows peak cache growing from
  955MB (clear every 5) to 1429MB (never clearing) with no plateau;
  clearing every 20 segments also measured *faster* wall-clock time
  than never clearing (135.5s vs 161.9s), not just lower memory
- Verified clear_cache() doesn't change output: same fixed input
  transcribed before/after 40 unrelated calls with periodic clearing
  produces byte-identical text and segments
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The transcription flow now imports MLX Core and clears the MLX cache after every 20 VAD segments.

Changes

MLX Cache Management

Layer / File(s) Summary
Periodic cache clearing
whispermlx/asr.py
The transcription flow imports mlx.core and clears the MLX cache after every 20 processed VAD segments.

Estimated code review effort: 1 (Trivial) | ~3 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: periodic MLX cache clearing during transcription.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@KalebJS
KalebJS merged commit 329ef2e into KalebJS:main Aug 7, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants