281 lines
11 KiB
Swift
281 lines
11 KiB
Swift
import Foundation
|
||
import MLXLLM
|
||
import MLXLMCommon
|
||
import Tokenizers
|
||
|
||
actor MLXProvider: InferenceProvider {
|
||
private var loaded: (directory: String, container: ModelContainer)?
|
||
|
||
private var eviction: Task<Void, Never>?
|
||
private var idle: Duration?
|
||
private var weightLimit: UInt64?
|
||
private var active = false
|
||
|
||
func configureRuntime(idle: Duration?, weightLimit: UInt64?) {
|
||
self.idle = idle
|
||
self.weightLimit = weightLimit
|
||
scheduleEviction()
|
||
}
|
||
|
||
func modelName() -> String? {
|
||
loaded.map { URL(fileURLWithPath: $0.directory).lastPathComponent }
|
||
}
|
||
|
||
func modelDirectory() -> String? { loaded?.directory }
|
||
|
||
func unload() {
|
||
guard !active else { return }
|
||
eviction?.cancel()
|
||
eviction = nil
|
||
loaded = nil
|
||
}
|
||
|
||
private func scheduleEviction() {
|
||
eviction?.cancel()
|
||
eviction = nil
|
||
guard !active, loaded != nil, let idle else { return }
|
||
eviction = Task { [weak self] in
|
||
do { try await Task.sleep(for: idle) }
|
||
catch { return }
|
||
await self?.evictWhenIdle()
|
||
}
|
||
}
|
||
|
||
private func evictWhenIdle() {
|
||
guard !Task.isCancelled else { return }
|
||
unload()
|
||
}
|
||
|
||
func load(_ directory: String) async throws {
|
||
guard !active else { throw StudioError("MLX is busy.") }
|
||
active = true
|
||
eviction?.cancel()
|
||
defer {
|
||
active = false
|
||
scheduleEviction()
|
||
}
|
||
_ = try await container(for: directory)
|
||
}
|
||
|
||
private func container(for directory: String) async throws -> ModelContainer {
|
||
let model: ModelContainer
|
||
if let loaded, loaded.directory == directory {
|
||
model = loaded.container
|
||
} else {
|
||
let url = URL(fileURLWithPath: directory, isDirectory: true)
|
||
guard MLXLibrary.isModel(at: url) else {
|
||
throw StudioError("Select a complete MLX model folder with a readable config.json and all safetensors weight files.")
|
||
}
|
||
if let weightLimit, try MLXRuntimeLimits.weightBytes(in: url) > weightLimit {
|
||
throw StudioError("The model’s weight files exceed the configured MLX weight limit.")
|
||
}
|
||
loaded = nil
|
||
model = try await LLMModelFactory.shared.loadContainer(from: url, using: StudioMLXTokenizerLoader())
|
||
try Task.checkCancellation()
|
||
loaded = (directory, model)
|
||
}
|
||
return model
|
||
}
|
||
|
||
nonisolated func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
||
streaming { continuation in
|
||
try await self.generate(request, continuation: continuation)
|
||
}
|
||
}
|
||
|
||
private func generate(_ request: InferenceRequest, continuation: AsyncThrowingStream<Delta, Error>.Continuation) async throws {
|
||
try Task.checkCancellation()
|
||
guard !active else { throw StudioError("MLX is already generating a reply.") }
|
||
active = true
|
||
eviction?.cancel()
|
||
eviction = nil
|
||
defer {
|
||
active = false
|
||
scheduleEviction()
|
||
}
|
||
let directory = request.model
|
||
let model = try await container(for: directory)
|
||
let history: [Chat.Message] = LocalChatHistory.prepare(request.messages).map {
|
||
switch $0.role {
|
||
case .system: .system($0.content)
|
||
case .user: .user($0.content)
|
||
case .assistant: .assistant($0.content)
|
||
}
|
||
}
|
||
let supportsThinking = ThinkingOutput.supportsMLX(directory)
|
||
var context: [String: any Sendable]?
|
||
if supportsThinking {
|
||
switch request.thinking {
|
||
case .off: context = ["enable_thinking": false]
|
||
case .on: context = ["enable_thinking": true]
|
||
case .automatic, .low, .medium, .high: break
|
||
}
|
||
}
|
||
var thinkingOutput = ThinkingOutput()
|
||
let input: LMInput
|
||
do {
|
||
input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
||
} catch let error where (error as NSError).domain == "Jinja.TemplateException" {
|
||
throw StudioError("The MLX model’s chat template rejected this conversation. Try sending the message in a new chat.")
|
||
}
|
||
let config = request.parameters
|
||
let parameters = GenerateParameters(maxTokens: config.maxTokens ?? 1024, maxKVSize: config.mlxCache,
|
||
temperature: Float(config.temperature ?? 0.6),
|
||
topP: Float(config.topP ?? 1),
|
||
repetitionPenalty: config.repeatPenalty.map(Float.init),
|
||
repetitionContextSize: config.repeatLastN ?? 20,
|
||
prefill: .init(stepSize: config.mlxPrefill ?? 512, chunking: .remainder))
|
||
let output = try await model.generate(input: input, parameters: parameters)
|
||
var stopMatcher = StopMatcher(sequences: config.stop)
|
||
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
|
||
var finished = false
|
||
generation: for await event in output {
|
||
try Task.checkCancellation()
|
||
switch event {
|
||
case .chunk(let chunk):
|
||
let text = stopMatcher.append(chunk)
|
||
if supportsThinking {
|
||
for delta in thinkingOutput.append(text) { continuation.yield(delta) }
|
||
} else if !text.isEmpty {
|
||
continuation.yield(.answer(text))
|
||
}
|
||
if stopMatcher.stopped {
|
||
finished = true
|
||
break generation
|
||
}
|
||
case .info(let info):
|
||
finished = true
|
||
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
||
case .toolCall, .rejectedToolCall:
|
||
continuation.yield(.committed)
|
||
throw StudioError("The MLX model returned a tool call, but no tools are configured.")
|
||
}
|
||
}
|
||
try Task.checkCancellation()
|
||
guard finished else { throw StudioError("MLX generation ended without completion information.") }
|
||
let remainder = stopMatcher.finish()
|
||
if supportsThinking {
|
||
for delta in thinkingOutput.append(remainder) + thinkingOutput.finish() { continuation.yield(delta) }
|
||
} else if !remainder.isEmpty {
|
||
continuation.yield(.answer(remainder))
|
||
}
|
||
}
|
||
}
|
||
|
||
enum MLXRuntimeLimits {
|
||
static let idleKey = "mlxIdleMinutes"
|
||
static let weightKey = "mlxWeightLimitGiB"
|
||
static let defaultIdleMinutes = 15
|
||
|
||
static func weightBytes(in directory: URL) throws -> UInt64 {
|
||
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
|
||
var seen: Set<URL> = []
|
||
var total: UInt64 = 0
|
||
for file in files where file.pathExtension.lowercased() == "safetensors" {
|
||
let target = file.resolvingSymlinksInPath()
|
||
guard seen.insert(target).inserted else { continue }
|
||
let values = try target.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||
if values.isRegularFile == true, let size = values.fileSize, size > 0 {
|
||
let (sum, overflow) = total.addingReportingOverflow(UInt64(size))
|
||
total = overflow ? UInt64.max : sum
|
||
}
|
||
}
|
||
return total
|
||
}
|
||
}
|
||
|
||
struct ThinkingOutput {
|
||
private static let start = "<think>"
|
||
private static let end = "</think>"
|
||
private var buffer = ""
|
||
private var readingThinking = false
|
||
private var decided = false
|
||
|
||
init(prefilled: Bool = false) {
|
||
readingThinking = prefilled
|
||
decided = prefilled
|
||
}
|
||
|
||
static func supportsMLX(_ folder: String) -> Bool {
|
||
guard !folder.isEmpty else { return false }
|
||
let url = URL(fileURLWithPath: folder).appending(path: "tokenizer_config.json")
|
||
guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize,
|
||
size < 2_000_000,
|
||
let data = try? Data(contentsOf: url, options: .mappedIfSafe),
|
||
let config = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||
let template = config["chat_template"] as? String else { return false }
|
||
return template.contains("enable_thinking") && template.contains(start) && template.contains(end)
|
||
}
|
||
|
||
mutating func append(_ text: String) -> [Delta] {
|
||
buffer += text
|
||
if !decided {
|
||
let candidate = buffer.drop(while: \.isWhitespace)
|
||
if candidate.isEmpty && buffer.count < 32 { return [] }
|
||
if candidate.hasPrefix(Self.start) {
|
||
buffer = String(candidate.dropFirst(Self.start.count))
|
||
readingThinking = true
|
||
} else if Self.start.hasPrefix(candidate) && !candidate.isEmpty {
|
||
return []
|
||
}
|
||
decided = true
|
||
}
|
||
if !readingThinking { return drain(asThinking: false) }
|
||
if let close = buffer.range(of: Self.end) {
|
||
let reasoning = String(buffer[..<close.lowerBound])
|
||
buffer = String(buffer[close.upperBound...])
|
||
readingThinking = false
|
||
return (reasoning.isEmpty ? [] : [.thinking(reasoning)]) + drain(asThinking: false)
|
||
}
|
||
let length = (1..<Self.end.count).reversed().first { size in
|
||
Self.end.hasPrefix(buffer.suffix(size)) && buffer.count >= size
|
||
} ?? 0
|
||
let complete = String(buffer.dropLast(length))
|
||
buffer = String(buffer.suffix(length))
|
||
return complete.isEmpty ? [] : [.thinking(complete)]
|
||
}
|
||
|
||
mutating func finish() -> [Delta] { drain(asThinking: readingThinking) }
|
||
|
||
private mutating func drain(asThinking: Bool) -> [Delta] {
|
||
guard !buffer.isEmpty else { return [] }
|
||
defer { buffer = "" }
|
||
return [asThinking ? .thinking(buffer) : .answer(buffer)]
|
||
}
|
||
}
|
||
|
||
|
||
private struct StudioMLXTokenizerLoader: TokenizerLoader {
|
||
func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer {
|
||
StudioMLXTokenizer(base: try await AutoTokenizer.from(modelFolder: directory))
|
||
}
|
||
}
|
||
|
||
private struct StudioMLXTokenizer: MLXLMCommon.Tokenizer {
|
||
let base: any Tokenizers.Tokenizer
|
||
|
||
var bosToken: String? { base.bosToken }
|
||
var eosToken: String? { base.eosToken }
|
||
var unknownToken: String? { base.unknownToken }
|
||
|
||
func encode(text: String, addSpecialTokens: Bool) -> [Int] {
|
||
base.encode(text: text, addSpecialTokens: addSpecialTokens)
|
||
}
|
||
|
||
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
|
||
base.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens)
|
||
}
|
||
|
||
func convertTokenToId(_ token: String) -> Int? { base.convertTokenToId(token) }
|
||
func convertIdToToken(_ id: Int) -> String? { base.convertIdToToken(id) }
|
||
|
||
func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
|
||
additionalContext: [String: any Sendable]?) throws -> [Int] {
|
||
do {
|
||
return try base.applyChatTemplate(messages: messages, tools: tools, additionalContext: additionalContext)
|
||
} catch Tokenizers.TokenizerError.missingChatTemplate {
|
||
throw MLXLMCommon.TokenizerError.missingChatTemplate
|
||
}
|
||
}
|
||
}
|