Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocLocalModelsTests/LiveLocalModelTests.swift10// Description : Real on-device runs through `LocalModelLibrary`, skipped11// unless asked for. ORIXDOCS_MLX_LIVE=1 : downloads a12// catalogued model (ORIXDOCS_MLX_MODEL, default13// Qwen3-0.6B-4bit) from the real sources into14// ORIXDOCS_MLX_DIR, verifies every SHA-256, loads it with15// MLX, generates with streaming, cancels a generation16// midway, unloads, and writes the measured figures to17// ORIXDOCS_MLX_REPORT (JSON). ORIXDOCS_APPLE_FM_LIVE=1 : one18// streamed answer from Apple Intelligence through the hub,19// when the system model is available. Run with20// Scripts/ai-live-smoke.sh.21// Module : DocLocalModelsTests22// Repository : https://git.spboucher.ai/orix-docs23// Created : 2026-11-2224// Last Modified : 2026-11-2225//26// =============================================================================27// AUTHOR & PROFESSIONAL AFFILIATION28// =============================================================================29//30// Author : Simon-Pierre Boucher31// Position : Professor of Finance32// Institution : Université du Québec en Outaouais (UQO)33// Department : Département des sciences administratives34// Organization : SP Boucher35//36// Website : https://spboucher.ai37// Git : https://git.spboucher.ai38//39// =============================================================================40// OFFICIAL CONTACT DIRECTORY41// =============================================================================42//43// General : info@spboucher.ai44// Professional : contact@spboucher.ai45// Direct : simon@spboucher.ai46// Research : research@spboucher.ai47// Development : dev@spboucher.ai48// Support : support@spboucher.ai49// Security/Admin : admin@spboucher.ai50// Notifications : notifications@spboucher.ai51//52// Preferred Contact: support@spboucher.ai53//54// =============================================================================55// COPYRIGHT & INTELLECTUAL PROPERTY56// =============================================================================57//58// Copyright (c) 202659// Simon-Pierre Boucher60//61// All rights reserved where applicable.62//63// This file is governed by the applicable project license,64// copyright notices, institutional agreements and relevant law.65//66// Unless expressly authorized by the applicable license or67// rights holder, copying, redistribution, sublicensing,68// publication and commercial exploitation are not permitted.69//70// Existing third-party rights and notices remain unaffected.71//72// =============================================================================73// CONFIDENTIALITY & SECURITY74// =============================================================================75//76// Classification : Public77// Distribution : Public repository; use is governed by the project license78// Security Contact : admin@spboucher.ai79//80// Access to this source does not independently grant permission81// to redistribute or disclose confidential materials.82//83// Do not embed credentials, private keys, access tokens,84// certificates or confidential personal information.85//86// =============================================================================87// LICENSE & MAINTENANCE88// =============================================================================89//90// License : None specified (no license file in this repository)91// Maintainer : Simon-Pierre Boucher92// Technical Contact: dev@spboucher.ai93//94// =============================================================================95// END OF SP BOUCHER SOURCE HEADER96// =============================================================================9798import AstraCore99@testable import AstraLocal100import DocAI101@testable import DocLocalModels102import Foundation103import Testing104105enum LiveLocal {106 static let env = ProcessInfo.processInfo.environment107 static let mlx = env["ORIXDOCS_MLX_LIVE"] == "1" && !(env["ORIXDOCS_MLX_DIR"] ?? "").isEmpty108 static let apple = env["ORIXDOCS_APPLE_FM_LIVE"] == "1"109 static let modelID = env["ORIXDOCS_MLX_MODEL"].flatMap { $0.isEmpty ? nil : $0 } ?? "Qwen3-0.6B-4bit"110111 struct Report: Codable {112 var date: String; var build: String; var machine: String; var osVersion: String; var physicalMemoryGB: Double113 var modelID: String; var repo: String; var revision: String114 var catalogSource: String; var catalogModels: Int115 var downloadBytes: Int64; var downloadSeconds: Double; var downloadMBPerSecond: Double; var downloadedFrom: String; var alreadyInstalled: Bool116 var filesVerified: Int; var verifySeconds: Double; var installedIntact: Bool117 var governorVerdict: String; var estimatedNeedBytes: Int64; var modelBudgetBytes: Int64118 var loadSeconds: Double; var weightsMemoryBytes: Int64?119 var promptTokens: Int?; var completionTokens: Int?; var timeToFirstToken: Double?; var decodeTokensPerSecond: Double?; var promptTokensPerSecond: Double?120 var totalSeconds: Double; var peakMemoryBytes: Int64?; var answerPreview: String; var streamedChunks: Int121 var warmTimeToFirstToken: Double?; var warmDecodeTokensPerSecond: Double?; var warmCompletionTokens: Int?122 var longCompletionTokens: Int?; var longDecodeTokensPerSecond: Double?; var longSeconds: Double; var longPeakMemoryBytes: Int64?123 var availableMemoryBytes: Int64?124 var cancelChunksBeforeCancel: Int; var cancelSecondsToStop: Double; var cancelEndedWithCancelledError: Bool; var cancelCompletedEventSeen: Bool125 var worksAfterCancel: Bool; var unloaded: Bool126 }127}128129@Suite("Live on-device models", .serialized)130struct LiveLocalModelTests {131 @Test(.enabled(if: LiveLocal.mlx), .timeLimit(.minutes(30)))132 func downloadVerifyLoadGenerateCancelUnload() async throws {133 let root = URL(fileURLWithPath: try #require(LiveLocal.env["ORIXDOCS_MLX_DIR"]), isDirectory: true)134 let library = try LocalModelLibrary(configuration: .init(root: root.appendingPathComponent("Models", isDirectory: true)))135 let device = library.device136 let id = LiveLocal.modelID137138 // Catalogue: the built-in copy, refreshed from www.orixlab.dev.139 let refresh = await library.refreshCatalog()140 let entry = try #require(await library.entry(id: id), "\(id) is not in the catalogue")141 print("MLX catalogue: \(refresh.modelCount) models, online refresh \(refresh.failure.map { "failed (\($0.title))" } ?? "ok"), rejected \(refresh.rejected.count)")142143 // Download with progress, from the real sources.144 let alreadyInstalled = entry.isInstalled145 let downloadStart = Date()146 var usedFallback = false147 if !alreadyInstalled {148 try await library.download(id)149 let progress = Task {150 var last = -1151 for await statuses in await library.downloadUpdates() {152 guard let s = statuses.first(where: { $0.id == id }) else { continue }153 let percent = Int(s.fraction * 10) * 10154 if percent != last { last = percent; print("MLX download \(percent)% \(s.bytesPerSecond.map { String(format: "%.1f MB/s", $0 / 1_048_576) } ?? "")") }155 if !s.phase.isActive { break }156 }157 }158 let final = try #require(await library.waitForDownload(id))159 progress.cancel()160 #expect(final.phase == .completed, "download ended as \(final.phase)")161 guard final.phase == .completed else { return }162 usedFallback = final.usedFallback163 for file in entry.card.files { #expect(final.sha256[file.path] == file.sha256, "\(file.path) checksum") }164 }165 let downloadSeconds = Date().timeIntervalSince(downloadStart)166167 // Independent re-hash of the installed files.168 let verifyStart = Date()169 let check = await library.verifyInstalled(id)170 let verifySeconds = Date().timeIntervalSince(verifyStart)171 #expect(check.isIntact, "\(check.summary)")172 #expect(check.bytesChecked == entry.card.totalBytes)173174 // Memory governor, then load.175 let decision = await library.governor.decision(for: entry.card)176 #expect(decision.mayLoadNow, "\(decision.reason)")177 let loadStart = Date()178 let info = try await library.load(id)179 let loadSeconds = Date().timeIntervalSince(loadStart)180181 // Streaming generation (cold), then a second one (warm).182 func run(_ prompt: String, maxTokens: Int) async throws -> (text: String, chunks: Int, metrics: LocalGenerationMetrics?) {183 var text = "", chunks = 0184 let request = GenerationRequest(model: ModelRef(provider: .mlx, modelID: id), system: "You are a concise writing assistant.", messages: [.user(prompt)],185 parameters: GenerationParameters(temperature: 0, maxOutputTokens: maxTokens, reasoning: .off))186 for try await event in library.generate(request) { if case .textDelta(let t) = event { text += t; chunks += 1 } }187 return (text, chunks, library.generationMetrics.last)188 }189 let coldStart = Date()190 let cold = try await run("Write three sentences about why clear paragraphs help readers.", maxTokens: 200)191 let coldSeconds = Date().timeIntervalSince(coldStart)192 #expect(!cold.text.isEmpty && cold.chunks > 1)193 let coldMetrics = try #require(cold.metrics)194 #expect((coldMetrics.decodeTokensPerSecond ?? 0) > 0)195 let warm = try await run("Rewrite in plain words: The aforementioned document shall be remitted forthwith.", maxTokens: 200)196 #expect(!warm.text.isEmpty)197 // A longer answer: the steadier throughput figure.198 let longStart = Date()199 let long = try await run("Write a detailed essay of about 400 words on the history of the printing press.", maxTokens: 500)200 let longSeconds = Date().timeIntervalSince(longStart)201 #expect((long.metrics?.completionTokens ?? 0) > 100)202203 // Cancellation in the middle of a long generation.204 let cancelRequest = GenerationRequest(model: ModelRef(provider: .mlx, modelID: id), messages: [.user("Count from 1 to 500, one number per line.")],205 parameters: GenerationParameters(temperature: 0, maxOutputTokens: 2_000, reasoning: .off))206 let cancelTask = Task { () -> (chunks: Int, cancelledAt: Date?, cancelledError: Bool, completed: Bool) in207 var chunks = 0, cancelledAt: Date?, completed = false208 do {209 for try await event in library.generate(cancelRequest) {210 if case .textDelta = event { chunks += 1; if chunks == 20 { cancelledAt = Date(); withUnsafeCurrentTask { $0?.cancel() } } }211 if case .messageCompleted = event { completed = true }212 }213 } catch { return (chunks, cancelledAt, AstraError.wrap(error) == .cancelled, completed) }214 return (chunks, cancelledAt, false, completed)215 }216 let cancelled = await cancelTask.value217 await library.cancelGeneration() // returns when the engine has really stopped218 let secondsToStop = cancelled.cancelledAt.map { Date().timeIntervalSince($0) } ?? -1219 #expect(cancelled.chunks >= 20 && cancelled.chunks < 400, "the generation was not cut short (\(cancelled.chunks) chunks)")220 #expect(!cancelled.completed)221 #expect(secondsToStop >= 0 && secondsToStop < 5)222 #expect(await library.engine.snapshot().active == nil)223 // The engine still answers after a cancellation.224 let after = try await run("Say hello in five words.", maxTokens: 40)225 #expect(!after.text.isEmpty)226227 // Unload.228 await library.unload(id)229 #expect(await library.loadedModels().isEmpty)230231 let report = LiveLocal.Report(232 date: ISO8601DateFormatter().string(from: Date()), build: LiveLocal.env["ORIXDOCS_MLX_BUILD"] ?? "unknown", machine: device.modelIdentifier, osVersion: device.osVersion,233 physicalMemoryGB: Double(device.physicalMemoryBytes) / 1_073_741_824, modelID: id, repo: entry.card.repo, revision: entry.card.revision,234 catalogSource: refresh.failure == nil ? "bundled + www.orixlab.dev" : "bundled only", catalogModels: refresh.modelCount,235 downloadBytes: entry.card.totalBytes, downloadSeconds: alreadyInstalled ? 0 : downloadSeconds,236 downloadMBPerSecond: alreadyInstalled || downloadSeconds <= 0 ? 0 : Double(entry.card.totalBytes) / 1_048_576 / downloadSeconds,237 downloadedFrom: alreadyInstalled ? "already installed" : (usedFallback ? "mirror and/or Hugging Face fallback" : (entry.card.sourceURLs.first?.host ?? "?")),238 alreadyInstalled: alreadyInstalled, filesVerified: entry.card.files.count, verifySeconds: verifySeconds, installedIntact: check.isIntact,239 governorVerdict: decision.verdict.rawValue, estimatedNeedBytes: decision.fit.estimatedNeedBytes, modelBudgetBytes: decision.budgetBytes,240 loadSeconds: loadSeconds, weightsMemoryBytes: info.weightsMemoryBytes,241 promptTokens: coldMetrics.promptTokens, completionTokens: coldMetrics.completionTokens, timeToFirstToken: coldMetrics.timeToFirstToken,242 decodeTokensPerSecond: coldMetrics.decodeTokensPerSecond, promptTokensPerSecond: coldMetrics.promptTokensPerSecond, totalSeconds: coldSeconds,243 peakMemoryBytes: coldMetrics.peakMemoryBytes, answerPreview: String(cold.text.prefix(160)), streamedChunks: cold.chunks,244 warmTimeToFirstToken: warm.metrics?.timeToFirstToken, warmDecodeTokensPerSecond: warm.metrics?.decodeTokensPerSecond, warmCompletionTokens: warm.metrics?.completionTokens,245 longCompletionTokens: long.metrics?.completionTokens, longDecodeTokensPerSecond: long.metrics?.decodeTokensPerSecond, longSeconds: longSeconds,246 longPeakMemoryBytes: long.metrics?.peakMemoryBytes, availableMemoryBytes: EditorMemoryGovernor.systemReading().availableBytes,247 cancelChunksBeforeCancel: cancelled.chunks, cancelSecondsToStop: secondsToStop, cancelEndedWithCancelledError: cancelled.cancelledError,248 cancelCompletedEventSeen: cancelled.completed, worksAfterCancel: !after.text.isEmpty, unloaded: true)249 let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]250 let data = try encoder.encode(report)251 if let path = LiveLocal.env["ORIXDOCS_MLX_REPORT"], !path.isEmpty { try data.write(to: URL(fileURLWithPath: path), options: .atomic) }252 print("MLX REPORT " + String(decoding: data, as: UTF8.self))253 }254255 @Test(.enabled(if: LiveLocal.apple), .timeLimit(.minutes(5)))256 func appleIntelligenceStreamsThroughTheHub() async throws {257 let availability = OnDeviceProviders.appleIntelligenceAvailability258 print("APPLE availability: \(availability) \(availability.reason ?? "")")259 let hub = ProviderHub(configuration: .init(credentials: InMemoryCredentialStore(), storageDirectory: nil))260 await OnDeviceProviders.register(in: hub, library: nil)261 let row = try await hub.provider(ProviderID(.appleFoundation))262 print("APPLE hub state: \(row.state.rawValue) models=\(row.modelCount ?? -1) detail=\(row.detail ?? "")")263 guard availability.isAvailable else {264 // Not available on this Mac right now: the hub must say so and must not answer.265 #expect(row.state == .unavailable)266 let refused = await hub.generate(GenerationRequest(model: AppleFoundationProvider.modelRef, messages: [.user("Hello")]))267 #expect(refused.error != nil && refused.text.isEmpty)268 return269 }270 #expect(row.state == .verified)271 let capabilities = try #require(await OnDeviceProviders.appleIntelligenceCapabilities())272 print("APPLE capabilities: context=\(capabilities.contextLength ?? -1) tools=\(capabilities.toolCalling) vision=\(capabilities.vision) source=\(capabilities.sourceLabel)")273 #expect(!capabilities.toolCalling && !capabilities.vision)274 var chunks = 0275 var outcome = GenerationOutcome()276 let request = GenerationRequest(model: AppleFoundationProvider.modelRef, system: "You are a concise writing assistant.",277 messages: [.user("Rewrite in plain words, one sentence: The aforementioned document shall be remitted forthwith.")],278 parameters: GenerationParameters(maxOutputTokens: 120))279 for await event in hub.stream(request) { if case .textDelta = event { chunks += 1 }; outcome.apply(event) }280 print("APPLE answer: chunks=\(chunks) stop=\(outcome.stopReason.rawValue) in=\(outcome.usage?.inputTokens ?? -1) out=\(outcome.usage?.outputTokens ?? -1) "281 + "ttft=\(outcome.timing.timeToFirstToken.map { String(format: "%.2fs", $0) } ?? "-") total=\(outcome.timing.totalTime.map { String(format: "%.2fs", $0) } ?? "-") "282 + "error=\(outcome.error?.title ?? "none") text=\(outcome.text.prefix(120))")283 #expect(outcome.error == nil, "\(outcome.error?.message ?? "")")284 #expect(!outcome.text.isEmpty && outcome.stopReason == .endOfTurn)285 #expect(await hub.usageSnapshot().total.onDeviceRequests == 1)286 }287}288