SPB Git

Repository Public

AdvisorTests.swift 16.0 KB 264 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/AdvisorTests.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 ModelAdvisorTests {94    /// The build 2 catalogue with tags, plus hand-made entries for the categories it does not cover.95    static func candidates(vision: Bool = true) throws -> [LocalModelCard] {96        var cards = try RecordedFixture.build2Cards().map { card in97            card.with {98                switch $0.family {99                case "Qwen3":100                    $0.tags = ["general", "reasoning", "multilingual"]; $0.thinking = .init(supported: true, toggleable: true, defaultOn: true)101                case "SmolLM2": $0.tags = ["lightweight"]102                case "Llama 3.2", "Gemma 3": $0.tags = ["general"]103                case "Phi-4": $0.tags = ["general", "math"]104                default: break105                }106            }107        }108        let base = try RecordedFixture.card("Qwen3-1.7B-4bit")109        cards.append(base.with { $0.id = "Coder-1.5B-4bit"; $0.displayName = "Coder 1.5B"; $0.tags = ["coding"]; $0.capabilities = [.text] })110        cards.append(base.with { $0.id = "Untested-Coder-4bit"; $0.tags = ["coding", "math", "reasoning", "multilingual", "general"]; $0.status = .experimental; $0.verified = nil111                                 $0.parameterCount = 3_900_000_000 })112        cards.append(base.with { $0.id = "Broken-Coder"; $0.tags = ["coding", "general"]; $0.status = .unsupported; $0.statusNote = "Tokenizer not handled." })113        cards.append(base.with { $0.id = "Unknown-Arch"; $0.tags = ["coding", "general"]; $0.architecture = "t5" })114        if vision {115            cards.append(base.with {116                $0.id = "Vision-2B-4bit"; $0.displayName = "Vision 2B"; $0.architecture = "smolvlm"; $0.tags = ["vision"]; $0.capabilities = [.text, .vision]117                $0.validation = ValidationRecord(downloaded: true, loaded: true, generated: true, cancelled: true, reloaded: true, image: true); $0.maxImages = 1118            })119            cards.append(base.with { $0.id = "Vision-Untested"; $0.architecture = "smolvlm"; $0.tags = ["vision"]; $0.capabilities = [.text, .vision]; $0.status = .experimental })120        }121        return cards122    }123124    static func recommend(_ goal: AdvisorGoal, gb: Double = 8, candidates: [LocalModelCard]? = nil, installed: Set<String> = [], availableGB: Double? = nil,125                          thermal: ThermalLevel = .nominal, measurements: [ModelMeasurement] = []) throws -> Recommendation {126        let d = FakeDevice.iPhone(gb, availableGB: availableGB)127        return ModelAdvisor.recommend(goal: goal, candidates: try candidates ?? Self.candidates(), installed: installed, device: d.device,128                                      measurements: measurements, memory: d.memory, thermal: thermal)129    }130131    @Test func everyGoalGetsAnExplainedPrimaryPick() throws {132        for goal in AdvisorGoal.allCases {133            let r = try Self.recommend(goal)134            let pick = try #require(r.primary, "no pick for \(goal)")135            #expect(!r.isNothingSuitable && r.nothingSuitableReason == nil)136            #expect(pick.card.status == .verified && !pick.isExperimental)137            #expect(pick.compatibility.compatibility != .unsupported && pick.compatibility.canLoadNow)138            #expect(pick.reasons.count >= 4)139            #expect(pick.summary.hasPrefix("A good fit for \(goal.phrase) on this device because "))140            #expect(r.headline == pick.summary)141            #expect(r.alternatives.count <= 3 && !r.alternatives.contains { $0.id == pick.id })142            #expect(pick.score > 0 && pick.score <= 1)143            #expect(abs(pick.components.reduce(0) { $0 + $1.contribution } - pick.score) < 1e-3)144            // Unsupported entries never appear anywhere, and are listed with the reason they were left out.145            for p in [pick] + r.alternatives { #expect(p.id != "Broken-Coder" && p.id != "Unknown-Arch" && p.compatibility.compatibility != .unsupported) }146            #expect(r.excluded.contains { $0.modelID == "Broken-Coder" && $0.reason == "Tokenizer not handled." })147            #expect(r.excluded.contains { $0.modelID == "Unknown-Arch" && $0.reason.contains("t5") })148            // Experimental entries are alternatives only, and say so.149            for p in r.alternatives where p.isExperimental {150                #expect(p.summary.hasPrefix("Experimental, not yet run with Astra"))151                #expect(p.reasons.contains("it is experimental: nobody has run it with Astra yet"))152            }153            // Deterministic.154            #expect(try Self.recommend(goal) == r)155            #expect(try ModelAdvisor.recommend(goal: goal, candidates: Self.candidates().reversed(), device: FakeDevice.iPhone(8).device, memory: FakeDevice.iPhone(8).memory) == r)156        }157    }158159    @Test func goalsPickTheModelsTheDataPointsTo() throws {160        #expect(try Self.recommend(.programming).primary?.id == "Coder-1.5B-4bit")161        #expect(try Self.recommend(.programming).primary?.reasons.first == "it is tagged for coding use")162        #expect(try Self.recommend(.mathematics).primary?.id == "Phi-4-mini-instruct-4bit")163        #expect(try Self.recommend(.imageAnalysis).primary?.id == "Vision-2B-4bit")164        #expect(try Self.recommend(.imageAnalysis).primary?.reasons.contains("image input was exercised when it was checked") == true)165        #expect(try Self.recommend(.imageAnalysis).alternatives.map(\.id) == ["Vision-Untested"])166        #expect(try Self.recommend(.fastest).primary?.id == "Qwen2.5-0.5B-Instruct-4bit")       // 562 tok/s, the highest measured167        #expect(try Self.recommend(.lowestMemory).primary?.id == "SmolLM2-135M-Instruct-8bit")  // 0.14 GB168        let reasoning = try #require(try Self.recommend(.advancedReasoning).primary)169        #expect(reasoning.card.family == "Qwen3" && reasoning.reasons.contains("its thinking mode can be switched on or off"))170        #expect(try Self.recommend(.multilingual).primary?.card.family == "Qwen3")171        #expect(try Self.recommend(.everydayChat).primary?.card.hasTag("general") == true)172        // Quality prefers more parameters, as long as the model is not classed unsupported here.173        let quality = try #require(try Self.recommend(.bestQuality, gb: 16).primary)174        #expect((quality.card.parameterCount ?? 0) >= 3_000_000_000)175        #expect(quality.reasons.contains { $0.contains("billion parameters") })176    }177178    @Test func reasonsAreFactsWithTheirOrigin() throws {179        let pick = try #require(try Self.recommend(.fastest).primary)180        #expect(pick.reasons.contains("it was measured at 562 tok/s, first token in 0.01 s on Mac17,6 (Apple M5 Max, 48 GB), not on this device"))181        #expect(pick.reasons.contains { $0.hasPrefix("its compatibility class here is “Excellent Fit”: about ") && $0.hasSuffix("(estimate)") })182        #expect(pick.reasons.contains("its download is 276 MB"))183        #expect(pick.reasons.contains("it was downloaded, loaded and run end to end on a Mac (not on an iPhone)"))184185        // A measurement taken on this device is reported as such and outranks a faster Mac figure of another model.186        let local = ModelMeasurement(modelID: "SmolLM2-135M-Instruct-8bit", on: FakeDevice.iPhone(8).device, tokensPerSecond: 480, timeToFirstToken: 0.05)187        let measured = try #require(try Self.recommend(.fastest, measurements: [local]).primary)188        #expect(measured.id == "SmolLM2-135M-Instruct-8bit")189        #expect(measured.reasons.contains("it was measured at 480 tok/s, first token in 0.05 s on this device"))190        #expect(measured.compatibility.basis == .measuredOnThisDevice)191192        // An unmeasured candidate says so instead of borrowing a number.193        let unmeasured = try Self.recommend(.programming, candidates: [try RecordedFixture.card("Qwen3-0.6B-4bit").with { $0.verified = nil; $0.tags = ["coding"] }])194        #expect(unmeasured.primary?.reasons.contains("its speed has not been measured") == true)195    }196197    @Test func installedModelsAreFavouredForOfflineUse() throws {198        let fresh = try #require(try Self.recommend(.offlinePrivacy).primary)199        #expect(fresh.reasons.contains { $0.hasPrefix("its download is ") })200        #expect(fresh.reasons.contains("it runs entirely on the device: prompts and answers are not sent anywhere"))201        let r = try Self.recommend(.offlinePrivacy, installed: ["SmolLM2-360M-Instruct-6bit"])202        #expect(r.primary?.id == "SmolLM2-360M-Instruct-6bit" && r.primary?.isInstalled == true)203        #expect(r.primary?.reasons.contains("it is already installed, so it works with no network at all") == true)204    }205206    @Test func nothingSuitableIsSaidExplicitly() throws {207        // Image analysis without any vision model.208        let none = try Self.recommend(.imageAnalysis, candidates: Self.candidates(vision: false))209        #expect(none.primary == nil && none.isNothingSuitable && none.alternatives.isEmpty)210        #expect(none.nothingSuitableReason == "No model that accepts images is available for this device yet, so nothing can be suggested for image analysis.")211        #expect(none.headline == none.nothingSuitableReason)212        #expect(none.excluded.contains { $0.reason == "Does not accept images." })213214        // Only an experimental vision model: listed as an alternative, never promoted.215        let onlyExperimental = try Self.recommend(.imageAnalysis, candidates: Self.candidates().filter { $0.id != "Vision-2B-4bit" })216        #expect(onlyExperimental.primary == nil && onlyExperimental.alternatives.map(\.id) == ["Vision-Untested"])217        #expect(onlyExperimental.nothingSuitableReason?.contains("Only experimental models") == true)218219        // A vision model whose image probe failed is not suggested for images.220        let failed = try Self.recommend(.imageAnalysis, candidates: [try #require(Self.candidates().first { $0.id == "Vision-2B-4bit" }).with { $0.validation?.image = false }])221        #expect(failed.primary == nil && failed.excluded.first?.reason == "Image input was tried with this model and did not work.")222223        // Nothing fits: every candidate is too large for the device.224        let big = [try RecordedFixture.card("Qwen3-4B-4bit"), try RecordedFixture.card("SmolLM2-1.7B-Instruct")]225        let tooLarge = try Self.recommend(.everydayChat, gb: 4, candidates: big)226        #expect(tooLarge.primary == nil && tooLarge.alternatives.isEmpty && tooLarge.excluded.count == 2)227        #expect(tooLarge.nothingSuitableReason?.contains("None of the 2 available models can run on this device") == true)228229        // No candidates at all, and a device too hot to load anything.230        #expect(try Self.recommend(.fastest, candidates: []).nothingSuitableReason == "There is no model to choose from.")231        let hot = try Self.recommend(.everydayChat, thermal: .critical)232        #expect(hot.primary == nil && hot.nothingSuitableReason?.contains("too hot") == true)233    }234235    @Test func memoryPressureAndDeviceSizeChangeThePick() throws {236        let roomy = try #require(try Self.recommend(.bestQuality, gb: 16).primary)237        let cramped = try #require(try Self.recommend(.bestQuality, gb: 4).primary)238        #expect(cramped.card.totalBytes < roomy.card.totalBytes)239        #expect(cramped.compatibility.compatibility != .unsupported)240        let squeezed = try Self.recommend(.bestQuality, gb: 16, availableGB: 1.0)241        #expect(squeezed.excluded.contains { $0.reason == "Does not fit in the memory available on this device right now." })242        #expect((squeezed.primary?.compatibility.estimatedNeedBytes ?? 0) <= Int64(0.85 * 1_073_741_824))243    }244245    @Test func aGoalWithoutTaggedModelsFallsBackHonestly() throws {246        let general = try RecordedFixture.build2Cards().map { $0.with { $0.tags = ["general"] } }247        let r = try Self.recommend(.programming, candidates: general)248        let pick = try #require(r.primary)249        #expect(pick.reasons.first == "no available model is tagged for coding use, and this is a general model")250    }251252    @Test func neverClaimsAnAbsoluteBest() throws {253        for goal in AdvisorGoal.allCases {254            #expect(!goal.title.lowercased().contains("best"))255            for gb in FakeDevice.sizes {256                let r = try Self.recommend(goal, gb: gb)257                let text = ([r.headline, r.nothingSuitableReason ?? ""] + ([r.primary].compactMap { $0 } + r.alternatives).flatMap { [$0.summary] + $0.reasons } + r.excluded.map(\.reason))258                    .joined(separator: " ").lowercased()259                for word in ["best model", "the best", "will run", "guarantee", "perfect"] { #expect(!text.contains(word), "“\(word)” for \(goal) on \(gb) GB: \(text)") }260            }261        }262    }263}264
Files main
Menu

Theme