Repository navigation
feat: inherit Gemma4 vMLX decode stack #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
8bfcdde
fix segsum dtype promotion -- 2x memory waste on hybrid SSM models (#…
TheTom d8cbca8
Fix nomic-embed-text-v1.5 'Key embeddings.position_embeddings.weight …
JamalK f72395e
Fix EmbeddingGemma init-order crash + dense head hidden size (#223)
0xweb3r 1d89424
fix: disable CIContext intermediate caching to prevent IOSurface exha…
Satchitananda e3dd4e3
fix gated delta state precision -- fp32 state to match Python (#224)
TheTom 7f001ce
fix(ssm): fp32 g/beta consistency + masked-output zero in gatedDelta
Gajesh2007 447fe21
fix(kv-quant): gate maybeQuantizeKVCache on first KVCacheSimple (hybr…
Gajesh2007 fbaf8a3
feat(tools): add .gemma4 ToolCallFormat case + auto-detect (8c61800)
Gajesh2007 b50b690
fix(tools): string-aware bare-JSON + declared-tool filter + FIFO drai…
Gajesh2007 529d18a
fix(kv-quant): group-size auto-resolve + quant-param serialization (0…
Gajesh2007 81dedb5
revert(tools): drop distinct .gemma4 ToolCallFormat case (supersedes …
Gajesh2007 88a2f78
perf(moe): fused gate_up single matmul + compiled GLU/combine kernels…
Gajesh2007 45625ed
Fix Qwen35 VLM crash on text-only inference (SmallVector out of range…
dirvine 1abd96e
Fix UserInput init not setting self.images / self.videos (#182) (#253)
john-rocky 49ad1fc
fix Idefics3 prepare() to honor windowSize -- prompt prefill is never…
Adi2K 004f783
fix Idefics3 vision encoder dtype -- SigLIP runs in float32 instead o…
Adi2K e499571
Fix vision-encoder attention mask being ignored in Qwen2.5-VL (#238)
NivDvir a4b7c79
Fix Qwen2-VL chat template: emit vision tokens before text (#242)
NivDvir b0ff526
Fix Qwen35 VLM sanitize for bare 'model.*' weight keys (#143) (#254)
john-rocky 625c101
Fix SmolVLM2 tiles() upscaling small images, ~9x slowdown (#208) (#255)
john-rocky c3294f4
Qwen2/2.5-VL: default to the model card's image pixel budget (#243)
NivDvir 48066d5
Expose ModelTypeRegistry.contains(_:) for pre-load support checks (#349)
jfranknichols 1b68504
fix MLXVLM prepare(): honor windowSize for chunked prefill (FastVLM /…
john-rocky 04afe43
fix(lfm2-moe): sigmoid routing + bias-selection-only + scaling (e3cb1e1)
Gajesh2007 563f9a7
fix(gemma4-vlm): no-cache KV share + 1D inputs + MoE router softmax o…
Gajesh2007 832167d
fix(qwen35-vlm): share fp32 gated-delta with MLXLLM (NB-1)
Gajesh2007 3a834ce
test(tools): cover declared-tool filter in JSON parser (NB-2)
Gajesh2007 fd01c04
test(lfm2-moe): lock sigmoid routing parity (NB-3)
Gajesh2007 f073a32
test(switchglu): quantized fused gate_up parity (N1)
Gajesh2007 48313a0
Merge origin/main (PR #48 EngineCore idle-clear marker) into feat/inh…
Gajesh2007 8a212b4
feat(gemma4): port vMLX decode hot path (#55)
Gajesh2007 b1af5c7
Merge remote-tracking branch 'origin/main' into feat/inherit-upstream…
Gajesh2007 b13f6b7
Merge remote-tracking branch 'origin/feat/inherit-upstream-2026-06' i…
Gajesh2007 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| // CompilableKVCache: Fixed-size KV cache using the Overflow Bin pattern. | ||
| // | ||
| // Ported from osaurus-ai/vmlx-swift-lm (Libraries/MLXLMCommon/CompilableKVCache.swift). | ||
| // This is the foundation type for whole-step compiled decode: it is the only | ||
| // full-attention cache whose `update()` is graph-traceable, so a decode step | ||
| // (model forward + cache write) can be captured by `compile(inputs:outputs:)`. | ||
| // | ||
| // Standard KVCacheSimple returns keys[..<offset] — a dynamically sized slice that | ||
| // changes every decode step. This prevents compile() from tracing through the cache | ||
| // because DynamicSlice requires static slice_size. | ||
| // | ||
| // CompilableKVCache solves this by: | ||
| // 1. Pre-allocating a fixed-size buffer [B, H, maxLength, D] | ||
| // 2. Writing new keys/values via dynamicSliceUpdate (compile-traceable writes) | ||
| // 3. Returning the FULL buffer from update() — constant shape every step | ||
| // 4. Generating a boolean attention mask in makeMask() that marks active positions | ||
| // | ||
| // The attention kernel handles the masking, computing only on valid positions. | ||
| // This trades marginal redundant compute (masked zeros) for enabling compile() | ||
| // to fuse hundreds of FFI crossings into a single compiled call. | ||
| // | ||
| // Usage: | ||
| // // After prefill with standard cache, convert for compiled decode: | ||
| // let compilableCache = standardCache.map { c in | ||
| // CompilableKVCache(from: c, maxLength: 2048) | ||
| // } | ||
| // | ||
| // NOTE (Darkbloom): this type is presently UNWIRED — it ships as the verified | ||
| // foundation for a future compiled-decode path. See `CompiledDecode.swift` for | ||
| // the `compileDecodeForward` wrapper and the port plan for batched integration | ||
| // into `GenerationBatch`. | ||
|
|
||
| import Foundation | ||
| import MLX | ||
| import MLXNN | ||
|
|
||
| /// A KV cache that returns fixed-size buffers to enable compile(). | ||
| /// | ||
| /// Key differences from KVCacheSimple: | ||
| /// - `offsetArray` (MLXArray) tracks position in the computation graph | ||
| /// - Pre-allocated buffer of fixed size (no dynamic growth during decode) | ||
| /// - `update()` returns the FULL buffer — mask handles which positions are valid | ||
| /// - `makeMask()` always returns an array mask covering the full buffer | ||
| /// - `innerState()` returns [keys, values, offsetArray] — all compile-tracked | ||
| public class CompilableKVCache: BaseKVCache { | ||
|
|
||
| public var keys: MLXArray? | ||
| public var values: MLXArray? | ||
|
|
||
| /// Offset as MLXArray (1D [1] int32) — tracked by compile tracer. | ||
| /// Must be 1D (not scalar) for DynamicSlice start parameter compatibility. | ||
| public var offsetArray: MLXArray | ||
|
|
||
| /// Maximum sequence length the buffer can hold. | ||
| public let maxLength: Int | ||
|
|
||
| /// Pre-allocation chunk size (same semantics as KVCacheSimple.step). | ||
| public var step: Int | ||
|
|
||
| /// Pre-computed column indices for mask creation [0, 1, ..., maxLength-1]. | ||
| /// Avoids re-creating every step. | ||
| private lazy var maskRinds: MLXArray = MLXArray(Int32(0) ..< Int32(maxLength)) | ||
|
|
||
| public init(maxLength: Int = 4096, step: Int = 256) { | ||
| self.maxLength = maxLength | ||
| self.step = step | ||
| self.offsetArray = MLXArray([Int32(0)]) | ||
| super.init() | ||
| } | ||
|
|
||
| /// Create from an existing KVCacheSimple (e.g., after prefill). | ||
| /// Copies the existing cache state into a fixed-size buffer. | ||
| public convenience init(from cache: KVCache, maxLength: Int = 4096) { | ||
| self.init(maxLength: maxLength) | ||
|
|
||
| let existingState = cache.state | ||
| if existingState.count >= 2 { | ||
| let existingKeys = existingState[0] // [B, H, seqLen, D] | ||
| let existingValues = existingState[1] | ||
|
|
||
| let seqLen = existingKeys.dim(2) | ||
| let B = existingKeys.dim(0) | ||
| let H = existingKeys.dim(1) | ||
| let kD = existingKeys.dim(3) | ||
| let vD = existingValues.dim(3) | ||
|
|
||
| // Pre-allocate to maxLength | ||
| self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: existingKeys.dtype) | ||
| self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: existingValues.dtype) | ||
|
|
||
| // Copy existing data at position 0 | ||
| self.keys![.ellipsis, ..<seqLen, 0...] = existingKeys | ||
| self.values![.ellipsis, ..<seqLen, 0...] = existingValues | ||
|
|
||
| self.offsetArray = MLXArray([Int32(seqLen)]) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - KVCache protocol | ||
|
|
||
| public override var offset: Int { | ||
| get { | ||
| // Materialize for compatibility with code that reads offset as Int. | ||
| // This triggers synchronous readback — avoid inside compiled paths. | ||
| offsetArray[0].item(Int.self) | ||
| } | ||
| set { | ||
| offsetArray = MLXArray([Int32(newValue)]) | ||
| } | ||
| } | ||
|
|
||
| public override func innerState() -> [MLXArray] { | ||
| if let keys, let values { | ||
| return [keys, values, offsetArray] | ||
| } | ||
| return [offsetArray] | ||
| } | ||
|
|
||
| public override func update(keys newKeys: MLXArray, values newValues: MLXArray) | ||
| -> (MLXArray, MLXArray) | ||
| { | ||
| let nTokens = newKeys.dim(2) | ||
|
|
||
| // Lazy initialization on first call | ||
| if self.keys == nil { | ||
| let B = newKeys.dim(0) | ||
| let H = newKeys.dim(1) | ||
| let kD = newKeys.dim(3) | ||
| let vD = newValues.dim(3) | ||
| self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: newKeys.dtype) | ||
| self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: newValues.dtype) | ||
| } | ||
|
|
||
| let prev = offsetArray | ||
| let newOffset = prev + MLXArray([Int32(nTokens)]) | ||
|
|
||
| // Must use _updateInternal to preserve object identity — compile() captures | ||
| // stateInputs at innerCall start and expects the same objects to be mutated. | ||
| self.keys!._updateInternal( | ||
| dynamicSliceUpdate(self.keys!, update: newKeys, start: prev, axes: [2])) | ||
| self.values!._updateInternal( | ||
| dynamicSliceUpdate(self.values!, update: newValues, start: prev, axes: [2])) | ||
|
|
||
| self.offsetArray._updateInternal(newOffset) | ||
|
|
||
| // OVERFLOW BIN: return the full static-size buffer. | ||
| // The attention mask from makeMask() handles which positions are valid. | ||
| // This keeps tensor shapes constant across all decode steps, | ||
| // enabling compile() to trace the entire forward pass. | ||
| return (self.keys!, self.values!) | ||
| } | ||
|
|
||
| // MARK: - Mask (Overflow Bin) | ||
|
|
||
| /// Generate attention mask for the full-buffer return. | ||
| /// | ||
| /// Since update() returns the entire maxLength buffer, we ALWAYS need an array | ||
| /// mask to prevent attention to unwritten positions. The mask is boolean: | ||
| /// True = attend, False = don't attend (gets -inf in attention scores). | ||
| /// | ||
| /// For decode (n=1): mask[0, j] = (j <= offset) | ||
| /// For prefill (n>1): mask[i, j] = (j <= offset + i) (causal) | ||
| /// | ||
| /// Note: `offset` here is the PRE-update value. After update, positions | ||
| /// 0..<offset+n are valid, matching the mask exactly. | ||
| /// | ||
| /// Uses `offsetArray` (MLXArray) for all computation so compile() can trace | ||
| /// the mask through the computation graph. | ||
| public override func makeMask( | ||
| n: Int, windowSize: Int?, returnArray: Bool | ||
| ) -> MLXFast.ScaledDotProductAttentionMaskMode { | ||
| // Use offsetArray directly — compile-traceable, no .item() needed | ||
| let currentOffsetArr = offsetArray // MLXArray [1] int32 | ||
|
|
||
| // Query positions: [offset, offset+1, ..., offset+n-1] | ||
| let linds: MLXArray | ||
| if n == 1 { | ||
| linds = currentOffsetArr.reshaped(1, 1) | ||
| } else { | ||
| linds = (MLXArray(Int32(0) ..< Int32(n)) + currentOffsetArr).reshaped(n, 1) | ||
| } | ||
|
|
||
| // Key positions: [0, 1, ..., maxLength-1] | ||
| let rinds = maskRinds.reshaped(1, maxLength) | ||
|
|
||
| // Causal + validity: attend to positions j where j <= query_position | ||
| var mask = linds .>= rinds | ||
|
|
||
| // Apply sliding window if specified | ||
| if let windowSize { | ||
| let windowStart = linds - Int32(windowSize - 1) | ||
| mask = mask & (rinds .>= windowStart) | ||
| } | ||
|
|
||
| return .array(mask) | ||
| } | ||
|
|
||
| // MARK: - State | ||
|
|
||
| public override var state: [MLXArray] { | ||
| get { | ||
| guard let keys, let values else { return [] } | ||
| let off: Int = offsetArray[0].item(Int.self) | ||
| if off == keys.dim(2) { | ||
| return [keys, values] | ||
| } else { | ||
| // Return only valid portion for serialization | ||
| return [ | ||
| keys[.ellipsis, ..<off, 0...], | ||
| values[.ellipsis, ..<off, 0...], | ||
| ] | ||
| } | ||
| } | ||
| set { | ||
| guard newValue.count == 2 else { return } | ||
| let seqLen = newValue[0].dim(2) | ||
| let B = newValue[0].dim(0) | ||
| let H = newValue[0].dim(1) | ||
| let kD = newValue[0].dim(3) | ||
| let vD = newValue[1].dim(3) | ||
|
|
||
| self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: newValue[0].dtype) | ||
| self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: newValue[1].dtype) | ||
| self.keys![.ellipsis, ..<seqLen, 0...] = newValue[0] | ||
| self.values![.ellipsis, ..<seqLen, 0...] = newValue[1] | ||
| self.offsetArray = MLXArray([Int32(seqLen)]) | ||
| } | ||
| } | ||
|
|
||
| public override var isTrimmable: Bool { true } | ||
|
|
||
| @discardableResult | ||
| public override func trim(_ n: Int) -> Int { | ||
| let current: Int = offsetArray[0].item(Int.self) | ||
| let trimmed = min(current, n) | ||
| offsetArray = MLXArray([Int32(current - trimmed)]) | ||
| super.offset = current - trimmed | ||
| return trimmed | ||
| } | ||
|
|
||
| public override func copy() -> any KVCache { | ||
| let c = CompilableKVCache(maxLength: maxLength, step: step) | ||
| c.keys = keys | ||
| c.values = values | ||
| c.offsetArray = offsetArray | ||
| return c | ||
| } | ||
|
|
||
| // MARK: - Debug | ||
|
|
||
| public var debugDescription: String { | ||
| "CompilableKVCache(offset=\(offset), maxLength=\(maxLength), " | ||
| + "shape=\(keys?.shape.description ?? "nil"))" | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
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