Compute Kernels

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A compute kernel is a function that the GPU runs many thousands of times at once, with no triangles, no rasteriser and no framebuffer. The same hardware that shades pixels does arithmetic on buffers and textures: moving particles, culling objects, filtering images, building histograms, evaluating small neural networks. Compute is the part of Metal that looks most like general GPU programming, and the rest of this section leans on it: particles (Particles), post-processing (Image Processing and Metal Performance Shaders), GPU culling (GPU-Driven Rendering and Indirect Command Buffers), tessellation factors and machine learning.

The facts were checked in November 2026. The page documents Metal 4 (the MTL4 types from the 26 OSes) and Metal Shading Language (MSL) 4.x, with the Metal 3 equivalent next to every Metal 4 listing, because a lot of existing code uses it. Compute runs on every Metal GPU; the SIMD-group reduction functions used here need the Apple7 family (A14, M1) or later, which every Metal 4 device is; non-uniform threadgroups need Apple4 (A11) or later. The examples are command-line Swift programs that compile MSL from a source string at run time, so they need no Xcode project: build them with swiftc on macOS 26 or later. Inside the Metal Bookshelf the kernels of this page are the building blocks of the dust particles (stage 8 of the running example), and the grayscale and reduction kernels are small versions of what exposure control and post-processing need. How a compute pass is ordered against render passes is in Synchronization and Barriers. The OpenGL version of this topic is Compute Shaders; the general GPU model is in GPU Architecture Basics.

The execution model: grid, threadgroups, threads

A 12 by 8 thread grid split into 3 by 2 threadgroups of 4 by 4 threads, with one group and one thread highlighted and the formula for the position in the grid
Figure 1. A dispatch is a grid of threadgroups, each a block of threads

A dispatch launches a grid of threads in one, two or three dimensions. Metal divides the grid into threadgroups; every threadgroup has the same number of threads (except possibly the last ones along an edge, see the dispatch section). Threads in one threadgroup run on the same GPU core, can share threadgroup memory and can wait for one another at a threadgroup_barrier. Threads in different threadgroups cannot synchronise inside a dispatch and may run in any order, on any core, at any time.

Inside a threadgroup the hardware groups threads into SIMD-groups (called warps or wavefronts elsewhere): threads that execute the same instruction at the same time on adjacent lanes. A SIMD-group is 32 threads on current Apple GPUs; the compute pipeline state reports it as threadExecutionWidth, and MSL as threads_per_simdgroup. Threads of a SIMD-group can exchange data directly through registers, without memory, using the SIMD-group functions below.

The position of a thread is described by built-in attributes of the kernel arguments. With \( g \) the position in the grid, \( t_g \) the position of its threadgroup, \( S \) the threadgroup size and \( t_l \) the position inside the threadgroup:

\[ g = t_g \cdot S + t_l \]

Attribute Meaning Type

[[thread_position_in_grid]]

\( g \): global index, the usual way to pick the element to process

uint, uint2, uint3 (or ushort)

[[threads_per_grid]]

size of the grid; must have the same type as thread_position_in_grid

as above

[[threadgroup_position_in_grid]]

\( t_g \): index of the threadgroup

uint, uint2, uint3

[[threadgroups_per_grid]]

number of threadgroups

as above

[[thread_position_in_threadgroup]]

\( t_l \): position inside the group

ushort or uint vectors; threads_per_threadgroup must match

[[thread_index_in_threadgroup]]

linear index, 0 up to the group size minus 1

uint (must be uint when the position is a uint type)

[[threads_per_threadgroup]]

actual size of this group (smaller than requested at grid edges with dispatchThreads)

as above

[[dispatch_threads_per_threadgroup]]

the size you asked for at dispatch

as above

[[thread_index_in_simdgroup]], [[threads_per_simdgroup]]

lane number (0 to 31) and SIMD-group size

ushort or uint

[[simdgroup_index_in_threadgroup]], [[simdgroups_per_threadgroup]]

which SIMD-group, and how many

ushort or uint

The types of related attributes must agree (the specification lists the rules): the position and size in the grid have the same type, the position and size in the threadgroup have the same type, and the SIMD-group attributes are ushort or uint. A mismatch is a compile error, not a runtime surprise. Inside a threadgroup, SIMD-groups of a standard compute function are linear and one-dimensional, and the number of SIMD-groups is the thread count divided by the SIMD-group size, rounded up.

Limits

Limit Value Where

Threads per threadgroup

1,024 on Apple4 and later, 512 on Apple2 and Apple3 (theoretical); the real limit of a kernel is pipeline.maxTotalThreadsPerThreadgroup

Feature Set Tables

Threadgroup memory

32 KB on Apple4 and later (16 KB on Apple3, 16,352 bytes on Apple2); the length must be a multiple of 16 bytes

Feature Set Tables

SIMD-group width

pipeline.threadExecutionWidth: query it, do not hard-code it

MTLComputePipelineState

Buffers per kernel

31 entries in the buffer table (the same number of bindings as an MTL4ArgumentTable)

