Skip to content

System Architecture ​

This guide documents the internal architecture of ParticleDynamics (v1.2.0): the strictly acyclic module graph, the 6-layer DeviceEngine CUDA-graph runtime, the ClusterPairs direct-space tile engine, the Electrostatics mesh/FFT subsystem, and the exact feature-composition truth table enforced at runtime.


1. Strictly Acyclic Module Include DAG ​

src/ParticleDynamics.jl includes 18 submodules in a fixed topological order (19 Julia module definitions including the root ParticleDynamics, across 20 top-level src/*.jl files plus src/constraints/ConstraintClusters.jl).

Load OrderModulePrimary Entry File(s)Direct Internal Dependencies
1Definitionssrc/Definitions.jl (+ src/geometry/PeriodicDisplacement.jl, src/gpu/RelaxedAtomics.jl, src/random/OUSpectrum.jl)(none)
2Backendssrc/Backends.jl(none)
3NeighborListssrc/NeighborLists.jl (+ src/neighbors/*.jl)Definitions
4BondedForcessrc/BondedForces.jl (+ src/bonded/*.jl)Definitions
5NonBondedForcessrc/NonBondedForces.jl (+ src/nonbonded/*.jl)Definitions, NeighborLists
6Electrostaticssrc/Electrostatics.jl (+ src/electrostatics/**/*.jl)Definitions, NeighborLists
7ClusterPairssrc/ClusterPairs.jl (+ src/clusterpairs/*.jl)Definitions, Electrostatics
8RigidWaterConstraintssrc/RigidWaterConstraints.jl (+ src/constraints/FloatFloat.jl, src/constraints/water/*.jl)Definitions
9ConstraintClusterssrc/constraints/ConstraintClusters.jl (+ src/constraints/clusters/*.jl)Definitions
10IntegratorInterfacessrc/IntegratorInterfaces.jl(none)
11Collisionssrc/Collisions.jl (+ src/collisions/*.jl)Definitions, NeighborLists
12ParticleGroupssrc/ParticleGroups.jlBackends, Definitions
13SimulationCoresrc/SimulationCore.jl, src/SimulationState.jl, src/SimulationBuild.jl (+ src/simulation/*.jl, src/random/NoiseConstruction.jl)IntegratorInterfaces, Definitions, Backends, NeighborLists, NonBondedForces, BondedForces, Collisions, Electrostatics, ClusterPairs, RigidWaterConstraints, ConstraintClusters
14DeviceEnginesrc/DeviceEngine.jl (+ src/engine/**/*.jl)Definitions, NeighborLists, NonBondedForces, BondedForces, Collisions, Electrostatics, ClusterPairs, RigidWaterConstraints, ConstraintClusters, SimulationCore
15Filterssrc/Filters.jl (+ src/filters/*.jl)Backends, Definitions, ParticleGroups, SimulationCore
16Writerssrc/Writers.jl (+ src/io/**/*.jl)SimulationCore, Electrostatics
17InitGeneratorssrc/InitGenerators.jlDefinitions
18Workflowsrc/Workflow.jl (+ src/workflow/**/*.jl)Backends, Definitions, NeighborLists, BondedForces, Electrostatics, Collisions, SimulationCore, DeviceEngine, Filters, Writers
19ParticleDynamicssrc/ParticleDynamics.jlRe-exports public symbols from all submodules
mermaid
flowchart TD
    DEF["Definitions"]
    BKD["Backends"]
    II["IntegratorInterfaces"]
    NL["NeighborLists"]
    BF["BondedForces"]
    NBF["NonBondedForces"]
    ES["Electrostatics"]
    CP["ClusterPairs"]
    RWC["RigidWaterConstraints"]
    CC["ConstraintClusters"]
    COL["Collisions"]
    PG["ParticleGroups"]
    IG["InitGenerators"]
    SC["SimulationCore (SimulationState + SimulationBuild)"]
    DE["DeviceEngine"]
    FLT["Filters"]
    WR["Writers"]
    WF["Workflow"]

    DEF --> NL
    DEF --> BF
    DEF --> NBF
    DEF --> ES
    DEF --> CP
    DEF --> RWC
    DEF --> CC
    DEF --> COL
    DEF --> PG
    DEF --> IG
    BKD --> PG
    NL --> NBF
    NL --> ES
    NL --> COL
    ES --> CP

    DEF --> SC
    BKD --> SC
    II --> SC
    NL --> SC
    NBF --> SC
    BF --> SC
    ES --> SC
    CP --> SC
    RWC --> SC
    CC --> SC
    COL --> SC

    SC --> DE
    ES --> WR
    SC --> WR
    PG --> FLT
    SC --> FLT

    DE --> WF
    FLT --> WF
    WR --> WF
    SC --> WF

