252 lines
12 KiB
Swift
252 lines
12 KiB
Swift
import SwiftUI
|
|
import UniformTypeIdentifiers
|
|
import Metal
|
|
import CryptoKit
|
|
|
|
enum ModelMemoryBudget {
|
|
static let gpu = MTLCreateSystemDefaultDevice().map { Int64($0.recommendedMaxWorkingSetSize) }
|
|
static let system = Int64(ProcessInfo.processInfo.physicalMemory)
|
|
|
|
static func exceeds(bytes: Int64?, budget: Int64?) -> Bool {
|
|
guard let bytes, let budget, budget > 0 else { return false }
|
|
return bytes > budget
|
|
}
|
|
}
|
|
|
|
struct ModelMemoryWarning: View {
|
|
let bytes: Int64?
|
|
var coreML = false
|
|
var mlx = false
|
|
@AppStorage(MLXRuntimeLimits.weightKey) private var mlxGiB = 0
|
|
|
|
var body: some View {
|
|
let configured = mlxGiB > 0 && mlxGiB <= Int64.max / 1_073_741_824 ? Int64(mlxGiB) * 1_073_741_824 : nil
|
|
let overMLXLimit = mlx && ModelMemoryBudget.exceeds(bytes: bytes, budget: configured)
|
|
if overMLXLimit || ModelMemoryBudget.exceeds(bytes: bytes, budget: coreML ? ModelMemoryBudget.system : ModelMemoryBudget.gpu) {
|
|
Label(overMLXLimit ? "Exceeds MLX weight limit" : coreML ? "Exceeds Mac memory" : "Exceeds GPU memory budget",
|
|
systemImage: "exclamationmark.triangle.fill")
|
|
.font(.caption.weight(.semibold))
|
|
.foregroundStyle(.red)
|
|
.help("The model files alone exceed this budget. Generation also uses memory for context.")
|
|
}
|
|
}
|
|
}
|
|
|
|
struct CoreMLLibrary: Codable, Identifiable, Sendable {
|
|
static let key = "coreMLLibrary"
|
|
let path: String
|
|
let bytes: Int64
|
|
var id: String { path }
|
|
|
|
static func read(_ data: Data) -> [Self] { (try? JSONDecoder().decode([Self].self, from: data)) ?? [] }
|
|
|
|
static func inspect(_ source: URL) throws -> Self {
|
|
let extensions = ["mlpackage", "mlmodelc", "mlmodel"]
|
|
var package = source.resolvingSymlinksInPath()
|
|
guard package.isFileURL else { throw StudioError("Choose a local Core ML model.") }
|
|
if !extensions.contains(package.pathExtension.lowercased()) {
|
|
let entries = try FileManager.default.contentsOfDirectory(at: package, includingPropertiesForKeys: nil)
|
|
.filter { extensions.contains($0.pathExtension.lowercased()) }
|
|
guard entries.count == 1, let match = entries.first else {
|
|
throw StudioError("Choose a Core ML model or a folder containing one model package.")
|
|
}
|
|
package = match
|
|
}
|
|
let tokenizer = package.deletingLastPathComponent()
|
|
guard MLXLibrary.hasFile("tokenizer.json", in: tokenizer), MLXLibrary.hasFile("tokenizer_config.json", in: tokenizer) else {
|
|
throw StudioError("Put the matching tokenizer.json and tokenizer_config.json beside the Core ML model.")
|
|
}
|
|
let manager = FileManager.default
|
|
let properties: Set<URLResourceKey> = [.isRegularFileKey, .fileSizeKey]
|
|
let values = try package.resourceValues(forKeys: properties)
|
|
var size = Int64(values.fileSize ?? 0)
|
|
if values.isRegularFile != true {
|
|
size = 0
|
|
if let entries = manager.enumerator(at: package, includingPropertiesForKeys: Array(properties)) {
|
|
for case let file as URL in entries {
|
|
let attributes = try file.resourceValues(forKeys: properties)
|
|
if attributes.isRegularFile == true { size += Int64(attributes.fileSize ?? 0) }
|
|
}
|
|
}
|
|
}
|
|
guard size > 0 else { throw StudioError("The Core ML package is empty.") }
|
|
return Self(path: package.path, bytes: size)
|
|
}
|
|
}
|
|
|
|
struct CoreMLDownloads {
|
|
static let repository = "apple/mistral-coreml"
|
|
static let modelBytes: Int64 = 4_078_518_656
|
|
static let package = "StatefulMistral7BInstructInt4.mlpackage"
|
|
private static let hashes = [
|
|
"model.mlmodel": "aa0d5b06e1fe50cbdb095b846c1f30fb69aef08550db309ef6fc48d43ea51ad6",
|
|
"weight.bin": "1fa5158e6a1c5d3d131a1b08cb8dd3a4030c682a5fefa625e37a289f34d7a7ff"
|
|
]
|
|
|
|
static func install(in destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate) async throws -> CoreMLLibrary {
|
|
let checkpoint = destination.appending(path: package)
|
|
if let installed = try? CoreMLLibrary.inspect(checkpoint) { return installed }
|
|
let fileManager = FileManager.default
|
|
let parent = destination.deletingLastPathComponent()
|
|
try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)
|
|
let stage = parent.appending(path: ".download-" + UUID().uuidString)
|
|
defer { try? fileManager.removeItem(at: stage) }
|
|
let hf = URL(string: "https://huggingface.co")!
|
|
let weights = hf.appending(path: "apple/mistral-coreml/resolve/ef561211ae2c829934011eec8b396776bf24df9b")
|
|
let tokenizer = hf.appending(path: "mistralai/Mistral-7B-Instruct-v0.3/resolve/c170c708c41dac9275d15a8fff4eca08d52bab71")
|
|
let files: [(URL, String, Int64)] = [
|
|
(weights, package + "/Manifest.json", 617),
|
|
(weights, package + "/Data/com.apple.CoreML/model.mlmodel", 984_023),
|
|
(weights, package + "/Data/com.apple.CoreML/weights/weight.bin", 4_077_534_016),
|
|
(tokenizer, "tokenizer.json", 1_961_548),
|
|
(tokenizer, "tokenizer_config.json", 140_874),
|
|
(tokenizer, "config.json", 601)
|
|
]
|
|
let total = files.reduce(0) { $0 + $1.2 }
|
|
var written: Int64 = 0
|
|
for (base, path, bytes) in files {
|
|
try Task.checkCancellation()
|
|
let file = stage.appending(path: path)
|
|
try fileManager.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
let offset = written
|
|
try await HubGGUFTransfer.download(base.appending(path: path), file) { count, _ in progress(offset + count, total) }
|
|
guard try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == bytes else {
|
|
throw StudioError("The Core ML download returned an unexpected file size.")
|
|
}
|
|
if let expected = hashes[file.lastPathComponent] {
|
|
let handle = try FileHandle(forReadingFrom: file)
|
|
defer { try? handle.close() }
|
|
var hash = SHA256()
|
|
while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty {
|
|
try Task.checkCancellation()
|
|
hash.update(data: chunk)
|
|
}
|
|
guard hash.finalize().map({ String(format: "%02x", $0) }).joined() == expected else {
|
|
throw StudioError("The Core ML download checksum does not match Hugging Face.")
|
|
}
|
|
}
|
|
written += bytes
|
|
}
|
|
_ = try CoreMLLibrary.inspect(stage.appending(path: package))
|
|
try Task.checkCancellation()
|
|
try fileManager.moveItem(at: stage, to: destination)
|
|
return try CoreMLLibrary.inspect(checkpoint)
|
|
}
|
|
}
|
|
|
|
struct CoreMLModels: View {
|
|
let selection: String
|
|
let disabled: Bool
|
|
let select: (String) -> Void
|
|
@AppStorage(CoreMLLibrary.key) private var stored = Data()
|
|
@State private var importing = false
|
|
@State private var status = ""
|
|
@State private var search = ""
|
|
@State private var searching = false
|
|
@State private var results: [HubGGUFAsset.RepositoryResult] = []
|
|
@State private var download: Task<Void, Never>?
|
|
@State private var received: Int64 = 0
|
|
@State private var total: Int64?
|
|
|
|
var body: some View {
|
|
Section("Core ML") {
|
|
if #available(macOS 15, *) {
|
|
Button("Import Core ML Model…", systemImage: "plus") { importing = true }.disabled(disabled)
|
|
ForEach(CoreMLLibrary.read(stored)) { model in
|
|
HStack {
|
|
VStack(alignment: .leading) {
|
|
Text(URL(fileURLWithPath: model.path).deletingPathExtension().lastPathComponent)
|
|
Text("Core ML · " + ModelLibrarySize.label(model.bytes)).font(.caption).foregroundStyle(.secondary)
|
|
ModelMemoryWarning(bytes: model.bytes, coreML: true)
|
|
}
|
|
Spacer()
|
|
Button(selection == model.path ? "Active" : "Use") { select(model.path) }
|
|
.disabled(disabled || selection == model.path || !FileManager.default.fileExists(atPath: model.path))
|
|
if selection != model.path {
|
|
Button("Remove", systemImage: "minus.circle") {
|
|
do { stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path }) }
|
|
catch { status = error.localizedDescription }
|
|
}.labelStyle(.iconOnly)
|
|
}
|
|
}
|
|
}
|
|
HStack {
|
|
VStack(alignment: .leading) {
|
|
Text("Apple Mistral 7B Instruct")
|
|
Text("Core ML · Int4 · " + ModelLibrarySize.label(CoreMLDownloads.modelBytes))
|
|
.font(.caption).foregroundStyle(.secondary)
|
|
ModelMemoryWarning(bytes: CoreMLDownloads.modelBytes, coreML: true)
|
|
}
|
|
Spacer()
|
|
if let download { Button("Cancel") { download.cancel() } }
|
|
else { Button("Download from Hugging Face", action: startDownload) }
|
|
}
|
|
if download != nil {
|
|
if let total { ProgressView(value: Double(min(total, received)), total: Double(total)) }
|
|
else { ProgressView("Starting download…") }
|
|
}
|
|
HStack {
|
|
TextField("Search Hugging Face", text: $search, prompt: Text("Core ML text-generation models"))
|
|
.onSubmit(find)
|
|
Button(search.isEmpty ? "Browse" : "Search", action: find).disabled(searching)
|
|
if searching { ProgressView().controlSize(.small) }
|
|
}
|
|
ForEach(results) { result in
|
|
Link(result.id, destination: URL(string: "https://huggingface.co")!.appending(path: result.id))
|
|
}
|
|
if !status.isEmpty { Text(status).font(.caption).foregroundStyle(.secondary) }
|
|
} else {
|
|
Text("Core ML chat requires macOS 15 or later.").foregroundStyle(.secondary)
|
|
}
|
|
}
|
|
.fileImporter(isPresented: $importing, allowedContentTypes: [.folder] + ["mlpackage", "mlmodel", "mlmodelc"].compactMap { UTType(filenameExtension: $0) }) { result in
|
|
do {
|
|
let url = try result.get()
|
|
let access = url.startAccessingSecurityScopedResource()
|
|
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
|
try register(CoreMLLibrary.inspect(url))
|
|
} catch { status = error.localizedDescription }
|
|
}
|
|
}
|
|
|
|
private func register(_ model: CoreMLLibrary) throws {
|
|
stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path } + [model])
|
|
status = "Core ML model added."
|
|
}
|
|
|
|
private func find() {
|
|
guard !searching else { return }
|
|
searching = true
|
|
status = ""
|
|
Task {
|
|
defer { searching = false }
|
|
do {
|
|
results = try await HubGGUFAsset.search(search.trimmingCharacters(in: .whitespaces), format: "coreml")
|
|
if results.isEmpty { status = "No public Core ML text-generation models found." }
|
|
} catch { status = error.localizedDescription }
|
|
}
|
|
}
|
|
|
|
private func startDownload() {
|
|
received = 0
|
|
total = nil
|
|
status = ""
|
|
download = Task {
|
|
defer { download = nil }
|
|
do {
|
|
let path = URL.applicationSupportDirectory.appending(path: "AIStudio/Models/CoreML/Apple-Mistral-7B")
|
|
let model = try await CoreMLDownloads.install(in: path) { written, expected in
|
|
Task { @MainActor in
|
|
guard download != nil, written >= received else { return }
|
|
received = written
|
|
total = expected
|
|
}
|
|
}
|
|
try register(model)
|
|
} catch {
|
|
status = Task.isCancelled ? "Download cancelled." : error.localizedDescription
|
|
}
|
|
}
|
|
}
|
|
}
|