Repository navigation
Merge upstream main (65 commits, through #662); re-thread the Qwen3.5 seam around #614 (gemma4-qat#283) - #2
Merged
Merged
Conversation
…l-explore#582) The Xcode 27 integration build job no longer runs on pull requests. The job condition is now false, and the original repository condition stays in a comment above it so it is easy to put back.
…xplore#583) MLXRandom.seed resets MLXRandom.globalState, a process-wide singleton. Swift Testing runs tests in parallel, so tests seeding and consuming the global stream interleave their key splits: one test's seed call resets another test's stream mid-consumption, making seeded tests neither isolated nor reproducible. Every seeded test now scopes its randomness with withRandomState(MLXRandom.RandomState(seed:)), which binds a @TaskLocal random state that resolve(key:) prefers over the global state - the pattern Gemma4UnifiedTests and EvalTests already use. Each test owns a private, deterministic stream regardless of what runs concurrently. Also pins the previously unseeded tiny-model factories (Qwen3-VL, Qwen3.5, GLM-OCR, Nanbeige) under a task-local state so their tolerance-based equivalence assertions are reproducible when they fail, and drops the now-redundant .serialized trait from RoPEApplicationTests. Fixes ml-explore#577
AI-generated code is allowed, and so is AI-drafted prose. What is not allowed is submitting either one without the human contributor understanding it. You must be able to explain the code you submit, you must disclose how you used AI, and you must read and approve any prose you submit. Agents may not autonomously create PRs or other reviewer-facing text without a human in the loop. Do not make reviewers read prose that you, the human, did not bother to read. The policy itself has been added to CONTRIBUTING.md, addressed to human contributors, including possible penalties if it is not followed. AGENTS.md is intended to help agents produce a submission with a better chance of being accepted. It contains the same rules, plus helpful local conventions and CI mechanics such as where CI's swift-format pin lives, the DocC check, and the fact that `swift test` does not work here. CLAUDE.md is a symlink to it. The pull request template asks the author to confirm they read the description and that it matches the code, and adds an AI usage disclosure that all submitters are expected to fill in. The issue templates now include the same acknowledgment.
Move the Qwen 3.5 decode-only Metal router kernel into MLXLMCommon and generalize it for separate selection and score tensors while preserving winner order.\n\nUse the shared path in Qwen 3 MoE, OLMoE, Mixtral, Jamba, and Granite MoE Hybrid, retaining the generic MLX path for prefill. Add cross-dtype bitwise coverage and model-level parity tests against each original router expression.
* Optimize Qwen MoE expert reduction * Enable Qwen direct expert reduction by default
* Fuse Qwen GDN input projections * Move inference preparation to LanguageModel lifecycle * Use prepare overload for inference lifecycle
…l-explore#594) * Stop calling deprecated MLX memory APIs from the integration tests MLX moved its memory inspection and cache control onto a Memory type and deprecated the older GPU spellings. The integration tests still used the old names, so every build of the IntegrationTesting scheme printed a dozen deprecation warnings that buried the warnings actually worth reading. Switch the call sites over to Memory.snapshot() and Memory.clearCache(), and fix a doc comment that pointed at the old name. The deprecated calls just forward to the new ones, so behavior is unchanged. * Move Gemma's video frame handling off the deprecated VideoFrame API Gemma was the last video model still building frames through the old VideoFrame spellings, which take and hand back a CoreImage image directly. Every other vision model already goes through the newer form that wraps the image in the general-purpose image case, so this was the only source of these deprecation warnings left in the library. Reading the incoming frame through the supported accessor also removes a force-try: the deprecated property traps when the frame is not backed by a CoreImage image, whereas the surrounding frame-processing closure is already allowed to throw, so the failure now surfaces to the caller instead of killing the process. * Remove a leftover unused local from Gemma's text backbone An earlier fix to Gemma's cross-layer key/value sharing stopped consulting whether the caller supplied a cache when deciding which layers reuse an earlier layer's keys and values. That fix removed both readers of the local variable holding that answer but left the variable itself behind, so the compiler has been reporting it as an unused value ever since. Drop the declaration. Its initializer only tested an optional for nil, so nothing observable changes. * Clear the remaining compiler warnings from the package With the deprecation warnings fixed, the build still reported a handful of style diagnostics. Most were `var` bindings that are only mutated through subscript assignment or a copying update, which `let` already permits, and `try`/`await` markers on expressions whose callees turned out to be synchronous. Breakpoints of note: the optional-key-path mock in the chat-session tests calls a synchronous prepare overload, and the reranker test used a conditional cast to an existential to check a protocol conformance that is statically guaranteed; the coercion form still fails the build if that conformance is ever removed, but no longer warns. The one warning needing care was ParoQuant's concurrency test, which captures a non-Sendable layer in the @sendable closure of DispatchQueue.concurrentPerform. Unsynchronized access is the whole point of that test, so the layer now crosses the boundary in a small unchecked-Sendable wrapper, alongside the existing thread-safe accumulator in the same file.
* Add the CI state label module with the run-start rule A pull request whose CI run has just started carries ci-running, and loses the labels that described the previous run. An approval by a maintainer survives the start, because the completion rule needs to see it. * Turn a finished CI run into one pull request label A green run asks for review, or reports the pull request ready to merge when a maintainer has already approved it. A red run names what the author must fix, and only calls for formatting work when formatting is the single thing that failed. A run that failed on the build image, or that was cancelled, asks for another run instead of blaming the author. * Put a pull request back in the CI queue when a new commit arrives Every CI result and every approval describes the commit that has just been replaced, so all of them go. The pull request is only queued again once a scan has read it, which its category label proves. * Read the run and write the labels through an injected client The three functions that talk to GitHub take the client as an argument, so the tests inject a fake and none of them reaches the network. Finding the pull request from the head commit is what makes this work for a fork, whose run payload may carry no pull request at all. * Choose the pull request the run actually tested, and test the requests A commit can belong to more than one open pull request when branches are stacked, so the head commit now decides which one the label describes. The fake client also records what each read asks GitHub for, so a wrong run number can no longer pass the tests and fail only in a live run. * Mark the build-image steps and run the label classifier's tests Three steps check the state of the build machine rather than the change, so their names now say so. A failure in one of them asks for another run instead of asking the author for a fix. A new job runs the classifier's own tests, so a change to it cannot merge untested. * Label a pull request while CI runs and when it finishes A pull request shows ci-running from the moment its run starts, and gets one label describing the result when the run ends. Both handlers ignore a run whose commit the pull request has already left, so nobody reviews code that has been replaced and no newer commit loses its place in the queue. * Requeue a pull request for CI when a new commit arrives Every label describing the previous commit goes, and the pull request waits for CI again. A pull request no scan has read is cleared but not queued, so new code never reaches the build machine before it has been read. * Ignore a CI run that never started, and stop pinning a stale base commit A run held for approval reports a conclusion without having run, so the completion handler now ignores it rather than clearing the labels a maintainer set. The reset workflow also takes the default branch instead of the pull request's base commit, because an older base does not yet contain the script the job loads. * Say what the reset workflow's checkout actually takes The comment still described a pinned base commit after the checkout changed to the default branch. It describes the security property of a job that holds a write token, so a stale version of it is worse than none. * Accept the old build-machine step names, and correct four comments A pull request from a fork runs its own copy of the CI workflow, so one branched before the step rename still reports the old names. The classifier now treats both spellings as a build-machine failure, rather than asking a contributor to fix a machine they cannot reach. Four comments also said more than was true: about which files a workflow loads, about what a checkout takes, about why one clause exists, and about what never cancelling guarantees. * Say when the legacy step names can go, without naming another repository The note pointed at a file a reader of this repository cannot see. It now states the condition on its own terms: the list can go once no open pull request predates the rename. * Copy edits * Read the CI workflow's contract number from a step name * Ask for another run when the rules do not match the branch * Let the contract number replace the list of old step names * Name the contract number in the CI workflow * Log the branch's contract number next to the expected one * Fix two tests that passed for the wrong reason Both tests check that a failure the author cannot fix gets the needs-ci label. Their sample job data left out the contract step. One test should reach the no-failed-step check, and the other should reach the build-machine check. Both reached the newer contract check instead. With the build-machine check deleted, every test still passed, so nothing guarded that check. This change adds the contract step to both samples. Each test then reaches needs-ci through its own check again. If you delete the build-machine check now, its test fails.
…ensors (ml-explore#598) An MLX-converted checkpoint may keep its mtp.* tensors for speculative decoding. Treating their presence as proof of a raw upstream checkpoint applies the zero-centered RMSNorm +1 shift a second time, leaving every layernorm near 2.0 instead of 1.0 and degrading generation to garbage tokens. The conv1d layout identifies raw checkpoints on its own: transformers exports store conv1d as [C, 1, K], and a converter that transposes conv1d shifts the norms in the same sanitize pass, so the two signals cannot diverge in a valid checkpoint. MTP-only drafter checkpoints are unaffected because the mtp. filter removes all their tensors before the shift loop.
…tchGLU (ml-explore#511) * Allow downstream specialization of Qwen3.5 GDN/MoE blocks and SwitchGLU `Qwen35Language` has no access modifier, so everything nested in it is internal regardless of its own modifier, and `GatedDeltaNet`, `SparseMoeBlock`, `DecoderLayer` and `Model` are additionally `final`. `SwitchGLU` and `SwitchLinear` are `public` rather than `open`. Together this makes the Qwen3.5 language stack impossible to specialize from another module. Serving this model with routed experts streamed from SSD instead of resident needs exactly one substitution — our own expert MLP in place of `SparseMoeBlock`'s — while keeping the rest of the vendored model and its weight keys intact. Without subclassing that becomes a reimplementation: ~445 lines re-deriving the `@ModuleInfo(key:)` bindings, the gather/scatter sort and the quantized-vs-dense dispatch that `SwitchGLU` already gets right, and every upstream fix has to be hand-ported. Widens access only: Qwen35Language -> public GatedDeltaNet, SparseMoeBlock, DecoderLayer, Model -> open SwitchGLU, SwitchLinear -> open SwitchGLU/SwitchLinear/SparseMoeBlock callAsFunction -> open `Module` is already `open`, so nothing changes in mlx-swift. `SparseMoeBlock.callAsFunction` had to widen as a consequence, not a choice: it satisfies a requirement in the public `UnaryLayer` protocol, so an `open` class cannot leave it internal. Made `open` rather than `public` since overriding it is the point. Leaves FusedGateUpSwitchGLU alone and omits the GDN conv-fold port, which is a behaviour change and belongs in its own PR. Full suite: 296 tests, 0 failures. * public/open updates --------- Co-authored-by: Fred Jura <digital@afya.ai> Co-authored-by: David Koski <dkoski@apple.com>
…e#596) Mirrors the Gemma 3/4 encoder exposures (ml-explore#387, and the Gemma 4 follow-up) for Falcon-H1, so client code can run the decoder stack over an embedding it built itself rather than over a single token id. The motivating case is a DualAR TTS model (Audio8 TTS Preview 0.1b, model_type `arktts`, `slow_backbone: falcon_h1`) whose slow-stack input is a text embedding summed with ten codec-codebook embeddings. Such a client never has one token id to look up, so `FalconH1ModelInner.callAsFunction(_:mask:cache:)` is unreachable for it, and today the only options are to fork the file or re-implement the mask setup and layer loop against internal details. Exposed at @_spi(FalconH1Encoder) scope, keeping this off the advertised public API of MLXLLM while making it usable outside the module: * FalconH1Configuration.hiddenSize / .numHiddenLayers / .rmsNormEps / .embeddingMultiplier * FalconH1DecoderLayer and its callAsFunction * FalconH1ModelInner.init, .embedTokens, .layers, .finalLayerNorm * FalconH1ModelInner.callAsFunction(inputsEmbeds:cache:) — new * FalconH1ModelInner.callAsFunction(_:mask:cache:) — was internal `callAsFunction(inputsEmbeds:cache:)` is the seam; the token-id overload now delegates to it, so the two paths cannot drift. No behaviour changes for existing callers: FalconH1Model still embeds, runs the stack and applies the head exactly as before. `FalconH1ModelInner.init` is exposed because constructing `FalconH1Model` is not an equivalent way in: the wrapper adds an `lm_head` whenever `tie_word_embeddings` is false, which is the decoded default. A client bringing its own head does not want that module and would otherwise have to account for it when matching module keys against a checkpoint. `FalconH1Model.model` and the mask helpers (`createSSMMask`, `createAttentionMask`) were already public, and none of the layer's stored property types are `private`, so unlike the Gemma 4 change nothing else had to widen. FalconH1EncoderAccessTests proves sufficiency the way the Gemma access tests do: it drives the stack using ONLY the exposed surface, importing MLXLLM without @testable and opting in via @_spi(FalconH1Encoder). It checks shape, determinism, that the seam agrees with the token path, that the layer stack can be driven a layer at a time to tap every hidden state, and that the stack actually transforms its input — the last so the suite cannot pass on a seam that returns its argument or runs zero layers. One test earns its place beyond access checking. `sanitize()` folds `embedding_multiplier` into `embed_tokens.weight`, which is right when the token lookup is the only thing entering the stack but is a live trap for a composite- embedding client: fold it and add unscaled contributions, and the lookup half is scaled while the rest is not. Measured against the PyTorch reference for the model above, that is 77% relative error on the embedding and 38% on the final hidden state — while still producing plausible audio of the right length, so listening does not catch it. testCompositeEmbeddingMultiplierEquivalence pins `(raw + other) * m == folded + other * m` and asserts the unscaled-remainder variant is observably different, both at the embedding and after the stack, so the wrong form cannot quietly become the expected one. Runs on a tiny randomly-initialized model; no weights are downloaded. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
- Restore the per-response usage update the adapter sends to FoundationModels. A July fix removed it because the beta SDK declared a call the shipping system library did not provide, and every request crashed the moment generation finished. - Confirm the mismatch is gone on Xcode 27 beta 6 with the macOS 27 and iOS 27 SDKs. The system library now provides the call, and a real request completes normally. - Before this change a caller read zero prompt tokens. Completion tokens were already counted from the streamed text, so totals looked plausible and the loss was easy to miss. - Add integration tests for the usage a caller actually reads: a new session starts at zero, one response reports both prompt and completion tokens, a session sums usage across turns, two sessions stay independent, and the streaming path agrees with its final snapshot. - Confirm the new tests fail without the restored update and pass with it. - Note the new tests need a macOS 27 host, so CI does not run them today.
…l-explore#579) * Suspend instead of blocking cooperative threads while weights load The Load API is synchronous and blocks its thread on file I/O and DispatchQueue.concurrentPerform, but every model factory calls it from an async context, parking a Swift concurrency cooperative thread for the whole load. Add an async loadWeights overload that hops to a global queue and suspends the caller, and use it from the factories. The synchronous overload remains for synchronous callers such as convert. * Disambiguate loadWeights doc links now that an async overload exists The new async loadWeights overload made three DocC symbol links ambiguous, failing the docs verification in CI. Point each link at the intended overload: the async one (-8b333) from porting.md, which describes the inference path, and the synchronous one (-6eqw7) from the model-conversion docs and the async overload's own doc comment.
- In `GenerationEventObserverTests`, two tasks drained the generation channel with an empty `catch {}` block. A read failure there would pass the test silently. Extracts one drain helper. Each test now awaits its result and accepts only a cancellation error.
- Asserts the expected error from every load and warmup task instead of discarding it with `try?`.
- The downloader and tokenizer-loader test stubs were classes with no stored state, marked `@unchecked Sendable`. That annotation tells the compiler to trust the type is safe to share across threads, without the compiler checking it. Converts the stubs to structs, which are `Sendable` by construction, so the compiler proves the guarantee instead of the annotation asserting it.
- `EventBox` and `SeedRecorder` hold mutable state a closure captures across a task boundary, so a struct will not work for them. They used `NSLock` with the same `@unchecked Sendable` escape hatch as the stubs above. Replaces the lock with the standard library's `Mutex`, so these types are provably `Sendable` too, instead of asserting it.
- In `GenerationEventObserverTests`, `withValue` took two closures, one passed as an argument and one as a trailing closure. swift-format's `OnlyOneTrailingClosureArgument` rule flags that form because it is easy to misread which parameter each closure binds to. Spells out the second closure with its argument label instead.
- `EvictBiasStubTokenizerLoader.load()` returns a `CountingTokenizer`, which requires OS 27. The old code checked that at runtime with a `guard` and a `preconditionFailure` that could never actually fire. Marks the stub itself with the OS 27 requirement, so the compiler enforces it and the dead runtime check is gone.
An empty catch and a discarded task result both hid a real loader failure, so a broken load could not fail a test. The fixtures also claimed thread safety by annotation where value semantics or a mutex states it, and asserted an availability requirement at runtime that the type system can enforce at compile time.
…follow-up) (ml-explore#471) feat(paroquant): MoE architecture support, prepared checkpoint caching, and rotation kernel optimizations ### MoE Support & Architecture - **PairwiseRotation & RotateSwitchGLU:** Extracted standalone `PairwiseRotation` module and implemented `RotateSwitchGLU` to support MoE PARO models (e.g., Qwen3.6-35B-A3B). - **MoE Loader Pipeline:** Added passes to stack per-expert AWQ weights, remap shared rotations, and patch switch GLU layers without mutating dense paths. - **Conversion Robustness:** Dropped theta-filter to convert un-partnered expert weights, match scales/biases to checkpoint float dtype, and optimized prefix matching from $O(N \cdot M)$ to $O(1)$. ### Performance - **Pre-Gather MoE Rotation:** Moved `gate_up` rotation before expert gather/sort, reducing row-rotation overhead by $1/\text{topK}$. - **Simdgroup Rotation Kernel:** Rewrote the Metal rotation kernel for `groupSize == 128` to execute in a single simdgroup with `simdgroup_barrier` (with generic fallback for other sizes), delivering up to 2x speedup. - **GatedDelta Fusion:** Compile-fused the 6-kernel elementwise decay gate chain into a single dispatch. - **Prepared Checkpoints:** Added background caching of converted weights to `prepared_checkpoint.safetensors` with self-healing validation manifests, cutting warm-load times significantly. ### Fixes & Cleanups - Unified `RotationDerivedState` and batched GPU evaluation across all rotation modules at load time. - Froze `PairwiseRotation` parameters to allow fused weighted reduction in `SwitchGLU`. - Fixed tool-call format and chat convention resolution in `loadParoQuantModel`. - Fixed volume free-space detection for disk persistence on CI runners. Refs ml-explore#208, ml-explore#209, ml-explore#220, ml-explore#424, ml-explore#471
…e#605) - Adds `await` to the two `loadWeights` calls in `Gemma4AssistantDraftModelIntegrationTests.swift`, both inside `async throws` test functions. - Adds `await` to the `loadWeights` call in `loadTargetAndDrafter` in `MTPIteratorEndToEndDiagnosticTests.swift`. - Adds `await` to the two `loadWeights` calls in `loadRung4Drafter` in `MTPRung4TokenParityTests.swift`. ml-explore#579 added an async `loadWeights` overload next to the existing synchronous one. Swift prefers the async overload inside an async function, so a plain `try loadWeights(...)` in an async function now needs `await`. These five calls sit inside async functions but never awaited. None compiled. The package's CI never builds IntegrationTesting. The only job that builds it, `integration_build_xcode27`, is disabled with `if: false`, so ml-explore#579 merged despite breaking this project.
…l-explore#602) loraLayers returned only selfAttn, so adapters targeting mlp.* failed LoRAContainer.load with unhandled keys. Gemma3Text/Qwen35/Llama (and the Gemma4 VLM wrapper) return the decoder layers; match them. Adds a regression test that loads a synthetic self_attn + mlp adapter onto a tiny Gemma4TextModel. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Support differentiation and activation checkpointing in gated-delta recurrence
• Enable training via ops fallback: The fused Metal CustomKernel lacks a VJP, causing fatal aborts during backward passes (e.g., in Qwen3.5/Qwen3-Next). Added a useKernel flag to gatedDeltaUpdate (defaults to true), passing !training from calling models to fall back to the differentiable ops path, matching Python mlx-lm. Added gradient sanity and numerical parity tests.
• Chunked activation recomputation: The step-by-step ops graph retains all intermediate states, consuming unviable amounts of memory at scale (~4 MB/step for Qwen3.5-27B). Wrapped recurrence in 16-step chunks via CustomFunction to recompute states during backward passes, mimicking mx.checkpoint.
• Inference unchanged: Continues using the fused kernel by default.
…ml-explore#613) NaiveStreamingDetokenizer.next() measured the common prefix between the previous decode and the new one in Characters, so a token that appended a combining scalar (U+FE0F, a zero-width joiner, an accent) to the previous character re-emitted the whole merged cluster: a ZWJ flag sequence streamed as its base flag repeated, a quote followed by a variation selector as two quotes. The prefix is now measured in Unicode scalars, which compares exactly and keeps the fallback for tokenizers whose decode is not append-only. Four tests in StreamingDetokenizerTests stream a ZWJ flag sequence, a variation selector after an ASCII quote, a combining accent, and a variation selector after a multi-byte character split across two tokens, and compare the scalar sequence with the full decode.
* Add configuration-based LoRA metadata discovery * Share LoRA metadata discovery across LLM and VLM factories
…l-explore#584) RotatingKVCache: make trim wrap-aware instead of corrupting the ring Speculative decoding rewinds rejected drafts by trimming, but trimming a wrapped ring previously left dead rows in the logical timeline. Trimming now linearizes the ring to temporal order and discards the newest rows, clamped to the non-pinned span. • Direct callers (speculative iterators): Accept documented, bounded window-edge loss rather than silent corruption when overwrites have occurred. • Exact callers (isTrimmable): Retain strict offset + positions < maxSize semantics for staged rounds, restore points, and prompt cache reuse. • State & layout: Decouple offset == fill by tracking live rows via idx and an explicit wrapped flag (serialized as a 7th metaState value; backward-compatible with 5/6-value legacy states). • Includes a fix for rotating cache trim following legacy restore.
## Add bounded cross-dialect tool-call recovery - Recover textual tool-call protocols missed by the selected parser, while preserving native frames and response ordering. Adds streaming, authorization, EOS, buffer-limit, and performance coverage. - Validate native XML tool calls against the shared Qwen payload grammar. - Validate tool-call arguments conservatively: add a package-scoped, three-state schema evaluator that rejects only proven violations (unsupported schema assertions fail open) at the common executable-call boundary, applied consistently across generic, Harmony, and Onyx calls. - Tighten recovery promotion: EOS repair only re-frames text after a `[TOOL_CALLS]` marker; markerless rehearsals promote only under the permissive policy; union/combinator-typed arguments coerce from their wire value before validation. - Fix native tool-call scanning to resume correctly after false openers, preserving leading text for incomplete calls. - Make strict tool-call validation opt-in.
A turn that adds a new image to an unchanged transcript extends the cached prefix exactly as a text turn does, but ml-explore#472 excludes every media turn from reuse, so it re-prefills the whole transcript and re-runs the vision tower over every cached image. Add PreparedInputSplitting, an opt-in protocol for models that can split their prepared input at a token boundary and keep only the suffix's media. AppendOnlyMediaRule fires when the turn carries new media, extends the cached prefix, and no speculative decoding is configured; ChatSession asks the model to split, verifies the returned tokens against the boundary, and downgrades to .rebuild otherwise. Qwen2.5-VL conforms: its vision mask isolates each frame, so dropping a cached image leaves the remaining features unchanged (tested on a tiny random-weight model). Qwen2-VL attends across images and does not conform; the same test shows the divergence. Video, temporal grids, audio, precomputed position ids, non-uniform masks, and boundaries inside a media block are refused and rebuild as before. No other model changes.
TokenIterator.next() cleared the buffer cache when tokenCount % 256 == 0, but checked after incrementing tokenCount, so the first clear came at token 256. mlx-lm checks before incrementing and also clears on the first token, right after prefill. A generation shorter than 256 tokens never cleared, so repeated short requests grew the cache without bound. Co-authored-by: Joshua Langberg <negativetime@me.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.
* 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
GLM4MoELiteAttention updated its cache with cache.update(keys:values:) and called MLXFast.scaledDotProductAttention directly, so kvBits trapped on the first decode step: maybeQuantizeKVCache swaps in a QuantizedKVCache whose update(keys:values:) is a fatalError. Route the update and the attention through attentionWithCacheUpdate, like the other MLA models. That exposed a second bug. quantizedScaledDotProductAttention reshaped its GQA output with the query head dim, but MLA caches store [kvLatent, kPe] as keys and only kvLatent as values, so the output is narrower than the queries and the reshape trapped. Use the value head dim; for caches with square head dims the shape is unchanged. Fixes ml-explore#652
…explore#625) `ToolCallProcessor` checked the whole buffered call for its end tag on every chunk while collecting a tagged call, on the native path and on the cross-dialect recovery path that declared tools enable, so a call costs time quadratic in its length: seconds for a call of ten thousand tokens, paid once on the live stream and again wherever the stream is replayed. Only the text a chunk appends can complete the end tag — an earlier occurrence was already in the buffer when the previous chunk was scanned — so both scanners now check the appended bytes plus the tag's overlap with what preceded them, and run the full structural frame scan only when that window holds the tag. The chunk that opens the frame still scans the whole buffer, which then holds at most the start tag and that chunk. Tests: a 40k-character call streamed one character at a time parses in linear time, with and without declared tools; the end tag is found when it is split across chunks, when it arrives in the chunk that completes the start tag, and when another call follows it in the same chunk.
…re#654) * MLXEmbedders: add createBidirectionalAttentionMask Encoder models need a bidirectional attention mask with an optional symmetric window and key padding. The existing helpers do not fit: createAttentionMask is causal, and createBidirectionalMask and createBidirectionalSlidingWindowMask in MLXLMCommon build additive masks with no padding and a window on the absolute key position. createBidirectionalAttentionMask(length:halfWindow:paddingMask:) returns .none when halfWindow and paddingMask are both nil. Otherwise it returns a boolean [batch or 1, 1, length, length] mask where query i may attend key j when |i - j| <= halfWindow and key j is not padding, or when i == j. - Padding hides key columns only, as in transformers, so a padded query row still sees the real keys. The boolean key mask follows Qwen3. - The diagonal is always kept, so no row is fully masked. For a fully masked row, MLX's attention returns a uniform average, zeros or another finite value depending on the kernel path. - A window that covers the whole sequence skips the band, so a huge halfWindow never reaches Int32. Tests cover the inclusive band bound, a zero window, padding on columns, padding dtypes, a single token, and agreement on real rows with the transformers 5.17 Gemma 3 sliding-window rule for windows 7, 8 and 9. Co-Authored-By: Claude <noreply@anthropic.com> * MLXEmbedders: use bidirectional attention in EmbeddingGemma EmbeddingGemma is a bidirectional encoder and its config.json says so ("use_bidirectional_attention": true), but the Swift backbone ignored the key and built causal masks, so every token saw only the tokens before it. Against transformers 5.17 with the original google/embeddinggemma-300m weights, the final embeddings had a cosine of only 0.45 to 0.70. Gemma3Configuration now decodes use_bidirectional_attention; absent or null means false. When it is true: - Sliding layers see sliding_window / 2 tokens on each side. This is the band transformers uses: it stores sliding_window // 2 + 1 and tests |i - j| < it, so 512 gives |i - j| <= 256. - Global layers see every token. - The padding mask passed to EmbeddingGemma.callAsFunction reaches the backbone and hides padded keys on every layer, so a padded batch gives the same states as its texts run one at a time. A 1-D mask is accepted with a 1-D input, and the backbone checks that the mask and the inputs have the same shape. Without a mask, attention sees no padding, as in transformers; padded batches need attentionMask. When the flag is false or absent the masks are the causal ones as before, so gemma3 and gemma3_text checkpoints that are causal by design do not change. Tests cover the flag-false path (padding ignored, causal, causal window), config decoding, bidirectionality in both directions, the window bound for sliding_window 8 and 9, right, left and mixed-length padded batches against single texts, 1-D inputs, and bfloat16 weights with padding. Fixes ml-explore#638 Co-Authored-By: Claude <noreply@anthropic.com>
Qwen3VL delegates to the shared QwenVL.splitPreparedInput with its own image and video token ids and spatial merge size, so ChatSession can reuse the KV cache on append-only media turns as it does for Qwen2.5-VL. The shared split holds for this model because its vision attention is block-diagonal per media item and deepstack features are rebuilt from the pixels on every forward. Qwen3VLMoE does not conform because it has no offset-aware continuation path.
* Parse GLM-4-0414 markerless tool calls (ml-explore#491) GLM-4-9B-0414 emits `name\n{json}` with no delimiters, so the marker driven pipeline never invoked the `.glm4` parser and the call leaked into the response text. Add `NamedJSONCallScanner`, a schema-anchored scanner (byte trie over the declared tool names + balanced JSON object), shared by the recovery lexer for streaming detection and by `GLM4ToolCallParser` as a fallback when no `<arg_key>` markers are present. Detection is line-anchored and only fires for a declared tool name, so ordinary `word\n{...}` prose is untouched. The integration harness now passes `tools:` to `generate`, as `ChatSession` already does; markerless detection needs the declared names. Re-enable `glm4EndToEnd`. * Fix GLM4 protocol markers in JSON arguments
Qwen3.5 and Qwen3-Next normalize q and k in the gated delta net with `invScale * rmsNorm(x, eps: 1e-6)`, where invScale = D^-0.5 and D = linear_key_head_dim. rmsNorm adds eps to mean(x^2), so the result is x / sqrt(sum(x^2) + D * 1e-6). The reference `l2norm` in transformers (qwen3_5 and qwen3_next) is x / sqrt(sum(x^2) + 1e-6), so the effective eps was D times too large (128x for Qwen/Qwen3.5-0.8B). Pass eps = 1e-6 / D to rmsNorm. Then sqrt(mean(x^2) + 1e-6 / D) = sqrt(sum(x^2) + 1e-6) / sqrt(D), which matches the reference. The invScale factors do not change. This affects the MLXLLM qwen3_5, qwen3_5_moe, qwen3_5_text and qwen3_next models and the MLXVLM qwen3_5 and qwen3_5_moe models. GatedDeltaQKNormTests compares each of the three layers with an output built from the same modules and the reference l2norm, on tokens scaled from 1 down to 1e-6. The largest per-token relative error goes from 0.984 to 2.4e-6 or less.
) Add `ChatSession.fork(history:)` to reuse prefix KV caches across conversations Starting every `ChatSession` with an empty cache causes expensive, redundant prefills for shared prompts (e.g. system instructions, tool schemas). `fork(history:)` creates a new session sharing the existing session's cache, configuration, and draft model, prefilling only the diff. Key changes: - `ChatSession.fork(history:)`: Returns a session with a sliced copy of the KV and draft caches; shares memory until write. - Cache pre-flight checks: Validates media presence before copying to avoid wasteful deep copies (e.g., in `VarianceNormalizedKVCache`). - Transcript validation: Requires exact token-by-token prefix matches and falls back to an empty cache if media is present. - Cache support: Implemented `copy()` for `TurboQuantKVCache`. - Concurrency: Made `fork` `nonisolated(nonsending)` so caller actors can fork without hop/executor overhead.
Fix Qwen reasoning history, Swift 6.3 isolation, and test sync - Qwen: Preserve prompt-priming provenance, pass reasoning via reasoning_content, and add 3.8/3.6 regression tests for cache reuse and fallback. - ChatSession: Fix Swift 6.3 isolation checker failure in Task closure. - Tests: Fix cache-clearing synchronization race.
* scripted Tokenizer - part 1 of scripted Tokenizers, Tools and LanguageModels - create a new Tokenizer from a simple corpus - behaves like a real Tokenizer (BPE style) and can do bidirectional encode/decode
…lore#685) * MLXEmbedders: build the README example mask from text lengths The "Generate embeddings" example pads every text with the EOS token and builds the attention mask as `padded .!= eosTokenId`. Tokenizers that end every text with a real EOS token, such as EmbeddingGemma's, then lose that token as well: the mask hides it from pooling and, since ml-explore#654, from attention. Build the mask from the real lengths instead, in the same shape as the padding above it. EmbeddingGemma (mlx-community/embeddinggemma-300m-bf16) in float32, an EOS-padded batch of an 11-token query and a 548-token text, cosine against sentence-transformers: 0.776 and 0.969 with the old mask, 1.00000 for both rows with the new one.
Add compiled decode for Qwen3.5 VLM models - Compile eligible single-token decode for plain, rotating, and quantized caches (per-layer GDN/MoE), keeping dynamic M-RoPE and cache mutation eager. - Correctly invalidate dependent traces on submodule updates using weak references to preserve deallocation. - Synchronize fused-projection trace registry to support concurrent registration. - Clean up unused test helper and add regression coverage (exactness, lifecycle, concurrency, submodule updates). AI assistance: Codex implemented the fix and regression tests.
Syncs the fork with upstream main (65 commits, through ml-explore#662) for numen-tech/gemma4-qat#283. Conflicts: - Package.swift: take upstream's; mlx-swift stays on numen-tech/mlx-swift branch "prism" (upstream pins 0.32.3). - Qwen3VL.swift: keep the fork's VisionResourceReleasing extension and upstream's PreparedInputSplitting conformance (ml-explore#627) side by side. - Qwen35.swift: take upstream's file (ml-explore#614, ml-explore#662, ml-explore#679) and re-apply the NumenKit seam. LanguageModel.hiddenStates(..., lastTokenOnly:) is ml-explore#614's forward minus the LM head; callAsFunction = hiddenStates + applyLMHead + MTP state, unchanged behavior. Qwen35.backboneHidden passes lastTokenOnly: false so speculative verify gets every position. Public seam signatures (backboneHidden, backboneLogits, backboneEmbed, textOnlyContinuationState) are unchanged.
…l-explore#614's trim ml-explore#614 trims the final prefill chunk's LM-head input to a 64-row-aligned tail when lastTokenOnly is set and the projection is 4/8-bit affine. Speculative verify reads every row, so the seam must never take it. 130 tokens on a 4-bit projection is a trimmed length (ml-explore#614 trims >= 97); flipping backboneHidden to lastTokenOnly: true fails this with 66 != 130.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
Sync
numen/mainwith ml-explore/mlx-swift-lm main and keep the NumenKit Qwen3.5 speculative seam on top of upstream ml-explore#614.Tracking: numen-tech/gemma4-qat#283. Companion mlx-swift PR: numen-tech/mlx-swift#11 (
prism-282-sync).What's in it
7eb77efa("Add compiled decode for Qwen3.5 VLM models (Add compiled decode for Qwen3.5 VLM models ml-explore/mlx-swift-lm#662)"), 65 commits, intonumen/main(e6d354a2).Qwen35ContinuationTests.testBackboneHiddenReturnsEveryPositionOfQuantizedProjectionPrompt.Package.swiftis upstream's, except that mlx-swift points athttps://github.com/numen-tech/mlx-swift.gitbranch: "prism". Upstream pins.upToNextMinor(from: "0.32.3"); the fork's branch carries no version tag. This PR builds against theprismbranch, so it should merge after numen-tech/mlx-swift#11 lands onprism. Locally, I verified it againstprism-282-sync@b721fdd8.Conflicts and resolutions
Package.swiftbranch: "prism"vs upstream0.32.3)branch: "prism"Libraries/MLXVLM/Models/Qwen3VL.swiftextension Qwen3VL: VisionResourceReleasingnext to upstream's newextension Qwen3VL: PreparedInputSplitting(ml-explore#627)Libraries/MLXVLM/Models/Qwen35.swifthiddenStates/applyLMHeadsplit vs ml-explore#614'slastTokenOnlyprojection trim, plus the seam block vs ml-explore#679'sprepareCheckpoint/throwingsanitizeTests/MLXLMTests/Qwen35ContinuationTests.swiftauto-merged cleanly: the fork's two seam tests plus upstream's ml-explore#583/ml-explore#649 edits.ml-explore#614 seam decision
Qwen35Language.LanguageModel.hiddenStates(..., lastTokenOnly:)is upstream's Reduce unused vocabulary projections during Qwen prefill (~8% speedup) ml-explore/mlx-swift-lm#614 forward up to and including thequantizedVocabularyProjectionInputtrim, without the LM head.lastTokenOnlyhas no default, so each caller states it.callAsFunction(..., lastTokenOnly: Bool = false)ishiddenStates+applyLMHead+ the MTP state block. It is equivalent to upstream: when the drafter flag is set the trim is skipped, somtpLastHiddenStatesKeystill gets the untrimmed hidden states.Qwen35.backboneHiddencallshiddenStates(..., lastTokenOnly: false). Speculative verify reads every position, so the seam never returns Reduce unused vocabulary projections during Qwen prefill (~8% speedup) ml-explore/mlx-swift-lm#614's 64-row-aligned tail.backboneHidden(_:cache:),backboneLogits(fromHidden:),backboneEmbed(_:),textOnlyContinuationState(batchSize:)and Qwen3VLreleaseVisionResources(reloadingFrom:).Qwen35, only the single-shot coldpreparepath passeslastTokenOnly: true.prepareContinuation(warm or windowed) andcallAsFunctionstay untrimmed.ropeDeltasKey,QwenVL.continuationAnchorandcontinuationResumeStateare untouched.The new test quantizes the tiny model's projection (4-bit, group 32) and feeds a 130-token text prompt. ml-explore#614 trims that length; it does not trim below 97 tokens. The test asserts
hidden.dim(1) == 130and that the seam logits match the regular forward on every row. IfbackboneHiddenis flipped tolastTokenOnly: true, the test fails with("66") is not equal to ("130").Upstream triage
What NumenKit has to handle in its own sync (numen-tech/gemma4-qat#283):
sanitizenowthrows, which needs atryinNumenMappedWeights/MappedModelWeights.swift.RotateQuantizedLinearruns inside those traces in both regimes.RotatingKVCache.trim.Tests
xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation -parallel-testing-enabled NO -only-testing:MLXLMTests/Qwen35ContinuationTests: 12/12 passed.... -only-testing:MLXLMTests:** TEST SUCCEEDED **. XCTest ran 734 tests: 730 passed, 4 skipped, 0 failures. Swift Testing ran 1060 tests in 88 suites, all passed. The 4 skips are env-gated benchmarks or local-checkpoint checks:Gemma4FusionTests.testFusionLatency,Qwen35FusedGDNProjectionTests.testRealCheckpointBenchmark,Qwen35PrefillLogitsTests.testLocalCheckpointTextAndVisionParityandQwen3PrefillLogitsTests.testLocalCheckpointPreservesLogitsCacheAndContinuation.xcrun swift build:Build complete!Merge order.
Package.swiftpins numen-tech/mlx-swiftbranch: "prism", which only builds this branch once numen-tech/mlx-swift#11 has merged intoprism. Merge numen-tech/mlx#10 first (merge commit or rebase, not squash: mlx-swift pins core2fc35a34), then numen-tech/mlx-swift#11, then this PR. Verified here againstprism-282-sync@b721fdd.Codex round
branch: "prism"resolves to the pre-sync mlx-swift until GatedDelta: opt-in float16 recurrent state storage (gemma4-qat#1697 spike) #11 merges. This is expected, given the merge order above; no code change.