Skip to content

feat: inherit Gemma4 vMLX decode stack - #56

Merged
Gajesh2007 merged 33 commits into
mainfrom
feat/inherit-upstream-2026-06
Jun 26, 2026
Merged

Gajesh2007 merged 33 commits into
mainfrom
feat/inherit-upstream-2026-06

Conversation

@Gajesh2007

Copy link
Copy Markdown
Member

Summary

  • Merges the feat/inherit-upstream-2026-06 integration branch into main.
  • Includes the Gemma4 vMLX decode-hot-path port from feat(gemma4): port vMLX decode hot path #55 plus prior upstream/VLM/MoE/KV/tooling inheritance work on the branch.
  • Enables Gemma4 26B-A4B 8-bit raw decode to reach 70+ TPS in release when consumed by d-inference.

Results

  • Integrated local package release benchmark against d-inference local packages: 79.5 tok/s on mlx-community/gemma-4-26b-a4b-it-8bit (M4 Max, B=1, 128 generated tokens).
  • Standalone vMLX proof on same model/machine: 79.6/79.7 TPS.
  • Python mlx-vlm baseline on same model/machine: 69.7 TPS.

Before

flowchart LR
  A[Gemma4 B=1 token] --> B[main branch Gemma4 path]
  B --> C[older VLM/MoE/RoPE/softcap implementation]
  C --> D[raw decode]
  D --> E[~39 TPS in d-inference raw loop]
Loading

After

flowchart LR
  A[Gemma4 B=1 token] --> B[feat/inherit-upstream-2026-06]
  B --> C[vMLX-derived Gemma4 VLM hot path + compiled GLU helpers]
  C --> D[release raw decode]
  D --> E[79.5 TPS in d-inference local package bench]
Loading

Verification

  • swift build / swift build --build-tests from porting agents passed for the integrated tree.
  • CompilableKVCacheTests passed 4/4.
  • /tmp/dbval/gemma4rawbench release executable against local packages produced [gemma4-rawbench] 79.5 tok/s.
  • Gated provider test generated coherent text with DARKBLOOM_GEMMA_PRINT_TEXT=1.

TheTom and others added 30 commits June 23, 2026 14:08
)

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 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)
…ustion (#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

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)
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>
…id 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>
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>
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>
…1b8624)

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>
…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>
…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>
#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 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 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

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)**

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)

