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 = [.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 var destination: URL { URL.applicationSupportDirectory.appending(path: "AIStudio/Models/CoreML/Apple-Mistral-7B") } private static var files: [(URL, String, Int64)] { 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") return [ (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) ] } static func installed(in destination: URL) -> CoreMLLibrary? { guard files.allSatisfy({ _, path, expected in let size = try? destination.appending(path: path).resourceValues(forKeys: [.fileSizeKey]).fileSize return size.map(Int64.init) == expected }) else { return nil } return try? CoreMLLibrary.inspect(destination.appending(path: package)) } static func install(in destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate) async throws -> CoreMLLibrary { if let model = installed(in: destination) { return model } let checkpoint = destination.appending(path: package) let fileManager = FileManager.default guard !fileManager.fileExists(atPath: destination.path) else { throw StudioError("The existing Core ML download is incomplete. Move the folder in Finder and try again. \(destination.path)") } 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 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 do { try await HubGGUFTransfer.download(base.appending(path: path), file) { count, _ in progress(offset + count, total) } } catch { try Task.checkCancellation() throw StudioError("Could not download \(file.lastPathComponent). \(error.localizedDescription)") } 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? @State private var received: Int64 = 0 @State private var total: Int64? @State private var showingAppleFiles = true @State private var catalogStatus = "" @State private var preview: ModelPreview? var body: some View { Group { ModelLibrarySection("Core ML", key: "libraryCoreMLExpanded") { 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) } } } if !status.isEmpty { Text(status).font(.caption).foregroundStyle(.secondary) } } else { Text("Core ML chat requires macOS 15 or later.").foregroundStyle(.secondary) } } if #available(macOS 15, *) { ModelLibrarySection("Hugging Face · Core ML", key: "catalogCoreMLExpanded") { HStack { TextField("Search Hugging Face", text: $search, prompt: Text("Model name or owner/model")) .textFieldStyle(.roundedBorder).onSubmit(find) Button(search.isEmpty ? "Browse" : "Search", action: find) .disabled(searching || download != nil) if searching { ProgressView().controlSize(.small) } } ForEach(results) { result in HubRepositoryRow(result: result, format: "Core ML") { if result.id == CoreMLDownloads.repository { Button("Choose Download…") { showingAppleFiles = true } } else { Link("Download Files…", destination: URL(string: "https://huggingface.co")!.appending(path: result.id).appending(path: "tree/main")) .help("Open this model’s downloadable files on Hugging Face.") } } } if showingAppleFiles { appleDownloadRow } if !catalogStatus.isEmpty { Text(catalogStatus).font(.caption).foregroundStyle(.secondary) } } } } .sheet(item: $preview) { ModelPreviewSheet(preview: $0) } .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 var appleDownloadRow: some View { let source = URL(string: "https://huggingface.co/apple/mistral-coreml")! return HubCatalogRow { Text("Apple Mistral 7B Instruct") HubCatalogFavorite(key: "Core ML:" + CoreMLDownloads.repository) } metadata: { Text("Core ML · Int4") Text(ModelLibrarySize.label(CoreMLDownloads.modelBytes)) ModelMemoryWarning(bytes: CoreMLDownloads.modelBytes, coreML: true) } actions: { Button("Preview") { preview = ModelPreview(title: "Apple Mistral 7B Instruct", fields: [ ("Format", "Core ML · Int4"), ("Size", ModelLibrarySize.label(CoreMLDownloads.modelBytes)), ("Package", CoreMLDownloads.package) ], source: source) } Link("Model Card", destination: source) Spacer() if let download { Button("Cancel") { download.cancel() } } else if let existing = CoreMLDownloads.installed(in: CoreMLDownloads.destination) { Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary) Button(selection == existing.path ? "Selected" : "Use") { do { try register(existing); select(existing.path) } catch { catalogStatus = error.localizedDescription } }.disabled(disabled || selection == existing.path) } else { Button("Download", action: startDownload) } } footer: { if download != nil { if let total { ProgressView(ModelLibrarySize.label(received), value: Double(min(total, received)), total: Double(total)) } else { ProgressView("Starting download…") } } } } 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 catalogStatus = "" Task { defer { searching = false } do { let query = search.trimmingCharacters(in: .whitespacesAndNewlines) showingAppleFiles = query.caseInsensitiveCompare(CoreMLDownloads.repository) == .orderedSame results = try await HubGGUFAsset.search(query, format: "coreml") if results.isEmpty { catalogStatus = "No public Core ML text-generation models found." } } catch { catalogStatus = error.localizedDescription } } } private func startDownload() { received = 0 total = nil catalogStatus = "" download = Task { defer { download = nil } do { let model = try await CoreMLDownloads.install(in: CoreMLDownloads.destination) { written, expected in Task { @MainActor in guard download != nil, written >= received else { return } received = written total = expected } } try register(model) catalogStatus = "Apple Mistral installed." } catch { catalogStatus = Task.isCancelled ? "Download cancelled." : error.localizedDescription } } } }