Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
mlx: port the Metal custom kernels to CUDA (#18657)
Daniel Hiltgen63b4f61ca926
diff --git a/mlx/depthwise_conv.go b/mlx/depthwise_conv.goindex 738e57ce6..7cb38fb92 100644--- a/mlx/depthwise_conv.go+++ b/mlx/depthwise_conv.go@@ -32,6 +32,7 @@ InT sigmoid = stable_sigmoid(conv_out);out[elem] = static_cast<InT>(conv_out * sigmoid);`+// TODO: call MLX's Sigmoid like CUDA does to DRY this out.const depthwiseConvSiLUMetalHeader = `template <typename T>T stable_sigmoid(T x) {@@ -40,6 +41,42 @@ T stable_sigmoid(T x) {}`+// The CUDA translation of depthwiseConvSiLUMetalSource.+const depthwiseConvSiLUCUDASource = `+unsigned int elem = blockIdx.x * blockDim.x + threadIdx.x;+int B = dims[0];+int T = dims[1];+unsigned int total = static_cast<unsigned int>(B) * static_cast<unsigned int>(T) * static_cast<unsigned int>(C);+if (elem >= total) {+ return;+}++int c = static_cast<int>(elem % static_cast<unsigned int>(C));+int t = static_cast<int>(elem / static_cast<unsigned int>(C)) % T;+int b = static_cast<int>(elem) / (C * T);+int in_base = (b * (T + K - 1) + t) * C + c;++// Not fmaf: the graph path rounds the multiply and the add separately.+float acc = 0.0f;+#pragma unroll+for (int i = 0; i < K; ++i) {+ acc += static_cast<float>(x[in_base + i * C]) * static_cast<float>(w[c * K + i]);+}++// The graph path is Add(conv(x, w), bias), so it rounds twice. Folding the+// bias into the float accumulator would round once and drift by an ULP.+InT conv_out = static_cast<InT>(acc);+conv_out = static_cast<InT>(static_cast<float>(conv_out) + DEPTHWISE_CONV_BIAS(c));+InT sigmoid = Sigmoid{}(conv_out);+out[elem] = static_cast<InT>(conv_out * sigmoid);+`++// MLX's own Sigmoid, so this stays bit-exact with the graph path's SiLU.+// unary_ops.cuh is embedded for the runtime JIT, so nvrtc resolves it.+const depthwiseConvSiLUCUDAHeader = `+#include "mlx/backend/cuda/device/unary_ops.cuh"+`+var (depthwiseConvSiLU = &gpuKernel{name: "depthwise_conv_silu",@@ -49,6 +86,10 @@ var (source: depthwiseConvSiLUMetalSource,header: depthwiseConvSiLUMetalHeader + "#define DEPTHWISE_CONV_BIAS(c) 0.0f\n",},+ cuda: gpuSource{+ source: depthwiseConvSiLUCUDASource,+ header: depthwiseConvSiLUCUDAHeader + "#define DEPTHWISE_CONV_BIAS(c) 0.0f\n",+ },fallback: func(launch gpuLaunch) []*Array {return []*Array{depthwiseConvSiLUGraph(launch.inputs[0], launch.inputs[1], nil)}},@@ -61,6 +102,10 @@ var (source: depthwiseConvSiLUMetalSource,header: depthwiseConvSiLUMetalHeader + "#define DEPTHWISE_CONV_BIAS(c) static_cast<float>(bias[c])\n",},+ cuda: gpuSource{+ source: depthwiseConvSiLUCUDASource,+ header: depthwiseConvSiLUCUDAHeader + "#define DEPTHWISE_CONV_BIAS(c) static_cast<float>(bias[c])\n",+ },fallback: func(launch gpuLaunch) []*Array {in := launch.inputsreturn []*Array{depthwiseConvSiLUGraph(in[0], in[1], in[2])}diff --git a/mlx/gated_delta.go b/mlx/gated_delta.goindex 77a7ea944..63576a6e8 100644--- a/mlx/gated_delta.go+++ b/mlx/gated_delta.go@@ -351,6 +351,10 @@ var (source: gatedDeltaMetalSource,header: gatedDeltaMetalHeader + "#define GDN_STORE_INTERIOR(index, value)\n",},+ cuda: gpuSource{+ source: gatedDeltaCUDASource,+ header: gatedDeltaCUDAHeader + "#define GDN_STORE_INTERIOR(index, value)\n",+ },fallback: func(launch gpuLaunch) []*Array {in := launch.inputsy, end, _ := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], false, false)@@ -365,6 +369,10 @@ var (source: gatedDeltaMetalSource,header: gatedDeltaMetalHeader + "#define GDN_STORE_INTERIOR(index, value) state_seq[index] = value\n",},+ cuda: gpuSource{+ source: gatedDeltaCUDASource,+ header: gatedDeltaCUDAHeader + "#define GDN_STORE_INTERIOR(index, value) state_seq[index] = value\n",+ },fallback: func(launch gpuLaunch) []*Array {in := launch.inputsy, end, interior := gatedDeltaGraph(in[0], in[1], in[2], in[3], in[5], true, false)@@ -596,6 +604,148 @@ for (int value_iter = 0; value_iter < ValuesPerSIMD; ++value_iter) {}`+// The CUDA translation of gatedDeltaMetalSource. Metal's threadgroup caches+// become per-warp registers: every warp normalizes the same q/k row and+// broadcasts the gates over its own lanes, so the step needs no shared+// memory and no barriers.+const gatedDeltaCUDASource = `+constexpr int SIMDGroups = 4;+constexpr int ValuesPerSIMD = DvTile / SIMDGroups;+constexpr int StatePerLane = Dk / 32;+constexpr int QDim = Hk * Dk;++int lane = static_cast<int>(threadIdx.x);+int simd_idx = static_cast<int>(threadIdx.y);+int n = static_cast<int>(blockIdx.z);+int b_idx = n / Hv;+int hv_idx = n % Hv;+int hk_idx = hv_idx / (Hv / Hk);+int value_tile = static_cast<int>(blockIdx.y);+int grid_z = static_cast<int>(gridDim.z * blockDim.z);++float state[ValuesPerSIMD][StatePerLane];+for (int value_iter = 0; value_iter < ValuesPerSIMD; ++value_iter) {+ int dv_idx = value_tile * DvTile + simd_idx + value_iter * SIMDGroups;+ int state_offset = (n * Dv + dv_idx) * Dk;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ int d = StatePerLane * lane + i;+ state[value_iter][i] = state_in[state_offset + d];+ }+}++for (int t = 0; t < SeqT; ++t) {+ auto token = packed + (b_idx * SeqT + t) * PackedDim;++ InT q_row[StatePerLane];+ InT k_row[StatePerLane];+ {+ float q_values[StatePerLane];+ float k_values[StatePerLane];+ float q_squares = 0.0f;+ float k_squares = 0.0f;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ int d = StatePerLane * lane + i;+ float q_value = static_cast<float>(token[hk_idx * Dk + d]);+ float k_value = static_cast<float>(token[QDim + hk_idx * Dk + d]);+ q_values[i] = q_value;+ k_values[i] = k_value;+ q_squares += q_value * q_value;+ k_squares += k_value * k_value;+ }+ q_squares = gdn_simd_sum(q_squares);+ k_squares = gdn_simd_sum(k_squares);+ float q_inv_rms = rsqrtf(q_squares / float(Dk) + 1.0e-6f);+ float k_inv_rms = rsqrtf(k_squares / float(Dk) + 1.0e-6f);+ InT q_scale = static_cast<InT>(qk_scale[0]);+ InT k_scale = static_cast<InT>(qk_scale[1]);+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ InT q_norm = static_cast<InT>(q_values[i] * q_inv_rms);+ InT k_norm = static_cast<InT>(k_values[i] * k_inv_rms);+ q_row[i] = static_cast<InT>(q_norm * q_scale);+ k_row[i] = static_cast<InT>(k_norm * k_scale);+ }+ }++ // Metal rounds both gates to InT through threadgroup memory, so round+ // here too rather than carrying float precision forward.+ float decay = 0.0f;+ float beta_gate = 0.0f;+ if (lane == 0) {+ int ba_row = (b_idx * SeqT + t) * 2 * Hv;+ InT gate_input = static_cast<InT>(ba[ba_row + Hv + hv_idx] + dt_bias[hv_idx]);+ InT softplus = LogAddExp{}(gate_input, static_cast<InT>(0));+ decay = static_cast<float>(static_cast<InT>(+ Exp{}(-static_cast<float>(softplus) * a_exp[hv_idx])));+ beta_gate = static_cast<float>(Sigmoid{}(ba[ba_row + hv_idx]));+ }+ decay = __shfl_sync(0xffffffff, decay, 0);+ beta_gate = __shfl_sync(0xffffffff, beta_gate, 0);++ for (int value_iter = 0; value_iter < ValuesPerSIMD; ++value_iter) {+ int dv_idx = value_tile * DvTile + simd_idx + value_iter * SIMDGroups;+ float projection = 0.0f;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ state[value_iter][i] *= decay;+ projection += state[value_iter][i] * static_cast<float>(k_row[i]);+ }+ projection = gdn_simd_sum(projection);++ float v_value = static_cast<float>(token[2 * QDim + hv_idx * Dv + dv_idx]);+ float delta = (v_value - projection) * beta_gate;++ float out = 0.0f;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ state[value_iter][i] += static_cast<float>(k_row[i]) * delta;+ out += state[value_iter][i] * static_cast<float>(q_row[i]);+ }+ out = gdn_simd_sum(out);+ if (lane == 0) {+ y[((b_idx * SeqT + t) * Hv + hv_idx) * Dv + dv_idx] = static_cast<InT>(out);+ }++ if (t + 1 < SeqT) {+ int seq_offset = ((t * grid_z + n) * Dv + dv_idx) * Dk;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ int d = StatePerLane * lane + i;+ GDN_STORE_INTERIOR(seq_offset + d, state[value_iter][i]);+ }+ }+ }+}++for (int value_iter = 0; value_iter < ValuesPerSIMD; ++value_iter) {+ int dv_idx = value_tile * DvTile + simd_idx + value_iter * SIMDGroups;+ int state_offset = (n * Dv + dv_idx) * Dk;+#pragma unroll+ for (int i = 0; i < StatePerLane; ++i) {+ int d = StatePerLane * lane + i;+ state_out[state_offset + d] = state[value_iter][i];+ }+}+`++// MLX's own ops, so the gates match the graph path this is pinned against.+// Both headers are embedded for the runtime JIT. gdn_simd_sum is Metal's+// simd_sum: a full-warp reduction every lane can read.+const gatedDeltaCUDAHeader = `+#include "mlx/backend/cuda/device/binary_ops.cuh"+#include "mlx/backend/cuda/device/unary_ops.cuh"++__device__ inline float gdn_simd_sum(float v) {+ for (int offset = 16; offset > 0; offset >>= 1) {+ v += __shfl_down_sync(0xffffffff, v, offset);+ }+ return __shfl_sync(0xffffffff, v, 0);+}+`++// TODO: call MLX's Sigmoid/LogAddExp like CUDA does to DRY this out.const gatedDeltaMetalHeader = `template <typename T>T gdn_sigmoid(T x) {diff --git a/mlx/gated_delta_test.go b/mlx/gated_delta_test.goindex 5b9c17116..8b69bd5b8 100644--- a/mlx/gated_delta_test.go+++ b/mlx/gated_delta_test.go@@ -56,17 +56,17 @@ func testGatedDeltaMatchesGraph(t *mlxthreadtest.T) {in := batchGatedDeltaRows(gatedDeltaTestInputs36(g, T), B)refY, refState, refInterior := gatedDeltaReference(in, captureAll)y, state, interior := GatedDelta(in.packed, in.ba, in.dtBias, in.aExp, in.state, nil, captureAll)- if err := requireExact("y", y, refY); err != nil {+ if err := requireClose("y", y, refY, gatedDeltaGraphTol); err != nil {t.Fatalf("%s: %v", name, err)}- if err := requireExact("state", state, refState); err != nil {+ if err := requireClose("state", state, refState, gatedDeltaGraphTol); err != nil {t.Fatalf("%s: %v", name, err)}if captureAll && len(interior) != len(refInterior) {t.Fatalf("%s: interior count = %d, want %d", name, len(interior), len(refInterior))}for i := range interior {- if err := requireExact(fmt.Sprintf("interior[%d]", i), interior[i], refInterior[i]); err != nil {+ if err := requireClose(fmt.Sprintf("interior[%d]", i), interior[i], refInterior[i], gatedDeltaGraphTol); err != nil {t.Fatalf("%s: %v", name, err)}}diff --git a/mlx/kernel_test.go b/mlx/kernel_test.goindex 4ae7ea2cf..efd921911 100644--- a/mlx/kernel_test.go+++ b/mlx/kernel_test.go@@ -3,8 +3,19 @@ package mlximport ("fmt""math"++ "github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest")+// requireGPUKernel skips where the kernel path and the reference would both+// be the same graph ops.+func requireGPUKernel(t *mlxthreadtest.T) {+ t.Helper()+ if !MetalIsAvailable() && !CUDAIsAvailable() {+ t.Skip("no GPU custom-kernel backend available")+ }+}+// 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@@ -19,6 +30,27 @@ func patternArray(dtype DType, shape []int, bias, scale float32, stride, modulusreturn FromValues(values, shape...).AsType(dtype)}+// Reduction order differs from the graph path, so bf16 y can land one ULP (6.1e-5) away.+const gatedDeltaGraphTol = 2e-4++// requireClose compares two arrays within tol after widening to float32.+// NaN never compares close, so a kernel that produces NaN fails.+func requireClose(label string, got, want *Array, tol float64) 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 diff := math.Abs(float64(gotValues[i] - wantValues[i])); !(diff <= tol) {+ return fmt.Errorf("%s[%d] = %v, want %v (differs by %g, tolerance %g)",+ label, i, gotValues[i], wantValues[i], diff, tol)+ }+ }+ return nil+}+// 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)diff --git a/mlx/mamba2_scan.go b/mlx/mamba2_scan.goindex a52847591..c5b387d57 100644--- a/mlx/mamba2_scan.go+++ b/mlx/mamba2_scan.go@@ -13,6 +13,10 @@ var (source: mamba2ScanMetalSource,header: "#define MAMBA2_STORE_INTERIOR(index, value)\n",},+ cuda: gpuSource{+ source: mamba2ScanCUDASource,+ header: "#define MAMBA2_STORE_INTERIOR(index, value)\n",+ },fallback: func(launch gpuLaunch) []*Array {in := launch.inputsy, end, _ := mamba2ScanGraph(in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7], false)@@ -27,6 +31,10 @@ var (source: mamba2ScanMetalSource,header: "#define MAMBA2_STORE_INTERIOR(index, value) state_seq[index] = value\n",},+ cuda: gpuSource{+ source: mamba2ScanCUDASource,+ header: "#define MAMBA2_STORE_INTERIOR(index, value) state_seq[index] = value\n",+ },fallback: func(launch gpuLaunch) []*Array {in := launch.inputsy, end, interior := mamba2ScanGraph(in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7], true)@@ -93,6 +101,80 @@ for (int i = 0; i < n_per_t; ++i) {}`+// The CUDA translation of mamba2ScanMetalSource. T arrives as a pointer+// because the CUDA kernel builder passes every input by address, while Metal+// scalarizes zero-dimensional ones.+const mamba2ScanCUDASource = `+int lane = static_cast<int>(threadIdx.x);+int d_idx = static_cast<int>(blockIdx.y * blockDim.y + threadIdx.y);+int bh_idx = static_cast<int>(blockIdx.z);+// Metal dispatches an exact thread count; CUDA rounds the grid up to whole+// blocks, so a D that is not a multiple of blockDim.y leaves a tail here.+// blockDim.x is 32, so a warp never straddles two d_idx values and the+// reduction below still sees all 32 lanes.+if (d_idx >= D) {+ return;+}+int b_idx = bh_idx / H;+int h_idx = bh_idx % H;+// B/C groups repeat across contiguous head blocks.+int g_idx = h_idx / (H / G);+constexpr int n_per_t = S / 32;+constexpr int state_count = B * H * D * S;++int T_val = static_cast<int>(*T);++int state_offset = ((b_idx * H + h_idx) * D + d_idx) * S;+float state[n_per_t];+#pragma unroll+for (int i = 0; i < n_per_t; ++i) {+ int s_idx = n_per_t * lane + i;+ state[i] = static_cast<float>(state_in[state_offset + s_idx]);+}++for (int t = 0; t < T_val; ++t) {+ int bth = (b_idx * T_val + t) * H + h_idx;+ float dt_raw = static_cast<float>(dt[bth]) + static_cast<float>(dt_bias[h_idx]);+ float dt_val = logf(1.0f + expf(dt_raw));+ float decay = expf(dt_val * static_cast<float>(a[h_idx]));+ float x_val = static_cast<float>(hidden[bth * D + d_idx]);++ float out = 0.0f;+ int bs_base = ((b_idx * T_val + t) * G + g_idx) * S;+#pragma unroll+ for (int i = 0; i < n_per_t; ++i) {+ int s_idx = n_per_t * lane + i;+ float b_val = static_cast<float>(b_state[bs_base + s_idx]);+ float c_val = static_cast<float>(c_state[bs_base + s_idx]);+ state[i] = state[i] * decay + x_val * (dt_val * b_val);+ out += state[i] * c_val;+ }++ if (t + 1 < T_val) {+ int seq_offset = t * state_count + state_offset;+#pragma unroll+ for (int i = 0; i < n_per_t; ++i) {+ int s_idx = n_per_t * lane + i;+ MAMBA2_STORE_INTERIOR(seq_offset + s_idx, state[i]);+ }+ }++ // Warp reduction. Only lane 0 stores, so the total need not be broadcast.+ for (int offset = 16; offset > 0; offset >>= 1) {+ out += __shfl_down_sync(0xffffffff, out, offset);+ }+ if (lane == 0) {+ y[bth * D + d_idx] = out + x_val * static_cast<float>(d[h_idx]);+ }+}++#pragma unroll+for (int i = 0; i < n_per_t; ++i) {+ int s_idx = n_per_t * lane + i;+ state_out[state_offset + s_idx] = state[i];+}+`+type mamba2ScanDims struct {B, T, H, G, D, S int}diff --git a/mlx/mamba_kernels_test.go b/mlx/mamba_kernels_test.goindex 724bdfce1..5df9a34ad 100644--- a/mlx/mamba_kernels_test.go+++ b/mlx/mamba_kernels_test.go@@ -10,7 +10,7 @@ import (func TestMamba2ScanMatchesReference(t *testing.T) {withMLXThread(t, func(t *mlxthreadtest.T) {- requireMamba2Metal(t)+ requireGPUKernel(t)var failures []errorin := newMamba2TestInputs(1, 3, 2, 2, 2, 32)gotY, gotState, interior := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)@@ -27,7 +27,7 @@ func TestMamba2ScanMatchesReference(t *testing.T) {// Every interior state must match, not just one boundary.func TestMamba2ScanCaptureAllMatchesPerTokenReference(t *testing.T) {withMLXThread(t, func(t *mlxthreadtest.T) {- requireMamba2Metal(t)+ requireGPUKernel(t)var failures []errorconst T = 4in := newMamba2TestInputs(1, T, 2, 2, 2, 32)@@ -58,7 +58,7 @@ func TestMamba2ScanCaptureAllMatchesPerTokenReference(t *testing.T) {func TestMamba2ScanGroupedStatesMatchRepeatedReference(t *testing.T) {withMLXThread(t, func(t *mlxthreadtest.T) {- requireMamba2Metal(t)+ requireGPUKernel(t)var failures []errorin := newMamba2TestInputs(1, 2, 4, 2, 2, 32)gotY, gotState, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)@@ -74,6 +74,25 @@ func TestMamba2ScanGroupedStatesMatchRepeatedReference(t *testing.T) {})}+// The launch sizes the y dimension as D threads in blocks of min(D, 4).+// Metal dispatches exactly D; CUDA rounds up to whole blocks, so a D that is+// not a multiple of the block height leaves a tail of threads addressing rows+// past the end. D of 5, 6 and 7 leave tails of 3, 2 and 1; D of 8 leaves none.+func TestMamba2ScanHeadDimTailMatchesReference(t *testing.T) {+ withMLXThread(t, func(t *mlxthreadtest.T) {+ requireGPUKernel(t)+ var failures []error+ for _, D := range []int{5, 6, 7, 8} {+ in := newMamba2TestInputs(1, 3, 2, 2, D, 32)+ gotY, gotState, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)+ wantY, wantState := mamba2ScanReference(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias)+ failures = appendArrayCloseError(failures, fmt.Sprintf("D=%d y", D), gotY, wantY, 1e-5)+ failures = appendArrayCloseError(failures, fmt.Sprintf("D=%d state", D), gotState, wantState, 1e-5)+ }+ reportMamba2Failures(t, failures)+ })+}+// A shape outside the kernel's contract must still compute the right answer// through the graph implementation rather than fail.func TestMamba2ScanUnsupportedShapeMatchesGraph(t *testing.T) {@@ -95,7 +114,7 @@ func TestMamba2ScanUnsupportedShapeMatchesGraph(t *testing.T) {// the state by exp(dt*a).func TestMamba2ScanPaddedRowIsIdentity(t *testing.T) {withMLXThread(t, func(t *mlxthreadtest.T) {- requireMamba2Metal(t)+ requireGPUKernel(t)var failures []errorconst (B = 2@@ -189,13 +208,6 @@ func onesTest(dtype DType, shape ...int) *Array {return AddScalar(Zeros(dtype, shape...), 1)}-func requireMamba2Metal(t *mlxthreadtest.T) {- t.Helper()- if !MetalIsAvailable() {- t.Skip("MLX Metal not available")- }-}-func appendArrayCloseError(failures []error, name string, got, want *Array, tol float64) []error {Eval(got, want)gotF := got.Floats()