From 59770d6013c6d0a885937074d4e5c84587cd0f37 Mon Sep 17 00:00:00 2001 From: Nataliya Kosmyna Date: Sun, 23 Nov 2025 20:45:27 -0500 Subject: [PATCH 1/4] Added MLXCustomFunction + MLXClosure --- Package.swift | 13 +- Source/Examples/CustomFunctionExample.swift | 311 ++++++++++++++++++ .../CustomFunctionExampleSimple.swift | 153 +++++++++ Source/MLX/MLXClosure.swift | 41 +++ Source/MLX/MLXCustomFunction.swift | 119 +++++++ 5 files changed, 636 insertions(+), 1 deletion(-) create mode 100644 Source/Examples/CustomFunctionExample.swift create mode 100644 Source/Examples/CustomFunctionExampleSimple.swift create mode 100644 Source/MLX/MLXClosure.swift create mode 100644 Source/MLX/MLXCustomFunction.swift diff --git a/Package.swift b/Package.swift index 49c39b2be..cb3624e5a 100644 --- a/Package.swift +++ b/Package.swift @@ -232,7 +232,18 @@ let package = Package( path: "Source/Examples", sources: ["Tutorial.swift"] ), - + .executableTarget( + name: "CustomFunctionExample", + dependencies: ["MLX"], + path: "Source/Examples", + sources: ["CustomFunctionExample.swift"] + ), + .executableTarget( + name: "CustomFunctionExampleSimple", + dependencies: ["MLX"], + path: "Source/Examples", + sources: ["CustomFunctionExampleSimple.swift"] + ), ], cxxLanguageStandard: .gnucxx17 ) diff --git a/Source/Examples/CustomFunctionExample.swift b/Source/Examples/CustomFunctionExample.swift new file mode 100644 index 000000000..1f4b40d1c --- /dev/null +++ b/Source/Examples/CustomFunctionExample.swift @@ -0,0 +1,311 @@ +import Foundation +import MLX + +@main +struct GridSampleExample { + static func main() throws { + // ----------------------------- + // Forward kernel: bilinear grid_sample + // ----------------------------- + let forwardSource = """ + uint elem = thread_position_in_grid.x; + + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + int gH = grid_shape[1]; + int gW = grid_shape[2]; + + int w_stride = C; + int h_stride = W * w_stride; + int b_stride = H * h_stride; + + // Properly decode batch/channel/grid indices + int c = elem % C; + int w = (elem / C) % gW; + int h = (elem / (C * gW)) % gH; + int b = elem / (C * gW * gH); + + if (b >= B) return; + + uint grid_idx = ((b * gH + h) * gW + w) * 2; + float ix = ((grid[grid_idx] + 1) * (W - 1)) / 2.0; + float iy = ((grid[grid_idx + 1] + 1) * (H - 1)) / 2.0; + + int ix_nw = floor(ix); + int iy_nw = floor(iy); + + int ix_ne = ix_nw + 1; + int iy_ne = iy_nw; + int ix_sw = ix_nw; + int iy_sw = iy_nw + 1; + int ix_se = ix_nw + 1; + int iy_se = iy_nw + 1; + + float nw = (ix_se - ix) * (iy_se - iy); + float ne = (ix - ix_sw) * (iy_sw - iy); + float sw = (ix_ne - ix) * (iy - iy_ne); + float se = (ix - ix_nw) * (iy - iy_nw); + + int base_idx = b * b_stride + c; + float I_nw = 0.0; + float I_ne = 0.0; + float I_sw = 0.0; + float I_se = 0.0; + + if (iy_nw >= 0 && iy_nw < H && ix_nw >= 0 && ix_nw < W) + I_nw = x[base_idx + iy_nw * h_stride + ix_nw * w_stride]; + if (iy_ne >= 0 && iy_ne < H && ix_ne >= 0 && ix_ne < W) + I_ne = x[base_idx + iy_ne * h_stride + ix_ne * w_stride]; + if (iy_sw >= 0 && iy_sw < H && ix_sw >= 0 && ix_sw < W) + I_sw = x[base_idx + iy_sw * h_stride + ix_sw * w_stride]; + if (iy_se >= 0 && iy_se < H && ix_se >= 0 && ix_se < W) + I_se = x[base_idx + iy_se * h_stride + ix_se * w_stride]; + + int out_idx = ((b * gH + h) * gW + w) * C + c; + out[out_idx] = nw * I_nw + ne * I_ne + sw * I_sw + se * I_se; + """ + + let forwardKernel = MLXFast.metalKernel( + name: "grid_sample_forward", + inputNames: ["x", "grid"], + outputNames: ["out"], + source: forwardSource + ) + + // ----------------------------- + // Backward kernel: VJP + // ----------------------------- + let vjpSource = """ + uint elem = thread_position_in_grid.x; + + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + int gH = grid_shape[1]; + int gW = grid_shape[2]; + + int w_stride = C; + int h_stride = W * w_stride; + int b_stride = H * h_stride; + + int c = elem % C; + int w = (elem / C) % gW; + int h = (elem / (C * gW)) % gH; + int b = elem / (C * gW * gH); + + if (b >= B) return; + + uint grid_idx = ((b * gH + h) * gW + w) * 2; + float ix = ((grid[grid_idx] + 1) * (W - 1)) / 2.0; + float iy = ((grid[grid_idx + 1] + 1) * (H - 1)) / 2.0; + + int ix_nw = floor(ix); + int iy_nw = floor(iy); + int ix_ne = ix_nw + 1; + int iy_ne = iy_nw; + int ix_sw = ix_nw; + int iy_sw = iy_nw + 1; + int ix_se = ix_nw + 1; + int iy_se = iy_nw + 1; + + float dx = ix - ix_nw; + float dy = iy - iy_nw; + + float nw = (1 - dx) * (1 - dy); + float ne = dx * (1 - dy); + float sw = (1 - dx) * dy; + float se = dx * dy; + + int base_idx = b * b_stride + c; + + // ------------------------- + // Accumulate x_grad + // ------------------------- + if (iy_nw >= 0 && iy_nw < H && ix_nw >= 0 && ix_nw < W) + atomic_fetch_add_explicit(&x_grad[base_idx + iy_nw * h_stride + ix_nw * w_stride], nw, memory_order_relaxed); + if (iy_ne >= 0 && iy_ne < H && ix_ne >= 0 && ix_ne < W) + atomic_fetch_add_explicit(&x_grad[base_idx + iy_ne * h_stride + ix_ne * w_stride], ne, memory_order_relaxed); + if (iy_sw >= 0 && iy_sw < H && ix_sw >= 0 && ix_sw < W) + atomic_fetch_add_explicit(&x_grad[base_idx + iy_sw * h_stride + ix_sw * w_stride], sw, memory_order_relaxed); + if (iy_se >= 0 && iy_se < H && ix_se >= 0 && ix_se < W) + atomic_fetch_add_explicit(&x_grad[base_idx + iy_se * h_stride + ix_se * w_stride], se, memory_order_relaxed); + + // ------------------------- + // Compute grid_grad (∂L/∂grid) + // ------------------------- + float gix = 0.0; + float giy = 0.0; + + if (iy_nw >= 0 && iy_nw < H && ix_nw >= 0 && ix_nw < W) { + float val = x[base_idx + iy_nw * h_stride + ix_nw * w_stride]; + gix += -(1 - dy) * val; + giy += -(1 - dx) * val; + } + if (iy_ne >= 0 && iy_ne < H && ix_ne >= 0 && ix_ne < W) { + float val = x[base_idx + iy_ne * h_stride + ix_ne * w_stride]; + gix += (1 - dy) * val; + giy += -dx * val; + } + if (iy_sw >= 0 && iy_sw < H && ix_sw >= 0 && ix_sw < W) { + float val = x[base_idx + iy_sw * h_stride + ix_sw * w_stride]; + gix += -dy * val; + giy += (1 - dx) * val; + } + if (iy_se >= 0 && iy_se < H && ix_se >= 0 && ix_se < W) { + float val = x[base_idx + iy_se * h_stride + ix_se * w_stride]; + gix += dy * val; + giy += dx * val; + } + + // Normalize to [-1,1] coordinates + gix *= 2.0 / float(W - 1); + giy *= 2.0 / float(H - 1); + + atomic_fetch_add_explicit(&grid_grad[grid_idx], gix, memory_order_relaxed); + atomic_fetch_add_explicit(&grid_grad[grid_idx + 1], giy, memory_order_relaxed); + """ + + let vjpKernel = MLXFast.metalKernel( + name: "grid_sample_vjp", + inputNames: ["x", "grid", "cotangent"], + outputNames: ["x_grad", "grid_grad"], + source: vjpSource, + atomicOutputs: true + ) + + // ----------------------------- + // Custom MLX function + // ----------------------------- + let gridSample: MLXClosure = { + @MLXCustomFunctionBuilder + var f: MLXClosure { + Forward { inputs in + let x = inputs[0] + let grid = inputs[1] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the forward pass + let startTime = Date() + let result = forwardKernel( + [x, grid], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Forward pass time: \(elapsedTime) seconds") + + return result + } + + VJP { primals, cotangents in + let x = primals[0] + let grid = primals[1] + let cot = cotangents[0] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the backward pass + let startTime = Date() + let result = vjpKernel( + [x, grid, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape, grid.shape], + outputDTypes: [x.dtype, grid.dtype], + initValue: 0 + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Backward pass time: \(elapsedTime) seconds") + + return result + } + } + return f + }() + + // ----------------------------- + // Example input + // ----------------------------- + let x = MLXArray(stride(from: Float(1), through: 16, by: 1), [1, 4, 4, 1]) + let grid = MLXArray(stride(from: Float(-1), through: 1, by: 0.5), [1, 5, 1, 1]) + + print("x:", x) + print("grid:", grid) + + // https://github.com/ml-explore/mlx/discussions/842#discussioncomment-8835095 + // The output of the model needs to be a scalar + func fn(_ x: MLXArray) -> MLXArray { + let y = try! MLXClosure.apply(gridSample, [x, grid])[0] + let result = MLX.sum(y) + + print("y:", y) + print("result:", result) + + return result + } + + let gradFn = grad(fn) + let dfdx = gradFn(x) + print("df/dx:", dfdx) + + // ----------------------------- + // Numerical check + // ----------------------------- + let eps: Float = 1e-3 + let xPerturbed = x + xPerturbed[0, 1, 1, 0] += eps + let f1 = fn(xPerturbed).item(Float.self) + xPerturbed[0, 1, 1, 0] -= 2 * eps + let f2 = fn(xPerturbed).item(Float.self) + let numericGrad = (f1 - f2) / (2 * eps) + print("numeric grad @ (1,1):", numericGrad) + print("autodiff grad @ (1,1):", dfdx[0, 1, 1, 0]) + } +} + +/* +## gives following output: + + x: array([[[[1],[2],[3],[4]], + [[5],[6],[7],[8]], + [[9],[10],[11],[12]], + [[13],[14],[15],[16]]]], dtype=float32) + grid: array([[[[-1]], + [[-0.5]], + [[0]], + [[0.5]], + [[1]]]], dtype=float32) + Forward pass time: 9.298324584960938e-05 seconds + y: + array([[[[4],[11.5],[10],[8.5]], + [[8.5],[0],[0],[0]], + [[0],[0],[0],[0]], + [[0],[0],[0],[0]]]], dtype=float32) + result: array(42.5, dtype=float32) + Backward pass time: 2.9087066650390625e-05 seconds + df/dx: array([[[[0.25],[0],[0],[0]], + [[0.75],[0.5],[0.5],[0.5]], + [[0],[0.875],[0.875],[0.5]], + [[0],[0.125],[0.125],[0]]]], dtype=float32) + Forward pass time: 1.800060272216797e-05 seconds + y: array([[[[4],[11.5],[10],[8.50025]], + [[8.50025],[0],[0],[0]], + [[0],[0],[0],[0]], + [[0],[0],[0],[0]]]], dtype=float32) + result: array(42.5005, dtype=float32) + Forward pass time: 1.5974044799804688e-05 seconds + y: array([[[[4],[11.5],[10],[8.49975]], + [[8.49975],[0],[0],[0]], + [[0],[0],[0],[0]], + [[0],[0],[0],[0]]]], dtype=float32) + result: array(42.4995, dtype=float32) + numeric grad @ (1,1): 0.50354004 + autodiff grad @ (1,1): array(0.5, dtype=float32) + Program ended with exit code: 0 +*/ diff --git a/Source/Examples/CustomFunctionExampleSimple.swift b/Source/Examples/CustomFunctionExampleSimple.swift new file mode 100644 index 000000000..cc85c35db --- /dev/null +++ b/Source/Examples/CustomFunctionExampleSimple.swift @@ -0,0 +1,153 @@ +import Foundation +import MLX + +@main +struct SimpleAddExample { + static func main() throws { + // ----------------------------- + // Forward kernel: Adding a constant + // ----------------------------- + let forwardSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = b * H * W * C + c; + out[base_idx] = x[base_idx] + 1.0f; // Add a constant (1.0f) to each element (use Float32) + """ + + let forwardKernel = MLXFast.metalKernel( + name: "add_constant_forward", + inputNames: ["x"], + outputNames: ["out"], + source: forwardSource + ) + + // ----------------------------- + // Backward kernel: Derivative of adding a constant + // ----------------------------- + let vjpSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = b * H * W * C + c; + x_grad[base_idx] = cotangent[base_idx]; // Derivative of x + 1 is 1, so we just pass the cotangent + """ + + let vjpKernel = MLXFast.metalKernel( + name: "add_constant_vjp", + inputNames: ["x", "cotangent"], + outputNames: ["x_grad"], + source: vjpSource + ) + + // ----------------------------- + // Custom MLX function + // ----------------------------- + let addConstantFunction: MLXClosure = { + @MLXCustomFunctionBuilder + var f: MLXClosure { + Forward { inputs in + let x = inputs[0] + let totalElems = x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3] + + let result = forwardKernel( + [x], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + + return result + } + + VJP { primals, cotangents in + let x = primals[0] + let cot = cotangents[0] + let totalElems = x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3] + + let result = vjpKernel( + [x, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype], + initValue: 0 + ) + + return result + } + } + return f + }() + + // ----------------------------- + // Example input + // ----------------------------- + let data: [Float32] = [1.0, 2.0, 3.0] // ensure Float32, as Float64 is not supported + let x = MLXArray(data, [1, 3, 1, 1]) + print("x:", x) + + // https://github.com/ml-explore/mlx/discussions/842#discussioncomment-8835095 + // The output of the model needs to be a scalar + func fn(_ x: MLXArray) -> MLXArray { + let y = try! MLXClosure.apply(addConstantFunction, [x])[0] + let result = MLX.sum(y) + print("y:", y) + print("result:", result) + return result + } + + let gradFn = grad(fn) + let dfdx = gradFn(x) + print("df/dx:", dfdx) + + // ----------------------------- + // Numerical check + // ----------------------------- + let eps: Float = 1e-3 + let xPerturbed = x + xPerturbed[0, 0, 0, 0] += eps + let f1 = fn(xPerturbed).item(Float.self) + xPerturbed[0, 0, 0, 0] -= 2 * eps + let f2 = fn(xPerturbed).item(Float.self) + let numericGrad = (f1 - f2) / (2 * eps) + print("numeric grad @ (0,0):", numericGrad) + print("autodiff grad @ (0,0):", dfdx[0, 0, 0, 0]) + } +} + +/* +## gives following output: + + x: array([[[[1]],[[2]],[[3]]]], dtype=float32) + y: array([[[[2]],[[0]],[[0]]]], dtype=float32) + result: array(2, dtype=float32) + df/dx: array([[[[1]],[[0]],[[0]]]], dtype=float32) + y: array([[[[2.001]],[[0]],[[0]]]], dtype=float32) + result: array(2.001, dtype=float32) + y: array([[[[1.999]],[[0]],[[0]]]], dtype=float32) + result: array(1.999, dtype=float32) + numeric grad @ (0,0): 0.99992746 + autodiff grad @ (0,0): array(1, dtype=float32) +*/ diff --git a/Source/MLX/MLXClosure.swift b/Source/MLX/MLXClosure.swift new file mode 100644 index 000000000..73d5a7d07 --- /dev/null +++ b/Source/MLX/MLXClosure.swift @@ -0,0 +1,41 @@ +import Cmlx +import Foundation + +// MARK: - MLXClosure wrapper +public struct MLXClosure { + public var c: mlx_closure + public init(_ c: mlx_closure) { self.c = c } + + /// Apply closure to a Swift array of MLXArray and return output arrays + public static func apply(_ closure: MLXClosure, _ inputs: [MLXArray]) throws -> [MLXArray] { + // Create a C mlx_vector_array and append input arrays + let inputVec = mlx_vector_array_new() + for arr in inputs { + mlx_vector_array_append_value(inputVec, arr.ctx) + } + + // Prepare output vector + var outputVec = mlx_vector_array_new() + + // Call C API + let status = mlx_closure_apply(&outputVec, closure.c, inputVec) + guard status == 0 else { + throw MLXError.caught("Failed to apply MLXClosure: \(status)") + } + + // Convert output mlx_vector_array to [MLXArray] + let count = mlx_vector_array_size(outputVec) + var result: [MLXArray] = [] + for i in 0 ..< count { + var arr = mlx_array() + mlx_vector_array_get(&arr, outputVec, i) + result.append(MLXArray(arr)) + } + + // Free the C vectors if needed + mlx_vector_array_free(inputVec) + mlx_vector_array_free(outputVec) + + return result + } +} diff --git a/Source/MLX/MLXCustomFunction.swift b/Source/MLX/MLXCustomFunction.swift new file mode 100644 index 000000000..98229a1a0 --- /dev/null +++ b/Source/MLX/MLXCustomFunction.swift @@ -0,0 +1,119 @@ +import Cmlx +import Foundation + +// MARK: - Custom Function Component +public enum MLXCustomFunctionComponent { + case forward(([MLXArray]) -> [MLXArray]) + case vjp(([MLXArray], [MLXArray]) -> [MLXArray]) +} + +// MARK: - DSL Builders +public func Forward(_ f: @escaping ([MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent { + .forward(f) +} + +public func VJP(_ f: @escaping ([MLXArray], [MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent +{ + .vjp(f) +} + +// MARK: - Result Builder +@resultBuilder +public enum MLXCustomFunctionBuilder { + public static func buildBlock(_ components: MLXCustomFunctionComponent...) -> MLXClosure { + var forwardFn: (([MLXArray]) -> [MLXArray])? + var vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? + + for component in components { + switch component { + case .forward(let f): forwardFn = f + case .vjp(let f): vjpFn = f + } + } + + guard let fwd = forwardFn else { + fatalError("MLXCustomFunction must have a Forward block") + } + + // Wrap Swift forward closure -> mlx_closure + let forwardClosure = mlx_closure_new_func_payload( + { out, inputs, payload in + let swiftFn = + Unmanaged.fromOpaque(payload!).takeUnretainedValue() + as! ([MLXArray]) -> [MLXArray] + let inArrays = withUnsafePointer(to: inputs) { + mlx_vector_array_to_swift($0) + } + let result = swiftFn(inArrays) + out!.pointee = swift_to_mlx_vector_array(result) + return 0 + }, Unmanaged.passRetained(fwd as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + + var resultClosure = mlx_closure_new() + + if let vjp = vjpFn { + // Wrap Swift vjp closure -> mlx_closure_custom + let vjpClosure = mlx_closure_custom_new_func_payload( + { out, primals, cotangents, _, payload in + let swiftFn = + Unmanaged.fromOpaque(payload!).takeUnretainedValue() + as! ([MLXArray], [MLXArray]) -> [MLXArray] + let p = withUnsafePointer(to: primals) { + mlx_vector_array_to_swift($0) + } + let c = withUnsafePointer(to: cotangents) { + mlx_vector_array_to_swift($0) + } + let grads = swiftFn(p, c) + out!.pointee = swift_to_mlx_vector_array(grads) + return 0 + }, Unmanaged.passRetained(vjp as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + + // empty closures + let jvpClosure = mlx_closure_custom_jvp_new() + let vmapClosure = mlx_closure_custom_vmap_new() + + _ = mlx_custom_function( + &resultClosure, forwardClosure, vjpClosure, jvpClosure, vmapClosure) + } else { + // empty closures + let vjpClosure = mlx_closure_custom_new() + let jvpClosure = mlx_closure_custom_jvp_new() + let vmapClosure = mlx_closure_custom_vmap_new() + + _ = mlx_custom_function( + &resultClosure, forwardClosure, vjpClosure, jvpClosure, vmapClosure) + } + + return MLXClosure(resultClosure) + } +} + +// MARK: - Example: bridging helpers +// Convert a C mlx_vector_array pointer to a Swift array of MLXArray +func mlx_vector_array_to_swift(_ v: UnsafePointer?) -> [MLXArray] { + guard let v = v else { return [] } + var result: [MLXArray] = [] + + // Get size from C API + let size = mlx_vector_array_size(v.pointee) + for i in 0 ..< size { + var cArray = mlx_array() // placeholder for the individual mlx_array + mlx_vector_array_get(&cArray, v.pointee, i) + result.append(MLXArray(cArray)) + } + + return result +} + +// Convert Swift array of MLXArray back to C mlx_vector_array +func swift_to_mlx_vector_array(_ arrays: [MLXArray]) -> mlx_vector_array { + var cArrays: [mlx_array] = arrays.map { $0.ctx } + return mlx_vector_array_new_data(&cArrays, cArrays.count) +} From 7bc90187d3d1f89a0915d575fba94440fd8af1ab Mon Sep 17 00:00:00 2001 From: nataliyakosmyna Date: Tue, 25 Nov 2025 22:39:59 -0500 Subject: [PATCH 2/4] Moved to mlx_vector_array_values and new_mlx_vector_array and simplified customFunction --- Source/Examples/CustomFunctionExample.swift | 118 ++++---- .../CustomFunctionExampleSimple.swift | 275 +++++++++--------- Source/MLX/MLXClosure.swift | 41 --- Source/MLX/MLXCustomFunction.swift | 241 ++++++++------- 4 files changed, 336 insertions(+), 339 deletions(-) delete mode 100644 Source/MLX/MLXClosure.swift diff --git a/Source/Examples/CustomFunctionExample.swift b/Source/Examples/CustomFunctionExample.swift index 1f4b40d1c..dd37ede6b 100644 --- a/Source/Examples/CustomFunctionExample.swift +++ b/Source/Examples/CustomFunctionExample.swift @@ -179,55 +179,51 @@ struct GridSampleExample { // ----------------------------- // Custom MLX function // ----------------------------- - let gridSample: MLXClosure = { - @MLXCustomFunctionBuilder - var f: MLXClosure { - Forward { inputs in - let x = inputs[0] - let grid = inputs[1] - let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] - - // Timing the forward pass - let startTime = Date() - let result = forwardKernel( - [x, grid], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype] - ) - - let elapsedTime = Date().timeIntervalSince(startTime) - print("Forward pass time: \(elapsedTime) seconds") - - return result - } - - VJP { primals, cotangents in - let x = primals[0] - let grid = primals[1] - let cot = cotangents[0] - let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] - - // Timing the backward pass - let startTime = Date() - let result = vjpKernel( - [x, grid, cot], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape, grid.shape], - outputDTypes: [x.dtype, grid.dtype], - initValue: 0 - ) - - let elapsedTime = Date().timeIntervalSince(startTime) - print("Backward pass time: \(elapsedTime) seconds") - - return result - } - } - return f - }() + let gridSample = CustomFunction { + Forward { inputs in + let x = inputs[0] + let grid = inputs[1] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the forward pass + let startTime = Date() + let result = forwardKernel( + [x, grid], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Forward pass time: \(elapsedTime) seconds") + + return result + } + + VJP { primals, cotangents in + let x = primals[0] + let grid = primals[1] + let cot = cotangents[0] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the backward pass + let startTime = Date() + let result = vjpKernel( + [x, grid, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape, grid.shape], + outputDTypes: [x.dtype, grid.dtype], + initValue: 0 + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Backward pass time: \(elapsedTime) seconds") + + return result + } + } // ----------------------------- // Example input @@ -241,7 +237,7 @@ struct GridSampleExample { // https://github.com/ml-explore/mlx/discussions/842#discussioncomment-8835095 // The output of the model needs to be a scalar func fn(_ x: MLXArray) -> MLXArray { - let y = try! MLXClosure.apply(gridSample, [x, grid])[0] + let y = gridSample([x, grid])[0] let result = MLX.sum(y) print("y:", y) @@ -270,36 +266,31 @@ struct GridSampleExample { } /* -## gives following output: - + ## gives following output: + x: array([[[[1],[2],[3],[4]], [[5],[6],[7],[8]], [[9],[10],[11],[12]], [[13],[14],[15],[16]]]], dtype=float32) - grid: array([[[[-1]], - [[-0.5]], - [[0]], - [[0.5]], - [[1]]]], dtype=float32) - Forward pass time: 9.298324584960938e-05 seconds - y: - array([[[[4],[11.5],[10],[8.5]], + grid: array([[[[-1]],[[-0.5]],[[0]],[[0.5]],[[1]]]], dtype=float32) + Forward pass time: 7.796287536621094e-05 seconds + y: array([[[[4],[11.5],[10],[8.5]], [[8.5],[0],[0],[0]], [[0],[0],[0],[0]], [[0],[0],[0],[0]]]], dtype=float32) result: array(42.5, dtype=float32) - Backward pass time: 2.9087066650390625e-05 seconds + Backward pass time: 4.303455352783203e-05 seconds df/dx: array([[[[0.25],[0],[0],[0]], [[0.75],[0.5],[0.5],[0.5]], [[0],[0.875],[0.875],[0.5]], [[0],[0.125],[0.125],[0]]]], dtype=float32) - Forward pass time: 1.800060272216797e-05 seconds + Forward pass time: 1.4066696166992188e-05 seconds y: array([[[[4],[11.5],[10],[8.50025]], [[8.50025],[0],[0],[0]], [[0],[0],[0],[0]], [[0],[0],[0],[0]]]], dtype=float32) result: array(42.5005, dtype=float32) - Forward pass time: 1.5974044799804688e-05 seconds + Forward pass time: 1.0967254638671875e-05 seconds y: array([[[[4],[11.5],[10],[8.49975]], [[8.49975],[0],[0],[0]], [[0],[0],[0],[0]], @@ -308,4 +299,5 @@ struct GridSampleExample { numeric grad @ (1,1): 0.50354004 autodiff grad @ (1,1): array(0.5, dtype=float32) Program ended with exit code: 0 + */ diff --git a/Source/Examples/CustomFunctionExampleSimple.swift b/Source/Examples/CustomFunctionExampleSimple.swift index cc85c35db..fdb97643f 100644 --- a/Source/Examples/CustomFunctionExampleSimple.swift +++ b/Source/Examples/CustomFunctionExampleSimple.swift @@ -3,140 +3,139 @@ import MLX @main struct SimpleAddExample { - static func main() throws { - // ----------------------------- - // Forward kernel: Adding a constant - // ----------------------------- - let forwardSource = """ - uint elem = thread_position_in_grid.x; - int B = x_shape[0]; - int H = x_shape[1]; - int W = x_shape[2]; - int C = x_shape[3]; - - int c = elem % C; - int w = (elem / C) % W; - int h = (elem / (C * W)) % H; - int b = elem / (C * W * H); - - if (b >= B) return; - - int base_idx = b * H * W * C + c; - out[base_idx] = x[base_idx] + 1.0f; // Add a constant (1.0f) to each element (use Float32) - """ - - let forwardKernel = MLXFast.metalKernel( - name: "add_constant_forward", - inputNames: ["x"], - outputNames: ["out"], - source: forwardSource - ) - - // ----------------------------- - // Backward kernel: Derivative of adding a constant - // ----------------------------- - let vjpSource = """ - uint elem = thread_position_in_grid.x; - int B = x_shape[0]; - int H = x_shape[1]; - int W = x_shape[2]; - int C = x_shape[3]; - - int c = elem % C; - int w = (elem / C) % W; - int h = (elem / (C * W)) % H; - int b = elem / (C * W * H); - - if (b >= B) return; - - int base_idx = b * H * W * C + c; - x_grad[base_idx] = cotangent[base_idx]; // Derivative of x + 1 is 1, so we just pass the cotangent - """ - - let vjpKernel = MLXFast.metalKernel( - name: "add_constant_vjp", - inputNames: ["x", "cotangent"], - outputNames: ["x_grad"], - source: vjpSource - ) - - // ----------------------------- - // Custom MLX function - // ----------------------------- - let addConstantFunction: MLXClosure = { - @MLXCustomFunctionBuilder - var f: MLXClosure { - Forward { inputs in - let x = inputs[0] - let totalElems = x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3] - - let result = forwardKernel( - [x], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype] - ) - - return result - } - - VJP { primals, cotangents in - let x = primals[0] - let cot = cotangents[0] - let totalElems = x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3] - - let result = vjpKernel( - [x, cot], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype], - initValue: 0 - ) - - return result - } - } - return f - }() - - // ----------------------------- - // Example input - // ----------------------------- - let data: [Float32] = [1.0, 2.0, 3.0] // ensure Float32, as Float64 is not supported - let x = MLXArray(data, [1, 3, 1, 1]) - print("x:", x) - - // https://github.com/ml-explore/mlx/discussions/842#discussioncomment-8835095 - // The output of the model needs to be a scalar - func fn(_ x: MLXArray) -> MLXArray { - let y = try! MLXClosure.apply(addConstantFunction, [x])[0] - let result = MLX.sum(y) - print("y:", y) - print("result:", result) - return result - } - - let gradFn = grad(fn) - let dfdx = gradFn(x) - print("df/dx:", dfdx) - - // ----------------------------- - // Numerical check - // ----------------------------- - let eps: Float = 1e-3 - let xPerturbed = x - xPerturbed[0, 0, 0, 0] += eps - let f1 = fn(xPerturbed).item(Float.self) - xPerturbed[0, 0, 0, 0] -= 2 * eps - let f2 = fn(xPerturbed).item(Float.self) - let numericGrad = (f1 - f2) / (2 * eps) - print("numeric grad @ (0,0):", numericGrad) - print("autodiff grad @ (0,0):", dfdx[0, 0, 0, 0]) - } + static func main() throws { + + // ----------------------------- + // Forward Metal kernel + // ----------------------------- + let forwardSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = ((b * H + h) * W + w) * C + c; + + out[base_idx] = x[base_idx] + 1.0f; + """ + + let forwardKernel = MLXFast.metalKernel( + name: "add_constant_forward", + inputNames: ["x"], + outputNames: ["out"], + source: forwardSource + ) + + // ----------------------------- + // VJP Metal kernel + // ----------------------------- + let vjpSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = b * H * W * C + c; + x_grad[base_idx] = cotangent[base_idx]; + """ + + let vjpKernel = MLXFast.metalKernel( + name: "add_constant_vjp", + inputNames: ["x", "cotangent"], + outputNames: ["x_grad"], + source: vjpSource + ) + + // ----------------------------- + // Your new API: CustomFunction {} + // ----------------------------- + let addConstant = CustomFunction { + Forward { inputs in + let x = inputs[0] + let totalElems = x.shape.reduce(1, *) + + return forwardKernel( + [x], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + } + + VJP { primals, cotangents in + let x = primals[0] + let cot = cotangents[0] + let totalElems = x.shape.reduce(1, *) + + return vjpKernel( + [x, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype], + initValue: 0 + ) + } + } + + // ----------------------------- + // Example input + // ----------------------------- + let data: [Float32] = [1, 2, 3] + let x = MLXArray(data, [1, 3, 1, 1]) + print("x:", x) + + // ----------------------------- + // Scalar-valued function + // ----------------------------- + func fn(_ x: MLXArray) -> MLXArray { + let y = addConstant([x])[0] + print("y:", y) + let result = MLX.sum(y) + print("result:", result) + return result + } + + let gradFn = grad(fn) + let dfdx = gradFn(x) + print("df/dx:", dfdx) + + // ----------------------------- + // Numerical derivative check + // ----------------------------- + let eps: Float = 1e-3 + + let xp = x + xp[0,0,0,0] += eps + let f1 = fn(xp).item(Float.self) + + xp[0,0,0,0] -= 2 * eps + let f2 = fn(xp).item(Float.self) + + let numeric = (f1 - f2) / (2 * eps) + print("numeric grad @ (0,0):", numeric) + print("autodiff grad @ (0,0):", dfdx[0,0,0,0]) + } } + /* ## gives following output: @@ -150,4 +149,16 @@ struct SimpleAddExample { result: array(1.999, dtype=float32) numeric grad @ (0,0): 0.99992746 autodiff grad @ (0,0): array(1, dtype=float32) + + x: array([[[[1]],[[2]],[[3]]]], dtype=float32) + y: array([[[[2]],[[3]],[[4]]]], dtype=float32) + result: array(9, dtype=float32) + df/dx: array([[[[1]],[[0]],[[0]]]], dtype=float32) + y: array([[[[2.001]],[[3]],[[4]]]], dtype=float32) + result: array(9.001, dtype=float32) + y: array([[[[1.999]],[[3]],[[4]]]], dtype=float32) + result: array(8.999, dtype=float32) + numeric grad @ (0,0): 0.9994506 + autodiff grad @ (0,0): array(1, dtype=float32) + Program ended with exit code: 0 */ diff --git a/Source/MLX/MLXClosure.swift b/Source/MLX/MLXClosure.swift deleted file mode 100644 index 73d5a7d07..000000000 --- a/Source/MLX/MLXClosure.swift +++ /dev/null @@ -1,41 +0,0 @@ -import Cmlx -import Foundation - -// MARK: - MLXClosure wrapper -public struct MLXClosure { - public var c: mlx_closure - public init(_ c: mlx_closure) { self.c = c } - - /// Apply closure to a Swift array of MLXArray and return output arrays - public static func apply(_ closure: MLXClosure, _ inputs: [MLXArray]) throws -> [MLXArray] { - // Create a C mlx_vector_array and append input arrays - let inputVec = mlx_vector_array_new() - for arr in inputs { - mlx_vector_array_append_value(inputVec, arr.ctx) - } - - // Prepare output vector - var outputVec = mlx_vector_array_new() - - // Call C API - let status = mlx_closure_apply(&outputVec, closure.c, inputVec) - guard status == 0 else { - throw MLXError.caught("Failed to apply MLXClosure: \(status)") - } - - // Convert output mlx_vector_array to [MLXArray] - let count = mlx_vector_array_size(outputVec) - var result: [MLXArray] = [] - for i in 0 ..< count { - var arr = mlx_array() - mlx_vector_array_get(&arr, outputVec, i) - result.append(MLXArray(arr)) - } - - // Free the C vectors if needed - mlx_vector_array_free(inputVec) - mlx_vector_array_free(outputVec) - - return result - } -} diff --git a/Source/MLX/MLXCustomFunction.swift b/Source/MLX/MLXCustomFunction.swift index 98229a1a0..9b3c4ef0e 100644 --- a/Source/MLX/MLXCustomFunction.swift +++ b/Source/MLX/MLXCustomFunction.swift @@ -1,119 +1,154 @@ import Cmlx import Foundation -// MARK: - Custom Function Component public enum MLXCustomFunctionComponent { - case forward(([MLXArray]) -> [MLXArray]) - case vjp(([MLXArray], [MLXArray]) -> [MLXArray]) + case forward(([MLXArray]) -> [MLXArray]) + case vjp(([MLXArray], [MLXArray]) -> [MLXArray]) } -// MARK: - DSL Builders public func Forward(_ f: @escaping ([MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent { - .forward(f) + .forward(f) } -public func VJP(_ f: @escaping ([MLXArray], [MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent -{ - .vjp(f) +public func VJP(_ f: @escaping ([MLXArray], [MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent { + .vjp(f) } -// MARK: - Result Builder -@resultBuilder -public enum MLXCustomFunctionBuilder { - public static func buildBlock(_ components: MLXCustomFunctionComponent...) -> MLXClosure { - var forwardFn: (([MLXArray]) -> [MLXArray])? - var vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? - - for component in components { - switch component { - case .forward(let f): forwardFn = f - case .vjp(let f): vjpFn = f - } - } - - guard let fwd = forwardFn else { - fatalError("MLXCustomFunction must have a Forward block") - } - - // Wrap Swift forward closure -> mlx_closure - let forwardClosure = mlx_closure_new_func_payload( - { out, inputs, payload in - let swiftFn = - Unmanaged.fromOpaque(payload!).takeUnretainedValue() - as! ([MLXArray]) -> [MLXArray] - let inArrays = withUnsafePointer(to: inputs) { - mlx_vector_array_to_swift($0) - } - let result = swiftFn(inArrays) - out!.pointee = swift_to_mlx_vector_array(result) - return 0 - }, Unmanaged.passRetained(fwd as AnyObject).toOpaque() - ) { ptr in - Unmanaged.fromOpaque(ptr!).release() - } - - var resultClosure = mlx_closure_new() - - if let vjp = vjpFn { - // Wrap Swift vjp closure -> mlx_closure_custom - let vjpClosure = mlx_closure_custom_new_func_payload( - { out, primals, cotangents, _, payload in - let swiftFn = - Unmanaged.fromOpaque(payload!).takeUnretainedValue() - as! ([MLXArray], [MLXArray]) -> [MLXArray] - let p = withUnsafePointer(to: primals) { - mlx_vector_array_to_swift($0) - } - let c = withUnsafePointer(to: cotangents) { - mlx_vector_array_to_swift($0) - } - let grads = swiftFn(p, c) - out!.pointee = swift_to_mlx_vector_array(grads) - return 0 - }, Unmanaged.passRetained(vjp as AnyObject).toOpaque() - ) { ptr in - Unmanaged.fromOpaque(ptr!).release() - } - - // empty closures - let jvpClosure = mlx_closure_custom_jvp_new() - let vmapClosure = mlx_closure_custom_vmap_new() - - _ = mlx_custom_function( - &resultClosure, forwardClosure, vjpClosure, jvpClosure, vmapClosure) - } else { - // empty closures - let vjpClosure = mlx_closure_custom_new() - let jvpClosure = mlx_closure_custom_jvp_new() - let vmapClosure = mlx_closure_custom_vmap_new() - - _ = mlx_custom_function( - &resultClosure, forwardClosure, vjpClosure, jvpClosure, vmapClosure) - } - - return MLXClosure(resultClosure) - } +final class _CustomFunctionState: @unchecked Sendable { + + private let lock = NSLock() + + private let forwardFn: ([MLXArray]) -> [MLXArray] + private let vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? + + private var forwardClosure: mlx_closure! + private var vjpClosure: mlx_closure_custom! + private var jvpClosure: mlx_closure_custom_jvp! + private var vmapClosure: mlx_closure_custom_vmap! + private var combined: mlx_closure! + + init( + forward: @escaping ([MLXArray]) -> [MLXArray], + vjp: (([MLXArray], [MLXArray]) -> [MLXArray])? + ) { + self.forwardFn = forward + self.vjpFn = vjp + buildClosures() + } + + deinit { + mlx_closure_free(forwardClosure) + mlx_closure_custom_free(vjpClosure) + mlx_closure_custom_jvp_free(jvpClosure) + mlx_closure_custom_vmap_free(vmapClosure) + mlx_closure_free(combined) + } + + private func buildClosures() { + + // --- FORWARD --- + forwardClosure = mlx_closure_new_func_payload( + { out, inputs, payload in + let swiftFn = Unmanaged + .fromOpaque(payload!) + .takeUnretainedValue() + as! ([MLXArray]) -> [MLXArray] + + let inp = mlx_vector_array_values(inputs) + let result = swiftFn(inp) + out!.pointee = new_mlx_vector_array(result) + return 0 + }, + Unmanaged.passRetained(forwardFn as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + + // --- VJP --- + if let vjpFn = vjpFn { + vjpClosure = mlx_closure_custom_new_func_payload( + { out, primals, cotangents, _, payload in + let fn = Unmanaged + .fromOpaque(payload!) + .takeUnretainedValue() + as! ([MLXArray], [MLXArray]) -> [MLXArray] + + let p = mlx_vector_array_values(primals) + let c = mlx_vector_array_values(cotangents) + out!.pointee = new_mlx_vector_array(fn(p, c)) + return 0 + }, + Unmanaged.passRetained(vjpFn as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + } else { + vjpClosure = mlx_closure_custom_new() + } + + // --- JVP + VMAP --- + jvpClosure = mlx_closure_custom_jvp_new() + vmapClosure = mlx_closure_custom_vmap_new() + + // --- COMBINED --- + combined = mlx_closure_new() + _ = mlx_custom_function( + &combined, + forwardClosure, + vjpClosure, + jvpClosure, + vmapClosure + ) + } + + func call(_ inputs: [MLXArray]) -> [MLXArray] { + lock.withLock { + let inVec = new_mlx_vector_array(inputs) + defer { mlx_vector_array_free(inVec) } + + var outVec = mlx_vector_array_new() + defer { mlx_vector_array_free(outVec) } + + let status = mlx_closure_apply(&outVec, combined, inVec) + precondition(status == 0, "mlx_closure_apply failed (\(status))") + + return mlx_vector_array_values(outVec) + } + } } -// MARK: - Example: bridging helpers -// Convert a C mlx_vector_array pointer to a Swift array of MLXArray -func mlx_vector_array_to_swift(_ v: UnsafePointer?) -> [MLXArray] { - guard let v = v else { return [] } - var result: [MLXArray] = [] - - // Get size from C API - let size = mlx_vector_array_size(v.pointee) - for i in 0 ..< size { - var cArray = mlx_array() // placeholder for the individual mlx_array - mlx_vector_array_get(&cArray, v.pointee, i) - result.append(MLXArray(cArray)) - } - - return result +public enum MLXCustomFunctionBuilder { + @resultBuilder + public struct Builder { + + public static func buildBlock( + _ components: MLXCustomFunctionComponent... + ) -> ([MLXArray]) -> [MLXArray] { + + var forwardFn: (([MLXArray]) -> [MLXArray])? + var vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? + + for c in components { + switch c { + case .forward(let f): forwardFn = f + case .vjp(let f): vjpFn = f + } + } + + guard let f = forwardFn else { + fatalError("CustomFunction must contain a Forward block") + } + + let state = _CustomFunctionState(forward: f, vjp: vjpFn) + + // EXACT match to compile(): return a Swift function that calls state.call + return { arrays in state.call(arrays) } + } + } } -// Convert Swift array of MLXArray back to C mlx_vector_array -func swift_to_mlx_vector_array(_ arrays: [MLXArray]) -> mlx_vector_array { - var cArrays: [mlx_array] = arrays.map { $0.ctx } - return mlx_vector_array_new_data(&cArrays, cArrays.count) +public func CustomFunction( + @MLXCustomFunctionBuilder.Builder _ build: () -> ([MLXArray]) -> [MLXArray] +) -> ([MLXArray]) -> [MLXArray] { + build() } From 4b33e73cbd19991e855ae38542245a0035ed1b93 Mon Sep 17 00:00:00 2001 From: nataliyakosmyna Date: Tue, 25 Nov 2025 23:44:23 -0500 Subject: [PATCH 3/4] formatting --- Source/Examples/CustomFunctionExample.swift | 92 +++--- .../CustomFunctionExampleSimple.swift | 263 +++++++++--------- Source/MLX/MLXCustomFunction.swift | 257 ++++++++--------- 3 files changed, 307 insertions(+), 305 deletions(-) diff --git a/Source/Examples/CustomFunctionExample.swift b/Source/Examples/CustomFunctionExample.swift index dd37ede6b..d35b3e07a 100644 --- a/Source/Examples/CustomFunctionExample.swift +++ b/Source/Examples/CustomFunctionExample.swift @@ -180,50 +180,50 @@ struct GridSampleExample { // Custom MLX function // ----------------------------- let gridSample = CustomFunction { - Forward { inputs in - let x = inputs[0] - let grid = inputs[1] - let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] - - // Timing the forward pass - let startTime = Date() - let result = forwardKernel( - [x, grid], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype] - ) - - let elapsedTime = Date().timeIntervalSince(startTime) - print("Forward pass time: \(elapsedTime) seconds") - - return result - } - - VJP { primals, cotangents in - let x = primals[0] - let grid = primals[1] - let cot = cotangents[0] - let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] - - // Timing the backward pass - let startTime = Date() - let result = vjpKernel( - [x, grid, cot], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape, grid.shape], - outputDTypes: [x.dtype, grid.dtype], - initValue: 0 - ) - - let elapsedTime = Date().timeIntervalSince(startTime) - print("Backward pass time: \(elapsedTime) seconds") - - return result - } - } + Forward { inputs in + let x = inputs[0] + let grid = inputs[1] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the forward pass + let startTime = Date() + let result = forwardKernel( + [x, grid], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Forward pass time: \(elapsedTime) seconds") + + return result + } + + VJP { primals, cotangents in + let x = primals[0] + let grid = primals[1] + let cot = cotangents[0] + let totalElems = x.shape[0] * grid.shape[1] * grid.shape[2] * x.shape[3] + + // Timing the backward pass + let startTime = Date() + let result = vjpKernel( + [x, grid, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape, grid.shape], + outputDTypes: [x.dtype, grid.dtype], + initValue: 0 + ) + + let elapsedTime = Date().timeIntervalSince(startTime) + print("Backward pass time: \(elapsedTime) seconds") + + return result + } + } // ----------------------------- // Example input @@ -267,7 +267,7 @@ struct GridSampleExample { /* ## gives following output: - + x: array([[[[1],[2],[3],[4]], [[5],[6],[7],[8]], [[9],[10],[11],[12]], @@ -299,5 +299,5 @@ struct GridSampleExample { numeric grad @ (1,1): 0.50354004 autodiff grad @ (1,1): array(0.5, dtype=float32) Program ended with exit code: 0 - + */ diff --git a/Source/Examples/CustomFunctionExampleSimple.swift b/Source/Examples/CustomFunctionExampleSimple.swift index fdb97643f..0c7087320 100644 --- a/Source/Examples/CustomFunctionExampleSimple.swift +++ b/Source/Examples/CustomFunctionExampleSimple.swift @@ -3,139 +3,138 @@ import MLX @main struct SimpleAddExample { - static func main() throws { - - // ----------------------------- - // Forward Metal kernel - // ----------------------------- - let forwardSource = """ - uint elem = thread_position_in_grid.x; - int B = x_shape[0]; - int H = x_shape[1]; - int W = x_shape[2]; - int C = x_shape[3]; - - int c = elem % C; - int w = (elem / C) % W; - int h = (elem / (C * W)) % H; - int b = elem / (C * W * H); - - if (b >= B) return; - - int base_idx = ((b * H + h) * W + w) * C + c; - - out[base_idx] = x[base_idx] + 1.0f; - """ - - let forwardKernel = MLXFast.metalKernel( - name: "add_constant_forward", - inputNames: ["x"], - outputNames: ["out"], - source: forwardSource - ) - - // ----------------------------- - // VJP Metal kernel - // ----------------------------- - let vjpSource = """ - uint elem = thread_position_in_grid.x; - int B = x_shape[0]; - int H = x_shape[1]; - int W = x_shape[2]; - int C = x_shape[3]; - - int c = elem % C; - int w = (elem / C) % W; - int h = (elem / (C * W)) % H; - int b = elem / (C * W * H); - - if (b >= B) return; - - int base_idx = b * H * W * C + c; - x_grad[base_idx] = cotangent[base_idx]; - """ - - let vjpKernel = MLXFast.metalKernel( - name: "add_constant_vjp", - inputNames: ["x", "cotangent"], - outputNames: ["x_grad"], - source: vjpSource - ) - - // ----------------------------- - // Your new API: CustomFunction {} - // ----------------------------- - let addConstant = CustomFunction { - Forward { inputs in - let x = inputs[0] - let totalElems = x.shape.reduce(1, *) - - return forwardKernel( - [x], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype] - ) - } - - VJP { primals, cotangents in - let x = primals[0] - let cot = cotangents[0] - let totalElems = x.shape.reduce(1, *) - - return vjpKernel( - [x, cot], - grid: (totalElems, 1, 1), - threadGroup: (32, 1, 1), - outputShapes: [x.shape], - outputDTypes: [x.dtype], - initValue: 0 - ) - } - } - - // ----------------------------- - // Example input - // ----------------------------- - let data: [Float32] = [1, 2, 3] - let x = MLXArray(data, [1, 3, 1, 1]) - print("x:", x) - - // ----------------------------- - // Scalar-valued function - // ----------------------------- - func fn(_ x: MLXArray) -> MLXArray { - let y = addConstant([x])[0] - print("y:", y) - let result = MLX.sum(y) - print("result:", result) - return result - } - - let gradFn = grad(fn) - let dfdx = gradFn(x) - print("df/dx:", dfdx) - - // ----------------------------- - // Numerical derivative check - // ----------------------------- - let eps: Float = 1e-3 - - let xp = x - xp[0,0,0,0] += eps - let f1 = fn(xp).item(Float.self) - - xp[0,0,0,0] -= 2 * eps - let f2 = fn(xp).item(Float.self) - - let numeric = (f1 - f2) / (2 * eps) - print("numeric grad @ (0,0):", numeric) - print("autodiff grad @ (0,0):", dfdx[0,0,0,0]) - } + static func main() throws { + + // ----------------------------- + // Forward Metal kernel + // ----------------------------- + let forwardSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = ((b * H + h) * W + w) * C + c; + + out[base_idx] = x[base_idx] + 1.0f; + """ + + let forwardKernel = MLXFast.metalKernel( + name: "add_constant_forward", + inputNames: ["x"], + outputNames: ["out"], + source: forwardSource + ) + + // ----------------------------- + // VJP Metal kernel + // ----------------------------- + let vjpSource = """ + uint elem = thread_position_in_grid.x; + int B = x_shape[0]; + int H = x_shape[1]; + int W = x_shape[2]; + int C = x_shape[3]; + + int c = elem % C; + int w = (elem / C) % W; + int h = (elem / (C * W)) % H; + int b = elem / (C * W * H); + + if (b >= B) return; + + int base_idx = b * H * W * C + c; + x_grad[base_idx] = cotangent[base_idx]; + """ + + let vjpKernel = MLXFast.metalKernel( + name: "add_constant_vjp", + inputNames: ["x", "cotangent"], + outputNames: ["x_grad"], + source: vjpSource + ) + + // ----------------------------- + // Your new API: CustomFunction {} + // ----------------------------- + let addConstant = CustomFunction { + Forward { inputs in + let x = inputs[0] + let totalElems = x.shape.reduce(1, *) + + return forwardKernel( + [x], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype] + ) + } + + VJP { primals, cotangents in + let x = primals[0] + let cot = cotangents[0] + let totalElems = x.shape.reduce(1, *) + + return vjpKernel( + [x, cot], + grid: (totalElems, 1, 1), + threadGroup: (32, 1, 1), + outputShapes: [x.shape], + outputDTypes: [x.dtype], + initValue: 0 + ) + } + } + + // ----------------------------- + // Example input + // ----------------------------- + let data: [Float32] = [1, 2, 3] + let x = MLXArray(data, [1, 3, 1, 1]) + print("x:", x) + + // ----------------------------- + // Scalar-valued function + // ----------------------------- + func fn(_ x: MLXArray) -> MLXArray { + let y = addConstant([x])[0] + print("y:", y) + let result = MLX.sum(y) + print("result:", result) + return result + } + + let gradFn = grad(fn) + let dfdx = gradFn(x) + print("df/dx:", dfdx) + + // ----------------------------- + // Numerical derivative check + // ----------------------------- + let eps: Float = 1e-3 + + let xp = x + xp[0, 0, 0, 0] += eps + let f1 = fn(xp).item(Float.self) + + xp[0, 0, 0, 0] -= 2 * eps + let f2 = fn(xp).item(Float.self) + + let numeric = (f1 - f2) / (2 * eps) + print("numeric grad @ (0,0):", numeric) + print("autodiff grad @ (0,0):", dfdx[0, 0, 0, 0]) + } } - /* ## gives following output: @@ -149,7 +148,7 @@ struct SimpleAddExample { result: array(1.999, dtype=float32) numeric grad @ (0,0): 0.99992746 autodiff grad @ (0,0): array(1, dtype=float32) - + x: array([[[[1]],[[2]],[[3]]]], dtype=float32) y: array([[[[2]],[[3]],[[4]]]], dtype=float32) result: array(9, dtype=float32) diff --git a/Source/MLX/MLXCustomFunction.swift b/Source/MLX/MLXCustomFunction.swift index 9b3c4ef0e..c2279513d 100644 --- a/Source/MLX/MLXCustomFunction.swift +++ b/Source/MLX/MLXCustomFunction.swift @@ -2,153 +2,156 @@ import Cmlx import Foundation public enum MLXCustomFunctionComponent { - case forward(([MLXArray]) -> [MLXArray]) - case vjp(([MLXArray], [MLXArray]) -> [MLXArray]) + case forward(([MLXArray]) -> [MLXArray]) + case vjp(([MLXArray], [MLXArray]) -> [MLXArray]) } public func Forward(_ f: @escaping ([MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent { - .forward(f) + .forward(f) } -public func VJP(_ f: @escaping ([MLXArray], [MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent { - .vjp(f) +public func VJP(_ f: @escaping ([MLXArray], [MLXArray]) -> [MLXArray]) -> MLXCustomFunctionComponent +{ + .vjp(f) } final class _CustomFunctionState: @unchecked Sendable { - private let lock = NSLock() - - private let forwardFn: ([MLXArray]) -> [MLXArray] - private let vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? - - private var forwardClosure: mlx_closure! - private var vjpClosure: mlx_closure_custom! - private var jvpClosure: mlx_closure_custom_jvp! - private var vmapClosure: mlx_closure_custom_vmap! - private var combined: mlx_closure! - - init( - forward: @escaping ([MLXArray]) -> [MLXArray], - vjp: (([MLXArray], [MLXArray]) -> [MLXArray])? - ) { - self.forwardFn = forward - self.vjpFn = vjp - buildClosures() - } - - deinit { - mlx_closure_free(forwardClosure) - mlx_closure_custom_free(vjpClosure) - mlx_closure_custom_jvp_free(jvpClosure) - mlx_closure_custom_vmap_free(vmapClosure) - mlx_closure_free(combined) - } - - private func buildClosures() { - - // --- FORWARD --- - forwardClosure = mlx_closure_new_func_payload( - { out, inputs, payload in - let swiftFn = Unmanaged - .fromOpaque(payload!) - .takeUnretainedValue() - as! ([MLXArray]) -> [MLXArray] - - let inp = mlx_vector_array_values(inputs) - let result = swiftFn(inp) - out!.pointee = new_mlx_vector_array(result) - return 0 - }, - Unmanaged.passRetained(forwardFn as AnyObject).toOpaque() - ) { ptr in - Unmanaged.fromOpaque(ptr!).release() - } - - // --- VJP --- - if let vjpFn = vjpFn { - vjpClosure = mlx_closure_custom_new_func_payload( - { out, primals, cotangents, _, payload in - let fn = Unmanaged - .fromOpaque(payload!) - .takeUnretainedValue() - as! ([MLXArray], [MLXArray]) -> [MLXArray] - - let p = mlx_vector_array_values(primals) - let c = mlx_vector_array_values(cotangents) - out!.pointee = new_mlx_vector_array(fn(p, c)) - return 0 - }, - Unmanaged.passRetained(vjpFn as AnyObject).toOpaque() - ) { ptr in - Unmanaged.fromOpaque(ptr!).release() - } - } else { - vjpClosure = mlx_closure_custom_new() - } - - // --- JVP + VMAP --- - jvpClosure = mlx_closure_custom_jvp_new() - vmapClosure = mlx_closure_custom_vmap_new() - - // --- COMBINED --- - combined = mlx_closure_new() - _ = mlx_custom_function( - &combined, - forwardClosure, - vjpClosure, - jvpClosure, - vmapClosure - ) - } - - func call(_ inputs: [MLXArray]) -> [MLXArray] { - lock.withLock { - let inVec = new_mlx_vector_array(inputs) - defer { mlx_vector_array_free(inVec) } - - var outVec = mlx_vector_array_new() - defer { mlx_vector_array_free(outVec) } - - let status = mlx_closure_apply(&outVec, combined, inVec) - precondition(status == 0, "mlx_closure_apply failed (\(status))") - - return mlx_vector_array_values(outVec) - } - } + private let lock = NSLock() + + private let forwardFn: ([MLXArray]) -> [MLXArray] + private let vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? + + private var forwardClosure: mlx_closure! + private var vjpClosure: mlx_closure_custom! + private var jvpClosure: mlx_closure_custom_jvp! + private var vmapClosure: mlx_closure_custom_vmap! + private var combined: mlx_closure! + + init( + forward: @escaping ([MLXArray]) -> [MLXArray], + vjp: (([MLXArray], [MLXArray]) -> [MLXArray])? + ) { + self.forwardFn = forward + self.vjpFn = vjp + buildClosures() + } + + deinit { + mlx_closure_free(forwardClosure) + mlx_closure_custom_free(vjpClosure) + mlx_closure_custom_jvp_free(jvpClosure) + mlx_closure_custom_vmap_free(vmapClosure) + mlx_closure_free(combined) + } + + private func buildClosures() { + + // --- FORWARD --- + forwardClosure = mlx_closure_new_func_payload( + { out, inputs, payload in + let swiftFn = + Unmanaged + .fromOpaque(payload!) + .takeUnretainedValue() + as! ([MLXArray]) -> [MLXArray] + + let inp = mlx_vector_array_values(inputs) + let result = swiftFn(inp) + out!.pointee = new_mlx_vector_array(result) + return 0 + }, + Unmanaged.passRetained(forwardFn as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + + // --- VJP --- + if let vjpFn = vjpFn { + vjpClosure = mlx_closure_custom_new_func_payload( + { out, primals, cotangents, _, payload in + let fn = + Unmanaged + .fromOpaque(payload!) + .takeUnretainedValue() + as! ([MLXArray], [MLXArray]) -> [MLXArray] + + let p = mlx_vector_array_values(primals) + let c = mlx_vector_array_values(cotangents) + out!.pointee = new_mlx_vector_array(fn(p, c)) + return 0 + }, + Unmanaged.passRetained(vjpFn as AnyObject).toOpaque() + ) { ptr in + Unmanaged.fromOpaque(ptr!).release() + } + } else { + vjpClosure = mlx_closure_custom_new() + } + + // --- JVP + VMAP --- + jvpClosure = mlx_closure_custom_jvp_new() + vmapClosure = mlx_closure_custom_vmap_new() + + // --- COMBINED --- + combined = mlx_closure_new() + _ = mlx_custom_function( + &combined, + forwardClosure, + vjpClosure, + jvpClosure, + vmapClosure + ) + } + + func call(_ inputs: [MLXArray]) -> [MLXArray] { + lock.withLock { + let inVec = new_mlx_vector_array(inputs) + defer { mlx_vector_array_free(inVec) } + + var outVec = mlx_vector_array_new() + defer { mlx_vector_array_free(outVec) } + + let status = mlx_closure_apply(&outVec, combined, inVec) + precondition(status == 0, "mlx_closure_apply failed (\(status))") + + return mlx_vector_array_values(outVec) + } + } } public enum MLXCustomFunctionBuilder { - @resultBuilder - public struct Builder { + @resultBuilder + public struct Builder { - public static func buildBlock( - _ components: MLXCustomFunctionComponent... - ) -> ([MLXArray]) -> [MLXArray] { + public static func buildBlock( + _ components: MLXCustomFunctionComponent... + ) -> ([MLXArray]) -> [MLXArray] { - var forwardFn: (([MLXArray]) -> [MLXArray])? - var vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? + var forwardFn: (([MLXArray]) -> [MLXArray])? + var vjpFn: (([MLXArray], [MLXArray]) -> [MLXArray])? - for c in components { - switch c { - case .forward(let f): forwardFn = f - case .vjp(let f): vjpFn = f - } - } + for c in components { + switch c { + case .forward(let f): forwardFn = f + case .vjp(let f): vjpFn = f + } + } - guard let f = forwardFn else { - fatalError("CustomFunction must contain a Forward block") - } + guard let f = forwardFn else { + fatalError("CustomFunction must contain a Forward block") + } - let state = _CustomFunctionState(forward: f, vjp: vjpFn) + let state = _CustomFunctionState(forward: f, vjp: vjpFn) - // EXACT match to compile(): return a Swift function that calls state.call - return { arrays in state.call(arrays) } - } - } + // EXACT match to compile(): return a Swift function that calls state.call + return { arrays in state.call(arrays) } + } + } } public func CustomFunction( - @MLXCustomFunctionBuilder.Builder _ build: () -> ([MLXArray]) -> [MLXArray] + @MLXCustomFunctionBuilder.Builder _ build: () -> ([MLXArray]) -> [MLXArray] ) -> ([MLXArray]) -> [MLXArray] { - build() + build() } From 8ebfb1974efa508189e172e9b43515648a4d2436 Mon Sep 17 00:00:00 2001 From: nataliyakosmyna Date: Wed, 26 Nov 2025 04:59:03 -0500 Subject: [PATCH 4/4] cleaned comments --- Source/Examples/CustomFunctionExampleSimple.swift | 2 +- Source/MLX/MLXCustomFunction.swift | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/Source/Examples/CustomFunctionExampleSimple.swift b/Source/Examples/CustomFunctionExampleSimple.swift index 0c7087320..c7ec32f83 100644 --- a/Source/Examples/CustomFunctionExampleSimple.swift +++ b/Source/Examples/CustomFunctionExampleSimple.swift @@ -63,7 +63,7 @@ struct SimpleAddExample { ) // ----------------------------- - // Your new API: CustomFunction {} + // Custom MLX function // ----------------------------- let addConstant = CustomFunction { Forward { inputs in diff --git a/Source/MLX/MLXCustomFunction.swift b/Source/MLX/MLXCustomFunction.swift index c2279513d..63eb66091 100644 --- a/Source/MLX/MLXCustomFunction.swift +++ b/Source/MLX/MLXCustomFunction.swift @@ -47,7 +47,6 @@ final class _CustomFunctionState: @unchecked Sendable { private func buildClosures() { - // --- FORWARD --- forwardClosure = mlx_closure_new_func_payload( { out, inputs, payload in let swiftFn = @@ -66,7 +65,6 @@ final class _CustomFunctionState: @unchecked Sendable { Unmanaged.fromOpaque(ptr!).release() } - // --- VJP --- if let vjpFn = vjpFn { vjpClosure = mlx_closure_custom_new_func_payload( { out, primals, cotangents, _, payload in @@ -89,11 +87,9 @@ final class _CustomFunctionState: @unchecked Sendable { vjpClosure = mlx_closure_custom_new() } - // --- JVP + VMAP --- jvpClosure = mlx_closure_custom_jvp_new() vmapClosure = mlx_closure_custom_vmap_new() - // --- COMBINED --- combined = mlx_closure_new() _ = mlx_custom_function( &combined, @@ -144,7 +140,6 @@ public enum MLXCustomFunctionBuilder { let state = _CustomFunctionState(forward: f, vjp: vjpFn) - // EXACT match to compile(): return a Swift function that calls state.call return { arrays in state.call(arrays) } } }