Skip to content

Fix vision-encoder attention mask being ignored in Qwen2.5-VL - #238

Merged
davidkoski merged 4 commits into
ml-explore:mainfrom
NivDvir:fix/qwen25vl-vision-attention-mask
May 27, 2026
Merged

davidkoski merged 4 commits into
ml-explore:mainfrom
NivDvir:fix/qwen25vl-vision-attention-mask

Conversation

@NivDvir

@NivDvir NivDvir commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

Vision.Attention.callAsFunction receives attentionMask but the SDPA call was hardcoded to mask: .none, so the mask is silently discarded.

The mask is [1, seqLen, seqLen] boolean; SDPA's .array fast path wants an additive Float16 mask, so the change folds in the conversion.

+9/-1, one function. Split out from #222 at @vade's suggestion.

The Vision.Attention callAsFunction receives attentionMask but the
SDPA call was hardcoded to mask: .none, so the window/full attention
mask was silently discarded.

Converts the [1, seqLen, seqLen] boolean mask to an additive Float16
mask and passes it via .array(floatMask) to match the Python
mlx-vlm reference behavior.
@davidkoski
davidkoski force-pushed the fix/qwen25vl-vision-attention-mask branch from 7b6bb57 to 4c32277 Compare May 22, 2026 21:56
@davidkoski

Copy link
Copy Markdown
Member

Rebase on main to pick up CI fix

Comment thread Libraries/MLXVLM/Models/Qwen25VL.swift Outdated
Comment on lines +324 to +325
MLXArray(Float16(0)),
MLXArray(Float16(-10000)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Although the weight might be float16 right now, this should probably use the dtype, see also 3a7503d

Suggested change
MLXArray(Float16(0)),
MLXArray(Float16(-10000)))
MLXArray(0, dtype: q.dtype),
MLXArray(-10000, dtype: q.dtype))

