Skip to content

Merge upstream main into pico/integration - #108

Merged
ronaldmannak merged 19 commits into
pico/integrationfrom
claude/upstream-sync
Nov 18, 2026
Merged

ronaldmannak merged 19 commits into
pico/integrationfrom
claude/upstream-sync

Conversation

@ronaldmannak

Copy link
Copy Markdown
Owner

Merges ml-explore/mlx-swift-lm main into pico/integration. Part of one update of all three MLX forks.

What changed

Evidence

Tested together, with PicoCore and EngineRouter pointed at local checkouts of the claude/upstream-sync branches of mlx-swift and mlx-swift-lm (and through mlx-swift, this mlx):

$ xcodebuild test -scheme PicoCI -destination 'platform=macOS' -skipMacroValidation -skipPackagePluginValidation     # PicoCore
  mlx-swift: …/mlx-sync/mlx-swift @ local
􁁛 Test run with 804 tests in 109 suites passed after 37.100 seconds.
􁁛 Test run with 49 tests in 3 suites passed after 0.191 seconds.
􁁛 Test run with 55 tests in 10 suites passed after 0.047 seconds.
􁁛 Test run with 7 tests in 2 suites passed after 0.001 seconds.
􁁛 Test run with 10 tests in 2 suites passed after 2.133 seconds.
** TEST SUCCEEDED **

$ TEST_RUNNER_ENGINEROUTER_MLX_MODEL_DIR=… TEST_RUNNER_ENGINEROUTER_MLXSERVE_LIBRARY=… xcodebuild test -scheme EngineRouter-Package …     # EngineRouter, live
  mlx-swift-lm: …/mlx-sync/mlx-swift-lm @ local
MLX continued:  Paris.
MLX answered: Paris
Swift MLX:  Paris.
mlx-serve:  Paris.
􁁛 Test run with 70 tests in 16 suites passed after 21.050 seconds.
** TEST SUCCEEDED **

The EngineRouter run includes a real generation with mlx-community/Qwen3.5-4B-bf16 through mlx-swift-lm, and Swift MLX generating beside a second copy of MLX in the same process.

Not done on purpose

  • The mlx-swift-lm test suite was not run on its own; it ran through PicoCore's and EngineRouter's suites. The new Gemma diffusion and LFM3 models were not run.
  • Pico Server was not built against these branches.

🤖 Generated with Claude Code

davidkoski and others added 19 commits November 16, 2026 09:14
* 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.
… scores (ml-explore#772)

* Apply a per-row mask to each row of Gemma 2's grouped-query scores

Gemma 2 scores grouped queries as [B, kv, repeats, L, S]. A cache whose mask carries one row per sequence, shape [B, 1, L, S], aligned its batch axis with the key-value heads, so row b masked head b of every sequence. Give such a mask the head-group axis before applying it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Add a release decode benchmark

Benchmarks/DecodeBench times greedy decode of TokenIterator on a local model as a median over rounds, so a change to the decode path can be compared with its base. MLX_SWIFT_LM_PATH points it at another checkout.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep the Gemma 2 mask fix focused on its existing test suite

Move the per-row mask regression into Gemma2Tests and reuse its tiny model. Extract the standalone decode benchmark from the functional stack for separate review.

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Codex <noreply@openai.com>
Brings in 21 upstream commits, among them Gemma block-diffusion, LFM3 text,
DeepSeek-V3 MoE fixes, Qwen-VL and GLM-OCR image fixes, guided generation
with the caller's sampler, and a per-row Gemma 2 mask for batching.

The one conflict, in GenerateParameters, kept both new properties: this
branch's cacheEvaluationPolicy and upstream's diffusion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T18:36:10.944108Z 5943f6c PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5943f6cc34

ℹ️ 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".

@ronaldmannak
ronaldmannak merged commit 84b799a into pico/integration Nov 18, 2026
3 checks passed
@ronaldmannak
ronaldmannak deleted the claude/upstream-sync branch November 18, 2026 21:07
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.