CUDA Engineering Hygiene & Invariants
Every GPU kernel in ParticleDynamics must satisfy the hard invariants below before merge. Violations directly degrade throughput, break CUDA-graph capture, or introduce subtle non-determinism and memory hazards.
1. Zero CUDA.@atomic: Use Definitions.@red
Invariant: Never use CUDA.@atomic or CUDA.atomic_add! for parallel force, energy, virial, histogram, or mesh-grid reductions in src/.
Why
CUDA.@atomic a[i] += v and CUDA.atomic_add! lower in LLVM/NVPTX to sequentially consistent system/device atomics (MEMBAR.ALL.GPU; ERRBAR; ATOMG.STRONG; CCTL.IVALL), emitting a full memory fence and L1 cache invalidation around every accumulation. In molecular dynamics, force and grid accumulations are read only after the kernel completes (or after sync_threads() in shared memory): they require atomicity, not memory ordering.
What to Use Instead
src/gpu/RelaxedAtomics.jl (included in Definitions) emits inline LLVM atomicrmw ... syncscope("device" | "block") monotonic, compiling to a single fence-free PTX red.relaxed.gpu / red.relaxed.cta instruction for Float32, Float64, Int32, and Int64 in both global (addrspace(1)) and shared (addrspace(3)) memory:
# Global or shared-memory reduction (preferred everywhere for sums/forces/grids):
Definitions.@red fc[ai, 1] += _acc_force(fc, fx_t)
Definitions.@red grid[gidx] += q_val
Definitions.@red bcnt[b + Int32(1)] += Int32(1)For read-modify-write counters that need the previous value (e.g., bin scatter cursors or dynamic work queues), src/clusterpairs/Primitives.jl provides monotonic _fetch_add!, _fetch_add_blk!, _atomic_or_u64!, and _atomic_cas_i32!.
When fences ARE required: Only for cross-block synchronization primitives (e.g., last-block reduction tickets in src/engine/Fusion.jl, where an explicit CUDA.threadfence() pairs with atomic counters, or first-error recording like CUDA.atomic_min! on a status slot).
2. Zero @noinline & Zero Defaulted Trailing Arguments in Device Helpers
Invariant:
Never annotate CUDA device helpers with
@noinline. Always mark hot device helpers@inline.Never put defaulted trailing keyword or positional arguments on GPU kernels or hot
@inlinedevice helpers invoked inside kernels.
Why
PTX ABI & stack spills:
@noinlineforces NVPTX to emit a.funccall frame with ABI parameter passing, disabling cross-function register allocation and almost always creating.localstack allocations (local memory spills) that serialize through L1/L2.Defaulted trailing arguments: Julia lowers defaulted arguments into multi-method forwarding stubs; on GPU kernels (
@cuda) or device helpers with tuple/array arguments, optional trailing defaults create extra specialization bloat, risk dynamic dispatch if type inference weakens, and complicatelaunch=falseprecompilation before CUDA graph capture. Pass explicit arguments (or pack immutable options into aVal{...}orisbitsstruct such asStepCaptureOpts).
3. Zero-Byte (0 B) PTX .local Spill Invariant
Invariant: Production hot-path kernels (direct-space ClusterPairs kernels, tight-AABB prune, CompactFFT, SMEM mesh spread/gather, rigid-water :df64 and ConstraintClusters star/general kernels, inter-step fused BAOAB, and grouped bonded kernels) MUST compile with 0 B local memory (CUDA.memory(k).local == 0) and zero .local declarations in PTX.
Verification in Julia Tests
Core GPU test suites (test/test_p1e2_direct_pairs_gpu.jl, test/test_p1e2_scatter_prune_gpu.jl, test/test_p1de_cluster_perf_gpu.jl, test/test_p1de_solute_dry_fuse_gpu.jl, test/test_p1e2_general_constr_gpu.jl, test/test_w2_mc_oop_gpu.jl, test/test_w3_respa_gpu.jl) enforce this automatically:
using CUDA
k = @cuda launch=false maxregs=72 MyModule._my_kernel!(args...)
ptx = sprint(io -> CUDA.code_ptx(io, MyModule._my_kernel!, Tuple{map(typeof, CUDA.cudaconvert.(args))...}))
@assert CUDA.memory(k).local == 0 "Kernel spilled $(CUDA.memory(k).local) B to local memory!"
@assert !any(ln -> occursin(".local", ln), split(ptx, '\n')) "PTX contains .local stack allocation!"
println("registers = ", CUDA.registers(k), ", local = ", CUDA.memory(k).local)Inspecting Exact ptxas Spill & Register Counts
To inspect exact SASS/register/spill statistics from NVIDIA's ptxas for the active GPU architecture:
julia --project -e '
using CUDA, ParticleDynamics
# Dump PTX of a compiled kernel to a temporary file
open("/tmp/kernel.ptx", "w") do io
CUDA.code_ptx(io, ParticleDynamics.ClusterPairs._update_bbox_f32_kernel!,
Tuple{CuDeviceVector{NTuple{4,Float32}}, CuDeviceVector{NTuple{4,Float32}},
CuDeviceVector{Int32}, CuDeviceVector{NTuple{4,Float32}}, Int32, Int32})
end
'
ptxas -v -arch=sm_86 /tmp/kernel.ptx -o /dev/null
# Verify: "0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads"Common Causes of .local Spills in Julia CUDA Kernels
Indexing a runtime-indexed
NTupleorSVectorwithout compile-time unrolling (Base.Cartesian.@nexprsorBase.Cartesian.@nif).Exceeding register pressure under an aggressive
maxregscap without moving read-only lookup data into shared memory (CuStaticSharedArray) or L1/RO cache (_ldg_v4f32/_ldg_v2f32).Keeping live
Float64values across barriers whenFloat32or shifted local coordinates suffice (e.g.,ssh[29]inPairKernelsF32.jland displacement-delta SMEM coordinates insrc/constraints/clusters/GeneralKernels.jl).
4. Adaptive :fixed64 Accumulation & Overflow Latching
ClusterPairs (src/clusterpairs/SlotPackScatter.jl & src/clusterpairs/EngineTypes.jl) supports bitwise-reproducible Float32 direct-space force summation via set_force_accumulation!(st, :fixed64) (or ClusterPairList(force_accumulation=:fixed64)).
How Fixed64ForceMatrix Works
Adaptive Power-of-Two Scale (
_compute_fixed64_scale): For standard reduced, nm, or Angstrom systems (1e-3 <= f_char <= 1e5), the scale isFIXED64_SCALE = Float32(1 << 30)(2^30, resolution~9.3e-10force units). For extreme unit systems (e.g., SI Newtons or ultra-stiff springs),_compute_fixed64_scalederives an exact power-of-two scaleldexp(1.0f0, clamp(round(Int, 30 - log2(f_char)), -120, 120))and inverseldexp(1.0, -p)so conversion adds zero mantissa rounding error.Checked & Deferred-Check Clamped Conversion (
_to_fixed64_checked,_red_force_rchk!+_latch_fixed64_rchk!):Hot tile-split pair kernels (
PairKernelsF32Split.jl) convert each force via the 4-instruction clamped PTX sequence_f32_to_i64_clamped_rni(±FIXED64_CLAMP = ±2^60), accumulate withDefinitions.@red(atomicrmw add i64 ... monotonic), and track a sticky NaN-preserving running magnitude_fmax_nan_abs_f32(r_chk, r)checked once at CTA epilogue in_latch_fixed64_rchk!.Non-finite forces (
!isfinite(f)): Latchescounts[CL_ERR] = CL_ERR_FIXED64_NONFINITE(Int32(5)). Scatter kernels detect_fixed64_error(fc)and propagateNaNcleanly instead of silently zeroing bad forces, and_list_invalid(counts)halts subsequent kernels until the host boundary throws.Overflowing finite forces (
abs(f * scale) > FIXED64_OVERFLOW_LIMIT = 9.0f18): Clamps the accumulated term to±FIXED64_CLAMP_I64(±2^60) and latchescounts[CL_ERR] = CL_ERR_FIXED64_OVERFLOW(Int32(4)) if no higher-priority error is set._list_invalid(counts),_cluster_error_kernel!, andensure_capacity!treatCL_ERR_FIXED64_OVERFLOWas non-fatal so diagnostics remain inspectable without aborting valid clamped steps.
5. Dynamic Hardware-Agnostic Launch Sizing (CUDA.attribute)
Invariant: Never hardcode GPU model names, SM counts (82, 108, 128), shared-memory sizes (48 KB, 99 KB), or warp counts. Always query the active device dynamically via CUDA.attribute and cache per CUDA.deviceid(dev).
Reference Implementations in src/
ClusterPairs._device_caps()(src/clusterpairs/EngineTypes.jl): Queries SM count, max registers per block/SM, max blocks/SM, and standard/opt-in shared memory per block to compute_split_factor,_split_factor_128,_split_factor_64,_split_factor_128_interleaved, and high-SMEM carveout decisions (_configure_f32shift_carveout!).Electrostatics._device_caps()(src/electrostatics/fft/Plan.jl): QueriesMULTIPROCESSOR_COUNT,MAX_SHARED_MEMORY_PER_BLOCK_OPTIN,MAX_SHARED_MEMORY_PER_BLOCK,MAX_SHARED_MEMORY_PER_MULTIPROCESSOR,MAX_THREADS_PER_MULTIPROCESSOR, andMAX_REGISTERS_PER_MULTIPROCESSORto computemax_bytes,two_blk_cap, andtwo_blk_thr_capforCompactPencilFFTPlan(XYMODE ∈ {0, 2, 3, 4}).DeviceEngine._rw_df64_launch_cfg&_cc_warp_launch_cfg(src/engine/water/WaterPolicy.jl): QueryWARP_SIZE,MAX_REGISTERS_PER_MULTIPROCESSOR,MAX_BLOCKS_PER_MULTIPROCESSOR, andMAX_THREADS_PER_MULTIPROCESSORto pick the highest-occupancy CTA size dynamically on Volta, Turing, Ampere, Ada, Hopper, and Blackwell GPUs alike.
6. compute-sanitizer Memory Verification Workflow
Every new or modified CUDA kernel must pass NVIDIA's compute-sanitizer with 0 errors before merge:
compute-sanitizer --tool memcheck --error-exitcode=99 \
julia --project --startup-file=no test/test_p1e2_direct_pairs_gpu.jlFor thorough race-condition checks on shared-memory kernels (CompactFFT, SMEM spread/gather, tight-AABB prune, SMEM general constraint solver), also run racecheck and initcheck:
compute-sanitizer --tool racecheck --error-exitcode=99 \
julia --project --startup-file=no test/test_p1e2_general_constr_gpu.jlBecause compute-sanitizer multiplies GPU kernel latency by ~10-50x, large suites support environment-variable chunking (see Testing, Verification & Benchmarking).
7. File Modularity (<= 700 Lines) & Repository Hygiene
<= 700-Line Source File Limit: Every.jlfile undersrc/is strictly capped at 700 lines (current maximum across all 222 files insrc/is 695 lines). When adding features or kernels, split cleanly by architectural layer (e.g., types/policies, kernels, launchers) rather than growing monolithic files. Check compliance before committing:bashfind src -name '*.jl' -print0 | xargs -0 wc -l | sort -n | tail -n 15Zero Retired Files / Zero Stale Global Knobs: Avoid module-level mutable
Ref{Bool}feature toggles for kernel dispatch — put capture/execution knobs in immutableEngineConfig(DEFAULT_ENGINE_CONFIG, hashed intoStateEngine._fingerprint) orStepCaptureOpts, and keep per-solver flags (compact_fft,smem_mesh,constraint_f64) immutable on the solver/workspace struct.Manifest.tomlHygiene: Never commitManifest.toml(neither at the repository root nor insidedocs/). KeepProject.toml[deps]and[compat]minimal and exact (CUDA,GSDFiles,LinearAlgebra,Printf,Random,StaticArrays).