Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraLocalTests/CompatibilityTests.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@Suite struct CompatibilityEngineTests {94 static func assess(_ card: LocalModelCard, gb: Double, availableGB: Double? = nil, thermal: ThermalLevel = .nominal, context: Int? = nil,95 measured: [ModelMeasurement] = [], model: String = "iPhone18,2") -> CompatibilityReport {96 let d = FakeDevice.iPhone(gb, availableGB: availableGB, model: model)97 return CompatibilityEngine.assess(card: card, context: context, device: d.device, memory: d.memory, thermal: thermal, measured: measured)98 }99 static func rank(_ c: CompatibilityClass) -> Int {100 switch c { case .unsupported: 0; case .memoryIntensive: 1; case .experimental: 1; case .compatible: 2; case .excellentFit: 3 }101 }102103 @Test func classesAndTitles() {104 #expect(CompatibilityClass.allCases.map(\.rawValue) == ["excellentFit", "compatible", "memoryIntensive", "experimental", "unsupported"])105 #expect(CompatibilityClass.allCases.map(\.title) == ["Excellent Fit", "Compatible", "Memory Intensive", "Experimental", "Unsupported"])106 #expect(CompatibilityBasis.allCases.map(\.rawValue) == ["measuredOnThisDevice", "measuredElsewhere", "estimated"])107 }108109 @Test func deviceMatrixForASmallAMediumAndALargeModel() throws {110 let small = try RecordedFixture.card("Qwen3-0.6B-4bit"), medium = try RecordedFixture.card("Qwen3-1.7B-4bit"), large = try RecordedFixture.card("Qwen3-4B-4bit")111 // 0.6 B at 4-bit (0.33 GB of weights): comfortable on every iPhone size.112 for gb in FakeDevice.sizes { #expect(Self.assess(small, gb: gb).compatibility == .excellentFit, "0.6B on \(gb) GB") }113 // 4 B at 4-bit (2.1 GB of weights, catalogue minimum 8 GB): out of reach on 4 GB, tight in the middle, at ease on 16 GB.114 let classes = FakeDevice.sizes.map { Self.assess(large, gb: $0).compatibility }115 #expect(classes[0] == .unsupported)116 #expect(classes[2] == .memoryIntensive)117 #expect(classes[4] == .compatible)118 #expect(classes.map(Self.rank) == classes.map(Self.rank).sorted(), "more memory never makes the class worse: \(classes)")119 // 1.7 B: never unsupported, never worse with more memory, excellent on the largest.120 let mid = FakeDevice.sizes.map { Self.assess(medium, gb: $0).compatibility }121 #expect(!mid.contains(.unsupported) && mid.map(Self.rank) == mid.map(Self.rank).sorted() && mid.last == .excellentFit, "\(mid)")122 #expect(Set(classes + mid).isSuperset(of: [.unsupported, .memoryIntensive, .compatible, .excellentFit]))123 }124125 @Test func theNumbersBehindTheLabelAddUp() throws {126 let card = try RecordedFixture.card("Qwen3-1.7B-4bit")127 let d = FakeDevice.iPhone(8, availableGB: 5)128 let r = CompatibilityEngine.assess(card: card, device: d.device, memory: d.memory)129 #expect(r.weightsBytes == card.weightsBytes && r.weightsBytes > 900 << 20)130 #expect(r.runtimeOverheadBytes == 350 << 20)131 #expect(r.kvCacheBytes > 0 && r.estimatedNeedBytes == r.weightsBytes + r.kvCacheBytes + r.runtimeOverheadBytes)132 #expect(r.physicalBudgetBytes == Int64(Double(d.memory.physicalBytes) * 0.5))133 #expect(r.availableBudgetBytes == Int64(Double(5 << 30) * 0.85))134 #expect(r.budgetBytes == min(r.physicalBudgetBytes, r.availableBudgetBytes!))135 #expect(r.physicalBytes == d.memory.physicalBytes && r.availableBytes == 5 << 30)136 #expect(r.requestedContext == 4_096 && r.recommendedContext != nil)137 #expect(r.fit.contextTokens == r.recommendedContext && r.fit.mayLoad)138 #expect(abs(r.memoryRatio - Double(r.estimatedNeedBytes) / Double(r.budgetBytes)) < 1e-9)139 }140141 @Test func tooLargeIsUnsupportedWithTheMemoryReason() throws {142 let r = Self.assess(try RecordedFixture.card("Qwen3-4B-4bit"), gb: 4)143 #expect(r.compatibility == .unsupported && !r.canLoadNow && r.recommendedContext == nil)144 #expect(r.reasons.first?.contains("more than the") == true && r.reasons.first?.contains("smallest context") == true)145 #expect(r.fit.state == .unlikely || r.fit.state == .tooLarge) // the older verdict agrees it must not load146 #expect(!r.fit.mayLoad)147 }148149 @Test func contextIsReducedAutomaticallyWithASentence() throws {150 let r = Self.assess(try RecordedFixture.card("Qwen3-4B-4bit"), gb: 12)151 #expect(r.requestedContext == 8_192)152 #expect(r.recommendedContext == 4_096)153 #expect(r.contextNote == "Context reduced from 8,192 to 4,096 tokens to stay within this device's memory.")154 #expect(r.reasons.contains(r.contextNote!))155 #expect(r.compatibility == .compatible)156 // An explicit request above the model's own limit is capped at that limit, without a memory sentence when it fits.157 let small = Self.assess(try RecordedFixture.card("SmolLM2-135M-Instruct-8bit"), gb: 8, context: 100_000)158 #expect(small.requestedContext == 8_192 && small.recommendedContext == 8_192 && small.contextNote == nil)159 }160161 @Test func thermalLevels() throws {162 let card = try RecordedFixture.card("Qwen3-0.6B-4bit")163 let nominal = Self.assess(card, gb: 8, thermal: .nominal), fair = Self.assess(card, gb: 8, thermal: .fair)164 let serious = Self.assess(card, gb: 8, thermal: .serious), critical = Self.assess(card, gb: 8, thermal: .critical)165 #expect(nominal.compatibility == .excellentFit && nominal.thermalFactor == 1 && nominal.canLoadNow && nominal.recommendedContext == 4_096)166 #expect(fair.compatibility == .excellentFit && fair.reasons == nominal.reasons)167 #expect(serious.compatibility == .compatible && serious.thermalFactor == 0.5 && serious.canLoadNow)168 #expect(serious.recommendedContext == 2_048)169 #expect(serious.contextNote == "Context reduced from 4,096 to 2,048 tokens because the device is hot.")170 #expect(serious.reasons.contains { $0.contains("The device is hot") })171 #expect(critical.thermalFactor == 0 && !critical.canLoadNow && critical.compatibility != .excellentFit)172 #expect(critical.headline == "The device is too hot to run a model right now.")173 #expect(critical.reasons.contains { $0.contains("too hot") })174 for level in ThermalLevel.allCases { #expect(Self.assess(card, gb: 8, thermal: level).thermal == level) }175 }176177 @Test func memoryPressureChangesTheClassAndSaysSo() throws {178 let card = try RecordedFixture.card("Qwen3-1.7B-4bit")179 let relaxed = Self.assess(card, gb: 8, availableGB: 6), squeezed = Self.assess(card, gb: 8, availableGB: 2.2), starved = Self.assess(card, gb: 8, availableGB: 1.0)180 #expect(relaxed.compatibility == .compatible || relaxed.compatibility == .excellentFit)181 #expect(relaxed.reasons.allSatisfy { !$0.contains("under pressure") })182 #expect(squeezed.compatibility == .memoryIntensive && squeezed.canLoadNow)183 #expect(squeezed.budgetBytes == squeezed.availableBudgetBytes && squeezed.budgetBytes < squeezed.physicalBudgetBytes)184 #expect(squeezed.reasons.contains { $0.contains("under pressure") })185 // Not enough right now, although the device itself is big enough: memory intensive, not unsupported, and not loadable at this moment.186 #expect(starved.compatibility == .memoryIntensive && !starved.canLoadNow && starved.recommendedContext == nil)187 #expect(starved.headline == "Probably too large to load right now.")188 #expect(starved.reasons.first?.contains("Closing other apps") == true)189 #expect(!starved.fit.mayLoad)190 }191192 @Test func experimentalAndUnsupportedEntries() throws {193 let base = try RecordedFixture.card("Qwen3-0.6B-4bit")194 let experimental = Self.assess(base.with { $0.status = .experimental; $0.statusNote = "Found on the Hub." }, gb: 8)195 #expect(experimental.compatibility == .experimental && experimental.canLoadNow && experimental.reasons.first == "Found on the Hub.")196 #expect(experimental.headline == "Untested: it may or may not work on this device.")197 let marked = Self.assess(base.with { $0.status = .unsupported; $0.statusNote = "Its tokenizer is not handled." }, gb: 16)198 #expect(marked.compatibility == .unsupported && marked.reasons == ["Its tokenizer is not handled."])199 let unknown = Self.assess(base.with { $0.architecture = "whisper" }, gb: 16)200 #expect(unknown.compatibility == .unsupported && !unknown.canLoadNow && unknown.runtime == .unsupported(reason: unknown.reasons[0]))201 #expect(unknown.reasons[0] == "The architecture “whisper” is not one that mlx-swift-lm 3.33.0 can load.")202 // Unsupported wins over experimental.203 #expect(Self.assess(base.with { $0.status = .experimental; $0.architecture = "t5" }, gb: 16).compatibility == .unsupported)204 // A vision entry whose architecture the runtime only loads as text.205 let vision = Self.assess(base.with { $0.capabilities = [.text, .vision] }, gb: 16)206 #expect(vision.compatibility == .unsupported && vision.reasons[0].contains("text model only"))207 #expect(Self.assess(base.with { $0.capabilities = [.text, .vision]; $0.architecture = "smolvlm" }, gb: 16).runtime == .vision)208 // OS requirement.209 let os = Self.assess(base.with { $0.minimumOS = "99.0" }, gb: 16)210 #expect(os.compatibility == .unsupported && os.reasons[0] == "It needs OS version 99.0 or later; this device runs 27.0.")211 #expect(Self.assess(base.with { $0.minimumOS = "18.0" }, gb: 16).compatibility == .excellentFit)212 }213214 @Test func belowTheDeclaredDeviceMemoryIsNeverExcellent() throws {215 let card = try RecordedFixture.card("Qwen3-0.6B-4bit").with { $0.minimumDeviceMemoryGB = 8 }216 let r = Self.assess(card, gb: 6)217 #expect(r.compatibility == .compatible)218 #expect(r.reasons.contains("The catalogue asks for a device with 8 GB of memory; this one has 6 GB."))219 #expect(Self.assess(card, gb: 8).compatibility == .excellentFit)220 #expect(CompatibilityEngine.nominalGigabytes(FakeDevice.iPhone(8).memory.physicalBytes) == 8 && CompatibilityEngine.nominalGigabytes(12 << 30) == 12)221 }222223 @Test func basisSaysHonestlyWhereTheLabelComesFrom() throws {224 let card = try RecordedFixture.card("Qwen3-0.6B-4bit") // carries the owner's Mac measurement225 let elsewhere = Self.assess(card, gb: 8)226 #expect(elsewhere.basis == .measuredElsewhere && elsewhere.isEstimate && elsewhere.measurement?.platform == "macOS")227 #expect(elsewhere.reasons.contains { $0.hasPrefix("Measured on another machine (Mac17,6") })228 #expect(elsewhere.headline == "Likely to run comfortably on this device.")229230 let estimated = Self.assess(card.with { $0.verified = nil }, gb: 8)231 #expect(estimated.basis == .estimated && estimated.measurement == nil)232 #expect(estimated.reasons.contains { $0.contains("Nobody has measured") })233234 let local = ModelMeasurement(modelID: card.id, on: FakeDevice.iPhone(8).device, tokensPerSecond: 61.5, timeToFirstToken: 0.2, peakMemoryBytes: 900 << 20)235 let here = Self.assess(card, gb: 8, measured: [local])236 #expect(here.basis == .measuredOnThisDevice && !here.isEstimate && here.measurement == local)237 #expect(here.headline == "Ran well on this device.")238 #expect(here.reasons.contains("Measured on this device: 61.5 tok/s, first token in 0.20 s."))239 // The measured peak replaces the weights + overhead estimate when it is larger.240 #expect(here.estimatedNeedBytes == (900 << 20) + here.kvCacheBytes && here.estimatedNeedBytes > elsewhere.estimatedNeedBytes)241242 // The same measurement on another iPhone model, or a measurement for another model, is not "this device".243 #expect(Self.assess(card, gb: 8, measured: [local], model: "iPhone17,1").basis == .measuredElsewhere)244 #expect(Self.assess(card.with { $0.verified = nil }, gb: 8, measured: [ModelMeasurement(modelID: "other", on: FakeDevice.iPhone(8).device, tokensPerSecond: 5)]).basis == .estimated)245 // The simulator runs on the host Mac: nothing measured there counts as this device.246 let sim = DeviceFacts(platform: .simulator, modelIdentifier: "iPhone18,2", osVersion: "27.0", physicalMemoryBytes: 48 << 30)247 #expect(!local.wasTaken(on: sim))248 }249250 @Test func wordingStaysProbabilisticForEstimates() throws {251 let cards = try RecordedFixture.build2Cards()252 let forbidden = ["will run", "will work", "guaranteed", "runs perfectly", "best model"]253 for card in cards {254 for gb in FakeDevice.sizes {255 for thermal in ThermalLevel.allCases {256 for available in [nil, 1.0, 3.0] as [Double?] {257 let r = Self.assess(card, gb: gb, availableGB: available, thermal: thermal)258 let text = ([r.headline] + r.reasons + [r.contextNote ?? ""]).joined(separator: " ").lowercased()259 for word in forbidden { #expect(!text.contains(word), "“\(word)” in: \(text)") }260 #expect(!r.reasons.isEmpty && !r.headline.isEmpty)261 #expect(r.basis != .measuredOnThisDevice) // nothing in the catalogue was measured on an iPhone262 #expect((r.recommendedContext == nil) == (r.compatibility == .unsupported || !r.fit.mayLoad))263 if r.compatibility == .unsupported { #expect(!r.canLoadNow) }264 if let c = r.recommendedContext { #expect(c <= r.requestedContext && c <= card.contextLength && r.estimatedNeedBytes <= r.budgetBytes) }265 }266 }267 }268 }269 }270271 @Test func runtimeTableMatchesTheLinkedPackage() throws {272 let table = RuntimeSupport.installed273 #expect(table.runtime == "mlx-swift-lm 3.33.0")274 for known in ["qwen3", "qwen2", "llama", "phi3", "gemma3_text", "smollm3", "deepseek_v3", "mistral"] { #expect(table.textArchitectures.contains(known)) }275 for known in ["smolvlm", "qwen2_5_vl", "gemma3", "fastvlm", "idefics3"] { #expect(table.visionArchitectures.contains(known)) }276 #expect(table.verdict(architecture: "qwen3") == .text && table.verdict(architecture: "smolvlm") == .vision)277 #expect(!table.supports("whisper") && !table.supports("") && !table.supports("qwen3_asr") && !table.supports("llama", needsVision: true))278 #expect(table.supports("gemma3", needsVision: true) && table.verdict(architecture: "gemma3") == .text)279280 // When the package checkout is on this machine, the constant must list exactly the keys of its two registries.281 let root = RecordedFixture.directory.deletingLastPathComponent().deletingLastPathComponent()282 let checkout = root.appendingPathComponent("build/dd/SourcePackages/checkouts/mlx-swift-lm/Libraries")283 func keys(_ file: String, _ registry: String) -> Set<String>? {284 guard let source = try? String(contentsOf: checkout.appendingPathComponent(file), encoding: .utf8),285 let start = source.range(of: "enum \(registry)"), let end = source.range(of: "\n ])", range: start.upperBound..<source.endIndex) else { return nil }286 var out = Set<String>()287 for line in source[start.upperBound..<end.lowerBound].split(separator: "\n") {288 let trimmed = line.trimmingCharacters(in: .whitespaces)289 guard trimmed.hasPrefix("\""), let close = trimmed.dropFirst().firstIndex(of: "\""), trimmed[trimmed.index(after: close)...].hasPrefix(":") else { continue }290 out.insert(String(trimmed.dropFirst()[..<close]))291 }292 return out293 }294 if let text = keys("MLXLLM/LLMModelFactory.swift", "LLMTypeRegistry"), let vision = keys("MLXVLM/VLMModelFactory.swift", "VLMTypeRegistry") {295 #expect(text == table.textArchitectures, "text: \(text.symmetricDifference(table.textArchitectures))")296 #expect(vision == table.visionArchitectures, "vision: \(vision.symmetricDifference(table.visionArchitectures))")297 }298 }299300 @Test func olderVerdictAPIStillWorks() throws {301 let card = try RecordedFixture.card("Qwen3-0.6B-4bit")302 let d = FakeDevice.iPhone(8)303 let verdict = MemoryGovernor(platform: .iOS).verdict(for: card.memoryProfile, context: 4_096, reading: d.memory)304 #expect(verdict.state == .comfortable && verdict.mayLoad && verdict.isEstimate)305 #expect(CompatibilityEngine.assess(card: card, device: d.device, memory: d.memory).fit == verdict)306 }307}308