Why Strict Acyclicity Matters ​

  • Zero method-table back-edges & predictable precompilation: Physics primitives (ClusterPairs, Electrostatics, BondedForces, ConstraintClusters, RigidWaterConstraints) never import SimulationCore or DeviceEngine. Modifying a high-level workflow file or barostat graph never invalidates compiled low-level CUDA kernels.

  • Clean hook inversion via abstract stubs: SimulationCore defines lightweight hook stubs (_engine_boundary!, _engine_evaluate!, _engine_set_box!, _drop_engine!, _engine_invalidated!, _ensure_csvr_report_sample!, step!, step_graph!, step_many!) that DeviceEngine specializes once loaded, without creating an upward import cycle.

  • Composable testing: Low-level modules (NeighborLists, ClusterPairs, Electrostatics, ConstraintClusters) can be unit-tested directly on synthetic GPU arrays independently of SimulationState or Workflow.


2. Six-Layer DeviceEngine Architecture ​

DeviceEngine (src/DeviceEngine.jl) is the single execution runtime for every step!, step_graph!, step_many!, and configuration evaluation in ParticleDynamics (there is no staged fallback engine). Its internal files form a strict 6-layer acyclic include hierarchy:

mermaid
flowchart TD
    L1["Layer 1: Core Primitives (Ordering, Observables, Traversal, PairModels, Builder, Policy, Fusion, Philox)"]
    L2["Layer 2: Features & Thermostats (ENGINE_FEATURES, Langevin, CSVR, NHC, Brownian)"]
    L3["Layer 3: Water & Decoupled Solute/Constraint Fast Paths (src/engine/water/)"]
    L4["Layer 4: Cluster-Pair Backend & Force Scheduling (src/engine/cluster/)"]
    L5["Layer 5: Run Control, Graph Capture & Device Barostats (src/engine/run/, src/engine/barostat/)"]
    L6["Layer 6: StateEngine Lifecycle, Recovery & Batch Scheduler (src/engine/state/)"]

    L1 --> L2
    L2 --> L3
    L3 --> L4
    L4 --> L5
    L5 --> L6

Layer Breakdown ​

LayerFilesKey Responsibilities
Layer 1: Core Primitivessrc/engine/Ordering.jl, Observables.jl, Traversal.jl, PairModels.jl, PairTraversal.jl, Builder.jl, Policy.jl, Fusion.jl, Philox.jlSpatial cell/Hilbert reordering (OrderingWorkspace), persistent Float64 observable reductions (ObservableWorkspace), cooperative warp pair traversal (TraversalWorkspace, PairModel, CustomPairModel), 3D cooperative ELL builder (_cooperative_rows3_kernel!), :displacement vs :adaptive policies, 3D ELL control-kernel fusion (FusionWorkspace, _fused_prefix_kernel!), and counter-based Philox4x32 RNG (philox_normals).
Layer 2: Features & Thermostatssrc/engine/Features.jl, Unwrap.jl, Masses.jl, Bonded.jl, Freeze.jl, OUNoise.jl, CollisionCounting.jl, ExternalPotential.jl, RigidWater.jl, ConstraintClustersFeature.jl, COMRemover.jl, Langevin.jl, CSVR.jl, NHC.jl, Brownian.jlZero-cost compile-time tuple registry ENGINE_FEATURES (EngineFeature subtypes). Absent features are omitted from run.fx so _find(fx, Val(key)) constant-folds to nothing. Includes GPU-capturable COM drift removal (COMRemoverFeature) and device thermostats (LangevinData, CSVRData, NHCData, BrownianData).
Layer 3: Water & Solute Fast Pathssrc/engine/water/WaterPolicy.jl, DF64Math.jl, WaterDriftKickKernels.jl, WaterDF64Kernels.jl, SoluteConstraintKernels.jl, SoluteConstraintStar4Kernel.jl, SoluteConstraintDF64.jl, SoluteConstraintWarpKernels.jl, GeneralInterstepKernel.jl, InterstepFusedKernels.jl, SoluteVVWarpKernels.jl, WaterLaunchers.jlStepCaptureOpts, rw_fast_path, _dry_cluster_baoab_ok, _can_fuse_posq, _baoab_interstep_fusable, _vv_interstep_fusable, 3-lane warp-cooperative :df64 rigid-water SETTLE/RATTLE (incl. BAOAB, CSVR, and NVE inter-step fusion), exact constrained-BAOAB & CSVR/NVE solute+ConstraintClusters DF64 warp/general kernels, and inter-step + posq + scatter fusion.
Layer 4: Cluster Backend & Schedulingsrc/engine/cluster/ClusterSetup.jl, ClusterForceKernels.jl, ClusterSchedule.jlEngineConfig (DEFAULT_ENGINE_CONFIG, incl. mts_mesh_interval), Static14Table, ClusterBackend, coprime-stride _spread_order, cluster_forces!, cluster_step_parts, _cluster_scatter_fuse_mode, and host_scheduled / scheduled_step / build_step predicates.
Layer 5: Run Control, Graph Capture & Barostatssrc/engine/run/RunTypes.jl, GraphCapture.jl, BatchCapture.jl; src/engine/barostat/BarostatTypes.jl, VirialKernels.jl, CRescale.jl, MCKernels.jl, MCScaleKernels.jl, MCOutOfPlace.jl, BarostatGraphs.jl, MCFallback.jlRun, SplitStep, native flat capture_step (CUDA.capture! + cuStreamBeginCaptureToGraph), ell_mesh_graph, _append_cluster_step_dag!, multi-cycle capture_batch_steps + CUDA.upload(exec), DeviceCRescale, DeviceMonteCarloBarostat, virial-trace sampling, out-of-place zero-restore energy-only MC graphs + 3-axis parallel Euler scaling, and fallback cores.
Layer 6: StateEngine Lifecycle & Schedulersrc/engine/state/EngineSupport.jl, Fingerprint.jl, EngineBuild.jl, BoundaryRecovery.jl, BatchScheduler.jlENGINE_SETTINGS size/density heuristic table, engine_supported / engine_unsupported_reason, _fingerprint, StateEngine, symmetric warm-both-sides MeshTune, _capture_engine, _dispose!, _engine_boundary!, capacity (CL_ERR_CAPACITY & CL_ERR_SLOW_CAPACITY) & grid-margin recovery, and _engine_step! / _engine_step_many!.

