Skip to content

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

mlxrunner: keep gated-delta recurrent state in float32

Jesse Gross275f122cda4e
diff --git a/x/mlxrunner/cache/recurrent.go b/x/mlxrunner/cache/recurrent.go
index cf87953db..d920e8807 100644
--- a/x/mlxrunner/cache/recurrent.go
+++ b/x/mlxrunner/cache/recurrent.go
@@ -1,6 +1,8 @@
package cache
import (
+ "fmt"
+
"github.com/ollama/ollama/x/mlxrunner/batch"
"github.com/ollama/ollama/x/mlxrunner/mlx"
"github.com/ollama/ollama/x/models/nn"
@@ -8,6 +10,11 @@ import (
// RecurrentCache stores state for linear-recurrent layers.
//
+// Conv state takes its dtype from the first Get call (the activation dtype).
+// Delta state is always float32: the gated-delta recurrent accumulator runs
+// for the full sequence length and needs the extra precision regardless of
+// activation dtype.
+//
// Conv state shape: [B, convTail, convDim]
// Delta state shape: [B, numVHeads, headVDim, headKDim]
type RecurrentCache struct {
@@ -48,33 +55,30 @@ func NewRecurrentCache(convTail, convDim, numVHeads, headVDim, headKDim int32) *
}
}
-func (c *RecurrentCache) ensure(batch int, dtype mlx.DType) {
+// Get returns the current conv/delta state for the SSM layer's read
+// phase. On first call it lazy-initializes zero-filled state tensors
+// sized from b.InputIDs and dtyped from the caller's activation dtype.
+// On subsequent calls it returns the existing state; batch size and
+// dtype must match the first call, since recurrent state is cumulative
+// and cannot be reshaped without losing history.
+func (c *RecurrentCache) Get(b *batch.Batch, dtype mlx.DType) *nn.RecurrentHistory {
+ batch := b.InputIDs.Dim(0)
if batch <= 0 {
batch = 1
}
- needConv := c.convState == nil || !c.convState.Valid() || c.convState.DType() != dtype ||
- c.convState.Dim(0) != batch || c.convState.Dim(1) != c.convTail || c.convState.Dim(2) != c.convDim
- needDelta := c.deltaState == nil || !c.deltaState.Valid() || c.deltaState.DType() != dtype ||
- c.deltaState.Dim(0) != batch || c.deltaState.Dim(1) != c.numVHeads || c.deltaState.Dim(2) != c.headVDim || c.deltaState.Dim(3) != c.headKDim
- if !needConv && !needDelta {
- return
- }
-
- if needConv {
- c.convState = c.setState(c.convState, mlx.Zeros(dtype, batch, c.convTail, c.convDim), false)
- }
- if needDelta {
- c.deltaState = c.setState(c.deltaState, mlx.Zeros(dtype, batch, c.numVHeads, c.headVDim, c.headKDim), false)
+ if c.convState != nil {
+ if got := c.convState.Dim(0); got != batch {
+ panic(fmt.Sprintf("recurrent cache: batch size changed mid-sequence (have %d, got %d)", got, batch))
+ }
+ if got := c.convState.DType(); got != dtype {
+ panic(fmt.Sprintf("recurrent cache: conv dtype changed mid-sequence (have %v, got %v)", got, dtype))
+ }
+ return nn.NewRecurrentHistory(c.convState, c.deltaState)
}
-}
-// Get returns the current conv/delta state for the SSM layer's read
-// phase. Lazy-initializes zero-filled state tensors using b.InputIDs
-// for the batch size; reallocates if the existing state's batch size
-// or dtype no longer matches.
-func (c *RecurrentCache) Get(b *batch.Batch, dtype mlx.DType) *nn.RecurrentHistory {
- c.ensure(b.InputIDs.Dim(0), dtype)
+ c.convState = c.setState(nil, mlx.Zeros(dtype, batch, c.convTail, c.convDim), false)
+ c.deltaState = c.setState(nil, mlx.Zeros(mlx.DTypeFloat32, batch, c.numVHeads, c.headVDim, c.headKDim), false)
return nn.NewRecurrentHistory(c.convState, c.deltaState)
}
diff --git a/x/mlxrunner/cache/recurrent_test.go b/x/mlxrunner/cache/recurrent_test.go
index 31e58dae2..cf98b6378 100644
--- a/x/mlxrunner/cache/recurrent_test.go
+++ b/x/mlxrunner/cache/recurrent_test.go
@@ -63,8 +63,8 @@ func TestRecurrentCacheGetLazyInit(t *testing.T) {
if got := h.ConvState().DType(); got != mlx.DTypeBFloat16 {
t.Fatalf("conv state dtype = %v, want %v", got, mlx.DTypeBFloat16)
}
- if got := h.DeltaState().DType(); got != mlx.DTypeBFloat16 {
- t.Fatalf("delta state dtype = %v, want %v", got, mlx.DTypeBFloat16)
+ if got := h.DeltaState().DType(); got != mlx.DTypeFloat32 {
+ t.Fatalf("delta state dtype = %v, want %v", got, mlx.DTypeFloat32)
}
}
diff --git a/x/mlxrunner/mlx/gated_delta.go b/x/mlxrunner/mlx/gated_delta.go
index 7034c33a6..729af01c3 100644
--- a/x/mlxrunner/mlx/gated_delta.go
+++ b/x/mlxrunner/mlx/gated_delta.go
@@ -83,7 +83,7 @@ for (int t = 0; t < T; ++t) {
for (int i = 0; i < n_per_t; ++i) {
auto s_idx = n_per_t * dk_idx + i;
- o_state[s_idx] = static_cast<InT>(state[i]);
+ o_state[s_idx] = static_cast<StT>(state[i]);
}
`
@@ -163,7 +163,7 @@ for (int t = 0; t < T_val; ++t) {
for (int i = 0; i < n_per_t; ++i) {
auto s_idx = n_per_t * dk_idx + i;
- o_state[s_idx] = static_cast<InT>(state[i]);
+ o_state[s_idx] = static_cast<StT>(state[i]);
}
`
@@ -262,8 +262,9 @@ func gatedDeltaKernel(q, k, v, g, beta, state *Array) (y, nextState *Array, ok b
return nil, nil, false
}
- dtype := q.DType()
- if k.DType() != dtype || v.DType() != dtype || g.DType() != dtype || beta.DType() != dtype || state.DType() != dtype {
+ inputDType := q.DType()
+ stateDType := state.DType()
+ if k.DType() != inputDType || v.DType() != inputDType || g.DType() != inputDType || beta.DType() != inputDType {
return nil, nil, false
}
@@ -277,7 +278,13 @@ func gatedDeltaKernel(q, k, v, g, beta, state *Array) (y, nextState *Array, ok b
cInT := C.CString("InT")
defer C.free(unsafe.Pointer(cInT))
- if C.mlx_fast_metal_kernel_config_add_template_arg_dtype(cfg, cInT, C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_metal_kernel_config_add_template_arg_dtype(cfg, cInT, C.mlx_dtype(inputDType)) != 0 {
+ gatedDeltaMetalDisabled = true
+ return nil, nil, false
+ }
+ cStT := C.CString("StT")
+ defer C.free(unsafe.Pointer(cStT))
+ if C.mlx_fast_metal_kernel_config_add_template_arg_dtype(cfg, cStT, C.mlx_dtype(stateDType)) != 0 {
gatedDeltaMetalDisabled = true
return nil, nil, false
}
@@ -301,11 +308,11 @@ func gatedDeltaKernel(q, k, v, g, beta, state *Array) (y, nextState *Array, ok b
yShape := []C.int{C.int(B), C.int(T), C.int(Hv), C.int(Dv)}
stateShape := []C.int{C.int(B), C.int(Hv), C.int(Dv), C.int(Dk)}
- if C.mlx_fast_metal_kernel_config_add_output_arg(cfg, unsafe.SliceData(yShape), C.size_t(len(yShape)), C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_metal_kernel_config_add_output_arg(cfg, unsafe.SliceData(yShape), C.size_t(len(yShape)), C.mlx_dtype(inputDType)) != 0 {
gatedDeltaMetalDisabled = true
return nil, nil, false
}
- if C.mlx_fast_metal_kernel_config_add_output_arg(cfg, unsafe.SliceData(stateShape), C.size_t(len(stateShape)), C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_metal_kernel_config_add_output_arg(cfg, unsafe.SliceData(stateShape), C.size_t(len(stateShape)), C.mlx_dtype(stateDType)) != 0 {
gatedDeltaMetalDisabled = true
return nil, nil, false
}
@@ -516,8 +523,9 @@ func gatedDeltaCUDAKernelApply(q, k, v, g, beta, state *Array) (y, nextState *Ar
return nil, nil, false
}
- dtype := q.DType()
- if k.DType() != dtype || v.DType() != dtype || g.DType() != dtype || beta.DType() != dtype || state.DType() != dtype {
+ inputDType := q.DType()
+ stateDType := state.DType()
+ if k.DType() != inputDType || v.DType() != inputDType || g.DType() != inputDType || beta.DType() != inputDType {
return nil, nil, false
}
@@ -531,7 +539,13 @@ func gatedDeltaCUDAKernelApply(q, k, v, g, beta, state *Array) (y, nextState *Ar
cInT := C.CString("InT")
defer C.free(unsafe.Pointer(cInT))
- if C.mlx_fast_cuda_kernel_config_add_template_arg_dtype(cfg, cInT, C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_cuda_kernel_config_add_template_arg_dtype(cfg, cInT, C.mlx_dtype(inputDType)) != 0 {
+ gatedDeltaCUDADisabled = true
+ return nil, nil, false
+ }
+ cStT := C.CString("StT")
+ defer C.free(unsafe.Pointer(cStT))
+ if C.mlx_fast_cuda_kernel_config_add_template_arg_dtype(cfg, cStT, C.mlx_dtype(stateDType)) != 0 {
gatedDeltaCUDADisabled = true
return nil, nil, false
}
@@ -555,11 +569,11 @@ func gatedDeltaCUDAKernelApply(q, k, v, g, beta, state *Array) (y, nextState *Ar
yShape := []C.int{C.int(B), C.int(T), C.int(Hv), C.int(Dv)}
stateShape := []C.int{C.int(B), C.int(Hv), C.int(Dv), C.int(Dk)}
- if C.mlx_fast_cuda_kernel_config_add_output_arg(cfg, unsafe.SliceData(yShape), C.size_t(len(yShape)), C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_cuda_kernel_config_add_output_arg(cfg, unsafe.SliceData(yShape), C.size_t(len(yShape)), C.mlx_dtype(inputDType)) != 0 {
gatedDeltaCUDADisabled = true
return nil, nil, false
}
- if C.mlx_fast_cuda_kernel_config_add_output_arg(cfg, unsafe.SliceData(stateShape), C.size_t(len(stateShape)), C.mlx_dtype(dtype)) != 0 {
+ if C.mlx_fast_cuda_kernel_config_add_output_arg(cfg, unsafe.SliceData(stateShape), C.size_t(len(stateShape)), C.mlx_dtype(stateDType)) != 0 {
gatedDeltaCUDADisabled = true
return nil, nil, false
}
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index 47c02ed4a..58b142635 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -1168,7 +1168,7 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
} else {
rec = nn.WithRecurrentState(
mlx.Zeros(x.DType(), int(B), int(convTail), qkv.Dim(2)),
- mlx.Zeros(x.DType(), int(B), int(cfg.LinearNumValueHeads), int(cfg.LinearValueHeadDim), int(cfg.LinearKeyHeadDim)),
+ mlx.Zeros(mlx.DTypeFloat32, int(B), int(cfg.LinearNumValueHeads), int(cfg.LinearValueHeadDim), int(cfg.LinearKeyHeadDim)),
)
}