Repository navigation
Conversation
Adi2K
force-pushed
the
fix/gemma-nested-marker-strings
branch
from
September 16, 2026 09:06
1588b98 to
3a377a6
Compare
There was a problem hiding this comment.
🟢 Approval recommended
The focused parser change preserves prior behavior and is thoroughly covered by relevant edge-case tests.
Pull request overview
Adds support for Gemma’s marker-quoted strings within nested brace-form values.
Changes:
- Retries structured parsing after converting marker-delimited spans to valid JSON strings.
- Escapes JSON-sensitive characters and preserves existing parsing behavior.
- Adds extensive parser and streaming regression coverage.
File summaries
| File | Description |
|---|---|
Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift |
Implements nested marker-string rewriting and parsing. |
Tests/MLXLMTests/ToolTests.swift |
Covers nested structures, escaping, malformed input, schemas, and streaming. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 0
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Gemma 4 writes every string in a tool call between escape markers,
including strings inside nested objects and arrays:
`{location:{city:<|"|>Paris<|"|>}}`. BareKeyJSONParser (ml-explore#557) only
understands JSON's own double quotes, so a value like this fails to
parse and GemmaFunctionParser falls back to the raw text. A parameter
the schema declares an object then arrives as a string, and a tool that
validates its input rejects the call. The ml-explore#557 review left this as a
follow-up.
Parse the original text first, exactly as before. Only when that fails,
and only if the text contains the marker, rewrite each marker-delimited
span as a JSON string (escaping backslash, double quote, and control
characters) and try again. Because the original text is always tried
first, anything that parsed before still gives the same result. This
matters for FunctionGemma's `<escape>` marker, which can appear inside
an already-quoted JSON string.
Add 20 tests to Tests/MLXLMTests/ToolTests.swift, next to the existing
Gemma tests. 17 fail without the fix: nested objects, arrays of
objects, bare scalars mixed with marker strings, control characters,
quotes and backslashes, empty and backslash-ended strings, non-ASCII
text, marker-quoted keys and a space before a key (both seen in
gemma-4-e2b-it output, though the template writes neither), deep
nesting, a call with no tool schema, FunctionGemma nested `<escape>`
strings, and a streamed call through ToolCallProcessor. Three pin
behavior that does not change for input outside the dialect: markers
inside an already-quoted JSON string, a FunctionGemma value with an
unpaired marker, and a string-typed parameter that keeps its raw text.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adi2K
force-pushed
the
fix/gemma-nested-marker-strings
branch
from
September 16, 2026 09:20
3a377a6 to
e3b9f33
Compare
GemmaFunctionParser trimmed argument values but not keys, so a space
after a comma, as in `{city:<|"|>Paris<|"|>, days:3}`, stored `days`
under the key " days", which the tool schema does not know. The chat
template writes no space there, but gemma-4-e2b-it wrote a space before
a nested key with thinking disabled. Trim the key the same way as the
value, and add a test.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The model sometimes marker-quotes a key, as it does values. Inside a
nested value the rewrite already turns `<|"|>city<|"|>` into a JSON
string, but a top-level key is read directly, so a call such as
`{<|"|>city<|"|>:<|"|>Paris<|"|>}` reached the tool with the key
`<|"|>city<|"|>`. Strip a marker pair around a top-level key after
trimming it, and add a test next to the space case.
Also say in `parseStructured` why the original text is parsed first:
FunctionGemma's `<escape>` can sit inside a JSON-quoted string, which
the rewrite would break.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…n-flight load (ml-explore#603) * Move the model cache into its own file - Moves the constraint kind, the tokenizer bias, and the cache actor out of the model file, changing only the access the cross-file use requires: `private actor ModelCache` becomes `actor ModelCache`, because a `private` top-level type is visible only inside its own file. No other content changes. The model cache grew large enough inside MLXLanguageModel.swift to warrant its own file, separate from the model's own responsibilities. * Catch only the fork-unavailable error when a constraint clone fails - Narrows the freshly-compiled constraint's clone attempt from a blanket `try?` to a catch on `GrammarError.forkFailed`, matching the cached-template clone site above it, which already narrowed this way. Every other clone failure now reaches the caller instead of being silently treated as the expected one. A blanket `try?` treated every clone failure as the one expected case, xgrammar lacking `Fork()`. `GrammarConstraint.clone()` has exactly one throw site today, so this narrowing changes no observable behavior yet; it only stops a future second failure mode from being swallowed the same way. * Cancel every registered load from evictAll() - Cancels every registered load task, which remove(modelID:) already did for one model. - Corrects the eviction documentation, which claimed an in-flight load completes. - Adds a test that evictAll() cancels an in-flight load, and the same probe against evict(). - Bounds both new tests with a time limit, because each parks its loader and a regression would hang. evictAll() dropped every load registration without cancelling, so nothing in the process could reach a load that was still running. A caller awaiting preload() or respond() now fails, and callers coalesced onto one load fail together. Cancellation is cooperative. A load already inside loadWeights runs to completion and allocates, and that limit applies to evict() too. * Rename the grammar tokenizer members away from an xgrammar abbreviation - Renames the grammar tokenizer members and their storage away from an abbreviation of the library name: `xgTokenizers` becomes `grammarTokenizers`, `makeXGTokenizer` becomes `makeGrammarTokenizer`, and `hasCachedXGTokenizer` becomes `hasCachedGrammarTokenizer`, at every call site. - Renames the same local variables at every call site: `xgTokenizer` and `xgTok` become `grammarTokenizer`, and the `vocab` local inside `makeGrammarTokenizer` becomes `vocabulary` to avoid shadowing the `vocab:` parameter label once its neighbor is renamed. The cache's tokenizer members were named after xgrammar's own abbreviation rather than the type they store, which the style guide's initialism rule flags. * Name the download progress throughput property in full - Renames the observable throughput property to throughputBytesPerSecond, dropping the abbreviation. - Drops public from the two reporting entry points, leaving the observable state and the shared instance public. Every caller of the two entry points is in this module, and the tests reach them through @testable import, so neither needs to be public. No release contains this type: the newest tag is 3.31.4 from June, and the whole MLXFoundationModels library arrived in July, so no consumer can depend on either name. * Track download progress for each model - Keys the progress state on the model ID, with one published value per model and accessors that add every entry. - Reports the end of a load from a defer, so a failed or cancelled load clears its own entry. - Sends every report through one stream and one main-actor consumer, which applies them in the order the loader sent them. - Gives every load its own identifier, so a report from a cancelled load cannot change the load that replaced it. - Removes isActive and modelName, and adds activeDownloads and download(forModelID:). One fraction and one identifier cannot describe two loads, and the cache loads models concurrently, so two downloads overwrote each other's state. reportCompleted() ran only after a successful load, so a cancelled load left the state active for the life of the process. Each report also created its own main-actor task, and those tasks run in no fixed order, so a progress report could apply after the end and leave a finished download on screen. Eviction cancels a load and forgets it at once, so a replacement can start while the cancelled load still transfers bytes, and both shared one entry. No release contains this type, so none of these changes can break a consumer.
* pick up mlx-swift 0.32.2
…ter (ml-explore#535) * Name each attached image in the prompt, refuse names that mimic picture markers - Names were thrown away before the prompt was built; a name now goes directly before its own picture, matching Foundation Models, across eleven model families - In MLXLMCommon: an image takes an optional name, and one shared function assembles a message's parts, so this works with no adapter - Name refused when its bracketed form is a reserved picture token, such as [IMG] on Mistral - Two smaller parity fixes: instructions images dropped and logged, and photo orientation applied - Source break: case .url(let u) = image becomes case .url(let u) = image.source * Refuse a picture name that holds a marker character - The name check asked the tokenizer whether a name held a reserved picture token, but a tokenizer flags only some of its reserved tokens as special; on GLM-OCR and FastVLM the picture token itself is not flagged, so such a name was accepted and the model then counted one more picture than it was given - A name that holds any of < > | [ ] is now refused on every model, which needs nothing from the tokenizer and so covers a marker the tokenizer cannot see at all - The tokenizer check still runs, and runs first, so the error can name the exact token; it remains the only check that catches a plain name such as IMG whose bracketed form is reserved - Names accepted before and refused now: chart [q3] (final), a <b> tag & an entity, <|, |> and <image> - New test drives the real tokenizer of all ten families and refuses each family's own picture token; without this change it fails on GLM-OCR and FastVLM * Leave a marker-carrying picture name out of the prompt - Only the Foundation Models path checked a picture name, so a caller using MLXLMCommon directly could put a reserved picture token into the prompt; on Mistral3 that doubled the picture tokens for one picture and the process then aborted instead of raising an error - A name that holds any of < > | [ ] is now left out of the prompt wherever it is assembled, and the reason is logged; the picture itself is always kept, so the count the model checks still matches - The Foundation Models path is unchanged and still raises a typed error, because its check runs before the prompt is assembled - One list of characters now serves both checks, so the two cannot drift apart * Raise an error when image tokens and features disagree - Replaces the fatalError in the LFM2VL and Mistral3 merge step with a thrown VLMError.processing. - Propagates the throw through the embedding helpers, which already run inside a throwing prepare. - Adds a test for each model that feeds one image token against a four-patch grid. Prompt text can hold a model's image placeholder, such as [IMG] on Mistral3. The tokenizer reads it as an image token, so user input can cause the mismatch. A crash of the host process is worse than an error the caller can catch. * Log dropped picture names through MLXLogger - Replaces the Apple-only logger in the message content builder with MLXLogger from mlx-swift. - Writes the marker character into the log message instead of marking it public. The Apple logger does not exist on Linux, so this file could not build there. The built-in MLXLogger handlers print only the message, so the marker must be part of the message text. * Log MLXFoundationModels through MLXLogger - Replaces the Apple logger in three adapter files with MLXLogger from mlx-swift. - Removes the privacy arguments, which MLXLogger does not take. This gives the package one logger. MLXLogger logs through OSLog under the subsystem mlx-swift, and it marks every message public. Two messages that the Apple logger redacted now log in public. They are the name of a rejected tool call and the text of a token-stream protocol error. * Move the special-token label check into MLXLMCommon - Moves the check that encodes a label's bracketed text and looks for special tokens out of the Foundation Models validator and into MLXLMCommon. - Gives the bracketed label text one source, which the message generators and the check both use. - Leaves the validator's behavior unchanged, so it still throws for such a label. The vision processors need the same check in the next change, and MLXVLM does not depend on MLXFoundationModels. * Leave special-token image labels out of VLM prompts - Adds a screen that removes each chat image label whose bracketed text the model's tokenizer reads as a special token, and logs the removal. - Runs the screen in every vision processor, before its message generator writes the prompt. - Keeps each image, so later labels still sit beside their own images. - Adds unit tests with a stub tokenizer, and an integration test that prepares a labeled image through the Mistral3 processor. The label IMG renders as [IMG], which is Mistral's image token. The Mistral3 processor splits the prompt on that text, so one image became two image blocks. A tokenizer check also catches [INST] and the other special tokens, which a fixed list would miss. * Screen image labels when a configured generator writes the prompt - Gives the wrapper that applies a configured message generator the model's tokenizer, through a package initializer. - Runs the special-token label screen in that wrapper, before the configured generator writes the prompt. - Adds a test that routes an IMG label through the wrapper with the Mistral3 generator. When a model configuration sets its own message generator, the wrapper wrote the prompt before the processor ran, so the processor's screen never saw the labels. The public initializer is unchanged. * Keep the attachment label out of the default log - Moves the label in the dropped tool-output attachment warning out of the message text and into the logger's metadata. - Splits that warning into two plain sentences. The default MLXLogger handler writes the message to the system log as readable text, and it ignores metadata. A label can hold user data, such as the name of a photo. An app that installs its own handler still receives the label. * Keep the message content helpers inside the package - Changes the message content layout enum and the content-parts function from public to package access. Only this package's vision message generators and its unit tests call them. A public version could not change later without breaking apps, and outside code could use it to write labels without the special-token check, which is package access too. * Unslop inline comments - Deletes comments that repeat the code, record measurements or review history, name a reviewer, or point at nearby tests. - Deletes comments that contradicted the code, such as the test counts in the vision integration tests, the model lists on the content layout, and the claim that the perform closure does not capture the request. - Rewrites each kept comment in short plain sentences, with the condition stated beside each claim. - Restores the original wording of five older comments that earlier commits on this branch reworded without need. - Changes only comment lines and blank lines. * Make UserInput.Audio a struct with a source, like UserInput.Image - Turns Audio from an enum into a struct that holds its old cases in a nested Source enum. - Adds a static url and a static array function with the old labels, so the code that creates an audio value still compiles. - Makes asMLXArray switch on the source, and keeps its case bodies. - Adds tests that create an audio value in each way that callers use today, and check its source. PR ml-explore#535 made Image a struct with a source. Audio now has the same structure. Code that matches on an audio value no longer compiles, and it must match on its source instead. * Make UserInput.Video a struct with a source, like UserInput.Image - Turns Video from an enum into a struct that holds its old cases in a nested Source enum. - Leaves the avAsset case and its static function behind the AVFoundation check. - Adds a static url and a static frames function with the old labels, so the code that creates a video value still compiles. - Makes the deprecated asAVAsset and MediaProcessing.asProcessedSequence switch on the source, and keeps their case bodies. - Adds tests that create a video value in each way that callers use today, and check its source. - Adds a source check to the image test for a function reference, so that it matches the audio and video tests. Image, Audio and Video now have the same structure. Code that matches on a video value no longer compiles, and it must match on its source instead. * Document the break for all three media types in the upgrade notes - Replaces the upgrade entry for UserInput.Image with one entry for Image, Video and Audio. - Lists the old cases of each type, and shows that the code that creates a media value still compiles. - Keeps the description of the image label. - Shows how to fix a switch or a case pattern that matches a media value.
…l-explore#653) - Converts each JSON boolean in a tool's parameter schema to a Swift Bool before the tool spec reaches the chat template. - Leaves each number in the schema unchanged, even a 0 or a 1. - Adds tests that check the booleans become Swift Bool values and the numbers stay numbers. JSONSerialization boxes each JSON boolean in an NSNumber. swift-jinja's Value(any:) matches Int before Bool, so it converts a boxed false to 0. When a tokenizer passed the schema to swift-jinja unchanged, the prompt showed "additionalProperties": 0. The conversion checks the type ID of each NSNumber. An `as? Bool` cast also accepts a boxed 0 or 1, so that cast would turn "minItems": 1 into true.
* adjustments for running tests on NAX/TF32 hardware * Apply suggestion from @nwh Co-authored-by: Nick Henderson <525247+nwh@users.noreply.github.com>
* update documentation and skills - make sure we are using current best practices e.g. for #huggingFaceTokenizerLoader() - where found, update skills to current API --------- Co-authored-by: Nick Henderson <525247+nwh@users.noreply.github.com>
…re#635) NVIDIA-Nemotron-3-Nano-4B is a dense Nemotron-H: its hybrid_override_pattern has no E layers and its config.json has no moe_intermediate_size, moe_shared_expert_intermediate_size, n_routed_experts or num_experts_per_tok. The configuration decoded all four with decode(), so loading it failed with keyNotFound before any weight was read. They are only used to build MoE layers, so decode them with decodeIfPresent and default to 0.
…e model (ml-explore#631) Fix memory leak from unregistered fused GDN projections in Qwen3.5 Because `prepare()` does not register the fused projection as a child of `Qwen35GatedDeltaNet`, traces treated its arrays as tape constants rather than state. Due to ml-explore/mlx#3932, these constants remained resident after function erasure, leaking ~2.3 GB per reload on 27B. Traces running GDN layers now explicitly declare the fused module as compile state. Verified with `testCompiledDecodeReleasesFusedProjectionWithTheModel`.
* Introduce component-aware checkpoint loading - note: sanitize() now throws
`KVCacheStatus` describes a cache's topology, strategy and progress, but not how much memory it holds, so an application cannot show what a conversation costs in unified memory. Two cache types count their own bytes (`TurboQuantKVCache.memoryBytes` and the internal `VarianceNormalizedKVCache.compactStorageByteCount`); the others leave callers to guess. Report it for every layer: - Add `KVCacheLayerStatus.memoryBytes`, the bytes allocated for the layer's arrays, and `KVCacheStatus.memoryBytes`, their total. Rows a cache reserves ahead of the tokens it holds are counted, since they are resident. - Count them from `innerState()`, the arrays `Evaluatable` already requires each cache to list. `nbytes` reads array metadata only, so building a status evaluates nothing and never waits on the GPU. - `TurboQuantKVCache` inherited `BaseKVCache`'s empty `innerState()`, so it reported no bytes and `asyncEval(cache)`, which chunked prefill runs after every chunk, skipped its buffers. List them, and count `memoryBytes` from the same list. - `VarianceNormalizedKVCache.innerState()` returned `state`, which slices a view of every tile on each call. Return the slabs, pending tiles and tail it stores instead: the same bytes, without work that grows with the context. Statuses are built when a turn starts, never in the token loop, and every built-in cache now lists only the arrays it stores, so the count stays cheap at any context length.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Internal review PR on Adi's fork. This mirrors ml-explore#626 (same branch).
Update 2026-09-16: added a second commit that trims whitespace around top-level argument keys, with a test.
Proposed changes
Gemma 4 writes every string in a tool call between escape markers (
<|"|>),including strings inside nested objects and arrays. A call with the
arguments
{"location": {"city": "Paris", "country": "FR"}}is written as:Today
GemmaFunctionParserreturns the nested value as a string, even whenthe tool's schema declares
locationan object:A tool that validates its input then rejects the call (for example, an MCP
server answers
string found, object expected). With this change:More examples of what Gemma writes, and what the parser returns with this
change:
{stops:[{city:<|"|>Paris<|"|>},{city:<|"|>Lyon<|"|>}]}becomes
[{"city": "Paris"}, {"city": "Lyon"}](today: a string).{note:{text:<|"|>line one+ newline +line two<|"|>}}becomes{"text": "line one\nline two"}(today: a string).{city:<|"|>Paris<|"|>}already worked and isunchanged.
Why. ml-explore#557 added
BareKeyJSONParser, which quotes bare object keys andretries JSON parsing. It only knows JSON's own double quotes, so a nested
value that holds marker-quoted strings still falls back to the raw text. The
ml-explore#557 review noted this: nested values written as
<|"|>…<|"|>are something"this parser still does not rewrite, but that is probably a separate
follow-up." This PR is that follow-up.
This is the shape the model is trained to write. The chat template's
format_argumentmacro wraps every string value in<|"|>at any nestingdepth and inserts the text as is, so line breaks can appear inside
(
google/gemma-4-e2b-itchat_template.jinja, lines 124–155; tool calls useit at line 253). The examples above are rendered by that template. Google's
tokenizer_config.jsonfor the same model tells transformers to read thesestrings (
string_delims: <|"|>,unquoted_keys: true), and mlx-lm'sgemma4tool parser reads them too. The regex in Google's function-callingdocs is a flat demo that does not read nested values, so it is not a useful
reference here.
What changed.
GemmaFunctionParserstill tries the original text first,exactly as before. Only if that fails, and the text contains the marker, it
rewrites each
<|"|>…<|"|>span as a JSON string and tries again. Therewrite escapes backslash, double quote, and every control character below
U+0020. Because the original text is always tried first, anything that
parsed before gives the same result now. This matters for FunctionGemma,
which shares this parser with the
<escape>marker:{a:"<escape>hi<escape>"}still parses as{"a": "<escape>hi<escape>"}.Two key shapes that the template never writes now parse as well: a
marker-quoted key, as in
{<|"|>city<|"|>:<|"|>Paris<|"|>}, and a spacebefore a key, as in
{city:<|"|>Paris<|"|>, country:<|"|>FR<|"|>}.gemma-4-e2b-it-4bit wrote both shapes with thinking disabled: the quoted key
in 1 of 8 sampled runs, the space in 2 of 8.
It also trims whitespace around top-level argument keys. The template
writes no space after a comma, but the model does not always follow that:
gemma-4-e2b-it wrote a space before a nested key (the second key shape
above). The same spacing at the top level, as in
{city:<|"|>Paris<|"|>, days:3}, made the parser storedaysunder thekey
" days", which the tool's schema does not know.How it's tested.
Tests/MLXLMTests/ToolTests.swiftadds 21 tests next tothe existing Gemma tests, four of them parameterized.
18 fail without these changes (29 issues): nested objects, arrays of objects, bare
scalars mixed with marker strings, line breaks, tabs and other control
characters, quotes and backslashes, empty and backslash-ended strings,
non-ASCII text, marker-quoted keys, the two key shapes above, a space before
a top-level key, a marker
string in an array nested several objects deep, a call with no tool schema,
a FunctionGemma nested
<escape>string, a FunctionGemma value where anunpaired marker follows a paired one, and a streamed call through
ToolCallProcessor(format: .gemma4).3 pass both before and after. They use input outside the dialect and pin
existing behavior: JSON-quoted FunctionGemma strings that contain markers
(the original text is read first), a FunctionGemma value with an unpaired
marker, and a string-typed parameter that keeps its raw brace text. The test
with an unpaired marker after a paired one also uses malformed input; it
pins the result this change chooses.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
I have read this PR description in full and approve it as my own, and it
accurately describes the code changes.
AI usage disclosure:
🤖 Generated with Claude Code