Skip to content

Sync upstream ml-explore/mlx-swift-lm (ecd8e88) via real merge - #76

Merged
solderzzc merged 6 commits into
mainfrom
sync/upstream-ecd8e88-merge
Oct 6, 2026
Merged

solderzzc merged 6 commits into
mainfrom
sync/upstream-ecd8e88-merge

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Proposed changes

Syncs the fork with upstream ml-explore/mlx-swift-lm (ecd8e88, 5 commits) as a real merge (--no-ff, no cherry-picks), like #74. Doing it by hand now keeps the new upstream-sync bot's first scheduled run from ending red on conflicts. Needs no mlx-swift change: Package.swift merged cleanly and still uses the local ../mlx-swift path.

What comes in from upstream

Conflicts and what I kept from the fork

  • Qwen35Checkpoint.swift (Qwen35CheckpointPolicy): upstream always splits the MTP tensors off the target model. SwiftLM's --mtp (MTPConfig.retainMTPWeights) keeps the MTP head inside the model, so targetWeights and prepareTarget get a retainMTP parameter (default false = upstream behavior). The Qwen3.5 LLM text, wrapper and MoE sanitize / prepareCheckpoint pass MTPConfig.retainMTPWeights.
  • Qwen35.swift (LLM) and Qwen35MoE.swift: upstream's checkpoint policy first, then the fork's FP8 block-wise dequant and MoE expert stacking unchanged.
  • Load.swift: upstream's ModelCheckpoint loading, with the fork's lazy / expert-streaming weight loading, the MTP add-on file (optiq/mtp.safetensors) and the per-layer-quantization path normalization (language_model., MTP and router prefixes) kept.
  • Evaluate.swift / TokenLoopHandler.swift: upstream's handler move; the fork's Generation.chunk(String, tokenId:) is carried over (TextToolTokenLoopHandler tracks the last token).
  • TokenLoopHandlerTests / GenerationExecutionTests: the fork's extra TokenIteratorProtocol requirements (streamingError, acceptedDraftTokens, totalDraftTokens) added to the new test mocks.
  • Qwen3.5 VLM sanitize: took upstream. It always drops MTP tensors, since the VLM has no MTP module.

One fix beyond the conflicts

ToolCallFormat.gemma4 still returned the fork's own Gemma4FunctionParser, which upstream replaced with GemmaFunctionParser in ml-explore#183 and then fixed in ml-explore#626. The fork's parser splits values at the first comma, so a nested object was truncated and the new upstream test Gemma 4 processor reads a streamed nested marker-quoted object failed. .gemma4 now returns GemmaFunctionParser(startTag: "<|tool_call>", endTag: "<tool_call|>", escapeMarker: "<|\"|>") as upstream does, and Gemma4FunctionParser.swift is removed (nothing in this repo or in SwiftLM references it).

Checked for silent reverts

For all 51 files upstream changed since the merge base (5e46681), I reverse-applied upstream's delta to the merged tree: 43 files contain it completely; the other 8 are the hand-resolved files above (6 source files and the 2 test files), and their remaining differences from upstream are the fork behavior listed here. A four-reviewer adversarial pass over the conflict resolutions (retain-MTP policy, Load.swift, tokenId carry-over, silent reverts) reported no findings; the Gemma parser issue above came from the test run, not from that review.

Behavior notes

  • With --mtp off, the LLM text model's hasMTPWeights heuristic no longer fires in the prepareCheckpoint flow, because upstream strips the MTP tensors first. The tensors are dropped either way.
  • Unchanged by this PR, noticed while resolving: the dense Qwen3.5 FP8 dequant in the LLM wrapper checks processed[wKey] == nil, so whether a weight gets dequantized can depend on dictionary order. Not changed here; worth a separate look.

Tests

xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation -skipMacroValidation -parallel-testing-enabled NO, against SharpAI/mlx-swift main (34bc52f):

  • XCTest: 691 tests, 6 skipped, 0 failures (680 before the merge; the extra 11 are upstream's new tests).
  • Swift Testing: 1076 + 70 + 7 tests, all passing (1021 + 70 + 7 before). The first full run had 1 failure, the Gemma 4 test above; it passes after the fix.
  • The 6 skipped tests need downloaded models, a benchmark env var, or a Debug-build WiredMemory assert (DeepseekV4Tests x2, Gemma4FusionTests, Qwen35FusedGDNProjectionTests, TestQwenFP8, GenerationExecutionTests.testCancellationDuringTicketAdmissionSkipsNextAndFinalizes).
  • Not run: pre-commit, the integration tests that need downloaded models (including the two new ones, GenerationObservabilityIntegrationTests and Qwen35CheckpointIntegrationTests), and a SwiftLM-side build against this branch.

Checklist

  • 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: this PR was prepared with Claude Code (Claude Sonnet 5.5): conflict resolution, build/test runs and the description. It still needs human review before merging.

🤖 Generated with Claude Code

aleroot and others added 6 commits October 5, 2026 11:22
* 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.
…strings (ml-explore#626)

Fix Gemma tool call parsing for nested marker-quoted strings and keys

- Fall back to rewriting marker-quoted strings (<|"|>, <escape>) as JSON strings when standard parsing fails.
- Trim whitespace and strip marker quotes from top-level argument keys.
- Add comprehensive test coverage across nested objects, arrays, and edge cases.
* Add generation observability
* Refactor generation observability into composable token handlers
* Defer log-probability readback to handlers and keep speculative drafters
Merges upstream main (5 commits: generation observability ml-explore#640, Gemma
nested tool-call arguments ml-explore#626, KV cache memory in KVCacheStatus ml-explore#639,
component-aware checkpoint loading ml-explore#679, reranker test ml-explore#669).

Conflicts resolved, keeping the fork behavior:
- Qwen35CheckpointPolicy gains a retainMTP parameter so SwiftLM's --mtp
  (MTPConfig.retainMTPWeights) keeps the MTP head inside the target model.
- Load.swift: lazy / expert-streaming weight loading, the MTP add-on file
  and per-layer quantization path normalization sit on top of upstream's
  ModelCheckpoint loading.
- Evaluate.swift / TokenLoopHandler.swift: upstream's handler move, with the
  fork's Generation.chunk(tokenId:) carried over.
- Tests: fork-only TokenIteratorProtocol requirements added to the new mocks.

Also route ToolCallFormat.gemma4 to upstream's GemmaFunctionParser (ml-explore#626)
and drop the fork's unused Gemma4FunctionParser, whose first-comma value
split truncated nested objects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@solderzzc
solderzzc merged commit 6490e3f into main Oct 6, 2026
7 checks passed
@solderzzc
solderzzc deleted the sync/upstream-ecd8e88-merge branch November 4, 2026 05:34
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.

4 participants