End-to-end zero-cgo Go demonstration of compiling and executing a neural network natively on Apple Silicon via Metal 4's MTL4MachineLearningCommandEncoder, MTL4MachineLearningPipelineState, and MTLTensor APIs (github.com/tmc/apple/x/metal4).
What it does
- Synthesizes a 2-layer ReLU MLP (
y = linear(relu(linear(x, W1, b1)), W2, b2), default [16, 128] -> [16, 256] -> [16, 128], float32) in pure Go as a Core ML MLProgram .mlpackage using github.com/tmc/apple/x/coremlcompiler.
- Packages for Metal 4 via
metal4.BuildMLPackage (xcrun metal-package-builder -ml), producing a .mtlpackage containing library.mpsgraphpackage and manifest.json.
- Compiles the ML pipeline via
CommandContext.NewMLPipelineFromURL (MTLDevice.NewLibraryWithURLError + MTL4Compiler.NewMachineLearningPipelineStateWithDescriptorError), requesting binding reflection (MTL4ShaderReflectionBindingInfo) and automatically sizing and registering the private intermediates MTLHeap (IntermediatesHeapSize()).
- Executes through
MTL4MachineLearningCommandEncoder using resident MTLTensor inputs/outputs (MTLTensorUsageMachineLearning | MTLTensorUsageCompute) bound via MTL4ArgumentTable.SetResourceAtBufferIndex.
- Verifies 3-way numerical parity against a float64 CPU reference and a Metal 4 compute-shader reference (
MTL4ComputeCommandEncoder + DispatchBarrier).
- Benchmarks latency (
encode, mean, p50, p95, p99 in µs/step) for both synchronous (CommitAndWait) and triple-buffered pipelined (RingDepth=3) loops, plus MTL4CommandAllocator memory stability across 200 resets.
MTLDevice.NewLibraryWithURLError rejects raw .mlpackage directories (Invalid library file (unexpected end of file)).
- It accepts
.mtlpackage directories created by xcrun metal-package-builder -ml <in.mlpackage> -o <out.mtlpackage> (which emit library.mpsgraphpackage/{manifest.plist,model_0.mpsgraph,reflection.fb} and manifest.json).
- Metal's
MTLTensorExtents stores the innermost (contiguous) dimension at index 0, whereas Core ML / Go row-major tensors store the outermost dimension first. x/metal4.Tensor and x/metal4.MLPipeline convert automatically in both directions.
- Buffer-backed
MTLTensor views with MTLTensorUsageMachineLearning and rank >= 2 require strides[1] aligned to 64 bytes; x/metal4.NewTensor handles this automatically when TensorOptions{BufferBacked: true} is set.
Running
CGO_ENABLED=0 go run ./examples/metal/metal4-ml-network
CGO_ENABLED=0 go test -v -count=1 ./examples/metal/metal4-ml-network
Flags:
-batch (default 16): batch size
-in (default 128): input feature dimension
-hidden (default 256): hidden layer dimension
-out (default 128): output feature dimension
-steps (default 200): measured steps
-warmup (default 20): warmup steps
Live Measurements
Captured on Apple M4 Max running macOS Version 26.6.2 (Build 25G83) with CGO_ENABLED=0 go run ./examples/metal/metal4-ml-network:
=== Metal 4 ML Network Demo ===
macOS: Version 26.6.2 (Build 25G83)
GPU: Apple M4 Max (unified=true)
Metal 4 Ready: true (Tensor=true, MLEncoder=true)
=== Compiled 2-Layer ReLU MLP ([16,128] -> [16,256] -> [16,128]) ===
.mlpackage -> .mtlpackage: 1.241s
MTL4Compiler ML PSO: 747ms
IntermediatesHeapSize: 64 bytes
Binding[0]: name="x" access=MTLBindingAccessReadOnly dtype=MTLTensorDataTypeFloat32 shape=[16 128]
Binding[1]: name="y" access=MTLBindingAccessWriteOnly dtype=MTLTensorDataTypeFloat32 shape=[16 128]
=== Numerical Parity ===
Metal 4 ML vs CPU: max_abs=2.794e-07 rms=9.214e-08
Metal 4 Compute vs CPU: max_abs=3.576e-07 rms=1.055e-07
Metal 4 ML vs Compute: max_abs=3.874e-07 rms=6.689e-08
=== Inference Latency Benchmark (N=200 steps, warmup=20) ===
Path encode mean p50 p95 p99
Metal 4 Compute Ref (sync) 70.7µs 701.6µs 193.7µs 3104.9µs 5944.3µs
Metal 4 ML Encoder (sync) 77.7µs 792.9µs 563.4µs 1395.2µs 6862.3µs
Metal 4 Compute Ref (ring=3) 82.9µs 220.3µs 55.9µs 636.0µs 2509.2µs
Metal 4 ML Encoder (ring=3) 79.4µs 413.9µs 208.4µs 1364.5µs 2671.4µs
Summary:
Sync p50 ratio (Compute/ML): 0.34x
Pipelined mean ratio (Compute/ML): 0.53x
MTL4CommandAllocator size (ML sync): before=57968 B, after=57968 B (delta=0 B over 200 resets)