Comment thread Libraries/MLXVLM/Models/Qwen25VL.swift Outdated
Comment on lines +321 to +322
let boolMask = attentionMask[.newAxis, 0..., 0..., 0...]
let floatMask = MLX.where(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This work on the attention mask is done per layer -- it would be better to hoist it into the VisionModel so that it can be used by all of the many blocks: [Qwen25VLVisionBlock]

NivDvir pushed a commit to NivDvir/mlx-swift-lm that referenced this pull request May 23, 2026
…block

Per davidkoski's review (CHANGES_REQUESTED on 2026-05-22):

1. dtype: build mask scalars in the same dtype as the q-tensor
   (carried by hiddenStates), instead of hard-coded Float16(0) /
   Float16(-10000). Matches the precedent in commit 3a7503d
   (Bert/NomicBert attention mask dtype fix).

2. hoist: convert the boolean masks (full + window) to additive
   float form ONCE at the VisionModel level — the conversion was
   previously done redundantly inside each of the 32 encoder
   blocks. The mask is constant across blocks for a given input
   so the per-block construction was pure duplication.

Inside Qwen25VLVisionBlock attention, the mask parameter is now
expected to arrive already in SDPA-ready additive form; the in-
block conversion is removed.

No behavioral change for the fp16 vision-encoder path (mask
matches the implicit dtype that q already carries). Other dtypes
(bf16, fp32) now produce a correctly-typed mask instead of
relying on implicit conversion from fp16.
…block

Per davidkoski's review (CHANGES_REQUESTED on 2026-05-22):

1. dtype: build mask scalars in the same dtype as the q-tensor
   (carried by hiddenStates), instead of hard-coded Float16(0) /
   Float16(-10000). Matches the precedent in commit 3a7503d
   (Bert/NomicBert attention mask dtype fix).

2. hoist: convert the boolean masks (full + window) to additive
   float form ONCE at the VisionModel level — the conversion was
   previously done redundantly inside each of the 32 encoder
   blocks. The mask is constant across blocks for a given input
   so the per-block construction was pure duplication.

Inside Qwen25VLVisionBlock attention, the mask parameter is now
expected to arrive already in SDPA-ready additive form; the in-
block conversion is removed.

No behavioral change for the fp16 vision-encoder path (mask
matches the implicit dtype that q already carries). Other dtypes
(bf16, fp32) now produce a correctly-typed mask instead of
relying on implicit conversion from fp16.
@NivDvir
NivDvir force-pushed the fix/qwen25vl-vision-attention-mask branch from e547487 to f804ac9 Compare May 24, 2026 00:53
Comment thread Libraries/MLXVLM/Models/Qwen25VL.swift Outdated
Comment on lines +591 to +600
// Build boolean masks once, then convert to additive float masks
// matching the q-tensor dtype (carried by hiddenStates as it
// flows through the encoder). Done ONCE here instead of inside
// each of the 32 encoder blocks — per davidkoski #238 review:
// • dtype: parity with the precedent in commit 3a7503d
// (Bert/NomicBert attention mask dtype fix)
// • hoist: avoid 32× redundant graph construction per layer
// The mask is constant across all blocks for a given input,
// so building it inside the per-block attention was pure
// duplication.

@davidkoski davidkoski May 26, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A comment is fine, but this maybe more commentary than is needed -- people can always go back to the PR the lines came from to see the discussion.

Suggested change
// Build boolean masks once, then convert to additive float masks
// matching the q-tensor dtype (carried by hiddenStates as it
// flows through the encoder). Done ONCE here instead of inside
// each of the 32 encoder blocks — per davidkoski #238 review:
// • dtype: parity with the precedent in commit 3a7503d
// (Bert/NomicBert attention mask dtype fix)
// • hoist: avoid 32× redundant graph construction per layer
// The mask is constant across all blocks for a given input,
// so building it inside the per-block attention was pure
// duplication.
// Build boolean masks once, then convert to additive float masks
// matching the q-tensor dtype (carried by hiddenStates as it
// flows through the encoder). Done ONCE here instead of inside
// each of the 32 encoder blocks

@davidkoski

Copy link
Copy Markdown
Member

Looks great, but I think the comment needs to be trimmed down a bit, then it is ready to merge!

NivDvir added 2 commits May 26, 2026 23:23
davidkoski: "A comment is fine, but this maybe more commentary than
is needed -- people can always go back to the PR the lines came from
to see the discussion."

Replaces the 10-line block (rationale + bullets) with the 4-line
version Koski suggested via the `suggestion` block.
Per davidkoski's ml-explore#238 standard ("people can always go back to the PR
the lines came from to see the discussion") applied harder: the
two comment blocks I'd kept were both restatements of what the
variable names and call structure already say.

Brings the comment-line ratio on this PR from ~40% to 0%, in line
with the maintainer's own recent PRs (ml-explore#283 2%, ml-explore#235 3%, ml-explore#228 0%).

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Great, thank you!

@davidkoski
davidkoski merged commit 2d0acae into ml-explore:main May 27, 2026
2 checks passed
davidkoski added a commit to NivDvir/mlx-swift-lm that referenced this pull request Jun 1, 2026
Gajesh2007 referenced this pull request in Layr-Labs/mlx-swift-lm Jun 26, 2026
…tive port) (#50)

* fix segsum dtype promotion -- 2x memory waste on hybrid SSM models (#229)

MLXArray(-Float.infinity) creates a float32 scalar. which() then promotes
the entire bf16 segsum output to fp32, doubling memory per SSM layer.

At L=2048 this wastes ~960MB on Qwen3.5-35B (30 GDN layers, 4 heads)
and ~24GB on Nemotron-30B (48 Mamba layers, 64 heads) per prefill.

Fix: match the -inf scalar to the accumulator dtype.
(cherry picked from commit 81829f6)

* Fix nomic-embed-text-v1.5 'Key embeddings.position_embeddings.weight not found' (#305)

(cherry picked from commit 9743c63)

* Fix EmbeddingGemma init-order crash + dense head hidden size (#223)

Fix EmbeddingGemma weight loading (`sanitize(weights:)`)

Two bugs prevented loading any `mlx-community/embeddinggemma-*` checkpoint:

1. **Init-order crash** — `sanitize(weights:)` assigned the dense head via `self._dense.wrappedValue = ...`, which fatals when `module != nil`. Route through `update(modules:)` instead.

2. **Wrong hidden size** — the dense head was initialized with `config.intermediateSize` (the backbone MLP dim), but the actual checkpoint expands 4× to `hiddenSize * 4`. Read the dim directly from `dense.0.weight` shape instead.

---
Co-authored-by: Anatoly Samoilenko anatoly.samoilenko@gmail.com
Co-authored-by: David Koski dkoski@apple.com

(cherry picked from commit f2f8b2e)

* fix: disable CIContext intermediate caching to prevent IOSurface exhaustion (#226)

CIContext() default options cache IOSurface-backed GPU textures for intermediate
filter results. Each frame in the VLM image pipeline (tone-curve → bicubic
resample → color-matrix normalize) allocates multiple IOSurfaces that are held
in the context cache across calls.

Processing a large library (hundreds of videos, each yielding several frames)
accumulates thousands of cached surfaces and hits the macOS per-process
IOSurface kernel limit of 16384, causing render failures:

  IOSurface creation failed: e00002be (likely per client IOSurface limit of
  16384 reached)
  -[CIContext _startTaskToRender:...] Render failed because of failure to
  allocate intermediate.

Fix: pass `.cacheIntermediates: false` when constructing the shared context.
Batch inference never re-renders the same CIImage twice, so the intermediate
cache provides no benefit. The change eliminates the surface accumulation while
leaving all functional behavior intact.

Co-authored-by: Vladimir <vladimir@sinitcin.com>
(cherry picked from commit 7e7663d)

* fix gated delta state precision -- fp32 state to match Python (#224)

* fix gated delta state precision -- fp32 state to match Python

State was typed as q.dtype (bf16), losing precision across T-step
recurrence. Python mlx-lm keeps state in fp32. Aligns Swift with that.

- kernel source: write o_state as StT not InT
- dispatch: add StT template, use state.dtype for output
- gatedDeltaUpdate: create state in fp32, upcast if needed

Before: kernel showed ~0.25 max diff vs ops fallback at T>1.
After: matches ops path.

Tested on M5 Max 128GB, Qwen3.6-35B-A3B-4bit.

Co-authored-by: tturney <tturney@psyguard.ai>
(cherry picked from commit c566c95)

* fix(ssm): fp32 g/beta consistency + masked-output zero in gatedDelta

Hand-port of upstream 93cf322 (targets the post-32d51e5 MLXLMCommon path
we did not adopt; re-derived into our MLXLLM/Models/GatedDelta.swift):
- computeGatedDeltaG keeps g in fp32 (no downcast to a.dtype)
- gatedDeltaUpdate keeps beta in fp32
- gatedDeltaOps state defaults to fp32
- gatedDeltaStepOps casts y back to q.dtype on return
- kernel zero-fills y for masked-out timesteps

g/beta inheriting bf16 forced a Metal kernel recompile between turns vs
the fp32 SSM state, triggering a use-after-free when reusing
QuantizedKVCache (our KV-quant path). Layers on top of c566c95.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(kv-quant): gate maybeQuantizeKVCache on first KVCacheSimple (hybrid SSM)

Hand-port of upstream 88beb40 (maybeQuantizeKVCache subset only; the rest
of that commit is the ParoQuant feature, which we skip). On hybrid
attention+SSM models (Qwen3.5, Qwen3-Next, Nemotron, Falcon-H1) cache[0]
is often a MambaCache, so gating on cache[0].offset silently no-ops KV
quantization. Scan for the first KVCacheSimple instead.

Behavior-preserving for our BatchKVCache continuous-batching path
(BatchKVCache is BaseKVCache, not KVCacheSimple, so it was never quantized
by this helper before or after).

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(tools): add .gemma4 ToolCallFormat case + auto-detect (8c61800)

Hand-port of upstream 8c61800. Adds a distinct .gemma4 ToolCallFormat
case and routes model_type prefix "gemma4" to it (checked before the
generic "gemma" prefix). Our GemmaFunctionParser is already a superset
that accepts both the Gemma (<start_function_call>) and Gemma4
(<|tool_call>) tag styles + both escape markers, so the new case maps to
the same parser; it exists for API parity and explicit format strings.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(tools): string-aware bare-JSON + declared-tool filter + FIFO drain (1335fb5)

Hand-port of upstream 1335fb5 (patch did not apply -- our ToolCallProcessor
is rewritten for multi-tag support and the EOS hunk lives in our forked
Evaluate.swift). Re-derived the three high-value parts:

- jsonBracesBalanced is now string-aware (tracks inString/escape), so a
  brace inside a JSON string value no longer miscounts depth and
  prematurely flushes partial JSON, corrupting the tool call.
- JSONToolCallParser drops bare JSON whose name is not a declared tool
  when tool schemas are supplied (false-positive hardening).
- ToolCallProcessor gains drainToolCalls() (FIFO emit-all, fixes
  multi-call turns dropping earlier calls) and processEOS(returnBufferedText:)
  to recover residual non-tool text at EOS instead of discarding it; the
  single-stream TextToolTokenLoopHandler now uses both. processEOS stays
  back-compatible (default arg + @discardableResult) for the server path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(kv-quant): group-size auto-resolve + quant-param serialization (01b8624)

Hand-port of the KVCache.swift subset of upstream 01b8624 (the Gemma4Text
attention half is deferred to the Gemma4 tier):
- resolvedKVQuantizationGroupSize() picks the supported group size
  ({32,64,128}) closest to the requested one that divides both head dims.
- KVCacheSimple.toQuantized + QuantizedKVCache.updateQuantized use it,
  so models whose head dim isn't divisible by 64 no longer hard-crash.
- maybeQuantizeKVCache skips head-dim-incompatible caches instead of
  reaching the fatalError.
- QuantizedKVCache.groupSize/bits are now private(set) var and the
  metaState setter restores them (the getter already serialized them);
  required so our encrypted prefix-cache persistence round-trips quant
  params instead of silently reverting to defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>

* revert(tools): drop distinct .gemma4 ToolCallFormat case (supersedes e89b8b3)

8c61800's intent (parse Gemma4 tool calls at the library layer) is ALREADY
satisfied in our fork by the unified .gemma format: our GemmaFunctionParser
accepts both the Gemma (<start_function_call>) and Gemma4 (<|tool_call>)
tag styles + both escape markers, and infer()/ServerToolParser map
gemma4* model types to .gemma by design. Adding a distinct .gemma4 case
was redundant, added no capability, and broke 6+ existing tests
(ToolTests, ToolCallParserIntegrationTests, ServerSurfaceTests) that
enshrine gemma4 -> .gemma. Keeping our superset design per
"our behavior wins; layer upstream fixes on top".

Co-authored-by: Cursor <cursoragent@cursor.com>

* perf(moe): fused gate_up single matmul + compiled GLU/combine kernels (b6aeaa6, ef85ed0)

SwitchLayers MoE improvements, re-derived onto our integrated
SwitchGLU(fuseGateUp:) path (our own e46b291 added fused storage but did
two matmuls on weight slices):

- b6aeaa6: the gateUpProj branch now runs ONE polymorphic gathered matmul
  (quantized + bias handled uniformly) and splits the float result,
  halving gather dispatches vs. slicing the packed weight twice. Verified
  bit-exact against separate projections (SwitchGLUTests).
- ef85ed0: add compiledSiluProduct (fused silu*up) + weightedExpertSum
  (compiled scale+reduce, used by Gemma4 combine in the next tier). Split
  SwitchGLU init so the default SiLU path uses the compiled product while
  custom-activation callers (Gemma4 gelu, Deepseek clipped-silu) keep the
  generic path. All ~20 SwitchGLU callers resolve unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix Qwen35 VLM crash on text-only inference (SmallVector out of range) (#149)

Qwen35Language.LanguageModel.callAsFunction assumes inputs is always 2D
[batch, seq], but text-only callers like WiredMemoryUtils.tune and
TokenIterator can pass 1D [seq] token arrays. This causes
getRopeIndex() and subsequent dim(1) calls to crash with
"SmallVector out of range" when accessing a non-existent dimension.

Add an ndim check at the top of callAsFunction to expand 1D inputs
to 2D before any dimension-dependent logic runs.

Fixes #148

(cherry picked from commit 3e2ddb4)

* Fix UserInput init not setting self.images / self.videos (#182) (#253)

Fix UserInput init not populating self.images/self.videos (#182)

Property observers don't fire during initialization, so prompt.didSet — which keeps self.images/self.videos in sync — was never called by two of the inits:

init(prompt: String, images:videos:tools:additionalContext:) built a .chat prompt from its parameters but never copied images/videos into self.
init(prompt: Prompt, images:videos:...) had an explicit case .chat: break, silently dropping the parameters.
Both inits now mirror init(chat:processing:tools:additionalContext:): extract images and videos from the chat messages, or use the explicit parameters for non-chat prompts.

Add regression tests for UserInput init image/video sync (#182)

Three tests pinning the contract that self.images/self.videos are populated at construction, not deferred to the next prompt assignment:

testInitFromPromptStringPopulatesImages — string-based init reflects the images parameter immediately.
testInitFromPromptEnumPopulatesImagesForChat — the .chat branch of the Prompt-based init derives images from chat messages rather than dropping them.
testInitFromPromptStringPopulatesVideos — symmetric coverage for the videos parameter.

(cherry picked from commit d6f3529)

* fix Idefics3 prepare() to honor windowSize -- prompt prefill is never chunked (#297)

(cherry picked from commit a65869e)

* fix Idefics3 vision encoder dtype -- SigLIP runs in float32 instead of bf16 (#296)

(cherry picked from commit 3c6dd34)

* Fix vision-encoder attention mask being ignored in Qwen2.5-VL (#238)

Fix Qwen2.5-VL vision attention mask being ignored

- Pass attention mask to SDPA (was hardcoded to `.none`)
- Convert boolean mask to additive float using q-tensor dtype
- Hoist mask conversion to VisionModel level (once, not per-block)

(cherry picked from commit 2d0acae)

* Fix Qwen2-VL chat template: emit vision tokens before text (#242)

Fix Qwen2-VL chat template: emit vision tokens before text

Qwen2VLMessageGenerator was emitting text before image content, shifting
image-token positions and skewing MROPE position IDs. This caused a
deterministic +9 px bbox offset vs the mlx-vlm reference. Reordering to
match HuggingFace's template (image before text) makes Swift bbox output
bit-exact on canonical test images.

(cherry picked from commit e832341)

* Fix Qwen35 VLM sanitize for bare 'model.*' weight keys (#143) (#254)

**Fix Qwen35 VLM sanitize for bare `model.*` weight keys (#143)**

Unified Qwen 3.5 checkpoints ship language-model tensors at bare `model.*` paths instead of `model.language_model.*`, causing a `keyNotFound` failure at load time. Adds the same `else if key.hasPrefix("model.")` fallback already present in the LLM path, prepending `language_model.` to route tensors correctly.

Also adds a regression test covering all four key shapes: bare `model.*`, `model.language_model.*`, and `lm_head.*`.

(cherry picked from commit 9650f9a)

* Fix SmolVLM2 tiles() upscaling small images, ~9x slowdown (#208) (#255)

Fix SmolVLM2 tiles() upscaling small images (~9x slowdown) (#208)

`tiles(from:)` passed `longestEdge = maxProcessingImageSize` (2048) unconditionally, causing images smaller than 2048px to be upscaled before tiling. A 512×384 input produced 13 patches (~1140 tokens) instead of 1 (~147 tokens); 2.83s vs 0.62s on M4 Pro.

Cap `longestEdge` at the image's actual longest side. Images larger than `maxProcessingImageSize` downscale as before.

Adds regression tests for tile counts at 512×384, 1024×768, and 4096×3072.

(cherry picked from commit 2007b1e)

* Qwen2/2.5-VL: default to the model card's image pixel budget (#243)

Qwen2.5-VL ships max_pixels = 12,845,056 in its preprocessor config, ~12x the
1280*28*28 budget the model card recommends for image tasks. Default to the
recommended budget; a caller can still set any budget via
UserInput.Processing.minPixels / maxPixels.

(cherry picked from commit b95dc78)

* Expose ModelTypeRegistry.contains(_:) for pre-load support checks (#349)

Lets a caller check whether the registry can instantiate a given model_type
without attempting a throwing, allocating createModel — e.g. to decide before
a multi-GB download whether a Hub repo's architecture is runnable. The creators
dictionary is private, so this check is only possible inside the type.

(cherry picked from commit 91323c6)

* fix MLXVLM prepare(): honor windowSize for chunked prefill (FastVLM / Gemma3 / Qwen2VL / LFM2VL / Pixtral / Mistral3) (#344)

Honor windowSize for chunked prefill in 6 MLXVLM models

Single-pass prefill allocates transient buffers proportional to prompt
length; chunking to windowSize=512 reduces peak memory from ~17.7 GB to
~5.1 GB on an 8k-token Gemma4 prompt (#336).

Extends the Gemma4/#337 loop pattern to remaining single-pass models:
- FastVLM, Gemma3, Qwen2VL, LFM2VL: embed-only path
- Pixtral, Mistral3: inputIds + inputsEmbeds path

Deferred (need non-trivial tensor slicing): Qwen25VL, GlmOcr, Qwen35,
Qwen3VL, Paligemma.

(cherry picked from commit 0ec0f33)

* fix(lfm2-moe): sigmoid routing + bias-selection-only + scaling (e3cb1e1)

Hand-port of upstream e3cb1e1. LFM2-MoE is sigmoid-gated, not softmax: the
old block softmaxed the gate and folded expert_bias into the combination
weights. Now expert_bias steers top-k SELECTION only, weights come from
the unbiased sigmoid scaled by routed_scaling_factor (new config field,
default 1.0), and the combine uses the compiled weightedExpertSum. MLP now
uses the compiled silu*up kernel (compiledSiluProduct made public, per
e3cb1e1).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(gemma4-vlm): no-cache KV share + 1D inputs + MoE router softmax order

Tier 4 Gemma4 correctness ports into our batched VLM Gemma4 (per-row RoPE
+ mask kernels + perRowOffset preserved):

- d675185: shared-KV layers gate on layer index only, not hasExplicitCache,
  so no-cache forwards (embedding extraction, retrieval, batched eval)
  correctly reuse the source layer's K/V instead of silently re-projecting.
  Cached generation unaffected.
- 84697ac: tolerate 1D (L,) token / 2D (L,D) embed inputs by adding the
  batch dim (zero-copy), fixing crashes on continuation prefills that build
  LMInput directly.
- 84ab278 (correctness half): softmax the MoE router weights AFTER top-k
  selection (was softmaxing all 128 experts then renormalizing the slice),
  matching our already-correct LLM Gemma4 router. Norm-fusion perf half
  omitted to keep the module tree / checkpoint layout unchanged.

Already present in our fork (parallel evolution, verified, no-op): 2409248
(vProj-nil uses kRaw single-transpose), 4bba1a8 (optional k/v/k_norm +
gated alloc + sanitize drop for KV-shared layers), 01ac5af (windowSize
chunked prefill in prepare()).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(qwen35-vlm): share fp32 gated-delta with MLXLLM (NB-1)

The VLM Qwen3.5 path carried a private duplicate of the gated-delta (GDN)
recurrence that defaulted the recurrent SSM state to q.dtype (bf16) and
downcast g/beta to bf16, drifting from the LLM twin's fp32 fix (upstream
c566c95 + 93cf322) and degrading Qwen3.5-VL SSM fidelity.

Delete the duplicate and call the shared MLXLLM.gatedDeltaUpdate (made
public) instead -- MLXVLM already depends on MLXLLM and the signatures
line up exactly, so there is one source of truth and no future drift.
The shared path keeps g/beta and the recurrent state in fp32.

Add Qwen35VLMGatedDeltaTests: exercises Qwen35Language.GatedDeltaNet with
bf16 weights/inputs and asserts the SSM state written to the cache is
fp32. Fails pre-fix (bfloat16), passes post-fix (float32).

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(tools): cover declared-tool filter in JSON parser (NB-2)

The JSON tool-call parser's declared-tool filter (reads
tool["function"]["name"] to drop undeclared / keep declared calls,
upstream 1335fb5) was only exercised with tools: nil. Add positive
(declared kept), negative (undeclared dropped), and multi-tool cases
through BatchedToolStreamHandler using the realistic nested tool shape
{"type":"function","function":{"name":...}}.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(lfm2-moe): lock sigmoid routing parity (NB-3)

The LFM2-MoE routing rewrite (softmax->sigmoid, bias-selection-only,
routed_scaling_factor, eps 1e-20->1e-6; upstream e3cb1e1) shipped with
no dedicated test. Add LFM2MoERoutingTests pinning that expert_bias
steers top-k SELECTION only while the combination weights stay the
unbiased sigmoid (normalized with eps 1e-6, scaled by
routed_scaling_factor), plus the no-bias selection path.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(switchglu): quantized fused gate_up parity (N1)

SwitchGLUTests only covered the fp32 fused gate_up path. Add a quantized
variant: affine quantization is independent per output row, so the fused
[gate; up] weight quantizes its gate/up rows identically to the separate
projections -- the single gathered quantized matmul + split is bit-exact
(maxDiff == 0) with two separate quantized matmuls. No model is wired to
fuseGateUp: true.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Tom Turney <tturney1@gmail.com>
Co-authored-by: Jamal Kharrat <jkharrat@hawk.iit.edu>
Co-authored-by: 0xweb3r <0xweb3r@gmail.com>
Co-authored-by: Vladimir Sinitsin <sadchitananda@yandex.ru>
Co-authored-by: Vladimir <vladimir@sinitcin.com>
Co-authored-by: tturney <tturney@psyguard.ai>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: David Irvine <david.irvine@maidsafe.net>
Co-authored-by: Daisuke Majima <rockyshikoku@gmail.com>
Co-authored-by: Aditya Kadam <57285352+Adi2K@users.noreply.github.com>
Co-authored-by: NivDvir <30941690+NivDvir@users.noreply.github.com>
Co-authored-by: Frank Nichols <64497529+jfranknichols@users.noreply.github.com>
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…lore#238)

Fix Qwen2.5-VL vision attention mask being ignored

- Pass attention mask to SDPA (was hardcoded to `.none`)
- Convert boolean mask to additive float using q-tensor dtype
- Hoist mask conversion to VisionModel level (once, not per-block)
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.

2 participants