Repository navigation
Fix Python finfo.min port in quantized attention masking - #17
Conversation
|
@codex review |
There was a problem hiding this comment.
Code Review
This pull request fixes a mistranslation of the minimum float value used for causal and sliding window masking, replacing Float.leastNormalMagnitude (which is close to 0) with -Float.greatestFiniteMagnitude in both Gemma3nText.swift and KVCache.swift. It also adds a regression test to verify that quantized causal attention matches full-precision results. The reviewer feedback highlights that creating the masking array without an explicit dtype defaults to .float32, which can cause silent type promotion of scores (typically .float16 or .bfloat16 in quantized models), leading to increased memory usage and degraded performance. It is recommended to explicitly specify dtype: scores.dtype in these array initializations.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| let causalMask = greaterEqual( | ||
| expandedDimensions(qIndices, axis: -1), expandedDimensions(kIndices, axis: -2)) | ||
| scores = MLX.where(causalMask, scores, MLXArray(Float.leastNormalMagnitude)) | ||
| scores = MLX.where(causalMask, scores, MLXArray(-Float.greatestFiniteMagnitude)) |
There was a problem hiding this comment.
Creating MLXArray(-Float.greatestFiniteMagnitude) without specifying a dtype defaults to .float32. If scores is .float16 or .bfloat16 (which is typical for quantized models), this will cause silent type promotion of scores to .float32 during the MLX.where operation. This increases memory usage and degrades performance for subsequent operations like softmax and quantizedMM. Specifying dtype: scores.dtype prevents this promotion.
| scores = MLX.where(causalMask, scores, MLXArray(-Float.greatestFiniteMagnitude)) | |
| scores = MLX.where(causalMask, scores, MLXArray(-Float.greatestFiniteMagnitude, dtype: scores.dtype)) |
| case .array(let maskArray): | ||
| if maskArray.dtype == .bool { | ||
| scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude)) | ||
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) |
There was a problem hiding this comment.
Creating MLXArray(-Float.greatestFiniteMagnitude) without specifying a dtype defaults to .float32. If scores is .float16 or .bfloat16 (which is typical for quantized models), this will cause silent type promotion of scores to .float32 during the MLX.where operation. This increases memory usage and degrades performance for subsequent operations like softmax and quantizedMM. Specifying dtype: scores.dtype prevents this promotion.
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) | |
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude, dtype: scores.dtype)) |
| if let maskArray = maskArrays.first { | ||
| if maskArray.dtype == .bool { | ||
| scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude)) | ||
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) |
There was a problem hiding this comment.
Creating MLXArray(-Float.greatestFiniteMagnitude) without specifying a dtype defaults to .float32. If scores is .float16 or .bfloat16 (which is typical for quantized models), this will cause silent type promotion of scores to .float32 during the MLX.where operation. This increases memory usage and degrades performance for subsequent operations like softmax and quantizedMM. Specifying dtype: scores.dtype prevents this promotion.
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude)) | |
| scores = MLX.where(maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude, dtype: scores.dtype)) |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6bf9997816
ℹ️ 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".
| scores = MLX.where( | ||
| maskArray, scores, MLXArray(-Float.greatestFiniteMagnitude, dtype: scores.dtype)) |
There was a problem hiding this comment.
Use the target dtype's finite minimum for masks
When scores.dtype is .float16 (and similarly for low-precision dtypes), constructing the mask fill from -Float.greatestFiniteMagnitude can overflow/round to -inf instead of the finite finfo(scores.dtype).min value described in the commit. If a boolean mask contains an all-false row (for example a padding/length mask passed through the quantized attention path), the subsequent softmax(scores, axis: -1) will see an all--inf row and produce NaNs, whereas the finite minimum keeps the row finite. Please derive the fill from the destination dtype's finite minimum rather than the Float32 maximum.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7f38c1625
ℹ️ 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".
| if isSliding, case .array(let maskArray) = mask { | ||
| let effectiveSeqLen = max(cachePosition?.dim(0) ?? 0, slidingWindow) | ||
| let minDtype = MLXArray(Float.leastNormalMagnitude, dtype: maskArray.dtype) | ||
| let minDtype = MLXArray(-Float.greatestFiniteMagnitude, dtype: maskArray.dtype) |
There was a problem hiding this comment.
Use target dtype for Gemma3n sliding fills
When Gemma3n sliding attention runs with fp16/bf16 hidden states, this scalar is built from Float32’s maximum and the mask is later cast to queries.dtype in Gemma3nAttention, so the fill can round to -inf instead of the finite dtype minimum. If a padding/sliding-window mask leaves a query row fully masked, softmax over all -inf produces NaNs; the finite dtype helper added for quantized attention avoids that. Fresh evidence: this commit adds the same -Float.greatestFiniteMagnitude fill in Gemma3nText.swift, outside the KVCache fix from the existing comment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2e050d90b2
ℹ️ 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".
| } | ||
| // IEEE 754 half-precision maximum finite value | ||
| let bound: Float = 65504.0 // Float16 maximum finite value | ||
| let bound: Float = .greatestFiniteMagnitude |
There was a problem hiding this comment.
Clamp fp16 residuals to fp16 range
When x.dtype == .float16, this bound is now Float32's maximum instead of fp16's 65504, so clip no longer caps finite fp16 residual sums that exceed the half-precision range. For example, two large-but-finite fp16 activations can sum in Float32 above 65504 and then overflow to inf when cast back to .float16, defeating this helper's purpose of preventing fp16 overflow in Gemma residual connections.
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 167f193eab
ℹ️ 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 causalMask = greaterEqual( | ||
| expandedDimensions(qIndices, axis: -1), expandedDimensions(kIndices, axis: -2)) | ||
| scores = MLX.where(causalMask, scores, MLXArray(Float.leastNormalMagnitude)) | ||
| scores = MLX.where(causalMask, scores, MLXArray.maskFill(for: scores.dtype)) |
There was a problem hiding this comment.
Replace the nonexistent maskFill helper
This commit calls MLXArray.maskFill(for:), but neither this repo nor the declared mlx-swift dependency exposes that static member; MLX exposes the finite limits through DType.finfo. Any target that compiles KVCache.swift now fails to type-check before the masking fix can run, so please add the helper or construct the scalar from scores.dtype.finfo at these new call sites.
Useful? React with 👍 / 👎.
| } | ||
| // IEEE 754 half-precision maximum finite value | ||
| let bound: Float = 65504.0 // Float16 maximum finite value | ||
| let bound = DType.float16.greatestFiniteMagnitude |
There was a problem hiding this comment.
Use DType.finfo for the fp16 residual bound
The declared MLX DType API exposes finite limits as DType.float16.finfo?.max, not as a greatestFiniteMagnitude member, so this replacement makes Gemma.swift fail to type-check anywhere clipResidual is compiled. Keep the literal or use DType.float16.finfo!.max to preserve the intended fp16 bound.
Useful? React with 👍 / 👎.
…nt main) Restacks the quantized batched KV cache (BatchQuantizedKVCache + tests, the BatchedCache/KVCache hooks, BatchCacheTests touch-ups) onto claude/cb-1-caches. PR5 is independent of the engine/promptcache (stacks on PR1), so it is based on cb-1-caches directly. Applied with no conflicts. PR5's KVCache.swift change includes the quantized- attention mask fix: replacing the Float.leastNormalMagnitude (~1e-38, a tiny positive value = effectively no masking) with a per-dtype most-negative finite fill, plus GQA head-group mask broadcasting. Current main still carries the buggy leastNormalMagnitude (3 occurrences), so the fix is wanted; note it overlaps with open PR #17 ("Fix Python finfo.min port in quantized attention masking"), which addresses the same bug standalone. Not yet compiled: needs a Metal/macOS build to confirm it compiles against current main. https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
- BatchQuantizedKVCache.finalize() needs `override` now that BaseKVCache declares `open func finalize()` (matches BatchKVCache convention). - Add BatchQuantizedKVCacheTests and QuantizedAttentionMaskTests to the macOS -only-testing gate. Kept the quantizedScaledDotProductAttention finfo/maskFill hunk: neither origin/main nor cb-1-caches carries the fix yet, so it is required for correctness (PR #17 has not landed). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013zX4QEsmT3Svfo3o5fJBJK
The merged #17 supersedes cb-5's local maskFill helper: the per-dtype most-negative-finite fill now comes from MLX-Swift's MLXArray.maskFill extension. cb-5's GQA head-group broadcast for 4-D batched masks is retained and routed through the same extension. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
Fresh package resolution has no tagged mlx-swift with the MLXArray.maskFill extension #17's call sites expect (main is currently red for the same reason), so the extension is defined here temporarily (public: Gemma3nText in MLXLLM calls it too) with a removal note for when mlx-swift ships it. The merge also duplicated the identical applyMask helper (#17 adopted cb-5's version); one copy removed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
extension) Gemma.clipResidual expects it from MLX-Swift; no tagged release provides it, so a fresh package resolution fails. Defined alongside the temporary MLXArray.maskFill with the same removal note. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…ask fix (chain 1/6) Neutral KVCache.swift plumbing for continuous batching (leftPadding in createCausalMask, batched-cache routing in the legacy mask overload, ArraysCache row extraction hooks, quantizedScaledDotProductAttention GQA broadcast for 4-D batched masks — the fill-value fix itself landed via #17), plus the Gemma2 attention-mask change it requires. Fork CI builds the package. NOTE FOR REVIEWERS: the Gemma2 change alters single-stream mask numerics (boolean mask added to logits -> where/-1e9); it needs a pinning test. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
Fixes a likely mistranslation from Python
mlx-lminquantizedScaledDotProductAttention.The Python reference masks boolean/causal logits with
mx.finfo(scores.dtype).min, a large negative finite value that suppresses masked positions before softmax. The Swift port usedFloat.leastNormalMagnitude, which is instead a tiny positive value, so masked positions could remain competitive or dominate when valid scores are negative.This updates the Swift quantized attention mask fill value to match the intended Python semantics and adds regression coverage for masked quantized attention.
Checklist
Put an
xin the boxes that apply.github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) documentpre-commit run --all-filesto format my code / installed pre-commit prior to committing changes