182 lines
9.4 KiB
Swift
182 lines
9.4 KiB
Swift
import Foundation
|
|
import CoreML
|
|
import Tokenizers
|
|
|
|
enum CoreMLInputs {
|
|
static func mask(queryCount: Int, pastCount: Int) -> [Float16] {
|
|
let width = queryCount + pastCount
|
|
return (0..<queryCount).flatMap { query in
|
|
(0..<width).map { $0 > pastCount + query ? -Float16.greatestFiniteMagnitude : 0 }
|
|
}
|
|
}
|
|
}
|
|
|
|
struct CoreMLProvider: InferenceProvider {
|
|
private static let engine = CoreMLEngine()
|
|
|
|
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
|
streaming { output in
|
|
guard #available(macOS 15, *) else { throw StudioError("Core ML chat requires macOS 15 or later.") }
|
|
try await Self.engine.generate(request, output: output)
|
|
}
|
|
}
|
|
}
|
|
|
|
private actor CoreMLEngine {
|
|
@available(macOS 15, *)
|
|
func generate(_ request: InferenceRequest, output: AsyncThrowingStream<Delta, Error>.Continuation) async throws {
|
|
guard !request.messages.contains(where: { $0.imagePNG != nil }), !request.parameters.json else {
|
|
throw StudioError("Use text input and turn off JSON mode for this Core ML model.")
|
|
}
|
|
try Task.checkCancellation()
|
|
output.yield(.backend("Core ML"))
|
|
let entry = try CoreMLLibrary.inspect(URL(fileURLWithPath: request.model))
|
|
let package = URL(fileURLWithPath: entry.path)
|
|
let compiled = package.pathExtension.lowercased() == "mlmodelc" ? package : try await MLModel.compileModel(at: package)
|
|
defer { if compiled != package { try? FileManager.default.removeItem(at: compiled) } }
|
|
let config = MLModelConfiguration()
|
|
config.computeUnits = .cpuAndGPU
|
|
let model = try await MLModel.load(contentsOf: compiled, configuration: config)
|
|
let description = model.modelDescription
|
|
let ids = description.inputDescriptionsByName["inputIds"]?.multiArrayConstraint
|
|
let mask = description.inputDescriptionsByName["causalMask"]?.multiArrayConstraint
|
|
let logits = description.outputDescriptionsByName["logits"]?.multiArrayConstraint
|
|
guard Set(description.inputDescriptionsByName.keys) == ["inputIds", "causalMask"],
|
|
ids?.dataType == .int32, mask?.dataType == .float16, logits != nil,
|
|
!description.stateDescriptionsByName.isEmpty,
|
|
let width = mask?.shapeConstraint.sizeRangeForDimension.last as? NSRange,
|
|
width.location == 1, width.length > 1 else {
|
|
throw StudioError("This package does not match the supported stateful Core ML chat model inputs.")
|
|
}
|
|
let tokenizer = try await AutoTokenizer.from(modelFolder: package.deletingLastPathComponent())
|
|
let context = min(width.length, request.parameters.context ?? width.length)
|
|
let outputReserve = min(request.parameters.maxTokens ?? 256, max(1, context / 4))
|
|
let tokens = try preparePrompt(request.messages, tokenizer: tokenizer, capacity: context - outputReserve)
|
|
let state = model.makeState()
|
|
let limit = min(request.parameters.maxTokens ?? 256, context - tokens.count)
|
|
var scores: MLMultiArray?
|
|
for offset in stride(from: 0, to: tokens.count, by: 256) {
|
|
try Task.checkCancellation()
|
|
scores = try await predict(model, state: state, tokens: Array(tokens[offset..<min(tokens.count, offset + 256)]), past: offset)
|
|
}
|
|
var generated: [Int] = []
|
|
var decoded = ""
|
|
var stop = StopMatcher(sequences: request.parameters.stop)
|
|
let start = ContinuousClock.now
|
|
for index in 0..<limit {
|
|
try Task.checkCancellation()
|
|
if stop.stopped { break }
|
|
guard let currentScores = scores else { throw StudioError("Core ML did not return token scores.") }
|
|
let next = try choose(currentScores, parameters: request.parameters)
|
|
if next == tokenizer.eosTokenId { break }
|
|
generated.append(next)
|
|
let text = tokenizer.decode(tokens: generated, skipSpecialTokens: true)
|
|
let valid = String(text.reversed().drop(while: { $0 == "�" }).reversed())
|
|
if valid.hasPrefix(decoded) {
|
|
let visible = stop.append(String(valid.dropFirst(decoded.count)))
|
|
decoded = valid
|
|
if !visible.isEmpty { output.yield(.answer(visible)) }
|
|
}
|
|
if index + 1 < limit && !stop.stopped {
|
|
scores = try await predict(model, state: state, tokens: [next], past: tokens.count + index)
|
|
}
|
|
}
|
|
let remainder = stop.finish()
|
|
if !remainder.isEmpty { output.yield(.answer(remainder)) }
|
|
let elapsed = (ContinuousClock.now - start).components
|
|
output.yield(.metrics(.init(tokens: generated.count, seconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18)))
|
|
}
|
|
|
|
private func preparePrompt(_ messages: [Message], tokenizer: any Tokenizer, capacity: Int) throws -> [Int] {
|
|
func encode(_ messages: [Message]) throws -> [Int] {
|
|
do {
|
|
return try tokenizer.applyChatTemplate(messages: messages.map {
|
|
["role": $0.role.rawValue, "content": $0.content]
|
|
})
|
|
} catch {
|
|
throw StudioError("The Core ML tokenizer could not render this chat. Check that its chat template matches the model.")
|
|
}
|
|
}
|
|
|
|
let normalized = LocalChatHistory.prepare(messages)
|
|
var system = Array(normalized.prefix(while: { $0.role == .system }))
|
|
var turns = Array(normalized.dropFirst(system.count))
|
|
var tokens = try encode(system + turns)
|
|
while tokens.count > capacity && turns.count > 1 {
|
|
turns.removeFirst(min(2, turns.count - 1))
|
|
tokens = try encode(system + turns)
|
|
}
|
|
if tokens.count > capacity, let instructions = system.first {
|
|
let userTokens = try encode(turns)
|
|
guard userTokens.count <= capacity else {
|
|
throw StudioError("The latest message needs \(userTokens.count) tokens. This Core ML model has \(capacity) prompt tokens available.")
|
|
}
|
|
let characters = Array(instructions.content)
|
|
var low = 0
|
|
var high = characters.count
|
|
tokens = userTokens
|
|
while low < high {
|
|
let length = low + (high - low + 1) / 2
|
|
system[0].content = String(characters.prefix(length))
|
|
let candidate = try encode(system + turns)
|
|
if candidate.count <= capacity {
|
|
tokens = candidate
|
|
low = length
|
|
} else {
|
|
high = length - 1
|
|
}
|
|
}
|
|
}
|
|
guard !tokens.isEmpty, tokens.count <= capacity else {
|
|
throw StudioError("The Core ML prompt uses \(tokens.count) tokens. The available prompt budget is \(capacity).")
|
|
}
|
|
return tokens
|
|
}
|
|
|
|
@available(macOS 15, *)
|
|
private func predict(_ model: MLModel, state: MLState, tokens: [Int], past: Int) async throws -> MLMultiArray {
|
|
let input = try MLMultiArray(shape: [1, NSNumber(value: tokens.count)], dataType: .int32)
|
|
for (index, token) in tokens.enumerated() { input[index] = NSNumber(value: token) }
|
|
let attention = try MLMultiArray(shape: [1, 1, NSNumber(value: tokens.count), NSNumber(value: past + tokens.count)], dataType: .float16)
|
|
let values = CoreMLInputs.mask(queryCount: tokens.count, pastCount: past)
|
|
attention.withUnsafeMutableBytes { buffer, _ in
|
|
_ = buffer.bindMemory(to: Float16.self).update(from: values)
|
|
}
|
|
let features = try MLDictionaryFeatureProvider(dictionary: ["inputIds": input, "causalMask": attention])
|
|
let result = try await model.prediction(from: features, using: state)
|
|
guard let logits = result.featureValue(for: "logits")?.multiArrayValue else { throw StudioError("Core ML returned no logits.") }
|
|
return logits
|
|
}
|
|
|
|
private func choose(_ logits: MLMultiArray, parameters: GenerationParameters) throws -> Int {
|
|
let dimensions = logits.shape.map(\.intValue)
|
|
guard dimensions.count == 3, dimensions[0] == 1, dimensions[1] > 0, dimensions[2] > 0 else {
|
|
throw StudioError("Core ML returned an unsupported logits shape.")
|
|
}
|
|
let position = NSNumber(value: dimensions[1] - 1)
|
|
let scores = (0..<dimensions[2]).map { index in logits[[0, position, NSNumber(value: index)]].doubleValue }
|
|
let temperature = parameters.temperature ?? 0
|
|
guard let best = scores.indices.filter({ scores[$0].isFinite }).max(by: { scores[$0] < scores[$1] }) else {
|
|
throw StudioError("Core ML returned invalid token scores.")
|
|
}
|
|
guard temperature > 0 else { return best }
|
|
let candidates = scores.indices.filter { scores[$0].isFinite }.sorted { scores[$0] > scores[$1] }
|
|
let top = candidates.prefix(max(1, parameters.topK.flatMap { $0 > 0 ? $0 : nil } ?? 50))
|
|
let weights = top.map { exp((scores[$0] - scores[best]) / temperature) }
|
|
let total = weights.reduce(0, +)
|
|
let cutoff = total * (parameters.topP ?? 1)
|
|
var mass = 0.0
|
|
let retained = weights.prefix { weight in
|
|
guard mass == 0 || mass < cutoff else { return false }
|
|
mass += weight
|
|
return true
|
|
}
|
|
var draw = Double.random(in: 0..<mass)
|
|
for (token, weight) in zip(top, retained) {
|
|
draw -= weight
|
|
if draw <= 0 { return token }
|
|
}
|
|
return best
|
|
}
|
|
}
|