SPB Git

Repository Public

VerificationReport.swift 67.5 KB 839 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/VerificationReport.swift10// Module           : AstraLocalTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// 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/// Facts about each candidate that do not come from running it: who made the original model, its nominal size, what it is for and94/// its license terms. License conditions are summarized from the license texts linked here; they are not legal advice.95struct CandidateFacts {96    enum Rehost: String { case yes = "Yes", conditional = "Conditional", no = "No", unclear = "Unclear" }97    struct License {98        var id: String; var name: String; var url: String; var conditions: String99    }100    var repo: String101    var displayName: String102    var family: String103    var publisher: String104    /// Nominal parameter count of the original model, from its publisher's repository.105    var parameters: Int64106    var license: License107    var rehost: Rehost108    /// Categories for the library ("general", "reasoning", "coding", "vision", "lightweight", "multilingual", "math").109    var tags: [String]110    /// Repository of the original model, and the license tag its card declared when checked (2026-11-22).111    var upstream: String?112    /// Other quantizations of the same model that exist on the Hub and were not run.113    var alternatives: String?114    /// Accept a conversion whose own card has no license tag when its declared base model is `upstream`.115    var acceptsMissingTag = false116    var id: String { String(repo.split(separator: "/").last ?? "") }117    var licenseID: String { license.id }118    var licenseName: String { license.name }119    var licenseURL: String { license.url }120    var conditions: String { license.conditions }121122    static let apache = License(id: "apache-2.0", name: "Apache-2.0", url: "https://www.apache.org/licenses/LICENSE-2.0",123                                conditions: "Keep the license text and any NOTICE with the files; state changes if the weights are modified.")124    static let mit = License(id: "mit", name: "MIT", url: "https://opensource.org/license/mit", conditions: "Keep the copyright and permission notice with the files.")125    static let gemma = License(id: "gemma", name: "Gemma Terms of Use", url: "https://ai.google.dev/gemma/terms",126                               conditions: "Redistribution is allowed only if recipients are bound by the same use restrictions (Prohibited Use Policy), receive a copy of the Gemma Terms, and modified files carry a notice. Served from Hugging Face only until the owner decides.")127    static let llama = License(id: "llama3.2", name: "Llama 3.2 Community License", url: "https://www.llama.com/llama3_2/license/",128                               conditions: "Redistribution is allowed only with a copy of the license, the “Built with Llama” attribution shown prominently, the notice file kept, and the Acceptable Use Policy respected. Served from Hugging Face only until the owner decides.")129    static let qwenResearch = License(id: "qwen-research", name: "Qwen Research License", url: "https://huggingface.co/Qwen/Qwen2.5-3B-Instruct/blob/main/LICENSE",130                                      conditions: "**Non-commercial (research and evaluation) use only**; commercial use needs a separate license from Alibaba Cloud. Copies may be distributed only with the agreement, a notice of changes and the Qwen attribution notice. Not re-hosted; served from Hugging Face only, and the app must present it as a research-only model.")131    static let lfm = License(id: "lfm1.0", name: "LFM Open License v1.0", url: "https://huggingface.co/LiquidAI/LFM2-1.2B/blob/main/LICENSE",132                             conditions: "Apache-style grant with a **commercial-use limit**: commercial use is licensed only to entities with less than 10 million US dollars of annual revenue (the threshold does not apply to qualified non-profits doing research). Redistribution is allowed with the license and notices. Not re-hosted: the condition depends on who the recipient is.")133134    static func make(_ name: String, _ display: String, _ family: String, _ publisher: String, _ parameters: Int64, _ license: License, _ rehost: Rehost,135                     tags: [String], upstream: String? = nil, alternatives: String? = nil, acceptsMissingTag: Bool = false) -> CandidateFacts {136        CandidateFacts(repo: "mlx-community/" + name, displayName: display, family: family, publisher: publisher, parameters: parameters,137                       license: license, rehost: rehost, tags: tags, upstream: upstream, alternatives: alternatives, acceptsMissingTag: acceptsMissingTag)138    }139140    static let qwen = "Alibaba Cloud (Qwen)", hf = "Hugging Face (HuggingFaceTB)"141142    static let all: [CandidateFacts] = [143        // Build 2 catalogue.144        make("Qwen3-0.6B-4bit", "Qwen3 0.6B", "Qwen3", qwen, 600_000_000, apache, .yes, tags: ["general", "reasoning", "lightweight", "multilingual"], upstream: "Qwen/Qwen3-0.6B"),145        make("Qwen3-1.7B-4bit", "Qwen3 1.7B", "Qwen3", qwen, 1_700_000_000, apache, .yes, tags: ["general", "reasoning", "multilingual"], upstream: "Qwen/Qwen3-1.7B"),146        make("Qwen3-4B-4bit", "Qwen3 4B", "Qwen3", qwen, 4_000_000_000, apache, .yes, tags: ["general", "reasoning", "multilingual"], upstream: "Qwen/Qwen3-4B"),147        make("Qwen2.5-0.5B-Instruct-4bit", "Qwen2.5 0.5B Instruct", "Qwen2.5", qwen, 494_000_000, apache, .yes, tags: ["general", "lightweight", "multilingual"]),148        make("gemma-3-1b-it-qat-4bit", "Gemma 3 1B (QAT)", "Gemma 3", "Google", 1_000_000_000, gemma, .conditional, tags: ["general", "lightweight"],149             alternatives: "`gemma-3-1b-it-4bit`, `-4bit-DWQ`, `-6bit`, `-8bit`, `-qat-6bit`, `-qat-8bit`"),150        make("gemma-3-4b-it-qat-4bit", "Gemma 3 4B (QAT)", "Gemma 3", "Google", 4_300_000_000, gemma, .conditional, tags: ["general", "vision"]),151        make("Llama-3.2-1B-Instruct-4bit", "Llama 3.2 1B Instruct", "Llama 3.2", "Meta", 1_240_000_000, llama, .conditional, tags: ["general", "lightweight"]),152        make("Llama-3.2-3B-Instruct-4bit", "Llama 3.2 3B Instruct", "Llama 3.2", "Meta", 3_210_000_000, llama, .conditional, tags: ["general"]),153        make("Phi-4-mini-instruct-4bit", "Phi-4 mini Instruct", "Phi-4", "Microsoft", 3_840_000_000, mit, .yes, tags: ["general", "reasoning", "math"]),154        make("SmolLM2-135M-Instruct", "SmolLM2 135M Instruct", "SmolLM2", hf, 135_000_000, apache, .yes, tags: ["general", "lightweight"]),155        make("SmolLM2-135M-Instruct-8bit", "SmolLM2 135M Instruct", "SmolLM2", hf, 135_000_000, apache, .yes, tags: ["general", "lightweight"]),156        make("SmolLM2-360M-Instruct", "SmolLM2 360M Instruct", "SmolLM2", hf, 362_000_000, apache, .yes, tags: ["general", "lightweight"]),157        make("SmolLM2-360M-Instruct-6bit", "SmolLM2 360M Instruct", "SmolLM2", hf, 362_000_000, apache, .yes, tags: ["general", "lightweight"]),158        make("SmolLM2-1.7B-Instruct", "SmolLM2 1.7B Instruct", "SmolLM2", hf, 1_710_000_000, apache, .yes, tags: ["general"]),159        // Second wave.160        make("DeepSeek-R1-Distill-Qwen-1.5B-4bit", "DeepSeek R1 Distill 1.5B", "DeepSeek-R1", "DeepSeek", 1_777_088_000, mit, .yes, tags: ["reasoning", "math"],161             upstream: "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", alternatives: "`-6bit`, `-8bit`, unquantized `deepseek-r1-distill-qwen-1.5b`", acceptsMissingTag: true),162        make("DeepSeek-R1-Distill-Qwen-7B-4bit", "DeepSeek R1 Distill 7B", "DeepSeek-R1", "DeepSeek", 7_615_616_512, mit, .yes, tags: ["reasoning", "math"],163             upstream: "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", alternatives: "`-6bit`, `-8bit`", acceptsMissingTag: true),164        make("Qwen2.5-Coder-1.5B-Instruct-4bit", "Qwen2.5 Coder 1.5B", "Qwen2.5-Coder", qwen, 1_543_714_304, apache, .yes, tags: ["coding", "lightweight"],165             upstream: "Qwen/Qwen2.5-Coder-1.5B-Instruct", alternatives: "`-8bit`, `-Q6`"),166        make("Qwen2.5-Coder-3B-Instruct-4bit", "Qwen2.5 Coder 3B", "Qwen2.5-Coder", qwen, 3_085_938_688, qwenResearch, .no, tags: ["coding"],167             upstream: "Qwen/Qwen2.5-Coder-3B-Instruct", alternatives: "`-8bit`"),168        make("Qwen2.5-Coder-7B-Instruct-4bit", "Qwen2.5 Coder 7B", "Qwen2.5-Coder", qwen, 7_615_616_512, apache, .yes, tags: ["coding"],169             upstream: "Qwen/Qwen2.5-Coder-7B-Instruct", alternatives: "`-8bit`, `Qwen2.5.1-Coder-7B-Instruct-4bit`"),170        make("Qwen3-8B-4bit", "Qwen3 8B", "Qwen3", qwen, 8_190_735_360, apache, .yes, tags: ["general", "reasoning", "multilingual"],171             upstream: "Qwen/Qwen3-8B", alternatives: "`-4bit-DWQ`, `-6bit`, `-8bit`"),172        make("gemma-3-4b-it-4bit", "Gemma 3 4B", "Gemma 3", "Google", 4_300_079_472, gemma, .conditional, tags: ["general", "vision", "multilingual"],173             upstream: "google/gemma-3-4b-it", alternatives: "`-4bit-DWQ` (text only), `-6bit`, `-8bit`, `gemma-3-text-4b-it-4bit` (text only)"),174        make("gemma-3-270m-it-4bit", "Gemma 3 270M", "Gemma 3", "Google", 268_098_176, gemma, .conditional, tags: ["general", "lightweight"],175             upstream: "google/gemma-3-270m-it", alternatives: "`-4bit-DWQ`, `-qat-4bit`, `-6bit`, `-8bit`"),176        make("SmolLM3-3B-4bit", "SmolLM3 3B", "SmolLM3", hf, 3_075_098_624, apache, .yes, tags: ["general", "reasoning", "multilingual"],177             upstream: "HuggingFaceTB/SmolLM3-3B", alternatives: "`-4bit-DWQ`, `-5bit`, `-6bit`, `-8bit`"),178        make("Phi-3.5-mini-instruct-4bit", "Phi-3.5 mini Instruct", "Phi-3.5", "Microsoft", 3_821_079_552, mit, .yes, tags: ["general", "reasoning"],179             upstream: "microsoft/Phi-3.5-mini-instruct", alternatives: "`-8bit`"),180        make("LFM2-1.2B-4bit", "LFM2 1.2B", "LFM2", "Liquid AI", 1_170_340_608, lfm, .conditional, tags: ["general", "lightweight"],181             upstream: "LiquidAI/LFM2-1.2B", alternatives: "`-5bit`, `-6bit`, `-8bit`"),182        make("LFM2-2.6B-4bit", "LFM2 2.6B", "LFM2", "Liquid AI", 2_569_272_320, lfm, .conditional, tags: ["general"],183             upstream: "LiquidAI/LFM2-2.6B", alternatives: "`-8bit`, `LFM2-2.6B-Exp-4bit`"),184        make("LFM2.5-1.2B-Instruct-4bit", "LFM2.5 1.2B Instruct", "LFM2.5", "Liquid AI", 1_170_340_608, lfm, .conditional, tags: ["general", "lightweight"],185             upstream: "LiquidAI/LFM2.5-1.2B-Instruct", alternatives: "`-5bit`, `-6bit`, `-8bit`"),186        make("LFM2.5-1.2B-Thinking-4bit", "LFM2.5 1.2B Thinking", "LFM2.5", "Liquid AI", 1_170_340_608, lfm, .conditional, tags: ["reasoning", "lightweight"],187             upstream: "LiquidAI/LFM2.5-1.2B-Thinking", alternatives: "`-5bit`, `-6bit`, `-8bit`"),188        make("Qwen2.5-3B-Instruct-4bit", "Qwen2.5 3B Instruct", "Qwen2.5", qwen, 3_085_938_688, qwenResearch, .no, tags: ["general", "multilingual"],189             upstream: "Qwen/Qwen2.5-3B-Instruct", alternatives: "`-8bit`"),190        make("SmolVLM2-256M-Video-Instruct-mlx", "SmolVLM2 256M", "SmolVLM2", hf, 256_484_928, apache, .yes, tags: ["vision", "lightweight"],191             upstream: "HuggingFaceTB/SmolVLM2-256M-Video-Instruct"),192        make("SmolVLM2-500M-Video-Instruct-mlx", "SmolVLM2 500M", "SmolVLM2", hf, 507_482_304, apache, .yes, tags: ["vision", "lightweight"],193             upstream: "HuggingFaceTB/SmolVLM2-500M-Video-Instruct"),194        make("SmolVLM2-2.2B-Instruct-mlx", "SmolVLM2 2.2B", "SmolVLM2", hf, 2_246_784_880, apache, .yes, tags: ["vision"],195             upstream: "HuggingFaceTB/SmolVLM2-2.2B-Instruct"),196        make("Qwen2.5-VL-3B-Instruct-4bit", "Qwen2.5-VL 3B", "Qwen2.5-VL", qwen, 3_754_622_976, qwenResearch, .no, tags: ["vision", "multilingual"],197             upstream: "Qwen/Qwen2.5-VL-3B-Instruct", alternatives: "`-6bit`, `-8bit`", acceptsMissingTag: true),198        make("Qwen3-0.6B-8bit", "Qwen3 0.6B (8-bit)", "Qwen3", qwen, 600_000_000, apache, .yes, tags: ["general", "reasoning", "lightweight", "multilingual"],199             upstream: "Qwen/Qwen3-0.6B", alternatives: "`-4bit` (in the catalogue), `-4bit-DWQ`, `-6bit`"),200        make("Qwen3-1.7B-4bit-DWQ-053125", "Qwen3 1.7B (4-bit DWQ)", "Qwen3", qwen, 1_700_000_000, apache, .yes, tags: ["general", "reasoning", "multilingual"],201             upstream: "Qwen/Qwen3-1.7B", alternatives: "`-4bit` (in the catalogue), `-5bit`, `-6bit`, `-8bit`"),202        // Named in the first candidate list; the Hub has no such repositories.203        make("SmolLM2-1.7B-Instruct-4bit", "SmolLM2 1.7B Instruct", "SmolLM2", hf, 1_710_000_000, apache, .yes, tags: ["general"]),204        make("SmolLM2-360M-Instruct-4bit", "SmolLM2 360M Instruct", "SmolLM2", hf, 362_000_000, apache, .yes, tags: ["general", "lightweight"]),205    ]206207    /// Candidates of the brief that were looked at and deliberately not run, with the reason.208    static let notRun: [(String, String)] = [209        ("Qwen3 4B / 1.7B “thinking mode” as separate entries", "They are the same weights as `Qwen3-4B-4bit` / `Qwen3-1.7B-4bit`: thinking is a switch of the chat template (`enable_thinking`), verified both ways on the existing entries. No duplicate download was created."),210        ("`mlx-community/gemma-3-1b-it-4bit` (non-QAT 1B)", "Not run: the QAT conversion of the same model is already in the catalogue and Google publishes the QAT weights as the ones meant for 4-bit use."),211        ("`mlx-community/gemma-3-text-4b-it-4bit`", "Not run: a text-only conversion of Gemma 3 4B. The full `gemma-3-4b-it-4bit` (with the vision tower) was verified instead."),212        ("6-bit, 8-bit and DWQ variants listed under “Other quantizations”", "They exist on the Hub and their architectures are the same as the verified 4-bit entries, but they were not downloaded or run, so they are not offered."),213        ("`mlx-community/Qwen3-4B-Instruct-2507-*`, `Qwen3-4B-Thinking-2507-*`", "Only 8-bit conversions were found under `mlx-community` when searched on 2026-11-22; not run."),214    ]215}216217/// The verdict derived from a verification record.218struct Assessment {219    var status: ModelStatus220    /// Why the entry is not "verified"; empty when it is.221    var issues: [String]222    var thinkingOK: Bool?223    var visionOK: Bool?224    var codingOK: Bool?225    var note: String? { issues.isEmpty ? nil : issues.joined(separator: " ") }226}227228enum VerificationReport {229    static func load() throws -> [String: VerificationResult] {230        let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601231        var out: [String: VerificationResult] = [:]232        for url in (try? FileManager.default.contentsOfDirectory(at: ProjectPaths.results, includingPropertiesForKeys: nil)) ?? [] where url.pathExtension == "json" {233            let r = try d.decode(VerificationResult.self, from: Data(contentsOf: url))234            out[r.id] = r235        }236        return out237    }238239    /// The catalogue shipped inside build 2 of the app. Its entries are carried over unchanged: installs depend on their ids, files and hashes.240    static let baselineURL = ProjectPaths.root.appendingPathComponent("docs/catalog/baseline/catalog-1.0.0-build2.json")241    static func baseline() throws -> [LocalModelCard] { try ModelCatalog.decode(Data(contentsOf: baselineURL)).models }242243    /// Quantization as the repository's own config states it; a repository without a quantization block holds unquantized weights.244    static func quantization(_ r: VerificationResult) -> String {245        if let bits = r.quantizationBits {246            let lower = r.id.lowercased()247            return "\(bits)-bit" + (lower.contains("qat") ? " (QAT)" : lower.contains("dwq") ? " (DWQ)" : "")248        }249        return "none (16-bit float)"250    }251252    /// Why a model that ran is still kept out of the catalog; nil when nothing objects.253    static func exclusion(_ r: VerificationResult, _ facts: CandidateFacts) -> String? {254        guard r.passed || r.turn1 != nil else { return r.failure ?? "failed" }255        // The Hub card must agree with what the files are: same family as the config, a license tag consistent with the original model.256        let tag = (r.hubLicense ?? "").lowercased()257        let named = r.hubTags.contains { $0.lowercased() == "license_name:" + facts.licenseID } || tag == facts.licenseID258        if named || (tag == "other" && ["qwen-research", "lfm1.0"].contains(facts.licenseID) && r.hubBaseModels.contains { $0.hasPrefix(facts.upstream?.split(separator: "/").first.map(String.init) ?? "?") }) { return nil }259        if tag.isEmpty, facts.acceptsMissingTag, let upstream = facts.upstream, r.hubBaseModels.contains(upstream) { return nil }260        return "Provenance unclear: the Hub card declares license “\(r.hubLicense ?? "none")” and base model “\(r.hubBaseModels.joined(separator: ", "))”, which does not match a \(facts.family) model (config model_type “\(r.modelType ?? "?")”)."261    }262263    /// verified = every applicable step passed; experimental = it loads and generates, but something listed in `issues` did not.264    static func assess(_ r: VerificationResult, _ facts: CandidateFacts) -> Assessment {265        var issues: [String] = []266        if !r.passed {267            if r.stage == "chat turn 1", let t = r.turn1, t.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, !t.reasoning.isEmpty {268                issues.append("The model spent the whole \(t.completionTokens ?? 0)-token budget of the first verification turn (a one-line greeting) thinking and never answered, at temperature 0 and again at temperature 0.6; the later steps (KV reuse, cancellation, reload, probes, benchmark) were not run, so it has no measured figures.")269            } else { issues.append("The verification run stopped at “\(r.stage)”: \(r.failure ?? "unknown").") }270        }271        var thinkingOK: Bool?, visionOK: Bool?, codingOK: Bool?272        guard let c = r.capability else {273            if r.passed { issues.append("The capability probes were not run on this entry.") }274            return Assessment(status: .experimental, issues: issues)275        }276        let behavior = FamilyThinkingBehavior(rawValue: c.thinkingBehavior) ?? .none277        if behavior.supported {278            var ok = true279            if let on = c.reasoningOn {280                if on.reasoningCharacters == 0 { ok = false; issues.append("With thinking on, no separate thinking text was produced.") }281                if on.answer.isEmpty { ok = false; issues.append("With thinking on, the model did not reach an answer within 1 500 tokens.") }282                if on.markersLeaked { ok = false; issues.append("A thinking marker leaked into the text with thinking on.") }283            } else { ok = false; issues.append("The thinking-on probe did not run.") }284            if behavior == .toggleable {285                if let off = c.reasoningOff {286                    if off.reasoningCharacters > 0 { ok = false; issues.append("With thinking off, the model still produced thinking text.") }287                    if off.answer.isEmpty { ok = false; issues.append("With thinking off, the model produced no answer.") }288                    if off.markersLeaked { ok = false; issues.append("A thinking marker leaked into the text with thinking off.") }289                } else { ok = false; issues.append("The thinking-off probe did not run.") }290            }291            if let x = c.thinkingCancellation {292                if x.reasoningChunksBeforeCancel < 15 { ok = false; issues.append("Cancellation during thinking could not be exercised: the model stopped thinking after \(x.reasoningChunksBeforeCancel) chunks.") }293                else if !x.endedWithCancelledError || x.completedEventSeen || x.secondsToStop >= 3 || !x.recordedAsCancelled { ok = false; issues.append("Cancelling during the thinking phase did not end the stream promptly with a cancellation.") }294                else if x.answerChunksBeforeCancel > 0 { ok = false; issues.append("Answer text appeared before the cancellation inside the thinking phase.") }295            } else { ok = false; issues.append("The cancellation-during-thinking probe did not run.") }296            if let cut = c.reasoningCutByTokenLimit {297                if !cut.answer.isEmpty || cut.markersLeaked || cut.reasoningUnterminated != true {298                    ok = false; issues.append("A thinking block cut by the token limit was not reported as unterminated thinking with no answer.")299                }300            } else { ok = false; issues.append("The token-limit-inside-thinking probe did not run.") }301            thinkingOK = ok302        }303        if facts.tags.contains("coding") {304            let missing = c.coding.filter { !$0.fencedBlockInRequestedLanguage }.map(\.id)305            codingOK = !c.coding.isEmpty && missing.isEmpty306            if c.coding.isEmpty { issues.append("The coding prompts did not run.") }307            else if !missing.isEmpty { issues.append("Coding prompts answered without a fenced block in the requested language: \(missing.joined(separator: ", ")).") }308        }309        if r.hasVision {310            if let v = c.vision {311                let shots = [("colour", v.colour), ("chart", v.chartNumber), ("text", v.textRead), ("description", v.description)]312                let failed = shots.filter { $0.1.error != nil }.map { "\($0.0): \($0.1.error ?? "")" }313                visionOK = failed.isEmpty && v.colour.ok314                if !failed.isEmpty { issues.append("Image inference failed (\(failed.joined(separator: "; "))).") }315                else if !v.colour.ok { issues.append("The model did not name the colour of a plain red image (answer: “\(v.colour.answer ?? "")”).") }316                if let multi = v.multiImage, multi.error != nil { issues.append("Two images in one request failed: \(multi.error ?? "").") }317            } else { visionOK = false; issues.append("The repository has a vision tower but the image probes did not run.") }318        }319        issues.append(contentsOf: c.errors)320        return Assessment(status: issues.isEmpty ? .verified : .experimental, issues: issues, thinkingOK: thinkingOK, visionOK: visionOK, codingOK: codingOK)321    }322323    static func thinking(_ r: VerificationResult) -> ThinkingSupport? {324        guard let c = r.capability, let b = FamilyThinkingBehavior(rawValue: c.thinkingBehavior), b.supported else { return nil }325        return b.support(defaultOn: false)326    }327328    static func validation(_ r: VerificationResult, _ a: Assessment) -> ValidationRecord {329        let stages = ["resolve", "download", "inspect", "load", "chat turn 1", "chat turn 2", "cancellation", "reload from disk", "probes", "capability probes", "benchmark", "done"]330        let reached = stages.firstIndex(of: r.stage) ?? 0331        func past(_ s: String) -> Bool { r.passed || reached > (stages.firstIndex(of: s) ?? 99) }332        var notes = ["Run on \(r.device.modelIdentifier) (\(r.device.platform.rawValue) \(r.device.osVersion)), \(r.date); not on an iPhone."]333        if let t = r.transfer { notes.append("Files: \(t), every file hashed against the Hub's SHA-256.") }334        if let v = r.capability?.vision {335            notes.append("Images: colour \(v.colour.ok ? "named" : "not named"), number on a chart \(v.chartNumber.ok ? "read" : "not read"), text \(v.textRead.ok ? "read" : "not read")"336                         + (v.multiImage.map { ", two images \($0.ok ? "handled" : "not handled")" } ?? ", one image per request") + ".")337        }338        if let j = r.capability?.jsonOnly { notes.append("JSON-only output: \(j.strictlyValid ? "valid" : j.validAfterRemovingFence ? "valid inside a code fence" : "not valid JSON").") }339        return ValidationRecord(downloaded: past("download"), loaded: past("load"), generated: r.turn1 != nil, cancelled: past("cancellation"), reloaded: past("reload from disk"),340                                toolCall: r.toolCallVerified, thinking: a.thinkingOK, image: r.hasVision ? a.visionOK : nil, notes: notes.joined(separator: " "))341    }342343    /// Additive fields for an entry, from its record. Used for new entries and to complete the entries carried over from build 2.344    static func annotate(_ card: inout LocalModelCard, _ r: VerificationResult?, _ facts: CandidateFacts) {345        card.tags = facts.tags346        card.modelFamily = facts.family347        card.requiredRuntime = "mlx-swift-lm 3.33.0"348        guard let r, r.revision == card.revision, r.capability != nil else { return }349        let a = assess(r, facts)350        card.status = a.status; card.statusNote = a.note351        card.thinking = thinking(r)352        card.promptTemplate = r.capability?.promptTemplate; card.tokenizer = r.capability?.tokenizerClass353        card.validation = validation(r, a)354        if r.hasVision, let v = r.capability?.vision, a.visionOK == true {355            let multi = v.multiImage?.ok == true356            card.maxImages = multi ? v.maxImages : 1; card.supportsMultipleImages = multi357        }358    }359360    static func card(_ r: VerificationResult, _ facts: CandidateFacts, machine: String) -> LocalModelCard? {361        guard exclusion(r, facts) == nil, let revision = r.revision, !r.files.isEmpty, r.turn1 != nil else { return nil }362        let a = assess(r, facts)363        let governor = MemoryGovernor(platform: .iOS)364        let weights = r.files.filter { $0.path.hasSuffix(".safetensors") }.reduce(Int64(0)) { $0 + $1.size }365        let profile = ModelMemoryProfile(weightsBytes: weights, parameterCount: facts.parameters, modelContextLength: r.contextLength)366        let need = weights + governor.kvCacheBytes(profile, context: 4_096) + governor.overheadBytes367        // Smallest common device memory on which the estimate stays inside the governor's 50 % share. An estimate, like the verdict itself.368        let minimum = [4.0, 6, 8, 12, 16, 24, 32].first { Double(need) <= $0 * 1_073_741_824 * governor.physicalShare } ?? 64369        var capabilities: [Capability] = [.text]370        var tasks = ["chat"]371        if a.thinkingOK == true || (r.capability == nil && r.reasoningVerified == true) { capabilities.append(.reasoning); tasks.append("reasoning") }372        if r.toolCallVerified == true { capabilities.append(.tools); tasks.append("tool-use") }373        if a.visionOK == true { capabilities.append(.vision); tasks.append("vision") }374        if a.codingOK == true { tasks.append("coding") }375        var notes = ["Measured on a Mac, not on an iPhone."]376        if r.recalledFact == false { notes.append("Did not recall a fact from the previous turn in the verification chat.") }377        if r.hasVision, a.visionOK != true { notes.append("The repository contains a vision tower; image input was not verified.") }378        if r.capability?.thinkingBehavior == FamilyThinkingBehavior.alwaysOn.rawValue { notes.append("Always thinks before answering; the thinking switch has no effect.") }379        if facts.rehost != .yes { notes.append("Not re-hosted: \(facts.licenseName).") }380        if facts.licenseID == "qwen-research" { notes.append("Research and evaluation use only (non-commercial license).") }381        if weights > 3_500_000_000 { notes.append(String(format: "Large: %.1f GB of weights; most iPhones cannot hold it.", Double(weights) / 1_073_741_824)) }382        let redistributable = facts.rehost == .yes383        var verified: VerifiedRecord?384        if let rate = r.tokensPerSecond, let ttft = r.timeToFirstToken, rate > 0 {385            verified = VerifiedRecord(date: r.date, machine: machine, platform: "macOS", osVersion: r.device.osVersion, tokensPerSecond: (rate * 10).rounded() / 10,386                                      timeToFirstToken: (ttft * 1000).rounded() / 1000, peakMemoryBytes: r.peakMemoryBytes,387                                      runtime: "mlx-swift-lm 3.33.0, \(r.buildConfiguration ?? "debug") build")388        }389        var card = LocalModelCard(390            id: r.id, displayName: facts.displayName, family: facts.family, publisher: facts.publisher, repo: r.repo, revision: revision,391            architecture: r.modelType ?? "unknown", quantization: quantization(r), parameterCount: facts.parameters,392            licenseID: facts.licenseID, licenseURL: facts.licenseURL, redistributable: redistributable,393            totalBytes: r.totalBytes, files: r.files, contextLength: r.contextLength ?? 2_048, capabilities: capabilities,394            minimumDeviceMemoryGB: minimum, estimatedRuntimeMemoryBytes: need, supportedTasks: tasks,395            verified: verified, notes: notes.joined(separator: " "),396            baseURL: redistributable ? ModelCatalog.defaultBase.absoluteString + "/files/\(r.id)/" : nil,397            fallbackBaseURL: LocalModelCard.huggingFaceBase(repo: r.repo, revision: revision))398        annotate(&card, r, facts)399        card.status = a.status; card.statusNote = a.note400        return card401    }402403    /// The catalogue: every build 2 entry with its original fields, then the new entries that ran.404    static func catalog(results: [String: VerificationResult], baseline: [LocalModelCard], machine: String) -> [LocalModelCard] {405        var out: [LocalModelCard] = []406        let known = Set(baseline.map(\.id))407        for var card in baseline {408            if let facts = CandidateFacts.all.first(where: { $0.id == card.id }) {409                annotate(&card, results[card.id], facts)410                // Same bytes, run again with the full protocol: the measured record is replaced by the newer run. Identity, files,411                // hashes, license, capabilities and mirror fields stay exactly as shipped.412                if let r = results[card.id], r.passed, r.revision == card.revision, r.capability != nil, let rate = r.tokensPerSecond, let ttft = r.timeToFirstToken, rate > 0 {413                    card.verified = VerifiedRecord(date: r.date, machine: machine, platform: "macOS", osVersion: r.device.osVersion, tokensPerSecond: (rate * 10).rounded() / 10,414                                                   timeToFirstToken: (ttft * 1000).rounded() / 1000, peakMemoryBytes: r.peakMemoryBytes,415                                                   runtime: "mlx-swift-lm 3.33.0, \(r.buildConfiguration ?? "debug") build")416                }417            }418            out.append(card)419        }420        for facts in CandidateFacts.all where !known.contains(facts.id) {421            if let r = results[facts.id], let card = card(r, facts, machine: machine) { out.append(card) }422        }423        return out424    }425426    // MARK: Formatting427428    static func mb(_ bytes: Int64?) -> String { bytes.map { String(format: "%.0f MB", Double($0) / 1_048_576) } ?? "–" }429    static func gb(_ bytes: Int64) -> String { String(format: "%.2f GB", Double(bytes) / 1_073_741_824) }430    static func num(_ v: Double?, _ format: String) -> String { v.map { String(format: format, $0) } ?? "–" }431    static func yesNo(_ v: Bool?) -> String { v == nil ? "not run" : (v! ? "yes" : "no") }432    static func cell(_ s: String?, _ n: Int = 140) -> String {433        guard let s, !s.isEmpty else { return "–" }434        let flat = s.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "|", with: "\\|")435        return flat.count > n ? String(flat.prefix(n)) + "…" : flat436    }437438    /// States plainly how busy the Mac was, because that bounds how far the speed figures can be trusted.439    static func loadNote(_ results: [String: VerificationResult]) -> String {440        let loads = results.values.compactMap(\.loadAverage)441        guard let low = loads.min(), let high = loads.max() else { return "The load of the machine during the run was not recorded." }442        let cores = ProcessInfo.processInfo.activeProcessorCount443        let range = String(format: "%.0f to %.0f", low, high)444        if high > Double(cores) * 1.5 {445            return "**The Mac was busy with other work during this run** (one-minute load average \(range) on \(cores) cores), so the speed and time-to-first-token figures are lower than what the same Mac does when idle. Treat them as conservative; run the script again on a quiet machine for representative figures."446        }447        return "One-minute load average during the runs: \(range) on \(cores) cores (other builds were running on the Mac part of the time, so treat speeds as conservative)."448    }449450    static func dates(_ results: [String: VerificationResult]) -> String {451        let all = results.values.filter(\.passed).map(\.date).sorted()452        guard let first = all.first, let last = all.last else { return "?" }453        return first == last ? first : "\(first) to \(last)"454    }455456    static func header(_ title: String, _ results: [String: VerificationResult], machine: String) -> String {457        let any = results.values.first { $0.passed } ?? results.values.first458        return """459        # \(title)460461        Generated by `Scripts/verify-models.sh` from the records in `build/verify/`. Every number below was measured by running the model;462        nothing is copied from a model card.463464        **All measurements were taken on a Mac: \(machine), macOS \(any?.device.osVersion ?? "?"), with mlx-swift-lm 3.33.0 (\(any?.buildConfiguration ?? "debug") build), on \(dates(results)).465        They are not iPhone measurements.** No iPhone was attached to this Mac.466467        \(loadNote(results))468469470        """471    }472473    static func statusWord(_ r: VerificationResult, _ facts: CandidateFacts, _ inCatalog: Bool) -> String {474        if r.revision == nil { return "**not found**" }475        if !r.passed && r.turn1 == nil { return "**unsupported** (failed at \(r.stage))" }476        if exclusion(r, facts) != nil { return "ran, **excluded**" }477        guard r.capability != nil else { return r.passed ? "**pass** (build 2 protocol)" : "**experimental** (stopped at \(r.stage))" }478        return "**\(assess(r, facts).status.rawValue)**"479    }480481    // MARK: MODEL_COMPATIBILITY.md482483    static func markdown(results: [String: VerificationResult], cards: [LocalModelCard], machine: String) -> String {484        var md = header("Model compatibility", results, machine: machine)485        md += """486        ## What the statuses mean487488        Every candidate goes through the same run: the repository's current commit is resolved from the Hugging Face API; every file is489        fetched through AstraLocal's `DownloadCoordinator` (or copied in beforehand, see "Transfer") and its SHA-256 recomputed from disk490        and matched against the hash the Hub publishes; the model is loaded by AstraLocal's MLX runtime; it answers a two-turn491        conversation with the second turn reusing the KV cache; a long answer is cancelled mid-stream and must stop within 3 s with492        `AstraError.cancelled`; the model is unloaded, loaded again from disk and answers; the capability probes run; then the benchmark493        sets. Speed is the median decode rate of the three warm prompts of the *general* set; time to first token is the warm median;494        peak memory is the highest MLX allocator peak during that set (weights included, short prompts).495496        - **verified**: all of the above passed, and every capability the model is listed for passed its probe:497          - a *thinking* model produced separate thinking text and an answer with thinking on; with thinking off (when the template has a498            switch) it produced an answer and no thinking; a cancellation fired *inside* the thinking phase ended the stream with a499            cancellation and no answer text; a thinking block cut by a 24-token limit ended as thinking, with no answer and no marker leaked;500          - a model tagged *coding* answered the three fixed coding prompts with a fenced block in the requested language (a format check,501            not a judgement of the code);502          - a *vision* model ran real image inference on four generated images without error and named the colour of a plain red image.503            Reading a number off a chart, reading printed text and handling two images are recorded per model in504            [MULTIMODAL_SUPPORT.md](MULTIMODAL_SUPPORT.md); they describe what the model can do and do not change the status.505        - **experimental**: the model loads and generates, but one of those steps failed. The reason is in the table and in `statusNote`.506        - **unsupported**: the model could not be loaded. It is listed here with the error and is not in the catalogue.507508        The tool-call and JSON-only probes are recorded and never decide the status: a model that fails them is simply not listed with the509        "tools" capability. Entries marked "build 2 protocol" were verified on 2026-11-21 before the capability probes existed.510511        ## Results512513        | Model (repository) | Status | Revision | Quantization | Download | Weights in memory | Speed | TTFT warm / cold | Peak memory | In catalog |514        |---|---|---|---|---|---|---|---|---|---|515516        """517        let order = CandidateFacts.all518        let inCatalog = Set(cards.map(\.id))519        for facts in order {520            guard let r = results[facts.id] else {521                md += "| `\(facts.repo)` | not run | – | – | – | – | – | – | – | \(inCatalog.contains(facts.id) ? "yes (build 2 record)" : "no") |\n"; continue522            }523            let revision = r.revision.map { "`\($0.prefix(12))`" } ?? "–"524            let status = statusWord(r, facts, inCatalog.contains(r.id))525            if r.turn1 != nil {526                md += "| `\(r.repo)` | \(status) | \(revision) | \(quantization(r)) | \(gb(r.totalBytes)) (\(r.files.count) files) | \(mb(r.weightsMemoryBytes)) | \(num(r.tokensPerSecond, "%.1f tok/s")) | \(num(r.timeToFirstToken, "%.3f s")) / \(num(r.coldTimeToFirstToken, "%.3f s")) | \(mb(r.peakMemoryBytes)) | \(inCatalog.contains(r.id) ? "yes" : "**no**") |\n"527            } else {528                md += "| `\(r.repo)` | \(status) | \(revision) | \(r.modelType == nil ? "–" : quantization(r)) | \(r.totalBytes > 0 ? gb(r.totalBytes) : "–") | – | – | – | – | no |\n"529            }530        }531        md += "\nRevisions are shortened to 12 characters here; the catalogue carries the full commit.\n"532533        let large = order.compactMap { facts -> String? in534            guard let r = results[facts.id], r.passed, let w = r.weightsMemoryBytes, w > 3_500 << 20 else { return nil }535            return "| `\(facts.id)` | \(gb(r.totalBytes)) | \(mb(w)) | \(mb(r.peakMemoryBytes)) | \(cards.first { $0.id == r.id }.map { String(format: "%.0f GB", $0.minimumDeviceMemoryGB) } ?? "–") |"536        }537        if !large.isEmpty {538            md += """539540            ## Large models (7B to 8B): measured size541542            These were verified on the Mac only. Their weights alone exceed what most iPhones can give one app; the catalogue's543            `minimumDeviceMemoryGB` is an estimate, and the app's compatibility engine decides per device. Nothing here shows they run on any iPhone.544545            | Model | Download | Weights in memory (measured) | Peak MLX memory, short prompts (measured) | Estimated minimum device memory |546            |---|---|---|---|---|547            \(large.joined(separator: "\n"))548549            """550        }551552        md += "\n## Capabilities actually probed\n\n"553        md += "| Model | Purpose | Thinking | Thinking on → separate text / answer | Thinking off → clean answer | Cancel inside thinking | Cut by token limit handled | Coding fences (Swift / Python / JS) | Image input | Tool call | JSON only | Recalled fact (turn 2) | Reason when not verified |\n|---|---|---|---|---|---|---|---|---|---|---|---|---|\n"554        for facts in order {555            guard let r = results[facts.id], r.turn1 != nil else { continue }556            guard let c = r.capability else {557                md += "| `\(facts.id)` | \(facts.tags.joined(separator: ", ")) | \(r.passed ? yesNo(r.reasoningVerified) + " (build 2 probe)" : "–") | – | – | – | – | – | \(yesNo(r.visionVerified)) | \(yesNo(r.toolCallVerified)) | – | \(yesNo(r.recalledFact)) | \(r.passed ? "–" : cell(assess(r, facts).note, 400)) |\n"; continue558            }559            let a = assess(r, facts)560            let on = c.reasoningOn.map { "\($0.reasoningCharacters > 0 ? "yes" : "no") (\($0.reasoningTokens ?? 0) tokens) / \($0.answer.isEmpty ? "no" : "yes")" } ?? "–"561            let off = c.reasoningOff.map { $0.reasoningCharacters == 0 && !$0.answer.isEmpty && !$0.markersLeaked ? "yes" : "no" } ?? (c.thinkingBehavior == "alwaysOn" ? "n/a (always on)" : "–")562            let cancel = c.thinkingCancellation.map { $0.endedWithCancelledError && $0.answerChunksBeforeCancel == 0 && $0.reasoningChunksBeforeCancel >= 15 ? String(format: "yes (%.2f s)", $0.secondsToStop) : "no" } ?? "–"563            let cut = c.reasoningCutByTokenLimit.map { $0.answer.isEmpty && !$0.markersLeaked && $0.reasoningUnterminated == true ? "yes" : "no" } ?? "–"564            let fences = c.coding.map { $0.fencedBlockInRequestedLanguage ? "yes" : ($0.hasFencedBlock ? "other fence" : "no") }.joined(separator: " / ")565            let image = r.hasVision ? yesNo(a.visionOK) : (c.refusesImages == true ? "refused (text-only)" : "–")566            let json = c.jsonOnly.map { $0.strictlyValid ? "yes" : $0.validAfterRemovingFence ? "in a fence" : "no" } ?? "–"567            md += "| `\(facts.id)` | \(facts.tags.joined(separator: ", ")) | \(c.thinkingBehavior) | \(on) | \(off) | \(cancel) | \(cut) | \(fences.isEmpty ? "–" : fences) | \(image) | \(yesNo(r.toolCallVerified)) | \(json) | \(yesNo(r.recalledFact)) | \(cell(a.note, 400)) |\n"568        }569        md += "\n“Thinking”: `none` = the model has no thinking phase; `toggleable` = the chat template has a switch (`enable_thinking`), driven by the request's reasoning setting; `alwaysOn` = the model always thinks and the switch is ignored. “Tool call” “not run” means the chat template declares no tool format. “JSON only”: whether the answer to a JSON-only request parsed as JSON as is, or only after removing a code fence.\n"570571        md += "\n## Licenses and re-hosting\n\n`redistributable` in the catalog is `true` only for “Yes” (Apache-2.0 and MIT). Everything else is downloaded from Hugging Face only.\nThe license of an entry is the license of the **original model**, read from its publisher's repository on 2026-11-22; the last column shows what the MLX conversion's own card declares.\n\n"572        md += "| Model | Original model | License | May the owner re-host the weights? | Conditions (summary, not legal advice) | License tag on the conversion's card |\n|---|---|---|---|---|---|\n"573        for facts in order {574            guard let r = results[facts.id], r.revision != nil else { continue }575            let name = r.hubTags.first { $0.hasPrefix("license_name:") }.map { " (" + $0.dropFirst(13) + ")" } ?? ""576            md += "| `\(facts.id)` | \(facts.upstream.map { "`\($0)`" } ?? "–") | [\(facts.licenseName)](\(facts.licenseURL)) | \(facts.rehost.rawValue) | \(facts.conditions) | `\(r.hubLicense ?? "none")`\(name) |\n"577        }578        md += """579580        Notes on the non-obvious cases:581582        - **DeepSeek-R1 distills**: the `mlx-community` conversions carry no license tag. The original repositories (`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` and `-7B`) declare MIT, and the conversions name them as base model, so they are treated as MIT and marked re-hostable. The owner should confirm before publishing them on the mirror.583        - **Qwen2.5 3B, Qwen2.5-Coder 3B, Qwen2.5-VL 3B**: unlike the other Qwen2.5 sizes these are under the Qwen Research License: non-commercial use only. They are in the catalogue as Hugging Face-only downloads when verified; whether a TestFlight or App Store app may offer them at all is the owner's decision.584        - **LFM2 / LFM2.5**: the LFM Open License v1.0 allows commercial use only below 10 million US dollars of annual revenue. Hugging Face only.585        - **Gemma 3**: Gemma Terms of Use; the original Google repositories are gated (terms must be accepted), the `mlx-community` conversions are not.586587        """588589        md += "\n## What each repository actually is\n\nRead from the downloaded `config.json`, tokenizer files and from the Hub API, not assumed from the name.\n\n"590        md += "| Model | `model_type` | Tokenizer class | Chat template | Context (config) | Vision tower | Base model on the conversion's card | Transfer | Load time | Other quantizations on the Hub (not run) |\n|---|---|---|---|---|---|---|---|---|---|\n"591        for facts in order {592            guard let r = results[facts.id], r.revision != nil, r.modelType != nil else { continue }593            md += "| `\(facts.id)` | `\(r.modelType ?? "?")` | \(r.capability?.tokenizerClass ?? "–") | \(r.capability?.promptTemplate ?? "–") | \(r.contextLength.map(String.init) ?? "–") | \(r.hasVision ? "yes" : "no") | \(r.hubBaseModels.joined(separator: ", ")) | \(r.transfer ?? "DownloadCoordinator") | \(num(r.loadSeconds, "%.2f s")) | \(facts.alternatives ?? "–") |\n"594        }595        md += "\n“Transfer”: `DownloadCoordinator` = fetched from Hugging Face by the app's own downloader during the run; `pre-staged` = the files were fetched on a server with a fast link and copied to the Mac, then hashed by the coordinator and by the harness exactly as after a download (only the network transfer was skipped); `already present` = downloaded by the coordinator in an earlier run and hashed again.\n"596597        let failures = order.compactMap { facts -> String? in598            guard let r = results[facts.id] else { return nil }599            if r.revision == nil { return "- `\(r.repo)`: **not found**: \(r.failure ?? "unknown")" }600            if !r.passed && r.turn1 == nil { return "- `\(r.repo)`: **unsupported**, failed at *\(r.stage)*: \(r.failure ?? "unknown")" }601            if let why = exclusion(r, facts) { return "- `\(r.repo)`: ran correctly but is **kept out of the catalog**. \(why)" }602            return nil603        }604        md += "\n## Rejected, unsupported and excluded candidates\n\n" + (failures.isEmpty ? "" : failures.joined(separator: "\n") + "\n")605        for (name, why) in CandidateFacts.notRun { md += "- \(name): \(why)\n" }606        md += "\nEvery candidate's `model_type` was checked against the architectures mlx-swift-lm 3.33.0 registers (`LLMModelFactory`, `VLMModelFactory`) before downloading; none of the candidates of this wave had an unregistered architecture.\n"607608        md += "\n## Sample output\n\nFirst turn of the verification chat (\"My name is Sam and my favourite number is 42. Greet me by name in one short sentence.\"), temperature 0.\n\n"609        for facts in order {610            guard let r = results[facts.id], let t = r.turn1 else { continue }611            md += "- `\(facts.id)`: \(t.text.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\n", with: " ").prefix(200))\n"612        }613614        md += """615616        ## Not yet verified on a physical iPhone617618        Nothing in this document was run on an iPhone or iPad. In particular, the following are unknown until a device run:619620        - Whether each model loads and generates on iOS at all (MLX does not run in the iOS Simulator, so there is no simulator result either).621        - Tokens per second, time to first token and peak memory on any iPhone. The Mac figures above come from a machine with far more memory bandwidth and must not be shown as iPhone figures.622        - Behaviour under the iOS memory limit (jetsam): the `minimumDeviceMemoryGB` and `estimatedRuntimeMemoryBytes` fields of the catalog are estimates computed from the weight size, a KV-cache formula at 4 096 tokens and a fixed overhead. They are not measurements.623        - Whether the 7B and 8B models can be loaded on any iPhone, and how vision models behave there (image preprocessing memory, time per image).624        - How long a thinking phase takes on a phone, and whether thinking models stay usable under the thermal policy.625        - Thermal behaviour during long generations, and the effect of the thermal policy.626        - Downloads on a cellular connection, and resuming after iOS suspends the app (downloads use a foreground session).627        - Whether the larger models (2 GB and more of weights) are usable on 8 GB devices in practice.628629        ## Apple Foundation Models (system model): verified on this Mac only630631        The system model is a separate provider (`AppleFoundationProvider`); it is not an MLX model, is not in this catalogue and was not changed in this wave.632633        - **macOS, verified.** On this Mac (macOS 27.0) the live test `appleSystemModelStreamsAMultiTurnAnswer` (`ASTRA_APPLE_FM_TESTS=1`) ran on 2026-11-22: a three-turn conversation replayed through a `Transcript` streamed an answer that recalled a fact from the first turn, ended with one `.messageCompleted`, and the framework reported token usage (86 input, 7 output), which the adapter passed on. Cancellation with the system model was not exercised.634        - **iOS Simulator, failed.** A generation was attempted in the iOS Simulator (iOS 26.5 runtime, Mac host on macOS 27) on 2026-11-21. `SystemLanguageModel.default.availability` reported `.available`, yet the generation failed with `LanguageModelSession.GenerationError` code -1. Availability in the Simulator is therefore not a reliable signal; the app now says so in its error message when an unrecognised failure happens there.635        - **iPhone / iPad, NOT verified.** Nothing was run on an Apple Intelligence-eligible device. It needs one.636637        The `verified` record of each catalog entry says `"platform": "macOS"` for this reason. It should be replaced by an iOS record only after a real run on the device it names.638639        """640        return md641    }642643    // MARK: MODEL_BENCHMARKS.md644645    static func benchmarkRows(_ b: LocalBenchmarkResult) -> (decode: Double?, prefill: Double?, ttft: Double?, ttfa: Double?, tokens: Int, reasoning: Int, total: Double, peak: Int64?) {646        let warm = b.warm.isEmpty ? b.samples : b.warm647        return (LocalBenchmarkResult.median(warm.compactMap(\.decodeTokensPerSecond)), LocalBenchmarkResult.median(warm.compactMap(\.promptTokensPerSecond)),648                LocalBenchmarkResult.median(warm.compactMap(\.timeToFirstToken)), LocalBenchmarkResult.median(warm.compactMap(\.timeToFirstAnswerToken)),649                b.samples.reduce(0) { $0 + ($1.outputTokens ?? 0) }, b.samples.reduce(0) { $0 + ($1.reasoningTokens ?? 0) },650                b.totalTime ?? b.samples.reduce(0) { $0 + $1.totalTime }, b.peakMemoryBytes)651    }652653    static func benchmarksMarkdown(results: [String: VerificationResult], machine: String) -> String {654        var md = header("Model benchmarks", results, machine: machine)655        md += """656        ## Method657658        `LocalBenchmark` (in `Packages/AstraLocal/Sources/LocalBenchmark.swift`) runs a fixed prompt set through `LocalEngine` exactly as a chat659        would, at temperature 0 with seed 7, and records for each prompt what the runtime measured:660661        | Figure | What it is |662        |---|---|663        | Time to first token | Wall-clock seconds from the request to the first token of anything (thinking included) |664        | Time to first answer token | Seconds to the first token of the answer itself, after any thinking |665        | Prefill | Newly evaluated prompt tokens per second (cached tokens excluded) |666        | Decode | Generated tokens per second over the decode phase |667        | Total time | Wall-clock seconds of the set, model load excluded |668        | Peak memory | Highest MLX allocator peak during the set (weights included) |669        | Load time (cold) | Seconds to load the weights after an unload; the file cache of the Mac was warm |670        | Tokens generated, context, thermal state before/after, device, OS, quantization, revision | Stored in every `LocalBenchmarkResult` |671672        The first prompt after a load is the **cold** sample; medians are over the warm samples. Four standard sets exist so runs are673        comparable: `general` (4 prompts, 160 tokens), `reasoning` (4 prompts, thinking on, 1 024 tokens), `coding` (3 prompts, 320 tokens)674        and `vision` (4 prompts on generated images, 160 tokens). A result carries `measuredOn` (the device identifier) and the app labels675        it with `provenanceLabel` ("Measured on …"); figures published by a model's author are never stored in that type.676677        Every table below is **measured on \(machine)**. Prefill rates on prompts of a few dozen tokens are noisy and understate long prompts.678679        ## General set680681        | Model | Quantization | Load (cold) | TTFT warm | TTFT cold | Prefill (median) | Decode (median) | Tokens generated | Total time | Peak memory | Thermal before → after |682        |---|---|---|---|---|---|---|---|---|---|---|683684        """685        for facts in CandidateFacts.all {686            guard let r = results[facts.id], let b = r.benchmark else { continue }687            let row = benchmarkRows(b)688            md += "| `\(facts.id)` | \(quantization(r)) | \(num(b.loadTime, "%.2f s")) | \(num(row.ttft, "%.3f s")) | \(num(b.cold?.timeToFirstToken, "%.3f s")) | \(num(row.prefill, "%.0f tok/s")) | \(num(row.decode, "%.1f tok/s")) | \(row.tokens) | \(num(row.total, "%.1f s")) | \(mb(row.peak)) | \(b.thermalBefore.rawValue) → \(b.thermalAfter.rawValue) |\n"689        }690        for (set, title, note) in [("reasoning", "Reasoning set (thinking on)", "Thinking tokens are part of the tokens generated. “Time to first answer token” is the wait before the answer itself starts; “–” means no prompt of the set reached its answer within 1 024 tokens."),691                                   ("coding", "Coding set", "Run on every model, not only the ones tagged for coding, so speeds are comparable. Whether the answers contain a correctly labelled code block is in MODEL_COMPATIBILITY.md."),692                                   ("vision", "Vision set (generated test images)", "Prompt tokens include the image tokens, which is why prefill dominates the time to first token. What the models answered is in MULTIMODAL_SUPPORT.md.")] {693            md += "\n## \(title)\n\n\(note)\n\n| Model | TTFT warm | Time to first answer token | Prefill (median) | Decode (median) | Tokens generated | of which thinking | Total time | Peak memory |\n|---|---|---|---|---|---|---|---|---|\n"694            for facts in CandidateFacts.all {695                guard let r = results[facts.id], let b = r.capability?.benchmarks[set] else { continue }696                let row = benchmarkRows(b)697                md += "| `\(facts.id)` | \(num(row.ttft, "%.3f s")) | \(num(row.ttfa, "%.2f s")) | \(num(row.prefill, "%.0f tok/s")) | \(num(row.decode, "%.1f tok/s")) | \(row.tokens) | \(set == "reasoning" ? String(row.reasoning) : "–") | \(num(row.total, "%.1f s")) | \(mb(row.peak)) |\n"698            }699        }700        md += """701702        ## Limits of these numbers703704        - They are Mac measurements. An iPhone has a fraction of this memory bandwidth and a thermal envelope a Mac does not have; expect705          several times lower speeds. No iPhone figure exists yet.706        - Other builds were running on the Mac during parts of the run (see the load average above).707        - Peak memory was measured on short prompts. A long conversation adds KV-cache memory that these figures do not include.708        - Entries verified on 2026-11-21 with the build 2 protocol have a general-set result only.709710        """711        return md712    }713714    // MARK: MULTIMODAL_SUPPORT.md715716    static func multimodalMarkdown(results: [String: VerificationResult], machine: String) -> String {717        var md = header("Multimodal (image) support", results, machine: machine)718        md += """719        ## What exists720721        - **Runtime path.** A model whose `config.json` declares a vision tower is loaded through `VLMModelFactory` (MLXVLM); everything else722          through `LLMModelFactory`. Images travel as `ImageInput` on a user `PromptMessage`, as with the cloud providers.723        - **`VisionPreprocessor`.** Every image is decoded with ImageIO straight to a bounded size (never at full resolution), with the EXIF724          orientation applied, the aspect ratio kept and no enlargement. The bounds come from the model family (`ModelFamilyAdapter.vision`):725          a maximum long side, a maximum pixel count, and the number of images one request may carry. The model's own processor then does726          its final resampling.727        - **Typed refusals** (`VisionInputError`, surfaced as `AstraError`): an image sent to a text-only model728          (“This model cannot read images.”), more images than the model accepts, bytes that are not an image. All are raised729          before the model is touched.730        - **Input only.** No model here generates images. Video and audio input are not wired, although some of these repositories support video.731732        ## Limits per family733734        | `model_type` | Family | Decoded at most | Images per request | Sizing done by the model's processor |735        |---|---|---|---|---|736737        """738        for (type, a) in ModelFamilyAdapter.byModelType.sorted(by: { $0.key < $1.key }) {739            guard let v = a.vision else { continue }740            md += "| `\(type)` | \(a.family) | \(v.maxLongSide) px long side, \(v.maxPixels / 1_000_000) MP | \(v.maxImages) | \(v.processorMaxPixels.map { "dynamic, budget \($0) px" } ?? "fixed by the processor") |\n"741        }742        md += """743744        A vision architecture missing from this table gets conservative limits (1 024 px, one image).745746        ## Probes747748        Four images are drawn locally with CoreGraphics and CoreText (`VisionTestImages`), so the expected answers are known exactly:749750        1. a 384 × 384 plain red square: “What colour fills this image? Answer with one word.” (expected: red);751        2. a 768 × 512 bar chart with bars A = 25, B = 50, C = 87, D = 12, each value printed above its bar: “What is the value written above bar C?” (expected: 87);752        3. a 768 × 512 white page with three printed lines (“INVOICE 4812”, “Total due: 73 dollars”, “Thank you, Marigold Bakery”): “Read the text in this image and write it out exactly.” (counted as read when the answer contains both “4812” and “Marigold”);753        4. the chart again: “Describe this image in two sentences.” (counted when the answer speaks of a chart, graph or bars);754        5. for families that accept several images: the red square and a blue square in one request, asked for both colours. For single-image755           families the same request must be refused with the typed error.756757        Temperature 0, at most 96 to 120 output tokens. One run per model: these are observations, not accuracy rates.758759        ## Results per model760761        | Model | Status | Colour | Number on a chart | Printed text | Description | Two images | Seconds per image request (median) | Prompt tokens (chart) |762        |---|---|---|---|---|---|---|---|---|763764        """765        var details = ""766        for facts in CandidateFacts.all {767            guard let r = results[facts.id], r.hasVision else { continue }768            guard let v = r.capability?.vision else {769                md += "| `\(facts.id)` | \(r.capability == nil ? "build 2 protocol" : "probes not run") | \(yesNo(r.visionVerified)) (96 px red square) | – | – | – | – | – | – |\n"; continue770            }771            let a = assess(r, facts)772            func mark(_ s: CapabilityProbes.Vision.Shot) -> String { s.error != nil ? "error" : (s.ok ? "yes" : "no") }773            let seconds = LocalBenchmarkResult.median([v.colour, v.chartNumber, v.textRead, v.description].compactMap(\.seconds))774            let two = v.multiImage.map(mark) ?? (v.refusesTooManyImages == true ? "refused (one image only)" : "not refused")775            md += "| `\(facts.id)` | \(exclusion(r, facts) != nil ? "excluded" : a.status.rawValue) | \(mark(v.colour)) | \(mark(v.chartNumber)) | \(mark(v.textRead)) | \(mark(v.description)) | \(two) | \(num(seconds, "%.2f s")) | \(v.chartNumber.promptTokens.map(String.init) ?? "–") |\n"776            details += "\n### `\(facts.id)`\n\n"777            details += "- Colour: \(cell(v.colour.answer ?? v.colour.error))\n- Chart, value above bar C: \(cell(v.chartNumber.answer ?? v.chartNumber.error))\n"778            details += "- Printed text: \(cell(v.textRead.answer ?? v.textRead.error, 260))\n- Description: \(cell(v.description.answer ?? v.description.error, 260))\n"779            if let m = v.multiImage { details += "- Two images: \(cell(m.answer ?? m.error, 200))\n" }780            else { details += "- Two images: \(v.refusesTooManyImages == true ? "refused before reaching the model, as intended (the processor takes one image)" : "the request was not refused as expected")\n" }781        }782        md += "\n“yes” = the expected content was in the answer; “no” = the model answered something else; “error” = inference failed.\n\n## What the models answered\n" + details783        let textOnly = CandidateFacts.all.compactMap { facts -> String? in784            guard let r = results[facts.id], !r.hasVision, let refused = r.capability?.refusesImages else { return nil }785            return refused ? nil : facts.id786        }787        let checked = results.values.filter { !$0.hasVision && $0.capability?.refusesImages != nil }.count788        md += """789790        ## Text-only models791792        An image was sent to each of the \(checked) text-only models that went through the capability probes. \(textOnly.isEmpty ? "All refused it with the typed error (“This model cannot read images.”) before any inference." : "These did not refuse it as expected: \(textOnly.joined(separator: ", ")).")793794        ## Known limits795796        - Nothing here was run on an iPhone. Image tokens make prompts long (see the prompt-token column); on a phone the wait before the797          first token of an image answer is unknown and probably several seconds.798        - SmolVLM2 takes one image per request in mlx-swift-lm 3.33.0; a conversation that already contains an image cannot receive a second one.799        - The image count limit applies to the whole request (every message of the conversation), because a conversation is replayed to the model.800        - `mlx-community/gemma-3-4b-it-qat-4bit` handles images but stays out of the catalogue for its contradictory metadata; `gemma-3-4b-it-4bit` is the Gemma 3 entry.801        - Charts and documents were tested with large, clean, synthetic images. Small print, photographs of documents and handwriting were not tested.802803        """804        return md805    }806}807808/// `ASTRA_VERIFY_REPORT=1 swift test --filter generateCatalogAndCompatibilityReport`809@Test(.enabled(if: ProjectPaths.env("ASTRA_VERIFY_REPORT") != nil)) func generateCatalogAndCompatibilityReport() throws {810    let results = try VerificationReport.load()811    try #require(!results.isEmpty, "no verification records in build/verify")812    let sample = try #require(results.values.first { $0.passed } ?? results.values.first)813    let machine = "\(sample.device.modelIdentifier) (\(sample.chip ?? "Apple silicon"), \(sample.device.physicalMemoryBytes >> 30) GB)"814    let baseline = try VerificationReport.baseline()815    let cards = VerificationReport.catalog(results: results, baseline: baseline, machine: machine)816    for card in cards { try card.validate() }817    // Build 2 entries keep their identity and bytes: same ids in the same order, same revision, files and hashes.818    #expect(Array(cards.prefix(baseline.count)).map(\.id) == baseline.map(\.id))819    for (old, new) in zip(baseline, cards) { #expect(old.contentFingerprint == new.contentFingerprint && old.repo == new.repo && old.totalBytes == new.totalBytes, "\(old.id)") }820    // Only licenses that clearly allow it are re-hosted.821    for card in cards where card.redistributable { #expect(["apache-2.0", "mit"].contains(card.licenseID), "\(card.id)") }822    for card in cards where !card.redistributable { #expect(card.baseURL == nil, "\(card.id)") }823    let catalog = ModelCatalog(generatedAt: Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded()), entries: cards.map { .init(card: $0, origin: .bundled) })824    let data = try catalog.encoded()825    // what is written must be exactly what the app will accept826    let decoded = try ModelCatalog.decode(data)827    #expect(decoded.models == cards)828    #expect(decoded.models.allSatisfy { $0.verified == nil || ($0.verified?.platform == "macOS" && $0.verified?.machine.hasPrefix("Mac") == true) })829    #expect(try RuntimeCatalogChecks.decodesWithBuild2Schema(data), "a build 2 app must still decode this catalogue")830    try FileManager.default.createDirectory(at: ProjectPaths.catalog.deletingLastPathComponent(), withIntermediateDirectories: true)831    try data.write(to: ProjectPaths.catalog, options: .atomic)832    let docs = ProjectPaths.compatibility.deletingLastPathComponent()833    try Data(VerificationReport.markdown(results: results, cards: cards, machine: machine).utf8).write(to: ProjectPaths.compatibility, options: .atomic)834    try Data(VerificationReport.benchmarksMarkdown(results: results, machine: machine).utf8).write(to: docs.appendingPathComponent("MODEL_BENCHMARKS.md"), options: .atomic)835    try Data(VerificationReport.multimodalMarkdown(results: results, machine: machine).utf8).write(to: docs.appendingPathComponent("MULTIMODAL_SUPPORT.md"), options: .atomic)836    let counts = Dictionary(grouping: cards, by: \.status).mapValues(\.count)837    FileHandle.standardError.write(Data("[report] \(cards.count) entries (\(counts[.verified] ?? 0) verified, \(counts[.experimental] ?? 0) experimental) from \(results.count) records → \(ProjectPaths.catalog.path)\n".utf8))838}839
Files main
Menu

Theme