Skip to content

Make local Gemma 4 load and parse correctly - #344

Merged
straff2002 merged 1 commit into
mainfrom
feat/dh1-gemma-load-parse
Aug 25, 2026
Merged

straff2002 merged 1 commit into
mainfrom
feat/dh1-gemma-load-parse

Conversation

@straff2002

Copy link
Copy Markdown
Owner

Local Gemma 4 has been the on-device catalog's headline agent while quietly not working. Three separate causes, all fixed here, so the keyless tier has a real assistant on any phone that runs MLX.

What

Load. The VLM weight-mapping failure (keyNotFound(…k_norm.weight, Gemma4RMSNormZeroShift)) is fixed upstream — KV-shared layers must not declare k_proj/v_proj (mlx-swift-lm 09deb8c). No released tag carries it (the newest, 3.31.4, predates it), so the package moves from a tag to a revision: project.base.yml, Package.swift, Package.resolved and ci_scripts/Package.resolved (regenerated with Scripts/update-package-resolved.sh, not hand-edited).

The pin is d661402, one commit short of what #331 chose, deliberately. The next commit (1441444) retargets MLXFoundationModels at the Xcode 27 beta 5 SDK (27A5237l) and does not compile against earlier 27.0 betas — updateMetadata takes [String: any Sendable & Codable & Equatable] there rather than ConvertibleToGeneratedContent. MLXHuggingFace pulls that module in through a default-on package trait, so the whole build fails on it. Verified: pinning 1441444 fails to build on this toolchain (27A5228h); d661402 builds and still contains the Gemma fix. The comment on the pin says when to move it forward.

Parse. Gemma 4's real chat template lives in chat_template.jinja and uses constructs swift-jinja's parser rejects. Gemma4ChatPrompt renders it by hand as the fallback — a genuine system turn (not merged into the first user turn), <|turn>/<turn|> delimiters, assistant renamed to model, no speaker labels anywhere. A template parse failure no longer falls into the generic no-system-role repair, which is what used to flatten the persona into the wearer's turn.

Stop. <turn|> is the checkpoint's eot_token while its eos_token is the different <eos>, so it is declared through LocalLLMService.modelConfiguration. Without it the model runs past the end of its answer into a hallucinated next turn.

A Gemma 4 loaded through the VLM factory now takes one path for both text and photo turns, through the processor that owns its template and image tokenization; the hand-render is the fallback inside that path, not a parallel one.

Memory pressure, tiered

A photo turn's prefill is one unchunked forward pass, so how much prompt it can carry is a property of the device, not the model. LocalModelBudget.multimodalTurnPlan decides: a 12 GB phone keeps its configured prompt and history; below that the turn is trimmed and the budget is scaled down. And the trimmed prompt is derived, not a hardcoded English literal — Config.compactVisionTurnPrompt keeps the configured prompt's identity line so a custom persona survives, and names the wearer's language explicitly so a non-English wearer isn't silently switched to English on every photo question.

Credit

Gemma chat-template and parsing fixes ported from #331 by @exadeci, re-composed onto current main (the files moved since that branch, and the review conditions are applied rather than the code taken verbatim).

Taken: the hand-rendered chat template and its tests, the <turn|> stop token, the VLM-processor turn path, the aspect-preserving image handling (no forced 896² pre-resize), the stale vision caveat coming off the two Gemma 4 catalog entries.

