68. GPU compute: a proved spread placed on the GPU, lowered through SPIR-V and SPIRV-Cross to Metal, launched by a small trusted shim¶
Date: 2026-11-25
Status: Accepted (2026-11-25, with Dean's answers below)
Context¶
ADR 0015 lets code be placed on the GPU with @place(gpu) and requires that placement never change the proved result. Nothing implements it yet: the compiler has no GPU code, and pia_par has no lowering to a device. Three things now need it:
- The flagship demo (ADR 0016, ADR 0055 section 6). D8 directions, rendering and the pull form of the sediment step all write one cell per iteration. On a real SRTM tile (13.0M cells, PR #422) the CPU pipeline takes 3.7 s.
- Lowerings written in Pia (ADR 0065 section 6). That ADR takes a
linalgkernel down to aspirv.moduleand defers the host side, the Metal shim and@place(gpu)to "the GPU ADR". This is that ADR. - Release 0.1.0 (ADR 0067, Proposed). Its milestone is a proved small Llama model on the M3, which needs f32 matrix-vector products on the GPU, with weights kept on the GPU across tokens.
Dean decided on 2026-11-23 (on the survey) that the GPU path is SPIR-V, so that AMD, Intel and NVIDIA can come later through Vulkan, with SPIRV-Cross translating it to MSL for Metal now.
What is already in place:
spreadv0 (ADR 0060) proves that each iteration writes only the cells it owns, one iteration at a time. This is exactly the fact a GPU kernel needs: each thread is an iteration, and no two threads write the same cell.- ADR 0038 defines tolerance contracts over a rounding theory. Each device has a float model that states its
eps, itstiny(the absolute error term) and the operations it does not round correctly. A kernel may be placed only on a device whose model proves its contract. - Apple Silicon has unified memory. A
MTLBufferin shared storage mode is the same physical memory to the CPU and the GPU, so placing work on the GPU copies nothing.
Decision¶
1. A kernel is a spread placed on the GPU¶
@place(gpu) on a spread makes each iteration a GPU thread. The loop is proved exactly as on the CPU: by the body, the ownership goals of ADR 0060 and the loop's ensures. Nothing about the proof depends on the placement. The rules of spread v0 carry over unchanged: no assignment to outer variables, writes only through owned cells, and calls only with footprints.
A GPU body has extra rules, checked by the type checker:
- No calls that cannot run on the device. Allowed are other functions the compiler can inline, or that are themselves GPU-placeable: no allocation, no foreign calls, no I/O, no recursion.
- Element types the device supports. These are integers of 8 to 64 bits and, after M11,
f32. Storage of 8- and 16-bit elements uses SPIR-V'sStorageBuffer8BitAccessand16BitAccess. - Every buffer the body touches is a device buffer (section 4), or a slice the shim can wrap without a copy.
A function marked @place(gpu) is a function whose body is one such spread plus scalar set-up, so let directions (dem) (out) @place(gpu) = spread i in 0 .. len out do ... done reads as one kernel.
Placement does not change an integer result. The body that runs on the GPU is the body that was proved. Integer operations have one meaning in Pia: wrap, saturate and checked are explicit, and division by zero and shifts out of range are already proved absent. Codegen lowers each operation to the same SPIR-V arithmetic on every device. So for integer kernels, ADR 0015's rule holds by construction, and the differential tests (section 6) check the toolchain rather than the proof.
2. The lowering: scf.parallel to gpu to SPIR-V to MSL¶
IRGen already lowers spread to scf.parallel (ADR 0060). For a GPU-placed loop, codegen then runs upstream MLIR passes only:
gpu-map-parallel-loopsandconvert-parallel-loops-to-gpumake agpu.launchwith one thread per iteration, in blocks of a fixed size (256 by default; a@schedulefrom ADR 0065 can choose it).gpu-kernel-outliningmoves the body into agpu.module, andgpu.launch_funcstays on the host.- The storage-class mapping and
convert-gpu-to-spirv(witharith,memrefandscfto SPIR-V) produce aspirv.module. It is serialised to a SPIR-V binary with the target environmentVulkan 1.1plus the capabilities above. - SPIRV-Cross translates the binary to MSL, with the Metal version and argument-buffer options fixed by the target model.
- The Metal compiler (
xcrun metal, thenmetallib) builds a.metallib, which is embedded in the object file as a section. At load, the shim finds kernels by name.
The host side of gpu.launch_func lowers to calls into the shim (section 3), not to MLIR's GPU runtime wrappers. Those wrappers exist for CUDA, ROCm and Vulkan, but not for Metal.
ADR 0065's linalg kernels join the same pipeline at step 1. Their @schedule maps scf.forall to blocks and threads, and steps 2 to 5 are shared.
3. The host shim is small, written in Objective-C, and trusted¶
src/runtime/metal/ is one Objective-C file over Metal, compiled with ARC, plus a C header. It exposes about eight functions, each declared in Pia as an extern with a contract:
device_openreturns a device orGpu_unavailable.buffer_newmakes a shared-storage buffer ofnbytes, or returnsGpu_out_of_memory.buffer_viewgives the CPU a slice over it, with no copy.buffer_freereleases it.kernel_getlooks a kernel up in the embedded library by name, with a pipeline cache.dispatchtakes a kernel, its buffers, scalar arguments and a grid size. It encodes one compute pass, commits it, and waits for completion. It returnsOk,Gpu_fault(a command buffer error) orGpu_timeout.
v0 is synchronous, so when dispatch returns, the GPU's writes are visible to the CPU and no buffer is in use by the device. That keeps ownership trivial: the host cannot touch a buffer while a kernel writes it, because the host is blocked. Asynchronous launches come with Pia.Exec.Metal (ADR 0050 step 9), where a buffer is moved into the GPU stage and returned in its value. That is the same rule, expressed as a sender.
The shim, SPIRV-Cross, the Metal compiler and the upstream MLIR GPU and SPIR-V conversions are trusted items, listed in the trust report and the certificate (ADR 0024). They are trusted the way the MLIR async runtime is in ADR 0060, and for the same reason: they are external toolchain pieces with wide use. Section 6 says how they are tested.
4. Device buffers are linear resources that stay on the GPU¶
Pia.Gpu.buffer t is a @linear resource (ADR 0026) that holds len elements of t in a shared-storage MTLBuffer. Making one is fallible, like every allocation. drop frees it. It lives as long as its owner, so weights loaded once stay resident across many launches. This is the LLM's requirement: load once, then one matrix-vector product per token.
On the CPU, view b is a slice of t over the same memory. It is borrowed, so it cannot outlive the buffer, and the type checker forbids holding it across a dispatch that writes b. A kernel takes buffers, not slices. Slices of a buffer (b.[lo .. hi]) are passed as a buffer and an offset.
On a device with its own memory (later, Vulkan), the same type holds device memory, and view becomes an explicit, fallible transfer. The Pia code does not change.
5. Errors: placement may fail, and the caller decides¶
A @place(gpu) function's error set gains Gpu.error (Gpu_unavailable | Gpu_out_of_memory | Gpu_fault | Gpu_timeout), handled with ? as any other error (ADR 0028). An explicit placement never silently runs on the CPU. @place(auto, prefer = gpu) may fall back to the CPU, because both run the same proved body. For integers the result is the same. For floats the fallback is allowed only when the CPU's float model also proves the contract, which the strict IEEE CPU model always does when the GPU's does.
6. Testing what is trusted¶
- Differential tests. Every
@place(gpu)test runs the kernel on the CPU too. Integers must match bit for bit. Floats must lie within the proved tolerance of each other and of af64reference. - A litmus battery for the float model (section 7), run on each Apple GPU we support. It checks the rounding of
+,-,*andfmaagainst a correctly rounded reference, subnormal inputs and outputs, and whethera * b + cwas contracted, for every rounding-sensitive pattern. It runs as for atomics (ADR 0052). - GPU tests run on the iMac only, tagged
requires-gpu. Linux CI has no Metal, so it builds the SPIR-V and the MSL (SPIRV-Cross runs anywhere) and checks them withspirv-val, but does not run them. A Vulkan runner can come with a Linux GPU.
7. The Apple GPU float model¶
Each placement target has a float model under ADR 0038. Pia.Device.Apple_gpu is a theory with one model per GPU family (M1 to M4 first). For f32 it states:
- Rounding.
+,-,*andfmaround to nearest even when fast math is off, soeps f32 = 2⁻²⁴. Pia compiles MSL with fast math off (-fno-fast-math), and the MSL specification's accuracy table lists these operations as correctly rounded. The litmus battery confirms it for each family. Division andsqrtare not correctly rounded on all families, so the model gives their error in ulps from the battery, or leaves them out, which makes a kernel that uses them unplaceable until it is measured. - Subnormals may be flushed. The model takes
tiny = 2⁻¹²⁶(the smallest normal) as the absolute error term of every operation, instead of the CPU's half-subnormal. That is sound whether or not a family flushes. If the battery shows that a family keeps subnormals, its model can use the CPU's value. - Contraction is stated, not assumed away. SPIR-V marks an operation that must not be contracted with
NoContraction. Pia marks every float operationNoContractionunless ADR 0012 licenses contraction for that expression, so the GPU computes what was proved. Whether SPIRV-Cross carries the decoration into MSL is checked in step 6. If it does not, contraction is turned off for the whole kernel with the Metal compiler's options. If the battery finds a family that contracts anyway, its model says "may contract", which is still sound for ADR 0038's bounds because a contraction only removes a rounding. - Reduction order is free. Threadgroup reductions reorder sums, so a GPU reduction is proved with ADR 0038's order-free bound,
γₙfor a sum of lengthn. That bound does not depend on the tree, so the proof holds for any schedule.
f16 and bf16 are later. The model is a trusted theory, since Apple documents correct rounding only in prose, and it is listed in the trust report.
8. Threadgroup memory, barriers and SIMD-group matrices¶
A spread v0 iteration shares nothing with other iterations, so it cannot use threadgroup memory. A tiled reduction or matmul needs a tile in threadgroup memory, a barrier, and threads that read each other's writes after it. These come through ADR 0065's @schedule (tile_using_forall with promotion to workgroup memory, upstream gpu.barrier), trusted at first and translation-validated later (ADR 0065 step 8), not through new spread syntax. A language-level form, a group of iterations with a scratch buffer they share between barriers, is left for a later ADR, once a kernel needs it that a schedule cannot express.
Apple's SIMD-group matrix operations (simdgroup_matrix) are vendor ops with no SPIR-V equivalent that SPIRV-Cross maps. If used, they are a trusted @lower to MSL (ADR 0065, state 3) behind a Pia contract. They are optional.
Implementation order¶
Each step is one PR and useful on its own. Steps 1 to 4 are integer-only.
- Toolchain. Link the
gpuandspirvdialects and conversions into piac. Add SPIRV-Cross and SPIRV-Tools as Bazel modules (from the Bazel Central Registry where they are, otherwise pinned like Z3). Add a macOS-only rule that runsxcrun metalandmetalliband embeds the library. Test: a hand-writtengpu.modulethat adds two buffers goes all the way to a.metallib, andspirv-valpasses. - The shim and
Pia.Gpu.buffer.src/runtime/metal/, theexterncontracts, the trust items, andbufferwithviewanddrop. Test: a C harness dispatches step 1's kernel on the iMac. @place(gpu)on aspreadwith identity ownership, with the device rules of section 1 and the error set of section 5. First kernels: D8 directions and render from the streams demo, with differential tests against the CPU on the SRTM fixture and the full tile.- The sediment pull step on the GPU, once its equality proof against the sequential step is merged (ADR 0055 section 6). The demo page then shows CPU and GPU timings on real tiles.
- ADR 0065 schedules on the GPU:
tile_using_forallmapped to blocks and threads, workgroup promotion, an integer matmul. - Floats, after M11: the Apple GPU float model and its litmus battery,
NoContraction, and anf32matrix-vector product with a tolerance contract (γₙ,nup to 768) for the 0.1.0 LLM. Pia.Exec.Metal: asynchronous launches as senders (ADR 0050 step 9), and placement of@place(auto)stages by the cost model.
Consequences¶
- The flagship demo and the 0.1.0 LLM get the GPU through one path, and that path is SPIR-V, so Vulkan devices need only a second shim.
- Integer kernels are proved once, and placing them on the GPU adds no proof obligation. The new trust is the toolchain (MLIR GPU and SPIR-V conversions, SPIRV-Cross, the Metal compiler) and a small shim. All of it is listed, and all of it is checked by differential tests.
- Float kernels on the GPU are proved against a stated device model, with subnormal flushing and contraction accounted for, so no kernel relies on Metal behaviour that wasn't written down.
- Building GPU code needs Xcode's Metal toolchain on macOS. Linux builds the SPIR-V and MSL but cannot run them.
Pia.Gpu.bufferis a new resource type, and the type checker gains device rules for GPU-placed bodies.
Answers to the review questions¶
Dean answered on 2026-11-25. Each answer is the proposed option:
- ~~Explicit placement and failure?~~
@place(gpu)addsGpu.errorto the function's error set. An explicit placement never runs silently on the CPU. Only@place(auto, prefer = gpu)may fall back. - ~~Where is MSL compiled?~~ At build time, by
xcrun metalandmetallib, into a.metallibembedded in the object file. No compiler runs or is trusted at run time, and GPU builds need Xcode's Metal toolchain. - ~~The shim's language?~~ Objective-C with ARC. It is one small file compiled by clang, with no extra dependency.