Skip to content

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:

julia
# 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 @inline device helpers invoked inside kernels.

Why ​

  1. PTX ABI & stack spills: @noinline forces NVPTX to emit a .func call frame with ABI parameter passing, disabling cross-function register allocation and almost always creating .local stack allocations (local memory spills) that serialize through L1/L2.

  2. 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 complicate launch=false precompilation before CUDA graph capture. Pass explicit arguments (or pack immutable options into a Val{...} or isbits struct such as StepCaptureOpts).


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:

julia
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:

bash
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 NTuple or SVector without compile-time unrolling (Base.Cartesian.@nexprs or Base.Cartesian.@nif).

  • Exceeding register pressure under an aggressive maxregs cap without moving read-only lookup data into shared memory (CuStaticSharedArray) or L1/RO cache (_ldg_v4f32 / _ldg_v2f32).

  • Keeping live Float64 values across barriers when Float32 or shifted local coordinates suffice (e.g., ssh[29] in PairKernelsF32.jl and displacement-delta SMEM coordinates in src/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 is FIXED64_SCALE = Float32(1 << 30) (2^30, resolution ~9.3e-10 force units). For extreme unit systems (e.g., SI Newtons or ultra-stiff springs), _compute_fixed64_scale derives an exact power-of-two scale ldexp(1.0f0, clamp(round(Int, 30 - log2(f_char)), -120, 120)) and inverse ldexp(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 with Definitions.@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)): Latches counts[CL_ERR] = CL_ERR_FIXED64_NONFINITE (Int32(5)). Scatter kernels detect _fixed64_error(fc) and propagate NaN cleanly 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 latches counts[CL_ERR] = CL_ERR_FIXED64_OVERFLOW (Int32(4)) if no higher-priority error is set. _list_invalid(counts), _cluster_error_kernel!, and ensure_capacity! treat CL_ERR_FIXED64_OVERFLOW as 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): Queries MULTIPROCESSOR_COUNT, MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, MAX_SHARED_MEMORY_PER_BLOCK, MAX_SHARED_MEMORY_PER_MULTIPROCESSOR, MAX_THREADS_PER_MULTIPROCESSOR, and MAX_REGISTERS_PER_MULTIPROCESSOR to compute max_bytes, two_blk_cap, and two_blk_thr_cap for CompactPencilFFTPlan (XYMODE ∈ {0, 2, 3, 4}).

  • DeviceEngine._rw_df64_launch_cfg & _cc_warp_launch_cfg (src/engine/water/WaterPolicy.jl): Query WARP_SIZE, MAX_REGISTERS_PER_MULTIPROCESSOR, MAX_BLOCKS_PER_MULTIPROCESSOR, and MAX_THREADS_PER_MULTIPROCESSOR to 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:

bash
compute-sanitizer --tool memcheck --error-exitcode=99 \
  julia --project --startup-file=no test/test_p1e2_direct_pairs_gpu.jl

For thorough race-condition checks on shared-memory kernels (CompactFFT, SMEM spread/gather, tight-AABB prune, SMEM general constraint solver), also run racecheck and initcheck:

bash
compute-sanitizer --tool racecheck --error-exitcode=99 \
  julia --project --startup-file=no test/test_p1e2_general_constr_gpu.jl

Because 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 .jl file under src/ is strictly capped at 700 lines (current maximum across all 222 files in src/ 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:

    bash
    find src -name '*.jl' -print0 | xargs -0 wc -l | sort -n | tail -n 15
  • Zero Retired Files / Zero Stale Global Knobs: Avoid module-level mutable Ref{Bool} feature toggles for kernel dispatch — put capture/execution knobs in immutable EngineConfig (DEFAULT_ENGINE_CONFIG, hashed into StateEngine._fingerprint) or StepCaptureOpts, and keep per-solver flags (compact_fft, smem_mesh, constraint_f64) immutable on the solver/workspace struct.

  • Manifest.toml Hygiene: Never commit Manifest.toml (neither at the repository root nor inside docs/). Keep Project.toml [deps] and [compat] minimal and exact (CUDA, GSDFiles, LinearAlgebra, Printf, Random, StaticArrays).

ParticleDynamics v1.2.0 · GPU-native molecular dynamics in pure Julia · MIT License