Ten million
particles, two GPUs,
one C++ core.
A step‑by‑step path to a Particle Life clone that runs on an Apple M2 through Metal compute and on an RTX 5090 through CUDA — starting from a GPU “hello world”, through a CPU baseline you can race the two machines with, all the way to a spatially‑accelerated 10‑million‑particle benchmark.
00 · Orientation
What we’re building, and the plan
Particle Life is deceptively small. You give N particle “types” an N×N matrix of attraction/repulsion coefficients, apply a short‑range force, integrate, and life‑like swarms fall out for free. The whole simulation is a few dozen lines of physics. The interesting part — and the reason it’s a perfect GPU teaching vehicle — is making it run on millions of particles in real time on two completely different architectures.
The reference behaviour we’re matching is Tom Mohr’s particle‑life‑app. We keep its exact force model and parameters, but rebuild the engine from scratch in C++ so we can target Metal and CUDA directly. The build climbs in deliberate stages, each one verifiable before the next:
| Stage | What runs | Why it exists |
|---|---|---|
| 02 | GPU hello‑world — a matmul on each device | Prove the toolchain compiles and the work truly lands on the GPU. |
| 04 | CPU Particle Life (single core → OpenMP) | A correct reference + the only fair way to race the two machines’ CPUs. |
| 05 | Metal compute on the M2, direct to screen | First GPU port; zero‑copy unified‑memory buffers shared by compute & render. |
| 06 | CUDA on the 5090, streamed to the Mac | Second backend; offscreen render + NVENC stream (X11 won’t cut it — we’ll see why). |
| 07 | Uniform grid on both | Kill the O(M²) all‑pairs cost; reach near‑O(M). |
| 08 | Blackwell tuning — clusters, DSM, CUDA graphs | Use the SM‑to‑SM features the 5090 actually has. |
| 09 | 10M particles | The payoff and the scoreboard. |
Metal’s native language is Objective‑C/Swift and CUDA’s is its own C++ dialect — but both expose a
first‑class C++ surface. On the Mac we use Apple’s official header‑only metal‑cpp (a zero‑overhead
1:1 wrapper over the Metal API). On the server we use nvcc with ordinary CUDA C++. That lets one
shared C++ codebase hold the model, the parameters and the grid logic, with two thin backends: a
.metal library and a set of .cu kernels. C++ is the only language that is native
to both sides.
- API
- Metal 4 (macOS 26)
- Memory
- Unified ~32 GB
- Copy model
- Zero‑copy shared
- Threadgroup mem
- ~32 KB
- Render
- CAMetalLayer, native
- API
- CUDA 13.x
- Arch
- GB202 · sm_120
- VRAM
- 32 GB GDDR7
- Bandwidth
- 1792 GB/s
- Shared/block
- up to 99 KB
The little swarm drifting behind the title is a real Particle Life simulation running in your browser — six types, a random interaction matrix, toroidal wrap. Same model, smaller numbers.
01 · Foundations
Toolchains, current as of 2026
Before any pixels move, get both compilers installed and confirm the version numbers, because both ecosystems moved recently and stale toolkits are the #1 cause of “sm_120 not recognized” and missing Metal 4 symbols.
macOS — M2
Metal 4 shipped at WWDC 2025 and lives in macOS 26 (“Tahoe”). You need a matching Xcode and the metal‑cpp headers, which Apple distributes as a single zip pinned to each OS/Xcode pair.
# Command-line tools (clang, metal, metallib, xcrun)
xcode-select --install
# Verify the Metal compiler is present
xcrun -sdk macosx metal --version
# metal-cpp: download the zip matching your macOS from
# https://developer.apple.com/metal/cpp/
# then unzip into your project, e.g. third_party/metal-cpp/
# It is header-only — there is nothing to build.
# Live GPU monitor (we'll use it to prove kernels ran on the GPU)
pip install asitop # graphical; needs sudo to read powermetrics
# or use the built-in:
sudo powermetrics --samplers gpu_power -i 500Arch Linux — RTX 5090
CUDA 12.8 (Jan 2025) was the first toolkit with full Blackwell support; CUDA 13.0 (Aug 2025)
covers everything Turing → Blackwell and is what we target. On Arch the cuda package pulls a
current 13.x toolkit. The open kernel modules are fine on Blackwell.
sudo pacman -S cuda nvidia-open nvidia-utils cmake gcc
sudo pacman -S nvtop # live per-SM utilisation
# btop with GPU panel is also great:
sudo pacman -S btop
# Confirm versions and that the GPU reports compute_cap 12.0
nvcc --version
nvidia-smi --query-gpu=name,driver_version,compute_cap,memory.total --format=csv
# Put CUDA on PATH (Arch installs under /opt/cuda)
export PATH=/opt/cuda/bin:$PATH
export LD_LIBRARY_PATH=/opt/cuda/lib64:$LD_LIBRARY_PATHIf nvcc rejects sm_120, you almost certainly have an old toolkit (some
repos ship a 12.0–12.4 era nvidia-cuda-toolkit). The 5090 is compute capability
12.0 and needs CUDA ≥ 12.8. Check with nvcc --list-gpu-arch — you should see
compute_120 in the list.
02 · Warm‑up
Hello, GPU: a matrix multiply you can see run
A matmul is the perfect first kernel: it’s embarrassingly parallel, trivially verifiable on the CPU, and heavy enough to light up a GPU monitor. We write it on both machines and, crucially, watch a tool confirm the work executed on the device — not silently on the CPU.
Both APIs tile the problem the same way, with different vocabulary. You launch a grid
of blocks (CUDA) / threadgroups (Metal); each contains many
threads. Inside, threads run in lockstep bundles — a warp of 32 on
NVIDIA, a SIMD‑group of 32 on Apple. Threads in the same block/threadgroup share fast
on‑chip memory (__shared__ / threadgroup) and can synchronise. Threads in
different blocks generally cannot — that independence is what lets the GPU schedule blocks across all
its SMs. Picking block/threadgroup size (often 256) is your first tuning knob.
2a · CUDA matmul — and the row/column question
We compute C = A·B for square n×n matrices. The naive kernel assigns one
thread to one output element C[row][col] and has it walk a row of A against a column of B.
A 2‑D matrix is stored as a flat 1‑D array, and there are two conventions for which index moves fastest in memory:
Row‑major (C, C++, NumPy default): consecutive elements of a row are adjacent.
Element (r,c) of an m×n matrix is at r*n + c.
Column‑major (Fortran, MATLAB, OpenGL, and cuBLAS): consecutive elements of a
column are adjacent. Element (r,c) is at c*m + r.
This isn’t academic: it decides your indexing arithmetic and your memory‑coalescing. On a GPU,
adjacent threads should touch adjacent addresses. If thread col reads B[k*n + col]
(row‑major B), neighbouring threads read neighbouring words → one coalesced transaction. Get the layout
wrong and every read is a separate transaction. We’ll keep everything row‑major in our
own kernels, then meet the one place that disagrees: cuBLAS.
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>
#define CHECK(x) do{ cudaError_t e=(x); if(e){ \
fprintf(stderr,"CUDA %s:%d %s\n",__FILE__,__LINE__,cudaGetErrorString(e)); \
exit(1);} }while(0)
// Row-major: A,B,C are n*n, element (r,c) lives at r*n + c.
// One thread computes one C element.
__global__ void matmul(const float* A, const float* B, float* C, int n){
int col = blockIdx.x * blockDim.x + threadIdx.x; // fastest index -> column
int row = blockIdx.y * blockDim.y + threadIdx.y;
if(row >= n || col >= n) return;
float acc = 0.f;
for(int k=0;k<n;++k)
acc += A[row*n + k] * B[k*n + col]; // walk row of A, column of B
C[row*n + col] = acc;
}
int main(){
const int n = 2048;
size_t bytes = (size_t)n*n*sizeof(float);
float *hA=(float*)malloc(bytes), *hB=(float*)malloc(bytes), *hC=(float*)malloc(bytes);
for(int i=0;i<n*n;++i){ hA[i]=1.0f; hB[i]=2.0f; } // expect every C = n*2
float *dA,*dB,*dC;
CHECK(cudaMalloc(&dA,bytes)); CHECK(cudaMalloc(&dB,bytes)); CHECK(cudaMalloc(&dC,bytes));
CHECK(cudaMemcpy(dA,hA,bytes,cudaMemcpyHostToDevice));
CHECK(cudaMemcpy(dB,hB,bytes,cudaMemcpyHostToDevice));
dim3 block(16,16); // 256 threads
dim3 grid((n+15)/16,(n+15)/16);
cudaEvent_t t0,t1; cudaEventCreate(&t0); cudaEventCreate(&t1);
cudaEventRecord(t0);
matmul<<<grid,block>>>(dA,dB,dC,n);
cudaEventRecord(t1); CHECK(cudaDeviceSynchronize());
float ms=0; cudaEventElapsedTime(&ms,t0,t1);
CHECK(cudaMemcpy(hC,dC,bytes,cudaMemcpyDeviceToHost));
double gflops = 2.0*n*n*n / (ms*1e6);
printf("C[0]=%.1f (expect %d) | %.2f ms | %.1f GFLOP/s\n", hC[0], n*2, ms, gflops);
return 0;
}# Native cubin for Blackwell:
nvcc -O3 -arch=sm_120 hello_mm.cu -o hello_mm
# Portable form: real sm_120 cubin + embedded PTX so future drivers can JIT it
nvcc -O3 -gencode arch=compute_120,code=sm_120 \
-gencode arch=compute_120,code=compute_120 hello_mm.cu -o hello_mm
./hello_mmThe moment you reach for the optimized library, the convention flips. cublasSgemm assumes
column‑major storage. A row‑major m×n buffer, reinterpreted as column‑major, is its
transpose. Rather than physically transpose your data, use the identity
(A·B)ᵀ = Bᵀ·Aᵀ: swap the operands and the dimensions. To get a row‑major
C = A·B with A being M×K and B being K×N:
// Treat our row-major buffers directly; cuBLAS sees them column-major (= transposed).
// We ask it for C^T = B^T A^T, which IS our row-major C in memory.
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N,
N, M, K, // m,n,k in cuBLAS' view
&alpha,
dB, N, // "A" = B, leading dim N
dA, K, // "B" = A, leading dim K
&beta,
dC, N); // C, leading dim N -> row-major MxNInternalise this once and you’ll stop fighting every BLAS/LAPACK call you ever make from C++.
A printed result isn’t proof — a CPU fallback could produce it. In a second terminal run
nvtop (or nvidia-smi dmon -s u) and watch the SM% spike during the launch.
For kernel‑level proof, profile it: nsys profile ./hello_mm shows the matmul
kernel on the device timeline, and ncu ./hello_mm reports its achieved occupancy. (Note: the
old nvprof was removed in CUDA 13 — use Nsight.)
2b · Metal matmul — the same idea in metal‑cpp
The Metal kernel is almost identical; the host orchestration is where Metal differs. You compile the
.metal shader offline into a .metallib, then load it from C++.
#include <metal_stdlib>
using namespace metal;
kernel void matmul(device const float* A [[buffer(0)]],
device const float* B [[buffer(1)]],
device float* C [[buffer(2)]],
constant uint& n [[buffer(3)]],
uint2 gid [[thread_position_in_grid]])
{
uint col = gid.x, row = gid.y;
if(row >= n || col >= n) return;
float acc = 0.f;
for(uint k=0;k<n;++k)
acc += A[row*n + k] * B[k*n + col]; // same row-major math as CUDA
C[row*n + col] = acc;
}xcrun -sdk macosx metal -c matmul.metal -o matmul.air
xcrun -sdk macosx metallib matmul.air -o default.metallib// Exactly ONE .cpp in the project defines these before including the headers:
#define NS_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#include <Foundation/Foundation.hpp>
#include <Metal/Metal.hpp>
#include <cstdio>
int main(){
MTL::Device* dev = MTL::CreateSystemDefaultDevice();
// Load the precompiled library and grab the kernel
NS::Error* err = nullptr;
auto url = NS::URL::fileURLWithPath(NS::String::string("default.metallib",
NS::UTF8StringEncoding));
MTL::Library* lib = dev->newLibrary(url, &err);
MTL::Function* fn = lib->newFunction(NS::String::string("matmul",
NS::UTF8StringEncoding));
MTL::ComputePipelineState* pso = dev->newComputePipelineState(fn, &err);
MTL::CommandQueue* q = dev->newCommandQueue();
const uint32_t n = 2048; size_t bytes = (size_t)n*n*sizeof(float);
// StorageModeShared: ONE allocation visible to CPU and GPU (unified memory).
MTL::Buffer* A = dev->newBuffer(bytes, MTL::ResourceStorageModeShared);
MTL::Buffer* B = dev->newBuffer(bytes, MTL::ResourceStorageModeShared);
MTL::Buffer* C = dev->newBuffer(bytes, MTL::ResourceStorageModeShared);
auto* a=(float*)A->contents(); auto* b=(float*)B->contents();
for(uint32_t i=0;i<n*n;++i){ a[i]=1.f; b[i]=2.f; } // write straight into GPU memory
MTL::CommandBuffer* cb = q->commandBuffer();
MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
enc->setComputePipelineState(pso);
enc->setBuffer(A,0,0); enc->setBuffer(B,0,1); enc->setBuffer(C,0,2);
enc->setBytes(&n,sizeof(n),3);
MTL::Size grid(n,n,1), tg(16,16,1); // 256 threads/threadgroup
enc->dispatchThreads(grid, tg); // non-uniform grid: API clamps edges
enc->endEncoding();
cb->commit(); cb->waitUntilCompleted();
double ms = (cb->GPUEndTime() - cb->GPUStartTime())*1e3;
printf("C[0]=%.1f (expect %u) | %.2f ms\n", ((float*)C->contents())[0], n*2, ms);
return 0;
}On Apple silicon, StorageModeShared means the buffer lives in unified memory:
the CPU loop above writes directly into the same bytes the GPU reads. No upload, no
cudaMemcpy. Hold onto that idea — it’s the backbone of the Metal renderer later.
Run sudo asitop (or sudo powermetrics --samplers gpu_power) and watch GPU
residency and frequency jump while the program runs. For a kernel‑level timeline, capture it in
Instruments → Metal System Trace. The GPUEndTime − GPUStartTime we printed is the
device’s own clock — further confirmation the work was scheduled on the GPU.
03 · The physics
The Particle Life model, stated exactly
Everything downstream is a re‑implementation of these few equations on faster hardware, so it pays to pin them down precisely and match the reference app rather than improvise.
Each particle i has a position xᵢ, velocity vᵢ, and an integer
type in [0, N). The dynamics come from three ingredients:
- an N×N matrix
a[ti][tj]of attraction coefficients in[−1, 1]— deliberately asymmetric (red can chase green while green flees red); - a force function of normalized distance that has a fixed short‑range repulsion zone;
- simple damped integration on a wrap‑around (toroidal) world.
Let r be the distance between two particles divided by the interaction radius
rmax (so r ∈ [0, ∞), and the force is zero beyond r = 1). With a
repulsion‑zone fraction β (the app calls it rmin; default 0.3) and the
matrix coefficient a:
f(r, a) =
r/β − 1 if r < β (always repulsive)
a · (1 − |2r − 1 − β| / (1 − β)) if β ≤ r < 1 (triangular hat)
0 if r ≥ 1
The first branch is a hard, type‑independent core repulsion that keeps particles from collapsing. The
middle branch is a triangle peaking at r = (1+β)/2, scaled by a: positive
a attracts, negative repels. Past rmax, nothing — and that zero is exactly what
makes the spatial grid in §07 valid.
Below β the force is hard repulsion regardless of a (the core that stops
collapse). Between β and 1 it’s a triangle scaled by a — flip a negative to watch
attraction become repulsion. Past r = 1 it’s flat zero: that’s why neighbours beyond
rmax can be ignored entirely.
Sum the force over neighbours to get an acceleration, scale it by rmax · forceFactor, then
integrate with semi‑implicit (symplectic) Euler — update velocity first, then position
with the new velocity. It’s one line different from explicit Euler and dramatically more stable:
v ← v + acc · dt
v ← v · friction // velocity damping
x ← wrap(x + v · dt)
Friction can be written two equivalent ways. The reference app multiplies velocity by a
fixed coefficient each step (assuming 60 fps). The cleaner, framerate‑independent form is a velocity
half‑life t½: friction = pow(0.5, dt / t½). Pick one and be explicit;
for behaviour identical to particle‑life‑app, use the fixed per‑step multiply at 60 fps.
Toroidal wrap: the world is a torus — positions in [−1, 1] wrap around.
When measuring the displacement between two particles, take the shortest of the direct and
wrapped deltas on each axis (subtract the world width if the gap exceeds half the width). Forget this and
particles ignore neighbours across the seam.
The obvious layout is an array of struct Particle{ float2 pos, vel; int type; } — “array of
structs” (AoS). Don’t. GPUs want struct of arrays (SoA): separate
posX[], posY[], velX[], velY[], type[].
When 32 neighbouring threads each read posX[i], SoA gives one contiguous, fully‑coalesced
memory transaction; AoS scatters those reads across struct‑sized strides and wastes most of every cache
line. We use SoA everywhere from here on — and it’s exactly the same arrays the CPU baseline will use,
so the comparison is apples‑to‑apples.
04 · Version 1
First runnable simulationThe CPU baseline — and a fair race between the two machines
Before either GPU, write the simulation on the CPU. Two reasons: it’s the ground truth every GPU port must match, and the CPU is the only component these two very different boxes share, so it’s the honest way to ask “which machine is faster?” at the single‑thread and multi‑thread level. We’ll start single‑threaded for clarity, then parallelise with OpenMP.
Shared state, SoA, used unchanged by every later backend:
#pragma once
#include <vector>
#include <cstdint>
#include <cmath>
struct Params {
int N = 6; // number of types
float rmax = 0.10f; // interaction radius (world units, world is [-1,1])
float beta = 0.30f; // repulsion-zone fraction (a.k.a. rmin)
float forceFactor = 1.0f;
float friction = 0.85f; // per-step velocity multiply (60 fps reference)
float dt = 0.016f;
float world = 2.0f; // [-1,1] -> width 2
};
struct Sim { // Struct-of-Arrays
std::vector<float> posX, posY, velX, velY;
std::vector<uint8_t> type;
std::vector<float> mat; // N*N attraction matrix, row-major: mat[ti*N+tj]
size_t M = 0; // particle count
};
// The exact tom-mohr piecewise force. r is distance/rmax.
static inline float force(float r, float a, float beta){
if (r < beta) return r/beta - 1.0f; // core repulsion
if (r < 1.0f) return a * (1.0f - fabsf(2.0f*r - 1.0f - beta)/(1.0f - beta));
return 0.0f;
}#include "sim.hpp"
// shortest signed delta on a torus of given width
static inline float wrapDelta(float d, float w){
if (d > 0.5f*w) d -= w;
if (d < -0.5f*w) d += w;
return d;
}
static inline float wrapPos(float x, float w){
if (x > 0.5f*w) x -= w;
if (x < -0.5f*w) x += w;
return x;
}
// Read from `cur`, write the integrated state into `next`; the caller swaps. So the
// force on every i uses start-of-step positions, exactly like the GPU backends.
void cpuStep(const Sim& cur, Sim& next, const Params& p){
const int N = p.N; const float rmax = p.rmax, w = p.world; const float rmax2 = rmax*rmax;
#pragma omp parallel for schedule(static)
for (long i = 0; i < (long)cur.M; ++i){
float xi = cur.posX[i], yi = cur.posY[i];
int ti = cur.type[i];
float fx = 0.f, fy = 0.f;
for (size_t j = 0; j < cur.M; ++j){
if (j == (size_t)i) continue;
float dx = wrapDelta(cur.posX[j]-xi, w);
float dy = wrapDelta(cur.posY[j]-yi, w);
float d2 = dx*dx + dy*dy;
if (d2 >= rmax2 || d2 == 0.f) continue; // outside radius -> no force
float dist = sqrtf(d2);
float r = dist / rmax;
float a = cur.mat[ti*N + cur.type[j]];
float f = force(r, a, p.beta);
fx += f * dx/dist; // unit direction * magnitude
fy += f * dy/dist;
}
fx *= rmax * p.forceFactor;
fy *= rmax * p.forceFactor;
// semi-implicit Euler with damping
float vx = (cur.velX[i] + fx*p.dt) * p.friction;
float vy = (cur.velY[i] + fy*p.dt) * p.friction;
next.velX[i] = vx; next.velY[i] = vy;
next.posX[i] = wrapPos(xi + vx*p.dt, w);
next.posY[i] = wrapPos(yi + vy*p.dt, w);
next.type[i] = cur.type[i]; // type is constant
}
}The force on i must use every other particle’s position from the start of the step. If
you integrate in place into a single array, a parallel for lets one thread read a neighbour’s
position that another thread has already advanced — a mild, nondeterministic order‑dependence. The fix is
ping‑pong (double) buffering: read from cur, write into next,
then swap (golden rule #4). That makes the step order‑independent and mirrors the GPU
backends, which are inherently double‑buffered — so the CPU stays a faithful ground truth. The grid
variant cpuStepGrid has the identical signature and produces matching dynamics
(--verify checks max|Δpos| < 1e‑3).
Drive it from a tiny harness that also serves as the benchmark. Build with OpenMP on both machines:
# Arch (server CPU):
g++ -O3 -march=native -fopenmp main.cpp cpu_step.cpp -o plife_cpu
# macOS (Apple needs libomp; clang doesn't bundle it):
brew install libomp
clang++ -O3 -std=c++17 -Xpreprocessor -fopenmp \
-I$(brew --prefix libomp)/include -L$(brew --prefix libomp)/lib -lomp \
main.cpp cpu_step.cpp -o plife_cpu
# Race them: fixed particle count, fixed steps, report particles*steps/sec
OMP_NUM_THREADS=1 ./plife_cpu --m 20000 --steps 300 # single-thread duel
OMP_NUM_THREADS=$(nproc) ./plife_cpu --m 20000 --steps 300 # all-core duelRun identical --m and --steps on both. Single‑thread numbers expose raw IPC and
memory latency (the M2’s big cores are excellent here); all‑core numbers expose core count and bandwidth
(the server’s desktop CPU usually pulls ahead). Record particle‑interactions/second =
M·(M−1)·steps / seconds. Keep this number — when the GPU versions land, the speedup over
this baseline is the headline result of the whole project.
At this point you have a real, correct Particle Life you can watch (dump frames to PPM, or wire up the same GLFW window we build next). It just tops out around tens of thousands of particles — which is precisely the motivation for everything that follows.
05 · Version 2
First GPU port · M2 · direct screenMetal compute, drawn straight to the Mac’s screen
Now the same physics on the M2’s GPU, with the simulation and the renderer sharing one set of unified‑memory buffers — the compute pass writes positions and the render pass reads them in the same command buffer, with no copy in between.
Windowing
The least‑friction way to get a Metal surface from C++ is GLFW with
GLFW_NO_API: create the window, fetch its NSWindow via
glfwGetCocoaWindow, and attach a CAMetalLayer whose drawables you render into.
(Pure Cocoa is the zero‑dependency alternative.) Each frame you ask the layer for the
nextDrawable and use its texture as the render target. Attaching the layer is the one place
that must touch Objective‑C, so it lives in a tiny .mm bridge; everything else stays pure
C++/metal‑cpp.
metal compilerThe offline xcrun metal / metallib tools ship with the full Xcode, not
the Command Line Tools. If xcrun -sdk macosx metal --version errors with “unable to find
utility metal”, don’t fight it — compile the shader from source at runtime instead:
read the .metal file and hand the string to
MTL::Device::newLibrary(source, …). No .metallib, no full Xcode, and the
.metal files stay the single source of truth. The finished tree does exactly this
(metal/shader_loader.hpp), which is why it builds on a stock Command‑Line‑Tools Mac.
// Compile shaders from source so the build needs no offline `metal` CLI.
inline MTL::Library* buildLibrary(MTL::Device* dev, const std::string& src){
NS::Error* err = nullptr;
auto* s = NS::String::string(src.c_str(), NS::UTF8StringEncoding);
MTL::Library* lib = dev->newLibrary(s, nullptr, &err); // runtime compile
if(!lib){ fprintf(stderr, "shader: %s\n", err->localizedDescription()->utf8String()); exit(3); }
return lib;
}
inline MTL::ComputePipelineState* computePSO(MTL::Device* dev, MTL::Library* lib, const char* fn){
auto* f = lib->newFunction(NS::String::string(fn, NS::UTF8StringEncoding));
NS::Error* err = nullptr;
return dev->newComputePipelineState(f, &err);
}#include <metal_stdlib>
using namespace metal;
struct Params { int N; float rmax, beta, forceFactor, friction, dt, world; };
inline float fwrap(float d, float w){ d -= w*round(d/w); return d; } // shortest delta
inline float force(float r, float a, float beta){
if (r < beta) return r/beta - 1.0f;
if (r < 1.0f) return a*(1.0f - fabs(2.0f*r-1.0f-beta)/(1.0f-beta));
return 0.0f;
}
kernel void step(device const float* inX [[buffer(0)]],
device const float* inY [[buffer(1)]],
device const float* inVX [[buffer(2)]],
device const float* inVY [[buffer(3)]],
device const uchar* type [[buffer(4)]],
device const float* mat [[buffer(5)]], // N*N
device float* outX [[buffer(6)]],
device float* outY [[buffer(7)]],
device float* outVX[[buffer(8)]],
device float* outVY[[buffer(9)]],
constant Params& P [[buffer(10)]],
constant uint& M [[buffer(11)]],
uint i [[thread_position_in_grid]])
{
if (i >= M) return;
float xi=inX[i], yi=inY[i]; int ti=type[i];
float fx=0, fy=0; float rmax2=P.rmax*P.rmax;
for (uint j=0;j<M;++j){
if (j==i) continue;
float dx=fwrap(inX[j]-xi,P.world), dy=fwrap(inY[j]-yi,P.world);
float d2=dx*dx+dy*dy;
if (d2>=rmax2 || d2==0) continue;
float dist=sqrt(d2), r=dist/P.rmax;
float f=force(r, mat[ti*P.N+type[j]], P.beta);
fx+=f*dx/dist; fy+=f*dy/dist;
}
fx*=P.rmax*P.forceFactor; fy*=P.rmax*P.forceFactor;
float vx=(inVX[i]+fx*P.dt)*P.friction;
float vy=(inVY[i]+fy*P.dt)*P.friction;
outVX[i]=vx; outVY[i]=vy;
outX[i]=fwrap(xi+vx*P.dt,P.world); // fwrap centres on 0 -> world [-1,1]
outY[i]=fwrap(yi+vy*P.dt,P.world);
}The render side is two tiny shaders that draw each particle as an instanced point, coloured by type.
Because positions live in a StorageModeShared buffer, the vertex shader reads the very bytes
the compute kernel just wrote:
#include <metal_stdlib>
using namespace metal;
struct VSOut { float4 pos [[position]]; float psize [[point_size]]; float4 col; };
constant float3 palette[6] = {
{1.0,0.39,0.39},{1.0,0.71,0.33},{0.45,0.90,0.66},
{0.34,0.83,0.90},{0.43,0.66,1.0},{0.73,0.59,0.97}
};
vertex VSOut vmain(uint vid [[vertex_id]],
device const float* X [[buffer(0)]],
device const float* Y [[buffer(1)]],
device const uchar* T [[buffer(2)]],
constant float& psize [[buffer(3)]]){
VSOut o;
o.pos = float4(X[vid], Y[vid], 0, 1); // world already in clip range [-1,1]
o.psize = psize;
o.col = float4(palette[T[vid] % 6], 1.0);
return o;
}
// round the square point sprite into a soft disc
fragment float4 fmain(VSOut in [[stage_in]], float2 pc [[point_coord]]){
float d = length(pc - float2(0.5));
if (d > 0.5) discard_fragment();
return float4(in.col.rgb, smoothstep(0.5, 0.32, d));
}// per frame:
MTL::CommandBuffer* cb = queue->commandBuffer();
// (1) physics
auto* ce = cb->computeCommandEncoder();
ce->setComputePipelineState(stepPSO);
ce->setBuffer(curX,0,0); ce->setBuffer(curY,0,1);
ce->setBuffer(curVX,0,2); ce->setBuffer(curVY,0,3);
ce->setBuffer(typeBuf,0,4); ce->setBuffer(matBuf,0,5);
ce->setBuffer(nextX,0,6); ce->setBuffer(nextY,0,7);
ce->setBuffer(nextVX,0,8); ce->setBuffer(nextVY,0,9);
ce->setBytes(¶ms,sizeof(params),10); ce->setBytes(&M,sizeof(M),11);
ce->dispatchThreads(MTL::Size(M,1,1), MTL::Size(256,1,1));
ce->endEncoding();
// (2) render — reads the buffers the compute pass just produced
auto* rpd = MTL::RenderPassDescriptor::renderPassDescriptor();
rpd->colorAttachments()->object(0)->setTexture(drawable->texture());
rpd->colorAttachments()->object(0)->setLoadAction(MTL::LoadActionClear);
rpd->colorAttachments()->object(0)->setClearColor(MTL::ClearColor(0.04,0.05,0.07,1));
auto* re = cb->renderCommandEncoder(rpd);
re->setRenderPipelineState(drawPSO);
re->setVertexBuffer(nextX,0,0); re->setVertexBuffer(nextY,0,1);
re->setVertexBuffer(typeBuf,0,2);
re->drawPrimitives(MTL::PrimitiveTypePoint, 0, M);
re->endEncoding();
cb->presentDrawable(drawable);
cb->commit();
std::swap(curX,nextX); std::swap(curY,nextY); // ping-pong
std::swap(curVX,nextVX); std::swap(curVY,nextVY);Metal automatically tracks that the render pass depends on the buffers the compute pass wrote, so the two
passes serialise correctly inside one command buffer with no manual fences and, critically, no staging
copy. On a discrete GPU you’d round‑trip positions through a vertex buffer; on unified memory the compute
output is the vertex input. (Under Metal 4 you can make the residency and barriers explicit with
MTL4ComputeCommandEncoder and residency sets, but the classic encoder shown here is fully
valid on the M2 and easier to read.)
This naive O(M²) Metal version comfortably handles ~100k particles in real time — a 5–20× jump over the CPU baseline already, and you’re watching it on the Mac’s own display.
06 · Version 3
Second GPU port · 5090 · streamedCUDA on the 5090, and getting the picture back to the Mac
The kernel port is almost mechanical. The genuinely interesting engineering is display: the server is headless‑ish and you want to watch it on the Mac. We’ll explain why the obvious approach (X11 forwarding) fails, then set up the approach that works.
struct Params { int N; float rmax, beta, forceFactor, friction, dt, world; };
__device__ __forceinline__ float fwrap(float d, float w){ d -= w*rintf(d/w); return d; }
__device__ __forceinline__ float force(float r, float a, float beta){
if (r < beta) return r/beta - 1.0f;
if (r < 1.0f) return a*(1.0f - fabsf(2.0f*r-1.0f-beta)/(1.0f-beta));
return 0.0f;
}
__global__ void step(const float* inX,const float* inY,
const float* inVX,const float* inVY,
const unsigned char* type,const float* mat,
float* outX,float* outY,float* outVX,float* outVY,
Params P, unsigned M)
{
unsigned i = blockIdx.x*blockDim.x + threadIdx.x;
if (i >= M) return;
float xi=inX[i], yi=inY[i]; int ti=type[i];
float fx=0,fy=0; float rmax2=P.rmax*P.rmax;
for (unsigned j=0;j<M;++j){
if (j==i) continue;
float dx=fwrap(inX[j]-xi,P.world), dy=fwrap(inY[j]-yi,P.world);
float d2=dx*dx+dy*dy;
if (d2>=rmax2 || d2==0.f) continue;
float dist=sqrtf(d2), r=dist/P.rmax;
float f=force(r, mat[ti*P.N+type[j]], P.beta);
fx+=f*dx/dist; fy+=f*dy/dist;
}
fx*=P.rmax*P.forceFactor; fy*=P.rmax*P.forceFactor;
float vx=(inVX[i]+fx*P.dt)*P.friction;
float vy=(inVY[i]+fy*P.dt)*P.friction;
outVX[i]=vx; outVY[i]=vy;
outX[i]=fwrap(xi+vx*P.dt,P.world);
outY[i]=fwrap(yi+vy*P.dt,P.world);
}
// launch: step<<<(M+255)/256, 256>>>(...); then swap cur/next pointersRendering on the server: CUDA ↔ OpenGL interop (no host round‑trip)
Mirror the Mac’s zero‑copy idea with graphics interop. Create an OpenGL vertex buffer, register it once with CUDA, and each frame let the kernel write positions directly into that VBO; then draw it as instanced points into an offscreen framebuffer.
cudaGraphicsResource* vboRes;
cudaGraphicsGLRegisterBuffer(&vboRes, gl_vbo, cudaGraphicsRegisterFlagsWriteDiscard);
// per frame:
cudaGraphicsMapResources(1, &vboRes);
float2* dPos; size_t nbytes;
cudaGraphicsResourceGetMappedPointer((void**)&dPos, &nbytes, vboRes);
// ... run step kernel writing into dPos (interleaved) or keep SoA + a pack kernel ...
cudaGraphicsUnmapResources(1, &vboRes);
// glDrawArrays(GL_POINTS, 0, M) into an FBOssh -X forwards the X protocol, and remote GLX is indirect: the GLX wire
protocol tops out at OpenGL 1.4, and core‑profile context creation
(GLX_ARB_create_context_profile) isn’t available over it. A modern renderer asking for an
OpenGL 3.3+ core context gets BadValue/GLXBadContext on
glXCreateNewContext and dies. You weren’t doing anything wrong — forwarding GPU‑accelerated
GL over X11 fundamentally doesn’t work for modern contexts. Don’t go down this road.
Render offscreen on the 5090, hardware‑encode the framebuffer with the GPU’s NVENC block, and send a low‑latency video stream to a thin client on the Mac that decodes with VideoToolbox. You don’t have to build this yourself: Sunshine (open‑source host, NVENC + framebuffer capture) paired with Moonlight (client, available for macOS) is exactly this pipeline and gets you sub‑frame latency on a wired LAN. It’s the same tech stack used for game streaming, tuned for low latency.
| Option | Latency | Verdict |
|---|---|---|
| X11 forwarding of a GL window | — | Broken for modern GL (indirect GLX). Avoid. |
| TV / dummy‑HDMI plug on the server | lowest (local) | Trivial & correct; you just don’t see it on the Mac. Great for debugging. |
| Sunshine → Moonlight (NVENC) | sub‑frame on wired LAN | Recommended. Robust, GPU‑accelerated, macOS client exists. |
| Custom NVENC + WebRTC client | tightest control | Build only if you want the encoder fused into your render loop. |
# On the Arch server:
sudo pacman -S sunshine # or from the LizardByte release
# A headless box needs a virtual display so there is a framebuffer to capture:
# - plug in a cheap HDMI/EDID "dummy" dongle, OR
# - configure a virtual display in xorg.conf / use the KMS capture backend.
sunshine # then pair from the client
# On the Mac:
brew install --cask moonlight # pair to the server's IP, pick the app/desktop
# Use wired Ethernet + Moonlight's low-latency settings for the lowest delay.Keep the dummy‑plug + local render path around as your fast debug loop, and switch to Sunshine/Moonlight when you want to actually watch 10M particles swarm from the couch.
07 · Optimization 3.1
Both platforms · O(M²) → ~O(M)The uniform grid: stop comparing every pair
The force is exactly zero beyond rmax, yet the naive kernel still tests all
M−1 other particles for every particle. With short‑range forces, almost every test is wasted.
The fix is the single most important optimization in the whole project and it’s identical in spirit on
Metal and CUDA: bin particles into a grid of cells sized rmax, and only look at the 3×3 block
of neighbouring cells.
Choose a cell edge of rmax. Then any particle within the interaction radius must lie in the
particle’s own cell or one of its 8 neighbours (2‑D). The classic GPU recipe (Green,
“Particle Simulation using CUDA”) is four passes per step:
- Hash — each particle computes its cell index
cell = cy*gridW + cx. - Sort — sort particle indices by cell key (a GPU radix sort), so all particles in a cell become contiguous.
- Cell ranges — scan the sorted keys; where the key changes, record
cellStart[c]andcellEnd[c]. - Force — each particle loops over its 3×3 neighbour cells, iterating only
[cellStart, cellEnd)in each.
This turns the inner loop from “all M” into “the handful of particles actually nearby”, i.e. near‑O(M) when density is bounded.
On CUDA you don’t write the sort yourself — CUB ships
cub::DeviceRadixSort::SortPairs (keys = cell, values = particle index). It’s O(M) in passes,
fully parallel, and stable; sort only the bits you need (end_bit = ceil(log2(numCells))).
On Metal there’s no general key/value sort, but you don’t need a full LSD radix sort
either. Because the number of cells is small and independent of M, a counting sort is
simpler and stays entirely on the GPU in one command buffer: (1) a kernel hashes each particle and
atomically bumps a per‑cell counter; (2) a one‑thread kernel exclusive‑prefix‑sums those counts into
cellStart; (3) a scatter kernel atomically claims each particle’s slot, writing the
cell‑ordered index array; (4) the force kernel reads [cellStart[c], cellStart[c+1]). That’s
what the finished Metal backend does (metal/plife.metal:
hashCount → scanCells → scatter → forceGrid) — verified to reproduce the CPU dynamics to six
decimals. (A full LSD radix sort with reorder‑for‑coalescing is the textbook alternative and a good
exercise when the cell count grows large.)
#include <cub/cub.cuh>
__global__ void hashCells(const float* X,const float* Y,unsigned M,
float world,float cell,int gw,int gh,
unsigned* cellKey,unsigned* idx){
unsigned i = blockIdx.x*blockDim.x+threadIdx.x; if(i>=M) return;
int cx = min(gw-1,(int)((X[i]+world*0.5f)/cell));
int cy = min(gh-1,(int)((Y[i]+world*0.5f)/cell));
cellKey[i] = (unsigned)(cy*gw + cx);
idx[i] = i;
}
__global__ void findRanges(const unsigned* keySorted,unsigned M,
unsigned* cellStart,unsigned* cellEnd){
unsigned i = blockIdx.x*blockDim.x+threadIdx.x; if(i>=M) return;
unsigned k = keySorted[i];
if (i==0 || k != keySorted[i-1]) cellStart[k] = i;
if (i==M-1 || k != keySorted[i+1]) cellEnd[k] = i+1;
}
// Force pass: particle 'a' is the sorted slot; gather via idxSorted[a]->original.
__global__ void forceGrid(const float* X,const float* Y,
const float* VX,const float* VY,
const unsigned char* T,const float* mat,
const unsigned* idxSorted,
const unsigned* cellStart,const unsigned* cellEnd,
float* oX,float* oY,float* oVX,float* oVY,
Params P,unsigned M,float cell,int gw,int gh){
unsigned a = blockIdx.x*blockDim.x+threadIdx.x; if(a>=M) return;
unsigned i = idxSorted[a];
float xi=X[i], yi=Y[i]; int ti=T[i];
int cx=min(gw-1,(int)((xi+P.world*0.5f)/cell));
int cy=min(gh-1,(int)((yi+P.world*0.5f)/cell));
float fx=0,fy=0,rmax2=P.rmax*P.rmax;
for(int oy=-1;oy<=1;++oy) for(int ox=-1;ox<=1;++ox){
int nx=(cx+ox+gw)%gw, ny=(cy+oy+gh)%gh; // toroidal neighbour cell
unsigned c=ny*gw+nx, s=cellStart[c], e=cellEnd[c];
for(unsigned b=s;b<e;++b){
unsigned j=idxSorted[b]; if(j==i) continue;
float dx=fwrap(X[j]-xi,P.world), dy=fwrap(Y[j]-yi,P.world);
float d2=dx*dx+dy*dy; if(d2>=rmax2||d2==0.f) continue;
float dist=sqrtf(d2), r=dist/P.rmax;
float f=force(r, mat[ti*P.N+T[j]], P.beta);
fx+=f*dx/dist; fy+=f*dy/dist;
}
}
fx*=P.rmax*P.forceFactor; fy*=P.rmax*P.forceFactor;
float vx=(VX[i]+fx*P.dt)*P.friction, vy=(VY[i]+fy*P.dt)*P.friction;
oVX[i]=vx; oVY[i]=vy;
oX[i]=fwrap(xi+vx*P.dt,P.world); oY[i]=fwrap(yi+vy*P.dt,P.world);
}
// host, per frame:
// hashCells<<<...>>>(...);
// cub::DeviceRadixSort::SortPairs(tmp, tmpBytes, keyIn,keyOut, idxIn,idxOut,
// M, 0, endBit);
// cudaMemset(cellStart,0,nc*4); cudaMemset(cellEnd,0,nc*4); // empty cells: start==end -> skipped
// findRanges<<<...>>>(keyOut,M,cellStart,cellEnd);
// forceGrid<<<...>>>(...);Within the force pass, threads in a block whose particles share neighbour cells re‑read the same
neighbours from global memory. Cooperatively stage a neighbour cell’s particles into
__shared__ (CUDA) / threadgroup (Metal) memory once, then have the whole block
read from there. This is the classic N‑body tiling, now bounded to local cells. Budget the tile to fit:
the M2 gives ~32 KB of threadgroup memory; sm_120 allows up to 99 KB per block out of
128 KB per SM. Keep the small N×N matrix in constant memory so it’s broadcast to every thread for
free.
With the grid in place both machines jump from “tens of thousands” to “millions” of particles interactively. This is also your benchmark centrepiece: run naive vs. grid at M = 10⁴, 10⁵, 10⁶, 10⁷ and plot the crossover.
08 · Optimization 3.2
CUDA‑specific · sm_120Blackwell tuning: the cluster features the 5090 actually has
You asked specifically about the H100‑style “compute clusters”. Good news, with one important caveat: the consumer RTX 5090 does support thread‑block clusters and Distributed Shared Memory — but it lacks the datacenter‑only acceleration around them. Knowing the line between the two saves you from copying code that won’t run.
NVIDIA’s Blackwell Tuning Guide and CUDA C++ Programming Guide confirm that thread‑block clusters and
Distributed Shared Memory (DSM) are available on Blackwell including compute capability 12.0, and this has
been reproduced on an actual RTX 5090: __cluster_dims__, cudaLaunchKernelEx with
a cluster‑dimension attribute, cluster.sync(), and cluster.map_shared_rank() all
work, with a portable cluster size of 8 blocks. DSM lets one block read, write, and atomically update
another block’s shared memory within the same cluster, over the fast SM‑to‑SM network instead of
going out to L2.
The grid force pass re‑reads “halo” particles from neighbouring cells. Make a cluster of blocks each own a contiguous strip of cells; each block stages its cells’ particles into shared memory, and exposes them to its cluster siblings through DSM. A block then reads its neighbours’ particles directly from a sibling’s shared memory — cutting the global‑memory traffic for halo cells. This is a genuine win only when that halo traffic dominates (very high particle counts); measure before committing to it.
#include <cooperative_groups.h>
namespace cg = cooperative_groups;
// 4 blocks per cluster; each block owns one cell-strip, shares it via DSM.
__global__ void __cluster_dims__(4,1,1) forceCluster(/* ...buffers... */){
cg::cluster_group cluster = cg::this_cluster();
extern __shared__ float tile[]; // this block's staged particles
// 1) load my cells' particles into my own shared 'tile'
// ... fill tile[] ...
cluster.sync(); // all siblings have published their tiles
// 2) read a neighbour block's shared memory directly:
unsigned myRank = cluster.block_rank();
float* neighborTile = cluster.map_shared_rank(tile, myRank ^ 1);
// ... accumulate forces using neighborTile without touching global memory ...
cluster.sync(); // before anyone exits / reuses shared mem
}
// launch with cudaLaunchKernelEx so you can set/verify the cluster dimension:
cudaLaunchConfig_t cfg = {};
cfg.gridDim = grid; cfg.blockDim = block; cfg.dynamicSmemBytes = tileBytes;
cudaLaunchAttribute attr[1];
attr[0].id = cudaLaunchAttributeClusterDimension;
attr[0].val.clusterDim = {4,1,1};
cfg.attrs = attr; cfg.numAttrs = 1;
cudaLaunchKernelEx(&cfg, forceCluster /*, args... */);The 5090 does not expose the datacenter accelerated MMA path: no tcgen05 /
2‑SM UMMA, no wgmma, and no TMA multicast (multicast::cluster)
or cluster‑scope TMA destinations. Those are sm_90a/sm_100a targets; there is no
usable accelerated‑MMA feature set on sm_120. Code lifted from CUTLASS GEMM examples for
Hopper/datacenter Blackwell will fail to run. Basic cp.async /
cuda::memcpy_async pipelines, and even basic CTA‑scope TMA
(cp.async.bulk.tensor), are present — but plain async copies are all this workload
needs. And tensor cores are irrelevant here: Particle Life is FP32 gather/elementwise, not GEMM.
Every frame launches the same fixed sequence — hash → sort → ranges → reorder → force → integrate —
60+ times a second. At those rates the CPU‑side launch overhead becomes measurable. Capture the sequence
once into a cudaGraph_t and relaunch the instantiated graph with a single
cudaGraphLaunch each frame. It collapses many launches into one and is frequently the
highest‑ROI change once the kernels themselves are tuned.
- Overlap with async copies. Use
cuda::memcpy_asyncpipelines to load the next neighbour tile into shared memory while computing on the current one. - Warp‑level primitives. Build cell histograms and start/end offsets with
__shfl_syncand warp‑aggregated atomics instead of naive global atomics. - Vectorised, aligned loads. CUDA 13 widened vector types to 32‑byte alignment for
better Blackwell load/store throughput; pack positions as
float2/float4and keep buffers aligned. - Lock clocks for honest benchmarks.
nvidia-smi -lgc <freq>pins the GPU clock so frame‑time variance reflects your code, not boost behaviour.
09 · The payoff
Ten million particles, and the scoreboard
At 10M particles the working set is a few hundred megabytes of SoA float buffers — trivial against 32 GB on either machine. The constraint isn’t memory, it’s bandwidth, which makes the coalescing and tiling work from §07–§08 the thing that actually determines your frame time.
| Particles | posX..velY (5×f32) + type | Verdict |
|---|---|---|
| 1M | ~24 MB ×2 buffers | Interactive on both with the grid; great for tuning. |
| 10M | ~240 MB ×2 buffers | Fits easily; bandwidth‑bound; the real target. |
The benchmark you’ve been building toward
You now have four measurable configurations: CPU single‑thread, CPU all‑core, GPU naive, GPU grid — on
two machines. Report a single hardware‑independent figure, particle‑interactions per second,
plus frame time at fixed M. Time the GPU work with device clocks (Metal command‑buffer
GPUStartTime/GPUEndTime; CUDA events around the kernel sequence), not wall‑clock, to exclude
present/encode latency.
① CPU baseline produces stable swarms and a recorded interactions/sec on both machines. ② Metal and CUDA naive ports reproduce the CPU dynamics at a matched seed and parameters. ③ Grid version matches naive at small M and reaches 1M interactively. ④ 10M renders; the cluster/DSM variant is measured against the plain grid — keep whichever wins. If DSM doesn’t beat the straightforward grid kernel, drop it; it’s a flourish, not a requirement.
Toolkits move fast. Confirm your live nvcc --version and that your CMake knows arch 120
(set(CMAKE_CUDA_ARCHITECTURES 120) needs CUDA ≥ 12.8 and a recent CMake; otherwise pass
-gencode by hand). On the Mac, query device limits at runtime
(supportsFamily:, maxThreadgroupMemoryLength) rather than trusting the ~32 KB
figure — Apple‑silicon ceilings vary by generation. And the “friction coefficient vs. half‑life” choice is
a reparameterisation: match the reference app with the fixed 60 fps multiply, or go framerate‑independent
with the half‑life form — just be explicit about which.
10 · The finished tree
Build it · run it · verify itFrom chunks to a program you can run
Everything above assembles into one small repository with a shared core and three thin backends. This section is the glue: the seeding/benchmark harness, the build system, and the exact commands to compile and run it — plus the numbers it actually produces, measured on an Apple M2.
The CPU and Metal backends build with cmake --build and run. At a matched seed the
CPU‑naive, CPU‑grid, Metal‑naive and Metal‑grid checksums are identical to six decimals (gate 3),
and grid matches naive at small M (gate 4). Hello‑GPU prints C[0]=4096 at ~500 GFLOP/s.
At 1 M particles the Metal grid runs ~12× faster than naive (≈96 vs ≈1188 ms/step,
device‑clock timed). The CUDA backend targets sm_120 and builds on the 5090 with the same harness.
The layout — backends share common/sim.hpp; nobody forks the model:
common/ sim.hpp # SINGLE SOURCE OF TRUTH: Params, Sim (SoA), force(), grid
main.cpp # CLI, deterministic seeding, CPU benchmark + --verify
cpu/ cpu_step.cpp # OpenMP naive + uniform-grid step (ground truth)
metal/ plife.metal # compute: naive step + grid (hashCount/scanCells/scatter/forceGrid)
draw.metal · matmul.metal
shader_loader.hpp · metal_bridge.{h,mm} # runtime shader compile + CAMetalLayer
backend_metal.cpp · hello_mm.cpp
cuda/ plife.cu # naive + grid (CUB radix sort) + headless bench, mirrors main.cpp
clusters.cu · backend_cuda.cpp · hello_mm.cu
third_party/metal-cpp/ # vendored, header-only
CMakeLists.txtThe harness seeds deterministically — the RNG draw order is the reproducibility contract, so every
backend that seeds the same way produces the same dynamics. It prints a position checksum you can diff across
backends, and a --verify mode that races naive against grid:
#include "sim.hpp"
#include <cstdio>
#include <cstring>
#include <chrono>
#include <random>
#include <cmath>
static void alloc(Sim& s, size_t M, int N){
s.M=M; s.posX.resize(M); s.posY.resize(M);
s.velX.assign(M,0.f); s.velY.assign(M,0.f); s.type.resize(M); s.mat.resize((size_t)N*N);
}
// Draw order (matrix, then per-particle pos/type) is the reproducibility contract.
static void seed(Sim& a, const Params& p, size_t M, unsigned s){
std::mt19937 rng(s);
std::uniform_real_distribution<float> U(-1.f,1.f), U01(0.f,1.f);
alloc(a,M,p.N);
for(int i=0;i<p.N*p.N;i++) a.mat[i]=U(rng);
for(size_t i=0;i<M;i++){ a.posX[i]=U(rng); a.posY[i]=U(rng); a.type[i]=(uint8_t)(U01(rng)*p.N); }
}
static double checksum(const Sim& s){
double acc=0; for(size_t i=0;i<s.M;i++) acc+=std::fabs(s.posX[i])+std::fabs(s.posY[i]);
return acc/(double)s.M;
}
int main(int argc, char** argv){
Params p; size_t M=20000; int steps=300; unsigned sd=1234; bool useGrid=false;
for(int i=1;i<argc;i++){ // (the repo also adds --verify: races naive vs grid)
if(!strcmp(argv[i],"--m")&&i+1<argc) M=strtoull(argv[++i],0,10);
else if(!strcmp(argv[i],"--steps")&&i+1<argc) steps=atoi(argv[++i]);
else if(!strcmp(argv[i],"--n")&&i+1<argc) p.N=atoi(argv[++i]);
else if(!strcmp(argv[i],"--seed")&&i+1<argc) sd=(unsigned)atoi(argv[++i]);
else if(!strcmp(argv[i],"--grid")) useGrid=true;
}
Sim a,b; seed(a,p,M,sd); b=a;
Sim* cur=&a; Sim* next=&b;
auto t0=std::chrono::high_resolution_clock::now();
for(int s=0;s<steps;s++){
if(useGrid) cpuStepGrid(*cur,*next,p); else cpuStep(*cur,*next,p);
std::swap(cur,next); // ping-pong (golden rule #4)
}
auto t1=std::chrono::high_resolution_clock::now();
double sec=std::chrono::duration<double>(t1-t0).count(), inter=(double)M*(M-1)*steps;
printf("M=%zu steps=%d %s | %.3f ms/step | %.3e interactions/s | checksum=%.6f\n",
M, steps, useGrid?"grid":"naive", sec/steps*1e3, inter/sec, checksum(*cur));
return 0;
}One CMakeLists.txt selects backends per platform: the CPU baseline everywhere, Metal on macOS,
CUDA wherever nvcc is found. It picks up Homebrew’s libomp for Apple clang and
passes the shader directory so the runtime compiler can find the .metal files:
cmake_minimum_required(VERSION 3.24)
project(particle_life LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(PLIFE_SHADER_DIR "${CMAKE_SOURCE_DIR}/metal")
# ---- CPU baseline (both platforms) ----
add_executable(plife_cpu common/main.cpp cpu/cpu_step.cpp)
target_include_directories(plife_cpu PRIVATE common)
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(plife_cpu PRIVATE OpenMP::OpenMP_CXX)
elseif(APPLE) # Apple clang doesn't bundle libomp; grab Homebrew's
execute_process(COMMAND brew --prefix libomp OUTPUT_VARIABLE OMP
OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
if(OMP AND EXISTS "${OMP}/include/omp.h")
target_compile_options(plife_cpu PRIVATE -Xpreprocessor -fopenmp -I${OMP}/include)
target_link_libraries(plife_cpu PRIVATE ${OMP}/lib/libomp.dylib)
endif()
endif()
# ---- Metal backend (macOS) ----
if(APPLE)
enable_language(OBJCXX)
find_package(glfw3 QUIET)
set(MTL "-framework Metal" "-framework Foundation" "-framework QuartzCore" "-framework Cocoa")
add_executable(hello_mm_mtl metal/hello_mm.cpp)
target_include_directories(hello_mm_mtl PRIVATE third_party/metal-cpp metal)
target_compile_definitions(hello_mm_mtl PRIVATE PLIFE_SHADER_DIR="${PLIFE_SHADER_DIR}")
target_link_libraries(hello_mm_mtl PRIVATE ${MTL})
if(glfw3_FOUND)
add_executable(plife_metal metal/backend_metal.cpp metal/metal_bridge.mm)
target_include_directories(plife_metal PRIVATE common third_party/metal-cpp metal)
target_compile_definitions(plife_metal PRIVATE PLIFE_SHADER_DIR="${PLIFE_SHADER_DIR}")
target_link_libraries(plife_metal PRIVATE glfw ${MTL})
endif()
endif()
# ---- CUDA backend (Linux + NVIDIA) ----
include(CheckLanguage)
check_language(CUDA)
if(CMAKE_CUDA_COMPILER)
enable_language(CUDA)
set(CMAKE_CUDA_STANDARD 17)
if(NOT CMAKE_CUDA_ARCHITECTURES)
set(CMAKE_CUDA_ARCHITECTURES 120) # sm_120 (RTX 5090); needs CUDA >= 12.8
endif()
add_executable(hello_mm_cuda cuda/hello_mm.cu)
add_executable(plife_cuda cuda/plife.cu)
add_library(plife_clusters OBJECT cuda/clusters.cu)
endif()# --- macOS (M2): CPU + Metal ---
brew install cmake glfw libomp
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j # plife_cpu, plife_metal, hello_mm_mtl
./build/hello_mm_mtl # C[0]=4096 ... ~500 GFLOP/s
./build/plife_cpu --m 10000 --steps 100 --verify # naive vs grid -> [OK]
./build/plife_metal --m 50000 # interactive: space pause · g grid · r reseed · esc
./build/plife_metal --m 1000000 --grid --bench --steps 200 # headless, device-timed
# --- Server (Arch, RTX 5090): CUDA ---
nvcc --list-gpu-arch | grep compute_120 # must be present (CUDA >= 12.8)
cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120
cmake --build build -j
./build/plife_cuda --m 200000 --steps 300 --gridThe streaming render path (CUDA↔GL interop + CUDA graphs in cuda/backend_cuda.cpp)
builds on the server with OpenGL/GLFW/GLEW and is viewed on the Mac via Sunshine → Moonlight, exactly as in
§06. Everything else above is what you just built.