Skip to content

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

nn/recurrent: activate the conv output in CausalConv1D

Jesse Gross721f05049d4c
diff --git a/x/mlxrunner/mlx/depthwise_conv.go b/x/mlxrunner/mlx/depthwise_conv.go
new file mode 100644
index 000000000..d92cd30f7
--- /dev/null
+++ b/x/mlxrunner/mlx/depthwise_conv.go
@@ -0,0 +1,88 @@
+package mlx
+
+import "fmt"
+
+// B and T arrive as runtime scalars rather than template arguments so
+// windows of any length share one compiled pipeline; only the channel
+// geometry specializes the kernel.
+const depthwiseConvSiLUMetalSource = `
+auto elem = thread_position_in_grid.x;
+int B = dims[0];
+int T = dims[1];
+uint total = uint(B) * uint(T) * uint(C);
+if (elem >= total) {
+ return;
+}
+
+int c = int(elem % uint(C));
+int t = int(elem / uint(C)) % T;
+int b = int(elem) / (C * T);
+auto in_base = (b * (T + K - 1) + t) * C + c;
+
+float acc = 0.0f;
+for (int i = 0; i < K; ++i) {
+ acc += static_cast<float>(x[in_base + i * C]) * static_cast<float>(w[c * K + i]);
+}
+
+InT conv_out = static_cast<InT>(acc);
+InT sigmoid = stable_sigmoid(conv_out);
+out[elem] = static_cast<InT>(conv_out * sigmoid);
+`
+
+const depthwiseConvSiLUMetalHeader = `
+template <typename T>
+T stable_sigmoid(T x) {
+ auto y = 1 / (1 + metal::exp(metal::abs(x)));
+ return (x < 0) ? y : 1 - y;
+}
+`
+
+var depthwiseConvSiLU = &gpuKernel{
+ name: "depthwise_conv_silu",
+ inputs: []string{"x", "w", "dims"},
+ outputs: []string{"out"},
+ metal: gpuSource{
+ source: depthwiseConvSiLUMetalSource,
+ header: depthwiseConvSiLUMetalHeader,
+ },
+ fallback: func(launch gpuLaunch) []*Array {
+ return []*Array{depthwiseConvSiLUGraph(launch.inputs[0], launch.inputs[1])}
+ },
+}
+
+func depthwiseConvSiLUGraph(x, w *Array) *Array {
+ Cdim, K := int32(w.Dim(0)), int32(w.Dim(1))
+ return SiLU(Conv1d(x, Reshape(w, Cdim, K, 1), nil, 1, 0, 1, Cdim))
+}
+
+// DepthwiseConvSiLU computes SiLU of a valid depthwise conv: x
+// [B, T+K-1, C] and w [C, K] give [B, T, C], each output reading the K
+// trailing input rows starting at its own index. Inputs that fit the fused
+// kernel's contract run there; anything else runs the same computation as
+// graph ops. The accumulator is rounded to the input dtype before the
+// activation so the result matches SiLU applied to the graph conv's output.
+func DepthwiseConvSiLU(x, w *Array, outLen int) *Array {
+ if x == nil || w == nil || x.NumDims() != 3 || w.NumDims() != 2 {
+ panic("mlx.DepthwiseConvSiLU: need x [B, T+K-1, C] and w [C, K]")
+ }
+ B, Cdim, K := x.Dim(0), x.Dim(2), w.Dim(1)
+ if w.Dim(0) != Cdim || K <= 0 || x.Dim(1) != outLen+K-1 {
+ panic(fmt.Sprintf("mlx.DepthwiseConvSiLU: shapes x %v, w %v do not fit outLen %d", x.Dims(), w.Dims(), outLen))
+ }
+ if x.DType() != w.DType() || (x.DType() != DTypeBFloat16 && x.DType() != DTypeFloat32) {
+ return depthwiseConvSiLUGraph(x, w)
+ }
+
+ total := B * outLen * Cdim
+ outs := depthwiseConvSiLU.run(gpuLaunch{
+ dtypes: []gpuDTypeArg{{"InT", x.DType()}},
+ ints: []gpuIntArg{{"C", Cdim}, {"K", K}},
+ outputs: []gpuOutputSpec{
+ {"DEPTHWISE_CONV_SILU", []int32{int32(B), int32(outLen), int32(Cdim)}, x.DType()},
+ },
+ grid: [3]int{(total + 255) / 256 * 256, 1, 1},
+ threadGroup: [3]int{256, 1, 1},
+ inputs: []*Array{x, w, NewArrayInt32([]int32{int32(B), int32(outLen)}, []int32{2})},
+ })
+ return outs[0]
+}
diff --git a/x/mlxrunner/mlx/depthwise_conv_test.go b/x/mlxrunner/mlx/depthwise_conv_test.go
new file mode 100644
index 000000000..61b39d6f1
--- /dev/null
+++ b/x/mlxrunner/mlx/depthwise_conv_test.go
@@ -0,0 +1,37 @@
+package mlx
+
+import (
+ "fmt"
+ "testing"
+)
+
+func TestDepthwiseConvSiLUMatchesGraph(t *testing.T) {
+ skipIfNoMLX(t)
+ withMLXThread(t, func() {
+ testDepthwiseConvSiLUMatchesGraph(t)
+ })
+}
+
+func testDepthwiseConvSiLUMatchesGraph(t *testing.T) {
+ for _, dtype := range []DType{DTypeBFloat16, DTypeFloat32} {
+ for _, shape := range []struct{ B, T, C, K int }{
+ {1, 1, 64, 4},
+ {1, 4, 64, 4},
+ {1, 11, 96, 4},
+ {1, 64, 64, 4},
+ {1, 333, 64, 4},
+ {3, 7, 64, 4},
+ {2, 5, 32, 2},
+ } {
+ name := fmt.Sprintf("%v_b%d_t%d_c%d_k%d", dtype, shape.B, shape.T, shape.C, shape.K)
+ x := patternArray(dtype, []int{shape.B, shape.T + shape.K - 1, shape.C}, 0.02, 0.004, 41, 263)
+ w := patternArray(dtype, []int{shape.C, shape.K}, 0.1, 0.01, 7, 53)
+
+ ref := SiLU(Conv1d(x, Reshape(w, int32(shape.C), int32(shape.K), 1), nil, 1, 0, 1, int32(shape.C)))
+ y := DepthwiseConvSiLU(x, w, shape.T)
+ if err := requireExact("y", y, ref); err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ }
+}
diff --git a/x/mlxrunner/mlx/kernel_test.go b/x/mlxrunner/mlx/kernel_test.go
new file mode 100644
index 000000000..4ae7ea2cf
--- /dev/null
+++ b/x/mlxrunner/mlx/kernel_test.go
@@ -0,0 +1,36 @@
+package mlx
+
+import (
+ "fmt"
+ "math"
+)
+
+// patternArray builds a deterministic value lattice for kernel parity tests.
+func patternArray(dtype DType, shape []int, bias, scale float32, stride, modulus int) *Array {
+ size := 1
+ for _, dim := range shape {
+ size *= dim
+ }
+ values := make([]float32, size)
+ center := modulus / 2
+ for i := range values {
+ values[i] = bias + float32((i*stride)%modulus-center)*scale
+ }
+ return FromValues(values, shape...).AsType(dtype)
+}
+
+// requireExact compares two arrays bit-for-bit after widening to float32.
+func requireExact(label string, got, want *Array) error {
+ got32, want32 := got.AsType(DTypeFloat32), want.AsType(DTypeFloat32)
+ Eval(got32, want32)
+ gotValues, wantValues := got32.Floats(), want32.Floats()
+ if len(gotValues) != len(wantValues) {
+ return fmt.Errorf("%s length = %d, want %d", label, len(gotValues), len(wantValues))
+ }
+ for i := range wantValues {
+ if math.Float32bits(gotValues[i]) != math.Float32bits(wantValues[i]) {
+ return fmt.Errorf("%s[%d] = %v, want %v", label, i, gotValues[i], wantValues[i])
+ }
+ }
+ return nil
+}
diff --git a/x/models/nn/recurrent.go b/x/models/nn/recurrent.go
index 57dedca57..ecc692f05 100644
--- a/x/models/nn/recurrent.go
+++ b/x/models/nn/recurrent.go
@@ -18,6 +18,7 @@ type recurrentConfig struct {
convState *mlx.Array
deltaState *mlx.Array
splits []int
+ convSiLU bool
}
// WithRecurrentHistory supplies a cache's per-layer view of conv and
@@ -37,6 +38,13 @@ func WithRecurrentState(convState, deltaState *mlx.Array) RecurrentOption {
}
}
+// WithConvSiLU applies SiLU to the conv output inside CausalConv1D,
+// fused into the conv kernel when the conv fits its contract. GatedDelta
+// ignores it, so it can ride a shared option list.
+func WithConvSiLU() RecurrentOption {
+ return func(c *recurrentConfig) { c.convSiLU = true }
+}
+
// WithSnapshotSplits requests that the scan run in segments cut at the given
// offsets within this forward (0 < offset < L), capturing the recurrent state
// at each boundary. The wrapper returns those per-boundary states to the
@@ -105,7 +113,7 @@ func resolveRecurrentConfig(opts []RecurrentOption) recurrentConfig {
// CausalConv1D runs a depthwise causal 1D convolution with recurrent
// state management. Prepends the prior conv state along axis 1 and runs
-// conv.Forward over the combined window.
+// the conv over the combined window.
//
// Shapes: input [B, L, D]; prior state [B, convTail, D]; output
// [B, L, D] (the causal conv strips the prepended state).
@@ -137,7 +145,15 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
input = mlx.Where(mlx.ExpandDims(mask, 2), input, zero)
}
concat := mlx.Concatenate([]*mlx.Array{prior, input}, 1)
- out = conv.Forward(concat)
+ if cfg.convSiLU {
+ if w := depthwiseConvWeight(conv); w != nil {
+ out = mlx.DepthwiseConvSiLU(concat, w, int(L))
+ } else {
+ out = mlx.SiLU(conv.Forward(concat))
+ }
+ } else {
+ out = conv.Forward(concat)
+ }
// Snapshot the conv tail at each segment boundary: interior splits in
// ascending order, then the forward end at L. Each boundary at offset O
@@ -156,6 +172,18 @@ func CausalConv1D(b *batch.Batch, input *mlx.Array, conv *Conv1d, convTail int,
return out, states
}
+// depthwiseConvWeight returns the [C, K] weight view the fused conv kernel
+// takes, or nil when the conv is not a plain depthwise causal conv.
+func depthwiseConvWeight(c *Conv1d) *mlx.Array {
+ if c.Bias != nil || c.Stride != 1 || c.Padding != 0 || c.Dilation != 1 {
+ return nil
+ }
+ if c.Weight.NumDims() != 3 || c.Weight.Dim(2) != 1 || int(c.Groups) != c.Weight.Dim(0) {
+ return nil
+ }
+ return mlx.Reshape(c.Weight, int32(c.Weight.Dim(0)), int32(c.Weight.Dim(1)))
+}
+
// convStateAt returns the conv state to cache at boundary: the trailing convTail
// input positions ending at boundary, clamped per row to the row's real length so
// a padded row freezes at its real end rather than capturing padding. The prior
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index 9100585d0..2501a7d89 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -1039,7 +1039,8 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
alpha := mlx.SliceStartStop(mixedBA, []int32{0, 0, cfg.LinearNumValueHeads}, []int32{B, L, 2 * cfg.LinearNumValueHeads})
convTail := cfg.LinearConvKernelDim - 1
var rc *cache.RecurrentCache
- opts := make([]nn.RecurrentOption, 0, 2)
+ opts := make([]nn.RecurrentOption, 0, 3)
+ opts = append(opts, nn.WithConvSiLU())
if typed, ok := c.(*cache.RecurrentCache); ok {
rc = typed
opts = append(opts, nn.WithRecurrentHistory(rc.Get(b, x.DType())))
@@ -1057,7 +1058,6 @@ func (g *GatedDeltaNet) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B,
}
convOut, convStates := nn.CausalConv1D(b, qkv, g.Conv1D, int(convTail), opts...)
- convOut = mlx.SiLU(convOut)
q := mlx.SliceStartStop(convOut, []int32{0, 0, 0}, []int32{B, L, keyDim})
k := mlx.SliceStartStop(convOut, []int32{0, 0, keyDim}, []int32{B, L, 2 * keyDim})