`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.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)
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)
… 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)
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>
…rder

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>
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>
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>
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>
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>
…erit-upstream-2026-06

Brings the measurement-only EngineCore idle-clear-in-flight marker
(d-inference#451, master pin 2b4b0d8) onto the inheritance branch so the
combined tree is a strict superset of the d-inference master pin. Preserves all
inheritance crown jewels (continuous batching, DAR-325 KV fix, KV-quant, MTP,
batched Gemma4, fp32 gated-delta dedupe) and the instrumentation marker.
@Gajesh2007
Gajesh2007 merged commit 7ce9e45 into main Jun 26, 2026
3 checks passed
@Gajesh2007
Gajesh2007 deleted the feat/inherit-upstream-2026-06 branch June 26, 2026 06:30

@ethenotethan ethenotethan 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.

Automated Code Review — Layr-Labs/mlx-swift-lm#

Verdict: COMMENT

Security — 3 finding(s)

  • 🔵 [INFO] Libraries/MLXLMCommon/CompilableKVCache.swift:139 — DynamicSlice start parameter lacks bounds validation
    • Suggestion: Add validation that offsetArray values are within valid bounds for the buffer dimensions before calling dynamicSliceUpdate
  • 🔵 [INFO] Libraries/MLXLMCommon/DynamicSlice.swift:36-55 — Dynamic slice operations lack input validation
    • Suggestion: Add validation for array dimensions, axis bounds, and slice size parameters before calling MLX C functions
  • 🔵 [INFO] Libraries/MLXVLM/Models/Gemma4.swift:1050-1065 — Image extent validation could be bypassed
    • Suggestion: Add additional validation to ensure width and height are positive integers and within reasonable bounds

Performance — ✅ No issues found

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

3 finding(s) total, 0 blocking. Verdict: COMMENT.

🤖 Automated review by Centaur · DAR-186


// Must use _updateInternal to preserve object identity — compile() captures
// stateInputs at innerCall start and expects the same objects to be mutated.
self.keys!._updateInternal(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 DynamicSlice start parameter lacks bounds validation

💡 Suggestion: Add validation that offsetArray values are within valid bounds for the buffer dimensions before calling dynamicSliceUpdate

📊 Score: 2×3 = 6 · Category: missing-input-validation

Comment on lines +36 to +55
) -> MLXArray {
// Use the C-level slice(array, array_start, axes, slice_size) overload.
// This creates a DynamicSlice primitive which has output_shapes support.
var result = mlx_array_new()
var axesInt = axes.map { Int32($0) }
var sizes = sliceSize.map { Int32($0) }
let rc = mlx_slice_dynamic(
&result,
src.ctx,
start.ctx,
&axesInt,
axesInt.count,
&sizes,
sizes.count,
stream.ctx)
if rc != 0 {
fatalError("[dynamicSlice] mlx_slice_dynamic failed with rc=\(rc)")
}
return MLXArray(result)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 Dynamic slice operations lack input validation

💡 Suggestion: Add validation for array dimensions, axis bounds, and slice size parameters before calling MLX C functions

📊 Score: 3×2 = 6 · Category: missing-input-validation

Comment on lines +1050 to +1065
var arrays = try input.images.map { img -> MLXArray in
let ci = try img.asCIImage()
// Reject zero-area, infinite, and NaN extents explicitly. The
// scale-factor math below divides by `w * h`; a CIImage with
// a zero extent produces infinite `f` and a NaN trap inside
// `Int(floor(.nan))`. A non-finite extent (e.g.
// `CIImage(color:)` returns `(.infinity, .infinity)`) traps
// even earlier inside `Int(.infinity)`. Both surface as
// VLMError.imageProcessingFailure now.
let (h, w) = try gemma4IntExtent(ci.extent.size)
let f = sqrt(Float(maxP * ps * ps) / Float(w * h))
let sm = config.poolingKernelSize * ps
var tH = Int(floor(f * Float(h) / Float(sm))) * sm; var tW = Int(floor(f * Float(w) / Float(sm))) * sm
if tH == 0 { tH = sm }; if tW == 0 { tW = sm }
let resized = MediaProcessing.resampleBicubic(ci, to: CGSize(width: tW, height: tH))
// Convert to sRGB tone curve — CIImage may be in linear space, but the

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 Image extent validation could be bypassed

💡 Suggestion: Add additional validation to ensure width and height are positive integers and within reasonable bounds

📊 Score: 2×2 = 4 · Category: missing-input-validation

@ethenotethan ethenotethan 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.

Automated Code Review — Layr-Labs/mlx-swift-lm#

Verdict: COMMENT

Security — ✅ No issues found

Performance — ✅ No issues found

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@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: 8a212b4caa

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

let pixelValues = concatenated(processedImages)
return (pixelValues, THW(images.count, Int(lastSize.height), Int(lastSize.width)))
let paddedCache = padCache(cache)
let out = languageModel(input.text.tokens, inputEmbedding: emb, cache: paddedCache)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Restore Gemma4 visual-token bidirectional masking

When input.image is present, this path scatters the vision features and then invokes the text model without passing any mask that identifies the contiguous image-token span. The new TextModel only builds causal masks from the cache, so image tokens can no longer attend bidirectionally within the same image block, which Gemma4 VLM configs require for visual prompts. This changes the attention pattern before the first generated token and can corrupt image-conditioned results; please carry the image-token mask into the text forward and overlay it on the causal mask.

Useful? React with 👍 / 👎.

(imageStd[0], imageStd[1], imageStd[2])
}
public func prepare(input: UserInput) async throws -> LMInput {
let messages = Qwen2VLMessageGenerator().generate(from: input)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use Gemma4 chat formatting for Gemma4 prompts

When Gemma4Processor prepares a chat with a system message, using Qwen2VLMessageGenerator emits Qwen-style typed content arrays for system messages, while Gemma4's prior generator/template contract used plain string content for system messages and Gemma-specific multimodal entries for user turns. That can make applyChatTemplate render malformed Gemma4 prompts or fail on otherwise valid Gemma4 chats; please preserve a Gemma4-specific message generator instead of reusing Qwen2VL's.

Useful? React with 👍 / 👎.

Comment on lines +510 to +511
for y in 0 ..< pH { for x in 0 ..< pW { posFlat.append(Int32(x)); posFlat.append(Int32(y)) } }
var patchPos = MLXArray(posFlat).reshaped(1, nReal, 2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Truncate oversized Gemma4 patch grids consistently

When a caller supplies already-processed pixels whose patch grid exceeds maxPatches (for example via a direct LMInput or custom processor), nReal is clamped but posFlat is still populated for all pH * pW patches, so reshaping it to [1, nReal, 2] traps before the intended clamp can help. The pixel patches also remain untruncated, so the embedding length would not match the clamped positions; please crop/truncate the patch grid and pixels consistently.

Useful? React with 👍 / 👎.

@@ -72,6 +140,11 @@ public class SwitchGLU: Module {
self.numExperts = numExperts
self.activation = MLXNN.silu
self.activationProduct = compiledSiluProduct

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor the compiled-decode opt-out for SiLU fusions

When MLX_COMPILED_DECODE=0 is set to avoid the documented Metal JIT issues, the default SwitchGLU path still wires itself to compiledSiluProduct, which is created with compile(shapeless:) unconditionally instead of using the gated fallback. Models that instantiate the default SiLU SwitchGLU therefore still hit compiled kernels on the very machines the opt-out is meant to protect; please route this through the same MLXHardwareInfo.isCompiledDecodeSupported gate.

Useful? React with 👍 / 👎.

targetW = sideMult
targetH = min(Int((h / w).rounded(.down)) * sideMult, maxSideLength)
var processedImage: LMInput.ProcessedImage?
if !input.images.isEmpty {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve Gemma4 video inputs

When input.videos is non-empty, the processor still builds messages that contain video placeholders, but this prepare path only constructs ProcessedImage data and never creates video frames or expands video tokens into vision features. Those video placeholders are then embedded as ordinary tokens because Gemma4.prepare only scatters input.image, so Gemma4 video prompts silently lose the visual content; please restore the video preprocessing/scatter path or reject videos explicitly.

Useful? React with 👍 / 👎.

vocabSize = try c.decodeIfPresent(Int.self, forKey: .vocabSize) ?? 262144
rmsNormEps = try c.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6
slidingWindow = try c.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 1024
layerTypes = try c.decodeIfPresent([String].self, forKey: .layerTypes) ?? []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Build Gemma4 attention pattern defaults

When a Gemma4 config omits layer_types, this now falls back to an empty array, and all of the downstream layer-type lookups treat missing entries as sliding_attention. The previous implementation rebuilt the sliding/full-attention pattern from sliding_window_pattern, so such configs lose every full-attention layer and instantiate the wrong cache/layout; please synthesize the default pattern instead of defaulting to [].

Useful? React with 👍 / 👎.

Comment on lines +984 to +985
if nk.hasPrefix("language_model.") && !nk.hasPrefix("language_model.model.") {
nk = "language_model.model." + String(nk.dropFirst("language_model.".count))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep Gemma4 lm_head weights outside model

For untied Gemma4 checkpoints, language_model.lm_head.* is a sibling of language_model.model, but this blanket remap moves it under language_model.model.lm_head.*, where no module exists. Those lm_head weights/scales then do not load, leaving the output head randomly initialized or missing for tie_word_embeddings == false; please special-case language_model.lm_head before adding the model. prefix.

Useful? React with 👍 / 👎.

jonathan308 added a commit that referenced this pull request Oct 22, 2026
mlx-swift 4c6ca4c53169d0ec52a31707e5ec9cc4fb8aab13 (local wip/cluster-next): cluster #56 + single-Mac #58,
pinning core a1d75679 (cluster #35 + single-Mac #37, the 4d913204 revert)
and mlx-c 1d0ce055. The merge before this needs GPU.withCommandBufferLimits,
which only this stack has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 26, 2026
Main's SDK needs the main-merged mlx-swift API (MLXArray.maskFill, QuantizedLinear.globalScale, ...): pin Layr-Labs/mlx-swift#56 merged with main 69594861, its nested core = mlx#35 merged with main (2b5253ad) and mlx-c#15 merged with main (73720efb). Built and tested against this stack locally (merge record MLX-SWIFT-LM-MERGE-2026-10-26).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 26, 2026
… with the batch-invariance switch

Package.swift: mlx-swift 3832c0de -> f70ddf7e = Layr-Labs/mlx-swift#61 merged with main 69594861 (89144f9f, which contains #61's head 3832c0de) + the nested core caa9ed53 (mlx#41 merged with main + MLX_QMV_BATCH_INVARIANT) and mlx-c 73720efb. Main's SDK needs the main-merged mlx-swift API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 27, 2026
mlx-swift 3e1fc78e -> aba48e15 (nests core #35 with main 6bc9de5b merged: the fix behind provider 0.10.3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.