Skip to content

Decode surrogate pairs and the remaining Python escapes in PythonLiteralParser - #769

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
unaltolga:fix-python-literal-escapes
Nov 6, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
unaltolga:fix-python-literal-escapes

Conversation

@unaltolga

@unaltolga unaltolga commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

PythonLiteralParser decodes string escapes the way Python does, but a few of Python's escapes fell through to the branch for unrecognized escapes, which keeps the backslash: \x41, octal escapes like \0 and \101, \a, \v, and a backslash at the end of a line. They are now decoded as Python decodes them.

A surrogate pair written as two \u escapes, like '\ud83d\ude00', made the parser reject the whole literal, because a Unicode.Scalar can't hold half of a pair. A model that escapes emoji the way JSON does writes them like this. The parser now joins the pair into one scalar, as JSON readers do. A lone surrogate is still rejected.

When PythonLiteralParser rejects a value, PythonicToolCallParser keeps the raw text: a string keeps its quotes and backslashes, and a dictionary becomes a string. For example, with this call:

[send(text='Hi \ud83d\ude00', options={'separator': '\x2c'})]

it was parsed as:

  • text: 'Hi \ud83d\ude00', the raw text with its quotes and backslashes
  • options: {"separator": "\\x2c"}

and with this change:

  • text: Hi 😀
  • options: {"separator": ","}

A truncated \x escape like '\x4' is now rejected, as Python rejects it. Before, it was kept as text. \N{name} escapes are left as they were.

Apart from surrogates and \N{name}, the results match ast.literal_eval, which the Python parser in mlx-lm uses (mlx_lm/tool_parsers/pythonic.py).

Tests:

  • pythonStringEscapes in ToolArgumentNormalizationTests covers the new escapes, a surrogate pair, an unrecognized escape that keeps its backslash, and the lone surrogate and truncated \x that are rejected.
  • testPythonicParserStringEscapes in ToolTests parses the call above.

Both fail on main and pass with this change. All unit tests pass with xcodebuild test.

I formatted the three files with the swift-format that ships with Xcode (6.4.4), which leaves them unchanged. I don't have the pinned 603.0.0, so I left the pre-commit box unchecked.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI 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: Claude Code (Claude Opus 5.5) found the issue by comparing the parser with Python's ast.literal_eval, wrote the change, the tests and a draft of this description. I reviewed the code and the description, and ran the unit tests on my Mac.

PythonLiteralParser kept the backslash for \x, octal, \a and \v escapes
and for a line continuation, though Python decodes them. A surrogate
pair written as two \u escapes made it reject the whole literal, so the
Pythonic parser passed the raw text, quotes included, to the tool.
@unaltolga unaltolga changed the title Decode surrogate pairs and the remaining Python escapes Decode surrogate pairs and the remaining Python escapes in PythonLiteralParser Nov 5, 2026

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change looks good, thank you!

@davidkoski
davidkoski merged commit 22bdf2c into ml-explore:main Nov 6, 2026
3 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 14, 2026
Apply the upstream commits 22bdf2c..6352907 (the 15 after c8dabc6) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- 22bdf2c Decode surrogate pairs and the remaining Python escapes (ml-explore#769)
- 0877a36 Fix model weight loading progress (ml-explore#551)
- 0dabaf7 Add production-ready LFM2.5 model support (ml-explore#528)
- 173c163 Add mid-turn steering to ChatSession (ml-explore#608)
- 37424a5 Stop image prompts from running VLM language models in float32 (ml-explore#766)
- c48e55e Add LiquidAI LFM3 model support (ml-explore#750)
- 4ab2679 MLXVLM Qwen35: apply YaRN from rope_parameters on the VLM rotary (ml-explore#761)
- 6e3fe5d Report token log probabilities during speculative decoding (ml-explore#774)
- ec4c966 Batch greedy MTP verification into one GPU readback per round (ml-explore#724)
- c9a9a3d Skip the checkpoint components a model does not have (ml-explore#711)
- a8429d0 Measure the memory of an EmbeddingGemma 2 embedding (ml-explore#787)
- 7b0e790 Parse triple-quoted strings in PythonLiteralParser (ml-explore#786)
- 4c91662 Fix the flaky usage test on the tool-calling path (ml-explore#784)
- d7b94ee Add ModelTypeRegistry.contains(_:configuration:) for shared model types (ml-explore#778)
- 6352907 Use MLXLogger for the model component warning (ml-explore#790)

Conflict resolutions:
- ml-explore#551 load progress: `LoadProgressHandlers` and `progress:` are threaded
  through the fork's async `loadWeights`/`installWeights`. The
  progress-aware `MLXLanguageModel.init(...progress:load:)` and the
  `#huggingFaceLanguageModel` macro also take the fork's
  `speculativeDecoding:`. The fork's tests and benchmark helpers move off the
  now-deprecated download-only loader.
- ml-explore#528 LFM2.5: `RewindableConvolutionCache` lives in ArraysCache.swift
  without upstream's extra `offset +=`, because the fork's `advance` moves
  `offset`. Speculative rewind and verify checks trim it like attention, and
  do not select a Mamba snapshot slot for it. It is also
  `PromptCacheRestorable`, so a saved LFM2 prompt cache restores into the
  model's template. `mtpTargetLayerIdsKey` is added to the fork's MTP
  exchange. `shouldSortExpertRoutes` drives the fork's shared switch
  projection. The fork's in-place verify (`verifiesInPlace`) and its
  greedy-only passthrough string are kept. The upstream tests that expect a
  wrapped sliding window to refuse rewind now expect the fork's behavior:
  the window rewinds the verify write and keeps speculating.
- ml-explore#608 steering: the steering boundary goes into the fork's
  `GenerationLoop.runTokenLoop`, and `Generation.steering` and
  `GenerateStopReason.steered` go into GenerationResults.swift. The fork's
  generation worker keeps its own stream synchronization.
- ml-explore#750 LFM3 is added to HybridRecurrentCacheOffsetTests.
- ml-explore#711: the new test awaits the fork's async `loadWeights`.

Dropped:
- ml-explore#774 (speculative log probabilities): the fork's MTP iterator already
  reports log probabilities by decoding plainly when they are requested.
  Upstream's batched recording in the draft-model iterator does not fit the
  fork's `sampleToken` path, so `ChatSession.ObservationError` stays for
  draft-model speculation.
- ml-explore#724 (batched greedy MTP verification): the fork already batches its
  greedy verify (`verifyDrafts`, MTPGreedyVerificationTests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants