"""Custom Metal kernels (mx.fast.metal_kernel) for the YOLO11n port: the ops where MLX's built-ins are slow on the M2 Pro GPU. Every kernel accumulates in fp32 and stores T (fp16). - bias_silu: SiLU(conv + bias) [+ residual] epilogue in one pass (MLX's sigmoid runs ~3x below bandwidth). - direct_conv3: 3x3 conv for tiny channel counts (MLX's implicit GEMM wastes most of its tile there), with the bias, SiLU and residual fused; also reads the uint8 image directly for the first layer (/255 fused). - dwconv3: depthwise 3x3 conv (stride 1) with bias and optional SiLU fused. """ import mlx.core as mx _BIAS_SILU_SRC = """ uint i = thread_position_in_grid.x; if (i >= N) return; float v = float(x[i]) + float(b[i % C]); v = v / (1.0f + metal::exp(-v)); o[i] = T(OUT); """ _bias_silu = mx.fast.metal_kernel(name="bias_silu", input_names=["x", "b"], output_names=["o"], source=_BIAS_SILU_SRC.replace("OUT", "v")) _bias_silu_res = mx.fast.metal_kernel(name="bias_silu_res", input_names=["x", "b", "r"], output_names=["o"], source=_BIAS_SILU_SRC.replace("OUT", "v + float(r[i])")) def bias_silu(y, b, res=None): n = y.size inputs = [y, b] if res is None else [y, b, res] k = _bias_silu if res is None else _bias_silu_res return k(inputs=inputs, template=[("T", y.dtype), ("C", y.shape[-1]), ("N", n)], grid=((n + 255) // 256 * 256, 1, 1), threadgroup=(256, 1, 1), output_shapes=[y.shape], output_dtypes=[y.dtype])[0] # One thread = one output pixel, all CO output channels. x: [B, H, W, CI] (T_in), w: [3, 3, CI, CO] fp32, # b: [CO] fp32, optional r: [B, HO, WO, CO]. Zero padding 1 (in the normalised domain for the uint8 input). _DIRECT_SRC = """ uint ox = thread_position_in_grid.x, oy = thread_position_in_grid.y, bi = thread_position_in_grid.z; if (ox >= WO || oy >= HO) return; const device float4* w4 = (const device float4*)w; float4 acc[CO / 4]; for (int c = 0; c < CO / 4; c++) acc[c] = ((const device float4*)b)[c]; for (int ky = 0; ky < 3; ky++) { int iy = int(oy) * S - 1 + ky; if (iy < 0 || iy >= H) continue; for (int kx = 0; kx < 3; kx++) { int ix = int(ox) * S - 1 + kx; if (ix < 0 || ix >= W) continue; const device auto* px = x + ((size_t(bi) * H + iy) * W + ix) * CI; const device float4* wr = w4 + (ky * 3 + kx) * CI * (CO / 4); for (int ci = 0; ci < CI; ci++) { float v = float(px[ci]) * SCALE; for (int c = 0; c < CO / 4; c++) acc[c] = fma(float4(v), wr[ci * (CO / 4) + c], acc[c]); } } } size_t ob = ((size_t(bi) * HO + oy) * WO + ox) * CO; device vec* o4 = (device vec*)(o + ob); for (int c4 = 0; c4 < CO / 4; c4++) { float4 a = acc[c4]; a = a / (1.0f + metal::exp(-a)); o4[c4] = vec(RES_EXPR); } """ def _direct_kernel(res, u8): src = _DIRECT_SRC.replace("RES_EXPR", "a + float4(((const device vec*)(r + ob))[c4])" if res else "a") src = src.replace("SCALE", "(1.0f / 255.0f)" if u8 else "1.0f") names = ["x", "w", "b"] + (["r"] if res else []) return mx.fast.metal_kernel(name=f"direct_conv3_{int(res)}{int(u8)}", input_names=names, output_names=["o"], source=src) _direct = {(r, u): _direct_kernel(r, u) for r in (False, True) for u in (False, True)} def direct_conv3(x, w, b, stride, out_dtype, res=None): """x [B,H,W,CI] (uint8 -> scaled by 1/255, or float), w [3,3,CI,CO] fp32, b [CO] fp32 -> SiLU(conv) [+ res].""" B, H, W, CI = x.shape CO = w.shape[-1] assert CO % 4 == 0 HO, WO = (H - 1) // stride + 1, (W - 1) // stride + 1 k = _direct[(res is not None, x.dtype == mx.uint8)] inputs = [x, w, b] + ([res] if res is not None else []) return k(inputs=inputs, template=[("T", out_dtype), ("H", H), ("W", W), ("HO", HO), ("WO", WO), ("CI", CI), ("CO", CO), ("S", stride)], grid=(WO, HO, B), threadgroup=(32, 8, 1), output_shapes=[(B, HO, WO, CO)], output_dtypes=[out_dtype])[0] # One thread = one (channel, x, y). x: [B, H, W, C], w: [3, 3, C] fp32, b: [C] fp32. _DW_SRC = """ uint c = thread_position_in_grid.x, ox = thread_position_in_grid.y, z = thread_position_in_grid.z; if (c >= C || ox >= W) return; uint oy = z % H, bi = z / H; float a = b[c]; for (int ky = 0; ky < 3; ky++) { int iy = int(oy) - 1 + ky; if (iy < 0 || iy >= H) continue; for (int kx = 0; kx < 3; kx++) { int ix = int(ox) - 1 + kx; if (ix < 0 || ix >= W) continue; a += float(x[((size_t(bi) * H + iy) * W + ix) * C + c]) * w[(ky * 3 + kx) * C + c]; } } if (ACT) a = a / (1.0f + metal::exp(-a)); o[((size_t(bi) * H + oy) * W + ox) * C + c] = T(a); """ _dw = mx.fast.metal_kernel(name="dwconv3", input_names=["x", "w", "b"], output_names=["o"], source=_DW_SRC) def dwconv3(x, w, b, act): B, H, W, C = x.shape tc = min(C, 64) return _dw(inputs=[x, w, b], template=[("T", x.dtype), ("H", H), ("W", W), ("C", C), ("ACT", bool(act))], grid=(C, W, B * H), threadgroup=(tc, max(1, 256 // tc), 1), output_shapes=[x.shape], output_dtypes=[x.dtype])[0]