Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraLocalTests/ModelVerification.swift10// Module : AstraLocalTests11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import CoreGraphics90import Foundation91import ImageIO92import Testing93@testable import AstraLocal9495enum ProjectPaths {96 /// Repository root, derived from this file's location (Tests/AstraLocalTests/…).97 static let root: URL = {98 if let override = ProcessInfo.processInfo.environment["ASTRA_PROJECT_ROOT"], !override.isEmpty { return URL(fileURLWithPath: override) }99 return URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()100 }()101 static let models = root.appendingPathComponent("build/models", isDirectory: true)102 static let results = root.appendingPathComponent("build/verify", isDirectory: true)103 static let catalog = root.appendingPathComponent("docs/catalog/catalog.json")104 static let compatibility = root.appendingPathComponent("docs/MODEL_COMPATIBILITY.md")105 static func env(_ name: String) -> String? { ProcessInfo.processInfo.environment[name].flatMap { $0.isEmpty ? nil : $0 } }106}107108/// Everything recorded while verifying one candidate repository on this machine.109struct VerificationResult: Codable {110 struct Turn: Codable {111 var text: String; var reasoning: String112 var promptTokens: Int?; var cachedPromptTokens: Int?; var completionTokens: Int?113 var timeToFirstToken: Double?; var decodeTokensPerSecond: Double?; var stopReason: String114 }115 struct Cancellation: Codable { var chunksBeforeCancel: Int; var secondsToStop: Double; var endedWithCancelledError: Bool; var completedEventSeen: Bool }116 var repo: String117 var id: String118 var date: String119 var passed = false120 var failure: String?121 var stage = "resolve"122 var revision: String?123 var hubLicense: String?124 var hubTags: [String] = []125 var hubBaseModels: [String] = []126 var hubPipeline: String?127 var files: [LocalModelFile] = []128 var totalBytes: Int64 = 0129 var downloadSeconds: Double?130 var downloadRetries: Int?131 var modelType: String?132 var quantizationBits: Int?133 var quantizationMode: String?134 var contextLength: Int?135 var hasVision = false136 var licenseFiles: [String] = []137 var licenseFileHead: String?138 var loadSeconds: Double?139 var weightsMemoryBytes: Int64?140 var templateSupportsTools: Bool?141 var turn1: Turn?142 var turn2: Turn?143 var recalledFact: Bool?144 var cancellation: Cancellation?145 var reloadSeconds: Double?146 var reloadAnswer: String?147 var benchmark: LocalBenchmarkResult?148 var tokensPerSecond: Double?149 var timeToFirstToken: Double?150 var coldTimeToFirstToken: Double?151 var peakMemoryBytes: Int64?152 var device: DeviceFacts = .current()153 var chip: String?154 /// Probes that do not decide pass or fail; nil = not attempted because the model does not declare the feature.155 var reasoningVerified: Bool?156 var toolCallVerified: Bool?157 var visionVerified: Bool?158 var visionAnswer: String?159 var buildConfiguration: String?160 /// One-minute load average of the machine when the benchmark ran: other work on the Mac lowers every speed figure.161 var loadAverage: Double?162 /// How the files reached this Mac: "DownloadCoordinator" (fetched by the app's own downloader in this run), "pre-staged" (copied in163 /// beforehand, then only hashed by the coordinator) or "already present" (downloaded by the coordinator in an earlier run).164 var transfer: String?165 /// Capability probes (thinking on/off, cancellation while thinking, coding prompts, image probes, JSON-only output).166 var capability: CapabilityProbes?167}168169struct ModelVerifier {170 let repo: String171 var id: String { String(repo.split(separator: "/").last ?? "") }172173 static func today() -> String { let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd"; return f.string(from: Date()) }174175 static func chip() -> String? {176 var size = 0177 guard sysctlbyname("machdep.cpu.brand_string", nil, &size, nil, 0) == 0, size > 0 else { return nil }178 var buffer = [CChar](repeating: 0, count: size)179 guard sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nil, 0) == 0 else { return nil }180 return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)181 }182183 /// A 96 × 96 plain red PNG, made here so the vision probe needs no fixture file.184 static func redSquarePNG() -> Data? {185 let side = 96186 guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),187 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }188 context.setFillColor(red: 0.9, green: 0.05, blue: 0.05, alpha: 1); context.fill(CGRect(x: 0, y: 0, width: side, height: side))189 guard let image = context.makeImage() else { return nil }190 let data = NSMutableData()191 guard let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { return nil }192 CGImageDestinationAddImage(destination, image, nil)193 return CGImageDestinationFinalize(destination) ? data as Data : nil194 }195196 func log(_ message: String) { FileHandle.standardError.write(Data("[verify \(id)] \(message)\n".utf8)) }197198 func run() async -> VerificationResult {199 var result = VerificationResult(repo: repo, id: id, date: Self.today())200 result.chip = Self.chip()201 #if DEBUG202 result.buildConfiguration = "debug"203 #else204 result.buildConfiguration = "release"205 #endif206 do { try await steps(&result); result.passed = true; result.stage = "done" }207 catch { result.failure = (error as? LocalizedError)?.errorDescription ?? String(describing: error) }208 log(result.passed ? "PASS" : "FAIL at \(result.stage): \(result.failure ?? "")")209 return result210 }211212 private func collect(_ engine: LocalEngine, _ request: GenerationRequest) async throws -> VerificationResult.Turn {213 var validator = StreamValidator(); var text = ""; var reasoning = ""; var completed: StopReason?214 for try await event in engine.generate(request) {215 for e in try validator.accept(event) {216 switch e {217 case .textDelta(let t): text += t218 case .reasoningSummaryDelta(let t): reasoning += t219 case .messageCompleted(let r): completed = r220 default: break221 }222 }223 }224 guard let completed else { throw AstraError.protocolViolation("the stream ended without .messageCompleted") }225 guard let m = engine.monitor.lastMetrics else { throw AstraError.local("no metrics were recorded") }226 return .init(text: text, reasoning: reasoning, promptTokens: m.promptTokens, cachedPromptTokens: m.cachedPromptTokens, completionTokens: m.completionTokens,227 timeToFirstToken: m.timeToFirstToken, decodeTokensPerSecond: m.decodeTokensPerSecond, stopReason: completed.rawValue)228 }229230 private func steps(_ r: inout VerificationResult) async throws {231 // 1. Resolve the current commit and file list from the public Hub API.232 r.stage = "resolve"233 let snapshot = try await HuggingFaceResolver(transport: URLSessionTransport()).snapshot(repo: repo)234 r.revision = snapshot.revision; r.hubLicense = snapshot.license; r.hubTags = snapshot.tags235 r.hubBaseModels = snapshot.baseModels; r.hubPipeline = snapshot.pipelineTag236 let plan = snapshot.plan(id: id)237 log("revision \(snapshot.revision), \(plan.files.count) files, \(MemoryGovernor.format(plan.totalBytes))")238239 // 2. Download through the app's own coordinator, with Range resume and per-file verification.240 r.stage = "download"241 let store = ModelStore(root: ProjectPaths.models)242 let coordinator = DownloadCoordinator(store: store, transport: URLSessionDownloadTransport())243 // Files copied in beforehand (Scripts/verify-models.sh --prestage) are not fetched again: the coordinator finds them, hashes244 // each one against the Hub's SHA-256 and accepts or deletes it. Everything after this point is identical in both modes.245 let present = plan.files.allSatisfy { f in (try? store.fileURL(modelID: id, path: f.path)).flatMap(ModelStore.fileSize) == f.size }246 // build/transfer/<id> is written by the prefetch pass ("DownloadCoordinator") and by --prestage ("pre-staged").247 let marker = (try? String(contentsOf: ProjectPaths.root.appendingPathComponent("build/transfer/\(id)"), encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)248 r.transfer = !present ? "DownloadCoordinator" : (marker?.isEmpty == false ? marker : "already present")249 if present { log("files already on disk (\(r.transfer ?? "")): hashing only") }250 let started = Date()251 try await coordinator.start(plan)252 let progress = Task {253 while !Task.isCancelled {254 try? await Task.sleep(nanoseconds: 15_000_000_000)255 if let s = await coordinator.status(id: id), s.phase.isActive {256 log(String(format: "%.0f %% %.1f MB/s", s.fraction * 100, (s.bytesPerSecond ?? 0) / 1_048_576))257 }258 }259 }260 let status = await coordinator.waitUntilSettled(id: id)261 progress.cancel()262 guard let status, status.phase == .completed else {263 if case .failed(let e)? = status?.phase { throw e }264 throw AstraError.local("download ended in state \(String(describing: status?.phase))")265 }266 r.downloadSeconds = Date().timeIntervalSince(started); r.downloadRetries = status.retries267 let directory = try store.directory(for: id)268 // SHA-256 of every file, recomputed here from disk, independently of the coordinator's own record.269 var files: [LocalModelFile] = []270 for f in plan.files {271 let url = try store.fileURL(modelID: id, path: f.path)272 let hash = try FileDigest.sha256(of: url)273 guard hash == status.sha256[f.path] else { throw AstraError.local("hash of \(f.path) changed between download and re-read") }274 if let published = f.sha256, published != hash { throw AstraError.local("\(f.path) does not match the SHA-256 published by the Hub") }275 guard ModelStore.fileSize(url) == f.size else { throw AstraError.local("size of \(f.path) differs from the Hub's listing") }276 files.append(LocalModelFile(path: f.path, size: f.size, sha256: hash))277 }278 r.files = files; r.totalBytes = files.reduce(0) { $0 + $1.size }279280 // 3. What the repository actually is, read from its own files.281 r.stage = "inspect"282 if let data = try? Data(contentsOf: directory.appendingPathComponent("config.json")), let config = JSONValue.parse(data) {283 r.modelType = config["model_type"]?.stringValue284 r.quantizationBits = config["quantization"]?["bits"]?.intValue285 r.quantizationMode = config["quantization"]?["mode"]?.stringValue286 r.hasVision = config["vision_config"] != nil287 }288 r.contextLength = ModelConfigSummary.read(directory).contextLength289 r.licenseFiles = snapshot.files.map(\.path).filter { $0.lowercased().contains("license") || $0.lowercased().contains("notice") || $0.lowercased().contains("use_policy") }290 if let first = r.licenseFiles.first, let text = try? String(contentsOf: store.fileURL(modelID: id, path: first), encoding: .utf8) {291 r.licenseFileHead = String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(200))292 }293294 // 4. Load with the MLX runtime on this machine.295 r.stage = "load"296 var configuration = LocalEngine.Configuration(maxLoadedModels: 1); configuration.enforceMemoryVerdict = false297 let engine = LocalEngine(store: store, configuration: configuration)298 let info = try await engine.load(modelID: id, directory: directory)299 r.loadSeconds = info.loadTime; r.weightsMemoryBytes = info.weightsMemoryBytes; r.templateSupportsTools = info.templateSupportsTools300 log(String(format: "loaded in %.2f s, %@ of weights", info.loadTime, MemoryGovernor.format(info.weightsMemoryBytes ?? 0)))301 let ref = ModelRef(provider: .mlx, modelID: id)302 // A model that always thinks first needs room to finish thinking before it answers.303 // It is also sampled the way thinking models are meant to be (temperature 0.6, top-p 0.95): greedy decoding makes some of them loop.304 let always = info.thinkingBehavior == .alwaysOn305 let parameters = GenerationParameters(temperature: always ? CapabilityProber.thinkingTemperature : 0, topP: always ? CapabilityProber.thinkingTopP : nil,306 maxOutputTokens: always ? 1_500 : 96, seed: 11)307308 // 5. A real two-turn conversation on one KV-cache session.309 r.stage = "chat turn 1"310 let first = PromptMessage.user("My name is Sam and my favourite number is 42. Greet me by name in one short sentence.")311 let t1 = try await collect(engine, GenerationRequest(model: ref, messages: [first], parameters: parameters, sessionKey: "verify"))312 r.turn1 = t1313 guard !t1.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, (t1.completionTokens ?? 0) > 0, (t1.promptTokens ?? 0) > 0 else {314 throw AstraError.local("turn 1 produced no text or no measured token counts")315 }316 r.stage = "chat turn 2"317 let t2 = try await collect(engine, GenerationRequest(model: ref, messages: [first, .assistant(t1.text), .user("What is my favourite number? Answer with the number only.")],318 parameters: parameters, sessionKey: "verify"))319 r.turn2 = t2320 guard !t2.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, (t2.completionTokens ?? 0) > 0 else { throw AstraError.local("turn 2 produced no text") }321 guard (t2.cachedPromptTokens ?? 0) > 0 else { throw AstraError.local("turn 2 did not reuse the KV cache of turn 1") }322 r.recalledFact = t2.text.contains("42")323 log("turn 2: \(t2.text.prefix(60).replacingOccurrences(of: "\n", with: " ")) (cached \(t2.cachedPromptTokens ?? 0) prompt tokens)")324325 // 6. Cancel in the middle of a long answer.326 r.stage = "cancellation"327 var long = parameters; long.maxOutputTokens = 2_000328 let request = GenerationRequest(model: ref, messages: [.user("Write a detailed 600-word story about a lighthouse keeper.")], parameters: long)329 var chunks = 0; var cancelledAt: Date?; var sawCompleted = false; var endedCancelled = false330 do {331 for try await event in engine.generate(request) {332 if case .textDelta = event { chunks += 1 }333 if case .reasoningSummaryDelta = event { chunks += 1 }334 if case .messageCompleted = event { sawCompleted = true }335 if chunks >= 12, cancelledAt == nil { cancelledAt = Date(); Task { await engine.cancelActiveGeneration() } }336 }337 } catch { endedCancelled = (error as? AstraError) == .cancelled }338 guard let cancelledAt else { throw AstraError.local("the model stopped before the cancellation point (\(chunks) chunks)") }339 let stop = Date().timeIntervalSince(cancelledAt)340 r.cancellation = .init(chunksBeforeCancel: chunks, secondsToStop: stop, endedWithCancelledError: endedCancelled, completedEventSeen: sawCompleted)341 guard endedCancelled, !sawCompleted, stop < 3 else { throw AstraError.local("cancellation did not end the stream promptly with .cancelled (\(stop) s)") }342 guard engine.monitor.lastMetrics?.stopReason == .cancelled else { throw AstraError.local("cancelled generation was not recorded as cancelled") }343344 // 7. Unload, then load again from disk only: no network object exists in this path.345 r.stage = "reload from disk"346 await engine.unload(id)347 guard await engine.snapshot().loaded.isEmpty else { throw AstraError.local("the model stayed loaded after unload") }348 let again = try await engine.load(modelID: id, directory: directory)349 r.reloadSeconds = again.loadTime350 let t3 = try await collect(engine, GenerationRequest(model: ref, messages: [.user("Name the capital of France in one word.")], parameters: parameters))351 r.reloadAnswer = t3.text352 guard !t3.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw AstraError.local("no text after reloading from disk") }353354 // Probes (recorded, never decisive): thinking block, tool call, image input. Each runs only when the model declares the feature.355 r.stage = "probes"356 if ModelConfigSummary.read(directory).templateSupportsThinking {357 var p = parameters; p.maxOutputTokens = 300; p.reasoning = .medium358 let t = try? await collect(engine, GenerationRequest(model: ref, messages: [.user("What is 17 + 26? Think first.")], parameters: p))359 r.reasoningVerified = !(t?.reasoning.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)360 }361 if again.templateSupportsTools {362 let tool = ToolDefinition(name: "get_weather", summary: "Get the current weather for a city.",363 parameters: ["type": "object", "properties": ["city": ["type": "string", "description": "City name"]], "required": ["city"]])364 var p = parameters; p.maxOutputTokens = 200365 var called = false366 do {367 for try await event in engine.generate(GenerationRequest(model: ref, messages: [.user("What is the weather in Paris right now? Use the tool.")], parameters: p, tools: [tool])) {368 if case .toolCallCompleted(let call) = event, call.name == "get_weather" { called = true }369 }370 } catch {}371 r.toolCallVerified = called372 }373 if again.hasVision, let image = Self.redSquarePNG() {374 let t = try? await collect(engine, GenerationRequest(model: ref, messages: [.user("What colour fills this image? Answer with one word.", images: [ImageInput(data: image, mimeType: "image/png")])], parameters: parameters))375 r.visionAnswer = t?.text376 r.visionVerified = t?.text.lowercased().contains("red") ?? false377 }378379 // Capability probes: thinking on and off, cancellation while thinking, the coding prompt set, real image inference, JSON-only output.380 r.stage = "capability probes"381 r.capability = await CapabilityProber(engine: engine, id: id, info: again, log: log).run(directory: directory)382383 // 8. Measured speed: reload once more so the first benchmark sample is a true cold start.384 r.stage = "benchmark"385 var load = [Double](repeating: 0, count: 3)386 if getloadavg(&load, 3) > 0 { r.loadAverage = load[0] }387 await engine.unload(id)388 _ = try await engine.load(modelID: id, directory: directory)389 let benchmark = try await LocalBenchmark().run(modelID: id, engine: engine, revision: snapshot.revision)390 r.benchmark = benchmark391 r.tokensPerSecond = benchmark.warmDecodeTokensPerSecond; r.timeToFirstToken = benchmark.warmTimeToFirstToken392 r.coldTimeToFirstToken = benchmark.cold?.timeToFirstToken; r.peakMemoryBytes = benchmark.peakMemoryBytes393 guard let rate = r.tokensPerSecond, rate > 0, r.timeToFirstToken != nil else { throw AstraError.local("the benchmark produced no measured speed") }394 log(String(format: "%.1f tok/s warm, ttft %.3f s warm / %.3f s cold, peak %@", rate, r.timeToFirstToken ?? 0, r.coldTimeToFirstToken ?? 0,395 MemoryGovernor.format(r.peakMemoryBytes ?? 0)))396 await engine.unloadAll()397 }398}399400/// `ASTRA_VERIFY_REPO=mlx-community/<name> swift test --filter verifyOneModel` (driven by Scripts/verify-models.sh).401@Test(.enabled(if: ProjectPaths.env("ASTRA_VERIFY_REPO") != nil)) func verifyOneModel() async throws {402 let repo = try #require(ProjectPaths.env("ASTRA_VERIFY_REPO"))403 let result = await ModelVerifier(repo: repo).run()404 try FileManager.default.createDirectory(at: ProjectPaths.results, withIntermediateDirectories: true)405 let e = JSONEncoder(); e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]; e.dateEncodingStrategy = .iso8601406 try e.encode(result).write(to: ProjectPaths.results.appendingPathComponent(result.id + ".json"), options: .atomic)407 #expect(result.passed, "\(repo): \(result.failure ?? "")")408}409410/// Downloads several repositories at once through the DownloadCoordinator, without loading them: `ASTRA_PREFETCH_REPOS=a,b,c`.411/// The Hub limits each connection to about 2 MB/s after an initial burst, so fetching the candidates one after the other takes hours;412/// verification itself stays sequential and finds the files already verified on disk.413@Test(.enabled(if: ProjectPaths.env("ASTRA_PREFETCH_REPOS") != nil)) func prefetchModels() async throws {414 let repos = (ProjectPaths.env("ASTRA_PREFETCH_REPOS") ?? "").split(separator: ",").map(String.init)415 let store = ModelStore(root: ProjectPaths.models)416 let coordinator = DownloadCoordinator(store: store, transport: URLSessionDownloadTransport())417 let resolver = HuggingFaceResolver(transport: URLSessionTransport())418 var ids: [String] = []419 for repo in repos {420 let id = String(repo.split(separator: "/").last ?? "")421 do {422 let plan = try await resolver.snapshot(repo: repo).plan(id: id)423 // Remember that this run transferred the files itself, for the "transfer" field of the verification record.424 let present = plan.files.allSatisfy { f in (try? store.fileURL(modelID: id, path: f.path)).flatMap(ModelStore.fileSize) == f.size }425 if !present {426 let dir = ProjectPaths.root.appendingPathComponent("build/transfer", isDirectory: true)427 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)428 try? Data("DownloadCoordinator".utf8).write(to: dir.appendingPathComponent(id))429 }430 try await coordinator.start(plan); ids.append(id)431 }432 catch { FileHandle.standardError.write(Data("[prefetch] \(repo): \(error)\n".utf8)) }433 }434 let reporter = Task {435 while !Task.isCancelled {436 try? await Task.sleep(nanoseconds: 60_000_000_000)437 let line = await coordinator.statuses().map { String(format: "%@ %.0f%%", $0.id, $0.fraction * 100) }.joined(separator: " ")438 FileHandle.standardError.write(Data("[prefetch] \(line)\n".utf8))439 }440 }441 for id in ids {442 let status = await coordinator.waitUntilSettled(id: id)443 FileHandle.standardError.write(Data("[prefetch] \(id): \(String(describing: status?.phase)) retries \(status?.retries ?? 0)\n".utf8))444 #expect(status?.phase == .completed)445 }446 reporter.cancel()447}448