Feature Set Tables

Textures per kernel

96 on Apple4 and Apple5, 128 on Apple6 and later

Feature Set Tables

Inline data with setBytes

4 KB (Metal 3 only; Metal 4 has no setBytes, put small constants in a buffer)

Feature Set Tables

Check the actual maximum of each pipeline: two pipelines on the same device can differ because register use limits occupancy. maxTotalThreadsPerThreadgroup does not change after a pipeline is created.

Writing kernels in MSL

A kernel is a function with the kernel qualifier that returns void. Its arguments are the data it reads and writes plus built-in attributes. Pointers and references carry an address space (see The Metal Shading Language):

Address space Meaning Typical use

device

read-write memory visible to every thread

large buffers: particles, results

constant

read-only, cached, shared by the dispatch

small uniform data, tables

threadgroup

fast memory shared by the threads of one group; undefined at the start of the group

tiles of data, partial sums, scratch

thread

private to one thread; registers and spill

local variables

Textures are arguments with an access qualifier: texture2d<float, access::read>, access::write, access::sample, or access::read_write where the pixel format supports it. A kernel reads with read(uint2), writes with write(value, uint2) and cannot sample with filtering unless the texture is declared access::sample and a sampler is supplied. The Bookshelf kernels are small:

#include <metal_stdlib>
using namespace metal;

// y[i] = a * x[i] + y[i]; one thread per element.
kernel void saxpy(device const float *x [[buffer(0)]],
                  device float       *y [[buffer(1)]],
                  constant float     &a [[buffer(2)]],
                  uint               i  [[thread_position_in_grid]])
{
    y[i] = a * x[i] + y[i];
}

// Convert a texture to grey, one thread per pixel.
kernel void grayscale(texture2d<float, access::read>  src [[texture(0)]],
                      texture2d<float, access::write> dst [[texture(1)]],
                      uint2 gid [[thread_position_in_grid]])
{
    float4 c = src.read(gid);
    float y = dot(c.rgb, float3(0.2126, 0.7152, 0.0722));
    dst.write(float4(y, y, y, c.a), gid);
}

Two attributes shape how a kernel is compiled. [[kernel, max_total_threads_per_threadgroup(256)]] before the function promises the compiler that the kernel is never launched with more than 256 threads per group, which lets it use more registers per thread; the pipeline then reports a maxTotalThreadsPerThreadgroup of at most 256. [[host_name("name")]] gives a function a different name for the Swift side, useful with templated kernels. Function constants (see The Render Pipeline for how they specialise a function) work for kernels as well.

Dispatch: dispatchThreads and dispatchThreadgroups

Two bars for 1,000 elements with threadgroups of 256: dispatchThreadgroups launches four full groups with 24 extra threads; dispatchThreads launches three full groups and one smaller group
Figure 2. The same 1,000 elements with the two dispatch calls

Metal gives two ways to launch the same kernel, on both MTL4ComputeCommandEncoder and the Metal 3 MTLComputeCommandEncoder:

Call You give Behaviour

dispatchThreads(threadsPerGrid:threadsPerThreadgroup:)

the exact number of threads

Metal makes as many full groups as fit and one smaller group per edge; no thread exists outside the grid (Apple4 and later)

dispatchThreadgroups(threadgroupsPerGrid:threadsPerThreadgroup:)

the number of groups

every group is full; you round up, and threads past the data must return early

Prefer dispatchThreads: the kernel is simpler and no thread is wasted. Use dispatchThreadgroups when the algorithm needs exactly one group per piece of work, as the reduction below does, or on hardware without non-uniform groups. With dispatchThreadgroups the kernel must protect itself:

if (gid >= count) { return; }     // one dimension
if (gid.x >= texture.get_width() || gid.y >= texture.get_height()) { return; }   // two dimensions

Do not return early before a threadgroup_barrier that the other threads of the group will reach; guard the memory access instead, as reduce_sum below does.

Both calls have indirect variants that read the dispatch size from a buffer the GPU wrote, such as the result of a culling pass: dispatchThreads(indirectBuffer:) and dispatchThreadgroups(indirectBuffer:threadsPerThreadgroup:) on the Metal 4 encoder (the argument is a GPU address). That is the compute half of GPU-driven rendering.

Choosing a threadgroup size

The simplest rule from Apple’s article: use the SIMD width as the first dimension and the maximum threads per group divided by it as the second.

let width = pipeline.threadExecutionWidth                         // 32
let height = pipeline.maxTotalThreadsPerThreadgroup / width       // 32 when the maximum is 1,024
let group = MTLSize(width: width, height: height, depth: 1)       // 1,024 threads for a 2D image

For one-dimensional work use a multiple of the SIMD width (256 is common). A group size that is not a multiple of the SIMD width leaves lanes idle in the last SIMD-group; MTL4ComputePipelineDescriptor.threadGroupSizeIsMultipleOfThreadExecutionWidth (and the same property of the Metal 3 descriptor) lets the compiler assume it. Bigger groups are not always better: they need all their threads to finish before the group’s memory is released, and a kernel with high register use may only fit 256 threads per group. For 2D image work, square-ish groups keep neighbouring pixels (and cache lines) in one group. Measure with the GPU counters in Xcode rather than guessing.

Encoding a compute pass, step by step

Six panels: compile the pipeline, allocate buffers and make them resident, bind them in an argument table, encode the dispatch, add a barrier if another dispatch reads the result, commit and wait for an event
Figure 3. The six steps of a compute dispatch under Metal 4
  1. Compile. Create an MTL4Compiler once, compile a library from source or load the default one, and make an MTLComputePipelineState from an MTL4ComputePipelineDescriptor.

  2. Allocate. Create buffers and textures; put them in an MTLResidencySet attached to the queue, because Metal 4 does not make resources resident for you.

  3. Bind. Fill an MTL4ArgumentTable with GPU addresses (setAddress(_:index:)) and texture resource IDs (setTexture(_:index:)). Slot numbers match the [[buffer(n)]] and [[texture(n)]] indices.

  4. Encode. In an MTL4ComputeCommandEncoder set the pipeline and the table, then dispatch. One encoder can issue many dispatches, and since it runs them concurrently, any dispatch that reads what a previous one wrote needs a barrier.

  5. Order. barrier(afterEncoderStages: .dispatch, beforeEncoderStages: .dispatch, visibilityOptions: .device) between dependent dispatches, or a queue barrier before a later pass. Details in Synchronization and Barriers.

  6. Submit. queue.commit([commandBuffer], options: nil), then signal an event; a CPU that needs the result waits on a shared event.

The helper below performs all six steps for one-off dispatches (this is a test harness style, it blocks until the GPU finishes). Put it in a file with the examples that follow and build both with swiftc -O ComputeRunner.swift main.swift -o compute.

import Metal

/// A tiny Metal 4 helper that compiles MSL source and runs one compute dispatch at a time.
final class ComputeRunner {
    let device: any MTLDevice
    let queue: any MTL4CommandQueue
    let compiler: any MTL4Compiler
    let allocator: any MTL4CommandAllocator
    let commandBuffer: any MTL4CommandBuffer
    let table: any MTL4ArgumentTable
    let residencySet: any MTLResidencySet
    let library: any MTLLibrary
    let finished: any MTLSharedEvent
    private var finishedValue: UInt64 = 0

    init(source: String) throws {
        guard let device = MTLCreateSystemDefaultDevice(), device.supportsFamily(.metal4) else {
            throw NSError(domain: "ComputeRunner", code: 1,
                          userInfo: [NSLocalizedDescriptionKey: "Metal 4 GPU required"])
        }
        self.device = device
        queue = device.makeMTL4CommandQueue()!
        compiler = try device.makeCompiler(descriptor: MTL4CompilerDescriptor())
        allocator = device.makeCommandAllocator()!
        commandBuffer = device.makeCommandBuffer()!
        finished = device.makeSharedEvent()!

        let libraryDescriptor = MTL4LibraryDescriptor()
        libraryDescriptor.source = source
        library = try compiler.makeLibrary(descriptor: libraryDescriptor)

        let tableDescriptor = MTL4ArgumentTableDescriptor()
        tableDescriptor.maxBufferBindCount = 8
        tableDescriptor.maxTextureBindCount = 4
        table = try device.makeArgumentTable(descriptor: tableDescriptor)

        let setDescriptor = MTLResidencySetDescriptor()
        setDescriptor.initialCapacity = 16
        residencySet = try device.makeResidencySet(descriptor: setDescriptor)
        queue.addResidencySet(residencySet)
    }

    func makePipeline(_ name: String) throws -> any MTLComputePipelineState {
        let function = MTL4LibraryFunctionDescriptor()
        function.library = library
        function.name = name
        let descriptor = MTL4ComputePipelineDescriptor()
        descriptor.computeFunctionDescriptor = function
        return try compiler.makeComputePipelineState(descriptor: descriptor,
                                                     dynamicLinkingDescriptor: nil,
                                                     compilerTaskOptions: nil)
    }

    func makeBuffer(length: Int) -> any MTLBuffer {
        let buffer = device.makeBuffer(length: length, options: .storageModeShared)!
        residencySet.addAllocation(buffer)
        residencySet.commit()
        return buffer
    }

    func makeTexture(_ descriptor: MTLTextureDescriptor) -> any MTLTexture {
        let texture = device.makeTexture(descriptor: descriptor)!
        residencySet.addAllocation(texture)
        residencySet.commit()
        return texture
    }

    /// Dispatches `pipeline` and blocks until the GPU has finished.
    /// Buffers are bound to slots 0, 1, 2 ... and textures to slots 0, 1 ...
    func run(_ pipeline: any MTLComputePipelineState,
             buffers: [any MTLBuffer] = [], textures: [any MTLTexture] = [],
             grid: MTLSize? = nil, threadgroups: MTLSize? = nil, group: MTLSize) {
        for (slot, buffer) in buffers.enumerated() { table.setAddress(buffer.gpuAddress, index: slot) }
        for (slot, texture) in textures.enumerated() { table.setTexture(texture.gpuResourceID, index: slot) }

        allocator.reset()                                  // safe: the previous work has finished
        commandBuffer.beginCommandBuffer(allocator: allocator)
        let encoder = commandBuffer.makeComputeCommandEncoder()!
        encoder.setComputePipelineState(pipeline)
        encoder.setArgumentTable(table)
        if let grid {
            encoder.dispatchThreads(threadsPerGrid: grid, threadsPerThreadgroup: group)
        } else if let threadgroups {
            encoder.dispatchThreadgroups(threadgroupsPerGrid: threadgroups, threadsPerThreadgroup: group)
        }
        encoder.endEncoding()
        commandBuffer.endCommandBuffer()

        queue.commit([commandBuffer], options: nil)
        finishedValue += 1
        queue.signalEvent(finished, value: finishedValue)
        guard finished.wait(untilSignaledValue: finishedValue, timeoutMS: 10_000) else {
            fatalError("The GPU did not finish in 10 seconds")
        }
    }
}

A few details that the code relies on:

  • MTL4LibraryDescriptor.source compiles MSL text at run time. In an Xcode project the .metal files are compiled at build time into the default library instead, and you load it with device.makeDefaultLibrary() and pass it as library of the function descriptor.

  • makeComputePipelineState(descriptor:dynamicLinkingDescriptor:compilerTaskOptions:) has a synchronous and an async variant; compile pipelines off the main thread in an app (see Shader Compilation and Pipeline Caching).

  • allocator.reset() frees the memory of the previous command: only safe because the previous dispatch has finished, which run guarantees by waiting. In a frame loop use one allocator per frame in flight.

  • The shared event finished counts dispatches. queue.signalEvent is encoded after the commit, so the CPU wait releases only when the GPU has finished the committed work.

The four examples as one program

main.swift below runs the four kernels of this page with the helper: saxpy on 1,000,003 floats (a number that is deliberately not a multiple of any threadgroup size, so the partial last group is exercised), a grayscale kernel on a 1,000 by 600 texture, a reduction and a stream compaction. It prints four lines, one per example; with the Metal API validation and shader validation turned on (MTL_DEBUG_LAYER=1 MTL_SHADER_VALIDATION=1 in the environment) it prints no messages.

// main.swift: build with  swiftc -O ComputeRunner.swift main.swift -o compute   (macOS 26 or later, Apple silicon)
import Metal

let source = """
#include <metal_stdlib>
using namespace metal;

kernel void saxpy(device const float *x [[buffer(0)]],
                  device float       *y [[buffer(1)]],
                  constant float     &a [[buffer(2)]],
                  uint               i  [[thread_position_in_grid]])
{
    y[i] = a * x[i] + y[i];
}

kernel void reduce_sum(device const float *input   [[buffer(0)]],
                       device float       *partial [[buffer(1)]],
                       constant uint      &count   [[buffer(2)]],
                       uint gid        [[thread_position_in_grid]],
                       uint group      [[threadgroup_position_in_grid]],
                       uint lane       [[thread_index_in_simdgroup]],
                       uint simd       [[simdgroup_index_in_threadgroup]],
                       uint simdCount  [[simdgroups_per_threadgroup]])
{
    threadgroup float sums[32];                    // at most 1,024 threads / 32 lanes
    float value = gid < count ? input[gid] : 0.0f; // dispatchThreadgroups can overshoot the data
    float simdTotal = simd_sum(value);             // step 1: reduce inside each SIMD-group
    if (lane == 0) sums[simd] = simdTotal;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (simd == 0) {                               // step 2: SIMD-group 0 reduces the partial sums
        float t = lane < simdCount ? sums[lane] : 0.0f;
        t = simd_sum(t);
        if (lane == 0) partial[group] = t;
    }
}

kernel void grayscale(texture2d<float, access::read>  src [[texture(0)]],
                      texture2d<float, access::write> dst [[texture(1)]],
                      uint2 gid [[thread_position_in_grid]])
{
    float4 c = src.read(gid);
    float y = dot(c.rgb, float3(0.2126, 0.7152, 0.0722));
    dst.write(float4(y, y, y, c.a), gid);
}

kernel void compact_positive(device const float *input   [[buffer(0)]],
                             device float       *output  [[buffer(1)]],
                             device atomic_uint *counter [[buffer(2)]],
                             constant uint      &count   [[buffer(3)]],
                             uint gid  [[thread_position_in_grid]],
                             uint lane [[thread_index_in_simdgroup]])
{
    bool keep = gid < count && input[gid] > 0.0f;
    uint flag = keep ? 1u : 0u;
    uint rank = simd_prefix_exclusive_sum(flag);       // index among the kept lanes of this SIMD-group
    uint total = simd_sum(flag);                       // how many lanes keep a value
    uint base = 0;
    if (lane == 0 && total > 0) {
        base = atomic_fetch_add_explicit(counter, total, memory_order_relaxed); // one atomic per SIMD-group
    }
    base = simd_broadcast_first(base);
    if (keep) { output[base + rank] = input[gid]; }
}
"""

let runner = try ComputeRunner(source: source)

// --- Example 1: saxpy on 1,000,003 elements (dispatchThreads, no bounds check needed) ---
do {
    let pipeline = try runner.makePipeline("saxpy")
    let count = 1_000_003
    let x = runner.makeBuffer(length: count * 4)
    let y = runner.makeBuffer(length: count * 4)
    let a = runner.makeBuffer(length: 4)
    let xs = x.contents().bindMemory(to: Float.self, capacity: count)
    let ys = y.contents().bindMemory(to: Float.self, capacity: count)
    for i in 0..<count { xs[i] = Float(i); ys[i] = 1 }
    a.contents().storeBytes(of: Float(2), as: Float.self)

    let width = pipeline.threadExecutionWidth
    let height = pipeline.maxTotalThreadsPerThreadgroup / width
    runner.run(pipeline, buffers: [x, y, a],
               grid: MTLSize(width: count, height: 1, depth: 1),
               group: MTLSize(width: width * height, height: 1, depth: 1))

    var wrong = 0
    for i in 0..<count where ys[i] != 2 * Float(i) + 1 { wrong += 1 }
    print("saxpy: \(count) elements, \(wrong) wrong")
}

// --- Example 2: a 2D kernel on a texture ---
do {
    let w = 1000, h = 600
    let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false)
    d.usage = [.shaderRead, .shaderWrite]
    d.storageMode = .shared
    let src = runner.makeTexture(d), dst = runner.makeTexture(d)
    var pixels = [UInt8](repeating: 0, count: w * h * 4)
    for i in 0..<(w * h) { pixels[i*4] = 255; pixels[i*4+1] = 0; pixels[i*4+2] = 0; pixels[i*4+3] = 255 }
    src.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0, withBytes: pixels, bytesPerRow: w * 4)
    let pipeline = try runner.makePipeline("grayscale")
    let width = pipeline.threadExecutionWidth
    let height = pipeline.maxTotalThreadsPerThreadgroup / width
    runner.run(pipeline, textures: [src, dst], grid: MTLSize(width: w, height: h, depth: 1),
               group: MTLSize(width: width, height: height, depth: 1))
    var out = [UInt8](repeating: 0, count: 4)
    dst.getBytes(&out, bytesPerRow: w * 4, from: MTLRegionMake2D(999, 599, 1, 1), mipmapLevel: 0)
    print("grayscale last pixel:", out, "(expected [54, 54, 54, 255])")
}

// --- Example 3: reduction (dispatchThreadgroups: one group per partial sum) ---
do {
    let count = 1_000_003
    let input = runner.makeBuffer(length: count * 4)
    let p = input.contents().bindMemory(to: Float.self, capacity: count)
    for i in 0..<count { p[i] = 1 }
    let pipeline = try runner.makePipeline("reduce_sum")
    let size = 1024
    let groups = (count + size - 1) / size
    let partial = runner.makeBuffer(length: groups * 4)
    let nBuf = runner.makeBuffer(length: 4)
    nBuf.contents().storeBytes(of: UInt32(count), as: UInt32.self)
    runner.run(pipeline, buffers: [input, partial, nBuf],
               threadgroups: MTLSize(width: groups, height: 1, depth: 1),
               group: MTLSize(width: size, height: 1, depth: 1))
    let q = partial.contents().bindMemory(to: Float.self, capacity: groups)
    var total: Float = 0
    for g in 0..<groups { total += q[g] }
    print("reduce_sum:", total, "expected", count)
}

// --- Example 4: stream compaction with one atomic per SIMD-group ---
do {
    let count = 100_000
    let input = runner.makeBuffer(length: count * 4)
    let output = runner.makeBuffer(length: count * 4)
    let counter = runner.makeBuffer(length: 4)
    counter.contents().storeBytes(of: UInt32(0), as: UInt32.self)     // the counter must start at zero
    let p = input.contents().bindMemory(to: Float.self, capacity: count)
    var expected = 0
    for i in 0..<count { p[i] = (i % 3 == 0) ? Float(i) + 1 : -1; if p[i] > 0 { expected += 1 } }
    let nBuf = runner.makeBuffer(length: 4)
    nBuf.contents().storeBytes(of: UInt32(count), as: UInt32.self)
    let pipeline = try runner.makePipeline("compact_positive")
    runner.run(pipeline, buffers: [input, output, counter, nBuf],
               grid: MTLSize(width: count, height: 1, depth: 1), group: MTLSize(width: 256, height: 1, depth: 1))
    let kept = counter.contents().load(as: UInt32.self)
    print("compact: kept", kept, "expected", expected)
}

Example 1, saxpy, uses dispatchThreads with the SIMD width times the height as a one-dimensional group, so the kernel has no guard and the last group is smaller. It prints 0 wrong.