StepCaptureOpts and EngineConfig ​

  • StepCaptureOpts (src/engine/water/WaterPolicy.jl): Immutable, reentrant capture-time control struct with fields (write_ekin::Bool, cc_skip_drift::Bool, cc_skip_kick::Bool) (default DEFAULT_CAPTURE_OPTS = StepCaptureOpts(true, false, false)). Replaces any hidden mutable capture flags:

    • write_ekin=false omits per-atom Ekin global writes on plain non-energy BAOAB steps (refresh_rw_ekin! refreshes Ekin at host boundaries).

    • cc_skip_drift and cc_skip_kick allow _append_cluster_step_dag! to split rigid-water and solute+ConstraintClusters work onto concurrent CUDA child-graph branches or defer kicks into fused inter-step kernels.

  • EngineConfig & DEFAULT_ENGINE_CONFIG (src/engine/cluster/ClusterSetup.jl): Immutable configuration struct hashed directly into StateEngine's fingerprint (DEFAULT_ENGINE_CONFIG[] in src/engine/state/Fingerprint.jl):

    • Fields: skin::Float64=NaN, cell_sub::Int=0, mesh_priority::Bool=false, mesh_parallel::Bool=true, batch_graph::Bool=true, max_batch_steps::Int=40, max_super_batch_steps::Int=50, max_cached_batches::Int=16, diagnostics::Bool=false, mts_mesh_interval::Int=1.

    • Scoped overrides use DeviceEngine.with_engine_config(; kwargs...) do ... end; because DEFAULT_ENGINE_CONFIG[] is part of _fingerprint, any knob change automatically triggers clean recapture without stale graph reuse. Setting mts_mesh_interval > 1 (validated via check_respa_stability / respa_engine_config) activates symplectic reciprocal-space BAOAB-RESPA / r-RESPA.

StateEngine Fingerprint, Lifecycle, and Recovery ​

  1. Zero-GPU-sync Fingerprint Check: On every step!, _fingerprint(st, dt, spec) hashes host-only metadata: device pointers of all SimulationState arrays, integrator spec signature (_spec_signature, including _param_version), feature_signatures(st, spec), box lengths, LJ/vdW/accumulation parameters, DEFAULT_ENGINE_CONFIG[], solver flags (compact_fft, smem_mesh), constraint precision modes (_rw_settle_mode, _cc_use_f64), and _pair_potential_sig. If unchanged and st.force_valid == true, step! launches directly with zero host-device synchronization.

  2. Deterministic Workspace Disposal (_dispose!): Whenever an engine is replaced or dropped (_drop_engine!, _abandon_engine!), _dispose! synchronizes once and explicitly calls _safe_free! on all engine-owned GPU buffers (never SimulationState buffers) before releasing references. This prevents Julia GC finalizers from firing on another thread during a subsequent CUDA graph capture.

  3. Periodic Host Boundaries (BOUNDARY_LAUNCHES = 1000): Every BOUNDARY_LAUNCHES steps (or on explicit observable/host read via SC._engine_boundary!), the engine synchronizes once, verifies status.step == e.device_step0 + e.launched, syncs ordering tags and barostat diagnostics (_sync_pressure_control!), and inspects latched error codes in ws.state[DN_ERROR]:

    • ELL Capacity Overflow (NL.DN_CAPACITY_ERROR): _recover_capacity! computes lost = e.launched - (status.step - e.device_step0), grows ws.list.cap to max(ceil(1.3 * required) + 16, ceil(1.25 * old)), recaptures all graphs (_recapture!), re-arms the failed rebuild section (resume_graph), and replays the remaining recorded e.flags steps. Because Philox noise is keyed on DN_STEP, the trajectory matches an ample-capacity run.

    • Cluster Outer-List Overflow (CP.CL_ERR_CAPACITY): _recover_cluster! grows L.necap to ceil(1.25 * need) + 1024 via CP._alloc_entries!, recaptures, resumes the interrupted step from section = NL.section_of(ws) via cluster_step_graph(...; resume=section), and replays _replay_cluster_flags!.

    • C-Rescale Grid-Margin Crossing (DN_CRESCALE_FALLBACK = -33): Neighbor grids on barostat runs are provisioned with CP.GEOMETRY_SHRINK = 0.98 (2% shrink margin). If a C-rescale event shrinks any axis below GEOMETRY_SHRINK * L_ref, _baro_check_grid_kernel! latches DN_CRESCALE_FALLBACK, pausing subsequent steps. _recover_crescale_fallback! re-centers CP.setup! (or NL.set_device_box!) and refreshes electrostatics/dispersion influence tables at the new device box, recaptures, finishes the interrupted step from resume=section, and replays skipped steps.

    • Async MC Barostat Fallback (DN_MC_FALLBACK = -32): If an async GPU MC trial crosses GEOMETRY_SHRINK, exceeds max_dscale, or hits a domain reject, it latches DN_MC_FALLBACK. _recover_mc_fallback! clears the latch, refreshes forces/energies, executes _device_mc_barostat_fallback_core!, recaptures if storage changed, and replays skipped steps.

