From 7ea1d51c9a544621a096b1ca897cff2d68d4bebd Mon Sep 17 00:00:00 2001
From: Pengchao Zhang <75114282+Zhang-pchao@users.noreply.github.com>
Date: Thu, 19 Nov 2026 11:02:29 +0800
Subject: [PATCH 1/6] Share reactive Voronoi assignments and add an optional
CUDA backend
---
plugins/reactive-voronoi-cuda/Makefile | 21 +
plugins/reactive-voronoi-cuda/README.md | 167 +++++++
.../ReactiveVoronoiCuda.cu | 444 ++++++++++++++++++
plugins/reactive-voronoi-cuda/plugin.yml | 6 +
.../reactive-voronoi-cuda/regtest/Makefile | 11 +
.../regtest/backend_checks.py | 342 ++++++++++++++
.../regtest/device_check.cpp | 164 +++++++
.../rt-reactive-voronoi-backends/Makefile | 1 +
.../basic/rt-reactive-voronoi-backends/config | 2 +
.../rt-reactive-voronoi-backends/main.cpp | 262 +++++++++++
.../output.reference | 1 +
.../basic/rt-reactive-voronoi-shared/Makefile | 1 +
.../basic/rt-reactive-voronoi-shared/config | 2 +
.../basic/rt-reactive-voronoi-shared/main.cpp | 98 ++++
.../output.reference | 1 +
src/colvar/ReactiveVoronoi.cpp | 388 +++++++++++++--
src/colvar/ReactiveVoronoiCuda.h | 153 ++++++
17 files changed, 2026 insertions(+), 38 deletions(-)
create mode 100644 plugins/reactive-voronoi-cuda/Makefile
create mode 100644 plugins/reactive-voronoi-cuda/README.md
create mode 100644 plugins/reactive-voronoi-cuda/ReactiveVoronoiCuda.cu
create mode 100644 plugins/reactive-voronoi-cuda/plugin.yml
create mode 100644 plugins/reactive-voronoi-cuda/regtest/Makefile
create mode 100644 plugins/reactive-voronoi-cuda/regtest/backend_checks.py
create mode 100644 plugins/reactive-voronoi-cuda/regtest/device_check.cpp
create mode 100644 regtest/basic/rt-reactive-voronoi-backends/Makefile
create mode 100644 regtest/basic/rt-reactive-voronoi-backends/config
create mode 100644 regtest/basic/rt-reactive-voronoi-backends/main.cpp
create mode 100644 regtest/basic/rt-reactive-voronoi-backends/output.reference
create mode 100644 regtest/basic/rt-reactive-voronoi-shared/Makefile
create mode 100644 regtest/basic/rt-reactive-voronoi-shared/config
create mode 100644 regtest/basic/rt-reactive-voronoi-shared/main.cpp
create mode 100644 regtest/basic/rt-reactive-voronoi-shared/output.reference
create mode 100644 src/colvar/ReactiveVoronoiCuda.h
diff --git a/plugins/reactive-voronoi-cuda/Makefile b/plugins/reactive-voronoi-cuda/Makefile
new file mode 100644
index 0000000000..4da69aa614
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/Makefile
@@ -0,0 +1,21 @@
+NVCC ?= nvcc
+CUDA_ARCH ?= native
+NVCCFLAGS ?= -O3 -std=c++17
+TARGET = libReactiveVoronoiCuda.so
+
+# Keep the CUDA runtime alive across PLUMED destruction inside an MD process.
+ifeq ($(shell uname -s),Linux)
+ PLATFORM_LDFLAGS = -Xlinker -z -Xlinker nodelete
+endif
+
+.PHONY: all clean check
+all: $(TARGET)
+
+$(TARGET): ReactiveVoronoiCuda.cu
+ $(NVCC) $(NVCCFLAGS) -arch=$(CUDA_ARCH) --cudart=shared -Xcompiler=-fPIC -shared $(PLATFORM_LDFLAGS) $(LDFLAGS) $< -o $@
+
+check: all
+ $(MAKE) -C regtest check LIBRARY=$(abspath $(TARGET))
+
+clean:
+ rm -f $(TARGET)
diff --git a/plugins/reactive-voronoi-cuda/README.md b/plugins/reactive-voronoi-cuda/README.md
new file mode 100644
index 0000000000..092b2db0e3
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/README.md
@@ -0,0 +1,167 @@
+# Reactive Voronoi assignment backends
+
+VORONOI_COORDINATION, VORONOI_DISTANCE and VORONOI_POSITION accept explicit
+atom selections and preserve their mathematical definitions across the
+assignment backends. The optional CUDA library implements FP64 soft
+assignments and their analytic reverse derivatives.
+
+## Input and backend selection
+
+The default is shared CPU evaluation. Compatible actions in one PLUMED
+instance reuse geometry, normalized weights and occupancies. Different
+KAPPA values share CPU geometry and normalize separately. Each action keeps
+its own REFERENCE, SELECT, coefficients, sign and reduction semantics.
+
+~~~plumed
+q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2
+d: VORONOI_DISTANCE CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 GROUP1=1,2
+PRINT ARG=q,d FILE=COLVAR
+~~~
+
+Add NO_SHARE to select independent CPU evaluation for a reference comparison.
+BACKEND=CPU also selects shared CPU evaluation.
+
+BACKEND=CUDA explicitly requests CUDA and reports an error when the library,
+device or requested calculation is unsupported.
+
+~~~plumed
+q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2 BACKEND=CUDA CUDA_LIBRARY=/path/libReactiveVoronoiCuda.so
+~~~
+
+BACKEND=AUTO opts into capability detection. It selects CUDA when the library,
+device and input are supported. Otherwise it selects CPU and logs the reason.
+
+~~~plumed
+q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2 BACKEND=AUTO
+~~~
+
+CUDA_LIBRARY defaults to libReactiveVoronoiCuda.so, searched through the
+system dynamic-library search path. An explicit path is useful for isolated
+installations. Backend names are case insensitive. The log identifies the
+requested backend, selected backend and GPU device when available.
+
+AUTO checks capability and input compatibility. Actual speed depends on system
+size, reduction groups, host transfers and the MD workload. The CPU default
+keeps existing inputs reproducible, and small groups can favor CPU execution.
+An initialization fallback persists for the action's lifetime. Changes between
+orthorhombic and triclinic boxes select a compatible backend on each request.
+Calculation errors after successful CUDA initialization propagate normally.
+
+The currently supported CUDA domain is orthorhombic PBC or NOPBC and a
+single rank, with either complete assignments or NLIST. AUTO falls back to
+CPU for triclinic PBC and multiple MPI ranks. Older CUDA libraries still
+support complete assignments, and AUTO uses CPU if their NLIST symbol is
+missing.
+
+NLIST uses the same CPU-built candidate list and cutoff in both backends.
+Each CUDA context uploads the list after a rebuild and reuses the uploaded
+indices between evaluations. The center-distance reduction for
+VORONOI_DISTANCE runs on the host over the configured GROUP1 and GROUP2
+pairs. NLIST renormalizes the assignment over the retained centers, so check
+both CVs and forces against complete assignments when choosing NL_CUTOFF.
+NL_STRIDE=1 rebuilds the candidates each step. For longer strides use a
+positive NL_SKIN to enable displacement- and box-triggered rebuilds.
+
+~~~plumed
+UNITS LENGTH=A
+q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2 NLIST NL_CUTOFF=6 NL_SKIN=0.5 NL_STRIDE=10 BACKEND=AUTO
+~~~
+
+The distances in this example are in angstroms. Choose the cutoff and buffer
+for the actual atom selections and length units.
+
+## Building the optional library
+
+The PLUMED core builds with a normal C++ compiler and keeps CUDA headers
+confined to the plugin. Build the CUDA library on a Linux CUDA host.
+
+~~~bash
+make CUDA_ARCH=sm_70
+~~~
+
+Select the architecture of the target GPU, such as sm_70 for V100 or sm_80
+for A100. The default CUDA_ARCH=native detects the GPU on the compilation
+host. Set NVCC and NVCCFLAGS when the toolchain requires them. Install the
+resulting libReactiveVoronoiCuda.so in a versioned library directory and put
+that directory in LD_LIBRARY_PATH, or provide CUDA_LIBRARY in the input.
+
+The build links the shared CUDA runtime and marks the Linux library NODELETE.
+This follows the lifetime protection used by the official CUDA plugin and
+preserves an MD engine's live device allocations when PLUMED is destroyed.
+
+## Device ownership and data flow
+
+Device selection follows the MD-provided setGpuDeviceId when supplied.
+Otherwise it captures the current CUDA device on first evaluation. Every
+allocation, transfer, kernel, synchronization and release uses that captured
+device, and restores the caller's device afterward. CUDA_VISIBLE_DEVICES
+provides the usual logical-device mapping.
+
+The v2 context factory accepts the MD device. The v1 factory remains exported.
+The core accepts a v1 library when the MD device is unspecified. An explicit
+MD device requires a library providing the v2 factory.
+
+Each compatible KAPPA context retains O(Ncenters+Nassigned) device buffers
+for complete assignments. NLIST adds offsets by assigned atom and one center
+index per buffered candidate. FP64 kernels stream over the selected centers
+for each assigned atom and use shifted-softmax normalization. Each scalar
+action still contracts its own analytic derivatives. PLUMED combines bias
+sensitivities using its existing force graph.
+
+OPES, scalar reductions, direct distance/position terms and their direct
+virial contributions execute on CPU. Full-pool VORONOI_DISTANCE therefore
+includes a CPU center-pair reduction. The current host MD interface supplies
+host coordinates and receives host forces.
+
+The official cudaCoord plugin registers CUDACOORDINATION and
+CUDACOORDINATIONFLOAT after LOAD. The openaccPTM plugin adds USEGPU selection
+to its supported actions after LOAD. This experimental library is loaded by
+the Voronoi core through CUDA_LIBRARY. Its BACKEND input is specific to these
+three actions.
+
+## Validation
+
+The core regtests rt-reactive-voronoi-shared and
+rt-reactive-voronoi-backends run with CPU-only PLUMED. The latter covers
+coordination powers/signs/selections, cross/within-group distances, position
+axes/signs/normalization/absolute values, reordered atoms, mixed KAPPA,
+PBC/NOPBC, strided lists, repeated-step changes and finite-difference forces
+and cell derivatives. It includes a triclinic position-image regression.
+
+Run the driver matrix from the plugin directory with the selected PLUMED
+installation. Run the CUDA cases on a CUDA-capable device.
+
+~~~bash
+make CUDA_ARCH=sm_70 check PLUMED=/absolute/path/bin/plumed
+~~~
+
+The driver matrix includes a fixed-box trajectory that forces a rebuild
+before the scheduled step. It compares values and derivatives to an
+independent CPU list rebuilt every step. It also checks invalid stride/skin
+inputs and pinpoints failed comparisons by file, row and column.
+Run the CPU and missing-library fallback cases on a CPU-only host with:
+
+~~~bash
+python3 regtest/backend_checks.py --plumed /absolute/path/bin/plumed --cpu-only
+~~~
+
+In a configured PLUMED source build, the native CPU regression is available
+through PLUMED's test harness.
+
+~~~bash
+make -C regtest/basic/rt-reactive-voronoi-backends
+~~~
+
+The native test executable also accepts a backend suffix for a manual CUDA
+or AUTO run. Use an empty working directory for each run because the test
+writes logs and an output file in the current directory.
+
+~~~bash
+/absolute/path/to/regtest/basic/rt-reactive-voronoi-backends/tmp/exe " BACKEND=CUDA CUDA_LIBRARY=/absolute/path/libReactiveVoronoiCuda.so"
+~~~
+
+Strict CUDA tests compare every supported force/virial component to CPU and
+finite-difference diagonal strains for PBC. AUTO also checks sheared boxes
+through its CPU fallback. All cell strains are checked for NOPBC.
+
+Application benchmarks and large trajectories belong in separate case records.
diff --git a/plugins/reactive-voronoi-cuda/ReactiveVoronoiCuda.cu b/plugins/reactive-voronoi-cuda/ReactiveVoronoiCuda.cu
new file mode 100644
index 0000000000..1104362363
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/ReactiveVoronoiCuda.cu
@@ -0,0 +1,444 @@
+/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Copyright (c) 2026 Reactive Voronoi contributors
+ (see the PEOPLE file at the root of the distribution for a list of names)
+
+ See http://www.plumed.org for more information.
+
+ This file is part of plumed, version 2.
+
+ plumed is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ plumed is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with plumed. If not, see .
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
+// FP64 streamed assignments with optional buffered center lists.
+#include
+#include
+#include
+#include
+
+namespace {
+constexpr int denseThreads=128;
+constexpr int neighborThreads=32;
+
+bool checkCuda(cudaError_t status) {
+ if(status==cudaSuccess) {
+ return true;
+ }
+ std::fprintf(stderr,"ReactiveVoronoi CUDA: %s\n",cudaGetErrorString(status));
+ return false;
+}
+
+/// Preserve the device context selected by the MD engine around every call.
+class DeviceScope {
+ int previous_=-1;
+ bool valid_=false;
+public:
+ explicit DeviceScope(int device) {
+ int current=-1;
+ if(!checkCuda(cudaGetDevice(¤t))) {
+ return;
+ }
+ if(current!=device) {
+ if(!checkCuda(cudaSetDevice(device))) {
+ return;
+ }
+ previous_=current;
+ }
+ valid_=true;
+ }
+ ~DeviceScope() {
+ if(previous_>=0) {
+ cudaSetDevice(previous_);
+ }
+ }
+ DeviceScope(const DeviceScope&)=delete;
+ DeviceScope& operator=(const DeviceScope&)=delete;
+ bool valid() const {
+ return valid_;
+ }
+};
+
+struct State {
+ int numCenters=0;
+ int numAssigned=0;
+ int device=-1;
+ double* positions=nullptr;
+ double* occupancy=nullptr;
+ double* maximum=nullptr;
+ double* normalization=nullptr;
+ double* sensitivity=nullptr;
+ double* derivatives=nullptr;
+ double* virial=nullptr;
+ int* invalid=nullptr;
+ int* offsets=nullptr;
+ int* candidateCenters=nullptr;
+ int candidateCapacity=0;
+ double cutoff=0;
+ bool useNeighbors=false;
+ double box[3] {};
+ double kappa=0;
+ bool pbc=false;
+ cudaStream_t stream=nullptr;
+};
+
+template
+__device__ double reduce(double value, bool maximum, double* scratch) {
+ const int thread=threadIdx.x;
+ if constexpr(threads==neighborThreads) {
+ for(int offset=threads/2; offset; offset/=2) {
+ const double other=__shfl_down_sync(0xffffffff,value,offset);
+ value=maximum ? fmax(value,other) : value+other;
+ }
+ return __shfl_sync(0xffffffff,value,0);
+ }
+ scratch[thread]=value;
+ __syncthreads();
+ for(int offset=threads/2; offset; offset/=2) {
+ if(thread
+__global__ void forwardKernel(State state) {
+ __shared__ double scratch[threads];
+ const int assigned=blockIdx.x;
+ const int thread=threadIdx.x;
+ const int begin=useNeighbors ? state.offsets[assigned] : 0;
+ const int end=useNeighbors ? state.offsets[assigned+1] : state.numCenters;
+ double maximum=-INFINITY;
+ for(int entry=begin+thread; entry(maximum,true,scratch);
+ if(useNeighbors && maximum==-INFINITY) {
+ if(thread==0) {
+ atomicCAS(state.invalid,0,2);
+ }
+ return;
+ }
+ double normalization=0;
+ for(int entry=begin+thread; entry(normalization,false,scratch);
+ if(thread==0) {
+ state.maximum[assigned]=maximum;
+ state.normalization[assigned]=normalization;
+ }
+ for(int entry=begin+thread; entrystate.cutoff) {
+ continue;
+ }
+ const double weight=exp(-state.kappa*length-maximum)/normalization;
+ atomicAdd(state.occupancy+center,weight);
+ }
+}
+
+template
+__global__ void backwardKernel(State state) {
+ __shared__ double scratch[threads];
+ const int assigned=blockIdx.x;
+ const int thread=threadIdx.x;
+ const int begin=useNeighbors ? state.offsets[assigned] : 0;
+ const int end=useNeighbors ? state.offsets[assigned+1] : state.numCenters;
+ const double maximum=state.maximum[assigned];
+ const double normalization=state.normalization[assigned];
+ double mean=0;
+ for(int entry=begin+thread; entrystate.cutoff) {
+ continue;
+ }
+ const double weight=exp(-state.kappa*length-maximum)/normalization;
+ mean+=weight*state.sensitivity[center];
+ }
+ mean=reduce(mean,false,scratch);
+ double assignedDerivative[3]= {0,0,0};
+ double virial[9]= {};
+ for(int entry=begin+thread; entrystate.cutoff) {
+ continue;
+ }
+ const double weight=exp(-state.kappa*length-maximum)/normalization;
+ const double radial=-state.kappa*weight*(state.sensitivity[center]-mean)/length;
+ for(int axis=0; axis<3; ++axis) {
+ const double gradient=radial*displacement[axis];
+ atomicAdd(state.derivatives+3*center+axis,-gradient);
+ assignedDerivative[axis]+=gradient;
+ for(int component=0; component<3; ++component) {
+ virial[3*axis+component]-=gradient*displacement[component];
+ }
+ }
+ }
+ for(int axis=0; axis<3; ++axis) {
+ const double value=reduce(assignedDerivative[axis],false,scratch);
+ if(thread==0) {
+ state.derivatives[3*(state.numCenters+assigned)+axis]=value;
+ }
+ }
+ for(int component=0; component<9; ++component) {
+ const double value=reduce(virial[component],false,scratch);
+ if(thread==0) {
+ atomicAdd(state.virial+component,value);
+ }
+ }
+}
+
+void release(State* state) {
+ if(!state) {
+ return;
+ }
+ DeviceScope scope(state->device);
+ if(scope.valid()) {
+ cudaFree(state->positions);
+ cudaFree(state->occupancy);
+ cudaFree(state->maximum);
+ cudaFree(state->normalization);
+ cudaFree(state->sensitivity);
+ cudaFree(state->derivatives);
+ cudaFree(state->virial);
+ cudaFree(state->invalid);
+ cudaFree(state->offsets);
+ cudaFree(state->candidateCenters);
+ if(state->stream) {
+ cudaStreamDestroy(state->stream);
+ }
+ }
+ delete state;
+}
+}
+
+extern "C" int reactive_voronoi_device_count_v1() {
+ int count=0;
+ if(cudaGetDeviceCount(&count)!=cudaSuccess) {
+ return 0;
+ }
+ return count;
+}
+
+extern "C" void* reactive_voronoi_create_v2(int numCenters, int numAssigned,
+ int mdDevice) {
+ const int deviceCount=reactive_voronoi_device_count_v1();
+ if(numCenters<=0 || numAssigned<=0 || deviceCount==0 || mdDevice>=deviceCount) {
+ return nullptr;
+ }
+ int device=mdDevice;
+ if(device<0 && !checkCuda(cudaGetDevice(&device))) {
+ return nullptr;
+ }
+ DeviceScope scope(device);
+ if(!scope.valid()) {
+ return nullptr;
+ }
+ State* state=new(std::nothrow) State;
+ if(!state) {
+ return nullptr;
+ }
+ state->numCenters=numCenters;
+ state->numAssigned=numAssigned;
+ state->device=device;
+ const size_t numAtoms=static_cast(numCenters)+numAssigned;
+ if(!checkCuda(cudaStreamCreateWithFlags(&state->stream,cudaStreamNonBlocking)) ||
+ !checkCuda(cudaMalloc(&state->positions,3*numAtoms*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->occupancy,numCenters*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->maximum,numAssigned*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->normalization,numAssigned*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->sensitivity,numCenters*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->derivatives,3*numAtoms*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->virial,9*sizeof(double))) ||
+ !checkCuda(cudaMalloc(&state->invalid,sizeof(int)))) {
+ release(state);
+ return nullptr;
+ }
+ return state;
+}
+
+extern "C" void* reactive_voronoi_create_v1(int numCenters, int numAssigned) {
+ return reactive_voronoi_create_v2(numCenters,numAssigned,-1);
+}
+
+extern "C" int reactive_voronoi_device_v1(void* context) {
+ return context ? static_cast(context)->device : -1;
+}
+
+extern "C" void reactive_voronoi_destroy_v1(void* context) {
+ release(static_cast(context));
+}
+
+namespace {
+int runForward(void* context, const double* positions, const double* box, int pbc,
+ double kappa, double* occupancy, bool useNeighbors, double cutoff,
+ const int* offsets, const int* centers, int count) {
+ if(!context || !positions || !box || !occupancy || !std::isfinite(kappa) || kappa<=0) {
+ return 1;
+ }
+ State& state=*static_cast(context);
+ DeviceScope scope(state.device);
+ if(!scope.valid()) {
+ return 1;
+ }
+ if(useNeighbors) {
+ if(offsets) {
+ if(count<0 || (count>0 && !centers)) {
+ return 1;
+ }
+ if(!state.offsets && !checkCuda(cudaMalloc(&state.offsets,
+ (static_cast(state.numAssigned)+1)*sizeof(int)))) {
+ return 1;
+ }
+ if(count>state.candidateCapacity) {
+ int* replacement=nullptr;
+ if(!checkCuda(cudaMalloc(&replacement,static_cast(count)*sizeof(int)))) {
+ return 1;
+ }
+ cudaFree(state.candidateCenters);
+ state.candidateCenters=replacement;
+ state.candidateCapacity=count;
+ }
+ if(!checkCuda(cudaMemcpyAsync(state.offsets,offsets,
+ (static_cast(state.numAssigned)+1)*sizeof(int),
+ cudaMemcpyHostToDevice,state.stream)) ||
+ (count>0 && !checkCuda(cudaMemcpyAsync(state.candidateCenters,centers,
+ static_cast(count)*sizeof(int),cudaMemcpyHostToDevice,state.stream)))) {
+ return 1;
+ }
+ } else if(!state.offsets) {
+ return 1;
+ }
+ state.cutoff=cutoff;
+ }
+ state.useNeighbors=useNeighbors;
+ state.pbc=pbc;
+ state.kappa=kappa;
+ for(int axis=0; axis<3; ++axis) {
+ state.box[axis]=box[axis];
+ if(pbc && (!std::isfinite(box[axis]) || box[axis]<=0)) {
+ return 1;
+ }
+ }
+ const size_t numAtoms=static_cast(state.numCenters)+state.numAssigned;
+ if(!checkCuda(cudaMemcpyAsync(state.positions,positions,3*numAtoms*sizeof(double),
+ cudaMemcpyHostToDevice,state.stream)) ||
+ !checkCuda(cudaMemsetAsync(state.occupancy,0,state.numCenters*sizeof(double),state.stream)) ||
+ !checkCuda(cudaMemsetAsync(state.invalid,0,sizeof(int),state.stream))) {
+ return 1;
+ }
+ if(useNeighbors) {
+ forwardKernel<<>>(state);
+ } else {
+ forwardKernel<<>>(state);
+ }
+ int invalid=0;
+ if(!checkCuda(cudaGetLastError()) ||
+ !checkCuda(cudaMemcpyAsync(occupancy,state.occupancy,state.numCenters*sizeof(double),
+ cudaMemcpyDeviceToHost,state.stream)) ||
+ !checkCuda(cudaMemcpyAsync(&invalid,state.invalid,sizeof(int),
+ cudaMemcpyDeviceToHost,state.stream)) ||
+ !checkCuda(cudaStreamSynchronize(state.stream))) {
+ return 1;
+ }
+ return invalid;
+}
+
+}
+
+extern "C" int reactive_voronoi_forward_v1(void* context, const double* positions,
+ const double* box, int pbc, double kappa, double* occupancy) {
+ return runForward(context,positions,box,pbc,kappa,occupancy,false,0,nullptr,nullptr,0);
+}
+
+// A null offsets pointer reuses the already uploaded candidate list.
+extern "C" int reactive_voronoi_forward_nlist_v1(void* context, const double* positions,
+ const double* box, int pbc, double kappa, double* occupancy, double cutoff,
+ const int* offsets, const int* centers, int count) {
+ return runForward(context,positions,box,pbc,kappa,occupancy,true,cutoff,offsets,centers,count);
+}
+
+extern "C" int reactive_voronoi_backward_v1(void* context, const double* sensitivity,
+ double* derivatives, double* virial) {
+ if(!context || !sensitivity || !derivatives || !virial) {
+ return 1;
+ }
+ State& state=*static_cast(context);
+ DeviceScope scope(state.device);
+ if(!scope.valid()) {
+ return 1;
+ }
+ const size_t numAtoms=static_cast(state.numCenters)+state.numAssigned;
+ if(!checkCuda(cudaMemcpyAsync(state.sensitivity,sensitivity,state.numCenters*sizeof(double),
+ cudaMemcpyHostToDevice,state.stream)) ||
+ !checkCuda(cudaMemsetAsync(state.derivatives,0,3*numAtoms*sizeof(double),state.stream)) ||
+ !checkCuda(cudaMemsetAsync(state.virial,0,9*sizeof(double),state.stream))) {
+ return 1;
+ }
+ if(state.useNeighbors) {
+ backwardKernel<<>>(state);
+ } else {
+ backwardKernel<<>>(state);
+ }
+ if(!checkCuda(cudaGetLastError()) ||
+ !checkCuda(cudaMemcpyAsync(derivatives,state.derivatives,3*numAtoms*sizeof(double),
+ cudaMemcpyDeviceToHost,state.stream)) ||
+ !checkCuda(cudaMemcpyAsync(virial,state.virial,9*sizeof(double),
+ cudaMemcpyDeviceToHost,state.stream)) ||
+ !checkCuda(cudaStreamSynchronize(state.stream))) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/plugins/reactive-voronoi-cuda/plugin.yml b/plugins/reactive-voronoi-cuda/plugin.yml
new file mode 100644
index 0000000000..7b6ec42cd8
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/plugin.yml
@@ -0,0 +1,6 @@
+name: reactive-voronoi-cuda
+authors: Reactive Voronoi contributors
+description: Optional FP64 streamed assignments and analytic reverse derivatives for reactive Voronoi actions
+dois: []
+nlessons: 0
+searchterm: voronoi
diff --git a/plugins/reactive-voronoi-cuda/regtest/Makefile b/plugins/reactive-voronoi-cuda/regtest/Makefile
new file mode 100644
index 0000000000..1445cb6f41
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/regtest/Makefile
@@ -0,0 +1,11 @@
+PYTHON ?= python3
+PLUMED ?= plumed
+LIBRARY ?= ../libReactiveVoronoiCuda.so
+
+.PHONY: check clean
+check:
+ rm -rf tmp
+ $(PYTHON) backend_checks.py --plumed $(PLUMED) --library $(abspath $(LIBRARY)) --work $(CURDIR)/tmp
+
+clean:
+ rm -rf tmp
diff --git a/plugins/reactive-voronoi-cuda/regtest/backend_checks.py b/plugins/reactive-voronoi-cuda/regtest/backend_checks.py
new file mode 100644
index 0000000000..2eb776a432
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/regtest/backend_checks.py
@@ -0,0 +1,342 @@
+"""Small driver parity and error-path checks for the optional CUDA library."""
+
+import argparse
+import json
+import math
+import re
+import resource
+import subprocess
+import tempfile
+from pathlib import Path
+
+
+def read_numbers(path):
+ rows = []
+ for line in path.read_text().splitlines():
+ if line.strip() and not line.startswith("#"):
+ rows.append([float(value) for value in line.split()])
+ return rows
+
+
+def compare(reference, candidate, location):
+ assert len(reference) == len(candidate), location
+ maximum = 0.0
+ for row, (left, right) in enumerate(zip(reference, candidate)):
+ assert len(left) == len(right), (location, row)
+ for column, (expected, actual) in enumerate(zip(left, right)):
+ assert math.isfinite(actual), (location, row, column, actual)
+ error = abs(expected - actual)
+ assert error <= 2e-8 + 2e-10 * abs(expected), (
+ location,
+ row,
+ column,
+ expected,
+ actual,
+ error,
+ )
+ maximum = max(maximum, error)
+ return maximum
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--plumed", default="plumed")
+ parser.add_argument("--library")
+ parser.add_argument("--work", type=Path)
+ parser.add_argument("--cpu-only", action="store_true")
+ arguments = parser.parse_args()
+ if not arguments.cpu_only and not arguments.library:
+ parser.error("--library is required unless --cpu-only is set")
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+ work = arguments.work or Path(tempfile.mkdtemp(prefix="voronoi-backends-"))
+ work.mkdir(parents=True, exist_ok=True)
+ positions = [
+ [0.2, 0.3, 0.4],
+ [1.3, 0.6, 0.2],
+ [2.2, 1.7, 0.8],
+ [3.0, 2.4, 1.9],
+ [0.4, 0.3, 0.4],
+ [0.1, 0.5, 0.4],
+ [0.2, 0.2, 0.6],
+ [1.4, 0.7, 0.3],
+ [2.3, 1.8, 0.9],
+ [3.1, 2.5, 2.0],
+ ]
+ common = "CENTERS=1,2,3,4 ASSIGNED=5,6,7,8,9,10 REFERENCE=1.5,1.2,1.1,2.2 KAPPA=5"
+ definitions = [
+ "VORONOI_COORDINATION " + common + " POWER=1",
+ "VORONOI_COORDINATION " + common + " POWER=2 SIGN=POSITIVE",
+ "VORONOI_COORDINATION " + common + " POWER=2 SIGN=NEGATIVE SELECT=1,3",
+ "VORONOI_COORDINATION " + common + " POWER=2 SELECT=2,4 COEFFICIENTS=1.3,-0.4",
+ "VORONOI_COORDINATION CENTERS=1,2,3,4 ASSIGNED=5,6,7,8,9,10 REFERENCE=1 KAPPA=8 POWER=2",
+ "VORONOI_DISTANCE " + common + " GROUP1=1,3 GROUP2=2,4",
+ "VORONOI_DISTANCE " + common + " GROUP1=1,2,3,4",
+ "VORONOI_POSITION " + common + " AXIS=X ORIGIN=0.35",
+ "VORONOI_POSITION " + common + " AXIS=Y ORIGIN=-0.7 SIGN=NEGATIVE NORMALIZE",
+ "VORONOI_POSITION " + common + " AXIS=Z ORIGIN=1.2 ABSOLUTE NORMALIZE",
+ "VORONOI_POSITION " + common + " AXIS=X ORIGIN=-0.4 SELECT=1,4 NORMALIZE",
+ ]
+ modes = {
+ "independent": " NO_SHARE",
+ "shared": " BACKEND=CPU",
+ "auto-missing": " BACKEND=AUTO CUDA_LIBRARY=missing-backend.so",
+ }
+ if not arguments.cpu_only:
+ modes.update(
+ {
+ "cuda": " BACKEND=CUDA CUDA_LIBRARY=" + arguments.library,
+ "auto": " BACKEND=AUTO CUDA_LIBRARY=" + arguments.library,
+ }
+ )
+ results = {"work": str(work), "positive": [], "negative": []}
+
+ def run(name, lines, coordinates=None, box="7,8,9", frames=None):
+ directory = work / name
+ directory.mkdir()
+ if frames is None:
+ frames = [coordinates if coordinates is not None else positions]
+ with (directory / "frame.xyz").open("w") as xyz:
+ for frame in frames:
+ xyz.write(f"{len(frame)}\nsmall backend regression\n")
+ for row in frame:
+ xyz.write("H " + " ".join(map(str, row)) + "\n")
+ (directory / "plumed.dat").write_text("\n".join(lines) + "\n")
+ command = [
+ arguments.plumed,
+ "driver",
+ "--ixyz",
+ "frame.xyz",
+ "--length-units",
+ "nm",
+ "--box",
+ box,
+ ]
+ with (directory / "stdout.log").open("w") as output:
+ process = subprocess.run(
+ command, cwd=directory, stdout=output, stderr=subprocess.STDOUT
+ )
+ return directory, process.returncode
+
+ for geometry in ["pbc", "nopbc", "nlist", "triclinic"]:
+ reference = None
+ for mode, backend in modes.items():
+ if mode == "cuda" and geometry == "triclinic":
+ continue
+ extra = " NOPBC" if geometry == "nopbc" else ""
+ if geometry == "nlist":
+ extra = " NLIST NL_CUTOFF=1.85 NL_STRIDE=3 NL_SKIN=0.4"
+ labels = ["v" + str(index) for index in range(len(definitions))]
+ lines = [
+ label + ": " + definition + extra + backend
+ for label, definition in zip(labels, definitions)
+ ]
+ lines += [
+ "PRINT ARG=" + ",".join(labels) + " FILE=values FMT=%24.16e",
+ "DUMPDERIVATIVES ARG="
+ + ",".join(labels)
+ + " FILE=derivatives FMT=%24.16e",
+ ]
+ box = "7,0,0,0.8,8,0,0.4,0.7,9" if geometry == "triclinic" else "7,8,9"
+ directory, code = run(geometry + "-" + mode, lines, box=box)
+ assert code == 0, directory
+ data = {
+ key: read_numbers(directory / key) for key in ["values", "derivatives"]
+ }
+ if reference is None:
+ reference = data
+ errors = {
+ key: compare(reference[key], data[key], directory / key) for key in data
+ }
+ log = (directory / "stdout.log").read_text()
+ if mode == "auto" and geometry == "triclinic":
+ assert "selected CPU" in log
+ if mode in ["cuda", "auto"] and geometry != "triclinic":
+ assert "selected CUDA" in log
+ results["positive"].append(
+ dict(geometry=geometry, mode=mode, errors=errors)
+ )
+
+ # Keep the box fixed. The second center is outside the initial buffered
+ # list and enters the true cutoff before the scheduled rebuild at step 10.
+ # The following frame moves below half the skin and reuses the new list.
+ frames = [
+ [[0, 0, 0], [1.8, 0, 0], [4, 0, 0], [x, 0.1, 0], [4.3, 0.1, 0]]
+ for x in (0.20, 0.95, 0.96, 1.55)
+ ]
+ buffered = " CENTERS=1,2,3 ASSIGNED=4,5 REFERENCE=1 KAPPA=5 NLIST NL_CUTOFF=1.2"
+ reference = None
+ for mode, backend in modes.items():
+ is_reference = mode == "independent"
+ suffix = " NL_STRIDE=1" if is_reference else " NL_STRIDE=10 NL_SKIN=0.25"
+ suffix += backend
+ lines = [
+ "q: VORONOI_COORDINATION SELECT=1 POWER=2" + buffered + suffix,
+ "d: VORONOI_DISTANCE GROUP1=1,2,3" + buffered + suffix,
+ "PRINT ARG=q,d FILE=values FMT=%24.16e",
+ "DUMPDERIVATIVES ARG=q,d FILE=derivatives FMT=%24.16e",
+ ]
+ directory, code = run("displacement-rebuild-" + mode, lines, frames=frames)
+ assert code == 0, directory
+ data = {key: read_numbers(directory / key) for key in ("values", "derivatives")}
+ assert len(data["values"]) == len(frames), directory
+ if is_reference:
+ reference = data
+ assert abs(data["values"][1][1] - data["values"][0][1]) > 0.05, directory
+ errors = {
+ key: compare(reference[key], data[key], directory / key) for key in data
+ }
+ log = (directory / "stdout.log").read_text()
+ expected = "selected CUDA" if mode in ("cuda", "auto") else "selected CPU"
+ assert expected in log, directory
+ if mode in ("cuda", "auto"):
+ assert "NLIST assignment and assignment derivatives" in log, directory
+ results["positive"].append(
+ dict(geometry="displacement-rebuild", mode=mode, errors=errors)
+ )
+
+ # Only the center at distance 0.5 contributes. The buffered center at
+ # distance 2 would overflow the score if evaluated before the true cutoff.
+ for mode, backend in modes.items():
+ directory, code = run(
+ "buffer-only-score-" + mode,
+ [
+ "v: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3 SELECT=1 "
+ "REFERENCE=0 KAPPA=1e308 NLIST NL_CUTOFF=1 NL_STRIDE=3 NL_SKIN=1.5"
+ + backend,
+ "PRINT ARG=v FILE=values",
+ "DUMPDERIVATIVES ARG=v FILE=derivatives",
+ ],
+ coordinates=[[0, 0, 0], [2.5, 0, 0], [0.5, 0, 0]],
+ )
+ assert code == 0, directory
+ assert read_numbers(directory / "values")[0][1] == 1.0, directory
+ derivatives = read_numbers(directory / "derivatives")
+ assert derivatives and all(row[-1] == 0.0 for row in derivatives), directory
+ results["positive"].append(dict(geometry="buffer-only-score", mode=mode))
+
+ invalid = [
+ (
+ "nlist-missing-stride",
+ "VORONOI_COORDINATION " + common + " NLIST NL_CUTOFF=1.85 NL_SKIN=0.4",
+ "NL_STRIDE must be positive",
+ ),
+ (
+ "nlist-skin-with-unit-stride",
+ "VORONOI_COORDINATION "
+ + common
+ + " NLIST NL_CUTOFF=1.85 NL_STRIDE=1 NL_SKIN=0.4",
+ "NL_SKIN requires NL_STRIDE greater than one",
+ ),
+ (
+ "bad-kappa",
+ "VORONOI_COORDINATION " + common.replace("KAPPA=5", "KAPPA=0"),
+ "KAPPA",
+ ),
+ (
+ "bad-reference",
+ "VORONOI_COORDINATION "
+ + common.replace("REFERENCE=1.5,1.2,1.1,2.2", "REFERENCE=1,2"),
+ "REFERENCE",
+ ),
+ (
+ "duplicate",
+ "VORONOI_COORDINATION "
+ + common.replace("CENTERS=1,2,3,4", "CENTERS=1,1,3,4"),
+ "duplicate",
+ ),
+ (
+ "overlap",
+ "VORONOI_COORDINATION "
+ + common.replace("ASSIGNED=5,6,7,8,9,10", "ASSIGNED=1,6,7,8,9,10"),
+ "disjoint",
+ ),
+ ("bad-power", "VORONOI_COORDINATION " + common + " POWER=3", "POWER"),
+ ("bad-select", "VORONOI_COORDINATION " + common + " SELECT=5", "SELECT"),
+ (
+ "bad-groups",
+ "VORONOI_DISTANCE " + common + " GROUP1=1,2 GROUP2=2,3",
+ "disjoint",
+ ),
+ ("bad-axis", "VORONOI_POSITION " + common + " AXIS=W ORIGIN=0", "AXIS"),
+ (
+ "bad-tolerance",
+ "VORONOI_POSITION " + common + " AXIS=X ORIGIN=0 TOLERANCE=0",
+ "TOLERANCE",
+ ),
+ (
+ "zero-weight",
+ "VORONOI_POSITION CENTERS=1 ASSIGNED=5 REFERENCE=1 KAPPA=5 AXIS=X ORIGIN=0 NORMALIZE",
+ "TOLERANCE",
+ ),
+ (
+ "bad-backend",
+ "VORONOI_COORDINATION " + common + " BACKEND=UNKNOWN",
+ "BACKEND",
+ ),
+ ]
+ for name, definition, expected in invalid:
+ for mode, backend in modes.items():
+ suffix = "" if name == "bad-backend" else backend
+ directory, code = run(
+ name + "-" + mode,
+ ["v: " + definition + suffix, "PRINT ARG=v FILE=values"],
+ )
+ assert code != 0, directory
+ assert re.search(expected, (directory / "stdout.log").read_text(), re.I), (
+ directory
+ )
+ results["negative"].append(dict(case=name, mode=mode, returncode=code))
+ for name, changed_atom, definition in [
+ ("coincident-assigned", 4, "VORONOI_COORDINATION " + common),
+ ("coincident-centers", 1, "VORONOI_DISTANCE " + common + " GROUP1=1 GROUP2=2"),
+ ]:
+ coordinates = [row.copy() for row in positions]
+ coordinates[changed_atom] = positions[0].copy()
+ for mode, backend in modes.items():
+ directory, code = run(
+ name + "-" + mode,
+ ["v: " + definition + backend, "PRINT ARG=v FILE=values"],
+ coordinates=coordinates,
+ )
+ assert code != 0, directory
+ assert re.search(
+ "zero|separation|forward failed|distance",
+ (directory / "stdout.log").read_text(),
+ re.I,
+ ), directory
+ results["negative"].append(dict(case=name, mode=mode, returncode=code))
+ if not arguments.cpu_only:
+ for name, suffix, box in [
+ ("missing-library", " CUDA_LIBRARY=missing-backend.so", "7,8,9"),
+ (
+ "empty-nlist",
+ " CUDA_LIBRARY="
+ + arguments.library
+ + " NLIST NL_CUTOFF=0.02 NL_STRIDE=3",
+ "7,8,9",
+ ),
+ (
+ "strict-triclinic",
+ " CUDA_LIBRARY=" + arguments.library,
+ "7,0,0,0.8,8,0,0.4,0.7,9",
+ ),
+ ]:
+ lines = [
+ "v: VORONOI_COORDINATION " + common + " BACKEND=CUDA" + suffix,
+ "PRINT ARG=v FILE=values",
+ ]
+ directory, code = run(name, lines, box=box)
+ assert code != 0, directory
+ if name == "empty-nlist":
+ assert (
+ "no CENTER inside the candidate list"
+ in (directory / "stdout.log").read_text()
+ )
+ results["negative"].append(dict(case=name, returncode=code))
+ results["status"] = "PASSED"
+ (work / "RESULTS.json").write_text(json.dumps(results, indent=2) + "\n")
+ print(json.dumps(results, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/reactive-voronoi-cuda/regtest/device_check.cpp b/plugins/reactive-voronoi-cuda/regtest/device_check.cpp
new file mode 100644
index 0000000000..413a62a599
--- /dev/null
+++ b/plugins/reactive-voronoi-cuda/regtest/device_check.cpp
@@ -0,0 +1,164 @@
+/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Copyright (c) 2026 Reactive Voronoi contributors
+ (see the PEOPLE file at the root of the distribution for a list of names)
+
+ See http://www.plumed.org for more information.
+
+ This file is part of plumed, version 2.
+
+ plumed is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ plumed is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with plumed. If not, see .
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+void check(cudaError_t status) {
+ if(status!=cudaSuccess) {
+ throw std::runtime_error(cudaGetErrorString(status));
+ }
+}
+
+void currentIs(int expected) {
+ int current=-1;
+ check(cudaGetDevice(¤t));
+ if(current!=expected) {
+ throw std::runtime_error("The MD current device changed");
+ }
+}
+
+std::array evaluate(const std::string& backend, int mdDevice,
+ const std::string& log) {
+ PLMD::Plumed plumed;
+ int atoms=4;
+ int precision=8;
+ double timestep=0.0005;
+ plumed.cmd("setNatoms",&atoms);
+ plumed.cmd("setRealPrecision",&precision);
+ plumed.cmd("setTimestep",×tep);
+ plumed.cmd("setLogFile",log.c_str());
+ if(mdDevice>=0) {
+ plumed.cmd("setGpuDeviceId",&mdDevice);
+ }
+ plumed.cmd("init");
+ const std::string line="q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4"
+ " REFERENCE=1 KAPPA=5 POWER=2"+backend;
+ plumed.cmd("readInputLine",line.c_str());
+ plumed.cmd("readInputLine","r: RESTRAINT ARG=q AT=0.3 KAPPA=3");
+ std::array positions{{0.1,0.2,0.1, 1.5,0.3,0.2, 0.4,0.3,0.2, 1.1,0.5,0.2}};
+ std::array forces{};
+ std::array masses{{1,1,1,1}};
+ std::array box{{3,0,0,0,3,0,0,0,3}},virial{};
+ int step=0;
+ plumed.cmd("setStep",&step);
+ plumed.cmd("setPositions",positions.data());
+ plumed.cmd("setMasses",masses.data());
+ plumed.cmd("setBox",box.data());
+ plumed.cmd("setForces",forces.data());
+ plumed.cmd("setVirial",virial.data());
+ plumed.cmd("calc");
+ return forces;
+}
+
+int main(int argc,char** argv) {
+ if(argc!=2) {
+ return 2;
+ }
+ int count=0;
+ check(cudaGetDeviceCount(&count));
+ if(count<2) {
+ std::cout<<"SKIP two GPUs are needed for distinct MD/CV contexts\n";
+ return 77;
+ }
+ check(cudaSetDevice(1));
+ double* mdMemory=nullptr;
+ check(cudaMalloc(&mdMemory,16*sizeof(double)));
+ const std::string library=argv[1];
+ const auto reference=evaluate("",-1,"cpu.log");
+ double maximum=0;
+ for(int requested: {
+ 0,-1
+ }) {
+ const std::string log=requested==0 ? "md-selected.log" : "md-current.log";
+ const auto forces=evaluate(" BACKEND=CUDA CUDA_LIBRARY="+library,requested,log);
+ currentIs(1);
+ check(cudaMemset(mdMemory,0,16*sizeof(double)));
+ check(cudaDeviceSynchronize());
+ for(unsigned index=0; index(stream)), {});
+ const std::string device=requested==0 ? "device 0" : "device 1";
+ if(text.find("selected CUDA ("+device)==std::string::npos) {
+ throw std::runtime_error("The logged CV device differs from the requested device");
+ }
+ }
+ for(int repeat=0; repeat<8; ++repeat) {
+ void* libraryHandle=dlopen(library.c_str(),RTLD_NOW|RTLD_LOCAL);
+ if(!libraryHandle) {
+ throw std::runtime_error(dlerror());
+ }
+ const auto create=reinterpret_cast(
+ dlsym(libraryHandle,"reactive_voronoi_create_v2"));
+ const auto destroy=reinterpret_cast(
+ dlsym(libraryHandle,"reactive_voronoi_destroy_v1"));
+ const auto device=reinterpret_cast(
+ dlsym(libraryHandle,"reactive_voronoi_device_v1"));
+ const auto forward=reinterpret_cast(
+ dlsym(libraryHandle,"reactive_voronoi_forward_v1"));
+ const auto backward=reinterpret_cast(
+ dlsym(libraryHandle,"reactive_voronoi_backward_v1"));
+ if(!create || !destroy || !device || !forward || !backward) {
+ throw std::runtime_error("CUDA library ABI is incomplete");
+ }
+ if(create(2,2,count)!=nullptr) {
+ throw std::runtime_error("An invalid requested GPU was accepted");
+ }
+ currentIs(1);
+ void* context=create(2,2,0);
+ if(!context || device(context)!=0) {
+ throw std::runtime_error("CUDA context has the wrong owner");
+ }
+ currentIs(1);
+ const double positions[12]= {0.1,0.2,0.1, 1.5,0.3,0.2, 0.4,0.3,0.2, 1.1,0.5,0.2};
+ const double box[3]= {3,3,3};
+ const double sensitivity[2]= {1.2,-0.7};
+ double occupancy[2],derivatives[12],virial[9];
+ if(forward(context,positions,box,1,5,occupancy)!=0 ||
+ backward(context,sensitivity,derivatives,virial)!=0) {
+ throw std::runtime_error("CUDA context evaluation failed");
+ }
+ currentIs(1);
+ destroy(context);
+ currentIs(1);
+ dlclose(libraryHandle);
+ check(cudaMemset(mdMemory,0,16*sizeof(double)));
+ check(cudaDeviceSynchronize());
+ currentIs(1);
+ }
+ check(cudaFree(mdMemory));
+ if(maximum>2e-10) {
+ throw std::runtime_error("Device-selection force parity failed");
+ }
+ std::cout<<"PASS requested/current device selection, restore and MD allocation lifetime\n"
+ <<"maximum_force_difference "<
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+struct Case {
+ std::string name;
+ std::string action;
+ std::string options;
+ double kappa=5.0;
+ bool triclinic=false;
+};
+
+struct System {
+ PLMD::Plumed plumed;
+ std::vector positions{
+ 0.2,0.3,0.4, 1.3,0.6,0.2, 2.2,1.7,0.8, 3.0,2.4,1.9,
+ 0.4,0.3,0.4, 0.1,0.5,0.4, 0.2,0.2,0.6,
+ 1.4,0.7,0.3, 2.3,1.8,0.9, 3.1,2.5,2.0
+ };
+ std::vector forces=std::vector(30,0.0);
+ std::vector masses=std::vector(10,1.0);
+ std::array box{{7,0,0,0,8,0,0,0,9}};
+ std::array virial{};
+ std::array values{};
+ double energy=0.0;
+
+ System(const Case& specification, bool shared, const std::string& mode,
+ const std::string& backend, unsigned identifier, bool legacy=false) {
+ int precision=8;
+ int atoms=10;
+ double timestep=0.0005;
+ plumed.cmd("setRealPrecision",&precision);
+ plumed.cmd("setNatoms",&atoms);
+ plumed.cmd("setTimestep",×tep);
+ const std::string log="system-"+std::to_string(identifier)+".log";
+ plumed.cmd("setLogFile",log.c_str());
+ plumed.cmd("init");
+ if(specification.triclinic) {
+ box[3]=0.8;
+ box[6]=0.4;
+ box[7]=0.7;
+ // A lattice translation exercises the image used by Cartesian positions.
+ positions[3]+=0.8;
+ positions[4]+=8.0;
+ }
+ const std::string control=(shared || legacy ? "" : " NO_SHARE")+mode+backend;
+ const std::string atomsInput=" CENTERS=1,2,3,4 ASSIGNED=5,6,7,8,9,10";
+ const std::string reference=" REFERENCE=1.5,1.2,1.1,2.2";
+ const std::string kappa=" KAPPA="+std::to_string(specification.kappa);
+ auto read=[&](const std::string& line) {
+ plumed.cmd("readInputLine",line.c_str());
+ };
+ read("a: "+specification.action+atomsInput+reference+kappa+
+ " "+specification.options+control);
+ read("b: VORONOI_COORDINATION"+atomsInput+reference+kappa+
+ " POWER=2 SELECT=1,3 COEFFICIENTS=1.1,0.7"+control);
+ read("c: VORONOI_COORDINATION"+atomsInput+reference+
+ " KAPPA=8 POWER=2 SIGN=NEGATIVE"+control);
+ read("d: "+specification.action+
+ " CENTERS=3,1,4,2 ASSIGNED=10,8,5,9,7,6"
+ " REFERENCE=1.1,1.5,2.2,1.2"+kappa+
+ " "+specification.options+control);
+ read("bias: RESTRAINT ARG=a,b,c,d AT=0.3,-0.1,0.2,0.3 KAPPA=3,2,1,3");
+ for(unsigned index=0; index('a'+index));
+ long rank=-1;
+ plumed.cmd("getDataRank "+label,&rank);
+ plumed.cmd("setMemoryForData "+label,&values[index]);
+ }
+ }
+
+ void evaluate(int step=7) {
+ std::fill(forces.begin(),forces.end(),0.0);
+ virial.fill(0.0);
+ plumed.cmd("setStep",&step);
+ plumed.cmd("setPositions",positions.data());
+ plumed.cmd("setMasses",masses.data());
+ plumed.cmd("setBox",box.data());
+ plumed.cmd("setForces",forces.data());
+ plumed.cmd("setVirial",virial.data());
+ plumed.cmd("calc");
+ plumed.cmd("getBias",&energy);
+ }
+};
+
+int main(int argc,char** argv) {
+ const bool legacy=argc>1 && std::string(argv[1])=="--legacy";
+ const std::string backend=argc>1 && !legacy ? argv[1] : "";
+ if(argc>2 && std::string(argv[2])=="--timing") {
+ Case specification{"tiny-cv","VORONOI_COORDINATION","POWER=2"};
+ System system(specification,true," NOPBC",backend,0);
+ for(int step=0; step<50; ++step) {
+ system.evaluate(step);
+ }
+ constexpr int timedCalls=1000;
+ for(int repeat=0; repeat<3; ++repeat) {
+ const auto start=std::chrono::steady_clock::now();
+ for(int step=0; step(
+ std::chrono::steady_clock::now()-start).count();
+ std::cout<<"tiny_cv_ms_per_call "< cases{
+ {"coord-power1","VORONOI_COORDINATION","POWER=1"},
+ {"coord-power2","VORONOI_COORDINATION","POWER=2"},
+ {"coord-positive","VORONOI_COORDINATION","POWER=1 SIGN=POSITIVE"},
+ {"coord-negative","VORONOI_COORDINATION","POWER=2 SIGN=NEGATIVE"},
+ {"coord-select","VORONOI_COORDINATION","POWER=2 SELECT=2,4 COEFFICIENTS=1.3,-0.4"},
+ {"coord-diffuse","VORONOI_COORDINATION","POWER=2",0.5},
+ {"coord-sharp","VORONOI_COORDINATION","POWER=2",100.0},
+ {"distance-cross","VORONOI_DISTANCE","GROUP1=1,3 GROUP2=2,4"},
+ {"distance-within","VORONOI_DISTANCE","GROUP1=1,2,3,4"},
+ {"position-x","VORONOI_POSITION","AXIS=X ORIGIN=0.35"},
+ {"position-y","VORONOI_POSITION","AXIS=Y ORIGIN=-0.7"},
+ {"position-z","VORONOI_POSITION","AXIS=Z ORIGIN=1.2"},
+ {"position-positive","VORONOI_POSITION","AXIS=X ORIGIN=0.35 SIGN=POSITIVE NORMALIZE"},
+ {"position-negative","VORONOI_POSITION","AXIS=Y ORIGIN=-0.7 SIGN=NEGATIVE NORMALIZE"},
+ {"position-positive-raw","VORONOI_POSITION","AXIS=X ORIGIN=0.35 SIGN=POSITIVE"},
+ {"position-negative-raw","VORONOI_POSITION","AXIS=Y ORIGIN=-0.7 SIGN=NEGATIVE"},
+ {"position-absolute-raw","VORONOI_POSITION","AXIS=Z ORIGIN=1.2 ABSOLUTE"},
+ {"position-absolute","VORONOI_POSITION","AXIS=Z ORIGIN=1.2 ABSOLUTE NORMALIZE"},
+ {"position-subset","VORONOI_POSITION","AXIS=X ORIGIN=-0.4 SELECT=1,4 NORMALIZE"},
+ {"position-triclinic-y","VORONOI_POSITION","AXIS=Y ORIGIN=-2.7 NORMALIZE",5.0,true}
+ };
+ double maximumValues=0.0;
+ double maximumForces=0.0;
+ double maximumVirial=0.0;
+ double maximumFiniteForce=0.0;
+ double maximumFiniteVirial=0.0;
+ unsigned evaluations=0;
+ unsigned identifier=0;
+ std::ofstream metrics("metrics");
+ metrics<2e-5) {
+ std::cerr<<"virial FD "<
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+struct System {
+ PLMD::Plumed p;
+ std::vector x{0.1,0.2,0.1, 1.5,0.3,0.2, 0.4,0.3,0.2, 1.1,0.5,0.2};
+ std::vector f=std::vector(12,0), m=std::vector(4,1);
+ std::array box{{3,0,0,0,3,0,0,0,3}}, vir{};
+ double energy=0;
+ System(bool share, const std::string& mode, const std::string& backend="") {
+ int precision=8,n=4;
+ double dt=0.0005;
+ p.cmd("setRealPrecision",&precision);
+ p.cmd("setNatoms",&n);
+ p.cmd("setTimestep",&dt);
+ p.cmd("setLogFile","/dev/null");
+ p.cmd("init");
+ const std::string extra=(share ? "" : " NO_SHARE")+mode+backend;
+ auto read=[&](const std::string& s) {
+ p.cmd("readInputLine",s.c_str());
+ };
+ read("a: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=0.8,1.2 POWER=2"+extra);
+ read("b: VORONOI_DISTANCE CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 GROUP1=1 GROUP2=2"+extra);
+ read("c: VORONOI_POSITION CENTERS=1,2 ASSIGNED=3,4 KAPPA=8 REFERENCE=0.9,1.1 AXIS=Y ORIGIN=0.3"+extra);
+ read("d: VORONOI_COORDINATION CENTERS=2,1 ASSIGNED=4,3 KAPPA=5 REFERENCE=1.2,0.8 SELECT=1 COEFFICIENTS=1.3 POWER=2"+extra);
+ read("bias: RESTRAINT ARG=a,b,c,d AT=0.3,-0.1,0.2,0.05 KAPPA=3,2,1,4");
+ }
+ void eval(int step=7) {
+ std::fill(f.begin(),f.end(),0);
+ vir.fill(0);
+ p.cmd("setStep",&step);
+ p.cmd("setPositions",x.data());
+ p.cmd("setMasses",m.data());
+ p.cmd("setBox",box.data());
+ p.cmd("setForces",f.data());
+ p.cmd("setVirial",vir.data());
+ p.cmd("calc");
+ p.cmd("getBias",&energy);
+ }
+};
+
+int main(int argc,char** argv) {
+ std::ofstream out("output");
+ double maxDifference=0,maxFiniteDifference=0;
+ const std::string backend=argc>1 ? argv[1] : "";
+ for(const std::string mode: {
+ "", " NOPBC", " NLIST NL_CUTOFF=2 NL_STRIDE=1",
+ " NLIST NL_CUTOFF=2 NL_STRIDE=3 NL_SKIN=0.4"
+ }) {
+ if(!backend.empty() && mode.find("NLIST")!=std::string::npos) {
+ continue;
+ }
+ System shared(true,mode,backend), independent(false,mode);
+ for(int k=0; k<12; ++k) {
+ // Repeated step, changed coordinates and box, then skipped steps.
+ shared.x[6]+=0.004;
+ shared.box[0]+=0.003;
+ independent.x=shared.x;
+ independent.box=shared.box;
+ const int step=k<8 ? 7 : 7+3*k;
+ shared.eval(step);
+ independent.eval(step);
+ maxDifference=std::max(maxDifference,std::abs(shared.energy-independent.energy));
+ for(unsigned i=0; i<12; ++i) {
+ maxDifference=std::max(maxDifference,std::abs(shared.f[i]-independent.f[i]));
+ }
+ for(unsigned i=0; i<9; ++i) {
+ maxDifference=std::max(maxDifference,std::abs(shared.vir[i]-independent.vir[i]));
+ }
+ }
+ shared.eval();
+ const auto force=shared.f;
+ const double h=1e-6;
+ for(unsigned i=0; i<12; ++i) {
+ const double x=shared.x[i];
+ shared.x[i]=x+h;
+ shared.eval();
+ const double plus=shared.energy;
+ shared.x[i]=x-h;
+ shared.eval();
+ const double minus=shared.energy;
+ shared.x[i]=x;
+ maxFiniteDifference=std::max(maxFiniteDifference,std::abs(force[i]+(plus-minus)/(2*h)));
+ }
+ }
+ std::cout<<"max_shared_force_energy_virial_error "<.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#include "Colvar.h"
+#include "ReactiveVoronoiCuda.h"
#include "core/ActionRegister.h"
+#include "core/ActionSet.h"
+#include "core/PlumedMain.h"
#include "tools/Communicator.h"
#include "tools/NeighborList.h"
#include "tools/OpenMP.h"
@@ -31,6 +34,8 @@
#include
#include
#include
+#include
+#include