Left, and why:

  • Unconditional prompt/history/tool stripping — routed through marketingRAMGB + LocalModelBudget instead, so a roomy phone doesn't pay for a tight one's problem.
  • English literal photo prompt — derived from the configured prompt and the wearer's language instead, and it lives with the other prompts in Config.swift.
  • The sendLocal imageData == nil change — redundant for Gemma 4 (its turn path already empties both downstream) and a straight regression for SmolVLM2, which has no unchunked-prefill problem. Dropped.
  • The direct swift-jinja dependency — nothing imports Jinja, and 2.4.2 (the version Gemma fix #331 pinned) already resolves transitively through swift-transformers 1.3.3. Adding it as a direct dependency would only be a second place to keep in sync.
  • Photo-library, camera, video-recording, stream-sharing, Info.plist and Localizable.xcstrings changes — a separate plan owns that audit.

#331 is left open for the orchestrator to close out.

Testing

Everything on a dedicated iOS 27 simulator (created for this run, deleted after), Xcode 27 beta toolchain, isolated DerivedData, SWIFT_EMIT_LOC_STRINGS=NO CODE_SIGNING_ALLOWED=NO.

  • Full suite: 3533 tests, 18 failures, 0 unexpected. All 18 are the known unsigned-build Keychain bucket (KeychainServiceTests, SecretMigrationTests, and the ConfigTests/OpenClawAgentGateTests cases that read a gateway token from the keychain) — environment, not regression.
  • 18 new tests in Gemma4ChatPromptTests cover id matching, the rendered turn format (including that the system prompt stays its own turn and that no speaker labels appear), the extra stop token, template-parse-failure classification, both RAM tiers, and the derived photo prompt.
  • Every pre-existing local-model test passes unmodified — LocalTokenShapeTests, LocalModelRoutingTests, LocalLocationFixTests, LocalModelBudgetTests. The pin is the part of this every user carries, including those who never touch Gemma; Qwen 2.5, SmolVLM2 and LFM2.5 routing, budget and token-shape contracts are green on the new revision.
  • Release build succeeded (-configuration Release).

Actual model loading is device work (P4) — no multi-GB download happens in any test.

🤖 Generated with Claude Code

Gemma 4 has been the on-device catalog's headline agent while quietly not
working: the VLM factory could not map its weights, so it demoted to text on
every load, its chat template did not render, and generation ran past the end
of every answer. Three separate causes, fixed here.

**Load.** The weight-mapping failure (`keyNotFound(…k_norm.weight,
Gemma4RMSNormZeroShift)`) is fixed upstream — KV-shared layers must not declare
`k_proj`/`v_proj`. No released mlx-swift-lm tag carries that commit, so the
package moves from a tag to a revision that does, in `project.base.yml`,
`Package.swift` and both resolved files (via `Scripts/update-package-resolved.sh`).
The pin stops short of upstream's tip deliberately: the next commit retargets
MLXFoundationModels at the Xcode 27 beta 5 SDK and does not compile on earlier
27.0 betas, and MLXHuggingFace pulls that module in through a default-on trait.
The comment on the pin says when to move it forward.

**Parse.** Gemma 4's real chat template lives in `chat_template.jinja` and uses
constructs swift-jinja's parser rejects. `Gemma4ChatPrompt` renders that template
by hand as the fallback — a genuine system turn (not merged into the first user
turn), `<|turn>`/`<turn|>` delimiters, `assistant` renamed to `model`, and no
speaker labels anywhere. The generic no-system-role repair is no longer applied
to a template *parse* failure, which is what used to flatten the persona into
the wearer's turn.

**Stop.** `<turn|>` is the checkpoint's `eot_token` while its `eos_token` is the
different `<eos>`, so it is declared through `LocalLLMService.modelConfiguration`.

A Gemma 4 that loads through the VLM factory now takes one path for both text
and photo turns, through the processor that owns its template and image
tokenization. A photo turn's prefill is one unchunked forward pass, so how much
prompt it can carry is a property of the device rather than the model:
`LocalModelBudget.multimodalTurnPlan` keeps the wearer's configured prompt and
history on a 12 GB phone and trims only where the memory actually runs out. The
trimmed prompt is derived, not hardcoded — the configured prompt's identity line
survives and the wearer's language is stated explicitly
(`Config.compactVisionTurnPrompt`).

The stale "vision doesn't load in this runtime" caveat comes off the two Gemma 4
catalog entries.

Gemma chat-template and parsing fixes ported from #331 by @exadeci,
re-composed onto current main. Taken: the hand-rendered template, the
`<turn|>` stop token, the VLM-processor turn path, and the tests. Left: the
unconditional prompt/history stripping (now RAM-tiered), the English literal
photo prompt (now derived), the `sendLocal` tools/history change (redundant for
Gemma, a regression for SmolVLM2), the direct swift-jinja dependency (nothing
imports it; 2.4.2 already arrives through swift-transformers), and the
photo-library/camera/recording changes, which another plan owns.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@straff2002
straff2002 merged commit 4b71b1f into main Aug 25, 2026
1 check passed
@straff2002
straff2002 deleted the feat/dh1-gemma-load-parse branch August 27, 2026 12:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant