import AppKit import Foundation import SwiftUI struct MLXTraining { enum Action: String { case validate, train, evaluate, fuse } let base: URL let dataset: URL? let project: URL let iterations: Int let layers: Int var adapter: URL { project.appending(path: "adapter", directoryHint: .isDirectory) } var fused: URL { project.appending(path: "trained-model", directoryHint: .isDirectory) } func arguments(for action: Action, runner: URL) throws -> [String] { var args = [runner.path, action.rawValue] if action != .validate { args += ["--base", base.path, "--adapter", adapter.path] } if action != .fuse { guard let dataset else { throw StudioError("Choose a dataset folder.") } args += ["--data", dataset.path] } if action == .train { args += ["--iters", String(iterations), "--layers", String(layers)] } if action == .fuse { args += ["--out", fused.path] } return args } static func conversionArguments(runner: URL, source: String, revision: String, output: URL, quantize: Bool) -> [String] { var args = [runner.path, "convert", "--source", source, "--out", output.path] if !revision.isEmpty { args += ["--revision", revision] } if quantize { args.append("--quantize") } return args } static func clone(_ source: URL, to destination: URL) throws { let files = FileManager.default let base = source.resolvingSymlinksInPath().standardizedFileURL let parent = destination.deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL let target = parent.appending(path: destination.lastPathComponent, directoryHint: .isDirectory) guard MLXLibrary.isModel(at: base) else { throw StudioError("Choose an installed MLX model.") } guard !target.pathComponents.starts(with: base.pathComponents), !files.fileExists(atPath: target.path) else { throw StudioError("Choose a new folder outside the base model.") } let staging = parent.appending(path: ".aistudio-clone-\(UUID().uuidString)", directoryHint: .isDirectory) try files.createDirectory(at: staging, withIntermediateDirectories: false) defer { try? files.removeItem(at: staging) } for item in try files.contentsOfDirectory(at: base, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) { try Task.checkCancellation() try files.copyItem(at: item.resolvingSymlinksInPath(), to: staging.appending(path: item.lastPathComponent)) } try Task.checkCancellation() try files.moveItem(at: staging, to: target) } } @MainActor final class TrainingOperation: ObservableObject { @Published private(set) var active: String? @Published private(set) var status = "" @Published private(set) var log = "" private var task: Task? private var process: Process? func run(_ title: String, work: @escaping @MainActor () async throws -> Void) { guard task == nil else { return } active = title status = "" log = "" task = Task { defer { active = nil; task = nil } do { try await work() try Task.checkCancellation() status = "\(title) complete." } catch { status = Task.isCancelled ? "Stopped." : error.localizedDescription } } } func stop() { task?.cancel() if let process, process.isRunning { process.terminate() } } func execute(_ executable: URL, _ args: [String]) async throws { try Task.checkCancellation() guard FileManager.default.isExecutableFile(atPath: executable.path) else { throw StudioError("Missing executable: \(executable.lastPathComponent). Install the MLX tools first.") } let process = Process() process.executableURL = executable process.arguments = args process.standardInput = FileHandle.nullDevice var environment = ProcessInfo.processInfo.environment environment["PYTHONUNBUFFERED"] = "1" environment["NO_COLOR"] = "1" environment["TERM"] = "dumb" environment["PATH"] = executable.deletingLastPathComponent().path + ":" + (environment["PATH"] ?? "/usr/bin:/bin") process.environment = environment let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe try process.run() self.process = process defer { self.process = nil } try? pipe.fileHandleForWriting.close() let exit = await Task.detached { let handle = pipe.fileHandleForReading defer { try? handle.close() } while let data = try? handle.read(upToCount: 4096), !data.isEmpty { await self.append(String(decoding: data, as: UTF8.self)) } process.waitUntilExit() return process.terminationStatus }.value try Task.checkCancellation() guard exit == 0 else { throw StudioError("The command exited with status \(exit). See the output below.") } } private func append(_ text: String) { log += text.replacingOccurrences(of: "\u{001B}\\[[0-?]*[ -/]*[@-~]", with: "", options: .regularExpression) if log.count > 80_000 { log = String(log.suffix(60_000)) } } } struct ModelWorkshop: Identifiable { let id = UUID() let base: URL? var modelName: String? } @MainActor struct ModelWorkshopView: View { let workshop: ModelWorkshop let register: (URL) -> Void let embedded: Bool private enum Stage: String, CaseIterable, Identifiable { case setup = "Tools", convert = "Convert", train = "Train" var id: Self { self } } @State private var stage: Stage = .train @Environment(\.dismiss) private var dismiss @AppStorage("trainingInstallerPython") private var installerPython = "" @AppStorage("trainingDatasetPath") private var datasetPath = "" @AppStorage("trainingProjectPath") private var projectPath = "" @StateObject private var operation = TrainingOperation() @State private var base: URL? @State private var sourceFolder: URL? @State private var repository = "" @State private var revision = "" @State private var quantize = true @State private var iterations = 50 @State private var layers = 4 init(workshop: ModelWorkshop, embedded: Bool = false, register: @escaping (URL) -> Void) { self.workshop = workshop self.register = register self.embedded = embedded _base = State(initialValue: workshop.base) } private var environment: URL { URL.applicationSupportDirectory.appending(path: "AIStudio/TrainingEnvironment", directoryHint: .isDirectory) } private var bin: URL { environment.appending(path: "bin", directoryHint: .isDirectory) } private var python: URL { bin.appending(path: "python3") } private var toolsInstalled: Bool { ["python3", "mlx_lm.lora", "mlx_lm.fuse", "mlx_lm.convert"].allSatisfy { FileManager.default.isExecutableFile(atPath: bin.appending(path: $0).path) } } private var busy: Bool { operation.active != nil } var body: some View { VStack(spacing: 0) { if embedded { VStack(alignment: .leading, spacing: 10) { Text("Training").font(.largeTitle.weight(.semibold)) Label(toolsInstalled ? "MLX tools ready" : "MLX tools setup required", systemImage: toolsInstalled ? "checkmark.circle.fill" : "info.circle") .foregroundStyle(.secondary) Picker("Training stage", selection: $stage) { ForEach(Stage.allCases) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 340) } .frame(maxWidth: .infinity, alignment: .leading) .padding(20) Divider() } Form { if !embedded || stage == .setup { Section("MLX Tools") { LabeledContent("Environment", value: toolsInstalled ? "Installed" : "Setup required") HStack { Button(toolsInstalled ? "Reinstall MLX Tools" : "Install MLX Tools", action: install) Button("Choose Python…") { if let url = selectURL(folders: false) { installerPython = url.path } } } Text(installerPython.isEmpty ? "Uses a local Python 3.11 or newer to set up a dedicated environment." : installerPython) .foregroundStyle(.secondary) } } if !embedded || stage == .convert { Section("Convert to MLX") { if let name = workshop.modelName { Text("For \(name), select its original Hugging Face checkpoint. Ollama GGUF files cannot be converted by MLX LM.") .foregroundStyle(.secondary) } if let sourceFolder { LabeledContent("Checkpoint", value: sourceFolder.path) } else { TextField("Hugging Face repository", text: $repository, prompt: Text("owner/model")) TextField("Revision", text: $revision, prompt: Text("Optional commit or tag")) } HStack { Button("Choose Checkpoint Folder…") { if let url = selectURL() { sourceFolder = url } } if sourceFolder != nil { Button("Use Hugging Face Repository") { sourceFolder = nil } } } Toggle("Quantize to 4-bit", isOn: $quantize) Button("Convert and Register…", action: convert) .disabled(!toolsInstalled || (sourceFolder == nil && repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)) } } if !embedded || stage == .train { Section("Clone and Train") { LabeledContent("Base checkpoint", value: base?.path ?? "Choose a converted MLX folder") HStack { Button("Choose Base…") { if let url = selectURL() { base = url } } Button("Clone Base…", action: clone).disabled(base == nil) } LabeledContent("Dataset", value: datasetPath.isEmpty ? "No folder selected" : datasetPath) Button("Choose Dataset…") { if let url = selectURL() { datasetPath = url.path } } Text("Use a folder containing train.jsonl, valid.jsonl and test.jsonl with text chat examples.") .foregroundStyle(.secondary) LabeledContent("Run folder", value: projectPath.isEmpty ? "No folder selected" : projectPath) Button("Choose Run Folder…") { if let url = selectURL(create: true) { projectPath = url.path } } Stepper("Training iterations: \(iterations)", value: $iterations, in: 1...100_000) Stepper("Adapted layers: \(layers)", value: $layers, in: 1...256) HStack { Button("Validate Dataset") { train(.validate) }.disabled(!toolsInstalled || datasetPath.isEmpty) Button("Train Adapter") { train(.train) }.disabled(!ready || datasetPath.isEmpty) Button("Evaluate") { train(.evaluate) }.disabled(!ready || datasetPath.isEmpty) Button("Fuse and Register") { train(.fuse) }.disabled(!ready) } } } } .formStyle(.grouped) .disabled(busy) Divider() VStack(alignment: .leading, spacing: 8) { if embedded { Text("Run output").font(.headline) } if !operation.log.isEmpty { ScrollViewReader { proxy in ScrollView { Text(operation.log).font(.system(.caption, design: .monospaced)) .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) .id("run-end") } .onChange(of: operation.log) { proxy.scrollTo("run-end", anchor: .bottom) } }.frame(height: embedded ? 145 : 112) } HStack { if let active = operation.active { ProgressView().controlSize(.small) Text(active) Button("Stop") { operation.stop() } } else if !operation.status.isEmpty { Text(operation.status).textSelection(.enabled) } Spacer() if !embedded { Button("Done") { dismiss() }.disabled(busy) } } } .padding(12) } .frame(width: embedded ? nil : 660, height: embedded ? nil : 585) .interactiveDismissDisabled(busy) .onAppear { if embedded && !toolsInstalled { stage = .setup } } } private var ready: Bool { toolsInstalled && base != nil && !projectPath.isEmpty } private func selectURL(folders: Bool = true, create: Bool = false) -> URL? { let panel = NSOpenPanel() panel.canChooseDirectories = folders panel.canChooseFiles = !folders panel.canCreateDirectories = create panel.allowsMultipleSelection = false return panel.runModal() == .OK ? panel.url : nil } private func outputFolder(suggestedName: String) -> URL? { let panel = NSSavePanel() panel.nameFieldStringValue = suggestedName panel.canCreateDirectories = true panel.prompt = "Choose" return panel.runModal() == .OK ? panel.url : nil } private func install() { let candidates = ["/opt/homebrew/bin/python3", "/usr/local/bin/python3", "/usr/bin/python3"] let path = installerPython.isEmpty ? candidates.first(where: FileManager.default.isExecutableFile(atPath:)) : installerPython operation.run("Install MLX tools") { guard let path else { throw StudioError("Choose a Python 3.11 or newer executable.") } if !FileManager.default.isExecutableFile(atPath: python.path) { try await operation.execute(URL(fileURLWithPath: path), ["-c", """ import platform, sys if sys.version_info < (3, 11) or platform.machine() != 'arm64': sys.exit('Choose an Apple Silicon Python 3.11 or newer.') """]) try FileManager.default.createDirectory(at: environment.deletingLastPathComponent(), withIntermediateDirectories: true) try await operation.execute(URL(fileURLWithPath: path), ["-m", "venv", environment.path]) } try await operation.execute(python, ["-m", "pip", "install", "mlx-lm[train]"]) } } private func clone() { guard let base, let output = outputFolder(suggestedName: base.lastPathComponent + "-clone") else { return } operation.run("Clone model") { let worker = Task.detached { try MLXTraining.clone(base, to: output) } try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } register(output) self.base = output } } private func convert() { let repo = repository.trimmingCharacters(in: .whitespacesAndNewlines) let revision = sourceFolder == nil ? revision.trimmingCharacters(in: .whitespacesAndNewlines) : "" let source = sourceFolder?.path ?? repo let name = sourceFolder?.lastPathComponent ?? repo.split(separator: "/").last.map(String.init) ?? "converted" guard let output = outputFolder(suggestedName: name + "-mlx") else { return } operation.run("Convert model") { if let sourceFolder { guard FileManager.default.fileExists(atPath: sourceFolder.appending(path: "config.json").path) else { throw StudioError("Choose a Hugging Face checkpoint folder containing config.json.") } } else { guard repo.range(of: #"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$"#, options: .regularExpression) != nil else { throw StudioError("Enter a Hugging Face repository as owner/model.") } } guard !FileManager.default.fileExists(atPath: output.path) else { throw StudioError("Choose a new output folder.") } let args = try MLXTraining.conversionArguments(runner: runner(), source: source, revision: revision, output: output, quantize: quantize) try await operation.execute(python, args) try registerModel(output) base = output } } private func train(_ action: MLXTraining.Action) { let title: String switch action { case .validate: title = "Validate dataset" case .train: title = "Train adapter" case .evaluate: title = "Evaluate adapter" case .fuse: title = "Fuse model" } operation.run(title) { let runner = try runner() let dataset = datasetPath.isEmpty ? nil : URL(fileURLWithPath: datasetPath, isDirectory: true) if action == .validate { guard let dataset else { throw StudioError("Choose a dataset folder.") } try await operation.execute(python, [runner.path, "validate", "--data", dataset.path]) return } guard let base, !projectPath.isEmpty else { throw StudioError("Choose a base and run folder.") } let project = URL(fileURLWithPath: projectPath, isDirectory: true) let job = MLXTraining(base: base, dataset: dataset, project: project, iterations: iterations, layers: layers) try await operation.execute(python, job.arguments(for: action, runner: runner)) if action == .fuse { try registerModel(job.fused) } } } private func runner() throws -> URL { guard let url = Bundle.main.url(forResource: "train-mlx", withExtension: "py") else { throw StudioError("The application is missing its MLX training runner.") } return url } private func registerModel(_ url: URL) throws { guard MLXLibrary.isModel(at: url) else { throw StudioError("The output does not contain an MLX configuration and weights.") } register(url) } }