From 0720c8a18b954b72cd896ea97126866b50d142da Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Thu, 19 Nov 2026 09:18:49 +0000 Subject: [PATCH] new features --- AIStudio.xcodeproj/project.pbxproj | 12 +- Docs/LOCAL-MODELS.md | 39 ++++ README.md | 8 + Sources/AIStudioApp.swift | 70 ++------ Sources/CoreMLLibrary.swift | 193 +++++++++++++------- Sources/CreativeWorkspace.swift | 57 +++++- Sources/GGUFDownloads.swift | 146 ++++++++++++--- Sources/GGUFModels.swift | 22 ++- Sources/ModelDownload.swift | 278 +++++++++++++++++++++++------ Sources/PerformanceDashboard.swift | 199 +++++++++++++++++++++ Sources/StudioModel.swift | 11 ++ Tests/Fixtures/server.py | 11 ++ Tests/StudioTests.swift | 83 +++++++++ 13 files changed, 918 insertions(+), 211 deletions(-) create mode 100644 Sources/PerformanceDashboard.swift diff --git a/AIStudio.xcodeproj/project.pbxproj b/AIStudio.xcodeproj/project.pbxproj index 60a584c..aabeadc 100644 --- a/AIStudio.xcodeproj/project.pbxproj +++ b/AIStudio.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + CA00000000000000000000CB = {isa = PBXBuildFile; fileRef = CA00000000000000000000CA; }; CA00000000000000000000BB = {isa = PBXBuildFile; fileRef = CA00000000000000000000BA; }; CA00000000000000000000AB = {isa = PBXBuildFile; fileRef = CA00000000000000000000AA; }; CA000000000000000000009B = {isa = PBXBuildFile; fileRef = CA000000000000000000009A; }; @@ -47,6 +48,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + CA00000000000000000000CA = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceDashboard.swift; sourceTree = ""; }; CA00000000000000000000BA = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreativeWorkspace.swift; sourceTree = ""; }; CA00000000000000000000AA = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreMLLibrary.swift; sourceTree = ""; }; CA000000000000000000009A = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreMLProvider.swift; sourceTree = ""; }; @@ -95,6 +97,7 @@ 000000000000000000000001 /* Inference.swift */, CA000000000000000000003A, CA000000000000000000007A, + CA00000000000000000000CA, CA00000000000000000000BA, CA00000000000000000000AA, CA000000000000000000009A, @@ -241,6 +244,7 @@ 00000000000000000000000B /* Inference.swift in Sources */, CA000000000000000000003B, CA000000000000000000007B, + CA00000000000000000000CB, CA00000000000000000000BB, CA00000000000000000000AB, CA000000000000000000009B, @@ -284,7 +288,7 @@ CLANG_ENABLE_OBJC_WEAK = YES; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 27; + CURRENT_PROJECT_VERSION = 31; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 39R6U3437D; ENABLE_HARDENED_RUNTIME = NO; @@ -292,7 +296,7 @@ INFOPLIST_FILE = Info.plist; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks"); - MARKETING_VERSION = 1.1.25; + MARKETING_VERSION = 1.1.29; OTHER_LDFLAGS = ( "$(inherited)", "-lsqlite3", @@ -310,14 +314,14 @@ CLANG_ENABLE_OBJC_WEAK = YES; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 27; + CURRENT_PROJECT_VERSION = 31; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 39R6U3437D; ENABLE_HARDENED_RUNTIME = YES; INFOPLIST_FILE = Info.plist; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools"; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks"); - MARKETING_VERSION = 1.1.25; + MARKETING_VERSION = 1.1.29; OTHER_LDFLAGS = ( "$(inherited)", "-lsqlite3", diff --git a/Docs/LOCAL-MODELS.md b/Docs/LOCAL-MODELS.md index 4b6abf9..6373378 100644 --- a/Docs/LOCAL-MODELS.md +++ b/Docs/LOCAL-MODELS.md @@ -130,3 +130,42 @@ The full suite passed 120 tests with 15 opt-in skips and no failures. The Core ML smoke test used Apple’s published Mistral Int4 weights, generated a reply through the Studio chat controller, and fetched live Hugging Face search results. GGUF Metal generation and native MLX generation also passed. + +### 18 November 2026 · AI Studio 1.1.26 (28) + +The Performance window charts first output, total duration, and throughput. +Benchmarks use the selected chat model, a fixed prompt, and a 128-token +output cap. They run outside the saved conversation. New assistant replies +retain their timing data in the chat database. + +Model Library has a separate LM Studio tab for local files and server models. +The Core ML catalog shares Hugging Face repository rows with GGUF and checks +the managed files before showing **Installed**. The Images workspace uses a +Metal-backed Core Image context for exposure adjustment and PNG export. + +The regression suite passed 126 tests with 16 opt-in skips and zero failures. +A separate live test downloaded the published 4.08 GB Core ML checkpoint +through the app downloader, verified the weights, and reused the installation. +The local LM Studio file scan and GGUF chat passed. The compatible API fixture +covered model discovery and benchmark generation. + +### 19 November 2026 · AI Studio 1.1.28 (30) + +GGUF and Core ML repository rows fetch Hugging Face file metadata and display +variant size ranges. Split GGUF files are grouped before comparison. Core ML +packages are totaled individually. Unknown variants stay explicit, and red +warnings identify some or all variants above the applicable memory budget. +Each MLX, GGUF, Core ML and Ollama catalog search can be collapsed independently +and remembers its setting. + +The size regression and existing suite passed 122 tests with 21 opt-in skips +and zero failures. Public Apple Mistral Core ML and SmolLM2 GGUF file metadata +returned sizes in live checks. + +### 19 November 2026 · AI Studio 1.1.29 (31) + +Every Model Library section now has the same disclosure header, including +installed GGUF, MLX, Core ML, recommendations, import/filter controls, and +LM Studio file and server sections. Each section remembers its expansion. +The tab picker hides its redundant label to avoid vertical wrapping. +Expanded content aligns to the leading edge. diff --git a/README.md b/README.md index 73194a8..3e9de7f 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,12 @@ See [Local Model Roadmap](Docs/LOCAL-MODELS.md) for supported families, verifica Open **Training & Images** from the main window toolbar. **Training** contains the MLX conversion and LoRA workflow with live run output. **Images** opens Apple Image Playground on supported Macs and can preview an existing image or export a PNG preview. [MLX fine-tuning guide](Docs/TRAINING.md) · [Apple Image Playground](https://developer.apple.com/documentation/imageplayground) +Open **Performance** from the chat toolbar to compare latency and throughput in a separate window. **Run Benchmark** uses the selected model, a fixed prompt, and a 128-token output cap. Completed replies keep their timing beneath the message, and the dashboard retains the latest 50 chat and benchmark runs. + +**Settings → Model Library → LM Studio** offers local file scanning and an API model list. Use **Use Locally** for an imported file or **Use Server Model** for a running LM Studio server. The **Hugging Face · Core ML** section shows the Apple checkpoint as **Installed** when its files are already present. Hugging Face catalog rows share the same layout across MLX, GGUF, and Core ML, with previews, model cards, favorites, and actions on a separate line. + +The Images workspace adjusts exposure using [Core Image with a Metal renderer](https://developer.apple.com/documentation/coreimage/cicontext). Export Preview saves the adjusted PNG. + ## 2. Chat with documents Use **Documents** in the conversation toolbar to import PDF, UTF-8 text, @@ -196,3 +202,5 @@ TEST_RUNNER_AISTUDIO_TEST_MODEL_DOWNLOAD=qwen3-0.6b-4bit \ See `Docs/RELEASE.md` for packaging, signing, and notarization. See [phase progress](Docs/PHASES.md) for verification status and remaining work. + +Hugging Face GGUF and Core ML search results fetch per-file sizes and show a range when a repository has multiple variants. Red warnings identify repositories with variants above the memory budget. Each catalog search section can be collapsed and remembers its state. diff --git a/Sources/AIStudioApp.swift b/Sources/AIStudioApp.swift index a18b4ef..2da468f 100644 --- a/Sources/AIStudioApp.swift +++ b/Sources/AIStudioApp.swift @@ -60,6 +60,12 @@ struct AIStudioApp: App { .tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? accent.color) } .defaultSize(width: 990, height: 690) + Window("Model Performance", id: "modelPerformance") { + PerformanceDashboard(studio: studio) + .preferredColorScheme(theme.colorScheme) + .tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? accent.color) + } + .defaultSize(width: 1030, height: 690) Settings { StudioSettingsView(studio: studio) .preferredColorScheme(theme.colorScheme) @@ -114,7 +120,6 @@ struct ChatView: View { @AppStorage("globalCustomPrompt") private var customPrompt = "" @AppStorage(GenerationSettings.key) private var generationSettings = Data() @State private var showingPromptBuilder = false - @State private var showingPerformance = false @State private var showingComparison = false @State private var comparisonChat: UUID? @StateObject private var splitStudio = StudioModel() @@ -327,7 +332,10 @@ struct ChatView: View { } } .disabled(splitStudio.running || (studio.conversations.count < 2 && !showingComparison)) - Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true } + Button("Performance", systemImage: "chart.xyaxis.line") { + studio.performanceModel = chatModel + openWindow(id: "modelPerformance") + } } } .toolbar(mode == .zen ? .hidden : .visible, for: .windowToolbar) @@ -343,7 +351,7 @@ struct ChatView: View { AgentToolApprovalView(approval: approval) { studio.resolveAgentTool(approval.id, approved: $0) } } .sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) } - .sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) } + .onChange(of: chatModel, initial: true) { _, choice in studio.performanceModel = choice } .sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) } .sheet(item: $filePreview) { pending in let preview = pending.preview @@ -397,6 +405,8 @@ struct ChatView: View { model = defaults.string(forKey: "ollamaModel") ?? "" mlxOnly = defaults.bool(forKey: "mlxOnly") compatibleEnabled = defaults.bool(forKey: "compatibleEnabled") + compatibleEndpoint = defaults.string(forKey: "compatibleEndpoint") ?? "http://127.0.0.1:1234/v1" + compatibleModel = defaults.string(forKey: "compatibleModel") ?? "" } .onChange(of: studio.selected) { old, _ in if old != nil { @@ -624,7 +634,7 @@ struct ChatView: View { Button("Send", systemImage: "arrow.up", action: sendMessage) .buttonStyle(.borderedProminent) .keyboardShortcut(.return, modifiers: .command) - .disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .disabled(studio.benchmarkRunning || studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } } @@ -1034,6 +1044,7 @@ struct MessageView: View { Text(message.content).textSelection(.enabled) } } + if let timing = message.performance { ReplyPerformance(run: timing) } ForEach(message.documentNames, id: \.self) { name in Label(name, systemImage: "paperclip") .font(.caption.weight(.semibold)) @@ -1621,57 +1632,6 @@ struct PromptBuilder: View { } } -struct PerformanceDashboard: View { - @Environment(\.dismiss) private var dismiss - @ObservedObject var studio: StudioModel - - var body: some View { - VStack(alignment: .leading, spacing: 14) { - HStack { - Text("Inference Performance").font(.title2.bold()) - Spacer() - Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) - } - Text("Last 50 generations. First output includes model loading and any fallback.") - .foregroundStyle(.secondary) - if studio.running { - Label("Generation in progress…", systemImage: "ellipsis").foregroundStyle(.secondary) - } - if studio.measurements.isEmpty { - ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line", - description: Text("Send a chat message to collect timing and throughput.")) - } else { - Chart { - ForEach(Array(studio.measurements.reversed().enumerated()), id: \.element.id) { index, run in - BarMark(x: .value("Run", index + 1), y: .value("Seconds", run.seconds)) - .foregroundStyle(by: .value("Backend", run.backend)) - } - } - .chartXAxisLabel("Generation") - .chartYAxisLabel("Total seconds") - .frame(height: 160) - Table(studio.measurements) { - TableColumn("Backend", value: \.backend) - TableColumn("First output") { Text(seconds($0.firstOutput)) } - TableColumn("Total") { Text(seconds($0.seconds)) } - TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") } - TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") } - TableColumn("Characters/s") { run in - Text(run.charactersPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") - } - TableColumn("Outcome", value: \.outcome) - } - } - } - .padding(20) - .frame(minWidth: 800, minHeight: 475) - } - - private func seconds(_ value: Double?) -> String { - value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—" - } -} - struct GenerationSettingsView: View { @AppStorage("globalPromptMode") private var promptMode = PromptMode.standard @AppStorage("globalCustomPrompt") private var prompt = "" diff --git a/Sources/CoreMLLibrary.swift b/Sources/CoreMLLibrary.swift index 9f14251..b4ca1af 100644 --- a/Sources/CoreMLLibrary.swift +++ b/Sources/CoreMLLibrary.swift @@ -83,18 +83,15 @@ struct CoreMLDownloads { "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) } + 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") - let files: [(URL, String, Int64)] = [ + 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), @@ -102,6 +99,27 @@ struct CoreMLDownloads { (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 { @@ -109,7 +127,14 @@ struct CoreMLDownloads { 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) } + 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.") } @@ -147,58 +172,62 @@ struct CoreMLModels: View { @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 { - Section("Core ML") { + 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, *) { - Button("Import Core ML Model…", systemImage: "plus") { importing = true }.disabled(disabled) - ForEach(CoreMLLibrary.read(stored)) { model in + ModelLibrarySection("Hugging Face · Core ML", key: "catalogCoreMLExpanded") { 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) + 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("View Files") { showingAppleFiles = true } + } else { + Link("View Files", destination: URL(string: "https://huggingface.co")!.appending(path: result.id)) + } } } + if showingAppleFiles { appleDownloadRow } + if !catalogStatus.isEmpty { Text(catalogStatus).font(.caption).foregroundStyle(.secondary) } } - 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) } } + .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() @@ -209,6 +238,46 @@ struct CoreMLModels: View { } } + 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." @@ -217,25 +286,26 @@ struct CoreMLModels: View { private func find() { guard !searching else { return } searching = true - status = "" + catalogStatus = "" 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 } + 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 - status = "" + catalogStatus = "" 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 + let model = try await CoreMLDownloads.install(in: CoreMLDownloads.destination) { written, expected in Task { @MainActor in guard download != nil, written >= received else { return } received = written @@ -243,8 +313,9 @@ struct CoreMLModels: View { } } try register(model) + catalogStatus = "Apple Mistral installed." } catch { - status = Task.isCancelled ? "Download cancelled." : error.localizedDescription + catalogStatus = Task.isCancelled ? "Download cancelled." : error.localizedDescription } } } diff --git a/Sources/CreativeWorkspace.swift b/Sources/CreativeWorkspace.swift index caf6bbf..c6cd07a 100644 --- a/Sources/CreativeWorkspace.swift +++ b/Sources/CreativeWorkspace.swift @@ -1,4 +1,6 @@ import AppKit +import CoreImage +import Metal import ImageIO import ImagePlayground import SwiftUI @@ -10,6 +12,33 @@ struct StudioImagePreview: Sendable { let height: Int let png: Data + private static let renderer: CIContext = { + if let device = MTLCreateSystemDefaultDevice() { return CIContext(mtlDevice: device) } + return CIContext(options: [.useSoftwareRenderer: true]) + }() + + func adjusted(exposure: Double) throws -> Self { + guard exposure.isFinite, let input = CIImage(data: png) else { throw StudioError("Could not read the preview.") } + let output = input.applyingFilter("CIExposureAdjust", parameters: [kCIInputEVKey: min(3, max(-3, exposure))]) + guard let image = Self.renderer.createCGImage(output, from: input.extent) else { + throw StudioError("Could not render the adjusted preview.") + } + let encoded = NSMutableData() + guard let destination = CGImageDestinationCreateWithData(encoded, UTType.png.identifier as CFString, 1, nil) else { + throw StudioError("Could not create the PNG preview.") + } + CGImageDestinationAddImage(destination, image, nil) + guard CGImageDestinationFinalize(destination) else { throw StudioError("Could not encode the PNG preview.") } + return Self(name: name, width: width, height: height, png: encoded as Data) + } + + private init(name: String, width: Int, height: Int, png: Data) { + self.name = name + self.width = width + self.height = height + self.png = png + } + init(data: Data, name: String, maxDimension: Int = 2048) throws { guard let source = CGImageSourceCreateWithData(data as CFData, nil), let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], @@ -92,6 +121,9 @@ struct CreativeWorkspace: View { private struct ImageWorkspace: View { @State private var prompt = "" @State private var preview: StudioImagePreview? + @State private var original: StudioImagePreview? + @State private var exposureStep = 0 + @State private var adjustment: Task? @State private var importing = false @State private var status = "" @@ -111,6 +143,9 @@ private struct ImageWorkspace: View { } Divider() Button("Open Image…", systemImage: "folder") { importing = true } + Stepper("Exposure \(Double(exposureStep) / 2, specifier: "%+.1f") EV", value: $exposureStep, in: -6...6) + .disabled(original == nil) + .onChange(of: exposureStep) { applyExposure() } Button("Export Preview PNG…", systemImage: "square.and.arrow.up", action: export) .disabled(preview == nil) if !status.isEmpty { @@ -156,12 +191,32 @@ private struct ImageWorkspace: View { let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } do { - preview = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe), + let image = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe), name: url.deletingPathExtension().lastPathComponent) + adjustment?.cancel() + exposureStep = 0 + original = image + preview = image status = "" } catch { status = error.localizedDescription } } + private func applyExposure() { + adjustment?.cancel() + guard let original else { return } + let exposure = Double(exposureStep) / 2 + if exposure == 0 { preview = original; return } + adjustment = Task { + do { + let image = try await Task.detached(priority: .userInitiated) { try original.adjusted(exposure: exposure) }.value + guard !Task.isCancelled else { return } + preview = image + } catch { + if !Task.isCancelled { status = error.localizedDescription } + } + } + } + private func export() { guard let preview else { return } let panel = NSSavePanel() diff --git a/Sources/GGUFDownloads.swift b/Sources/GGUFDownloads.swift index 22cf7a8..27f4ad8 100644 --- a/Sources/GGUFDownloads.swift +++ b/Sources/GGUFDownloads.swift @@ -24,11 +24,12 @@ struct HubGGUFAsset: Identifiable, Equatable, Sendable { struct RepositoryResult: Decodable, Identifiable { let id: String let downloads: Int? + let likes: Int? let gated: CatalogModel.HubGating? let isPrivate: Bool? enum CodingKeys: String, CodingKey { - case id, downloads, gated + case id, downloads, likes, gated case isPrivate = "private" } } @@ -43,7 +44,7 @@ struct HubGGUFAsset: Identifiable, Equatable, Sendable { .init(name: "sort", value: "downloads"), .init(name: "direction", value: "-1"), .init(name: "limit", value: "25"), .init(name: "search", value: query), .init(name: "expand", value: "downloads"), .init(name: "expand", value: "gated"), - .init(name: "expand", value: "private") + .init(name: "expand", value: "private"), .init(name: "expand", value: "likes") ] guard let url = parts.url else { throw StudioError("Invalid Hugging Face search.") } let response = try await WebFetch.load(url, types: ["application/json"]) @@ -197,7 +198,7 @@ enum HubGGUFTransfer { guard let http = downloadTask.response as? HTTPURLResponse, http.statusCode == 200, http.url?.scheme == "https" else { let status = (downloadTask.response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? "" - result.finish(throwing: StudioError("Could not download the GGUF file\(status).")) + result.finish(throwing: StudioError("Could not download the model file\(status).")) return } do { try FileManager.default.moveItem(at: location, to: destination) } @@ -220,9 +221,97 @@ enum HubGGUFTransfer { } } +struct HubCatalogRow: View { + @ViewBuilder let heading: () -> Heading + @ViewBuilder let metadata: () -> Metadata + @ViewBuilder let actions: () -> Actions + @ViewBuilder let footer: () -> Footer + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(content: heading).font(.headline) + HStack(content: metadata).font(.caption).foregroundStyle(.secondary) + HStack(content: actions) + footer() + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 4) + } +} + +struct HubCatalogFavorite: View { + let key: String + @AppStorage("favoriteModelKeys") private var data = Data() + + var body: some View { + let keys = (try? JSONDecoder().decode(Set.self, from: data)) ?? [] + let saved = keys.contains(key) + let label = saved ? "Remove from Favorites" : "Add to Favorites" + Button(label, systemImage: saved ? "star.fill" : "star") { + var updated = keys + if saved { updated.remove(key) } else { updated.insert(key) } + if let encoded = try? JSONEncoder().encode(updated) { data = encoded } + } + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .help(label) + } +} + +struct HubRepositoryRow: View { + let result: HubGGUFAsset.RepositoryResult + let format: String + @ViewBuilder let action: () -> Action + @State private var preview: ModelPreview? + @State private var sizes: CatalogVariantSizes? + @State private var sizeError = false + + var body: some View { + let source = URL(string: "https://huggingface.co")!.appending(path: result.id) + HubCatalogRow { + Text(result.id).lineLimit(1).help(result.id) + HubCatalogFavorite(key: format + ":" + result.id) + } metadata: { + Text(format) + Text(sizes?.label ?? (sizeError ? "Size unavailable" : "Loading size…")) + if let sizes { + let budget = format == "Core ML" ? ModelMemoryBudget.system : ModelMemoryBudget.gpu + if sizes.someExceed(budget: budget) { + Label(sizes.allExceed(budget: budget) ? "Exceeds memory budget" : "Some variants exceed memory budget", + systemImage: "exclamationmark.triangle.fill") + .foregroundStyle(.red) + } + } + if let count = result.downloads { Label(count.formatted(), systemImage: "arrow.down") } + if let count = result.likes { Label(count.formatted(), systemImage: "heart") } + } actions: { + Button("Preview") { + preview = ModelPreview(title: result.id, fields: [("Format", format), + ("Size", sizes?.label), ("Downloads", result.downloads?.formatted()), ("Likes", result.likes?.formatted())], + source: source) + } + Link("Model Card", destination: source) + Spacer() + action() + } footer: {} + .sheet(item: $preview) { ModelPreviewSheet(preview: $0) } + .task(id: result.id + format) { + do { + let metadata = try await HubModelMetadata.load(repository: result.id) + guard !Task.isCancelled else { return } + sizes = metadata.variantSizes(format: format == "Core ML" ? .coreML : .gguf) + sizeError = false + } catch { + if !Task.isCancelled { sizeError = true } + } + } + } +} + struct HubGGUFDownloads: View { @AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data() @State private var repository = "" + @State private var preview: ModelPreview? @State private var repositories: [HubGGUFAsset.RepositoryResult] = [] @State private var assets: [HubGGUFAsset] = [] @State private var lookupInProgress = false @@ -234,7 +323,7 @@ struct HubGGUFDownloads: View { @State private var failure: String? var body: some View { - Section("Hugging Face · GGUF") { + ModelLibrarySection("Hugging Face · GGUF", key: "catalogGGUFExpanded") { HStack { TextField("Search Hugging Face", text: $repository, prompt: Text("Model name or owner/model")) .textFieldStyle(.roundedBorder) @@ -244,35 +333,34 @@ struct HubGGUFDownloads: View { if lookupInProgress { ProgressView().controlSize(.small) } } ForEach(repositories) { result in - HStack { - VStack(alignment: .leading, spacing: 3) { - Text(result.id).lineLimit(1).help(result.id) - if let downloads = result.downloads { - Text("\(downloads.formatted()) downloads").font(.caption).foregroundStyle(.secondary) - } - } - Spacer() + HubRepositoryRow(result: result, format: "GGUF") { Button("View Files") { lookup(result.id) }.disabled(lookupInProgress || download != nil) } } ForEach(assets) { asset in - VStack(alignment: .leading, spacing: 6) { - HStack { - VStack(alignment: .leading, spacing: 3) { - Text(asset.filename).fontWeight(.medium).lineLimit(1).help(asset.filename) - Text("GGUF · " + ModelLibrarySize.label(asset.bytes)) - .font(.caption).foregroundStyle(.secondary) - ModelMemoryWarning(bytes: asset.bytes) - } - Spacer() - if downloadingID == asset.id { - Button("Cancel") { download?.cancel() } - } else if isRegistered(asset) { - Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary) - } else { - Button("Download") { start(asset) }.disabled(download != nil) - } + let source = URL(string: "https://huggingface.co")!.appending(path: asset.repository) + HubCatalogRow { + Text(asset.filename).lineLimit(1).help(asset.filename) + HubCatalogFavorite(key: "GGUF:" + asset.repository) + } metadata: { + Text("GGUF") + Text(ModelLibrarySize.label(asset.bytes)) + ModelMemoryWarning(bytes: asset.bytes) + } actions: { + Button("Preview") { + preview = ModelPreview(title: asset.filename, fields: [("Format", "GGUF"), + ("Size", ModelLibrarySize.label(asset.bytes)), ("Revision", asset.revision)], source: source) } + Link("Model Card", destination: source) + Spacer() + if downloadingID == asset.id { + Button("Cancel") { download?.cancel() } + } else if isRegistered(asset) { + Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary) + } else { + Button("Download") { start(asset) }.disabled(download != nil) + } + } footer: { if downloadingID == asset.id { let label = ByteCountFormatter.string(fromByteCount: written, countStyle: .file) if let expected, expected > 0 { @@ -283,11 +371,11 @@ struct HubGGUFDownloads: View { } } } - .padding(.vertical, 3) } if let notice { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary) } if let failure { Label(failure, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) } } + .sheet(item: $preview) { ModelPreviewSheet(preview: $0) } } private func isRegistered(_ asset: HubGGUFAsset) -> Bool { diff --git a/Sources/GGUFModels.swift b/Sources/GGUFModels.swift index 533ae88..82adc85 100644 --- a/Sources/GGUFModels.swift +++ b/Sources/GGUFModels.swift @@ -86,6 +86,20 @@ 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] { @@ -157,13 +171,9 @@ struct GGUFModels: View { } var body: some View { - Section { + ModelLibrarySection("Local GGUF", key: "libraryGGUFExpanded") { HStack { - VStack(alignment: .leading, spacing: 4) { - Label("Local GGUF", systemImage: "cpu") - .font(.headline) - memorySummary - } + memorySummary Spacer() Button("Import…", systemImage: "plus") { showingImporter = true } .disabled(inspecting) diff --git a/Sources/ModelDownload.swift b/Sources/ModelDownload.swift index 50bcf52..03c7b11 100644 --- a/Sources/ModelDownload.swift +++ b/Sources/ModelDownload.swift @@ -211,6 +211,45 @@ struct HubModelMetadata: Decodable { let siblings: [File] + enum Format { case gguf, coreML } + + func variantSizes(format: Format) -> CatalogVariantSizes { + var groups: [String: [Int64?]] = [:] + for file in siblings { + let name = file.rfilename + let lower = name.lowercased() + let bytes = file.lfs?.size ?? file.size + switch format { + case .gguf: + guard lower.hasSuffix(".gguf"), !lower.contains("mmproj"), !lower.contains("adapter") else { continue } + let key = name.replacingOccurrences(of: #"-[0-9]{5}-of-[0-9]{5}\.gguf$"#, + with: ".gguf", options: .regularExpression) + groups[key, default: []].append(bytes) + case .coreML: + if let range = lower.range(of: ".mlpackage/") { + let key = String(name[.. Self { + guard CatalogModel.repositoryParts(repository) != nil else { throw StudioError("Invalid model repository.") } + var parts = URLComponents() + parts.scheme = "https" + parts.host = "huggingface.co" + parts.path = "/api/models/" + repository + parts.queryItems = [.init(name: "blobs", value: "true")] + guard let url = parts.url else { throw StudioError("Invalid metadata URL.") } + let response = try await WebFetch.load(url, types: ["application/json"]) + return try JSONDecoder().decode(Self.self, from: response.data) + } + func weightBytes(files: [String]) -> Int64? { let weights = Set(files.filter { $0.hasSuffix(".safetensors") }) return ModelLibrarySize.total(weights.sorted().map { name in @@ -248,7 +287,7 @@ struct OllamaRegistryManifest: Decodable { } } -private struct ModelPreview: Identifiable { +struct ModelPreview: Identifiable { let id = UUID() let title: String let fields: [(String, String?)] @@ -256,7 +295,7 @@ private struct ModelPreview: Identifiable { var load: (() async throws -> [(String, String?)])? } -private struct ModelPreviewSheet: View { +struct ModelPreviewSheet: View { let preview: ModelPreview @Environment(\.dismiss) private var dismiss @State private var details: [(String, String?)] = [] @@ -300,6 +339,54 @@ private struct ModelPreviewSheet: View { } } +struct CatalogVariantSizes { + let known: [Int64] + let totalVariants: Int + + var label: String { + guard let minimum = known.min(), let maximum = known.max() else { return "Size unknown" } + let range = minimum == maximum ? ModelLibrarySize.label(minimum) : + ModelLibrarySize.label(minimum) + " – " + ModelLibrarySize.label(maximum) + return range + (known.count < totalVariants ? " · some sizes unknown" : "") + } + + func someExceed(budget: Int64?) -> Bool { + guard let budget else { return false } + return known.contains { $0 > budget } + } + + func allExceed(budget: Int64?) -> Bool { + totalVariants > 0 && known.count == totalVariants && + known.allSatisfy { ModelMemoryBudget.exceeds(bytes: $0, budget: budget) } + } +} + +struct ModelLibrarySection: View { + let title: String + @AppStorage private var expanded: Bool + @ViewBuilder let content: () -> Content + + init(_ title: String, key: String, @ViewBuilder content: @escaping () -> Content) { + self.title = title + self._expanded = AppStorage(wrappedValue: true, key) + self.content = content + } + + var body: some View { + Section { + DisclosureGroup(isExpanded: $expanded) { + VStack(alignment: .leading, spacing: 12) { + content() + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.top, 8) + } label: { + Text(title).font(.headline) + } + } + } +} + enum ModelLibrarySize { static func total(_ sizes: [Int64?]) -> Int64? { guard !sizes.isEmpty else { return nil } @@ -413,6 +500,14 @@ struct ModelCatalogView: View { @AppStorage("favoriteModelKeys") private var favoriteData = Data() @State private var libraryBackend = "Local" + @AppStorage("lmStudioLibraryEndpoint") private var lmStudioEndpoint = "http://127.0.0.1:1234/v1" + @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" + @AppStorage("compatibleModel") private var compatibleModel = "" + @State private var lmStudioLocalModels: [LocalModelImport] = [] + @State private var lmStudioServerModels: [String] = [] + @State private var lmStudioResultsEndpoint = "" + @State private var lmStudioConnecting = false + @State private var lmStudioServerStatus = "" @State private var localQuery = "" @AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434" @@ -555,29 +650,25 @@ struct ModelCatalogView: View { } private func favoriteButton(_ key: String) -> some View { - let saved = favorites.contains(key) - let label = saved ? "Remove from Favorites" : "Add to Favorites" - return Button(label, systemImage: saved ? "star.fill" : "star") { - var updated = favorites - if saved { updated.remove(key) } else { updated.insert(key) } - if let data = try? JSONEncoder().encode(updated) { favoriteData = data } - } - .labelStyle(.iconOnly) - .buttonStyle(.borderless) - .help(label) + HubCatalogFavorite(key: key) } var body: some View { VStack(spacing: 0) { Picker("Model library", selection: $libraryBackend) { Text("On This Mac").tag("Local") + Text("LM Studio").tag("LM Studio") Text("Ollama").tag("Ollama") } .pickerStyle(.segmented) - .frame(width: 260) + .labelsHidden() + .accessibilityLabel("Model library") + .frame(maxWidth: 430) .padding() if libraryBackend == "Ollama" { ollamaLibrary + } else if libraryBackend == "LM Studio" { + lmStudioLibrary } else { localLibrary } @@ -621,12 +712,93 @@ struct ModelCatalogView: View { try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder) }.value try registerLocalModels(models) + lmStudioLocalModels = models libraryStatus = models.isEmpty ? "No supported models found in the LM Studio library." : "Found \(models.count) models in the LM Studio library." } catch { libraryStatus = error.localizedDescription } } } + private var lmStudioLibrary: some View { + Form { + ModelLibrarySection("Files on This Mac", key: "libraryLMStudioFilesExpanded") { + LabeledContent("Folder", value: LocalModelImport.lmStudioFolder.path(percentEncoded: false)) + HStack { + Button("Scan & Import", systemImage: "folder.badge.plus", action: importLMStudioLibrary) + .disabled(scanningLibrary || studio.running) + if scanningLibrary { ProgressView().controlSize(.small) } + } + if !libraryStatus.isEmpty { Text(libraryStatus).font(.caption).foregroundStyle(.secondary) } + ForEach(lmStudioLocalModels, id: \.path) { model in + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(URL(fileURLWithPath: model.path).deletingPathExtension().lastPathComponent) + Text(model.format).font(.caption).foregroundStyle(.secondary) + switch model { + case .gguf: + let size = try? URL(fileURLWithPath: model.path).resourceValues(forKeys: [.fileSizeKey]).fileSize + ModelMemoryWarning(bytes: size.map(Int64.init)) + case .mlx: + let size = try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: model.path)) + ModelMemoryWarning(bytes: size.flatMap { Int64(exactly: $0) }, mlx: true) + } + } + Spacer() + Button("Use Locally") { + switch model { + case .gguf(let entry): studio.selectGGUFModel(entry.path) + case .mlx(let path): studio.selectMLXModel(path) + } + }.disabled(studio.running || studio.benchmarkRunning) + } + } + } + ModelLibrarySection("LM Studio Server", key: "libraryLMStudioServerExpanded") { + TextField("API endpoint", text: $lmStudioEndpoint).onSubmit(refreshLMStudioServer) + HStack { + Button("List Server Models", systemImage: "arrow.clockwise", action: refreshLMStudioServer) + .disabled(lmStudioConnecting || lmStudioEndpoint.isEmpty) + if lmStudioConnecting { ProgressView().controlSize(.small) } + } + if !lmStudioServerStatus.isEmpty { Text(lmStudioServerStatus).font(.caption).foregroundStyle(.secondary) } + if lmStudioResultsEndpoint == lmStudioEndpoint { + ForEach(lmStudioServerModels, id: \.self) { model in + HStack { + Text(model) + Spacer() + let active = compatibleEnabled && defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && + !mlxOnly && compatibleModel == model && compatibleEndpoint == lmStudioEndpoint + Button(active ? "Selected" : "Use Server Model") { + studio.selectCompatibleModel(model, endpoint: lmStudioEndpoint) + }.disabled(active || studio.running || studio.benchmarkRunning) + } + } + } + } + }.formStyle(.grouped) + } + + private func refreshLMStudioServer() { + guard !lmStudioConnecting else { return } + let endpoint = lmStudioEndpoint.trimmingCharacters(in: .whitespacesAndNewlines) + lmStudioEndpoint = endpoint + lmStudioConnecting = true + lmStudioServerStatus = "" + lmStudioResultsEndpoint = "" + Task { + defer { lmStudioConnecting = false } + do { + let models = try await studio.compatibleClient(endpoint: endpoint).models() + guard lmStudioEndpoint == endpoint else { return } + lmStudioServerModels = models + lmStudioResultsEndpoint = endpoint + if models.isEmpty { lmStudioServerStatus = "The server reported no models." } + } catch { + if lmStudioEndpoint == endpoint { lmStudioServerStatus = error.localizedDescription } + } + } + } + private func acceptModelDrop(_ providers: [NSItemProvider]) -> Bool { let files = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) } guard !files.isEmpty, !scanningLibrary, !studio.running else { return false } @@ -665,7 +837,7 @@ struct ModelCatalogView: View { private var localLibrary: some View { Form { - Section { + ModelLibrarySection("Import & Filter", key: "libraryImportExpanded") { TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format")) .textFieldStyle(.roundedBorder) .accessibilityLabel("Filter installed models") @@ -688,7 +860,7 @@ struct ModelCatalogView: View { studio.selectGGUFModel($0) } - Section("Installed MLX Models") { + ModelLibrarySection("Installed MLX Models", key: "libraryMLXExpanded") { HStack { Button("Import MLX Models…") { pickingLibrary = true } Button("Refresh Local Models") { cacheScan += 1 } @@ -745,7 +917,7 @@ struct ModelCatalogView: View { } CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) } HubGGUFDownloads() - Section("Hugging Face · MLX") { + ModelLibrarySection("Hugging Face · MLX", key: "catalogMLXExpanded") { HStack { TextField("Search MLX models", text: $query, prompt: Text("Qwen, Gemma, or owner/model")) .labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search) @@ -758,7 +930,7 @@ struct ModelCatalogView: View { modelRow(model) } } - Section("Recommended Models") { + ModelLibrarySection("Recommended Models", key: "libraryRecommendedExpanded") { ForEach(favoriteFirst(CatalogModel.all.filter { !$0.installed(at: $0.localFolder) }) { "mlx:" + $0.id }) { model in modelRow(model) } } if !status.isEmpty && !hasMLXDownloads { @@ -816,7 +988,7 @@ struct ModelCatalogView: View { private var ollamaLibrary: some View { Form { - Section("Installed on Ollama") { + ModelLibrarySection("Installed on Ollama", key: "libraryOllamaExpanded") { LabeledContent("Server", value: ollamaEndpoint) Button("Refresh Installed Models") { studio.refresh(endpoint: ollamaEndpoint) } .disabled(studio.managing) @@ -860,7 +1032,7 @@ struct ModelCatalogView: View { Button("Cancel") { studio.cancelManagement() } } } - Section("Ollama Catalog") { + ModelLibrarySection("Ollama Catalog", key: "catalogOllamaExpanded") { HStack { TextField("Search Ollama models", text: $ollamaQuery, prompt: Text("e.g. Qwen, Llama")) .labelsHidden().textFieldStyle(.roundedBorder).onSubmit(searchOllama) @@ -986,47 +1158,43 @@ struct ModelCatalogView: View { let installed = saved.installed(at: saved.localFolder) let isActive = installed && selection.isMLX(saved.localFolder.path) let metadataKey = model.metadataKey - return VStack(alignment: .leading, spacing: 6) { - HStack { - Text(model.title).font(.headline) - favoriteButton("mlx:" + model.id) - popularityBadge(model.repository) - } - HStack { - Text("MLX · Safetensors") - Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey])) - .help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision") - ModelMemoryWarning(bytes: installed - ? (try? MLXRuntimeLimits.weightBytes(in: saved.localFolder)).flatMap { Int64(exactly: $0) } - : catalogBytes[metadataKey], mlx: true) - if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") } - if let count = model.likes { Label(count.formatted(), systemImage: "heart") } - if installed { mlxStatus(saved.localFolder.path) } - }.font(.caption).foregroundStyle(.secondary) - HStack { - Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) } - Link("Model Card", destination: model.source) - Spacer() - if installed { - mlxLoadButton(saved.localFolder.path) - Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) } - .disabled(studio.running || loadingPath != nil) - Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) } + return HubCatalogRow { + Text(model.title).font(.headline) + favoriteButton("mlx:" + model.id) + popularityBadge(model.repository) + } metadata: { + Text("MLX · Safetensors") + Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey])) + .help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision") + ModelMemoryWarning(bytes: installed + ? (try? MLXRuntimeLimits.weightBytes(in: saved.localFolder)).flatMap { Int64(exactly: $0) } + : catalogBytes[metadataKey], mlx: true) + if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") } + if let count = model.likes { Label(count.formatted(), systemImage: "heart") } + if installed { mlxStatus(saved.localFolder.path) } + } actions: { + Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) } + Link("Model Card", destination: model.source) + Spacer() + if installed { + mlxLoadButton(saved.localFolder.path) + Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) } + .disabled(studio.running || loadingPath != nil) + Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) } + } else { + if let task = downloads["mlx:" + model.id] { + Button("Cancel Download") { task.cancel() } } else { - if let task = downloads["mlx:" + model.id] { - Button("Cancel Download") { task.cancel() } - } else { - Button("Download") { download(model) } - } - } - if FileManager.default.fileExists(atPath: saved.localFolder.path) { - Button("Remove…", role: .destructive) { removing = saved } - .disabled(studio.running || downloads["mlx:" + model.id] != nil || loadingPath != nil) + Button("Download") { download(model) } } } + if FileManager.default.fileExists(atPath: saved.localFolder.path) { + Button("Remove…", role: .destructive) { removing = saved } + .disabled(studio.running || downloads["mlx:" + model.id] != nil || loadingPath != nil) + } + } footer: { downloadProgress("mlx:" + model.id) } - .padding(.vertical, 4) .listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil) .task(id: installed ? nil : metadataKey) { guard !installed, catalogBytes[metadataKey] == nil else { return } diff --git a/Sources/PerformanceDashboard.swift b/Sources/PerformanceDashboard.swift new file mode 100644 index 0000000..3ebb4f9 --- /dev/null +++ b/Sources/PerformanceDashboard.swift @@ -0,0 +1,199 @@ +import Charts +import SwiftUI + +struct ReplyPerformance: View { + let run: GenerationMeasurement + + private var timings: [String] { + var fields = run.firstOutput.map { ["First output " + duration($0)] } ?? [] + fields.append("Total " + duration(run.seconds)) + if let rate = run.provider?.tokensPerSecond { + fields.append("\(rate.formatted(.number.precision(.fractionLength(1)))) tok/s") + } else if let rate = run.charactersPerSecond { + fields.append("\(rate.formatted(.number.precision(.fractionLength(1)))) chars/s") + } + return fields + } + + var body: some View { + Label { + Text(timings.joined(separator: " · ")) + } icon: { + Image(systemName: "stopwatch") + } + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } +} + +private func duration(_ seconds: Double) -> String { + seconds.formatted(.number.precision(.fractionLength(2))) + " s" +} + +struct PerformanceDashboard: View { + @ObservedObject var studio: StudioModel + @AppStorage(GenerationMeasurement.key) private var stored = Data() + @AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434" + @AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1" + @State private var repetitions = 1 + @State private var scope: Scope = .all + @State private var throughput: Throughput = .tokens + + private enum Scope: String, CaseIterable, Identifiable { + case all = "All runs", benchmark = "Benchmarks", chat = "Chats" + var id: Self { self } + } + + private enum Throughput: String, CaseIterable, Identifiable { + case tokens = "Tokens/s", characters = "Characters/s" + var id: Self { self } + + func value(_ run: GenerationMeasurement) -> Double? { + self == .tokens ? run.provider?.tokensPerSecond : run.charactersPerSecond + } + } + + private var runs: [GenerationMeasurement] { + GenerationMeasurement.history(stored).filter { + switch scope { + case .all: true + case .benchmark: $0.benchmark == true + case .chat: $0.benchmark != true + } + } + } + + private var recent: [GenerationMeasurement] { Array(runs.prefix(12).reversed()) } + + var body: some View { + VStack(alignment: .leading, spacing: 17) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 5) { + Text("Model Performance").font(.largeTitle.weight(.semibold)) + Text("Compare the latest 50 runs. First output includes startup and prompt processing.") + .foregroundStyle(.secondary) + } + Spacer() + Picker("Show", selection: $scope) { + ForEach(Scope.allCases) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 260) + } + benchmarkControls + if runs.isEmpty { + ContentUnavailableView("No runs in this view", systemImage: "chart.xyaxis.line", + description: Text("Run a benchmark or generate a chat reply.")) + } else { + HStack(spacing: 14) { + chartCard("Latency", accent: .indigo) { latencyChart } + chartCard("Throughput", accent: .teal) { throughputChart } + } + Table(runs) { + TableColumn("Model") { run in Text(run.model ?? "—").help(run.model ?? "") } + TableColumn("Time") { Text($0.recordedAt?.formatted(.dateTime.month().day().hour().minute()) ?? "—") } + TableColumn("Backend", value: \.backend) + TableColumn("Source") { Text($0.benchmark == true ? "Benchmark" : "Chat") } + TableColumn("First output") { Text($0.firstOutput.map(duration) ?? "—") } + TableColumn("Total") { Text(duration($0.seconds)) } + TableColumn("Tokens/s") { Text(number($0.provider?.tokensPerSecond)) } + TableColumn("Outcome") { run in + Label(run.outcome, systemImage: run.outcome == "Complete" ? "checkmark.circle" : "exclamationmark.circle") + .foregroundStyle(run.outcome == "Complete" ? Color.secondary : run.outcome == "Stopped" ? .orange : .red) + } + } + .frame(minHeight: 180) + } + } + .padding(22) + .frame(minWidth: 940, minHeight: 625) + } + + private var benchmarkControls: some View { + HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 4) { + Text(studio.performanceModel?.displayName ?? "Choose a model in chat").font(.headline) + Text(studio.benchmarkStatus.isEmpty + ? "Fixed prompt · 128 output tokens maximum · temperature 0" + : studio.benchmarkStatus) + .font(.caption).foregroundStyle(.secondary) + .help(StudioModel.benchmarkPrompt) + } + Spacer() + Picker("Runs", selection: $repetitions) { + ForEach([1, 3, 5], id: \.self) { Text($0.formatted()).tag($0) } + }.fixedSize().disabled(studio.benchmarkRunning) + if studio.benchmarkRunning { + ProgressView().controlSize(.small) + Button("Stop", action: studio.stopBenchmark) + } else { + Button("Run Benchmark", systemImage: "play.fill", action: runBenchmark) + .buttonStyle(.borderedProminent) + .disabled(studio.running || studio.performanceModel?.model.isEmpty != false) + } + } + .padding(13) + .background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 11)) + } + + private func chartCard(_ title: String, accent: Color, @ViewBuilder content: () -> Content) -> some View { + VStack(alignment: .leading, spacing: 12) { + Label(title, systemImage: "chart.bar.xaxis").font(.headline).foregroundStyle(accent) + content() + } + .padding(13) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 11)) + } + + private var latencyChart: some View { + Chart { + ForEach(Array(recent.enumerated()), id: \.element.id) { index, run in + BarMark(x: .value("Run", index + 1), y: .value("Seconds", run.seconds)) + .position(by: .value("Timing", "Total")) + .foregroundStyle(by: .value("Timing", "Total")) + if let first = run.firstOutput { + BarMark(x: .value("Run", index + 1), y: .value("Seconds", first)) + .position(by: .value("Timing", "First output")) + .foregroundStyle(by: .value("Timing", "First output")) + } + } + } + .chartForegroundStyleScale(domain: ["First output", "Total"], range: [Color.teal, Color.indigo]) + .chartLegend(position: .bottom, alignment: .leading) + .chartYAxisLabel("Seconds") + .frame(height: 180) + } + + private var throughputChart: some View { + VStack(alignment: .leading, spacing: 7) { + Picker("Unit", selection: $throughput) { + ForEach(Throughput.allCases) { Text($0.rawValue).tag($0) } + }.pickerStyle(.segmented).labelsHidden().frame(width: 195) + if recent.contains(where: { $0.outcome == "Complete" && throughput.value($0) != nil }) { + Chart { + ForEach(Array(recent.enumerated()), id: \.element.id) { index, run in + if run.outcome == "Complete", let value = throughput.value(run) { + BarMark(x: .value("Run", index + 1), y: .value(throughput.rawValue, value)) + .foregroundStyle(Color.teal.gradient) + } + } + } + .chartYAxisLabel(throughput.rawValue) + .frame(height: 150) + } else { + Text("No completed runs reported \(throughput.rawValue.lowercased()).") + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, minHeight: 150) + } + }.frame(height: 180, alignment: .top) + } + + private func runBenchmark() { + guard let model = studio.performanceModel else { return } + studio.benchmark(model, endpoint: model.backend == .compatible ? compatibleEndpoint : ollamaEndpoint, + repetitions: repetitions) + } + + private func number(_ value: Double?) -> String { + value?.formatted(.number.precision(.fractionLength(1))) ?? "—" + } +} diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index 2ce0b0a..a5165cc 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -1038,6 +1038,17 @@ final class StudioModel: ObservableObject { discoveredMLXPaths.removeAll { $0 == path } } + func selectCompatibleModel(_ model: String, endpoint: String) { + let defaults = UserDefaults.standard + defaults.removeObject(forKey: "defaultGGUFPath") + defaults.removeObject(forKey: "defaultCoreMLPath") + defaults.set(false, forKey: "mlxOnly") + defaults.set(endpoint, forKey: "compatibleEndpoint") + defaults.set(model, forKey: "compatibleModel") + defaults.set(true, forKey: "compatibleEnabled") + modelSelectionRevision += 1 + } + func selectCoreMLModel(_ path: String) { UserDefaults.standard.removeObject(forKey: "defaultGGUFPath") UserDefaults.standard.set(path, forKey: "defaultCoreMLPath") diff --git a/Tests/Fixtures/server.py b/Tests/Fixtures/server.py index fe9e5c8..aef948a 100644 --- a/Tests/Fixtures/server.py +++ b/Tests/Fixtures/server.py @@ -24,6 +24,17 @@ class Handler(BaseHTTPRequestHandler): message = self.body() method = message.get('method') args = message.get('params', {}) + if self.path == '/benchmark/v1/chat/completions': + valid = (message.get('stream') is True and message.get('model') == 'fixture-model' + and message.get('temperature') == 0 and message.get('max_tokens') == 128 + and len(message.get('messages', [])) == 1 + and 'garden' in message['messages'][0]['content']) + if not valid: + self.reply(400) + return + frame = {'choices': [{'delta': {'content': 'Benchmark reply'}}]} + self.reply(200, f'data: {json.dumps(frame)}\n\ndata: [DONE]\n\n'.encode(), 'text/event-stream') + return if self.path == '/compatible/v1/chat/completions': if self.headers.get('Authorization') != 'Bearer fixture-token': self.reply(401) diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index 044465b..9c4e820 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -298,6 +298,10 @@ final class StudioTests: XCTestCase { } let model = try CoreMLLibrary.inspect(URL(fileURLWithPath: path)) XCTAssertGreaterThan(model.bytes, 0) + let defaults = UserDefaults.standard + let previousSearch = defaults.object(forKey: "automaticChatWebSearch") + defaults.set(false, forKey: "automaticChatWebSearch") + defer { defaults.set(previousSearch, forKey: "automaticChatWebSearch") } let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) defer { try? FileManager.default.removeItem(at: folder) } let studio = StudioModel() @@ -375,6 +379,81 @@ final class StudioTests: XCTestCase { XCTAssertEqual(messages.last?.performance, timing) } + @MainActor + func testBenchmarkUsesCompatibleServerWithoutCreatingChat() async throws { + guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else { + throw XCTSkip("Run Scripts/test.sh to launch the compatible API fixture.") + } + let defaults = UserDefaults.standard + let previous = defaults.data(forKey: GenerationMeasurement.key) + defer { defaults.set(previous, forKey: GenerationMeasurement.key) } + let studio = StudioModel() + let benchmarkEndpoint = endpoint.replacingOccurrences(of: "/compatible/v1", with: "/benchmark/v1") + studio.benchmark(.init(backend: .compatible, model: "fixture-model"), endpoint: benchmarkEndpoint, repetitions: 1) + let deadline = ContinuousClock.now + .seconds(10) + while studio.benchmarkRunning && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } + let run = try XCTUnwrap(studio.measurements.first, studio.benchmarkStatus) + XCTAssertEqual(run.benchmark, true) + XCTAssertEqual(run.model, "fixture-model") + XCTAssertEqual(run.outcome, "Complete", studio.benchmarkStatus) + XCTAssertNotNil(run.firstOutput) + XCTAssertTrue(studio.messages.isEmpty) + XCTAssertTrue(studio.conversations.isEmpty) + } + + func testLiveCoreMLDownloadStagesWeightsAndReusesInstallation() async throws { + guard ProcessInfo.processInfo.environment["AISTUDIO_TEST_COREML_DOWNLOAD"] == "1" else { + throw XCTSkip("Set TEST_RUNNER_AISTUDIO_TEST_COREML_DOWNLOAD=1 for the 4.08 GB Hugging Face test.") + } + let destination = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: destination) } + let progress = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + let model = try await CoreMLDownloads.install(in: destination) { bytes, _ in progress.continuation.yield(bytes) } + progress.continuation.finish() + var observed: Int64? + for await bytes in progress.stream { observed = bytes } + XCTAssertGreaterThan(try XCTUnwrap(observed), CoreMLDownloads.modelBytes) + XCTAssertEqual(model.bytes, CoreMLDownloads.modelBytes) + XCTAssertEqual(CoreMLDownloads.installed(in: destination)?.path, model.path) + let existing = try await CoreMLDownloads.install(in: destination) { _, _ in } + XCTAssertEqual(existing.path, model.path) + } + + func testCoreImageExposureKeepsPreviewDimensionsAndIncreasesBrightness() throws { + // A flat 2 × 2 RGBA fixture with 64 in each color channel. + let data = try XCTUnwrap(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEUlEQVR4nGNwcHD4D8IMMAYAOnQG/e3tajcAAAAASUVORK5CYII=")) + let original = try XCTUnwrap(NSBitmapImageRep(data: data)) + let preview = try StudioImagePreview(data: data, name: "Dark") + let rendered = try preview.adjusted(exposure: 1) + let result = try XCTUnwrap(NSBitmapImageRep(data: rendered.png)) + XCTAssertEqual(result.pixelsWide, 2) + XCTAssertEqual(result.pixelsHigh, 2) + let originalColor = try XCTUnwrap(original.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB)) + let adjustedColor = try XCTUnwrap(result.colorAt(x: 0, y: 0)?.usingColorSpace(.deviceRGB)) + XCTAssertGreaterThan(adjustedColor.redComponent, originalColor.redComponent) + } + + func testCatalogSizesCompareVariantsWithoutSummingAlternatives() throws { + let data = Data(""" + {"siblings":[{"rfilename":"chat-Q4.gguf","size":100},{"rfilename":"chat-Q8.gguf","size":300}, + {"rfilename":"mmproj-chat.gguf","size":500},{"rfilename":"A.mlpackage/Manifest.json","size":10}, + {"rfilename":"A.mlpackage/Data/weights/weight.bin","lfs":{"size":200}}, + {"rfilename":"B.mlpackage/Manifest.json","size":10},{"rfilename":"B.mlpackage/Data/weights/weight.bin","size":400}, + {"rfilename":"C.mlpackage/Data/weights/weight.bin"}]} + """.utf8) + let info = try JSONDecoder().decode(HubModelMetadata.self, from: data) + let gguf = info.variantSizes(format: .gguf) + XCTAssertEqual(gguf.known.sorted(), [100, 300]) + XCTAssertTrue(gguf.someExceed(budget: 150)) + XCTAssertFalse(gguf.someExceed(budget: 400)) + let coreML = info.variantSizes(format: .coreML) + XCTAssertEqual(coreML.known.sorted(), [210, 410]) + XCTAssertEqual(coreML.totalVariants, 3) + XCTAssertTrue(coreML.someExceed(budget: 300)) + XCTAssertFalse(coreML.allExceed(budget: 100)) + XCTAssertTrue(gguf.allExceed(budget: 99)) + } + func testMarkdownExportIncludesEntireStoredConversationInOrder() throws { let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) @@ -2406,6 +2485,10 @@ extension ChatDocumentFallbackTests { let base = URL(string: endpoint)?.deletingLastPathComponent() else { throw XCTSkip("Run Scripts/test.sh to configure the local fixture.") } + let defaults = UserDefaults.standard + let previousSearch = defaults.object(forKey: "automaticChatWebSearch") + defaults.set(false, forKey: "automaticChatWebSearch") + defer { defaults.set(previousSearch, forKey: "automaticChatWebSearch") } let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)