The Metal 3 equivalent

import Metal

let source = """
#include <metal_stdlib>
using namespace metal;
kernel void saxpy(device const float *x [[buffer(0)]],
                  device float       *y [[buffer(1)]],
                  constant float     &a [[buffer(2)]],
                  uint               i  [[thread_position_in_grid]])
{
    y[i] = a * x[i] + y[i];
}
"""

let device = MTLCreateSystemDefaultDevice()!
let queue = device.makeCommandQueue()!
let library = try device.makeLibrary(source: source, options: nil)
let pipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "saxpy")!)

let count = 1_000_003
let x = device.makeBuffer(length: count * 4, options: .storageModeShared)!
let y = device.makeBuffer(length: count * 4, options: .storageModeShared)!
let px = x.contents().bindMemory(to: Float.self, capacity: count)
let py = y.contents().bindMemory(to: Float.self, capacity: count)
for i in 0..<count { px[i] = Float(i); py[i] = 1 }
var a: Float = 2

let commandBuffer = queue.makeCommandBuffer()!            // a new, single-use buffer every time
let encoder = commandBuffer.makeComputeCommandEncoder()!
encoder.setComputePipelineState(pipeline)
encoder.setBuffer(x, offset: 0, index: 0)                  // resources are bound on the encoder
encoder.setBuffer(y, offset: 0, index: 1)
encoder.setBytes(&a, length: MemoryLayout<Float>.stride, index: 2)
let width = pipeline.threadExecutionWidth
encoder.dispatchThreads(MTLSize(width: count, height: 1, depth: 1),
                        threadsPerThreadgroup: MTLSize(width: width * 8, height: 1, depth: 1))
encoder.endEncoding()
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
print(py[10], py[count - 1])

What differs from Metal 4: a new MTLCommandBuffer per dispatch; resources bound on the encoder with setBuffer and setBytes (Metal 4 has no setBytes: put constants in a buffer); no argument table, no residency set, no allocator; commit() and waitUntilCompleted() instead of events; hazard tracking orders dependent passes automatically and a serial compute encoder orders its dispatches. The kernel is identical.

Example 2: a 2D kernel on a texture

Image kernels use a 2D grid. The grid is the size of the image, the group is the 32 by 32 block from the rule above. In main.swift the texture is 1,000 by 600, not a multiple of 32 on either axis, and dispatchThreads handles both edges. The last pixel of a pure red image comes out as [54, 54, 54, 255]: 0.2126 of 255 is about 54.

A texture that a kernel writes needs .shaderWrite in its usage, and its pixel format must support writes: the Feature Set Tables list which formats allow write and read_write access (many compressed and some packed formats do not). In a real frame you would not create a texture per dispatch: allocate once, put it in the residency set and bind its gpuResourceID in the table, which makeTexture and setTexture(_:index:) of the helper do.

SIMD-group functions

Four SIMD-groups each reduce their lanes with simd_sum, lane 0 of each writes to a threadgroup array, a barrier follows, and SIMD-group 0 reduces the array to one partial sum per threadgroup
Figure 4. A two-level reduction: SIMD-groups first, then one SIMD-group over the partial sums

Threads of one SIMD-group run in lockstep, so they can exchange values without going through memory. The functions are in <metal_simdgroup> and are included by metal_stdlib. They operate on the active threads of the SIMD-group: those that have not exited and are not on the other side of a divergent branch.

Family Functions What they do

Reduction

simd_sum, simd_product, simd_min, simd_max, simd_and, simd_or, simd_xor

combine a value of every active lane and give the result to all of them

Prefix

simd_prefix_exclusive_sum, simd_prefix_inclusive_sum (and _product)

each lane gets the sum of the values of the lower lanes (exclusive, the first lane gets 0) or of the lower lanes and itself (inclusive)

Broadcast

simd_broadcast(value, lane), simd_broadcast_first(value)

every lane gets the value of one lane

Shuffle

simd_shuffle, simd_shuffle_up, simd_shuffle_down, simd_shuffle_xor, simd_shuffle_rotate_up, simd_shuffle_rotate_down

lane exchange by index, by offset (no wrap-around for up and down) or by XOR of the lane number

Vote

simd_all, simd_any, simd_ballot, simd_active_threads_mask

boolean questions about the active lanes; simd_ballot returns a bit mask of the lanes whose predicate is true

Barrier

simdgroup_barrier(mem_flags)

execution barrier and optional memory fence among the lanes of a SIMD-group

Matrix

simdgroup_float8x8 and simdgroup_multiply_accumulate

8 by 8 matrix multiply across the SIMD-group; the building block of fast matrix and neural network code (see Machine Learning in Metal 4)

Quad

quad_sum, quad_shuffle, …​

the same ideas over groups of four lanes

Availability on the hardware: SIMD-scoped permute operations (shuffles) need Apple6; SIMD-scoped reductions and matrix multiply need Apple7; shift-and-fill shuffles need Apple8. The simdgroup_barrier exists on all Apple GPUs. All of them are available on every Metal 4 device.

