new features
This commit is contained in:
+60
-12
@@ -1,6 +1,7 @@
|
||||
import Foundation
|
||||
import MLXLLM
|
||||
import MLXLMCommon
|
||||
import Tokenizers
|
||||
|
||||
actor MLXProvider: InferenceProvider {
|
||||
private var loaded: (directory: String, container: ModelContainer)?
|
||||
@@ -20,6 +21,8 @@ actor MLXProvider: InferenceProvider {
|
||||
loaded.map { URL(fileURLWithPath: $0.directory).lastPathComponent }
|
||||
}
|
||||
|
||||
func modelDirectory() -> String? { loaded?.directory }
|
||||
|
||||
func unload() {
|
||||
guard !active else { return }
|
||||
eviction?.cancel()
|
||||
@@ -59,15 +62,15 @@ actor MLXProvider: InferenceProvider {
|
||||
if let loaded, loaded.directory == directory {
|
||||
model = loaded.container
|
||||
} else {
|
||||
loaded = nil
|
||||
let url = URL(fileURLWithPath: directory, isDirectory: true)
|
||||
guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else {
|
||||
throw StudioError("Select an MLX model folder containing config.json and model weights.")
|
||||
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.")
|
||||
}
|
||||
model = try await LLMModelFactory.shared.loadContainer(configuration: .init(directory: url))
|
||||
loaded = nil
|
||||
model = try await LLMModelFactory.shared.loadContainer(from: url, using: StudioMLXTokenizerLoader())
|
||||
try Task.checkCancellation()
|
||||
loaded = (directory, model)
|
||||
}
|
||||
@@ -92,14 +95,14 @@ actor MLXProvider: InferenceProvider {
|
||||
}
|
||||
let directory = request.model
|
||||
let model = try await container(for: directory)
|
||||
let history: [Chat.Message] = request.messages.map {
|
||||
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 = MLXThinking.supports(directory)
|
||||
let supportsThinking = ThinkingOutput.supportsMLX(directory)
|
||||
var context: [String: any Sendable]?
|
||||
if supportsThinking {
|
||||
switch request.thinking {
|
||||
@@ -108,15 +111,20 @@ actor MLXProvider: InferenceProvider {
|
||||
case .automatic, .low, .medium, .high: break
|
||||
}
|
||||
}
|
||||
var thinkingOutput = MLXThinking()
|
||||
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
||||
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,
|
||||
prefillStepSize: config.mlxPrefill ?? 512)
|
||||
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)"))
|
||||
@@ -138,7 +146,7 @@ actor MLXProvider: InferenceProvider {
|
||||
case .info(let info):
|
||||
finished = true
|
||||
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
||||
case .toolCall:
|
||||
case .toolCall, .rejectedToolCall:
|
||||
continuation.yield(.committed)
|
||||
throw StudioError("The MLX model returned a tool call, but no tools are configured.")
|
||||
}
|
||||
@@ -176,14 +184,19 @@ enum MLXRuntimeLimits {
|
||||
}
|
||||
}
|
||||
|
||||
struct MLXThinking {
|
||||
struct ThinkingOutput {
|
||||
private static let start = "<think>"
|
||||
private static let end = "</think>"
|
||||
private var buffer = ""
|
||||
private var readingThinking = false
|
||||
private var decided = false
|
||||
|
||||
static func supports(_ folder: String) -> Bool {
|
||||
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,
|
||||
@@ -230,3 +243,38 @@ struct MLXThinking {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user