Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Libraries/MLXLMCommon/LanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -354,8 +354,8 @@ public protocol LanguageModel: BaseLanguageModel, ChatConventionsProviding {
///
/// Implementations that chunk the prompt should drive the loop with
/// ``PrefillParameters/forEachChunk(total:reserving:defaultStepSize:maximumStepSize:_:)``,
/// which owns cancellation, pooling, and per-chunk progress. An
/// implementation returning `.logits` owns its whole
/// which owns cancellation, pooling, buffer cache clearing, and per-chunk
/// progress. An implementation returning `.logits` owns its whole
/// ``PrefillParameters/progress`` sequence, including the terminal
/// `(total, total)`; one returning `.tokens` reports only its own chunks —
/// the iterator that evaluates the remainder completes the sequence.
Expand Down
11 changes: 8 additions & 3 deletions Libraries/MLXLMCommon/PrefillParameters.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX

/// Parameters controlling how a prompt is prefilled into the ``KVCache``.
///
Expand Down Expand Up @@ -125,9 +126,12 @@ public struct PrefillParameters: Sendable {
/// range. The driver owns the loop's shared obligations: cooperative
/// cancellation between chunks (a long prompt must be interruptible — see
/// the note in `LLMModel.prepare`), an autorelease pool per chunk (long
/// prompts run hundreds of forwards before any autorelease boundary), and
/// the per-chunk ``progress`` report. `body` performs the model's forward
/// and its own cache fencing (`asyncEval`/`eval`).
/// prompts run hundreds of forwards before any autorelease boundary), the
/// per-chunk ``progress`` report, and clearing the MLX buffer cache after
/// each chunk, as mlx-lm does. The KV cache grows with every chunk, so the
/// buffers it outgrows cannot be reused and would otherwise stay in the
/// buffer cache. `body` performs the model's forward and its own cache
/// fencing (`asyncEval`/`eval`).
///
/// `reserving` positions are left unprocessed for the caller's final
/// forward — the one that produces logits (1 for every current caller).
Expand Down Expand Up @@ -156,6 +160,7 @@ public struct PrefillParameters: Sendable {
body(processed ..< processed + n)
processed += n
progress?(processed, total)
Memory.clearCache()
}
}
return processed
Expand Down
34 changes: 34 additions & 0 deletions Tests/MLXLMTests/PrefillClearCacheTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright © 2026 Apple Inc.

import MLX
import MLXLMCommon
import XCTest

final class PrefillClearCacheTests: XCTestCase {

// Buffers a chunk leaves behind, such as a KV cache the next chunk outgrows,
// must not stay in the buffer cache for the rest of the prefill.
func testEachChunkClearsBufferCache() throws {
let seeded = 256 * 1024 * 1024
var cached: [Int] = []
let processed = try PrefillParameters(stepSize: 4).forEachChunk(total: 9) { range in
cached.append(Memory.cacheMemory)
do {
let buffer = MLXArray.zeros([seeded], dtype: .uint8) + range.lowerBound + 1
eval(buffer)
}
// A freed buffer reaches the cache only after the GPU releases it on another
// thread, so wait for it before the driver clears the cache.
let deadline = Date().addingTimeInterval(1)
while Memory.cacheMemory < seeded, Date() < deadline {
usleep(1000)
}
XCTAssertGreaterThanOrEqual(Memory.cacheMemory, seeded)
}

XCTAssertEqual(processed, 8)
XCTAssertEqual(cached.count, 2)
XCTAssertLessThan(cached[1], seeded / 4)
XCTAssertLessThan(Memory.cacheMemory, seeded / 4)
}
}
Loading