Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraLocalTests/RuntimeCapabilityProbes.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/// What was observed when a model's capabilities were exercised for real. Facts only: the verdict (verified / experimental) is94/// derived from these by `VerificationReport`, so it can be re-derived without running the model again.95struct CapabilityProbes: Codable {96 struct ReasoningRun: Codable {97 var thinkingRequested: Bool98 var reasoningCharacters: Int99 var reasoningTokens: Int?100 var completionTokens: Int?101 var reasoningPreview: String102 var answer: String103 var timeToFirstReasoningToken: Double?104 var timeToFirstAnswerToken: Double?105 /// A thinking marker reached the answer or the thinking text.106 var markersLeaked: Bool107 var stopReason: String108 var reasoningUnterminated: Bool?109 var thinkingApplied: Bool?110 var error: String?111 }112 struct ThinkingCancellation: Codable {113 var reasoningChunksBeforeCancel: Int114 var answerChunksBeforeCancel: Int115 var secondsToStop: Double116 var endedWithCancelledError: Bool117 var completedEventSeen: Bool118 var recordedAsCancelled: Bool119 var reasoningUnterminated: Bool?120 }121 struct Coding: Codable {122 var id: String123 var language: String124 var tokensPerSecond: Double?125 var outputTokens: Int?126 var hasFencedBlock: Bool127 var fencedBlockInRequestedLanguage: Bool128 var stopReason: String129 var preview: String130 }131 struct Vision: Codable {132 struct Shot: Codable { var answer: String?; var ok: Bool; var seconds: Double?; var promptTokens: Int?; var error: String? }133 var colour: Shot134 var chartNumber: Shot135 var textRead: Shot136 var description: Shot137 /// nil when the processor takes one image only.138 var multiImage: Shot?139 /// For single-image models: two images were refused with the typed error before reaching the model.140 var refusesTooManyImages: Bool?141 var maxImages: Int142 }143 struct JSONOnly: Codable { var raw: String; var strictlyValid: Bool; var validAfterRemovingFence: Bool; var hasExpectedKeys: Bool }144145 var family: String?146 var thinkingBehavior: String147 var tokenizerClass: String?148 var promptTemplate: String?149 var reasoningOn: ReasoningRun?150 var reasoningOff: ReasoningRun?151 var thinkingCancellation: ThinkingCancellation?152 /// Thinking cut by a small token limit.153 var reasoningCutByTokenLimit: ReasoningRun?154 var coding: [Coding] = []155 var vision: Vision?156 /// Text-only models: an image was refused with the typed error.157 var refusesImages: Bool?158 var jsonOnly: JSONOnly?159 /// Standard benchmark sets beyond "general" ("reasoning", "coding", "vision").160 var benchmarks: [String: LocalBenchmarkResult] = [:]161 var errors: [String] = []162}163164struct CapabilityProber {165 let engine: LocalEngine166 let id: String167 let info: LoadedModelInfo168 let log: (String) -> Void169 var ref: ModelRef { ModelRef(provider: .mlx, modelID: id) }170171 struct Collected { var text = ""; var reasoning = ""; var stop: StopReason?; var error: AstraError?; var metrics: LocalGenerationMetrics?; var seconds = 0.0 }172173 func collect(_ request: GenerationRequest) async -> Collected {174 var out = Collected(); let started = Date()175 do {176 for try await event in engine.generate(request) {177 switch event {178 case .textDelta(let t): out.text += t179 case .reasoningSummaryDelta(let t): out.reasoning += t180 case .messageCompleted(let r): out.stop = r181 default: break182 }183 }184 } catch { out.error = AstraError.wrapLocal(error) }185 out.seconds = Date().timeIntervalSince(started)186 out.metrics = engine.monitor.lastMetrics187 return out188 }189190 static func leaked(_ c: Collected) -> Bool { ["<think>", "</think>"].contains { c.text.contains($0) || c.reasoning.contains($0) } }191 static func clip(_ s: String, _ n: Int = 300) -> String { String(s.trimmingCharacters(in: .whitespacesAndNewlines).prefix(n)) }192193 /// Sampler for every run with thinking on: temperature 0.6, top-p 0.95, fixed seed. These families document that greedy decoding194 /// makes a thinking model repeat itself without end (observed here on Qwen3 1.7B and LFM2.5 Thinking at temperature 0).195 static let thinkingTemperature = 0.6, thinkingTopP = 0.95196197 func reasoningRun(_ prompt: String, thinking: Bool, maxTokens: Int) async -> CapabilityProbes.ReasoningRun {198 let p = GenerationParameters(temperature: thinking ? Self.thinkingTemperature : 0, topP: thinking ? Self.thinkingTopP : nil,199 maxOutputTokens: maxTokens, reasoning: thinking ? .medium : .off, seed: 11)200 let c = await collect(GenerationRequest(model: ref, messages: [.user(prompt)], parameters: p))201 return .init(thinkingRequested: thinking, reasoningCharacters: c.reasoning.count, reasoningTokens: c.metrics?.reasoningTokens, completionTokens: c.metrics?.completionTokens,202 reasoningPreview: Self.clip(c.reasoning, 240), answer: Self.clip(c.text, 400),203 timeToFirstReasoningToken: c.metrics?.timeToFirstReasoningToken, timeToFirstAnswerToken: c.metrics?.timeToFirstAnswerToken,204 markersLeaked: Self.leaked(c), stopReason: (c.stop ?? c.metrics?.stopReason ?? .unknown).rawValue,205 reasoningUnterminated: c.metrics?.reasoningUnterminated, thinkingApplied: c.metrics?.thinkingApplied, error: c.error?.message)206 }207208 func cancelDuringThinking() async -> CapabilityProbes.ThinkingCancellation {209 let p = GenerationParameters(temperature: Self.thinkingTemperature, topP: Self.thinkingTopP, maxOutputTokens: 2_000, reasoning: .high, seed: 11)210 let request = GenerationRequest(model: ref, messages: [.user("Think carefully and at length before answering: design a fair rota for five nurses over three shifts and seven days, where nobody works two nights in a row. Explain every constraint you check.")], parameters: p)211 var reasoningChunks = 0, answerChunks = 0, sawCompleted = false, endedCancelled = false; var cancelledAt: Date?212 do {213 for try await event in engine.generate(request) {214 if case .reasoningSummaryDelta = event, cancelledAt == nil { reasoningChunks += 1 }215 if case .textDelta = event, cancelledAt == nil { answerChunks += 1 }216 if case .messageCompleted = event { sawCompleted = true }217 if reasoningChunks == 15, cancelledAt == nil { cancelledAt = Date(); Task { [engine] in await engine.cancelActiveGeneration() } }218 }219 } catch { endedCancelled = (error as? AstraError) == .cancelled }220 let m = engine.monitor.lastMetrics221 return .init(reasoningChunksBeforeCancel: reasoningChunks, answerChunksBeforeCancel: answerChunks,222 secondsToStop: cancelledAt.map { Date().timeIntervalSince($0) } ?? -1, endedWithCancelledError: endedCancelled, completedEventSeen: sawCompleted,223 recordedAsCancelled: m?.stopReason == .cancelled, reasoningUnterminated: m?.reasoningUnterminated)224 }225226 func coding() async -> [CapabilityProbes.Coding] {227 var out: [CapabilityProbes.Coding] = []228 for prompt in LocalBenchmark.codingPrompts {229 let language = prompt.codeLanguage ?? ""230 // An always-thinking model needs room to finish thinking before it writes the code.231 let always = info.thinkingBehavior == .alwaysOn232 let p = GenerationParameters(temperature: always ? Self.thinkingTemperature : 0, topP: always ? Self.thinkingTopP : nil, maxOutputTokens: always ? 2_000 : 500, seed: 11)233 let c = await collect(GenerationRequest(model: ref, messages: [.user(prompt.text)], parameters: p))234 out.append(.init(id: prompt.id, language: language, tokensPerSecond: c.metrics?.decodeTokensPerSecond, outputTokens: c.metrics?.completionTokens,235 hasFencedBlock: LocalBenchmark.containsAnyFencedBlock(c.text), fencedBlockInRequestedLanguage: LocalBenchmark.containsFencedBlock(c.text, language: language),236 stopReason: (c.stop ?? .unknown).rawValue, preview: Self.clip(c.text, 200)))237 }238 return out239 }240241 func shot(_ text: String, _ images: [Data?], maxTokens: Int = 96, check: (String) -> Bool) async -> CapabilityProbes.Vision.Shot {242 let inputs = images.compactMap { $0 }.map { ImageInput(data: $0, mimeType: "image/png") }243 guard inputs.count == images.count else { return .init(answer: nil, ok: false, seconds: nil, promptTokens: nil, error: "the test image could not be drawn") }244 let c = await collect(GenerationRequest(model: ref, messages: [.user(text, images: inputs)], parameters: GenerationParameters(temperature: 0, maxOutputTokens: maxTokens, seed: 11)))245 return .init(answer: Self.clip(c.text, 300), ok: c.error == nil && check(c.text.lowercased()), seconds: c.seconds, promptTokens: c.metrics?.promptTokens, error: c.error?.message)246 }247248 func vision(_ limits: VisionLimits) async -> CapabilityProbes.Vision {249 let colour = await shot("What colour fills this image? Answer with one word.", [VisionTestImages.solid(VisionTestImages.red)]) { $0.contains("red") }250 let chart = await shot("This is a bar chart. What is the value written above bar C? Answer with the number.", [VisionTestImages.chart()]) { $0.contains("87") }251 let text = await shot("Read the text in this image and write it out exactly.", [VisionTestImages.textPage()], maxTokens: 120) { $0.contains("4812") && $0.contains("marigold") }252 let description = await shot("Describe this image in two sentences.", [VisionTestImages.chart()], maxTokens: 120) { $0.contains("chart") || $0.contains("graph") || $0.contains("bar") }253 var out = CapabilityProbes.Vision(colour: colour, chartNumber: chart, textRead: text, description: description, multiImage: nil, refusesTooManyImages: nil, maxImages: limits.maxImages)254 let two = [VisionTestImages.solid(VisionTestImages.red), VisionTestImages.solid(VisionTestImages.blue)]255 if limits.maxImages > 1 {256 out.multiImage = await shot("There are two images. What colour is the first image, and what colour is the second image?", two) { $0.contains("red") && $0.contains("blue") }257 } else {258 let refused = await shot("What colours are these two images?", two) { _ in false }259 out.refusesTooManyImages = refused.error?.contains("one image") == true260 }261 return out262 }263264 func jsonOnly() async -> CapabilityProbes.JSONOnly {265 let prompt = "Return only a JSON object with the keys \"name\" (string) and \"age\" (number) for this sentence: Alice is 30 years old. No other text, no code fence."266 let c = await collect(GenerationRequest(model: ref, messages: [.user(prompt)], parameters: GenerationParameters(temperature: info.thinkingBehavior == .alwaysOn ? Self.thinkingTemperature : 0, topP: info.thinkingBehavior == .alwaysOn ? Self.thinkingTopP : nil,267 maxOutputTokens: info.thinkingBehavior == .alwaysOn ? 1_200 : 120, seed: 11)))268 let raw = c.text.trimmingCharacters(in: .whitespacesAndNewlines)269 func object(_ s: String) -> [String: Any]? { (try? JSONSerialization.jsonObject(with: Data(s.utf8))) as? [String: Any] }270 var stripped = raw271 if stripped.hasPrefix("```") {272 stripped = stripped.split(separator: "\n", omittingEmptySubsequences: false).dropFirst().joined(separator: "\n")273 if let end = stripped.range(of: "```", options: .backwards) { stripped = String(stripped[..<end.lowerBound]) }274 stripped = stripped.trimmingCharacters(in: .whitespacesAndNewlines)275 }276 let parsed = object(raw) ?? object(stripped)277 return .init(raw: Self.clip(raw, 200), strictlyValid: object(raw) != nil, validAfterRemovingFence: object(stripped) != nil,278 hasExpectedKeys: (parsed?["name"] as? String)?.lowercased() == "alice" && (parsed?["age"] as? NSNumber)?.intValue == 30)279 }280281 static func describeTemplate(_ directory: URL) -> (tokenizer: String?, template: String?) {282 let summary = ModelConfigSummary.read(directory)283 let tokenizer = (try? Data(contentsOf: directory.appendingPathComponent("tokenizer_config.json"))).flatMap { JSONValue.parse($0) }?["tokenizer_class"]?.stringValue284 guard let t = summary.template else { return (tokenizer, nil) }285 let name: String286 if t.contains("<|Assistant|>") { name = "deepseek" }287 else if t.contains("<|im_start|>") && t.contains("<end_of_utterance>") { name = "smolvlm" }288 else if t.contains("<|im_start|>") { name = "chatml" }289 else if t.contains("<start_of_turn>") { name = "gemma" }290 else if t.contains("<|start_header_id|>") { name = "llama3" }291 else if t.contains("<|assistant|>") { name = "phi" }292 else { name = "custom" }293 return (tokenizer, name)294 }295296 func run(directory: URL) async -> CapabilityProbes {297 let behavior = info.thinkingBehavior ?? .none298 let described = Self.describeTemplate(directory)299 var probes = CapabilityProbes(family: info.family, thinkingBehavior: behavior.rawValue, tokenizerClass: described.tokenizer, promptTemplate: described.template)300 if behavior.supported {301 let question = "What is 17 + 26? Think step by step, then give the number."302 probes.reasoningOn = await reasoningRun(question, thinking: true, maxTokens: 1_500)303 log("thinking on: \(probes.reasoningOn?.reasoningCharacters ?? 0) chars of reasoning (\(probes.reasoningOn?.reasoningTokens ?? 0) tokens), answer “\(Self.clip(probes.reasoningOn?.answer ?? "", 60))”")304 if behavior == .toggleable {305 probes.reasoningOff = await reasoningRun(question, thinking: false, maxTokens: 300)306 log("thinking off: \(probes.reasoningOff?.reasoningCharacters ?? 0) chars of reasoning, answer “\(Self.clip(probes.reasoningOff?.answer ?? "", 60))”")307 }308 probes.thinkingCancellation = await cancelDuringThinking()309 log(String(format: "cancel during thinking: stopped in %.2f s, cancelled error %@", probes.thinkingCancellation?.secondsToStop ?? -1, String(probes.thinkingCancellation?.endedWithCancelledError ?? false)))310 probes.reasoningCutByTokenLimit = await reasoningRun("Explain, reasoning carefully, why the sum of two odd numbers is always even.", thinking: true, maxTokens: 24)311 }312 probes.coding = await coding()313 log("coding: " + probes.coding.map { "\($0.id) fence=\($0.fencedBlockInRequestedLanguage)" }.joined(separator: ", "))314 if info.hasVision, let limits = info.vision {315 let v = await vision(limits)316 probes.vision = v317 log("vision: colour=\(v.colour.ok) chart=\(v.chartNumber.ok) text=\(v.textRead.ok) describe=\(v.description.ok) multi=\(v.multiImage.map { String($0.ok) } ?? "n/a")")318 } else {319 let refused = await shot("What is this?", [VisionTestImages.solid(VisionTestImages.red)]) { _ in false }320 probes.refusesImages = refused.error?.contains("cannot read images") == true321 }322 probes.jsonOnly = await jsonOnly()323 var sets: [LocalBenchmark.PromptSet] = [.coding]324 if behavior.supported { sets.append(.reasoning) }325 if info.hasVision { sets.append(.vision) }326 for set in sets {327 do { probes.benchmarks[set.rawValue] = try await LocalBenchmark(set: set).run(modelID: id, engine: engine, revision: info.revision) }328 catch { probes.errors.append("benchmark \(set.rawValue): \(AstraError.wrapLocal(error).message)") }329 }330 return probes331 }332}333