Host-Scheduled Fixed-Interval Graphs & Super-Batching ​

When a cluster-pair run specifies list_intervals = (nstlist, nstprune) with nstlist % nstprune == 0 (and has no ELL contact-row consumers or Euler-Heun midpoint), host_scheduled(run) activates specialized graphs:

  • Single-step specializations:

    • :fast (e.fast): omits list displacement check, decision kernel, and both conditional nodes (runs between prune steps).

    • :prune (e.prune): runs pruning unconditionally (known=:prune) while keeping the rebuild node conditional for host requests or non-finite coordinates.

    • :build (e.build): runs rebuild and prune unconditionally (known=:build, zero conditional nodes).

    • MeshTune: On charged runs with mesh_priority=false, after MESH_TUNE_WARM = 40 fast launches, MeshTune times MESH_TUNE_ROUNDS = 4 alternating blocks of MESH_TUNE_BLOCK = 8 launches to pick whether the parallel mesh branch uses high stream priority (GRAPH_FLAGS()).

  • K-step NVT Batch Graphs (capture_batch_steps in src/engine/run/BatchCapture.jl): step_many! caches canonical multi-step graphs in e.batches (bounded by max_cached_batches = 16): :list_cycle (full nstlist-step cycle), :prune_cycle (nstprune steps), :fast_only / :pending_fast, or :plain_batch (K ∈ {20, 10, 4} for ELL and displacement-driven cluster runs).

  • Full-Cycle NPT Super-Batches (_select_super_batch_plan in src/engine/state/BatchScheduler.jl): When a barostat has 2 <= interval <= max_super_batch_steps (default 50) and st.step % interval == 0, an entire NPT cycle is fused into a single CUDA graph launch:

    • :npt_cr_cycle (and :npt_cr_plain): interval - 2 plain/fast/prune/build steps + 1 virial-trace step (:virial_*, accumulating Σ r·f in one register per thread instead of full energies/virials) + 1 C-rescale event step (:event_*).

    • :npt_mc_cycle (and :npt_mc_plain): interval - 1 plain/fast/prune/build steps + 1 lightweight MC-energy step (:mc_*, skipping observables/virials) + inline _append_mc_fast_body! (GPU trial proposal, molecular COM scaling, trial energy evaluation, exact Float64 Metropolis accept/reject, and conditional rollback).

Inter-Step BAOAB, pack_posq, and Scatter-into-BAOAB Fusion ​

Inside multi-step BAOAB batch graphs (length(kinds) >= 2 and _baoab_interstep_fusable(run) == true — covering rigid water, rigid water + solute with stars or general.n > 0 ConstraintClusters, and dry :cluster systems via _dry_cluster_baoab_ok):

  1. Inter-Step BAOAB Fusion: Between step t - 1 and step t, step t - 1 defers its final kick (defer_kick=true, advancing DN_STEP concurrently) and step t sets skip_drift=true. One fused boundary kernel (_rw_baoab_fused_step_df64_kernel!, _cc_baoab_fused_step_kernel! / _cc_baoab_fused_step_warp_kernel!, or _dry_baoab_fused_step_kernel!) loads (r, v, f) once and executes B2(t-1) + RATTLE(t-1) -> B1(t) + A1(t) + O(t, DN_STEP) + A2(t) + SETTLE/SHAKE(t) in registers, storing (r(t+1), v_half(t)) once. When both rigid water and solute ConstraintClusters are present, water and solute+CC fused kernels execute concurrently on parallel child-graph branches.

  2. Fused posq Coordinate Packing (pack_posq / Val(PACK_POSQ)): Gated by _can_fuse_posq(run, b) on Float32 f32shift cluster runs (non-build, non-event steps), the integrator kernel calls _rw_pack_posq! directly while updated coordinates are in registers, writing L.posq (NTuple{4,Float32}) and skipping the separate _pack_posq_f32_kernel! launch completely.

  3. Scatter-into-BAOAB Fusion (_cluster_scatter_fuse_mode): On non-energy, non-virial, non-event deferred steps, _cluster_scatter_fuse_mode(run, b) selects:

    • Mode 1 (meshed early-gather + mesh_parallel=true): the parallel mesh branch writes mesh (+ overlapped bonded/exception) forces into run.f, while the direct-space pair kernel leaves slot forces in fc (skipping _enqueue_scatter_only! and emptying the join node completely). The next step's fused BAOAB kernel loads f[j] + fc[slot_of[j] + 1] via _rw_load_force!(T, f, j, Val(false)) and zeroes fc in place.

    • Mode 2 (dry uncharged/no-bonded/no-exception :cluster): the pair kernel leaves slot forces in fc, and the next step's fused BAOAB kernel reads fc[slot_of[j] + 1] directly (replace-scatter) and zeroes fc in place.