Example 3: a two-level reduction

Summing a million numbers on a CPU is a loop; on a GPU it is a tree. Each SIMD-group reduces its 32 values with one simd_sum, the SIMD-groups of a threadgroup combine through threadgroup memory, and each threadgroup writes one partial sum that the CPU (or a second dispatch) adds up. The kernel is the code of the figure:

kernel void reduce_sum(device const float *input   [[buffer(0)]],
                       device float       *partial [[buffer(1)]],
                       constant uint      &count   [[buffer(2)]],
                       uint gid        [[thread_position_in_grid]],
                       uint group      [[threadgroup_position_in_grid]],
                       uint lane       [[thread_index_in_simdgroup]],
                       uint simd       [[simdgroup_index_in_threadgroup]],
                       uint simdCount  [[simdgroups_per_threadgroup]])
{
    threadgroup float sums[32];                    // at most 1,024 threads / 32 lanes
    float value = gid < count ? input[gid] : 0.0f; // dispatchThreadgroups can overshoot the data
    float simdTotal = simd_sum(value);             // step 1: reduce inside each SIMD-group
    if (lane == 0) sums[simd] = simdTotal;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (simd == 0) {                               // step 2: SIMD-group 0 reduces the partial sums
        float t = lane < simdCount ? sums[lane] : 0.0f;
        t = simd_sum(t);
        if (lane == 0) partial[group] = t;
    }
}

The host code in main.swift uses dispatchThreadgroups, because each threadgroup produces exactly one output: it rounds the number of groups up ((count + size - 1) / size), the kernel guards the overshoot with gid < count, and the CPU adds the 977 partial sums. It prints reduce_sum: 1000003.0 expected 1000003.

Points to check in the kernel:

  • The threadgroup_barrier is reached by every thread of the group; only the memory accesses are conditional. A barrier inside if (simd == 0) would hang or give undefined results.

  • mem_flags::mem_threadgroup orders the writes to threadgroup memory. mem_flags::mem_device orders device memory, mem_flags::mem_texture orders read-write textures, and mem_flags::mem_none is an execution barrier only.

  • sums[32] assumes that a group has at most 1,024 threads and a SIMD-group of 32. Size it from maxTotalThreadsPerThreadgroup / threadExecutionWidth if you want it portable, or check threadExecutionWidth == 32 on the host.

  • Floating-point addition is not associative, so the result depends on the order. The tree is deterministic for a given grid and group size, but differs from a sequential sum in the last bits; sum in float and compare with a tolerance.

Example 4: stream compaction with one atomic per SIMD-group

Compaction keeps the interesting elements of an array and packs them. The parallel version needs each thread to know where to write. Doing an atomic add per thread contends on one counter; with SIMD-group functions each SIMD-group does one atomic for all its lanes.

kernel void compact_positive(device const float *input   [[buffer(0)]],
                             device float       *output  [[buffer(1)]],
                             device atomic_uint *counter [[buffer(2)]],
                             constant uint      &count   [[buffer(3)]],
                             uint gid  [[thread_position_in_grid]],
                             uint lane [[thread_index_in_simdgroup]])
{
    bool keep = gid < count && input[gid] > 0.0f;
    uint flag = keep ? 1u : 0u;
    uint rank = simd_prefix_exclusive_sum(flag);       // index among the kept lanes of this SIMD-group
    uint total = simd_sum(flag);                       // how many lanes keep a value
    uint base = 0;
    if (lane == 0 && total > 0) {
        base = atomic_fetch_add_explicit(counter, total, memory_order_relaxed); // one atomic per SIMD-group
    }
    base = simd_broadcast_first(base);                 // lane 0 tells everyone where the block starts
    if (keep) { output[base + rank] = input[gid]; }
}

In main.swift it runs with dispatchThreads over 100,000 elements where every third is positive, and it keeps 33,334 values: the counter ends at 33,334. The output order is not the input order (SIMD-groups reach the atomic in any order), but the order inside each SIMD-group is. Use this pattern to build visible-object lists, particle free lists and the output of a culling pass. The counter buffer must be cleared (to zero) before the dispatch, for example with a fill on the compute encoder or by the CPU for a shared buffer, and a barrier must separate the clear from the dispatch.

Threadgroup memory

threadgroup variables hold data shared inside one group and live for the group’s lifetime, with no initial value. Declare them in the kernel (static size, as sums above) or as a pointer argument threadgroup float *scratch [[threadgroup(0)]] and pass its length on the host with setThreadgroupMemoryLength(_:index:) on the compute encoder (a multiple of 16 bytes). Typical uses: staging a tile of a texture so that neighbouring threads (a blur kernel) reuse each pixel, partial sums, per-group histograms combined with atomics on threadgroup memory, and small sort networks. Rules:

  • After writing and before reading data another thread wrote, call threadgroup_barrier(mem_flags::mem_threadgroup).

  • All threads of the group must execute the barrier, so do not put it behind a divergent branch.

  • The total must stay under the limit (32 KB on Apple4 and later), and a large allocation reduces the number of groups resident on a core at once (occupancy).

  • Threadgroup memory is the same on-chip memory that tile shaders use for imageblocks; see Deferred and Tile Shading.

