Repository navigation
fix Idefics3 prepare() to honor windowSize -- prompt prefill is never chunked - #297
Merged
Merged
Conversation
davidkoski
reviewed
May 18, 2026
| let nToProcess = min(prefillStepSize, embeddings.dim(1) - 1) | ||
| let chunk = embeddings[0..., ..<nToProcess] | ||
| _ = languageModel(nil, cache: cache, inputs_embeds: chunk) | ||
| eval(cache) |
Contributor
Author
There was a problem hiding this comment.
Cools, will take a look and revert.
Member
|
Waiting for CI -- currently an infrastructure issue. |
davidkoski
force-pushed
the
idefics3-chunked-prefill
branch
from
May 22, 2026 16:53
edaa456 to
ccb724a
Compare
Member
|
Rebase to pick up CI fix |
wangqi
pushed a commit
to wangqi/mlx-swift-lm
that referenced
this pull request
May 23, 2026
…meterized GemmaFunctionParser (PR ml-explore#183) keeping the wangqi Gemma4FunctionParser double-brace JSON fallback, LMOutput.State-based M-RoPE position passing (PR ml-explore#283) for Qwen35 and GlmOcr with a canSlicePrecomputed guard, and always-chunked Idefics3 prefill (PR ml-explore#297).
This was referenced Jun 10, 2026
Merged
davidkoski
pushed a commit
to john-rocky/mlx-swift-lm
that referenced
this pull request
Jun 16, 2026
Single-pass prefill allocates transient buffers proportional to prompt length (~1.7 MB/token on Gemma4 E4B 4-bit); with an 8k-token prompt this pushes peak active memory to ~17.7 GB. Chunking to windowSize=512 brings the same prompt to ~5.1 GB (measured by joshuaejackson in ml-explore#336). Idefics3 was fixed in ml-explore#297; SmolVLM2 inherits the fix via typealias; Gemma4 was fixed in ml-explore#337. This PR extends the same pattern to the remaining single-pass models: - FastVLM: embed-only path (languageModel(nil, inputEmbedding:)) - Gemma3: embed path (causal mask) + text-only token-chunking path - Qwen2VL: embed-only path - LFM2VL: embed-only path (inputsEmbeds label) - Pixtral: inputIds + inputsEmbeds path, expands tokens to 2D before slicing - Mistral3: same pattern as Pixtral All 6 follow the Gemma4/ml-explore#337 loop structure: asyncEval(cache) between chunks, eval(cache) sync before the last position, then a single final forward for the first-token logits. README porting template updated to show chunked prepare(). Remaining models deferred (different architectures): - Qwen25VL/GlmOcr: MROPE positionIds tensor needs 3D slicing - Qwen35/Qwen3VL: pass raw pixelValues into languageModel directly - Paligemma: uses a 4D bidirectional attention mask 137/137 tests pass (xcodebuild test -scheme mlx-swift-lm-Package).
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
`Idefics3.prepare(_:cache:windowSize:)` accepts a `windowSize` argument but never
uses it: the entire merged image+text embedding -- which can be 10k+ positions for
multi-tile Idefics3 / SmolVLM2 inputs -- is run through the language model in a
single forward pass.
`LLMModel.prepare` already chunks token prompts into `windowSize`-sized slices. This
applies the same chunking to Idefics3's merged-embedding prefill: the embeddings are
fed in `windowSize`-sized slices with the KV cache evaluated between chunks, and the
final embedding is run for the first-token logits. This matches `mlx-vlm`'s
`generate_step` chunked prefill.
Unlike `LLMModel.prepare` -- which works on tokens and returns `.tokens` -- Idefics3's
merged image+text embeddings have no token IDs, so this keeps the existing `.logits`
return: it chunks down to the final embedding and returns its logits.
Verification
Verified as part of the same Granite Docling parity effort. Chunked vs single-pass
prefill is logit-neutral under causal masking -- generated output is unchanged -- but
it honors the `windowSize` contract and bounds peak prefill memory on large
multi-tile inputs, consistent with `LLMModel.prepare` and every other model's
prefill path.
Checklist