3. ClusterPairs Nonbonded Engine ​

ClusterPairs (src/ClusterPairs.jl, 4 internal layers) evaluates 3D short-range Lennard-Jones, real-space Coulomb, and optional real-space 1/r^6 dispersion in one Newton-3 fused kernel over 8-atom clusters (CLUSTER = 8) grouped into 64-atom super-clusters (SUPER = 64).

Outer Build, Molecule-Anchored Clustering & Intra-C8 Zero-LJ Segregation ​

  • ListCluster.jl bins particles into (x, y) columns and z bins (_column_key_hist_kernel!), performs a fused 1-block super-cluster offset scan (_cols_to_super_1block_kernel! for ncol <= 1024), assigns 64-atom super-clusters into 8 spatial C_8 octants in _cluster_assign_pack_bbox_body!, and compacts L.order in a single kernel.

  • Short-Range Molecule-Anchored Clustering (L.anchor, src/simulation/ClusterCoupling.jl): For systems with exclusions, _build_cluster_anchor builds a depth-1 anchor map grouping rigid waters (H → O), short ConstraintClusters stars (≤ 0.25 r_max), and degree-1 terminal bonded leaves (r_0 ≤ 0.20 r_max) — plus small connected exclusion components (2..4 atoms). _column_key_hist_kernel! and _cluster_assign_pack_bbox_body! (Val(HAS_ANC)) use boundary-safe anchor coordinates (_anc_wrap) only for column/octant assignment while storing exact real coordinates in xs/ys/zs and all AABBs, cutting off-diagonal exclusion tiles by 43.6%–62.1% with zero overhead on unbonded systems (isempty(L.anchor)).

  • Fused Zero-LJ Segregation (Val(SEG_ZLJ)): Composes cleanly with molecule anchoring when a system mixes LJ-active and zero-LJ atom types (e.g., TIP3P/TIP4P water hydrogens, eng.has_zero_lj == true), partitioning has_lj_t[typ] == 1 atoms into low slots 0..k-1 and zero-LJ atoms into high slots k..7 with 0.000 nm AABB inflation. Active LJ types are deduplicated and compacted into 1..n_act (_compact_lj_types_cp), mapping every zero-LJ type to Int32(0).

  • ListBuild.jl constructs the outer super-cluster list (scio, cjf, m8f, xid, masks), encoding the 5-bit periodic image shift sh ∈ 0..26 (plus sentinel sh == 27 for general MIC on sparse boxes) and the exclusion bit directly in each UInt32 entry cjf[e].

Single-Pass AABB-Only F32 Prune & Split Compaction ​

  • _update_bbox_f32_kernel! (src/clusterpairs/ListPrune.jl) computes exact tight per-J_4 (4-atom half-cluster) AABBs into bb_lo / bb_hi (storing NaN32 for empty halves) using warp shuffles and LDG.128 (_ldg_v4f32).

  • _prune_aabb_f32_kernel! (P5_128t_nosph_notr 128-thread CTA, 0 B spills) performs exact J_4-vs-C_8 AABB culling, unrolled 1 | (2,3) | (4,5) | (6,7,8) exact distance checks, and deferred exclusion-mask resolution (rem_ex = mh & ~acc8).

  • _compact_from_cjf_split_kernel! and _rebuild_split_from_wlist_kernel! (src/clusterpairs/PairKernelsF32Split.jl) partition surviving tiles into exclusion-free fast tiles and a flat slow-tile queue (merging same-image self-C_8 triangles into unified sh_id == 28 circular 28-pair tiles), latching CL_ERR_SLOW_CAPACITY for transparent capacity recovery if the slow queue grows.

Tile-Split fast_clean / slow_flat, Direct-r² Monomials, DualRC & Out-of-Place MC Kernels ​

Production Float32 pair kernels read 16-byte aligned posq::CuVector{NTuple{4,Float32}} (LDG.128, NaN-padded empty slots), evaluate Coulomb/dispersion splittings via direct-r² monomials conditioned strictly at ≤ 2.5e-7 (PairKernelsF32Eval.jl, PairTableF32.jl), accumulate deterministic :fixed64 forces via clamped deferred-check _red_force_rchk! + _latch_fixed64_rchk! (SlotPackScatter.jl), and dispatch across specialized 0 B-spill kernels:

Kernel / ModeCTA Size & RegistersSMEM / Parameter Lookup StrategyUse Cases
_cluster_pair_kernel_f32shift_fast_clean! (PairKernelsF32Split.jl)64t (LJ_UNIFORM, mr=64) / 128t (LJ_TABLE_SHARED, mr=72)Exclusion-free fast path; i_lj_bits zero-LJ skip; direct LDG.64 ljp2_act (SLJP2); deferred :fixed64 check.Production force-only Float32 clean tiles (uniform LJ & multi-type biomolecular PME/LJPME).
_cluster_pair_kernel_f32shift_slow_flat! (PairKernelsF32Split.jl)Bounded grid-stride (bl_slow = min(cld(slow_cap, 4), 12 * nsm)), 0 B spillProcesses exclusion-bearing off-diagonal tiles and unified sh_id == 28 circular 28-pair self-C_8 tiles.Self-cluster & exclusion tiles paired with fast_clean!.
_cluster_pair_kernel_f32shift_dualrc! (PairKernelsF32DualRC.jl)128 threads, 0 B spillDedicated dual-cutoff (rc_lj != rc_coul) fast path without falling back to generic v3!.Mixed LJ/Coulomb cutoff setups (e.g., LJPME / switched-LJ with distinct real-space cutoffs).
_cluster_pair_kernel_f32shift_energy_only! & _fast_scalar! (PairKernelsF32MC.jl)mr=48 (en_only) / mr=72 (fast_scalar), 0 B spillEnergy-only & scalar-energy pair kernels using i_lj_bits (LJ_UNIFORM) and SMEM stb (LJ_TABLE_SHARED).Out-of-place zero-restore MonteCarloBarostat trial evaluation.
_cluster_pair_kernel_f32shift_v3! (PairKernelsF32.jl)128 threads, maxregs=72Supports EM ∈ {:none, :scalar}, virial trace Val(VT), C² switches (SWM ∈ {0,1,2}), LJ_LB_SHARED, LJ_SEPARABLE, LJ_MIXED, and LJ_TABLE_GLOBAL.C-rescale virial-trace passes, switched LJ, uncharged LJ, and high-type fallback modes.

Float64 states, per-particle full energy/virial evaluations (Val(:full)), and unshifted paths use PairKernelsGeneral.jl and PairKernelsEnergy.jl.


4. Electrostatics Mesh & CompactFFT Architecture ​

Electrostatics (src/Electrostatics.jl) implements SPME (:spme), P3M (:p3m_ad, :p3m_ik), C⁰ ESP (:esp, :esp_deconvolution), and C² ESP (:c2_esp, :c2_esp_deconvolution) for Coulomb 1/r, plus DispersionPME and DispersionESP for 1/r^6 lattice dispersion.

CompactPencilFFTPlan Dynamic SMEM/Register Planner ​

For smooth {2, 3, 5, 7} meshes up to 128^3 (_COMPACT_FFT_MAX_DIM = 128), src/electrostatics/fft/Plan.jl replaces cuFFT R2C + separate spectral solve + cuFFT C2R with a pure-Julia shared-memory 3D FFT (CompactPencilFFTPlan) factored into radices {10, 9, 8, 7, 6, 5, 4, 3, 2} (largest radix first so stage 1 skips twiddle multiplies). It also skips eager cuFFT plan allocation on MeshWorkspace / DualMeshWorkspace, saving tens of MiB of VRAM.

_device_caps() queries CUDA.attribute once per device ID (MULTIPROCESSOR_COUNT, MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, MAX_SHARED_MEMORY_PER_BLOCK, MAX_SHARED_MEMORY_PER_MULTIPROCESSOR, MAX_THREADS_PER_MULTIPROCESSOR, MAX_REGISTERS_PER_MULTIPROCESSOR) and _build_compact_pencil_plan dynamically picks XYMODE:

XYMODEPipelineSelection Criterion
43 kernels (odd-K1 2-row real-packed bank-conflict-free 2-buffer fused 2D XY + Pencil-Z fused solve + inverse 2D XY)Odd K1 when s2odd <= max_bytes; halves X work and SMEM.
33 kernels (even-K1 full-slice bank-conflict-free 2-buffer fused 2D XY + Pencil-Z fused solve + inverse 2D XY)Even K1 when s2bcf <= two_blk_cap (preferred at >= 2 blk/SM) or fallback when s15 is also 1 blk/SM.
23 kernels (even-K1 1.5-buffer bank-conflict-free fused 2D XY + Pencil-Z fused solve + inverse 2D XY)Even K1 when s2bcf > two_blk_cap but s15 <= two_blk_cap (preserves 2 blk/SM occupancy).
05 kernels (batched 1D-pencil X -> Y -> Z+solve -> Y -> X in SMEM)Large meshes (128^3 Float32, large Float64) or smaller-SMEM GPUs where 2D slices exceed max_bytes.

