288 lines
12 KiB
Swift
288 lines
12 KiB
Swift
import SwiftUI
|
||
import UniformTypeIdentifiers
|
||
import Metal
|
||
import llama
|
||
|
||
struct GGUFModelMetadata: Codable, Equatable, Sendable {
|
||
static let libraryKey = "ggufLibrary"
|
||
|
||
let path: String
|
||
let version: UInt32
|
||
let tensorFormat: String
|
||
let architecture: String
|
||
var hasThinkingTemplate: Bool? = nil
|
||
|
||
var supportsThinking: Bool {
|
||
hasThinkingTemplate ?? ["qwen35", "qwen35moe"].contains(architecture)
|
||
}
|
||
|
||
var architectureName: String {
|
||
switch architecture {
|
||
case "llama": "Llama"
|
||
case "qwen35", "qwen35moe": "Qwen3.5"
|
||
case "mpt": "MPT"
|
||
case "openelm": "OpenELM"
|
||
default: architecture
|
||
}
|
||
}
|
||
|
||
static func library(in data: Data) -> [Self] {
|
||
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
|
||
}
|
||
|
||
static func register(_ additions: [Self], in data: Data) throws -> Data {
|
||
var entries = library(in: data)
|
||
for model in additions {
|
||
entries.removeAll { $0.path == model.path }
|
||
entries.append(model)
|
||
}
|
||
return try JSONEncoder().encode(entries.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending })
|
||
}
|
||
|
||
static func read(_ url: URL) throws -> Self {
|
||
let file = try FileHandle(forReadingFrom: url)
|
||
defer { try? file.close() }
|
||
let version = try GGUFHeader.version(in: file.read(upToCount: 8) ?? Data())
|
||
guard let model = gguf_init_from_file(url.path, .init(no_alloc: true, ctx: nil)) else {
|
||
throw StudioError("Could not read the GGUF metadata.")
|
||
}
|
||
defer { gguf_free(model) }
|
||
|
||
let architectureKey = gguf_find_key(model, "general.architecture")
|
||
let tensorCount = gguf_get_n_tensors(model)
|
||
guard tensorCount > 0, architectureKey >= 0, gguf_get_kv_type(model, architectureKey) == GGUF_TYPE_STRING,
|
||
let architecture = gguf_get_val_str(model, architectureKey) else {
|
||
throw StudioError("This GGUF file does not contain model weights and architecture metadata.")
|
||
}
|
||
let templateKey = gguf_find_key(model, "tokenizer.chat_template")
|
||
guard templateKey >= 0, gguf_get_kv_type(model, templateKey) == GGUF_TYPE_STRING,
|
||
let template = gguf_get_val_str(model, templateKey), template.pointee != 0 else {
|
||
throw StudioError("This model has no embedded chat template. Choose a GGUF chat or instruct model.")
|
||
}
|
||
let fileSize = try file.seekToEnd()
|
||
let dataOffset = UInt64(gguf_get_data_offset(model))
|
||
guard dataOffset < fileSize else { throw StudioError("This GGUF file is incomplete.") }
|
||
let dataSize = fileSize - dataOffset
|
||
var bytesByType: [String: UInt64] = [:]
|
||
for index in 0..<tensorCount {
|
||
let type = String(cString: ggml_type_name(gguf_get_tensor_type(model, index))).uppercased()
|
||
let offset = UInt64(gguf_get_tensor_offset(model, index))
|
||
let size = UInt64(gguf_get_tensor_size(model, index))
|
||
guard offset <= dataSize, size <= dataSize - offset,
|
||
bytesByType[type, default: 0] <= dataSize - size else {
|
||
throw StudioError("This GGUF file contains incomplete tensor data.")
|
||
}
|
||
bytesByType[type, default: 0] += size
|
||
}
|
||
let primary = bytesByType.sorted {
|
||
$0.value == $1.value ? $0.key < $1.key : $0.value > $1.value
|
||
}.first?.key ?? "Unknown"
|
||
return Self(path: url.path, version: version, tensorFormat: primary, architecture: String(cString: architecture),
|
||
hasThinkingTemplate: GGUFThinking.supports(String(cString: template)))
|
||
}
|
||
}
|
||
|
||
enum LocalModelImport: Equatable, Sendable {
|
||
case mlx(String)
|
||
case gguf(GGUFModelMetadata)
|
||
|
||
var path: String {
|
||
switch self {
|
||
case .mlx(let path): path
|
||
case .gguf(let model): model.path
|
||
}
|
||
}
|
||
|
||
var format: String {
|
||
switch self {
|
||
case .mlx: "MLX · Safetensors"
|
||
case .gguf(let model): "GGUF · " + model.tensorFormat
|
||
}
|
||
}
|
||
|
||
static var lmStudioFolder: URL { URL.homeDirectory.appending(path: ".lmstudio/models") }
|
||
|
||
static func discover(in folder: URL) throws -> [Self] {
|
||
let files = FileManager.default
|
||
guard let entries = files.enumerator(at: folder, includingPropertiesForKeys: [.isDirectoryKey],
|
||
options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
|
||
throw StudioError("Could not open the model library folder.")
|
||
}
|
||
var models: [Self] = []
|
||
for case let url as URL in entries {
|
||
try Task.checkCancellation()
|
||
if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
|
||
if MLXLibrary.isModel(at: url) {
|
||
models.append(.mlx(url.resolvingSymlinksInPath().path))
|
||
entries.skipDescendants()
|
||
}
|
||
} else if url.pathExtension.lowercased() == "gguf",
|
||
!url.lastPathComponent.lowercased().hasPrefix("mmproj"),
|
||
let model = try? inspect(url) {
|
||
models.append(model)
|
||
}
|
||
}
|
||
return models
|
||
}
|
||
|
||
static func inspect(_ source: URL) throws -> Self {
|
||
guard source.isFileURL else { throw StudioError("Choose a local model file or folder.") }
|
||
let scoped = source.startAccessingSecurityScopedResource()
|
||
defer { if scoped { source.stopAccessingSecurityScopedResource() } }
|
||
let url = source.resolvingSymlinksInPath().standardizedFileURL
|
||
let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey])
|
||
if values.isDirectory == true {
|
||
guard MLXLibrary.isModel(at: url) else {
|
||
throw StudioError("Choose a complete MLX folder with a readable configuration and all safetensors weights.")
|
||
}
|
||
return .mlx(url.path)
|
||
}
|
||
guard values.isRegularFile == true else {
|
||
throw StudioError("Choose a regular GGUF file or an MLX model folder.")
|
||
}
|
||
return .gguf(try GGUFModelMetadata.read(url))
|
||
}
|
||
}
|
||
|
||
struct GGUFModels: View {
|
||
let selection: String?
|
||
var inUse = false
|
||
var filter = ""
|
||
var selectionDisabled = false
|
||
let select: (String) -> Void
|
||
@AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data()
|
||
@State private var showingImporter = false
|
||
@State private var inspecting = false
|
||
@State private var error: String?
|
||
@State private var notice: String?
|
||
|
||
private var models: [GGUFModelMetadata] {
|
||
GGUFModelMetadata.library(in: stored)
|
||
}
|
||
|
||
private var filteredModels: [GGUFModelMetadata] {
|
||
let query = filter.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
return models.filter { model in
|
||
query.isEmpty || [URL(fileURLWithPath: model.path).lastPathComponent,
|
||
model.architectureName, model.tensorFormat, "GGUF"].contains {
|
||
$0.localizedStandardContains(query)
|
||
}
|
||
}
|
||
}
|
||
|
||
var body: some View {
|
||
ModelLibrarySection("Local GGUF", key: "libraryGGUFExpanded") {
|
||
HStack {
|
||
memorySummary
|
||
Spacer()
|
||
Button("Import…", systemImage: "plus") { showingImporter = true }
|
||
.disabled(inspecting)
|
||
.accessibilityLabel("Import GGUF model")
|
||
}
|
||
if models.isEmpty && !inspecting {
|
||
Text("Import a GGUF chat model to run it on this Mac.")
|
||
.foregroundStyle(.secondary)
|
||
}
|
||
if !models.isEmpty && filteredModels.isEmpty {
|
||
Text("No matching GGUF models").foregroundStyle(.secondary)
|
||
}
|
||
ForEach(filteredModels, id: \.path) { model in
|
||
modelRow(model)
|
||
}
|
||
if inspecting {
|
||
ProgressView("Inspecting model…").controlSize(.small)
|
||
} else if let error {
|
||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange)
|
||
} else if let notice {
|
||
Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary)
|
||
}
|
||
}
|
||
.fileImporter(isPresented: $showingImporter, allowedContentTypes: [UTType(filenameExtension: "gguf") ?? .data]) {
|
||
switch $0 {
|
||
case .success(let url): Task { await importModel(url) }
|
||
case .failure(let failure): error = failure.localizedDescription
|
||
}
|
||
}
|
||
}
|
||
|
||
private var memorySummary: some View {
|
||
let systemMemory = ByteCountFormatter.string(fromByteCount: Int64(ProcessInfo.processInfo.physicalMemory), countStyle: .memory)
|
||
let recommended = MTLCreateSystemDefaultDevice().map {
|
||
ByteCountFormatter.string(fromByteCount: Int64($0.recommendedMaxWorkingSetSize), countStyle: .memory)
|
||
}
|
||
return Text(recommended.map { "Metal budget \($0) · Unified memory \(systemMemory)" } ?? "Metal unavailable")
|
||
.font(.caption)
|
||
.foregroundStyle(.secondary)
|
||
.help("Metal budget is the GPU’s recommended working set. Model weights and the context cache share system memory.")
|
||
}
|
||
|
||
private func importModel(_ url: URL) async {
|
||
inspecting = true
|
||
error = nil
|
||
notice = nil
|
||
defer { inspecting = false }
|
||
do {
|
||
let metadata = try await Task.detached(priority: .userInitiated) {
|
||
guard case .gguf(let model) = try LocalModelImport.inspect(url) else {
|
||
throw StudioError("Choose a GGUF chat model file.")
|
||
}
|
||
return model
|
||
}.value
|
||
stored = try GGUFModelMetadata.register([metadata], in: stored)
|
||
notice = "Added \(url.lastPathComponent)"
|
||
} catch {
|
||
self.error = error.localizedDescription
|
||
}
|
||
}
|
||
|
||
private func modelRow(_ model: GGUFModelMetadata) -> some View {
|
||
let url = URL(fileURLWithPath: model.path)
|
||
let name = url.deletingPathExtension().lastPathComponent
|
||
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize
|
||
let active = selection.map {
|
||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().standardizedFileURL.path ==
|
||
url.resolvingSymlinksInPath().standardizedFileURL.path
|
||
} ?? false
|
||
return HStack(spacing: 11) {
|
||
Image(systemName: active ? "checkmark.circle.fill" : "shippingbox")
|
||
.font(.title3)
|
||
.foregroundStyle(active ? Color.accentColor : Color.secondary)
|
||
.frame(width: 24)
|
||
VStack(alignment: .leading, spacing: 4) {
|
||
Text(name).fontWeight(active ? .semibold : .regular).lineLimit(1)
|
||
Text([
|
||
"GGUF v\(model.version)", model.architectureName, model.tensorFormat,
|
||
size.map { ByteCountFormatter.string(fromByteCount: Int64($0), countStyle: .file) } ?? "File missing"
|
||
].joined(separator: " · "))
|
||
.font(.caption)
|
||
.foregroundStyle(.secondary)
|
||
.help("Architecture: \(model.architecture). Quantisation shows the tensor format that accounts for the most weight bytes.")
|
||
ModelMemoryWarning(bytes: size.map(Int64.init))
|
||
}
|
||
Spacer()
|
||
if active {
|
||
Text(inUse ? "In use" : "Active")
|
||
.font(.caption.weight(.semibold))
|
||
.foregroundStyle(Color.accentColor)
|
||
.padding(.horizontal, 8)
|
||
.padding(.vertical, 4)
|
||
.background(Color.accentColor.opacity(0.12), in: Capsule())
|
||
} else {
|
||
Button("Use") { select(model.path) }.disabled(size == nil || selectionDisabled)
|
||
Button {
|
||
do { stored = try JSONEncoder().encode(models.filter { $0.path != model.path }) }
|
||
catch { self.error = error.localizedDescription }
|
||
} label: {
|
||
Image(systemName: "minus.circle")
|
||
}
|
||
.buttonStyle(.borderless)
|
||
.disabled(selectionDisabled)
|
||
.accessibilityLabel("Remove \(name) from library")
|
||
}
|
||
}
|
||
.padding(.vertical, 6)
|
||
.listRowBackground(active ? Color.accentColor.opacity(0.10) : nil)
|
||
.help(model.path)
|
||
}
|
||
}
|