Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraLocalTests/RuntimeMLXTests.swift10// Module : AstraLocalTests11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2213// 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 Foundation90import Testing91@testable import AstraLocal9293/// Real inference for the reasoning, vision and lifecycle paths. Enabled with `ASTRA_MLX_TESTS=1`; each test needs its model in94/// build/models (downloaded by Scripts/verify-models.sh) and is skipped when the directory is absent.95enum RuntimeMLXModels {96 static let on = ProjectPaths.env("ASTRA_MLX_TESTS") == "1"97 static func directory(_ name: String) -> URL { ProjectPaths.models.appendingPathComponent(name) }98 static func has(_ name: String) -> Bool { on && FileManager.default.fileExists(atPath: directory(name).appendingPathComponent("config.json").path) }99 static let qwen3 = "Qwen3-0.6B-4bit"100 /// The thinking test uses the 1.7B model: the 0.6B one often thinks past any reasonable token limit.101 static let qwen3Thinking = "Qwen3-1.7B-4bit"102 static let smolLM3 = "SmolLM3-3B-4bit"103 static let deepSeek = "DeepSeek-R1-Distill-Qwen-1.5B-4bit"104 static let smolVLM = "SmolVLM2-256M-Video-Instruct-mlx"105 static let small = "SmolLM2-135M-Instruct-8bit"106}107108@Suite(.enabled(if: RuntimeMLXModels.on), .serialized) struct RuntimeMLXTests {109 struct Turn { var text = ""; var reasoning = ""; var stop: StopReason?; var error: AstraError?; var metrics: LocalGenerationMetrics? }110111 private func engine(maxLoaded: Int = 1) -> LocalEngine {112 var configuration = LocalEngine.Configuration(maxLoadedModels: maxLoaded); configuration.enforceMemoryVerdict = false113 return LocalEngine(store: ModelStore(root: ProjectPaths.models), configuration: configuration)114 }115116 private func ask(_ engine: LocalEngine, _ id: String, _ text: String, images: [ImageInput] = [], reasoning: ReasoningEffort? = nil, maxTokens: Int = 200) async -> Turn {117 // Thinking runs are sampled: greedy decoding makes small thinking models repeat themselves until the token limit.118 let thinks = (reasoning ?? .off) != .off119 let request = GenerationRequest(model: ModelRef(provider: .mlx, modelID: id), messages: [.user(text, images: images)],120 parameters: GenerationParameters(temperature: thinks ? 0.6 : 0, topP: thinks ? 0.95 : nil, maxOutputTokens: maxTokens, reasoning: reasoning, seed: 11))121 var turn = Turn()122 do {123 for try await event in engine.generate(request) {124 switch event {125 case .textDelta(let t): turn.text += t126 case .reasoningSummaryDelta(let t): turn.reasoning += t127 case .messageCompleted(let r): turn.stop = r128 default: break129 }130 }131 } catch { turn.error = AstraError.wrapLocal(error) }132 turn.metrics = engine.monitor.lastMetrics133 return turn134 }135136 private func noMarkers(_ turn: Turn) -> Bool { !["<think>", "</think>"].contains { turn.text.contains($0) || turn.reasoning.contains($0) } }137138 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.qwen3Thinking))) func aToggleableModelThinksOnlyWhenAsked() async throws {139 let engine = engine(), id = RuntimeMLXModels.qwen3Thinking140 let info = try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))141 #expect(info.thinkingBehavior == .toggleable && info.thinking == ThinkingSupport(supported: true, toggleable: true, defaultOn: false))142 #expect(info.capabilities.contains(.reasoning) && info.family == "qwen3" && info.quantization == "4-bit")143144 let on = await ask(engine, id, "What is 17 + 26? Think step by step, then give the number.", reasoning: .medium, maxTokens: 1_500)145 #expect(on.error == nil && !on.reasoning.isEmpty && on.text.contains("43") && noMarkers(on))146 let m = try #require(on.metrics)147 #expect((m.reasoningTokens ?? 0) > 0 && m.thinkingRequested == true && m.thinkingApplied == true && m.reasoningUnterminated == false)148 let first = try #require(m.timeToFirstReasoningToken), answer = try #require(m.timeToFirstAnswerToken)149 #expect(first < answer, "thinking starts before the answer")150151 let off = await ask(engine, id, "What is 12 + 30? Answer with the number.", reasoning: .off)152 #expect(off.error == nil && off.reasoning.isEmpty && off.text.contains("42") && noMarkers(off))153 #expect(off.metrics?.timeToFirstReasoningToken == nil && off.metrics?.thinkingApplied == false && off.metrics?.reasoningUnterminated == nil)154155 // A token limit inside the thinking block: thinking, no answer, flagged.156 let cut = await ask(engine, id, "Explain carefully why the sum of two odd numbers is even.", reasoning: .medium, maxTokens: 20)157 #expect(cut.stop == .maxTokens && cut.text.isEmpty && !cut.reasoning.isEmpty && cut.metrics?.reasoningUnterminated == true && noMarkers(cut))158 await engine.unloadAll()159 }160161 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.smolLM3))) func aModelTheRuntimeDoesNotSeparateIsSeparatedByTheParser() async throws {162 let engine = engine(), id = RuntimeMLXModels.smolLM3163 let info = try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))164 #expect(info.thinkingBehavior == .toggleable && info.family == "smollm3")165 let on = await ask(engine, id, "What is 12 + 30? Think, then answer with the number.", reasoning: .medium, maxTokens: 1_500)166 #expect(on.error == nil && !on.reasoning.isEmpty && !on.text.isEmpty && noMarkers(on))167 #expect((on.metrics?.reasoningTokens ?? 0) > 0 && (on.metrics?.answerTokens ?? 0) > 0)168 let off = await ask(engine, id, "What is 12 + 30? Answer with the number.", reasoning: .off)169 #expect(off.reasoning.isEmpty && off.text.contains("42") && noMarkers(off))170 await engine.unloadAll()171 }172173 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.deepSeek))) func anAlwaysThinkingModelIgnoresTheSwitchAndSaysSo() async throws {174 let engine = engine(), id = RuntimeMLXModels.deepSeek175 let info = try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))176 #expect(info.thinkingBehavior == .alwaysOn && info.thinking == ThinkingSupport(supported: true, toggleable: false, defaultOn: true))177 let turn = await ask(engine, id, "What is 12 + 30?", reasoning: .off, maxTokens: 1_500)178 #expect(turn.error == nil && !turn.reasoning.isEmpty && noMarkers(turn))179 #expect(turn.metrics?.thinkingRequested == false && turn.metrics?.thinkingApplied == true)180 await engine.unloadAll()181 }182183 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.smolVLM))) func aVisionModelReadsARealImageAndRefusesTwo() async throws {184 let engine = engine(), id = RuntimeMLXModels.smolVLM185 let info = try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))186 #expect(info.hasVision && info.maxImages == 1 && info.capabilities.contains(.vision))187 let red = ImageInput(data: try #require(VisionTestImages.solid(VisionTestImages.red)), mimeType: "image/png")188 let blue = ImageInput(data: try #require(VisionTestImages.solid(VisionTestImages.blue)), mimeType: "image/png")189 let turn = await ask(engine, id, "What colour fills this image? Answer with one word.", images: [red], maxTokens: 40)190 #expect(turn.error == nil && turn.text.lowercased().contains("red") && turn.metrics?.imageCount == 1)191 let two = await ask(engine, id, "What colours?", images: [red, blue], maxTokens: 40)192 #expect(two.error == VisionInputError.tooManyImages(sent: 2, limit: 1, modelID: id).astraError && two.text.isEmpty)193 let bad = await ask(engine, id, "What is this?", images: [ImageInput(data: Data("nope".utf8))], maxTokens: 40)194 #expect(bad.error == .invalidRequest("Image 1 could not be decoded."))195 // The engine is still usable after the refusals.196 #expect(await ask(engine, id, "Say hello.", maxTokens: 20).error == nil)197 await engine.unloadAll()198 }199200 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.small))) func aTextOnlyModelRefusesAnImageWithTheTypedError() async throws {201 let engine = engine(), id = RuntimeMLXModels.small202 try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))203 let red = ImageInput(data: try #require(VisionTestImages.solid(VisionTestImages.red)), mimeType: "image/png")204 let turn = await ask(engine, id, "What colour?", images: [red], maxTokens: 20)205 #expect(turn.error == VisionInputError.modelCannotReadImages(modelID: id).astraError && turn.text.isEmpty)206 await engine.unloadAll()207 }208209 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.small) && RuntimeMLXModels.has(RuntimeMLXModels.qwen3))) func switchingBetweenRealModelsLeavesOneLoaded() async throws {210 let engine = engine()211 try await engine.load(modelID: RuntimeMLXModels.small, directory: RuntimeMLXModels.directory(RuntimeMLXModels.small))212 #expect(await ask(engine, RuntimeMLXModels.small, "Say hello.", maxTokens: 20).error == nil)213 // The second model is not installed through the store here, so the switch is done with an explicit unload-then-load; the214 // engine's own limit of one model enforces the same rule.215 try await engine.load(modelID: RuntimeMLXModels.qwen3, directory: RuntimeMLXModels.directory(RuntimeMLXModels.qwen3))216 let snapshot = await engine.snapshot()217 #expect(snapshot.models.map(\.id) == [RuntimeMLXModels.qwen3] && snapshot.phase == .idle)218 #expect(await ask(engine, RuntimeMLXModels.qwen3, "Say hello.", maxTokens: 20).error == nil)219 let released = await engine.releaseUnusedResources(keepSessions: false)220 #expect(released.unloadedModels.isEmpty && released.sessionsReset == [RuntimeMLXModels.qwen3])221 await engine.unloadAll()222 #expect(await engine.snapshot().models.isEmpty)223 }224225 @Test(.enabled(if: RuntimeMLXModels.has(RuntimeMLXModels.qwen3))) func theStandardSetsProduceMeasuredResults() async throws {226 let engine = engine(), id = RuntimeMLXModels.qwen3227 try await engine.load(modelID: id, directory: RuntimeMLXModels.directory(id))228 let coding = try await LocalBenchmark(set: .coding, maxOutputTokens: 120).run(modelID: id, engine: engine)229 #expect(coding.promptSet == "coding" && coding.samples.count == 3 && coding.measuredOn == DeviceFacts.current().modelIdentifier)230 #expect(coding.samples.allSatisfy { ($0.decodeTokensPerSecond ?? 0) > 0 && ($0.outputTokens ?? 0) > 0 } && (coding.tokensGenerated ?? 0) > 0)231 #expect(coding.quantization == "4-bit" && coding.architecture == "qwen3" && coding.contextLength == 40_960 && (coding.totalTime ?? 0) > 0)232 let reasoning = try await LocalBenchmark(set: .reasoning, maxOutputTokens: 200).run(modelID: id, engine: engine)233 #expect(reasoning.samples.contains { ($0.reasoningTokens ?? 0) > 0 })234 await engine.unloadAll()235 }236}237