new features

This commit is contained in:
Mark Gregory
2026-11-18 13:55:47 +00:00
parent 17bcf178a9
commit a07ddf4d6d
29 changed files with 3457 additions and 306 deletions
+398 -103
View File
@@ -32,7 +32,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
url.host = "huggingface.co"
url.path = "/api/models"
url.queryItems = [
.init(name: "author", value: "mlx-community"),
.init(name: "filter", value: "mlx"),
.init(name: "pipeline_tag", value: "text-generation"),
.init(name: "search", value: query),
.init(name: "limit", value: "25"),
@@ -45,46 +45,94 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
return try decodeSearch(response.data)
}
static func decodeSearch(_ data: Data) throws -> [Self] {
struct Entry: Decodable {
struct File: Decodable { let rfilename: String }
let id: String
let sha: String?
let siblings: [File]?
let downloads: Int?
let likes: Int?
enum HubGating: Decodable {
case open, restricted
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
self = (try? value.decode(Bool.self)) == false ? .open : .restricted
}
return try JSONDecoder().decode([Entry].self, from: data).compactMap { entry in
let prefix = "mlx-community/"
guard entry.id.hasPrefix(prefix), let revision = entry.sha, revision.count == 40,
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { return nil }
let name = String(entry.id.dropFirst(prefix.count))
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
guard !name.isEmpty, name.unicodeScalars.allSatisfy(safe.contains) else { return nil }
let files = (entry.siblings ?? []).map(\.rfilename).filter { file in
!file.hasPrefix(".") && file.unicodeScalars.allSatisfy(safe.contains) &&
(file.hasSuffix(".safetensors") || file.hasSuffix(".json") || file.hasSuffix(".txt") ||
file.hasSuffix(".model") || file.hasSuffix(".jinja") || file.hasSuffix(".tiktoken"))
}
}
private struct HubEntry: Decodable {
struct File: Decodable { let rfilename: String }
let id: String
let sha: String?
let siblings: [File]?
let downloads: Int?
let likes: Int?
let library_name: String?
let tags: [String]?
let privateModel: Bool?
let gated: HubGating?
enum CodingKeys: String, CodingKey {
case id, sha, siblings, downloads, likes, library_name, tags, gated
case privateModel = "private"
}
func catalogModel() -> CatalogModel? {
guard let (owner, name) = CatalogModel.repositoryParts(id),
let revision = sha, revision.count == 40,
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }),
privateModel != true, gated != .restricted else { return nil }
let declaresMLX = library_name == "mlx" || tags?.contains("mlx") == true
guard declaresMLX || (owner == "mlx-community" && library_name == nil) else { return nil }
let files = Set((siblings ?? []).map(\.rfilename).filter { file in
CatalogModel.safeComponent(file) &&
[".safetensors", ".json", ".txt", ".model", ".jinja", ".tiktoken"].contains { file.hasSuffix($0) }
})
guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }),
!files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil }
return Self(id: "hf-" + name, title: name, size: "", repository: entry.id, revision: revision,
files: Array(Set(files)).sorted(), downloads: entry.downloads, likes: entry.likes)
// Keep the existing installation key for mlx-community models.
let key = owner == "mlx-community" ? "hf-" + name : "hf--" + owner + "/" + name
return CatalogModel(id: key, title: name, size: "", repository: id, revision: revision,
files: files.sorted(), downloads: downloads, likes: likes)
}
}
static func safeComponent(_ value: String) -> Bool {
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
return !value.isEmpty && !value.hasPrefix(".") && value.unicodeScalars.allSatisfy(safe.contains)
}
static func repositoryParts(_ id: String) -> (String, String)? {
let parts = id.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
guard parts.count == 2, parts.allSatisfy(safeComponent) else { return nil }
return (parts[0], parts[1])
}
static func decodeSearch(_ data: Data) throws -> [Self] {
try JSONDecoder().decode([HubEntry].self, from: data).compactMap { $0.catalogModel() }
}
static func resolve(_ repository: String) async throws -> Self {
guard repositoryParts(repository) != nil else {
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
}
let endpoint = URL(string: "https://huggingface.co/api/models/")!.appending(path: repository)
let response = try await WebFetch.load(endpoint, types: ["application/json"])
return try decodeRepository(response.data, requested: repository)
}
static func decodeRepository(_ data: Data, requested: String) throws -> Self {
let entry = try JSONDecoder().decode(HubEntry.self, from: data)
guard entry.id.caseInsensitiveCompare(requested) == .orderedSame,
let model = entry.catalogModel() else {
throw StudioError("The repository does not expose a public MLX checkpoint with safetensors weights.")
}
return model
}
var source: URL { URL(string: "https://huggingface.co/" + repository)! }
var metadataKey: String { "mlx:" + repository + "@" + revision }
var localFolder: URL {
URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory)
.appending(path: id, directoryHint: .isDirectory)
.appending(path: id.contains("/") ? "Custom/" + repository : id, directoryHint: .isDirectory)
}
func installed(at folder: URL) -> Bool {
files.allSatisfy {
let file = folder.appending(path: $0)
return ((try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 0
}
!files.isEmpty && files.allSatisfy { MLXLibrary.hasFile($0, in: folder) } && MLXLibrary.isModel(at: folder)
}
func install(
@@ -96,7 +144,9 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
if manager.fileExists(atPath: destination.path) {
throw StudioError("Remove the incomplete managed model before reinstalling.")
}
let staging = URL.temporaryDirectory.appending(path: "AIStudio-model-\(UUID())", directoryHint: .isDirectory)
let parent = destination.deletingLastPathComponent()
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
let staging = parent.appending(path: ".download-\(UUID())", directoryHint: .isDirectory)
try manager.createDirectory(at: staging, withIntermediateDirectories: false)
defer { try? manager.removeItem(at: staging) }
@@ -113,14 +163,15 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
defer { try? manager.removeItem(at: download) }
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
http.url?.scheme == "https" else {
throw StudioError("Could not download \(file).")
let code = (response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
throw StudioError("Could not download \(file)\(code).")
}
try manager.moveItem(at: download, to: staging.appending(path: file))
}
try Task.checkCancellation()
guard installed(at: staging) else { throw StudioError("The download was incomplete.") }
try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
try manager.moveItem(at: staging, to: destination)
await progress("Download complete.", 1)
}
}
@@ -152,7 +203,7 @@ struct MLXModelConfiguration: Decodable {
struct HubModelMetadata: Decodable {
struct File: Decodable {
struct LFS: Decodable { let size: Int64 }
struct LFS: Decodable { let size: Int64; let sha256: String? }
let rfilename: String
let size: Int64?
let lfs: LFS?
@@ -295,15 +346,30 @@ struct ModelLibrarySelection {
let compatible: Bool
let mlxPath: String
let ollamaModel: String
let ggufPath: String
init(mlxOnly: Bool, compatible: Bool, mlxPath: String, ollamaModel: String, ggufPath: String = "") {
self.mlxOnly = mlxOnly
self.compatible = compatible
self.mlxPath = mlxPath
self.ollamaModel = ollamaModel
self.ggufPath = ggufPath
}
func isGGUF(_ path: String) -> Bool {
!ggufPath.isEmpty && canonicalPath(ggufPath) == canonicalPath(path)
}
private func canonicalPath(_ path: String) -> String {
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
}
func isMLX(_ path: String) -> Bool {
mlxOnly && !mlxPath.isEmpty &&
URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().standardizedFileURL.path ==
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
ggufPath.isEmpty && mlxOnly && !mlxPath.isEmpty && canonicalPath(mlxPath) == canonicalPath(path)
}
func isOllama(_ name: String) -> Bool {
guard !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
guard ggufPath.isEmpty, !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
func tag(_ value: String) -> String {
let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
return value.split(separator: "/").last?.contains(":") == true ? value : value + ":latest"
@@ -314,6 +380,8 @@ struct ModelLibrarySelection {
struct ModelCatalogView: View {
@ObservedObject var studio: StudioModel
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
@AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("mlxOnly") private var mlxOnly = false
@State private var downloads: [String: Task<Void, Never>] = [:]
@@ -324,11 +392,15 @@ struct ModelCatalogView: View {
let fraction: Double?
}
@AppStorage("mlxRegisteredPaths") private var registered = Data()
@AppStorage(GGUFModelMetadata.libraryKey) private var ggufLibrary = Data()
@State private var dropTargeted = false
@State private var pickingLibrary = false
@State private var scanningLibrary = false
@State private var scanRequested = false
@State private var libraryStatus = ""
@State private var loadedPath: String?
@State private var cacheScan = 0
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
@State private var removing: CatalogModel?
@State private var status = ""
@@ -340,12 +412,9 @@ struct ModelCatalogView: View {
@State private var loadingPath: String?
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
@State private var libraryBackend: String?
@State private var libraryBackend = "Local"
@State private var localQuery = ""
private var backend: Binding<String> {
Binding(get: { libraryBackend ?? (selection.mlxOnly ? "MLX" : "Ollama") },
set: { libraryBackend = $0 })
}
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@AppStorage("ollamaModel") private var ollamaModel = ""
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
@@ -368,12 +437,15 @@ struct ModelCatalogView: View {
@State private var catalogBytes: [String: Int64] = [:]
private func mlxPreview(model: CatalogModel?, folder: URL?) -> ModelPreview {
let title = model?.title ?? folder?.lastPathComponent ?? "MLX model"
let title = model?.title ?? folder.map(MLXLibrary.displayName(for:)) ?? "MLX model"
let cached = model.flatMap { catalogBytes[$0.metadataKey] }
let size = folder.map { ModelLibrarySize.mlx($0.path) } ?? cached.map { ModelLibrarySize.label($0) }
return ModelPreview(title: title, fields: [
("Backend", "MLX"), ("Weights", size), ("Repository", model?.repository),
("Revision", model?.revision), ("Local folder", folder?.path)
("Revision", model?.revision), ("Local folder", folder?.path),
("Compatibility", folder.map {
MLXLibrary.isModel(at: $0) ? "Checkpoint files present · runtime checked on load" : "Missing or invalid checkpoint files"
} ?? "MLX checkpoint · runtime checked on load")
], source: model?.source, load: {
if let folder {
let data = try Data(contentsOf: folder.appending(path: "config.json"))
@@ -426,11 +498,12 @@ struct ModelCatalogView: View {
return ModelLibrarySelection(
mlxOnly: studio.inferenceBackend.hasPrefix("MLX · "),
compatible: !studio.inferenceBackend.hasPrefix("Ollama · ") || run.endpoint != ollamaEndpoint,
mlxPath: run.path, ollamaModel: run.tag
mlxPath: run.path, ollamaModel: run.tag,
ggufPath: studio.inferenceBackend.hasPrefix("GGUF · ") ? run.tag : ""
)
}
return ModelLibrarySelection(mlxOnly: mlxOnly, compatible: compatibleEnabled,
mlxPath: mlxPath, ollamaModel: ollamaModel)
return ModelLibrarySelection(mlxOnly: mlxOnly && defaultCoreMLPath.isEmpty, compatible: compatibleEnabled || !defaultCoreMLPath.isEmpty,
mlxPath: mlxPath, ollamaModel: ollamaModel, ggufPath: defaultGGUFPath)
}
private func activeBadge(_ runtime: String) -> some View {
@@ -496,17 +569,17 @@ struct ModelCatalogView: View {
var body: some View {
VStack(spacing: 0) {
Picker("Model runtime", selection: backend) {
Text("MLX").tag("MLX")
Picker("Model library", selection: $libraryBackend) {
Text("On This Mac").tag("Local")
Text("Ollama").tag("Ollama")
}
.pickerStyle(.segmented)
.frame(width: 260)
.padding()
if backend.wrappedValue == "Ollama" {
if libraryBackend == "Ollama" {
ollamaLibrary
} else {
mlxLibrary
localLibrary
}
}
.sheet(item: $preview) { ModelPreviewSheet(preview: $0) }
@@ -526,30 +599,120 @@ struct ModelCatalogView: View {
}
}
private var mlxLibrary: some View {
private func matchesLocal(_ name: String) -> Bool {
let query = localQuery.trimmingCharacters(in: .whitespacesAndNewlines)
return query.isEmpty || [name, "MLX"].contains { $0.localizedStandardContains(query) }
}
private func registerLocalModels(_ models: [LocalModelImport]) throws {
let gguf = models.compactMap { if case .gguf(let model) = $0 { return model }; return nil }
let mlx = models.compactMap { if case .mlx(let path) = $0 { return path }; return nil }
if !gguf.isEmpty { ggufLibrary = try GGUFModelMetadata.register(gguf, in: ggufLibrary) }
if !mlx.isEmpty { registered = try JSONEncoder().encode(Array(Set(library + mlx)).sorted()) }
}
private func importLMStudioLibrary() {
scanningLibrary = true
libraryStatus = ""
Task {
defer { scanningLibrary = false }
do {
let models = try await Task.detached(priority: .userInitiated) {
try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
}.value
try registerLocalModels(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 func acceptModelDrop(_ providers: [NSItemProvider]) -> Bool {
let files = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }
guard !files.isEmpty, !scanningLibrary, !studio.running else { return false }
scanningLibrary = true
Task {
defer { scanningLibrary = false }
var models: [LocalModelImport] = []
var messages: [String] = []
for provider in files {
do {
let url: URL = try await withCheckedThrowingContinuation { continuation in
_ = provider.loadDataRepresentation(forTypeIdentifier: UTType.fileURL.identifier) { data, error in
if let error { continuation.resume(throwing: error) }
else if let data, let url = URL(dataRepresentation: data, relativeTo: nil), url.isFileURL {
continuation.resume(returning: url)
} else {
continuation.resume(throwing: StudioError("Finder did not provide a local file URL."))
}
}
}
let model = try await Task.detached(priority: .userInitiated) { try LocalModelImport.inspect(url) }.value
models.append(model)
} catch {
messages.append(error.localizedDescription)
}
}
do {
try registerLocalModels(models)
let count = models.count
if count > 0 { messages.insert("Registered \(count) model(s).", at: 0) }
} catch { messages.append(error.localizedDescription) }
libraryStatus = messages.joined(separator: " ")
}
return true
}
private var localLibrary: some View {
Form {
Section {
TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format"))
.textFieldStyle(.roundedBorder)
.accessibilityLabel("Filter installed models")
Label(dropTargeted ? "Release to import" : "Drop GGUF files or MLX folders here",
systemImage: "square.and.arrow.down")
.font(.callout)
.foregroundStyle(dropTargeted ? Color.accentColor : Color.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(dropTargeted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.07),
in: RoundedRectangle(cornerRadius: 8))
.onDrop(of: [.fileURL], isTargeted: $dropTargeted, perform: acceptModelDrop)
Button("Import LM Studio Library", systemImage: "folder.badge.plus", action: importLMStudioLibrary)
.disabled(scanningLibrary || studio.running)
if scanningLibrary { ProgressView("Checking model files…").controlSize(.small) }
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
GGUFModels(selection: selection.ggufPath, inUse: studio.inferenceBackend.hasPrefix("GGUF · "),
filter: localQuery, selectionDisabled: studio.running) {
studio.selectGGUFModel($0)
}
Section("Installed MLX Models") {
HStack {
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true }
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true }
Button("Import MLX Models…") { pickingLibrary = true }
Button("Refresh Local Models") { cacheScan += 1 }
Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) }
if scanningLibrary { ProgressView().controlSize(.small) }
}
.disabled(studio.running || scanningLibrary)
if library.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
if library.isEmpty && studio.discoveredMLXPaths.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
Text("Register an existing MLX folder, scan a model library, or download a catalog model below.")
.foregroundStyle(.secondary)
}
ForEach(favoriteFirst(readyModels) { "mlx:" + $0.id }) { model in modelRow(model) }
ForEach(favoriteFirst(readyModels.filter { matchesLocal($0.id) }) { "mlx:" + $0.id }) { model in modelRow(model) }
let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : []
let paths = Array(Set(library + selectedPath)).sorted().filter { path in
!readyModels.contains { $0.localFolder.standardizedFileURL.path == URL(fileURLWithPath: path).standardizedFileURL.path }
}
ForEach(favoriteFirst(paths) { "folder:" + $0 }, id: \.self) { path in
let managedPaths = Set(readyModels.map { $0.localFolder.resolvingSymlinksInPath().path })
let paths = Set((library + studio.discoveredMLXPaths + selectedPath).map {
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}).subtracting(managedPaths).sorted()
ForEach(favoriteFirst(paths.filter { matchesLocal(MLXLibrary.displayName(for: URL(fileURLWithPath: $0))) }) { "folder:" + $0 }, id: \.self) { path in
HStack {
let title = URL(fileURLWithPath: path).lastPathComponent
let title = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
VStack(alignment: .leading, spacing: 4) {
Text(title).help(path)
Text("MLX · Safetensors").font(.caption).foregroundStyle(.secondary)
ModelMemoryWarning(bytes: (try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: path))).flatMap { Int64(exactly: $0) }, mlx: true)
popularityBadge(title)
}
favoriteButton("folder:" + path)
@@ -557,13 +720,11 @@ struct ModelCatalogView: View {
Text(ModelLibrarySize.mlx(path))
.font(.caption).foregroundStyle(.secondary)
.help("Size of local model weights")
if selection.isMLX(path) { activeBadge("MLX") }
mlxStatus(path)
Button("Preview") {
preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path))
}
Button("Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || selection.isMLX(path) ||
!MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
mlxLoadButton(path)
Menu("Tools") {
Button("Clone & Train…") { workshop = ModelWorkshop(base: URL(fileURLWithPath: path)) }
Button("Reveal") {
@@ -572,20 +733,23 @@ struct ModelCatalogView: View {
}
.fixedSize()
if library.contains(path) {
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
if library.contains(path) {
Button("Unregister") {
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
}.disabled(studio.running)
}
}
}
.listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil)
}
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
}
Section("Hugging Face") {
CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) }
HubGGUFDownloads()
Section("Hugging Face · MLX") {
HStack {
TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma"))
TextField("Search MLX models", text: $query, prompt: Text("Qwen, Gemma, or owner/model"))
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching || hasMLXDownloads)
Button(query.isEmpty ? "Browse" : (query.contains("/") ? "Find Model ID" : "Search"), action: search).disabled(searching || hasMLXDownloads)
if searching { ProgressView().controlSize(.small) }
}
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
@@ -605,26 +769,41 @@ struct ModelCatalogView: View {
}
}
.formStyle(.grouped)
.onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } }
.task(id: cacheScan) {
do {
try await studio.refreshLocalMLXModels()
} catch is CancellationError {
return
} catch {
libraryStatus = "Could not scan local models. \(error.localizedDescription)"
}
}
.task {
while !Task.isCancelled {
await refreshLoadedPath()
do { try await Task.sleep(for: .seconds(2)) }
catch { return }
}
}
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
do {
let url = try result.get()
if scanRequested {
scanningLibrary = true
Task {
defer { scanningLibrary = false }
do {
let found = try await Task.detached { try MLXLibrary.discover(in: url) }.value
registered = try JSONEncoder().encode(Array(Set(library + found.map(\.path))).sorted())
libraryStatus = "Found \(found.count) compatible MLX model folder(s)."
} catch { libraryStatus = error.localizedDescription }
}
} else {
guard MLXLibrary.isModel(at: url) else {
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
}
registered = try JSONEncoder().encode(Array(Set(library + [url.resolvingSymlinksInPath().path])).sorted())
libraryStatus = "Registered \(url.lastPathComponent)."
scanningLibrary = true
libraryStatus = ""
Task {
defer { scanningLibrary = false }
do {
let found = try await Task.detached(priority: .userInitiated) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
return try MLXLibrary.discover(in: url.resolvingSymlinksInPath())
}.value
guard !found.isEmpty else {
throw StudioError("No complete MLX checkpoints found in \(url.lastPathComponent).")
}
try registerLocalModels(found.map { .mlx($0.path) })
libraryStatus = "Registered \(found.count) MLX model(s)."
} catch { libraryStatus = error.localizedDescription }
}
} catch { libraryStatus = error.localizedDescription }
}
@@ -647,6 +826,9 @@ struct ModelCatalogView: View {
HStack {
VStack(alignment: .leading, spacing: 4) {
Label(model.name, systemImage: "cube")
if let format = model.details?.format {
Text(format.uppercased()).font(.caption).foregroundStyle(.secondary)
}
popularityBadge(model.name)
}
favoriteButton("ollama:" + model.name)
@@ -811,19 +993,22 @@ struct ModelCatalogView: View {
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 isActive { activeBadge("MLX") }
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 {
Button("Load Model") { load(saved.localFolder.path) }
.disabled(studio.running || loadingPath != nil || isActive)
mlxLoadButton(saved.localFolder.path)
Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) }
.disabled(studio.running || loadingPath != nil)
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
@@ -843,7 +1028,7 @@ struct ModelCatalogView: View {
}
.padding(.vertical, 4)
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
.task(id: installed) {
.task(id: installed ? nil : metadataKey) {
guard !installed, catalogBytes[metadataKey] == nil else { return }
if let metadata = try? await HubModelMetadata.load(model), !Task.isCancelled {
catalogBytes[metadataKey] = metadata.weightBytes(files: model.files)
@@ -865,27 +1050,75 @@ struct ModelCatalogView: View {
guard !searching, !hasMLXDownloads else { return }
searching = true
searchStatus = ""
matches = []
Task {
defer { searching = false }
do {
matches = try await CatalogModel.search(term)
if term.contains("/") {
matches = [try await CatalogModel.resolve(term)]
} else {
matches = try await CatalogModel.search(term)
}
if matches.isEmpty { searchStatus = "No MLX checkpoints matched." }
} catch { searchStatus = error.localizedDescription }
}
}
private func refreshLoadedPath() async {
loadedPath = await studio.mlxLoadedPath().map {
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}
}
private func isLoaded(_ path: String) -> Bool {
loadedPath == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
}
@ViewBuilder
private func mlxStatus(_ path: String) -> some View {
if selection.isMLX(path) {
Label("Selected", systemImage: "checkmark.circle.fill")
.font(.caption.weight(.semibold)).foregroundStyle(Color.accentColor)
}
if isLoaded(path) {
let inUse = studio.running && studio.inferenceBackend.hasPrefix("MLX")
Label(inUse ? "In use" : "Loaded", systemImage: "memorychip")
.font(.caption).foregroundStyle(.secondary)
}
}
@ViewBuilder
private func mlxLoadButton(_ path: String) -> some View {
if isLoaded(path) {
Button("Unload") {
Task {
await studio.unloadMLXModel()
await refreshLoadedPath()
}
}
.disabled(studio.running || loadingPath != nil)
if !selection.isMLX(path) {
Button("Use Model") { studio.selectMLXModel(path) }.disabled(studio.running)
}
} else {
Button("Load Model") { load(path) }
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
}
}
private func load(_ path: String) {
guard loadingPath == nil, !studio.running else { return }
loadingPath = path
let name = URL(fileURLWithPath: path).lastPathComponent
let name = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
status = "Loading \(name)…"
Task {
defer { loadingPath = nil }
do {
try await studio.loadMLX(path)
studio.selectMLXModel(path)
status = "Loaded \(name)."
} catch { status = error.localizedDescription }
} catch { status = "Could not load \(name). \(error.localizedDescription)" }
await refreshLoadedPath()
loadingPath = nil
}
}
@@ -913,10 +1146,11 @@ struct ModelCatalogView: View {
guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
do {
try FileManager.default.removeItem(at: model.localFolder)
if mlxPath == model.localFolder.path {
if isLoaded(model.localFolder.path) { studio.unloadMLX() }
if URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().path == model.localFolder.resolvingSymlinksInPath().path {
mlxPath = ""
studio.unloadMLX()
}
studio.forgetDiscoveredMLXModel(model.localFolder.resolvingSymlinksInPath().path)
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) })
status = "Removed \(model.title)."
} catch { status = error.localizedDescription }
@@ -937,9 +1171,17 @@ enum MLXLibrary {
offset += 1
if isModel(at: folder) { found.append(folder); continue }
guard depth < 4 else { continue }
let children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants])
let children: [URL]
do {
children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants])
.sorted { $0.lastPathComponent < $1.lastPathComponent }
} catch {
if depth == 0 { throw error }
continue
}
for child in children where queue.count < 2000 {
if folder.lastPathComponent.hasPrefix("models--"), child.lastPathComponent != "snapshots" { continue }
if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
values.isDirectory == true, values.isSymbolicLink != true {
queue.append((child, depth + 1))
@@ -949,9 +1191,62 @@ enum MLXLibrary {
return found.sorted { $0.path < $1.path }
}
static func discoverLocalModels() throws -> [URL] {
let environment = ProcessInfo.processInfo.environment
let home = URL.homeDirectory
let defaultCache = home.appending(path: ".cache/huggingface/hub")
var roots = [
URL.applicationSupportDirectory.appending(path: "AIStudio/Models"),
URL.documentsDirectory.appending(path: "huggingface/models"),
defaultCache, LocalModelImport.lmStudioFolder
]
if let cache = environment["HF_HUB_CACHE"] ?? environment["HUGGINGFACE_HUB_CACHE"], !cache.isEmpty {
roots.append(URL(fileURLWithPath: cache))
}
if let hfHome = environment["HF_HOME"], !hfHome.isEmpty {
roots.append(URL(fileURLWithPath: hfHome).appending(path: "hub"))
}
if let cache = environment["XDG_CACHE_HOME"], !cache.isEmpty {
roots.append(URL(fileURLWithPath: cache).appending(path: "huggingface/hub"))
}
var found: Set<URL> = []
for root in Set(roots.map { $0.resolvingSymlinksInPath() }) where FileManager.default.fileExists(atPath: root.path) {
found.formUnion(try discover(in: root))
}
return found.sorted { $0.path < $1.path }
}
static func displayName(for folder: URL) -> String {
let snapshots = folder.deletingLastPathComponent()
let repository = snapshots.deletingLastPathComponent().lastPathComponent
guard snapshots.lastPathComponent == "snapshots", repository.hasPrefix("models--") else {
return folder.lastPathComponent
}
let name = repository.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/")
return "\(name) · \(folder.lastPathComponent.prefix(8))"
}
static func hasFile(_ name: String, in folder: URL) -> Bool {
let file = folder.appending(path: name).resolvingSymlinksInPath()
guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else { return false }
return values.isRegularFile == true && (values.fileSize ?? 0) > 0
}
static func isModel(at url: URL) -> Bool {
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) &&
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0
let config = url.appending(path: "config.json")
guard hasFile("config.json", in: url),
let data = try? Data(contentsOf: config),
(try? MLXModelConfiguration.decode(data)) != nil,
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 else { return false }
let index = url.appending(path: "model.safetensors.index.json")
guard FileManager.default.fileExists(atPath: index.path) else { return true }
struct Index: Decodable { let weight_map: [String: String] }
guard let data = try? Data(contentsOf: index),
let map = try? JSONDecoder().decode(Index.self, from: data).weight_map,
!map.isEmpty else { return false }
return Set(map.values).allSatisfy {
CatalogModel.safeComponent($0) && $0.hasSuffix(".safetensors") && hasFile($0, in: url)
}
}
}