Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

gemma4: use MLX SDPA for CUDA prefill with wide head dims (#18809)

Daniel Hiltgen41503eb272d6
diff --git a/mlxrunner/model/gemma4/gemma4.go b/mlxrunner/model/gemma4/gemma4.go
index 2c50fc281..27264820c 100644
--- a/mlxrunner/model/gemma4/gemma4.go
+++ b/mlxrunner/model/gemma4/gemma4.go
@@ -1438,51 +1438,15 @@ func (a *Attention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positio
}
var out *mlx.Array
- if headDim > 128 && L > 1 && !mlx.MetalIsAvailable() {
- // Manual attention for CUDA prefill with head_dim > 128.
- // cuDNN SDPA requires head_dim <= 128, and the MLX CUDA SDPA vector
- // kernel only handles L < 4 (generation). For prefill, we fall back
- // to explicit matmul+softmax+matmul on CUDA.
- var k, v *mlx.Array
- mask := baseMask.Intersect(nn.QPaddingMask(b, q.DType()))
- if kv.history != nil {
- k, v = kv.history.K(), kv.history.V()
- mask = kv.history.Mask(mask)
- } else {
- k, v = kv.k, kv.v
- mask = mask.Intersect(nn.KPaddingMask(b, k.Dim(2), b.SeqQueryLens, q.DType()))
- mask = mask.Intersect(kv.mask)
- }
- kvHeads := int32(k.Dim(1))
- nRepeats := cfg.NumAttentionHeads / kvHeads
- kLen := int32(k.Dim(2))
- // AsArray returns [B, 1, L, K]; reshape to rank 5 so that
- // right-to-left broadcast against scores [B, kvHeads,
- // nRepeats, L, K] aligns the batch dim correctly.
- maskArr := mlx.Reshape(mask.AsArray(b, int(kLen), q.DType()), B, 1, 1, L, kLen)
-
- q = mlx.MulScalar(q, scale)
- q = mlx.Reshape(q, B, kvHeads, nRepeats, L, headDim)
- k = mlx.Reshape(k, B, kvHeads, 1, kLen, headDim)
- v = mlx.Reshape(v, B, kvHeads, 1, kLen, headDim)
-
- kT := mlx.Transpose(k, 0, 1, 2, 4, 3)
- scores := mlx.Matmul(q, kT)
- scores = mlx.Add(scores, maskArr)
- scores = mlx.SoftmaxAxis(scores, -1, true)
- out = mlx.Matmul(scores, v)
- out = mlx.Reshape(out, B, cfg.NumAttentionHeads, L, headDim)
+ var opt nn.SDPAOption
+ mask := baseMask
+ if kv.history != nil {
+ opt = nn.WithKVHistory(kv.history)
} else {
- var opt nn.SDPAOption
- mask := baseMask
- if kv.history != nil {
- opt = nn.WithKVHistory(kv.history)
- } else {
- opt = nn.WithKV(kv.k, kv.v, b.SeqQueryLens)
- mask = mask.Intersect(kv.mask)
- }
- out = nn.ScaledDotProductAttention(b, q, scale, opt, nn.WithMask(mask))
+ opt = nn.WithKV(kv.k, kv.v, b.SeqQueryLens)
+ mask = mask.Intersect(kv.mask)
}
+ out = nn.ScaledDotProductAttention(b, q, scale, opt, nn.WithMask(mask))
out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), B, L, cfg.NumAttentionHeads*headDim)
if !mlx.MetalIsAvailable() {
// Force contiguous layout before OProj on CUDA where matmul handles