Repository navigation
Sync numen/main with ml-explore/mlx-swift-lm 3.33.0 (numen-tech/gemma4-qat#1962) - #15
Conversation
* Serialize integration tests and their model loading. - many models were loaded at once - while interesting, this easily overwhelms memory - gate largest model on actually having enough memory to run it
swift-jinja throws on NSNull, so once a tool call with a null argument was in history every later prompt failed. Tool-call arguments now reach the template with null as Optional.none, which swift-jinja renders as null.
**Add DiffusionGemma support** - Add production-ready DiffusionGemma support. - Rename `LanguageModelCapabilities` to `LMModelCapabilities` to avoid a FoundationModels clash. - Fix DiffusionGemma review issues. - Expose live K/V from `VarianceNormalizedKVCache`. DiffusionGemma's decoder reads the prompt through `currentKeyValues()`, which the cache left as the default `nil`. Decoding therefore ran without the prompt in those layers and produced wrong answers. The cache now returns its dense, chronological K/V (completed tiles plus the raw tail, trimmed to the offset). The output now matches the default cache. - Use the Gemma 4 image geometry. Images and frames were resized to 224x224 with a fixed 280 soft tokens. That size is not a multiple of 48 (`patch_size * pooling_kernel`), so only 21 of the 280 tokens carried image content. - `DiffusionGemma4Processor` now resizes each image within `image_seq_length` cells and each video within `video_processor.max_soft_tokens`. It keeps the aspect ratio and gives each placeholder its item's own token count. - `DiffusionGemma` encodes each image and frame at its own size and batches neighbouring items of the same size. - The fixed-length padded encoder path and its `-inf` mask are removed, which restores `Gemma4Encoders.swift` to upstream. - On diffusiongemma-26B-A4B-it-mxfp4, the COCO "two cats" photo (000000039769) now reports 2 cats instead of 1. A text-only image reads the same as before.
…n tests (ml-explore#756) * Add LiquidAI LFM3 text model support * Share the LFM3 text backbone for multimodal wrappers Move the LFM3 configuration, decoder blocks, and backbone to MLXLMCommon so an MLXVLM wrapper can reuse them; LFM3Model, its registry entry, and LoRA stay in MLXLLM. The backbone takes token ids or embeddings through the same code path, uses caller-owned caches for positions, and accepts an optional mask per attention type. It exposes embed(_:), projectLogits(_:lmHead:) for tied and untied heads, and newCache(parameters:). LFM3Model conforms to HiddenStateLanguageModel. Keep the bare lm_head module path when stripping the language_model prefix, so an untied lm_head keeps its per-layer quantization. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(lfm3): harden implementation and expand regression coverage * chore(lfm3): remove incorrect Apple attribution from new tests * fix(lfm3): align validation and tests with review feedback * fix(lfm3): address backbone and generation review feedback * Move tokenizer validation to BaseLanguageModel --------- Co-authored-by: pHequals7 <ce17b115@smail.iitm.ac.in> Co-authored-by: Pranav Hari <39328505+pHequals7@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
MoEGate gathered the routing weights from the bias-corrected, group-masked scores, applied routed_scaling_factor only when it normalised them, and computed the scores in the activation dtype. mlx-lm uses e_score_correction_bias only to choose the experts, gathers the weights from the sigmoid scores, always applies the scaling factor, and scores in float32. With a bfloat16 bias near 4, bfloat16 selection scores take about a third as many distinct values as there are experts and change which experts are selected. Score in float32 and return the weights in the input dtype, as DeepSeek's inference Gate does with weights.type_as(x), so the MoE output keeps the activation dtype. Add tests with expected values from mlx-lm's MoEGate in float32 and bfloat16.
…ml-explore#799) A Pythonic tool call that writes a regex or a Windows path as a raw string, like pattern=r"\d+", was rejected, so the tool got the raw text with the r and the quotes. With a declared string parameter the parser was not even tried. Python also joins adjacent string literals, as in ('part one ' 'part two'). The parser now reads r and u prefixes and adjacent literals as ast.literal_eval does.
…tSize (ml-explore#764) * Scale up GLM-OCR images with a side under 28 px GlmOcrProcessor threw for images with a side under patch_size * merge_size. QwenVL.targetSize now takes a scaleUpSmallSides flag that scales such images up first, as Glm46VImageProcessor.smart_resize and mlx-vlm do. Only GLM-OCR sets it, so the Qwen processors keep throwing like their transformers counterparts. * Match smart_resize's rounding and checks in QwenVL.targetSize Comparing QwenVL.targetSize with the Python smart_resize it ports (transformers' Qwen2-VL and GLM-4.6V processors, and mlx-vlm's GLM-OCR port) over ~12k image sizes found these differences: - Python's `round` rounds halves to even; Swift's `round` rounds them away from zero. Any side that's an odd multiple of `factor / 2` (e.g. 70 or 1022 px with factor 28) came out one factor larger. - The aspect-ratio check used integer division, so ratios just over 200 (10010 / 50) weren't rejected. - When scaling down for maxPixels, a side wasn't clamped to at least `factor` as it is in Python. - The arithmetic was done in Float instead of Double. With these fixed, the results match the Python implementations for every size in the comparison (GLM-OCR and Qwen2-VL budgets). * Spell out height and width in the GLM-OCR small-image test
* Keep Qwen2-VL vision attention inside each image Two still images each have t == 1, so the vision tower treated every patch row as one attention block. Each image could attend to the other. Attention now follows the cu_seqlens boundaries, which is what one image or one video already produced. * Run swift-format * update tests and comments to reflect fix --------- Co-authored-by: David Koski <dkoski@apple.com>
* Steer reasoning models and framed protocols at the next safe point ml-explore#608 ends a steered step at the next text boundary only when the model declares no reasoning protocol. Reasoning models and the framed Harmony and Onyx protocols finish their whole step instead, even in the middle of a thought. In an app that steers Qwen3.8-27B, an instruction sent while the answer streamed reached the model 190-217 chunks later (6.9-8.1 s), and one sent while the model was thinking waited 23.8 s for the rest of the thought and the whole answer. A step can now end at the next safe point, in the answer or inside a thought, with every decoder: - The standard decoder accepts a reasoning model while its emitter holds nothing back: no partial delimiter, no unresolved label, and no trailing whitespace of a thought. - Harmony and Onyx end inside an analysis, private, or visible frame, never in a header or a tool frame. - A safe point never follows whitespace. Templates commonly trim a message's trailing whitespace, so a step that ended on "\n\n" left the cache holding tokens the re-render dropped. Caches that cannot rewind, as in Qwen 3.5 hybrids and M-RoPE VLMs, then rebuilt the whole conversation: 2 of 8 cuts on Qwen3.8-27B did. - A thought that steering cuts short is recorded as finished, so a template that replays reasoning renders what the cache holds and the next step prefills only the new message. A thought cut by the length limit is still dropped. Measured in the app on an M5 Max: - Qwen3.8-27B-4bit: 0.22-0.30 s from the instruction to the first new text in the answer, 0.22 s inside a thought. All 11 cuts continued the cache append-only, and so did the turn after each. - Muse-Glimmer-30B-8bit (Onyx): the step ends 0.06-0.12 s after the instruction and new text follows in 0.50-0.67 s, from its private and visible frames alike. - LFM2.5-24B-A2B-OptiQ-4bit, which declares no reasoning protocol: 0.11-0.17 s, as before. Harmony is covered by scripted tests only. * Interrupt a response at its next safe point A client can stop a ChatSession response only by cancelling its consumer. That rolls the turn back: the prompt and the partial reply leave the transcript and the token ledger is cleared, so the next call prefills the whole conversation again. An app that keeps the stopped reply on screen also ends up with a transcript the model never saw. `interrupt(response:)` ends the response at its next safe point, the one a steered step uses, inside a thought too. The step reports the new `GenerateStopReason.interrupted`, the reply is recorded, and the stream finishes normally. Instructions the response has not applied are reported as failed with `responseEnded`. With `toolDispatch`, calls the model already made run first, and the step that answers them stops at its first safe point, so no tool result is left without an answer. Interrupting needs no structured conversation, so the token loop now receives the mailbox of a response from a raw restored cache too. Its steering is still rejected up front. Measured in the app on Qwen3.8-27B-4bit with thinking on: the response ends 0.04-0.05 s after the call in the answer or in a thought, and 0.41 s after a call made during prefill, which lets the model write its first token. Each time the next turn continued the cache and prefilled 25-28 tokens; after cancelling, it prefilled the whole conversation. `.steered` from ml-explore#608 is not in a release yet, so clients update their exhaustive switches over `GenerateStopReason` once for both cases. * Decide interruption inside the steering mailbox's take The runner checked `isInterrupted` and then called `take(closeIfEmpty:)`, two separate lock acquisitions. An interrupt that landed between them let `take` drain instructions queued before it, so the response added a user turn and ran one more step before it stopped at the next safe point. Nothing was lost, but the interrupt was not as prompt as it promises. Make the decision atomic: - `SteeringControl.take(closeIfEmpty:)` returns no instructions once the response is interrupted, under the same lock that drains the mailbox. The pending batch stays for `closeAndTake()`, which reports it as `responseEnded`, as `interrupt(response:)` documents. - `ChatSession` no longer checks `isInterrupted` before `take`. `isInterrupted` remains only for the token loop's stop reason. The mailbox owns its state, so the question "may this batch be applied" belongs with it rather than with a caller that reads the state twice.
…-explore#630) PrismML's Bonsai 2 27B ships as a Qwen3.8-27B whose language-model weights are ternary, packed in MLX affine 2-bit form in a Hadamard-rotated input basis: R = H·S/√n with n = 1024 and a ±1 sign vector per module. The config declares `model_type: prism_hadamard_qwen35`, `base_model_type: qwen3_5` and a `modules` manifest naming every packed module. The weights carry ordinary `.scales`, so a loader that skips the rotation accepts them and decodes fluent nonsense instead of failing. MLXLMCommon gains `HadamardQuantized.swift`, built on stock ops (`hadamardTransform` and the quantized layers' own forwards): - `SignedBlockHadamard`: the blockwise signed transform and its inverse, in float32 and cast back to the input dtype, as the reference runtime does. - `HadamardQuantizedLinear` rotates the input before the packed matmul. `HadamardQuantizedEmbedding` un-rotates looked-up rows and rotates the input when the table serves as a tied head. `signs` is a frozen parameter, so the pack's `.signs` tensors load like any other weight. - `HadamardQuantizedManifest` decodes the pack's declaration. - `HadamardQuantizedCheckpointPolicy` validates the manifest (schema, base model type, tensor namespace, activation layout and dtype, duplicate paths), replaces exactly the manifest's `Linear` / `Embedding` leaves with rotated placeholders before the weights load (rejecting a block that does not divide the layer's width), and prepares the checkpoint: it rejects sign vectors other than ±1 and casts the unpacked float32 tensors to the activation dtype, except `A_log`, as mlx-vlm's converter does. MLXLLM and MLXVLM each gain `Models/PrismHadamardQwen35.swift`: `PrismHadamardQwen35Model: Qwen35Model` and `PrismHadamardQwen35: Qwen35` substitute the manifest modules in `init` and override `prepareCheckpoint` to run the policy after the base class maps the checkpoint names. The vision class inherits `Qwen35`'s on-demand vision tower, whose deferred load runs through the same override. Both registries map `prism_hadamard_qwen35`, and `LLMRegistry` and `VLMRegistry` gain `bonsai2_27B_ternary_2bit`. `HadamardQuantizedTests` (16) cover the transform, both layers, the substitution and its rejections, the loader's quantize pass, manifest and sign validation, both registries, the vision tower loading only for media, and the exact-class guards that keep upstream's projection fusion and prefill trimming away from rotated layers.
The SwiGLU clipped with MLXArray(limit) bounds. MLXArray(Float) is a float32 array, so clip promoted bfloat16 activations to float32. From the first MLP on, the residual stream, the later layers' KV caches and the logits ran in float32. Plain Float bounds follow the activation dtype, as the scalar bounds in mlx-lm's swiglu_oai do. The new tests check that a bfloat16 MLP block keeps bfloat16, and that the whole model, with and without affine quantization, keeps bfloat16 in the prefill, in a decode step and in the keys of each layer's cache.
…explore#734) A hard reasoning budget ends the span with the model's declared budgetTransition, or with ReasoningBudgetTransition.immediate when it declares none. Only QwenReasoningProtocol.qwen3 declared one, so every other reasoning model relied on an untested fallback. Measure the fallback and declare it where it holds. Muse Glimmer answers the user after a forced <|eom|>: over 20 cuts it never resumed reasoning and never ended the turn, while forcing an answer header instead pushed scratch work into the user-visible answer. Qwen3.5 answers after a bare </think> just as well as with Qwen3's early-stop text, and far better than unbounded reasoning, which runs past the generation limit. Express a validated transition as a delta on one protocol definition. ReasoningConfig.declaringBudgetTransition(_:) returns a copy that adds the transition, so QwenReasoningProtocol.qwen3 and .qwen35 both derive from .tagged and a new OnyxReasoningProtocol.glimmer derives from .frames. Delimiters keep a single definition, a family adapter restates only what it measured, and a later model cannot inherit a transition by sharing the control vocabulary. A test asserts the transition is the only difference between a family and its base protocol. Mellum and DeepSeek-R1 distills were measured too and are deliberately left undeclared: .immediate is measurably worse for them than ending the span with text, so they need their own evidence before they get a declaration. Developed with Filo assistance.
…l-explore#733) Add optional logitSampler: and logitProcessor: parameters to GuidedGenerationLoop.run. Nil keeps greedy sampling. The processor gets the same lifecycle calls as in TokenIterator, and a sampler that picks a token the grammar excludes throws instead of ending the run.
On Apple silicon with neural accelerators (M5 and later) MLX runs float32 matmuls as TF32 unless MLX_ENABLE_TF32=0, and five tests fail there with default settings. - HadamardQuantizedTests (2 tests), EmbeddingGemmaMaskTests G7 and LFM2DSparkMetalTests.rotatingHybridCacheMatchesGreedyAcrossWindow use MatmulPrecision.tolerance: the float32 bound is unchanged, the reduced bound applies only where the probe measures TF32. - EvalTests speculative log-probability test runs on the CPU, which pins IEEE float32: it compares top-k order exactly, and TF32 reorders near-ties.
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 956beaefd9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Fork patches: DiffusionGemma review findings from #15 (confidence sampler, chunked prefill, processor config round trip)
Syncs
numen/mainwith ml-explore/mlx-swift-lm tag3.33.0(ca661dc, 2026-11-17): 17 commits past6352907, the base of the last sync (numen-tech/gemma4-qat#1692, fork PR #9). Tracked in numen-tech/gemma4-qat#1962 (epic #1970). A merge, as #9 was. mlx-swift 0.33.0, which 3.33.0 picks up, is already in theprismbranch this repo'sPackage.swiftnames, soPackage.swiftmerged without a conflict.The merge
956beae:git merge 3.33.0intonumen/main(82e8f31), no conflicts (git merge-treesaid so beforehand). Six files change on both sides and auto-merged:KVCache.swift(disjoint regions), the twoQwen35.swiftcopies (upstream's change isreasoningConfig.taggedto.qwen35, ml-explore#734),GPTOSS.swift(the fork's@Sendableclosures plus upstream ml-explore#792),Qwen35ContinuationTests,KVCacheTests.What the 17 commits bring that the host cares about:
HadamardQuantizedLinear/HadamardQuantizedEmbedding,SignedBlockHadamard,HadamardQuantizedManifest/Module/CheckpointPolicyin MLXLMCommon, andPrismHadamardQwen35(MLXVLM) /PrismHadamardQwen35Model(MLXLLM) behind aprism_hadamard_qwen35registry key. The two layer class names clash with numen-tech/gemma4-qat's ParoQuantMLX layers; the host renames its own (PrismHadamardQuantized*, numen-tech/gemma4-qat#1962). The host keeps its own loader.GenerateStopReason.interrupted(the host's exhaustive switches get a case).QwenVL.targetSizerounds half to even; Keep Qwen2-VL vision attention inside each image ml-explore/mlx-swift-lm#755 Qwen2-VL vision attention stays inside each image; Declare default(measured) budget transitions for Muse Glimmer and Qwen3.5 ml-explore/mlx-swift-lm#734 Qwen3.5reasoningConfig.qwen35;KVCache.currentKeyValues()gets a default on every cache; the rest (Gemma diffusion, LFM3, DeepSeek-V3, GPT-OSS, GLM-OCR, tool-call rendering, guided generation, LoRA refusal, test sizing) is off the host's path.Semantic risk
Nothing textual conflicts, but upstream's
PrismHadamardQwen35andPrismHadamardQwen35Modelarefinalsubclasses ofQwen35/Qwen35Model, which the fork modifies (the speculative seambackboneHidden/backboneLogits/backboneEmbed,textOnlyContinuationState, the op-cost probe marks, the GDN rollback recording). They compile and upstream'sHadamardQuantizedTests(registry, checkpoint policy, on-demand vision tower through the subclass hook) pass on this head, so the subclass sees the fork'sQwen35as a base. The seam’sbackboneHiddencalls the language model’shiddenStates, which walks the module tree aftersubstituteModules, so it would run the rotated layers (not exercised by any test here); but nothing in the host takes that path: the host loads Bonsai through its own loader andqwen3_5, never theprism_hadamard_qwen35creator. The host's opt-in cross-check against upstream's loader on the staged 27B pack is in its Draft PR.What ran
xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidationon956beae(Xcode 27.0 / Swift 6.4, M3 Max): 2884 passed, 13 skipped, 1 expected failure, 0 failed (xcresult summary),** TEST SUCCEEDED **.Not run here: the host's model suites. numen-tech/gemma4-qat runs them against this head through its Draft PR, which pins
956beaeinPackage.resolvedunderbranch: numen/main; its results go on that PR. Merge this, then the host bumps the pin to the merge commit.