P = 4 / P = 5 C²-ESP Single & Dual Meshes, Octant Tables & MC Split ​

  • Orthorhombic Octant Influence Tables & Coalesced posq / s6 Loads: src/electrostatics/influence/ stores symmetric orthorhombic octant tables (G_oct, Vc_oct, cutting spectral memory footprint by ~4×), while mesh spread and gather kernels read coalesced 16-byte posq and slot-ordered s6 directly from ClusterPairs with f_scale support for symplectic BAOAB-RESPA.

  • Single-Mesh SMEM Spread & Gather (src/electrostatics/mesh/SpreadSmem.jl, GatherSmem.jl): Uses ProlatePolyStencil{4,T,D,2} (C2ProlateWindow) and P = 5 scaled-Int32 SMEM spreading. Super-cluster-tiled kernels accumulate all 64 slot atoms into a periodic-aware SMEM tile via block-scoped relaxed atomics, then flush non-zero voxels once to global memory (falling back inline to direct global atomics if a sparse super-cluster's tile overflows the SMEM cap). For P = 4, _spread_weights2_cell uses 2 threads/atom (tpa2) evaluating mirror pairs (0, 3) and (1, 2) in lockstep with only 4 shfl_xor_sync calls and a 40-mul factored tile spread. On L2-resident grids (<= SPREAD_STRIDE_BYTES = 2 MiB), _spread_order uses a golden-ratio coprime stride to eliminate warp atomic contention on sorted atoms.

  • Fused Dual-Mesh & 0 B-Spill MC Energy Split (src/electrostatics/dual/, src/electrostatics/fft/PencilEnergyKernels.jl): When Coulomb (ESP with continuity=:c2) and DispersionESP share mesh (K1, K2, K3) and stencil (automatically co-gridded in src/workflow/Forces.jl when neither pins conflicting parameters), ClusterBackend allocates a DualMeshWorkspace holding (K1, K2, K3, 2) grids. One particle pass computes the 3P window weights once, spreads (q_i, sqrt(c6)_i) together, runs one batched 2-field FFT+solve+iFFT, and gathers -q_i ∇φ_q - sqrt(c6)_i ∇φ_d in a single pass. Out-of-place NPT-MC trials skip the inverse FFT and force gather via PencilEnergyKernels.jl.


5. Feature-Composition Truth Table ​

The table below reflects the exact runtime predicates in src/engine/state/EngineSupport.jl, src/engine/ExternalPotential.jl, src/engine/water/WaterPolicy.jl, src/engine/Fusion.jl, src/simulation/ExternalPotential.jl, and src/workflow/.

Feature / Subsystem2D3D :ell3D :clusterCUDA-Graph & step_many!Notes & Composition Constraints
Dimensionality & Neighbor ListsDense ELL & all-pairs (2D ELL control-kernel fusion unlocked via Fusion.jl; serial builder build_lanes=1, cell_sub=1)Dense ELL, typed stencil (mapped onto single max-rc ELL), all-pairs (N <= 32,768), cooperative builder & cell_sub=2Newton-3 8x8 molecule-anchored cluster list (always 3D, spatial_reorder=false, fused=false); optional ELL contact rows for collisionsFull single-step + K-step flat batchingAll-pairs auto-selected when < 3 cells fit per side and 2 r_c <= L.
Short-Range Built-in PairsLJ, WCA, SoftRep (uniform), Mixed-σ, PairMatrix, C² switches (:force_switch/:potential_switch)All 2D models + :potential_shiftUniform LJ/WCA, PairMatrix LJ/WCA, Mixed-σ, NB_KIND_NONE, C² switches, DualRC, per-pair LJ exceptions (lj_exceptions)FullSoftRep & custom AbstractPairPotential run on :ell only; lj_exceptions run on :cluster only.
NVESpec / ConstantVolume()Yes (ELL fused when eligible)Yes (ELL fused when eligible)Yes (RW fast path with inter-step fusion when rigid water attached)Fullmass > 0 required.
VVSpec (GJF) / BAOASpec / GSMSpecYesYes (unfused)YesFullVVSpec allows γ >= 0; BAOA/GSM require γ > 0. Accepts gamma, friction_rate, or tau.
BAOABSpec / BAOAB / BAOABFastYes (2D ELL fused via Fusion.jl)Yes (3D ELL fused via Fusion.jl)Yes (inter-step BAOAB + pack_posq + scatter-into-BAOAB fusion + exact constrained-BAOAB projections!)FullBAOABFast() sets track_thermo=false (skips dU/dq). Accepts gamma, friction_rate, or tau. Supports RigidWater, ConstraintClusters, and mts_mesh_interval RESPA.
CSVRSpec / CSVRYes (2D single-bath ELL fused; up to CSVR_MAX_BATHS)Yes (3D single-bath ELL fused)Yes (RW fast path with inter-step fusion; lazy reporting when no barostat/constraints)FullConstrained molecules must lie within a single bath (_constraint_dof_per_bath).
NHCSpec / NoseHooverChainYes (all 3 propagators)Yes (unfused)YesFullSupports RigidWater & ConstraintClusters (NHCData.cdof).
BrownianSpec (Euler-Heun) & EMSpec (Euler-Maruyama)YesYes (unfused)Yes (Euler-Heun runs 2 cluster force evaluations/step)Full (single/batch; Euler-Heun needs conditional graph)Allows mass >= 0. No barostats or holonomic constraints.
ActiveOrnsteinUhlenbeck (AOUP)Yes (with Brownian/EM or Langevin)YesYesFull (OUFeature)Single- or multi-mode OUSpectrum; requires set_ou_spectrum! / ou workspace.
FIRE & SteepestDescent (minimize!)YesYesYesUses evaluation-only StateEngine (no sorting)Fixed box, respects FreezeGroup (FREEZE_HOLD pinned) and both AbstractPairPotential and AbstractExternalPotential.
DeviceCRescale (StochasticCellRescaling)No (3D only)Yes (3D pairs/unbonded + optional :ell mesh without exclusions/bonds/constraints, or capturable :replace ext with provides_virial=true)Yes (full topology: bonds, electrostatics, dispersion, RigidWater, ConstraintClusters, :additive ext with provides_virial=true)Full + :npt_cr_cycle super-batch (interval >= 2)Integrators: NVE, CSVR, NHC, VV, BAOAB, BAOABFast, GSM. Requires cell grid (no all-pairs), mobile particles (FREEZE_NONE), no collisions. Mode: :isotropic.
MonteCarloBarostatSpec (DeviceMonteCarloBarostat)No (3D only)Yes (3D, host-synced fallback core)Yes (out-of-place zero-restore energy-only GPU graph + 3-axis parallel Euler scaling + :npt_mc_cycle super-batch)Full (:cluster async super-batch; :ell host-boundary)Modes: :isotropic, :semiisotropic, :z (:z_only); scale ∈ {:atoms, :molecules}; 40 KB SMEM Euler up to 10,241 atoms + unlimited global fallback; adaptive tune=true.
RigidWaterConstraints (RigidWaterConstraint)No (3D only)Yes (no device barostat on :ell)Yes (rw_fast_path: 3-lane warp :df64 SETTLE/RATTLE, inter-step BAOAB fusion)FullIntegrators: NVE, CSVR, NHC, BAOAB (BAOABFast).
ConstraintClusters (stars & general.n > 0)No (3D only)Yes (no device barostat on :ell)Yes (stars + SMEM general fast path; concurrent water || solute+CC branches; inter-step BAOAB fusion)FullIntegrators: NVE, CSVR, NHC, BAOAB (BAOABFast). Stars: analytical k=1..4; General: SMEM up to 32 atoms / 48 edges, global F64 fallback above.
ESP / PME / PPPM (ElectrostaticsSolver)No (3D only)Yes (3D only, no Coulomb exceptions or excluded bonds; parallel ell_mesh_graph or fused AD gather-kick)Yes (full exclusions, Static14Table 1-4 scaling, parallel mesh branch, CompactFFT, SMEM spread/gather)FullOrthorhombic 3D periodic boxes only (boundary=:tin_foil).
DispersionESP / DispersionPME (DispersionSolver)No (3D only)No (:cluster only)Yes (standalone or fused DualMeshWorkspace with C² ESP)FullRequires LennardJones nonbonded force and :cluster backend.
AbstractExternalPotential (:replace)YesYes (unsorted :ell, no bonds/ES/dispersion; RigidWater/CC allowed iff is_device_capturable=true)No (:ell only)Capturable: full single-step & step_many! graphs; Host: SplitStep graphsReplaces internal forces. Capturable + provides_virial=true enables DeviceCRescale NPT; external_energy or capturable enables MC NPT.
AbstractExternalPotential (:additive)YesYes (capturable supports spatial_reorder=true; host-synced requires spatial_reorder=false)Yes (composes with pairs, bonds, ES, dispersion, constraints!)Capturable: full single-step & step_many! graphs; Host: SplitStep graphsAdds external fields/restraints onto all internal forces.
AbstractPairPotential (MorsePotential, YukawaPotential, custom)YesYes (2D/3D cooperative warp traversal, bonds, exclusions, spatial_reorder=true via sorted_particle_arrays, NPT, FIRE)No (:ell only)FullCannot combine with DispersionSolver; vdw_modifier reset to :none.
FreezeGroup (FREEZE_HOLD / FREEZE_SPRING)YesYes (unfused)Yes (incompatible with rw_fast_path / dry fused BAOAB)Full (FreezeFeature)Disallowed with device barostats (FREEZE_NONE required).
spatial_reorder (OrderingWorkspace)Yes (ELL, non-allpairs)Yes (ELL, non-allpairs; permutes bonded slot_of, thermostat arrays, and sorted_particle_arrays)No (cluster list spatially orders particles internally)Full (host-scheduled e.sort on fused ELL)Disallowed for host-synced external potentials, :replace external potentials, and barostats.

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