Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 262 additions & 14 deletions OpenGlasses/Sources/Services/LocalLLMService.swift

Large diffs are not rendered by default.

43 changes: 43 additions & 0 deletions OpenGlasses/Sources/Services/LocalModelBudget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 40 additions & 4 deletions OpenGlasses/Sources/Utils/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 }
Expand Down
217 changes: 217 additions & 0 deletions OpenGlassesTests/Gemma4ChatPromptTests.swift
Original file line number Diff line number Diff line change
@@ -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: "<bos>")
XCTAssertEqual(
text,
"<bos><|turn>system\nYou are helpful.<turn|>\n"
+ "<|turn>user\nWhat's the quickest route to Istanbul<turn|>\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.<turn|>\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<turn|>\n<|turn>model\nHello<turn|>\n<|turn>user\nNext<turn|>\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<turn|>\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: "<bos>")
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

/// `<turn|>` is the checkpoint's `eot_token`, and its `eos_token` is the different `<eos>` —
/// 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,
["<turn|>"])
XCTAssertEqual(Gemma4ChatPrompt.endOfTurnToken, "<turn|>")
}

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"))
}
}
11 changes: 7 additions & 4 deletions OpenGlassesTests/LocalModelRoutingTests.swift
Original file line number Diff line number Diff line change
@@ -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 {

Expand Down
5 changes: 2 additions & 3 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
],
Expand Down
Loading
Loading