Repository navigation
Sync upstream ml-explore/mlx-swift-lm (ecd8e88) via real merge - #76
Merged
Merged
Conversation
* 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>
4 tasks
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.
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.swiftmerged cleanly and still uses the local../mlx-swiftpath.What comes in from upstream
ecd8e88generation observability (Add generation observability ml-explore/mlx-swift-lm#640):LogProbabilityTokenLoopHandler; the token-loop handlers move fromEvaluate.swiftinto a publicTokenLoopHandler.swift.0754e10Gemma tool calls keep nested object and array arguments (Fix Gemma tool calls losing nested object and array arguments to raw strings ml-explore/mlx-swift-lm#626).282c2f5KV cache memory inKVCacheStatus(Report KV cache memory in KVCacheStatus ml-explore/mlx-swift-lm#639).6d84ef6component-aware checkpoint loading (Introduce component-aware checkpoint loading ml-explore/mlx-swift-lm#679):ModelCheckpoint,CheckpointNameMapping,Qwen35CheckpointPolicy,loadModelCheckpoint(urls:),PerLayerQuantization.quantization(layer:).c07010edeterministic reranker cancellation test (Make reranker cancellation test deterministic ml-explore/mlx-swift-lm#669).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, sotargetWeightsandprepareTargetget aretainMTPparameter (defaultfalse= upstream behavior). The Qwen3.5 LLM text, wrapper and MoEsanitize/prepareCheckpointpassMTPConfig.retainMTPWeights.Qwen35.swift(LLM) andQwen35MoE.swift: upstream's checkpoint policy first, then the fork's FP8 block-wise dequant and MoE expert stacking unchanged.Load.swift: upstream'sModelCheckpointloading, 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'sGeneration.chunk(String, tokenId:)is carried over (TextToolTokenLoopHandlertracks the last token).TokenLoopHandlerTests/GenerationExecutionTests: the fork's extraTokenIteratorProtocolrequirements (streamingError,acceptedDraftTokens,totalDraftTokens) added to the new test mocks.sanitize: took upstream. It always drops MTP tensors, since the VLM has no MTP module.One fix beyond the conflicts
ToolCallFormat.gemma4still returned the fork's ownGemma4FunctionParser, which upstream replaced withGemmaFunctionParserin 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 testGemma 4 processor reads a streamed nested marker-quoted objectfailed..gemma4now returnsGemmaFunctionParser(startTag: "<|tool_call>", endTag: "<tool_call|>", escapeMarker: "<|\"|>")as upstream does, andGemma4FunctionParser.swiftis 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,tokenIdcarry-over, silent reverts) reported no findings; the Gemma parser issue above came from the test run, not from that review.Behavior notes
--mtpoff, the LLM text model'shasMTPWeightsheuristic no longer fires in theprepareCheckpointflow, because upstream strips the MTP tensors first. The tensors are dropped either way.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, againstSharpAI/mlx-swiftmain(34bc52f):DeepseekV4Testsx2,Gemma4FusionTests,Qwen35FusedGDNProjectionTests,TestQwenFP8,GenerationExecutionTests.testCancellationDuringTicketAdmissionSkipsNextAndFinalizes).pre-commit, the integration tests that need downloaded models (including the two new ones,GenerationObservabilityIntegrationTestsandQwen35CheckpointIntegrationTests), and a SwiftLM-side build against this branch.Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.
🤖 Generated with Claude Code