Files
ai_studio/Sources/GGUFProvider.swift
2026-11-18 13:55:47 +00:00

191 lines
9.6 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import llama
struct GGUFProvider: InferenceProvider {
private static let engine = GGUFEngine()
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in
try await Self.engine.generate(request, continuation)
}
}
}
private actor GGUFEngine {
init() { llama_backend_init() }
func generate(_ request: InferenceRequest, _ output: AsyncThrowingStream<Delta, Error>.Continuation) throws {
try Task.checkCancellation()
guard !request.messages.contains(where: { $0.imagePNG != nil }) else {
throw StudioError("This GGUF backend supports text input.")
}
guard !request.parameters.json else {
throw StudioError("JSON mode is unavailable for local GGUF chat. Turn it off in Generation settings.")
}
guard ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nil else { throw StudioError("Metal acceleration is unavailable.") }
let file = URL(fileURLWithPath: request.model)
guard FileManager.default.isReadableFile(atPath: file.path) else {
throw StudioError("Cannot read \(file.lastPathComponent). Import the model again if it was moved.")
}
var modelSettings = llama_model_default_params()
modelSettings.n_gpu_layers = .max
guard let model = llama_model_load_from_file(request.model, modelSettings) else {
throw StudioError("llama.cpp could not load \(file.lastPathComponent). Check that the download is complete and the file contains chat model weights.")
}
defer { llama_model_free(model) }
try Task.checkCancellation()
let vocab = llama_model_get_vocab(model)
let formatted = try format(LocalChatHistory.prepare(request.messages), model: model)
let thinking = GGUFThinking.prepare(formatted.prompt, template: formatted.template, mode: request.thinking)
let prompt = thinking.prompt
var thinkingOutput = ThinkingOutput(prefilled: thinking.prefilled)
func emit(_ text: String) {
if thinking.supported {
for delta in thinkingOutput.append(text) { output.yield(delta) }
} else if !text.isEmpty {
output.yield(.answer(text))
}
}
var tokens = [llama_token](repeating: 0, count: prompt.utf8.count + 32)
var count = tokenize(prompt, vocab: vocab, tokens: &tokens)
if count < 0 {
tokens = [llama_token](repeating: 0, count: -Int(count))
count = tokenize(prompt, vocab: vocab, tokens: &tokens)
}
let settings = request.parameters
var contextSettings = llama_context_default_params()
contextSettings.n_ctx = UInt32(min(settings.context ?? 4096, Int(llama_model_n_ctx_train(model))))
contextSettings.n_batch = min(512, contextSettings.n_ctx)
contextSettings.n_ubatch = min(contextSettings.n_ubatch, contextSettings.n_batch)
guard count > 0, UInt32(count) < contextSettings.n_ctx else {
throw StudioError("The prompt exceeds the GGUF model’s context window.")
}
guard let context = llama_init_from_model(model, contextSettings) else {
throw StudioError("llama.cpp could not allocate the GGUF context.")
}
defer { llama_free(context) }
let sampler = llama_sampler_chain_init(llama_sampler_chain_default_params())
defer { llama_sampler_free(sampler) }
llama_sampler_chain_add(sampler, llama_sampler_init_penalties(
llama_vocab_n_tokens(vocab), Int32(settings.repeatLastN ?? 64), Float(settings.repeatPenalty ?? 1),
Float(settings.frequencyPenalty ?? 0), Float(settings.presencePenalty ?? 0)))
if settings.temperature == 0 {
llama_sampler_chain_add(sampler, llama_sampler_init_greedy())
} else {
llama_sampler_chain_add(sampler, llama_sampler_init_top_k(Int32(settings.topK ?? 40)))
llama_sampler_chain_add(sampler, llama_sampler_init_top_p(Float(settings.topP ?? 0.95), 1))
llama_sampler_chain_add(sampler, llama_sampler_init_min_p(Float(settings.minP ?? 0), 1))
llama_sampler_chain_add(sampler, llama_sampler_init_temp(Float(settings.temperature ?? 0.8)))
llama_sampler_chain_add(sampler, llama_sampler_init_dist(settings.seed.map { UInt32(truncatingIfNeeded: $0) } ?? UInt32.max))
}
output.yield(.backend("GGUF · Metal"))
try tokens.withUnsafeMutableBufferPointer { buffer in
for offset in stride(from: 0, to: Int(count), by: Int(contextSettings.n_batch)) {
try Task.checkCancellation()
let length = min(Int(contextSettings.n_batch), Int(count) - offset)
try decode(context, buffer.baseAddress?.advanced(by: offset), count: Int32(length))
}
}
var pending = Data()
var produced = 0
var heldText = ""
let stops = settings.stop.filter { !$0.isEmpty }
let start = ContinuousClock.now
let limit = min(settings.maxTokens ?? 1024, Int(contextSettings.n_ctx) - Int(count))
for index in 0..<limit {
try Task.checkCancellation()
var token = llama_sampler_sample(sampler, context, -1)
if llama_vocab_is_eog(vocab, token) { break }
produced += 1
var bytes = [Int8](repeating: 0, count: 128)
var size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
if size < 0 {
bytes = [Int8](repeating: 0, count: -Int(size))
size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
}
if size > 0 {
pending.append(contentsOf: bytes.prefix(Int(size)).map { UInt8(bitPattern: $0) })
}
if let text = String(data: pending, encoding: .utf8), !text.isEmpty {
pending.removeAll(keepingCapacity: true)
heldText += text
if let end = stops.compactMap({ heldText.range(of: $0)?.lowerBound }).min() {
let visible = String(heldText[..<end])
if !visible.isEmpty { emit(visible) }
heldText = ""
break
}
let maxPrefix = stops.map(\.count).max() ?? 1
let keep = min(heldText.count, maxPrefix - 1)
let visible = String(heldText.dropLast(keep))
heldText = String(heldText.suffix(keep))
if !visible.isEmpty { emit(visible) }
}
if index + 1 < limit { try decode(context, &token, count: 1) }
}
try Task.checkCancellation()
heldText += String(decoding: pending, as: UTF8.self)
if !heldText.isEmpty { emit(heldText) }
if thinking.supported {
for delta in thinkingOutput.finish() { output.yield(delta) }
}
let elapsed = (ContinuousClock.now - start).components
let seconds = Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18
output.yield(.metrics(.init(tokens: produced, seconds: seconds)))
}
private func decode(_ context: OpaquePointer, _ tokens: UnsafeMutablePointer<llama_token>?, count: Int32) throws {
guard llama_decode(context, llama_batch_get_one(tokens, count)) == 0 else {
throw StudioError("llama.cpp could not decode the GGUF prompt or response.")
}
}
private func tokenize(_ prompt: String, vocab: OpaquePointer?, tokens: inout [llama_token]) -> Int32 {
llama_tokenize(vocab, prompt, Int32(prompt.utf8.count), &tokens, Int32(tokens.count), true, true)
}
private func format(_ messages: [Message], model: OpaquePointer) throws -> (prompt: String, template: String) {
let roles = messages.map { strdup($0.role.rawValue) }
let contents = messages.map { strdup($0.content.replacingOccurrences(of: "\0", with: "�")) }
defer {
roles.forEach { free($0) }
contents.forEach { free($0) }
}
let chat = zip(roles, contents).map { llama_chat_message(role: UnsafePointer($0), content: UnsafePointer($1)) }
guard let template = llama_model_chat_template(model, nil) else {
throw StudioError("This GGUF file has no chat template. Import an instruct or chat model.")
}
let size = llama_chat_apply_template(template, chat, chat.count, true, nil, 0)
guard size > 0 else { throw StudioError("llama.cpp does not support this GGUF chat template.") }
var buffer = [CChar](repeating: 0, count: Int(size) + 1)
let written = llama_chat_apply_template(template, chat, chat.count, true, &buffer, Int32(buffer.count))
guard written == size else { throw StudioError("llama.cpp could not format the chat.") }
return (String(cString: buffer), String(cString: template))
}
}
enum GGUFThinking {
private static let assistantMarker = "<|im_start|>assistant\n"
static func supports(_ template: String) -> Bool {
["enable_thinking", "<think>", "</think>", "<|im_start|>assistant"].allSatisfy { template.contains($0) }
}
static func prepare(_ prompt: String, template: String, mode: Thinking) -> (prompt: String, supported: Bool, prefilled: Bool) {
let supported = supports(template)
guard supported, prompt.hasSuffix(assistantMarker) else {
return (prompt, supported, supported && prompt.hasSuffix("<think>\n"))
}
switch mode {
case .on: return (prompt + "<think>\n", true, true)
case .off: return (prompt + "<think>\n\n</think>\n\n", true, false)
default: return (prompt, true, false)
}
}
}