SPB Git

Repository Public

RuntimeAdapterTests.swift 11.1 KB 188 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/RuntimeAdapterTests.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 RuntimeAdapterTests {94    static let qwen3Template = "{%- if add_generation_prompt %}{{- '<|im_start|>assistant\\n' }}{%- if enable_thinking is defined and enable_thinking is false %}{{- '<think>\\n\\n</think>\\n\\n' }}{%- endif %}{%- endif %}"95    static let deepSeekTemplate = "{% if '</think>' in content %}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|><think>\\n'}}{% endif %}"9697    @Test func qwen3IsToggleable() {98        let a = ModelFamilyAdapter.resolve(modelType: "qwen3", modelID: "Qwen3-4B-4bit", template: Self.qwen3Template)99        #expect(a.family == "qwen3" && a.thinking == .toggleable && a.reasoningMarkers == [.think] && !a.promptOpensReasoning && a.vision == nil)100        #expect(a.templateContext(thinking: false)["enable_thinking"] as? Bool == false)101        #expect(a.templateContext(thinking: true)["enable_thinking"] as? Bool == true)102        #expect(a.thinkingApplied(requested: false) == false && a.thinkingApplied(requested: true))103        #expect(a.thinking.support(defaultOn: false) == ThinkingSupport(supported: true, toggleable: true, defaultOn: false))104    }105106    @Test func deepSeekDistillsAlwaysThinkAndAreRecognisedByName() {107        for id in ["DeepSeek-R1-Distill-Qwen-1.5B-4bit", "mlx-community/DeepSeek-R1-Distill-Qwen-7B-4bit", "some-r1-distill-copy"] {108            let a = ModelFamilyAdapter.resolve(modelType: "qwen2", modelID: id, template: Self.deepSeekTemplate)109            #expect(a.family == "deepseek-r1" && a.thinking == .alwaysOn && a.promptOpensReasoning)110            #expect(a.templateContext(thinking: false).isEmpty, "an always-on family gets no switch")111            #expect(a.thinkingApplied(requested: false), "the toggle is ignored")112            #expect(a.thinking.support(defaultOn: false) == ThinkingSupport(supported: true, toggleable: false, defaultOn: true))113        }114        // A plain Qwen2.5 with the same model_type is not a reasoning model.115        let plain = ModelFamilyAdapter.resolve(modelType: "qwen2", modelID: "Qwen2.5-Coder-1.5B-Instruct-4bit", template: "{{ tools }}")116        #expect(plain.thinking == .none && plain.reasoningMarkers.isEmpty && plain.templateContext(thinking: true).isEmpty)117    }118119    @Test func aFamilySwitchIsNotClaimedWhenTheTemplateLacksIt() {120        let noSwitch = ModelFamilyAdapter.resolve(modelType: "qwen3", modelID: "x", template: "{{ messages }}")121        #expect(noSwitch.thinking == .none && noSwitch.thinkingTemplateKey == nil && noSwitch.reasoningMarkers.isEmpty)122        let thinksAlways = ModelFamilyAdapter.resolve(modelType: "qwen3", modelID: "x", template: "… <think> …")123        #expect(thinksAlways.thinking == .alwaysOn)124        // No template text available (not read): the family row stands.125        #expect(ModelFamilyAdapter.resolve(modelType: "qwen3", modelID: "x", template: nil).thinking == .toggleable)126    }127128    @Test func unknownFamiliesWithTheCommonSwitchAreToggleable() {129        let a = ModelFamilyAdapter.resolve(modelType: "brand_new", modelID: "x", template: "{% if enable_thinking %}<think>{% endif %}")130        #expect(a.family == "brand_new" && a.thinking == .toggleable && a.thinkingTemplateKey == "enable_thinking")131        let b = ModelFamilyAdapter.resolve(modelType: nil, modelID: "x", template: nil)132        #expect(b.family == "unknown" && b.thinking == .none)133    }134135    @Test func lfm25ThinkingCheckpointsAlwaysThinkButPlainLFM2DoesNot() {136        #expect(ModelFamilyAdapter.resolve(modelType: "lfm2", modelID: "LFM2.5-1.2B-Thinking-4bit", template: "</think>").thinking == .alwaysOn)137        #expect(ModelFamilyAdapter.resolve(modelType: "lfm2", modelID: "LFM2-1.2B-4bit", template: "x").thinking == .none)138        #expect(ModelFamilyAdapter.resolve(modelType: "lfm2", modelID: "LFM2.5-1.2B-Instruct-4bit", template: "x").thinking == .none)139    }140141    @Test func visionLimitsComeFromTheFamilyTable() {142        let gemma = ModelFamilyAdapter.resolve(modelType: "gemma3", modelID: "gemma-3-4b-it-4bit", template: nil, hasVision: true)143        #expect(gemma.vision?.maxImages == 4 && gemma.vision?.supportsMultipleImages == true && gemma.vision?.processorMaxPixels == nil)144        let smol = ModelFamilyAdapter.resolve(modelType: "smolvlm", modelID: "SmolVLM2-500M-Video-Instruct-mlx", template: nil, hasVision: true)145        #expect(smol.vision?.maxImages == 1 && smol.vision?.supportsMultipleImages == false)146        let qwen = ModelFamilyAdapter.resolve(modelType: "qwen2_5_vl", modelID: "Qwen2.5-VL-3B-Instruct-4bit", template: nil, hasVision: true)147        #expect(qwen.vision?.processorMaxPixels == 768 * 28 * 28)148        // The text-only conversion of a vision family has no limits; an unknown vision architecture gets the conservative ones.149        #expect(ModelFamilyAdapter.resolve(modelType: "gemma3", modelID: "gemma-3-text-4b-it-4bit", template: nil, hasVision: false).vision == nil)150        #expect(ModelFamilyAdapter.resolve(modelType: "new_vlm", modelID: "x", template: nil, hasVision: true).vision == .conservative)151    }152153    @Test func everyTableRowIsConsistent() {154        for (type, a) in ModelFamilyAdapter.byModelType {155            #expect(!a.family.isEmpty, "\(type)")156            if a.thinking == .toggleable { #expect(a.thinkingTemplateKey != nil && !a.reasoningMarkers.isEmpty, "\(type)") }157            if a.thinking == .none { #expect(a.reasoningMarkers.isEmpty && a.thinkingTemplateKey == nil, "\(type)") }158            if let v = a.vision { #expect(v.maxImages >= 1 && v.maxLongSide >= 224 && v.maxPixels >= 224 * 224, "\(type)") }159        }160    }161162    @Test func templateOpensThinkingOnlyWhenTheGenerationPromptEndsInsideTheBlock() {163        #expect(ModelFamilyAdapter.templateOpensThinking(Self.deepSeekTemplate))164        #expect(!ModelFamilyAdapter.templateOpensThinking(Self.qwen3Template))165        #expect(!ModelFamilyAdapter.templateOpensThinking("no generation prompt here <think>"))166    }167168    @Test func loadedModelInfoReportsThinkingAndReasoningCapability() {169        var info = LoadedModelInfo(modelID: "m", directory: URL(fileURLWithPath: "/dev/null"), architecture: "qwen3", contextLength: 4096, hasVision: false,170                                   hasChatTemplate: true, templateSupportsTools: true, weightsMemoryBytes: 1, loadTime: 0, loadedAt: Date())171        #expect(info.thinking == ThinkingSupport(supported: false, toggleable: false, defaultOn: false) && !info.capabilities.contains(.reasoning) && info.maxImages == 0)172        info.thinkingBehavior = .alwaysOn173        #expect(info.thinking.supported && !info.thinking.toggleable && info.capabilities.contains(.reasoning))174        info.vision = VisionLimits(maxLongSide: 1024, maxPixels: 1 << 20, maxImages: 3)175        #expect(info.maxImages == 3)176    }177178    @Test func newMetricsFieldsAreOptionalForStoredRecords() throws {179        // A record written before the fields existed must still decode.180        let old = LocalGenerationMetrics(modelID: "m", totalTime: 1, stopReason: .endOfTurn)181        var object = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(old)) as? [String: Any])182        for key in ["timeToFirstReasoningToken", "timeToFirstAnswerToken", "answerTokens", "thinkingRequested", "thinkingApplied", "reasoningUnterminated",183                    "imageCount", "requestedContextLength", "effectiveContextLength", "contextReduction"] { object[key] = nil }184        let decoded = try JSONDecoder().decode(LocalGenerationMetrics.self, from: JSONSerialization.data(withJSONObject: object))185        #expect(decoded.modelID == "m" && decoded.timeToFirstAnswerToken == nil && decoded.contextReduction == nil)186    }187}188
Files main
Menu

Theme