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 Order | Module | Primary Entry File(s) | Direct Internal Dependencies |
|---|---|---|---|
| 1 | Definitions | src/Definitions.jl (+ src/geometry/PeriodicDisplacement.jl, src/gpu/RelaxedAtomics.jl, src/random/OUSpectrum.jl) | (none) |
| 2 | Backends | src/Backends.jl | (none) |
| 3 | NeighborLists | src/NeighborLists.jl (+ src/neighbors/*.jl) | Definitions |
| 4 | BondedForces | src/BondedForces.jl (+ src/bonded/*.jl) | Definitions |
| 5 | NonBondedForces | src/NonBondedForces.jl (+ src/nonbonded/*.jl) | Definitions, NeighborLists |
| 6 | Electrostatics | src/Electrostatics.jl (+ src/electrostatics/**/*.jl) | Definitions, NeighborLists |
| 7 | ClusterPairs | src/ClusterPairs.jl (+ src/clusterpairs/*.jl) | Definitions, Electrostatics |
| 8 | RigidWaterConstraints | src/RigidWaterConstraints.jl (+ src/constraints/FloatFloat.jl, src/constraints/water/*.jl) | Definitions |
| 9 | ConstraintClusters | src/constraints/ConstraintClusters.jl (+ src/constraints/clusters/*.jl) | Definitions |
| 10 | IntegratorInterfaces | src/IntegratorInterfaces.jl | (none) |
| 11 | Collisions | src/Collisions.jl (+ src/collisions/*.jl) | Definitions, NeighborLists |
| 12 | ParticleGroups | src/ParticleGroups.jl | Backends, Definitions |
| 13 | SimulationCore | src/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 |
| 14 | DeviceEngine | src/DeviceEngine.jl (+ src/engine/**/*.jl) | Definitions, NeighborLists, NonBondedForces, BondedForces, Collisions, Electrostatics, ClusterPairs, RigidWaterConstraints, ConstraintClusters, SimulationCore |
| 15 | Filters | src/Filters.jl (+ src/filters/*.jl) | Backends, Definitions, ParticleGroups, SimulationCore |
| 16 | Writers | src/Writers.jl (+ src/io/**/*.jl) | SimulationCore, Electrostatics |
| 17 | InitGenerators | src/InitGenerators.jl | Definitions |
| 18 | Workflow | src/Workflow.jl (+ src/workflow/**/*.jl) | Backends, Definitions, NeighborLists, BondedForces, Electrostatics, Collisions, SimulationCore, DeviceEngine, Filters, Writers |
| 19 | ParticleDynamics | src/ParticleDynamics.jl | Re-exports public symbols from all submodules |
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 --> WFWhy Strict Acyclicity Matters
Zero method-table back-edges & predictable precompilation: Physics primitives (
ClusterPairs,Electrostatics,BondedForces,ConstraintClusters,RigidWaterConstraints) never importSimulationCoreorDeviceEngine. Modifying a high-level workflow file or barostat graph never invalidates compiled low-level CUDA kernels.Clean hook inversion via abstract stubs:
SimulationCoredefines lightweight hook stubs (_engine_boundary!,_engine_evaluate!,_engine_set_box!,_drop_engine!,_engine_invalidated!,_ensure_csvr_report_sample!,step!,step_graph!,step_many!) thatDeviceEnginespecializes 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 ofSimulationStateorWorkflow.
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:
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 --> L6Layer Breakdown
| Layer | Files | Key Responsibilities |
|---|---|---|
| Layer 1: Core Primitives | src/engine/Ordering.jl, Observables.jl, Traversal.jl, PairModels.jl, PairTraversal.jl, Builder.jl, Policy.jl, Fusion.jl, Philox.jl | Spatial 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 & Thermostats | src/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.jl | Zero-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 Paths | src/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.jl | StepCaptureOpts, 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 & Scheduling | src/engine/cluster/ClusterSetup.jl, ClusterForceKernels.jl, ClusterSchedule.jl | EngineConfig (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 & Barostats | src/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.jl | Run, 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 & Scheduler | src/engine/state/EngineSupport.jl, Fingerprint.jl, EngineBuild.jl, BoundaryRecovery.jl, BatchScheduler.jl | ENGINE_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)(defaultDEFAULT_CAPTURE_OPTS = StepCaptureOpts(true, false, false)). Replaces any hidden mutable capture flags:write_ekin=falseomits per-atomEkinglobal writes on plain non-energy BAOAB steps (refresh_rw_ekin!refreshesEkinat host boundaries).cc_skip_driftandcc_skip_kickallow_append_cluster_step_dag!to split rigid-water and solute+ConstraintClusterswork 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 intoStateEngine's fingerprint (DEFAULT_ENGINE_CONFIG[]insrc/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; becauseDEFAULT_ENGINE_CONFIG[]is part of_fingerprint, any knob change automatically triggers clean recapture without stale graph reuse. Settingmts_mesh_interval > 1(validated viacheck_respa_stability/respa_engine_config) activates symplectic reciprocal-spaceBAOAB-RESPA/r-RESPA.
StateEngine Fingerprint, Lifecycle, and Recovery
Zero-GPU-sync Fingerprint Check: On every
step!,_fingerprint(st, dt, spec)hashes host-only metadata: device pointers of allSimulationStatearrays, 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 andst.force_valid == true,step!launches directly with zero host-device synchronization.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 (neverSimulationStatebuffers) before releasing references. This prevents Julia GC finalizers from firing on another thread during a subsequent CUDA graph capture.Periodic Host Boundaries (
BOUNDARY_LAUNCHES = 1000): EveryBOUNDARY_LAUNCHESsteps (or on explicit observable/host read viaSC._engine_boundary!), the engine synchronizes once, verifiesstatus.step == e.device_step0 + e.launched, syncs ordering tags and barostat diagnostics (_sync_pressure_control!), and inspects latched error codes inws.state[DN_ERROR]:ELL Capacity Overflow (
NL.DN_CAPACITY_ERROR):_recover_capacity!computeslost = e.launched - (status.step - e.device_step0), growsws.list.captomax(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 recordede.flagssteps. Because Philox noise is keyed onDN_STEP, the trajectory matches an ample-capacity run.Cluster Outer-List Overflow (
CP.CL_ERR_CAPACITY):_recover_cluster!growsL.necaptoceil(1.25 * need) + 1024viaCP._alloc_entries!, recaptures, resumes the interrupted step fromsection = NL.section_of(ws)viacluster_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 withCP.GEOMETRY_SHRINK = 0.98(2% shrink margin). If a C-rescale event shrinks any axis belowGEOMETRY_SHRINK * L_ref,_baro_check_grid_kernel!latchesDN_CRESCALE_FALLBACK, pausing subsequent steps._recover_crescale_fallback!re-centersCP.setup!(orNL.set_device_box!) and refreshes electrostatics/dispersion influence tables at the new device box, recaptures, finishes the interrupted step fromresume=section, and replays skipped steps.Async MC Barostat Fallback (
DN_MC_FALLBACK = -32): If an async GPU MC trial crossesGEOMETRY_SHRINK, exceedsmax_dscale, or hits a domain reject, it latchesDN_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 withmesh_priority=false, afterMESH_TUNE_WARM = 40fast launches,MeshTunetimesMESH_TUNE_ROUNDS = 4alternating blocks ofMESH_TUNE_BLOCK = 8launches to pick whether the parallel mesh branch uses high stream priority (GRAPH_FLAGS()).
K-step NVT Batch Graphs (
capture_batch_stepsinsrc/engine/run/BatchCapture.jl):step_many!caches canonical multi-step graphs ine.batches(bounded bymax_cached_batches = 16)::list_cycle(fullnstlist-step cycle),:prune_cycle(nstprunesteps),: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_planinsrc/engine/state/BatchScheduler.jl): When a barostat has2 <= interval <= max_super_batch_steps(default50) andst.step % interval == 0, an entire NPT cycle is fused into a single CUDA graph launch::npt_cr_cycle(and:npt_cr_plain):interval - 2plain/fast/prune/build steps + 1 virial-trace step (:virial_*, accumulatingΣ r·fin one register per thread instead of full energies/virials) + 1 C-rescale event step (:event_*).:npt_mc_cycle(and:npt_mc_plain):interval - 1plain/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):
Inter-Step BAOAB Fusion: Between step
t - 1and stept, stept - 1defers its final kick (defer_kick=true, advancingDN_STEPconcurrently) and steptsetsskip_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 executesB2(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 soluteConstraintClustersare present, water and solute+CC fused kernels execute concurrently on parallel child-graph branches.Fused
posqCoordinate Packing (pack_posq/Val(PACK_POSQ)): Gated by_can_fuse_posq(run, b)on Float32f32shiftcluster runs (non-build, non-event steps), the integrator kernel calls_rw_pack_posq!directly while updated coordinates are in registers, writingL.posq(NTuple{4,Float32}) and skipping the separate_pack_posq_f32_kernel!launch completely.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 intorun.f, while the direct-space pair kernel leaves slot forces infc(skipping_enqueue_scatter_only!and emptying the join node completely). The next step's fused BAOAB kernel loadsf[j] + fc[slot_of[j] + 1]via_rw_load_force!(T, f, j, Val(false))and zeroesfcin place.Mode
2(dry uncharged/no-bonded/no-exception:cluster): the pair kernel leaves slot forces infc, and the next step's fused BAOAB kernel readsfc[slot_of[j] + 1]directly (replace-scatter) and zeroesfcin 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.jlbins particles into(x, y)columns andzbins (_column_key_hist_kernel!), performs a fused 1-block super-cluster offset scan (_cols_to_super_1block_kernel!forncol <= 1024), assigns 64-atom super-clusters into 8 spatialC_8octants in_cluster_assign_pack_bbox_body!, and compactsL.orderin a single kernel.Short-Range Molecule-Anchored Clustering (
L.anchor,src/simulation/ClusterCoupling.jl): For systems with exclusions,_build_cluster_anchorbuilds a depth-1 anchor map grouping rigid waters (H → O), shortConstraintClustersstars (≤ 0.25 r_max), and degree-1 terminal bonded leaves (r_0 ≤ 0.20 r_max) — plus small connected exclusion components (2..4atoms)._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 inxs/ys/zsand all AABBs, cutting off-diagonal exclusion tiles by43.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), partitioninghas_lj_t[typ] == 1atoms into low slots0..k-1and zero-LJ atoms into high slotsk..7with 0.000 nm AABB inflation. Active LJ types are deduplicated and compacted into1..n_act(_compact_lj_types_cp), mapping every zero-LJ type toInt32(0).ListBuild.jlconstructs the outer super-cluster list (scio,cjf,m8f,xid,masks), encoding the 5-bit periodic image shiftsh ∈ 0..26(plus sentinelsh == 27for general MIC on sparse boxes) and the exclusion bit directly in eachUInt32entrycjf[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 intobb_lo/bb_hi(storingNaN32for empty halves) using warp shuffles andLDG.128(_ldg_v4f32)._prune_aabb_f32_kernel!(P5_128t_nosph_notr128-thread CTA,0 Bspills) performs exactJ_4-vs-C_8AABB culling, unrolled1 | (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_8triangles into unifiedsh_id == 28circular 28-pair tiles), latchingCL_ERR_SLOW_CAPACITYfor 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 / Mode | CTA Size & Registers | SMEM / Parameter Lookup Strategy | Use 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 spill | Processes 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 spill | Dedicated 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 spill | Energy-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=72 | Supports 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:
XYMODE | Pipeline | Selection Criterion |
|---|---|---|
4 | 3 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. |
3 | 3 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. |
2 | 3 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). |
0 | 5 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/s6Loads: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-byteposqand slot-ordereds6directly fromClusterPairswithf_scalesupport for symplecticBAOAB-RESPA.Single-Mesh SMEM Spread & Gather (
src/electrostatics/mesh/SpreadSmem.jl,GatherSmem.jl): UsesProlatePolyStencil{4,T,D,2}(C2ProlateWindow) andP = 5scaled-Int32SMEM 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). ForP = 4,_spread_weights2_celluses 2 threads/atom (tpa2) evaluating mirror pairs(0, 3)and(1, 2)in lockstep with only 4shfl_xor_synccalls and a 40-mul factored tile spread. On L2-resident grids (<= SPREAD_STRIDE_BYTES = 2 MiB),_spread_orderuses 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 (ESPwithcontinuity=:c2) andDispersionESPshare mesh(K1, K2, K3)and stencil (automatically co-gridded insrc/workflow/Forces.jlwhen neither pins conflicting parameters),ClusterBackendallocates aDualMeshWorkspaceholding(K1, K2, K3, 2)grids. One particle pass computes the3Pwindow 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 ∇φ_din a single pass. Out-of-place NPT-MC trials skip the inverse FFT and force gather viaPencilEnergyKernels.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 / Subsystem | 2D | 3D :ell | 3D :cluster | CUDA-Graph & step_many! | Notes & Composition Constraints |
|---|---|---|---|---|---|
| Dimensionality & Neighbor Lists | Dense 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=2 | Newton-3 8x8 molecule-anchored cluster list (always 3D, spatial_reorder=false, fused=false); optional ELL contact rows for collisions | Full single-step + K-step flat batching | All-pairs auto-selected when < 3 cells fit per side and 2 r_c <= L. |
| Short-Range Built-in Pairs | LJ, WCA, SoftRep (uniform), Mixed-σ, PairMatrix, C² switches (:force_switch/:potential_switch) | All 2D models + :potential_shift | Uniform LJ/WCA, PairMatrix LJ/WCA, Mixed-σ, NB_KIND_NONE, C² switches, DualRC, per-pair LJ exceptions (lj_exceptions) | Full | SoftRep & 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) | Full | mass > 0 required. |
VVSpec (GJF) / BAOASpec / GSMSpec | Yes | Yes (unfused) | Yes | Full | VVSpec allows γ >= 0; BAOA/GSM require γ > 0. Accepts gamma, friction_rate, or tau. |
BAOABSpec / BAOAB / BAOABFast | Yes (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!) | Full | BAOABFast() sets track_thermo=false (skips dU/dq). Accepts gamma, friction_rate, or tau. Supports RigidWater, ConstraintClusters, and mts_mesh_interval RESPA. |
CSVRSpec / CSVR | Yes (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) | Full | Constrained molecules must lie within a single bath (_constraint_dof_per_bath). |
NHCSpec / NoseHooverChain | Yes (all 3 propagators) | Yes (unfused) | Yes | Full | Supports RigidWater & ConstraintClusters (NHCData.cdof). |
BrownianSpec (Euler-Heun) & EMSpec (Euler-Maruyama) | Yes | Yes (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) | Yes | Yes | Full (OUFeature) | Single- or multi-mode OUSpectrum; requires set_ou_spectrum! / ou workspace. |
FIRE & SteepestDescent (minimize!) | Yes | Yes | Yes | Uses 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) | Full | Integrators: 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) | Full | Integrators: 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) | Full | Orthorhombic 3D periodic boxes only (boundary=:tin_foil). |
DispersionESP / DispersionPME (DispersionSolver) | No (3D only) | No (:cluster only) | Yes (standalone or fused DualMeshWorkspace with C² ESP) | Full | Requires LennardJones nonbonded force and :cluster backend. |
AbstractExternalPotential (:replace) | Yes | Yes (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 graphs | Replaces internal forces. Capturable + provides_virial=true enables DeviceCRescale NPT; external_energy or capturable enables MC NPT. |
AbstractExternalPotential (:additive) | Yes | Yes (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 graphs | Adds external fields/restraints onto all internal forces. |
AbstractPairPotential (MorsePotential, YukawaPotential, custom) | Yes | Yes (2D/3D cooperative warp traversal, bonds, exclusions, spatial_reorder=true via sorted_particle_arrays, NPT, FIRE) | No (:ell only) | Full | Cannot combine with DispersionSolver; vdw_modifier reset to :none. |
FreezeGroup (FREEZE_HOLD / FREEZE_SPRING) | Yes | Yes (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. |