Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: prompt cache

Louis2816aea9c609
diff --git a/mlx-server/Sources/MLXServer/ModelRunner.swift b/mlx-server/Sources/MLXServer/ModelRunner.swift
index 88e191224..99d64744d 100644
--- a/mlx-server/Sources/MLXServer/ModelRunner.swift
+++ b/mlx-server/Sources/MLXServer/ModelRunner.swift
@@ -8,7 +8,8 @@ import MLXVLM
actor ModelRunner {
private var container: ModelContainer?
private var modelId: String = ""
- private var promptCache: [String: PromptCache] = [:]
+ /// Stores a prompt cache for each loaded model
+ private let promptCache = NSCache<NSString, PromptCache>()
private var isVLM: Bool = false // Track if model is VLM (has different cache structure)
var isLoaded: Bool {
@@ -19,12 +20,6 @@ actor ModelRunner {
modelId
}
- /// Clear the prompt cache when loading a new model
- private func clearPromptCache() {
- promptCache.removeAll()
- log("[mlx] Prompt cache cleared")
- }
-
/// Warm up the model by running a short generation to initialize GPU kernels
func warmUp() async throws {
guard let container = container else {
@@ -210,26 +205,26 @@ actor ModelRunner {
self.modelId = modelId
log("[mlx] Model ready: \(modelId)")
- // Clear prompt cache when loading a new model
- clearPromptCache()
+ // Clear out the promptCache for new model load
+ promptCache.removeObject(forKey: modelId as NSString)
}
/// Build Chat.Message array from ChatMessages, including images and videos
private func buildChat(from messages: [ChatMessage]) -> [Chat.Message] {
messages.map { message in
let role: Chat.Message.Role =
- switch message.role {
- case "assistant":
+ switch message.role {
+ case "assistant":
.assistant
- case "user":
+ case "user":
.user
- case "system":
+ case "system":
.system
- case "tool":
+ case "tool":
.tool
- default:
+ default:
.user
- }
+ }
// Get image URLs from both explicit images field and content array format
var imageUrls = message.content.imageUrls
@@ -292,22 +287,38 @@ actor ModelRunner {
)
}
- /// Get or create a prompt cache for the current model
- /// Note: VLM models have different cache structure, so caching is skipped for them
- private func getPromptCache(context: ModelContext, parameters: GenerateParameters) -> PromptCache? {
- // VLM models have incompatible cache structure - skip prefix caching
- if isVLM {
- return nil
+ func getPromptCache(
+ fullPrompt: LMInput, parameters: GenerateParameters, context: ModelContext,
+ modelName: String
+ ) -> (PromptCache, LMInput) {
+
+ if self.isVLM {
+ return (PromptCache(cache: context.model.newCache(parameters: parameters)), fullPrompt)
+ }
+
+ let cache: PromptCache
+ if let existingCache = promptCache.object(forKey: modelName as NSString) {
+ cache = existingCache
+ } else {
+ // Create cache if it doesn't exist yet
+ cache = PromptCache(cache: context.model.newCache(parameters: parameters))
+ self.promptCache.setObject(cache, forKey: modelName as NSString)
}
- if let existingCache = promptCache[modelId] {
- return existingCache
+
+ let lmInput: LMInput
+
+ /// Remove prefix from prompt that is already in cache
+ if let suffix = cache.getUncachedSuffix(prompt: fullPrompt.text.tokens) {
+ lmInput = LMInput(text: LMInput.Text(tokens: suffix))
+ } else {
+ // If suffix is nil, the cache is inconsistent with the new prompt
+ // and the cache doesn't support trimming so create a new one here.
+ let newCache = PromptCache(cache: context.model.newCache(parameters: parameters))
+ self.promptCache.setObject(newCache, forKey: modelName as NSString)
+ lmInput = fullPrompt
}
- // Create new cache with the model's KV cache structure
- let modelCache = context.model.newCache(parameters: parameters)
- let newCache = PromptCache(cache: modelCache)
- promptCache[modelId] = newCache
- log("[mlx] Created new prompt cache with \(modelCache.count) KV layers for model: \(modelId)")
- return newCache
+
+ return (cache, lmInput)
}
/// Generate a chat completion (non-streaming)
@@ -347,17 +358,13 @@ actor ModelRunner {
let promptTokenCount = fullTokens.size
// Get or create prompt cache (nil for VLM models)
- let cache = await getPromptCache(context: context, parameters: generateParameters)
-
- // Determine if we can use cached prefix
- let lmInput: LMInput
- if let cache = cache, let suffix = cache.getUncachedSuffix(prompt: fullTokens) {
- lmInput = LMInput(text: LMInput.Text(tokens: suffix))
- log("[mlx] Using cached prefix, processing \(suffix.size) new tokens")
- } else {
- lmInput = fullInput
- log("[mlx] Cache miss, processing all \(fullTokens.size) tokens")
- }
+ // TODO: Prompt cache access isn't isolated
+ // Get the prompt cache and adjust new prompt to remove
+ // prefix already in cache, trim cache if cache is
+ // inconsistent with new prompt.
+ let (cache, lmInput) = await getPromptCache(
+ fullPrompt: fullInput, parameters: generateParameters, context: context,
+ modelName: modelId)
var output = ""
var completionTokenCount = 0
@@ -366,7 +373,7 @@ actor ModelRunner {
do {
for await generation in try MLXLMCommon.generate(
- input: lmInput, cache: cache?.cache, parameters: generateParameters, context: context
+ input: lmInput, cache: cache.cache, parameters: generateParameters, context: context
) {
switch generation {
case .chunk(let chunk):
@@ -478,17 +485,13 @@ actor ModelRunner {
let fullTokens = fullInput.text.tokens
// Get or create prompt cache (nil for VLM models)
- let cache = await self.getPromptCache(context: context, parameters: generateParameters)
-
- // Determine if we can use cached prefix
- let lmInput: LMInput
- if let cache = cache, let suffix = cache.getUncachedSuffix(prompt: fullTokens) {
- lmInput = LMInput(text: LMInput.Text(tokens: suffix))
- log("[mlx] Stream using cached prefix, processing \(suffix.size) new tokens")
- } else {
- lmInput = fullInput
- log("[mlx] Stream cache miss, processing all \(fullTokens.size) tokens")
- }
+ // TODO: Prompt cache access isn't isolated
+ // Get the prompt cache and adjust new prompt to remove
+ // prefix already in cache, trim cache if cache is
+ // inconsistent with new prompt.
+ let (cache, lmInput) = await getPromptCache(
+ fullPrompt: fullInput, parameters: generateParameters, context: context,
+ modelName: modelId)
var completionTokenCount = 0
var accumulated = ""
@@ -496,7 +499,7 @@ actor ModelRunner {
do {
for await generation in try MLXLMCommon.generate(
- input: lmInput, cache: cache?.cache, parameters: generateParameters, context: context
+ input: lmInput, cache: cache.cache, parameters: generateParameters, context: context
) {
switch generation {
case .chunk(let chunk):
diff --git a/mlx-server/Sources/MLXServer/PromptCache.swift b/mlx-server/Sources/MLXServer/PromptCache.swift
index 1d797d677..bb77a7e69 100644
--- a/mlx-server/Sources/MLXServer/PromptCache.swift
+++ b/mlx-server/Sources/MLXServer/PromptCache.swift
@@ -1,326 +1,124 @@
-import Foundation
+//
+// PromptCache.swift
+// mlx-swift-examples
+//
+// Created by Jolon Faichney on 3/5/2025.
+//
+
import MLX
import MLXLMCommon
-/// Manages KV cache between generate calls to avoid re-processing common prompt prefixes
+/// Stores the KV Cache between calls to ``generate`` and maintains
+/// the token ids reflected in the cache.
+///
+/// ``PromptCache`` is ``@unchecked Sendable`` which allows it
+/// to be used within the ``ModelContainer`` context.
+///
+/// TODO: cache isolation
public class PromptCache: @unchecked Sendable {
- /// The stored KV cache layers
private(set) var cache: [KVCache]
- /// The tokens corresponding to the cached KV state
private(set) var tokens: MLXArray
- /// Maximum number of cached tokens (0 = unlimited)
- private let maxTokens: Int
-
- /// LRU tracking: hash of prompt -> last access time
- private var lruOrder: [String: Date]
+ public init(cache: [KVCache]) {
+ log("[PromptCache.init]")
+ self.cache = cache
+ self.tokens = []
+ }
+
+ /// Returns the suffix of the prompt not already in cache, so that only
+ /// the new part is processed. The tokens of the cache are adjusted here
+ /// to reflect the new full prompt (i.e. the suffix tokens are added to the
+ /// cache tokens array), assuming that the prompt suffix will
+ /// be processed after the call to this function.
+ ///
+ /// Trims cache if necessary if part of the cache doesn't match the new
+ /// prompt. If the model doesn't support trimming and the cache needs to be
+ /// trimmed, will return nil for the caller to create a new cache.
+ ///
+ /// - Returns:
+ /// - If entirety of cache is in the new prompt:
+ /// - Return suffix of new prompt, less what is in the cache
+ /// - If only a portion of the cache is in the new prompt:
+ /// - Attempt to trim the cache to the common prefix
+ /// - Return suffix of prompt not in cache
+ /// - If the cache is not trimmable return nil for the caller
+ /// to create a new cache.
+ public func getUncachedSuffix(prompt: MLXArray) -> MLXArray? {
- /// Cache hits and misses for metrics
- private var hits: Int = 0
- private var misses: Int = 0
+ log("[getUncachedSuffix] self.tokens.size = \(self.tokens.size)")
- /// Lock for thread safety
- private let lock = NSLock()
+ log("cache[\(self.tokens.size)]: \(self.tokens)")
+ log("prompt[\(prompt.size)]: \(prompt)")
- public init(cache: [KVCache], maxTokens: Int = 0) {
- self.cache = cache
- self.tokens = MLXArray()
- self.maxTokens = maxTokens
- self.lruOrder = [:]
- }
-
- /// Returns the suffix of the prompt not already in cache
- /// If nil is returned, the entire prompt should be processed
- public func getUncachedSuffix(prompt: MLXArray) -> MLXArray? {
let comPrefixLength = commonPrefixLength(newPromptTokens: prompt)
-
- lock.lock()
- defer { lock.unlock() }
+ log("[getUncachedSuffix] comPrefixLength: \(comPrefixLength)")
if comPrefixLength == self.tokens.size {
- // All tokens already cached, return suffix to append
- let suffix = prompt[comPrefixLength..<prompt.size]
- if suffix.size > 0 {
- // Update LRU
- let hash = computeHash(for: prompt[0..<comPrefixLength])
- lruOrder[hash] = Date()
- return suffix
- }
- hits += 1
- return nil
+ let suffix = prompt[comPrefixLength ..< prompt.size]
+ log("Concating...")
+ self.tokens = concatenated([self.tokens, suffix], axis: 0)
+ return suffix
} else if comPrefixLength < self.tokens.size {
- // Part of the prompt diverges from cache
- // Check if we can trim the cache
if isTrimmable() {
- let trimmed = trim(self.tokens.size - comPrefixLength)
- self.tokens = self.tokens[0..<comPrefixLength]
- let suffix = prompt[comPrefixLength..<prompt.size]
- if suffix.size > 0 {
- let hash = computeHash(for: self.tokens)
- lruOrder[hash] = Date()
- return suffix
+ log("trimming: \(self.tokens.size - comPrefixLength)")
+ let trimmedLen = self.trim(self.tokens.size - comPrefixLength)
+ log("trimmed: \(trimmedLen)")
+ if trimmedLen != self.tokens.size - comPrefixLength {
+ log("Warning: request trimmed amount and actual trimmed amount are different")
}
+ self.tokens = self.tokens[0 ..< comPrefixLength]
+ let suffix = prompt[comPrefixLength ..< prompt.size]
+ self.tokens = concatenated([self.tokens, suffix], axis: 0)
+ return suffix
+ } else {
+ // Caller must create a new cache
+ return nil
}
- misses += 1
- return nil
}
- misses += 1
return nil
}
- /// Compute a hash for the given tokens
- private func computeHash(for tokens: MLXArray) -> String {
- // Simple hash using token values - in production, use a proper hash
- let tokenCount = Int(tokens.size)
- var hash = 0
- for i in 0..<min(tokenCount, 100) {
- let token = tokens[Int(i)].item(Int32.self)
- hash = hash &* 31 &+ Int(token)
- }
- return "hash_\(hash)"
- }
-
- /// Checks if all KV cache layers are trimmable
+ /// - Returns: true if all KV caches are trimmable
public func isTrimmable() -> Bool {
- return cache.isEmpty || cache.allSatisfy { $0.isTrimmable }
+ return cache.allSatisfy { $0.isTrimmable }
}
- /// Trims the cache by n tokens, returning the actual number trimmed
- @discardableResult
+ /// Trims all KV caches.
+ /// - Parameters:
+ /// - n: Amount to trim.
+ /// - Returns: Amount KV Caches were trimmed (may be less than ``n``).
public func trim(_ n: Int) -> Int {
- if cache.isEmpty || !isTrimmable() { return 0 }
+ if !self.isTrimmable() {
+ return 0
+ }
return cache.map { $0.trim(n) }.max() ?? 0
}
- /// Returns the length of the common prefix between cached and new tokens
+ /// Finds the common prefix between the cached prompt and
+ /// the new prompt.
+ /// - Parameters:
+ /// - newPromptTokens: Tokens to compare with cached tokens.
+ /// - Returns: Length of the common prefix
public func commonPrefixLength(newPromptTokens: MLXArray) -> Int {
- let cachedCount = Int(self.tokens.size)
- let newCount = Int(newPromptTokens.size)
-
- let limit = min(cachedCount, newCount)
- for i in 0..<limit {
- let cachedToken = self.tokens[Int(i)].item(Int32.self)
- let newToken = newPromptTokens[Int(i)].item(Int32.self)
- if cachedToken != newToken {
+ return commonPrefixLength(self.tokens, newPromptTokens)
+ }
+
+ /// Finds the common prefix between ``MLXArray``s.
+ /// - Parameters:
+ /// - array1: First array
+ /// - array2: Second array
+ /// - Returns: Length of the common prefix
+ public func commonPrefixLength(_ array1: MLXArray, _ array2: MLXArray) -> Int {
+ // TODO: Add test cases
+ log("Calculating common prefix: array1[\(array1.size)] array2[\(array2.size)]")
+ let minLength = min(array1.size, array2.size)
+ for i in 0 ..< minLength {
+ if all(array1[i] .!= array2[i]).item(Bool.self) {
return i
}
}
- return limit
+ return minLength
}
- /// Updates the cache with new KV cache and tokens
- public func update(cache: [KVCache], tokens: MLXArray) {
- lock.lock()
- defer { lock.unlock() }
-
- // Check if we need to evict
- if maxTokens > 0 && Int(tokens.size) > maxTokens {
- // Evict oldest entries
- evictOldest(extraTokens: Int(tokens.size) - maxTokens)
- }
-
- self.cache = cache
- self.tokens = tokens
-
- // Update LRU
- let hash = computeHash(for: tokens)
- lruOrder[hash] = Date()
-
- log("[mlx] Prompt cache updated with \(tokens.size) tokens, \(cache.count) layers")
- }
-
- /// Evict oldest cache entries to stay within limits
- private func evictOldest(extraTokens: Int) {
- guard extraTokens > 0 else { return }
-
- // Sort by last access time
- let sortedEntries = lruOrder.sorted { $0.value < $1.value }
-
- var tokensToEvict = extraTokens
- for (hash, _) in sortedEntries {
- if tokensToEvict <= 0 { break }
- lruOrder.removeValue(forKey: hash)
- tokensToEvict -= 16 // Assume block size of 16
- }
- }
-
- /// Get cache metrics
- public func getMetrics() -> CacheMetrics {
- lock.lock()
- defer { lock.unlock() }
-
- let total = hits + misses
- let hitRate = total > 0 ? Double(hits) / Double(total) : 0.0
-
- return CacheMetrics(
- totalTokens: Int(tokens.size),
- layers: cache.count,
- hits: hits,
- misses: misses,
- hitRate: hitRate,
- maxTokens: maxTokens
- )
- }
-
- /// Clear the cache and reset metrics
- public func clear() {
- lock.lock()
- defer { lock.unlock() }
-
- cache = []
- tokens = MLXArray()
- lruOrder.removeAll()
- hits = 0
- misses = 0
-
- log("[mlx] Prompt cache cleared")
- }
-}
-
-// MARK: - Shared KV Cache Manager
-
-/// Manages shared KV caches across multiple requests for common prefixes
-/// This enables significant speedup when processing similar system prompts
-final class SharedKVCacheManager: @unchecked Sendable {
- /// Shared cache entries indexed by prompt hash
- private var sharedCaches: [String: SharedCacheEntry] = [:]
-
- /// Lock for thread safety
- private let lock = NSLock()
-
- /// Maximum number of shared caches to maintain
- private let maxCaches: Int
-
- /// LRU tracking for eviction
- private var lruOrder: [String: Date] = [:]
-
- init(maxCaches: Int = 100) {
- self.maxCaches = maxCaches
- }
-
- /// Get or create a shared cache entry for the given prompt
- func getOrCreate(
- promptHash: String,
- promptTokens: MLXArray,
- cacheProvider: () -> [KVCache]
- ) -> SharedCacheEntry {
- lock.lock()
- defer { lock.unlock() }
-
- // Check if we have an existing cache
- if let existing = sharedCaches[promptHash] {
- // Update LRU
- lruOrder[promptHash] = Date()
- return existing
- }
-
- // Check if we need to evict
- if sharedCaches.count >= maxCaches {
- evictOldest()
- }
-
- // Create new cache
- let entry = SharedCacheEntry(
- tokens: promptTokens,
- cache: cacheProvider()
- )
-
- sharedCaches[promptHash] = entry
- lruOrder[promptHash] = Date()
-
- log("[mlx] Created shared KV cache for hash: \(promptHash)")
-
- return entry
- }
-
- /// Get cache entry if it exists (without creating)
- func getIfExists(_ promptHash: String) -> SharedCacheEntry? {
- lock.lock()
- defer { lock.unlock() }
-
- guard let entry = sharedCaches[promptHash] else { return nil }
-
- // Update LRU
- lruOrder[promptHash] = Date()
- return entry
- }
-
- /// Evict oldest cache entries
- private func evictOldest() {
- let sorted = lruOrder.sorted { $0.value < $1.value }
- let toRemove = sorted.prefix(maxCaches / 4) // Remove 25%
-
- for (hash, _) in toRemove {
- sharedCaches.removeValue(forKey: hash)
- lruOrder.removeValue(forKey: hash)
- }
-
- log("[mlx] Evicted \(toRemove.count) shared KV caches")
- }
-
- /// Clear all shared caches
- func clearAll() {
- lock.lock()
- defer { lock.unlock() }
-
- sharedCaches.removeAll()
- lruOrder.removeAll()
- log("[mlx] All shared KV caches cleared")
- }
-
- /// Get statistics
- func getStats() -> SharedCacheStats {
- lock.lock()
- defer { lock.unlock() }
-
- return SharedCacheStats(
- cacheCount: sharedCaches.count,
- maxCaches: maxCaches
- )
- }
-}
-
-/// Entry in the shared KV cache
-final class SharedCacheEntry {
- let tokens: MLXArray
- private(set) var cache: [KVCache]
- private(set) var useCount: Int = 0
- private(set) var lastAccess: Date
-
- init(tokens: MLXArray, cache: [KVCache]) {
- self.tokens = tokens
- self.cache = cache
- self.lastAccess = Date()
- }
-
- /// Use this cache entry
- func use() -> [KVCache] {
- useCount += 1
- lastAccess = Date()
- return cache
- }
-
- /// Update the underlying cache (e.g., after new tokens added)
- func updateCache(_ newCache: [KVCache]) {
- cache = newCache
- }
-}
-
-// MARK: - Supporting Types
-
-/// Cache metrics
-public struct CacheMetrics {
- let totalTokens: Int
- let layers: Int
- let hits: Int
- let misses: Int
- let hitRate: Double
- let maxTokens: Int
-}
-
-/// Statistics for shared cache manager
-struct SharedCacheStats {
- let cacheCount: Int
- let maxCaches: Int
}