diff --git a/OpenGlasses/Sources/Services/LocalLLMService.swift b/OpenGlasses/Sources/Services/LocalLLMService.swift index 98e7bfc98..e069e665b 100644 --- a/OpenGlasses/Sources/Services/LocalLLMService.swift +++ b/OpenGlasses/Sources/Services/LocalLLMService.swift @@ -82,7 +82,7 @@ final class LocalLLMService: ObservableObject { estimatedSize: "3.6 GB", hasVision: true, hasToolCalling: true, - notes: "Best on-device agent — tool calling, 140+ languages. Vision-ready architecture, but this build's vision weights don't load in the current MLX runtime (device-verified 2026-07-16) — photo questions answer text-only until a fixed build lands, then vision enables automatically. Uses ~4 GB while running.", + notes: "Best on-device agent — tool calling, 140+ languages, vision. Uses ~4 GB while running.", minimumRAMGB: 8 ), RecommendedModel( @@ -91,7 +91,7 @@ final class LocalLLMService: ObservableObject { estimatedSize: "5.1 GB", hasVision: true, hasToolCalling: true, - notes: "Bigger Gemma 4 — highest-quality on-device agent. Same vision caveat as E2B (text-only until an MLX runtime fix). Needs a high-memory device (12 GB).", + notes: "Bigger Gemma 4 — highest-quality on-device agent, with vision. Needs a high-memory device (12 GB).", minimumRAMGB: 12 ), // Vision models (can see photos from glasses) @@ -148,11 +148,13 @@ final class LocalLLMService: ObservableObject { /// Gemma 4 history: the VLM factory used to fatally trap on 1-D tokens (talk-button /// crash); mlx-swift-lm 3.31.4 made that catchable — but a device test (2026-07-15) /// showed the e2b 4-bit quant failing VLM weight mapping (`keyNotFound(language_model… - /// k_norm.weight, Gemma4RMSNormZeroShift)`). The hub configs for all three Gemma 4 - /// checkpoints declare `Gemma4ForConditionalGeneration` with a `vision_config` - /// (verified 2026-07-16), so vision is *attempted* — and a mapping failure now demotes - /// gracefully to the text factory (`loadModel`), with image turns refused honestly by - /// the vision guard in LLMService. Nothing regresses if a checkpoint doesn't cooperate. + /// k_norm.weight, Gemma4RMSNormZeroShift)`). That is fixed upstream — KV-shared layers + /// must not declare `k_proj`/`v_proj` — and the fix is pinned in `project.base.yml`, so + /// the Gemma 4 checkpoints load as the VLMs they are and vision works. + /// + /// The demotion path in `loadModel` stays as the safety net: a checkpoint that still + /// fails weight mapping loads as a perfectly good text model, and image turns are refused + /// honestly by the vision guard in LLMService rather than answered blind. nonisolated static let visionModelIds: Set = [ "mlx-community/SmolVLM2-2.2B-Instruct-mlx", "mlx-community/SmolVLM2-500M-Video-Instruct-mlx", @@ -322,7 +324,7 @@ final class LocalLLMService: ObservableObject { // own iOS guidance; set here (not init) so simulator unit tests never touch Metal. Memory.cacheLimit = 20 * 1024 * 1024 - let config = ModelConfiguration(id: modelId) + let config = Self.modelConfiguration(for: modelId) func load(with factory: any ModelFactory) async throws -> ModelContainer { try await factory.loadContainer( from: #hubDownloader(hub), @@ -342,11 +344,12 @@ final class LocalLLMService: ObservableObject { modelContainer = try await load(with: VLMModelFactory.shared) loadedViaVLMFactory = true } catch { - // The known shape of this failure is a quant whose weight tree doesn't - // match the VLM export (keyNotFound …k_norm.weight — device trace - // 2026-07-15). Whatever the cause, the model is still a perfectly good - // text model: demote for this run and load through the text factory. - // Image turns then get the honest refusal instead of a broken load. + // The known shape of this failure was a quant whose weight tree didn't match + // the VLM export (keyNotFound …k_norm.weight — device trace 2026-07-15), + // fixed upstream and pinned. Whatever the cause, a model that fails VLM + // mapping is still a perfectly good text model: demote for this run and load + // through the text factory. Image turns then get the honest refusal instead + // of a broken load. NSLog("[LocalLLM] VLM load failed for %@ — demoting to text factory: %@", modelId, error.localizedDescription) visionDemotedModelIds.insert(modelId) @@ -420,6 +423,12 @@ final class LocalLLMService: ObservableObject { // has no way to interleave image tokens. if let imageData { if loadedViaVLMFactory { + if Gemma4ChatPrompt.matches(modelId: loadedModelId) { + return try await generateGemma4Turn( + userMessage: userMessage, systemPrompt: systemPrompt, + history: history, imageData: imageData, + container: container, onToken: onToken) + } return try await generateVisionTurn( userMessage: userMessage, systemPrompt: systemPrompt, history: history, imageData: imageData, @@ -434,10 +443,36 @@ final class LocalLLMService: ObservableObject { return Self.visionWeightsUnavailableMessage } + let tokenizer = await container.tokenizer + + // A Gemma 4 that loaded through the VLM factory takes its own path even for a text + // turn: the VLM processor owns the model's chat template and the `LMInput` shape it + // expects, and hand-assembling either is how the old crashes happened. History is + // still budgeted first — measured with the same render the processor's template + // produces, so the count matches what the model will actually see. + if loadedViaVLMFactory && Gemma4ChatPrompt.matches(modelId: loadedModelId) { + let budget = LocalModelBudget.promptBudget(for: loadedModelId) + let trimmedHistory = try LocalModelBudget.historyFittingBudget( + history: history, budget: budget + ) { hist in + let text = Gemma4ChatPrompt.render( + system: systemPrompt, history: hist, userMessage: userMessage, + bosToken: tokenizer.bosToken) + return tokenizer.encode(text: text, addSpecialTokens: false).count + } + if trimmedHistory.count < history.count { + NSLog("🔬 LocalLLM.generate trimmed history %d→%d turns to fit budget %d", + history.count, trimmedHistory.count, budget) + } + return try await generateGemma4Turn( + userMessage: userMessage, systemPrompt: systemPrompt, + history: trimmedHistory, imageData: nil, + container: container, onToken: onToken) + } + // Tokenize a candidate history exactly as the model will — chat template, with the // no-system-role fallback some small models need. Used both to measure truncation // candidates and to produce the final token ids. - let tokenizer = await container.tokenizer func tokenize(_ hist: [(role: String, content: String)]) throws -> [Int] { var messages: [[String: String]] = [["role": "system", "content": systemPrompt]] for turn in hist { messages.append(["role": turn.role, "content": turn.content]) } @@ -445,6 +480,17 @@ final class LocalLLMService: ObservableObject { do { return try tokenizer.applyChatTemplate(messages: messages) } catch { + // Gemma 4's `chat_template.jinja` uses constructs swift-jinja's parser rejects. + // That is a *template* failure, not a "no system role" one, and the role-merging + // fallback below would be the wrong repair: render Gemma's turn format directly + // instead, which keeps the genuine system turn the template emits. + if Gemma4ChatPrompt.isTemplateParseFailure(error), + Gemma4ChatPrompt.matches(modelId: loadedModelId) { + let text = Gemma4ChatPrompt.render( + system: systemPrompt, history: hist, userMessage: userMessage, + bosToken: tokenizer.bosToken) + return tokenizer.encode(text: text, addSpecialTokens: false) + } // Merge the system prompt into the user turn for models without a system role. // No "User:" transcript label — a small model reads a speaker-labelled dialogue // and can flip roles, replying *as* the user addressed to the persona name. @@ -583,6 +629,126 @@ final class LocalLLMService: ObservableObject { return output.trimmingCharacters(in: .whitespacesAndNewlines) } + /// One turn — text or photo — on a Gemma 4 that loaded through the VLM factory. + /// + /// Everything goes through `context.processor.prepare`, which owns Gemma's chat template + /// and (for a photo) the interleaving of image soft tokens. Hand-assembling the `LMInput` + /// is the fallback, not the plan: it happens only when swift-jinja cannot parse Gemma's + /// template, and then the hand-render mirrors what the template emits — a genuine system + /// turn, `<|turn>`/`` delimiters, `assistant` mapped to `model`. + /// + /// A photo turn's prefill is one unchunked forward pass, so how much prompt it can afford + /// is a property of the device, not of the model: `LocalModelBudget.multimodalTurnPlan` + /// decides, and a roomy phone keeps its configured prompt and history. + private func generateGemma4Turn( + userMessage: String, + systemPrompt: String, + history: [(role: String, content: String)], + imageData: Data?, + container: ModelContainer, + onToken: ((String) -> Void)? + ) async throws -> String { + let parameters = Self.generateParameters(for: loadedModelId) + + // Same mid-generation backgrounding watch as the other paths, via a lock-guarded box + // because the drain runs off the main actor inside `container.perform`. + let backgroundedFlag = LockedFlag() + let bgObserver = NotificationCenter.default.addObserver( + forName: UIApplication.didEnterBackgroundNotification, + object: nil, + queue: .main + ) { _ in + backgroundedFlag.set() + } + defer { NotificationCenter.default.removeObserver(bgObserver) } + + let effectiveSystem: String + let effectiveHistory: [(role: String, content: String)] + if let photo = imageData { + let plan = LocalModelBudget.multimodalTurnPlan( + for: loadedModelId, marketingRAMGB: Self.marketingRAMGB) + effectiveSystem = plan.keepsFullSystemPrompt + ? systemPrompt + : Config.compactVisionTurnPrompt(from: systemPrompt) + effectiveHistory = plan.keepsHistory ? Array(history.suffix(4)) : [] + NSLog("🔬 LocalLLM.generateGemma4Turn model=%@ image=%dKB ram=%.0fGB fullPrompt=%@ history=%d", + loadedModelId ?? "?", photo.count / 1024, Self.marketingRAMGB, + plan.keepsFullSystemPrompt ? "yes" : "no", effectiveHistory.count) + } else { + effectiveSystem = systemPrompt + effectiveHistory = history + NSLog("🔬 LocalLLM.generateGemma4Turn model=%@ text-only", loadedModelId ?? "?") + } + + let report = LockedGenerationReport() + // `UserInput` (and any `CIImage` in it) isn't `Sendable`, so it is built inside the + // `@Sendable` closure from Sendable ingredients only. + let output = try await container.perform { context -> String in + var chat: [Chat.Message] = [.system(effectiveSystem)] + for turn in effectiveHistory { + chat.append(turn.role == "assistant" ? .assistant(turn.content) : .user(turn.content)) + } + if let imageData { + guard let ciImage = CIImage(data: imageData) else { + throw LocalLLMError.generationFailed("Couldn't decode the photo.") + } + chat.append(.user(userMessage, images: [.ciImage(ciImage)])) + } else { + chat.append(.user(userMessage)) + } + + // No forced resize: Gemma's processor picks an aspect-preserving canvas and its own + // per-image token count, and pre-squashing to 896² neither shrinks that count nor + // improves the crop — it just spends preprocessing on a phone photo twice. + let userInput = UserInput(chat: chat) + let lmInput: LMInput + do { + lmInput = try await context.processor.prepare(input: userInput) + } catch { + // Only the text turn can be rescued by hand: a photo turn's soft tokens can + // only be produced by the processor, so a failure there has to surface. + guard imageData == nil, Gemma4ChatPrompt.isTemplateParseFailure(error) else { throw error } + let text = Gemma4ChatPrompt.render( + system: effectiveSystem, history: effectiveHistory, userMessage: userMessage, + bosToken: context.tokenizer.bosToken) + let tokens = context.tokenizer.encode(text: text, addSpecialTokens: false) + // VLM-factory shape: (1, L). The mask must be explicit — a nil mask reaches + // Metal as a null buffer. + let promptArray = Self.tokenBatch(tokens, isVisionModel: true) + lmInput = LMInput(text: .init(tokens: promptArray, + mask: ones(like: promptArray).asType(.int8))) + } + + NSLog("🔬 LocalLLM.generateGemma4Turn tokenIDs.shape=%@ count=%d", + "\(lmInput.text.tokens.shape)", lmInput.text.tokens.size) + + let stream = try MLXLMCommon.generate( + input: lmInput, parameters: parameters, context: context) + var iterator = stream.makeAsyncIterator() + return try await Self.drainTokenStream( + nextChunk: { + while let generation = await iterator.next() { + if case .chunk(let text) = generation { return text } + if case .info(let info) = generation { report.note(info) } + } + return nil + }, + isBackgrounded: { backgroundedFlag.isSet }, + onToken: { chunk in + report.noteToken(at: Date()) + onToken?(chunk) + } + ) + } + if let firstTokenAt = report.firstTokenAt { TurnRecorder.mark(.firstToken, at: firstTokenAt) } + if let completion = report.completion { + TurnRecorder.addGeneration(tokens: completion.generationTokenCount, seconds: completion.generateTime) + } + NSLog("🔬 LocalLLM.generateGemma4Turn done — mlx active=%dMB cache=%dMB", + Memory.activeMemory / 1_048_576, Memory.cacheMemory / 1_048_576) + return output.trimmingCharacters(in: .whitespacesAndNewlines) + } + /// One image turn through a VLM-factory model. The processor owns the chat template and /// image tokenization; history is kept short (image tokens are big) and un-budgeted — the /// processor's own encoding is the authority on how many tokens the image costs. @@ -680,6 +846,19 @@ final class LocalLLMService: ObservableObject { ) } + /// Load configuration for a model id. + /// + /// Gemma 4 needs `` declared as an extra stop token: its `tokenizer_config.json` + /// sets `eos_token` to `` while the chat template ends every turn with the separate + /// `eot_token` ``. Without it the model runs straight through the end of its answer + /// into a hallucinated next turn. + nonisolated static func modelConfiguration(for modelId: String) -> ModelConfiguration { + if Gemma4ChatPrompt.matches(modelId: modelId) { + return ModelConfiguration(id: modelId, extraEOSTokens: [Gemma4ChatPrompt.endOfTurnToken]) + } + return ModelConfiguration(id: modelId) + } + /// Shape token ids for the loaded model (see the call site in `generate` for why): /// 1D (L,) for text-factory models — their chunked prefill slices axis 0 and an explicit /// batch axis fatally breaks prompts over the prefill step size; (1, L) for vision-factory @@ -962,3 +1141,72 @@ final class LockedGenerationReport: @unchecked Sendable { return info } } + +/// Gemma 4's turn format, rendered by hand. +/// +/// The model's real chat template lives in `chat_template.jinja` (not `tokenizer_config.json`) +/// and swift-jinja's parser rejects some of what it uses. This is the fallback for that case, +/// and it is a faithful transcription of the template rather than a generic "chat transcript": +/// +/// - `<|turn>` opens a turn and `` closes it — `sot_token`/`eot_token` in the +/// checkpoint's `tokenizer_config.json`, distinct from its `eos_token` (``). +/// - The system prompt is a **genuine system turn**, not merged into the first user turn. The +/// template emits `<|turn>system\n…` whenever message 0 is a system/developer message. +/// - `assistant` is renamed to `model`, and every body is trimmed. +/// - The generation prompt is a bare `<|turn>model\n`. +/// +/// No speaker labels ("User:", "Assistant:") appear anywhere — a small model reading a +/// labelled dialogue can flip roles and answer *as* the wearer. +enum Gemma4ChatPrompt { + /// Start-of-turn marker (`sot_token`). + static let startOfTurnToken = "<|turn>" + /// End-of-turn marker (`eot_token`) — must also be declared as an extra EOS token, since + /// the checkpoint's `eos_token` is the different ``. + static let endOfTurnToken = "" + + /// Whether a model id is a Gemma 4 checkpoint. Matched on the id (both hub casings of the + /// E-series appear in the wild) rather than a fixed list, so a user-typed Gemma 4 id gets + /// the same handling as a catalog one. + static func matches(modelId: String?) -> Bool { + guard let id = modelId?.lowercased() else { return false } + return id.contains("gemma-4") || id.contains("gemma4") + } + + /// Whether an error is the template failing to *parse*, as opposed to any other failure + /// from `applyChatTemplate` / `processor.prepare`. + /// + /// Matched on the error's description because the Jinja error type is not part of this + /// target's dependency surface; both observed shapes are covered — the wrapped + /// `parser("…")` case and a bare `Unexpected token …` message. + static func isTemplateParseFailure(_ error: Error) -> Bool { + let text = String(describing: error) + return text.contains("parser(") || text.contains("Unexpected token") + } + + /// Render a turn in Gemma 4's format. `bosToken` is prepended when the tokenizer has one, + /// because the caller encodes with `addSpecialTokens: false` (the template emits + /// `bos_token` itself, and letting both add it would double it). + static func render( + system: String, + history: [(role: String, content: String)], + userMessage: String, + bosToken: String? + ) -> String { + var out = bosToken ?? "" + let sys = system.trimmingCharacters(in: .whitespacesAndNewlines) + if !sys.isEmpty { + appendTurn(&out, role: "system", body: sys) + } + for turn in history { + appendTurn(&out, role: turn.role == "assistant" ? "model" : turn.role, body: turn.content) + } + appendTurn(&out, role: "user", body: userMessage) + out += "\(startOfTurnToken)model\n" + return out + } + + private static func appendTurn(_ out: inout String, role: String, body: String) { + let trimmed = body.trimmingCharacters(in: .whitespacesAndNewlines) + out += "\(startOfTurnToken)\(role)\n\(trimmed)\(endOfTurnToken)\n" + } +} diff --git a/OpenGlasses/Sources/Services/LocalModelBudget.swift b/OpenGlasses/Sources/Services/LocalModelBudget.swift index ea9ba7b71..8ba02790a 100644 --- a/OpenGlasses/Sources/Services/LocalModelBudget.swift +++ b/OpenGlasses/Sources/Services/LocalModelBudget.swift @@ -85,6 +85,49 @@ enum LocalModelBudget { /// Floor so a tiny/misconfigured window still admits the minimal system + turn prompt. static let minimumBudget = 512 + // MARK: - Multimodal (image) turns + + /// What survives a multimodal turn on this device. + /// + /// A text prefill is chunked, so a fat prompt costs time rather than a memory spike. A + /// *multimodal* prefill is one unchunked forward: the whole prompt plus the image's soft + /// tokens are resident together, and that is what Jetsam-kills a small-RAM phone mid-Metal. + /// The mitigation is real, but it is a small-device mitigation — a 12 GB phone has the + /// headroom and should keep its configured prompt, its tools and its history. + struct MultimodalTurnPlan: Equatable { + /// Keep prior turns in the prompt. Off on the constrained tier: history tokens compete + /// with the image's soft tokens in the same unchunked pass. + let keepsHistory: Bool + /// Keep the wearer's full configured system prompt (persona, tool block, house style). + /// Off on the constrained tier, which falls back to `Config.compactVisionTurnPrompt`. + let keepsFullSystemPrompt: Bool + /// Tokenized-prompt ceiling for the turn. + let promptBudget: Int + } + + /// Marketing RAM (GB) at or above which a phone carries a full multimodal turn. Below it, + /// the turn is trimmed. 12 GB is the same tier line the model catalog already draws for the + /// larger Gemma 4 checkpoint, so there is one notion of "roomy device", not two. + static let multimodalFullPromptRAMGB: Double = 12 + + /// Fraction of the text budget a constrained device allows a multimodal prompt. The image's + /// soft tokens are not in our token count but are in the model's, so the prompt has to leave + /// room for them. + static let constrainedMultimodalBudgetFraction = 0.25 + + /// Per-device plan for an image turn. Pure — the caller supplies the device's RAM, so this + /// is exercised headlessly at both tiers. + static func multimodalTurnPlan(for modelId: String?, marketingRAMGB: Double) -> MultimodalTurnPlan { + let full = promptBudget(for: modelId) + guard marketingRAMGB < multimodalFullPromptRAMGB else { + return MultimodalTurnPlan(keepsHistory: true, keepsFullSystemPrompt: true, promptBudget: full) + } + return MultimodalTurnPlan( + keepsHistory: false, + keepsFullSystemPrompt: false, + promptBudget: max(minimumBudget, Int(Double(full) * constrainedMultimodalBudgetFraction))) + } + /// Trim conversation history so the tokenized prompt fits `budget`, dropping the **oldest** /// turns first (the current user turn and system prompt are never dropped). Pure: the caller /// injects `tokenCount`, which tokenizes a candidate history the same way the model will. diff --git a/OpenGlasses/Sources/Utils/Config.swift b/OpenGlasses/Sources/Utils/Config.swift index 1574fe3c8..84871d8ef 100644 --- a/OpenGlasses/Sources/Utils/Config.swift +++ b/OpenGlasses/Sources/Utils/Config.swift @@ -602,6 +602,42 @@ struct Config { - If you hit a dead end, offer the next best option instead of giving up. """ + /// Compact system prompt for an on-device photo turn on a memory-constrained device. + /// + /// A multimodal prefill is one unchunked forward pass — the whole prompt plus the image's + /// soft tokens are resident at once — so on a small-RAM phone the full agent prompt is what + /// tips the turn into a Jetsam kill. Roomier devices keep their configured prompt; this is + /// only what the constrained tier falls back to (`LocalModelBudget.multimodalTurnPlan`). + /// + /// It is *derived*, not hardcoded: the configured prompt's opening line carries the + /// assistant's identity in every preset, so the persona survives the trim, and the wearer's + /// language is stated explicitly rather than implied by an English literal. + static func compactVisionTurnPrompt( + from systemPrompt: String, + languageCode: String = preferredLanguageCode + ) -> String { + var lines: [String] = [] + let identity = systemPrompt + .split(separator: "\n", omittingEmptySubsequences: true) + .first + .map { $0.trimmingCharacters(in: .whitespaces) } ?? "" + if !identity.isEmpty { lines.append(identity) } + lines.append("A photo from the glasses camera is attached. You CAN see it — never say you lack vision.") + lines.append("Answer in 1–2 short spoken sentences. Name the main subject and anything asked. Skip background, lighting, and composition unless asked.") + lines.append("If asked to read text: quote it verbatim; translate only if asked.") + if let language = spokenLanguageName(for: languageCode) { + lines.append("Answer in \(language).") + } + return lines.joined(separator: "\n") + } + + /// The wearer's language, named in English for a prompt — `nil` when it is already English + /// (the surrounding instructions are English, so the line would only spend tokens). + static func spokenLanguageName(for languageCode: String) -> String? { + guard languageCode != "en" else { return nil } + return Locale(identifier: "en").localizedString(forLanguageCode: languageCode) ?? languageCode + } + /// Returns the active preset's prompt, falling back to default. static var systemPrompt: String { if let preset = activePreset { @@ -3459,10 +3495,10 @@ struct Config { /// Whether fast-tier queries may run on the *on-device* MLX agent model. /// /// Historically default-off because the gemma-4 agent model fatally crashed during - /// inference: it was mis-routed through `VLMModelFactory` (see - /// `LocalLLMService.visionModelIds`) into the uncatchable `MLXVLM.Gemma4` trap. That - /// routing is fixed — the model now loads as text — but the default stays off pending - /// on-device confirmation that the text path generates cleanly. Cloud agents are unaffected. + /// inference: the VLM factory could not map its weights, and the fallbacks around that + /// failure were where the crashes lived. The upstream load fix is now pinned (see + /// `project.base.yml`), but the default stays off pending on-device confirmation that a + /// full turn generates cleanly. Cloud agents are unaffected. @UserDefaultsBacked("localAgentEnabled", default: false) static var localAgentEnabled: Bool static func setLocalAgentEnabled(_ value: Bool) { localAgentEnabled = value } diff --git a/OpenGlassesTests/Gemma4ChatPromptTests.swift b/OpenGlassesTests/Gemma4ChatPromptTests.swift new file mode 100644 index 000000000..a66d1f5f0 --- /dev/null +++ b/OpenGlassesTests/Gemma4ChatPromptTests.swift @@ -0,0 +1,217 @@ +import XCTest +@testable import OpenGlasses + +/// Gemma 4's prompt format, its stop token, and the device tiering around a photo turn. +/// +/// All of it is deliberately pure: the model itself is multi-gigabyte and MLX has no Metal on +/// the simulator, so what is testable here is the *contract* the on-device path depends on — +/// what the rendered turn looks like, what counts as a template-parse failure, and how much of +/// a turn a given phone is allowed to carry. +final class Gemma4ChatPromptTests: XCTestCase { + + // MARK: - Model id matching + + func testMatchesGemma4Ids() { + XCTAssertTrue(Gemma4ChatPrompt.matches(modelId: "mlx-community/gemma-4-e2b-it-4bit")) + // The community page uses a capital E for the E-series; the catalog uses lowercase. + XCTAssertTrue(Gemma4ChatPrompt.matches(modelId: "mlx-community/gemma-4-E2B-it-4bit")) + XCTAssertTrue(Gemma4ChatPrompt.matches(modelId: "mlx-community/gemma-4-e4b-it-4bit")) + XCTAssertFalse(Gemma4ChatPrompt.matches(modelId: "mlx-community/gemma-3-4b-it-qat-4bit")) + XCTAssertFalse(Gemma4ChatPrompt.matches(modelId: "mlx-community/gemma-2-2b-it-4bit")) + XCTAssertFalse(Gemma4ChatPrompt.matches(modelId: "mlx-community/Qwen2.5-3B-Instruct-4bit")) + XCTAssertFalse(Gemma4ChatPrompt.matches(modelId: nil)) + } + + /// Every Gemma 4 id the catalog offers must take the Gemma path, or a checkpoint would load + /// with the wrong stop token and run past the end of its answer. + @MainActor + func testEveryCatalogGemma4TakesTheGemmaPath() { + let gemmaIds = LocalLLMService.recommendedModels + .map(\.id) + .filter { $0.lowercased().contains("gemma-4") } + XCTAssertFalse(gemmaIds.isEmpty, "catalog should still offer Gemma 4") + for id in gemmaIds { + XCTAssertTrue(Gemma4ChatPrompt.matches(modelId: id), id) + } + } + + // MARK: - Rendering + + func testRenderSystemUser() { + let text = Gemma4ChatPrompt.render( + system: "You are helpful.", + history: [], + userMessage: "What's the quickest route to Istanbul", + bosToken: "") + XCTAssertEqual( + text, + "<|turn>system\nYou are helpful.\n" + + "<|turn>user\nWhat's the quickest route to Istanbul\n" + + "<|turn>model\n") + } + + /// The system prompt is a genuine system TURN, exactly as `chat_template.jinja` emits it — + /// not merged into the first user turn. Merging is the role-flip hazard: the model reads a + /// persona description as something the wearer said and answers in the wearer's voice. + func testSystemPromptIsItsOwnTurnNotMergedIntoTheUserTurn() { + let text = Gemma4ChatPrompt.render( + system: "You are OpenGlasses.", + history: [], + userMessage: "Hello", + bosToken: nil) + XCTAssertTrue(text.hasPrefix("<|turn>system\nYou are OpenGlasses.\n")) + XCTAssertFalse(text.contains("You are OpenGlasses.\n\nHello")) + } + + func testRenderHistoryMapsAssistantToModel() { + let text = Gemma4ChatPrompt.render( + system: "", + history: [ + (role: "user", content: "Hi"), + (role: "assistant", content: "Hello"), + ], + userMessage: "Next", + bosToken: nil) + XCTAssertEqual( + text, + "<|turn>user\nHi\n<|turn>model\nHello\n<|turn>user\nNext\n<|turn>model\n") + } + + /// An empty system prompt emits no system turn at all (the template only opens one when + /// message 0 is a system message), and the BOS token is omitted when the tokenizer has none. + func testEmptySystemAndNoBosProduceNoScaffolding() { + let text = Gemma4ChatPrompt.render( + system: " \n ", history: [], userMessage: "Hi", bosToken: nil) + XCTAssertEqual(text, "<|turn>user\nHi\n<|turn>model\n") + } + + /// No "User:"/"Assistant:" transcript labels anywhere — a small model reading a labelled + /// dialogue can flip roles and reply *as* the wearer. + func testRenderUsesNoSpeakerLabels() { + let text = Gemma4ChatPrompt.render( + system: "Persona.", + history: [(role: "user", content: "Hi"), (role: "assistant", content: "Hello")], + userMessage: "Next", + bosToken: "") + XCTAssertFalse(text.contains("User:")) + XCTAssertFalse(text.contains("Assistant:")) + XCTAssertFalse(text.contains("Model:")) + } + + /// The render always ends on the generation prompt, so the model continues rather than + /// opening a turn of its own. + func testRenderEndsOnTheGenerationPrompt() { + let text = Gemma4ChatPrompt.render( + system: "S", history: [], userMessage: "U", bosToken: nil) + XCTAssertTrue(text.hasSuffix("<|turn>model\n")) + } + + // MARK: - Stop token + + /// `` is the checkpoint's `eot_token`, and its `eos_token` is the different `` — + /// so it has to be declared explicitly or generation runs past the end of the answer. + func testGemma4ConfigurationAddsTurnStop() { + XCTAssertEqual( + LocalLLMService.modelConfiguration(for: "mlx-community/gemma-4-e2b-it-4bit").extraEOSTokens, + [""]) + XCTAssertEqual(Gemma4ChatPrompt.endOfTurnToken, "") + } + + func testNonGemmaConfigurationAddsNoExtraStops() { + XCTAssertTrue( + LocalLLMService.modelConfiguration(for: "mlx-community/Qwen2.5-3B-Instruct-4bit") + .extraEOSTokens.isEmpty) + XCTAssertTrue( + LocalLLMService.modelConfiguration(for: "mlx-community/SmolVLM2-2.2B-Instruct-mlx") + .extraEOSTokens.isEmpty) + } + + // MARK: - Template parse failure + + /// The Jinja error type isn't in this target's dependency surface, so the classifier reads + /// the error's description. These fixtures reproduce the two shapes seen from Gemma 4's + /// template; anything else must fall through to the ordinary no-system-role repair. + func testTemplateParseFailureRecognisesJinjaShapesOnly() { + struct DescribedError: Error, CustomStringConvertible { let description: String } + + XCTAssertTrue(Gemma4ChatPrompt.isTemplateParseFailure( + DescribedError(description: #"parser("Unexpected token for primary expression: modulo")"#))) + XCTAssertTrue(Gemma4ChatPrompt.isTemplateParseFailure( + DescribedError(description: "Unexpected token for primary expression: modulo"))) + XCTAssertFalse(Gemma4ChatPrompt.isTemplateParseFailure( + DescribedError(description: "The glasses camera is not connected."))) + XCTAssertFalse(Gemma4ChatPrompt.isTemplateParseFailure( + LocalLLMError.modelNotLoaded)) + // A "no system role" template failure must NOT be mistaken for a parse failure — those + // models want the merge repair, not Gemma's turn format. + XCTAssertFalse(Gemma4ChatPrompt.isTemplateParseFailure( + DescribedError(description: "chatTemplate(\"System role not supported\")"))) + } + + // MARK: - Device tiering for a photo turn + + /// A roomy phone keeps its configured prompt and its history: the memory workaround is a + /// small-device workaround, and charging a 12 GB phone for an 8 GB phone's problem costs + /// persona, tools and context for nothing. + func testRoomyDeviceKeepsTheWholeMultimodalTurn() { + let plan = LocalModelBudget.multimodalTurnPlan( + for: "mlx-community/gemma-4-e2b-it-4bit", marketingRAMGB: 12) + XCTAssertTrue(plan.keepsFullSystemPrompt) + XCTAssertTrue(plan.keepsHistory) + XCTAssertEqual(plan.promptBudget, + LocalModelBudget.promptBudget(for: "mlx-community/gemma-4-e2b-it-4bit")) + } + + func testConstrainedDeviceTrimsTheMultimodalTurn() { + let id = "mlx-community/gemma-4-e2b-it-4bit" + let plan = LocalModelBudget.multimodalTurnPlan(for: id, marketingRAMGB: 8) + XCTAssertFalse(plan.keepsFullSystemPrompt) + XCTAssertFalse(plan.keepsHistory) + XCTAssertLessThan(plan.promptBudget, LocalModelBudget.promptBudget(for: id)) + XCTAssertGreaterThanOrEqual(plan.promptBudget, LocalModelBudget.minimumBudget) + } + + /// Text turns are unaffected by the tiering — their prefill is chunked, so a fat prompt + /// costs time rather than a resident-memory spike. + func testTextBudgetIsUnchangedByDeviceRAM() { + let id = "mlx-community/gemma-4-e2b-it-4bit" + XCTAssertEqual(LocalModelBudget.promptBudget(for: id), 4096 - 512 - 128) + } + + // MARK: - Compact photo-turn prompt + + /// The reduced prompt is derived, not hardcoded: the configured prompt's identity line + /// survives, so a custom persona isn't silently replaced on every photo question. + func testCompactVisionPromptKeepsThePersonaLine() { + let configured = """ + You are Ada, a birding assistant on smart glasses. + + RESPONSE STYLE: + - Be brief. + """ + let compact = Config.compactVisionTurnPrompt(from: configured, languageCode: "en") + XCTAssertTrue(compact.hasPrefix("You are Ada, a birding assistant on smart glasses.")) + XCTAssertTrue(compact.contains("You CAN see it")) + XCTAssertLessThan(compact.count, configured.count + 400) + XCTAssertFalse(compact.contains("RESPONSE STYLE")) + } + + /// A non-English wearer keeps their language. The old shape of this fix replaced the whole + /// prompt with an English literal, which silently switched them to English on every photo. + func testCompactVisionPromptNamesTheWearersLanguage() { + let compact = Config.compactVisionTurnPrompt(from: "You are OpenGlasses.", languageCode: "ja") + XCTAssertTrue(compact.contains("Answer in Japanese."), compact) + } + + func testCompactVisionPromptOmitsTheLanguageLineForEnglish() { + let compact = Config.compactVisionTurnPrompt(from: "You are OpenGlasses.", languageCode: "en") + XCTAssertFalse(compact.contains("Answer in English.")) + XCTAssertNil(Config.spokenLanguageName(for: "en")) + } + + func testCompactVisionPromptSurvivesAnEmptySystemPrompt() { + let compact = Config.compactVisionTurnPrompt(from: "", languageCode: "en") + XCTAssertFalse(compact.isEmpty) + XCTAssertTrue(compact.contains("You CAN see it")) + } +} diff --git a/OpenGlassesTests/LocalModelRoutingTests.swift b/OpenGlassesTests/LocalModelRoutingTests.swift index 3907cff6b..79c526f29 100644 --- a/OpenGlassesTests/LocalModelRoutingTests.swift +++ b/OpenGlassesTests/LocalModelRoutingTests.swift @@ -1,10 +1,13 @@ import XCTest @testable import OpenGlasses -/// Regression guard for the talk-button / Field-Assist crash: the on-device agent model must -/// load through the TEXT factory, not the vision factory. `visionModelIds` decides that in -/// `LocalLLMService.loadModel`, so the agent model landing in that set silently routes inference -/// into mlx-swift-lm's crashing `MLXVLM.Gemma4` (an uncatchable MLX assertion). +/// Regression guard for on-device model routing, and for the prompt budget that keeps a turn +/// under the observed OOM point. +/// +/// `visionModelIds` decides which factory `LocalLLMService.loadModel` tries first. Gemma 4 is in +/// that set because it *is* a VLM; what used to make that dangerous — a wrong token shape through +/// the VLM forward pass — is now keyed off `loadedViaVLMFactory`, the factory that actually +/// loaded, so a checkpoint that fails VLM weight mapping demotes to text without a shape mismatch. @MainActor final class LocalModelRoutingTests: XCTestCase { diff --git a/Package.resolved b/Package.resolved index e59de6d1f..91282374d 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "18e3260711c0130c5c74b2ecf73b3387b67fb41621ecbcb8aa9eb73917aefae6", + "originHash" : "8bbceb54bc83290e094582502a07f09bfd380732ff7ec4a45ee2beb66682d9bb", "pins" : [ { "identity" : "haishinkit.swift", @@ -42,8 +42,7 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/ml-explore/mlx-swift-lm.git", "state" : { - "branch" : "main", - "revision" : "702e5a0eaf990e1f6d3db2b6e7d8872858a44055" + "revision" : "d6614025fa1f6133e34c4fe0cea2815d672d8742" } }, { diff --git a/Package.swift b/Package.swift index 813cefb5d..5c0c61629 100644 --- a/Package.swift +++ b/Package.swift @@ -11,8 +11,11 @@ let package = Package( .package(url: "https://github.com/facebook/meta-wearables-dat-ios.git", from: "0.7.0"), // HaishinKit — RTMP live streaming .package(url: "https://github.com/shogo4405/HaishinKit.swift.git", from: "2.2.5"), - // MLX Swift LM — on-device LLM inference - .package(url: "https://github.com/ml-explore/mlx-swift-lm.git", branch: "main"), + // MLX Swift LM — on-device LLM inference. Pinned to the same revision as + // `project.base.yml` (see the note there): no released tag carries the Gemma 4 + // VLM load fix, and a floating branch would silently move under us. + .package(url: "https://github.com/ml-explore/mlx-swift-lm.git", + revision: "d6614025fa1f6133e34c4fe0cea2815d672d8742"), // WebRTC — real peer-to-peer expert transport (Plan L) .package(url: "https://github.com/stasel/WebRTC.git", from: "120.0.0"), ], diff --git a/ci_scripts/Package.resolved b/ci_scripts/Package.resolved index 549b0743a..bd5abe4f3 100644 --- a/ci_scripts/Package.resolved +++ b/ci_scripts/Package.resolved @@ -5,8 +5,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/mattt/EventSource.git", "state" : { - "revision" : "a3a85a85214caf642abaa96ae664e4c772a59f6e", - "version" : "1.4.1" + "revision" : "86b5096ac59ab46e66bd1f6377c604bc1dab0bc2", + "version" : "1.5.1" } }, { @@ -50,8 +50,7 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/ml-explore/mlx-swift-lm.git", "state" : { - "revision" : "1c05248bb0899e2a7a4962b84d319cf12f4e12aa", - "version" : "3.31.3" + "revision" : "d6614025fa1f6133e34c4fe0cea2815d672d8742" } }, { @@ -68,17 +67,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-asn1.git", "state" : { - "revision" : "eb50cbd14606a9161cbc5d452f18797c90ef0bab", - "version" : "1.7.0" - } - }, - { - "identity" : "swift-atomics", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-atomics.git", - "state" : { - "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7", - "version" : "1.3.0" + "revision" : "a9a5efd40eaf558a2bcd48d64b1d1646be686008", + "version" : "1.7.1" } }, { @@ -86,8 +76,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections.git", "state" : { - "revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a", - "version" : "1.5.1" + "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", + "version" : "1.6.0" } }, { @@ -95,8 +85,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-crypto.git", "state" : { - "revision" : "1b6b2e274e85105bfa155183145a1dcfd63331f1", - "version" : "4.5.0" + "revision" : "47d3869a7291f085c1fb9fb1e6d3b97a793f45c6", + "version" : "4.5.1" } }, { @@ -113,17 +103,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/huggingface/swift-jinja.git", "state" : { - "revision" : "0b67ecb79139f6addef8699eff3622808aa6c7dc", - "version" : "2.3.6" - } - }, - { - "identity" : "swift-nio", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-nio.git", - "state" : { - "revision" : "57c0a08a331aaea9f5d7a932ad94ef43be942a95", - "version" : "2.100.0" + "revision" : "7d0b8880ef8e567dd4e0089f8b99fb354129017c", + "version" : "2.4.2" } }, { @@ -140,17 +121,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax.git", "state" : { - "revision" : "0687f71944021d616d34d922343dcef086855920", - "version" : "600.0.1" - } - }, - { - "identity" : "swift-system", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-system.git", - "state" : { - "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", - "version" : "1.6.4" + "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1", + "version" : "603.0.2" } }, { diff --git a/project.base.yml b/project.base.yml index 236f59159..53ae23fb3 100644 --- a/project.base.yml +++ b/project.base.yml @@ -69,7 +69,18 @@ packages: from: "2.2.5" mlx-swift-lm: url: https://github.com/ml-explore/mlx-swift-lm.git - version: "3.31.3" + # Pinned to a revision, not a tag, and deliberately: the Gemma 4 VLM load failure + # (`keyNotFound(…k_norm.weight, Gemma4RMSNormZeroShift)` — KV-shared layers must not + # declare k_proj/v_proj) is fixed upstream in 09deb8c, and no released tag contains it — + # the newest, 3.31.4, predates it. Go back to `version:` as soon as a tag ships that does. + # + # Why *this* revision and not upstream's tip: the next commit after it (14414441) retargets + # MLXFoundationModels at the Xcode 27 beta 5 SDK (27A5237l), and MLXHuggingFace — which we + # link for `#hubDownloader` — pulls that module in through a default-on package trait. On an + # earlier 27.0 beta the retarget does not compile (`updateMetadata` takes + # `[String: any Sendable & Codable & Equatable]` there, not `ConvertibleToGeneratedContent`). + # So: on beta 5 or later, move to 14414441 or newer; before it, stay here. + revision: d6614025fa1f6133e34c4fe0cea2815d672d8742 swift-huggingface: # Same 0.x exposure as the DAT SDK, and it already drifted: the spec said `from: "0.1.0"` while # Package.resolved had walked to 0.9.0 — eight minor versions of a pre-1.0 package, adopted