The Metal 4 compute encoder does more than dispatches

MTL4ComputeCommandEncoder replaces three Metal 3 encoders at once: MTLComputeCommandEncoder, MTLBlitCommandEncoder and MTLAccelerationStructureCommandEncoder. The one encoder can copy buffers and textures (copy(sourceBuffer:...)), fill buffers (fill(buffer:range:value:)), generate mipmaps (generateMipmaps(texture:)), build and refit acceleration structures, execute indirect command buffers and write timestamps, next to its dispatchThreads calls. Their stages are .dispatch, .blit and .accelerationStructure in barriers. Fewer encoders mean fewer encoder switches; the price is that all of this work in one encoder runs concurrently unless you add barriers.

Common mistakes

  • No bounds check with dispatchThreadgroups. The last group writes past the buffer; the symptom is memory corruption that moves around.

  • A barrier that not every thread reaches. The group deadlocks or computes garbage.

  • Assuming a SIMD-group size of 32 in a kernel that indexes arrays with it. Use threads_per_simdgroup.

  • Forgetting .shaderWrite on a texture the kernel writes, or using a format that does not support writes.

  • Missing barrier between two dependent dispatches in a Metal 4 encoder. They run concurrently; see the synchronisation page.

  • A resource missing from the residency set. In Metal 4 the dispatch can read garbage or page fault.

  • Reading the result on the CPU before the GPU finishes. Wait on an event (or waitUntilCompleted in Metal 3) first.

  • Hard-coding the threadgroup size. Use the pipeline’s limits; a complex kernel may get a smaller maximum than a simple one.

  • Comparing GPU floating-point sums with exact equality.

  • Returning early in a kernel that later calls a SIMD-group function or barrier, which changes which lanes are active.

Performance notes

  • Memory access dominates. Have neighbouring threads read neighbouring addresses (thread i reads element i), use half where precision allows and read vector types (float4) for fewer, wider loads.

  • Keep SIMD-groups convergent. A branch that splits a SIMD-group runs both sides one after the other with some lanes masked. Make the condition uniform per SIMD-group where you can (sort or bin the work first).

  • Reduce atomics. Combine within the SIMD-group first (Example 4), then within the group, then across the grid.

  • Occupancy. Registers and threadgroup memory limit how many threadgroups a core keeps resident; more resident groups hide memory latency. Look at the occupancy and register counters in a GPU capture (Debugging and Profiling).

  • Launch overhead. Every dispatch has a fixed cost, so batch small tasks into one dispatch, or into one encoder.

  • Use the Metal Performance Shaders when one exists. Image filters, matrix products and reductions in MetalPerformanceShaders are tuned for each GPU (Image Processing and Metal Performance Shaders).

  • Compute and graphics share the GPU. A long compute pass delays the frame it feeds; see Performance Best Practices.

What changed recently

When What

2014 (Metal 1)

compute kernels, threadgroups and threadgroup memory arrive

2017 (Metal 2, iOS 11, macOS 10.13)

dispatchThreads and non-uniform threadgroups (A11 and later)

2020 (A14 and M1, family Apple7)

SIMD-scoped reductions and matrix multiply operations in the Feature Set Tables; the SIMD-scoped permutes need A13 (Apple6)

2023 (Metal 3.1)

global variables with built-in attributes in kernel contexts

2024 (Metal 3.2)

lambda expressions in MSL

2025 (26 OSes, Metal 4)

MTL4ComputeCommandEncoder merges compute, blit and acceleration structure encoding; MTL4ArgumentTable replaces per-encoder bindings; encoder barriers; no setBytes; MSL 4.0

2026 (27 OSes, MSL 4.1)

placement new in MSL

Where the books are outdated

Book Topic Current practice

CLA (throughout)

Swift 4, Xcode 9 and device.newDefaultLibrary()

makeDefaultLibrary(), Swift 6.4 and Xcode 27

CLA ch. 15

threadgroups limited to 512 threads on iOS

1,024 threads per group on A11 (Apple4) and later; check maxTotalThreadsPerThreadgroup and the Feature Set Tables

MBT ch. 16 to 18 and CLA ch. 15 and 16

compute and particles on the Metal 2 and Metal 3 encoders, where a blit needs a separate MTLBlitCommandEncoder

MTL4ComputeCommandEncoder also does blits and acceleration structure builds; use dispatchThreads and the SIMD-group functions

MBT and CLA

written for Metal 2 and Metal 3, where Metal tracks the hazards of tracked resources between dispatches

Metal 4 does not track hazards: add barriers (Synchronization and Barriers)

MBT and CLA

predate argument tables and residency sets

Metal 4 compute binds resources through MTL4ArgumentTable and needs residency sets

See also