diff --git a/.github/workflows/gpuPluginsWF.yml b/.github/workflows/gpuPluginsWF.yml index a60f829718..0914ac7901 100644 --- a/.github/workflows/gpuPluginsWF.yml +++ b/.github/workflows/gpuPluginsWF.yml @@ -4,8 +4,8 @@ name: GPU plugins # installed PLUMED, and the tests that do not need a GPU are run (loading the plugin, input # errors, the error when there is no GPU). The kernels themselves need a real GPU. # -# cudaCoord is compiled with more than one version of the CUDA toolkit, taken from conda-forge -# (no driver is needed to compile, and the runtime is linked statically by nvcc). +# Both plugins are compiled with more than one version of the CUDA toolkit, taken from conda-forge +# (no driver is needed to compile). on: workflow_call: @@ -68,7 +68,7 @@ jobs: "$HOME/cuda-$v/bin/nvcc" --version done - - name: Build and test cudaCoord + - name: Build and test CUDA plugins run: | export PLUMED_KERNEL="$HOME/opt/lib/libplumedKernel.so" cd plugins/cudaCoord @@ -81,5 +81,9 @@ jobs: ./configure.sh make -j 4 make check-nogpu + make -C ../reactive-voronoi-cuda clean + # Voronoi uses shared cudart. Set an explicit architecture on the GPU-less runner. + LD_LIBRARY_PATH="$HOME/cuda-$v/lib:$HOME/cuda-$v/targets/x86_64-linux/lib:${LD_LIBRARY_PATH:-}" \ + make -C ../reactive-voronoi-cuda CUDA_ARCH=sm_80 check-nogpu echo "::endgroup::" done diff --git a/CHANGES/v2.11.md b/CHANGES/v2.11.md index d07123e9b6..8b5f7ae370 100644 --- a/CHANGES/v2.11.md +++ b/CHANGES/v2.11.md @@ -175,6 +175,11 @@ The entries below give the details; the main cases are: #### Collective variables, molecules and virtual atoms + - Compatible [VORONOI_COORDINATION](VORONOI_COORDINATION.md), [VORONOI_DISTANCE](VORONOI_DISTANCE.md) and + [VORONOI_POSITION](VORONOI_POSITION.md) actions share the assignment calculation by default. Use NO_SHARE + for independent CPU evaluation. BACKEND selects CPU or the optional CUDA implementation, which is made + available with [LOAD](LOAD.md). BACKEND=AUTO falls back to CPU when the CUDA backend is unavailable. + - When using [MOLINFO](MOLINFO.md) with the `WHOLE` flag, PBCs in the following actions will be reconstructed using a minimum spanning tree based on the coordinates stored in the MOLINFO reference PDB. Fixed the tree construction and parent/child indexing in this reconstruction: previously actions such as [CENTER](CENTER.md), [RMSD](RMSD.md), and [GYRATION](GYRATION.md) could silently use split coordinates (see [#1496](https://github.com/plumed/plumed2/issues/1496)). - When the reference pdb of [MOLINFO](MOLINFO.md) with the `WHOLE` flag has a CRYST1 record with space group P 1, PLUMED now checks along each chain that the reference is whole in that box, and writes a warning to the log naming the atoms that are across the periodic boundary from the atom before them. Before, a split reference made [WHOLEMOLECULES](WHOLEMOLECULES.md) split whole molecules without any warning. diff --git a/plugins/reactive-voronoi-cuda/Makefile b/plugins/reactive-voronoi-cuda/Makefile new file mode 100644 index 0000000000..0b10428291 --- /dev/null +++ b/plugins/reactive-voronoi-cuda/Makefile @@ -0,0 +1,38 @@ +PLUMED ?= plumed +NVCC ?= nvcc +CUDA_ARCH ?= native +NVCCFLAGS ?= -O3 -std=c++17 + +.PHONY: all clean check check-nogpu astyle +all: + +ifneq ($(filter-out clean astyle,$(or $(MAKECMDGOALS),all)),) + SOEXT := $(shell $(PLUMED) --no-mpi info --soext) + ifeq ($(SOEXT),) + $(error Set PLUMED to an installed plumed executable) + endif + TARGET = libReactiveVoronoiCuda.$(SOEXT) + PLUMED_INCLUDE ?= $(shell $(PLUMED) --no-mpi info --include-dir) + PLUMED_KERNEL ?= $(shell $(PLUMED) --no-mpi info --lib-dir)/libplumedKernel.$(SOEXT) + + # Keep the runtime alive across PLUMED destruction inside an MD process. + ifeq ($(shell uname -s),Linux) + PLATFORM_LDFLAGS = -Xlinker -z -Xlinker nodelete -Xlinker -rpath -Xlinker "$(dir $(PLUMED_KERNEL))" + endif + +all: $(TARGET) + +$(TARGET): src/ReactiveVoronoiCuda.cu $(PLUMED_KERNEL) + $(NVCC) $(NVCCFLAGS) -arch=$(CUDA_ARCH) --cudart=shared -Xcompiler=-fPIC -shared -I"$(PLUMED_INCLUDE)" $(PLATFORM_LDFLAGS) $(LDFLAGS) $< "$(PLUMED_KERNEL)" -o $@ + +check: all + $(MAKE) -C regtest check PLUMED="$(PLUMED)" LIBRARY="$(abspath $(TARGET))" +check-nogpu: all + CUDA_VISIBLE_DEVICES="" $(MAKE) -C regtest check-nogpu PLUMED="$(PLUMED)" LIBRARY="$(abspath $(TARGET))" +endif + +astyle: + @../astyle.sh + +clean: + rm -f libReactiveVoronoiCuda.so libReactiveVoronoiCuda.dylib diff --git a/plugins/reactive-voronoi-cuda/README.md b/plugins/reactive-voronoi-cuda/README.md new file mode 100644 index 0000000000..0fb2a07d9a --- /dev/null +++ b/plugins/reactive-voronoi-cuda/README.md @@ -0,0 +1,193 @@ +# 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 plugin has not been +loaded or the device or requested calculation is unsupported. + +~~~plumed +LOAD FILE=./libReactiveVoronoiCuda.so +q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2 BACKEND=CUDA +~~~ + +BACKEND=AUTO opts into capability detection. It selects CUDA when the plugin has +been loaded and the 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 +~~~ + +Place LOAD before the Voronoi actions. 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 stop the calculation. +For a rejected center–assigned pair, the message includes the MD step and +the atom numbers from the input selections. + +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. + +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. + +## Using CUDA Voronoi with other actions and force fields + +The existing cudaCoord plugin and the CUDA Voronoi backend can run in the +same PLUMED input. Load both plugins and select the Voronoi backend on +the Voronoi action. + +~~~plumed +LOAD FILE=./CudaCoordination.so +LOAD FILE=./libReactiveVoronoiCuda.so +c: CUDACOORDINATION GROUPA=1,2 GROUPB=3,4 R_0=0.32 D_MAX=1.25 +q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4 KAPPA=5 REFERENCE=1 POWER=2 BACKEND=CUDA +PRINT ARG=c,q FILE=COLVAR +~~~ + +The example uses PLUMED's default length unit (nm). The two plugins keep +their own GPU data and can use the same device. The MD engine can also use +that device for the potential, as in the single-GPU DeePMD examples. The CV's backend is chosen independently of +the potential. For a CPU force field, the default shared CPU CV requires no +CUDA library. BACKEND=CUDA can instead offload the Voronoi assignment if +the run and GPU meet the requirements above. Coordinates and bias +derivatives pass through the regular host PLUMED interface. + +## 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 PLUMED=/path/to/plumed 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 library in a versioned directory and pass its path to LOAD. Use +the same PLUMED build at compile time and at runtime. The Makefile uses the +shared-library extension reported by PLUMED. + +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. + +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. CUDA FP64 +atomic additions can sum in a different order between runs, so the final +digits of values and derivatives can vary. 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. The Voronoi plugin registers its assignment +backend after LOAD. Its BACKEND keyword belongs to the three Voronoi 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-plugin fallback cases on a CPU-only host with: + +~~~bash +python3 regtest/backend_checks.py --plumed /absolute/path/bin/plumed --cpu-only +~~~ + +With a CUDA toolkit, `make CUDA_ARCH=sm_80 check-nogpu` also tests loading +the real plugin with no visible GPU. It checks the numerical CPU fallback +for AUTO and the initialization error for an explicit CUDA request. + +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 +PLUMED_VORONOI_TEST_PLUGIN=/absolute/path/libReactiveVoronoiCuda.so \ + /absolute/path/to/regtest/basic/rt-reactive-voronoi-backends/tmp/exe " BACKEND=CUDA" +~~~ + +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/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..3c3c1fe2dc --- /dev/null +++ b/plugins/reactive-voronoi-cuda/regtest/Makefile @@ -0,0 +1,15 @@ +PYTHON ?= python3 +PLUMED ?= plumed +LIBRARY ?= ../libReactiveVoronoiCuda.so + +.PHONY: check check-nogpu clean +check: + rm -rf tmp + $(PYTHON) backend_checks.py --plumed $(PLUMED) --library $(abspath $(LIBRARY)) --work $(CURDIR)/tmp + +check-nogpu: + rm -rf tmp-nogpu + $(PYTHON) backend_checks.py --plumed "$(PLUMED)" --cpu-only --library "$(abspath $(LIBRARY))" --work "$(CURDIR)/tmp-nogpu" + +clean: + rm -rf tmp tmp-nogpu 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..687b44156a --- /dev/null +++ b/plugins/reactive-voronoi-cuda/regtest/backend_checks.py @@ -0,0 +1,506 @@ +"""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", + ] + plugin = arguments.library and Path(arguments.library).resolve() + modes = { + "independent": " NO_SHARE", + "shared": " BACKEND=CPU", + "auto-missing": " BACKEND=AUTO", + } + if not arguments.cpu_only: + modes.update( + { + "cuda": " BACKEND=CUDA", + "auto": " BACKEND=AUTO", + } + ) + results = {"work": str(work), "positive": [], "negative": []} + + def run(name, lines, coordinates=None, box="7,8,9", frames=None, load=False): + 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") + if load: + lines = [f"LOAD FILE={plugin}", *lines] + (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, load=mode in ("cuda", "auto") + ) + 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) + ) + + # At half the box length two images have the same distance but opposite + # derivatives. Check the image convention against the independent CPU CV. + half_box_frames = [ + [[0, 0, 0], [1, 0, 0], [x, 0, 0]] for x in (2, -2, 6, 2.000001, 1.999999) + ] + for mode, backend in modes.items(): + directory, code = run( + "half-box-" + mode, + [ + "q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3 SELECT=1 KAPPA=1 REFERENCE=0 POWER=1" + + backend, + "PRINT ARG=q FILE=values FMT=%.17g", + "DUMPDERIVATIVES ARG=q FILE=derivatives FMT=%.17g", + ], + box="4,4,4", + frames=half_box_frames, + load=mode in ("cuda", "auto"), + ) + assert code == 0, directory + data = {key: read_numbers(directory / key) for key in ("values", "derivatives")} + if mode == "independent": + reference = data + errors = { + key: compare(reference[key], data[key], directory / key) for key in data + } + results["positive"].append(dict(geometry="half-box", 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, + load=mode in ("cuda", "auto"), + ) + 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]], + load=mode in ("cuda", "auto"), + ) + 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)) + + # A single center has unit occupancy and zero derivatives. With a large + # finite KAPPA, fusing the score multiplication with the softmax shift + # can otherwise leave a large residual even at the maximum. + for mode, backend in modes.items(): + directory, code = run( + "large-finite-score-" + mode, + [ + "q: VORONOI_COORDINATION CENTERS=1 ASSIGNED=2 KAPPA=1e308 REFERENCE=0 NOPBC" + + backend, + "PRINT ARG=q FILE=values FMT=%.17g", + "DUMPDERIVATIVES ARG=q FILE=derivatives FMT=%.17g", + ], + coordinates=[[0, 0, 0], [0.43, 0.19, 0]], + load=mode in ("cuda", "auto"), + ) + assert code == 0 and 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="large-finite-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"], + load=mode in ("cuda", "auto"), + ) + 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, + load=mode in ("cuda", "auto"), + ) + 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)) + strict_cases = [ + ("missing-plugin", "", "7,8,9", False, "No CUDA Voronoi backend is available") + ] + if arguments.cpu_only and plugin: + # The plugin is loaded here, so this exercises device discovery + # separately from the missing-plugin case. + reference = None + for tag, backend in (("independent", "NO_SHARE"), ("auto", "BACKEND=AUTO")): + directory, code = run( + "no-device-" + tag, + [ + "q: VORONOI_COORDINATION " + common + " " + backend, + "PRINT ARG=q FILE=values FMT=%.17g", + "DUMPDERIVATIVES ARG=q FILE=derivatives FMT=%.17g", + ], + load=tag == "auto", + ) + assert code == 0, directory + data = { + key: read_numbers(directory / key) for key in ("values", "derivatives") + } + if reference is None: + reference = data + continue + log = (directory / "stdout.log").read_text() + assert "selected CPU" in log and "No CUDA device is available" in log, ( + directory + ) + errors = { + key: compare(reference[key], data[key], directory / key) for key in data + } + results["positive"].append( + dict(geometry="no-device", mode=tag, errors=errors) + ) + strict_cases.append( + ("no-device-cuda", "", "7,8,9", True, "No CUDA device is available") + ) + if not arguments.cpu_only: + strict_cases += [ + ( + "empty-nlist", + " NLIST NL_CUTOFF=0.02 NL_STRIDE=3", + "7,8,9", + True, + "no CENTER inside the candidate list", + ), + ( + "strict-triclinic", + "", + "7,0,0,0.8,8,0,0.4,0.7,9", + True, + "CUDA backend does not support triclinic", + ), + ] + for name, suffix, box, load, reason in strict_cases: + lines = [ + "v: VORONOI_COORDINATION " + common + " BACKEND=CUDA" + suffix, + "PRINT ARG=v FILE=values", + ] + directory, code = run(name, lines, box=box, load=load) + assert code != 0, directory + log = (directory / "stdout.log").read_text() + assert "label v" in log and reason in log, directory + results["negative"].append(dict(case=name, returncode=code)) + for mode, backend in modes.items(): + directory, code = run( + "degenerate-box-" + mode, + [ + "q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3 KAPPA=1 REFERENCE=0" + + backend, + "PRINT ARG=q FILE=values", + ], + coordinates=[[0, 0, 0], [1e-6, 0, 0], [2.2e-6, 0, 0]], + box="4e-6,4e-6,4e-6", + load=mode in ("cuda", "auto"), + ) + log = (directory / "stdout.log").read_text() + assert code != 0 and "label q" in log and "degenerate" in log, directory + results["negative"].append( + dict(case="degenerate-box", mode=mode, returncode=code) + ) + + if not arguments.cpu_only: + for name, suffix in [ + ("full", ""), + ("buffered", " NLIST NL_CUTOFF=3 NL_STRIDE=1"), + ]: + directory, code = run( + "invalid-pair-" + name, + [ + "q: VORONOI_COORDINATION CENTERS=4,1 ASSIGNED=3,2 KAPPA=1 REFERENCE=0 BACKEND=AUTO" + + suffix, + "PRINT ARG=q FILE=values", + ], + frames=[ + [[0, 0, 0], [1, 0, 0], [2, 0, 0], [2.5, 0, 0]], + [[0, 0, 0], [1, 0, 0], [2, 0, 0], [1, 0, 0]], + ], + load=True, + ) + log = (directory / "stdout.log").read_text() + assert code != 0 and "label q" in log, directory + assert ( + "zero or near-zero CENTER-ASSIGNED distance step=1 center_atom=4 assigned_atom=2" + in log + ), directory + results["negative"].append( + dict(case="invalid-pair-" + name, returncode=code) + ) + for name, coordinate, kappa, reason in ( + ("nonfinite-distance", "1e200", "1", "non-finite CENTER-ASSIGNED distance"), + ( + "overflow-score", + "2", + "1e308", + "non-finite KAPPA times CENTER-ASSIGNED distance", + ), + ): + directory, code = run( + name, + [ + f"q: VORONOI_COORDINATION CENTERS=1 ASSIGNED=2 REFERENCE=0 KAPPA={kappa} NOPBC BACKEND=CUDA", + "PRINT ARG=q FILE=values", + ], + coordinates=[[0, 0, 0], [coordinate, 0, 0]], + load=True, + ) + log = (directory / "stdout.log").read_text() + assert ( + code != 0 and reason + " step=0 center_atom=1 assigned_atom=2" in log + ), directory + 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..ec91f7feb8 --- /dev/null +++ b/plugins/reactive-voronoi-cuda/regtest/device_check.cpp @@ -0,0 +1,145 @@ +/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + 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 + +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& library, 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"); + if(!library.empty()) { + plumed.cmd("readInputLine","LOAD FILE="+library); + } + const std::string line="q: VORONOI_COORDINATION CENTERS=1,2 ASSIGNED=3,4" + " REFERENCE=1 KAPPA=5 POWER=2"+ + std::string(library.empty() ? "" : " BACKEND=CUDA"); + 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==0) { + std::cout<<"SKIP no visible CUDA device\n"; + return 77; + } + // With two devices, verify that offloading to device 0 restores device 1. + const int current=count>1 ? 1 : 0; + check(cudaSetDevice(current)); + 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(library,requested,log); + currentIs(current); + check(cudaMemset(mdMemory,0,16*sizeof(double))); + check(cudaDeviceSynchronize()); + for(unsigned index=0; index(stream)), {}); + const std::string device="device "+std::to_string(requested==0 ? 0 : current); + if(text.find("selected CUDA ("+device)==std::string::npos) { + throw std::runtime_error("The logged CV device differs from the requested device"); + } + } + try { + evaluate(library,count,"invalid-device.log"); + throw std::runtime_error("An invalid requested GPU was accepted"); + } catch(const std::exception& error) { + if(std::string(error.what()).find("CUDA initialization failed")==std::string::npos) { + throw; + } + } + currentIs(current); + for(int repeat=0; repeat<8; ++repeat) { + const auto forces=evaluate(library,0,"repeat.log"); + currentIs(current); + for(unsigned index=0; index2e-10) { + throw std::runtime_error("Device-selection force parity failed"); + } + std::cout<<"PASS requested/current device selection, restore and MD allocation lifetime\n" + <<"visible_devices "<. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ +// FP64 streamed assignments with optional buffered center lists. +#include "plumed/colvar/ReactiveVoronoiBackend.h" +#include "plumed/tools/Pbc.h" +#include +#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; + unsigned long long* invalid=nullptr; + int* offsets=nullptr; + int* candidateCenters=nullptr; + int candidateCapacity=0; + double cutoff=0; + bool useNeighbors=false; + double box[3] {}; + double inverseBox[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(center)*state.numAssigned+assigned; + atomicMin(state.invalid,pair*failureKinds+reason); +} + +template +__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) { + atomicMin(state.invalid,emptyList); + } + 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(assignmentScore(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(assignmentScore(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(assignmentScore(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; +} + +State* createState(int numCenters, int numAssigned, int mdDevice) { + int deviceCount=0; + if(!checkCuda(cudaGetDeviceCount(&deviceCount)) || deviceCount==0) { + throw std::runtime_error("No CUDA device is available"); + } + if(numCenters<=0 || numAssigned<=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(*state->invalid)))) { + release(state); + return nullptr; + } + return state; +} + +int runForward(State& state, const double* positions, const PLMD::Pbc& box, bool pbc, + double kappa, double* occupancy, bool useNeighbors, double cutoff, + const int* offsets, const int* centers, int count) { + 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.getBox()(axis,axis); + state.inverseBox[axis]=box.getInvBox()(axis,axis); + } + 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,0xff,sizeof(*state.invalid),state.stream))) { + return 1; + } + if(useNeighbors) { + forwardKernel<<>>(state); + } else { + forwardKernel<<>>(state); + } + unsigned long long invalid=noFailure; + if(!checkCuda(cudaGetLastError()) || + !checkCuda(cudaMemcpyAsync(occupancy,state.occupancy,state.numCenters*sizeof(double), + cudaMemcpyDeviceToHost,state.stream)) || + !checkCuda(cudaMemcpyAsync(&invalid,state.invalid,sizeof(invalid), + cudaMemcpyDeviceToHost,state.stream)) || + !checkCuda(cudaStreamSynchronize(state.stream))) { + return 1; + } + if(invalid==noFailure) { + return 0; + } + if(invalid==emptyList) { + return 2; + } + const auto pair=invalid/failureKinds; + const char* reasons[]= {"non-finite CENTER-ASSIGNED distance", "zero or near-zero CENTER-ASSIGNED distance", + "non-finite KAPPA times CENTER-ASSIGNED distance" + }; + throw PLMD::colvar::ReactiveVoronoiBackend::InvalidPair(pair/state.numAssigned,pair%state.numAssigned, + reasons[invalid%failureKinds]); +} + +int runBackward(State& state, const double* sensitivity, double* derivatives, double* virial) { + 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; +} + + +class ReactiveVoronoiCuda final : public PLMD::colvar::ReactiveVoronoiBackend { + std::unique_ptr state_; + unsigned long uploadedNeighborVersion_=0; + +public: + ReactiveVoronoiCuda(int centers, int assigned, int device): + state_(createState(centers,assigned,device),release) { + if(!state_) { + throw std::runtime_error("CUDA backend context creation failed on the requested or current device"); + } + } + + int device() const override { + return state_->device; + } + + void forward(const double* positions, const PLMD::Pbc& box, bool pbc, + double kappa, double* occupancy) override { + if(runForward(*state_,positions,box,pbc,kappa,occupancy,false,0,nullptr,nullptr,0)!=0) { + throw std::runtime_error("CUDA reactive Voronoi forward failed; check geometry and CUDA diagnostics"); + } + } + + void forwardNeighbors(const double* positions, const PLMD::Pbc& box, bool pbc, + double kappa, double* occupancy, double cutoff, + const std::vector& offsets, const std::vector& centers, + unsigned long version) override { + const bool upload=uploadedNeighborVersion_!=version; + const int status=runForward(*state_,positions,box,pbc,kappa,occupancy,true,cutoff, + upload ? offsets.data() : nullptr, + upload ? centers.data() : nullptr, + upload ? static_cast(centers.size()) : 0); + if(status==2) { + throw std::runtime_error("an ASSIGNED atom has no CENTER inside the candidate list"); + } + if(status!=0) { + throw std::runtime_error("CUDA reactive Voronoi NLIST forward failed; check geometry and CUDA diagnostics"); + } + uploadedNeighborVersion_=version; + } + + void backward(const double* sensitivity, double* derivatives, double* virial) override { + if(runBackward(*state_,sensitivity,derivatives,virial)!=0) { + throw std::runtime_error("CUDA reactive Voronoi backward failed"); + } + } +}; + +PLMD::colvar::ReactiveVoronoiBackendRegistration registration("CUDA"); + +} diff --git a/regtest/basic/rt-reactive-voronoi-backends/Makefile b/regtest/basic/rt-reactive-voronoi-backends/Makefile new file mode 100644 index 0000000000..3703b27cea --- /dev/null +++ b/regtest/basic/rt-reactive-voronoi-backends/Makefile @@ -0,0 +1 @@ +include ../../scripts/test.make diff --git a/regtest/basic/rt-reactive-voronoi-backends/config b/regtest/basic/rt-reactive-voronoi-backends/config new file mode 100644 index 0000000000..1466fad6cb --- /dev/null +++ b/regtest/basic/rt-reactive-voronoi-backends/config @@ -0,0 +1,2 @@ +type=make +export PLUMED_NUM_THREADS=1 diff --git a/regtest/basic/rt-reactive-voronoi-backends/main.cpp b/regtest/basic/rt-reactive-voronoi-backends/main.cpp new file mode 100644 index 0000000000..4abc3ad698 --- /dev/null +++ b/regtest/basic/rt-reactive-voronoi-backends/main.cpp @@ -0,0 +1,268 @@ +#include "plumed/wrapper/Plumed.h" +#include +#include +#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()); + }; + if(!backend.empty()) { + if(const char* library=std::getenv("PLUMED_VORONOI_TEST_PLUGIN")) { + read(std::string("LOAD FILE=")+library); + } + } + 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 + +namespace { + +void test(bool cells, bool strideOwner) { + const int extra=cells ? 128 : 0; + const int centers=2+extra, assigned=1+2*extra; + const int atoms=centers+assigned; + std::vector x(3*atoms,0.0), forces(3*atoms), masses(atoms,1.0); + const double length=cells ? 12.0 : 3.0; + // One assigned atom sees both centers across the periodic seam. + x[0]=0.1; + x[3]=length-0.13; + x[3*centers]=length-0.04; + for(int i=0; i center{{1.0+i%8,1.0+(i/8)%8,1.0+i/64}}; + for(int k=0; k<3; ++k) { + x[3*(i+2)+k]=center[k]; + x[3*(centers+2*i+1)+k]=center[k]+(k==0 ? 0.12 : 0.0); + x[3*(centers+2*i+2)+k]=center[k]+(k==1 ? 0.14 : 0.0); + } + } + std::array box{{length,0,0,0,length,0,0,0,length}}, virial{}; + const std::string label=std::string(cells ? "cells" : "scan")+(strideOwner ? "-stride" : "-unused"); + PLMD::Plumed p; + p.cmd("setRealPrecision",8); + p.cmd("setNatoms",atoms); + p.cmd("setTimestep",0.001); + const std::string logfile=label+".log"; + p.cmd("setLogFile",logfile.c_str()); + p.cmd("init"); + const std::string parameters=": VORONOI_COORDINATION CENTERS=1-"+std::to_string(centers)+ + " ASSIGNED="+std::to_string(centers+1)+"-"+std::to_string(atoms)+ + " REFERENCE=0 POWER=2 NLIST NL_CUTOFF=0.30 NL_SKIN=0.10 NL_STRIDE=5"; + const auto read=[&](const std::string& line) { + p.cmd("readInputLine",line.c_str()); + }; + read("owner"+parameters+" KAPPA=4"); + read("active"+parameters+" KAPPA=5"); + read("reference"+parameters+" KAPPA=5 NO_SHARE"); + if(strideOwner) { + read("PRINT ARG=owner STRIDE=100 FILE="+label+".colvar"); + } + read("bias: RESTRAINT ARG=active,reference AT=0.25,0.25 KAPPA=2,2"); + double active=0.0, reference=0.0; + long rank=-1; + p.cmd("getDataRank active",&rank); + p.cmd("setMemoryForData active",&active); + p.cmd("getDataRank reference",&rank); + p.cmd("setMemoryForData reference",&reference); + for(int step=0; step<3; ++step) { + // Step 1 changes the box and makes the first image outside the owner's + // stored candidate cutoff. The active action still sees both centers. + box[0]=length-(step ? 0.42 : 0.0); + x[0]=step ? 0.32 : 0.1; + x[3]=box[0]-0.22; + x[3*centers]=box[0]+0.12; + if(step==0) { + x[0]=0.1; + x[3]=length-0.13; + x[3*centers]=length-0.04; + } + p.cmd("setStep",step); + p.cmd("setPositions",x.data()); + p.cmd("setMasses",masses.data()); + p.cmd("setForces",forces.data()); + p.cmd("setBox",box.data()); + p.cmd("setVirial",virial.data()); + p.cmd("calc"); + if(!std::isfinite(active) || !std::isfinite(reference) || + std::abs(active-reference)>1e-10) { + throw std::runtime_error(label+" active and independent CV differ at step "+std::to_string(step)); + } + } +} + +} + +int main() { + try { + for(bool cells: { + false,true + }) { + for(bool strideOwner: { + false,true + }) { + test(cells,strideOwner); + } + } + std::ofstream("output")<<"PASS reactive Voronoi uses the active PBC for shared list rebuilds\n"; + } catch(const std::exception& error) { + std::cerr< +#include +#include + +namespace { + +class TestVoronoiBackend final : public PLMD::colvar::ReactiveVoronoiBackend { + static double separation(const double* x) { + return std::hypot(x[3]-x[0],x[4]-x[1],x[5]-x[2]); + } + +public: + TestVoronoiBackend(int centers, int assigned, int device) { + if(centers!=1 || assigned!=1 || device>0) { + throw std::runtime_error("test backend context creation failed"); + } + } + + int device() const override { + return 0; + } + + void forward(const double* x, const PLMD::Pbc&, bool, double, double* occupancy) override { + if(separation(x)<=0.0) { + throw InvalidPair(0,0,"test backend forward failed"); + } + occupancy[0]=1.0; + } + + void forwardNeighbors(const double* x, const PLMD::Pbc& box, bool pbc, double kappa, + double* occupancy, double cutoff, + const std::vector& offsets, const std::vector& centers, + unsigned long) override { + if(offsets.size()!=2 || offsets[0]!=0 || offsets[1]!=static_cast(centers.size()) || + centers.size()>1 || (!centers.empty() && centers[0]!=0)) { + throw std::runtime_error("invalid candidate list"); + } + if(centers.empty() || separation(x)>cutoff) { + throw std::runtime_error("no CENTER inside the candidate list"); + } + forward(x,box,pbc,kappa,occupancy); + } + + void backward(const double*, double* gradient, double* virial) override { + std::fill_n(gradient,6,0.0); + std::fill_n(virial,9,0.0); + } +}; + +PLMD::colvar::ReactiveVoronoiBackendRegistration registerBackend("CUDA"); + +} diff --git a/regtest/basic/rt-reactive-voronoi-loader/config b/regtest/basic/rt-reactive-voronoi-loader/config new file mode 100644 index 0000000000..a1454e1ee4 --- /dev/null +++ b/regtest/basic/rt-reactive-voronoi-loader/config @@ -0,0 +1,11 @@ +type=make +plumed_needs="tools:dlopen" +plumed_src=main.cpp +plumed_link=shared +export PLUMED_NUM_THREADS=1 + +function plumed_regtest_before(){ + local soext + soext=$($plumed_nompi info --soext) || return 1 + $plumed_nompi mklib -o "backend.$soext" backend.cpp +} diff --git a/regtest/basic/rt-reactive-voronoi-loader/main.cpp b/regtest/basic/rt-reactive-voronoi-loader/main.cpp new file mode 100644 index 0000000000..3dcf49a73c --- /dev/null +++ b/regtest/basic/rt-reactive-voronoi-loader/main.cpp @@ -0,0 +1,163 @@ +#include "plumed/wrapper/Plumed.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +const std::string backend="./backend." __PLUMED_SOEXT; +const std::string neighbors=" NLIST NL_CUTOFF=1 NL_STRIDE=10 NL_SKIN=0.4"; +const std::string input="VORONOI_COORDINATION CENTERS=1 ASSIGNED=2 REFERENCE=0 KAPPA=5"; + +void check(bool pass, const std::string& message) { + if(!pass) { + throw std::runtime_error(message); + } +} + +struct System { + PLMD::Plumed plumed; + std::array positions{{0,0,0,0.5,0,0}}; + std::array forces{}; + std::array masses{{1,1}}; + std::array box{{4,0,0,0,4,0,0,0,4}}, virial{}; + double value=0.0; + std::string file; + + explicit System(const std::string& label, int device=-1): file(label+".log") { + plumed.cmd("setRealPrecision",8); + plumed.cmd("setNatoms",2); + plumed.cmd("setTimestep",0.001); + plumed.cmd("setLogFile",file.c_str()); + if(device>=0) { + plumed.cmd("setGpuDeviceId",device); + } + plumed.cmd("init"); + } + + void read(const std::string& line) { + plumed.cmd("readInputLine",line.c_str()); + } + + void declare(const std::string& options) { + read("q: "+input+options); + read("bias: RESTRAINT ARG=q AT=0 KAPPA=2"); + long rank=-1; + plumed.cmd("getDataRank q",&rank); + plumed.cmd("setMemoryForData q",&value); + } + + void evaluate(int step) { + forces.fill(0.0); + virial.fill(0.0); + plumed.cmd("setStep",step); + plumed.cmd("setPositions",positions.data()); + plumed.cmd("setForces",forces.data()); + plumed.cmd("setMasses",masses.data()); + plumed.cmd("setBox",box.data()); + plumed.cmd("setVirial",virial.data()); + plumed.cmd("calc"); + double bias=0.0; + plumed.cmd("getBias",&bias); + const auto zero=[](double x) { + return std::abs(x)<1e-12; + }; + check(std::abs(value-1.0)<1e-12 && std::abs(bias-1.0)<1e-12 && + std::all_of(forces.begin(),forces.end(),zero) && + std::all_of(virial.begin(),virial.end(),zero),file+": wrong value or derivatives"); + } +}; + +std::string log(const std::string& label) { + std::ifstream in(label+".log"); + return {std::istreambuf_iterator(in),std::istreambuf_iterator()}; +} + +void positive(const std::string& label, const std::string& options, + const std::string& selection, int device=-1, bool shear=false, bool load=true) { + { + System system(label,device); + if(shear) { + system.box[3]=0.5; + } + if(load) { + system.read("LOAD FILE="+backend); + } + system.declare(options); + system.evaluate(0); + system.positions[3]=0.6; + system.evaluate(1); + system.positions[3]=0.8; + system.evaluate(2); + } + check(log(label).find(selection)!=std::string::npos,label+": wrong backend or fallback"); +} + +void rejects(const std::string& label, const std::string& options, + const std::string& reason, double separation=0.5, int device=-1, bool load=true) { + try { + System system(label,device); + if(load) { + system.read("LOAD FILE="+backend); + } + system.declare(options); + system.positions[3]=separation; + system.evaluate(0); + } catch(const std::exception& error) { + const std::string message=error.what(); + check(message.find(reason)!=std::string::npos && message.find("label q")!=std::string::npos, + label+": unexpected error: "+message); + return; + } + throw std::runtime_error(label+": expected an error"); +} + +void exactNeighborSettings() { + { + System system("exact-settings"); + system.read("a: "+input+neighbors); + system.read("b: "+input+neighbors); + system.read("c: "+input+" NLIST NL_CUTOFF=1.0000000000000002 NL_STRIDE=10 NL_SKIN=0.4"); + system.read("d: "+input+" NLIST NL_CUTOFF=1 NL_STRIDE=10 NL_SKIN=0.4000000000000001"); + } + const std::string report=log("exact-settings"); + const std::string sharing="sharing reactive Voronoi geometry with "; + const auto first=report.find(sharing); + check(first!=std::string::npos && report.find(sharing,first+sharing.size())==std::string::npos, + "only the actions with identical neighbor settings should share"); +} + +} + +int main() { + try { + exactNeighborSettings(); + const std::string cuda=" BACKEND=CUDA"; + const std::string automatic=" BACKEND=AUTO"; + positive("full",cuda,"selected CUDA (device 0",0); + positive("buffered",automatic+neighbors,"selected CUDA (device 0; NLIST"); + positive("sheared",automatic,"selected CPU (triclinic", -1,true); + rejects("invalid-device",cuda,"context creation failed",0.5,1); + rejects("coincident",automatic,"test backend forward failed step=0 center_atom=1 assigned_atom=2",0.0); + rejects("outside",automatic+neighbors,"no CENTER inside the candidate list",1.2); + + // A plugin loaded by a live PLUMED instance is not available to a + // different instance unless it has also loaded that plugin. + System loaded("loaded"); + loaded.read("LOAD FILE="+backend); + loaded.declare(cuda); + loaded.evaluate(0); + positive("absent",automatic,"AUTO initialization fallback",-1,false,false); + rejects("missing",cuda,"No CUDA Voronoi backend is available",0.5,-1,false); + loaded.evaluate(1); + std::ofstream("output")<<"PASS reactive Voronoi runtime backend loading and fallback\n"; + } catch(const std::exception& error) { + std::cerr< +#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 "ReactiveVoronoiBackend.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,9 +34,12 @@ #include #include #include +#include +#include #include #include #include +#include #include #include #include @@ -174,8 +180,47 @@ class SoftVoronoiBase : public Colvar { struct Assignment { std::vector pairs; std::vector occupancy; + std::shared_ptr cuda; }; + struct CudaNeighbors { + // The offsets index centers grouped by assigned atom. + std::vector offsets; + std::vector centers; + unsigned long version=0; + }; + + struct SharedEvaluation { + unsigned consumers=1; + double firstKappa=0; + bool mixedKappa=false; + bool valid=false; + long long step=0; + std::vector positions; + Tensor box; + std::vector geometry; + std::map assignments; + std::map> cuda; + CudaNeighbors cudaNeighbors; + bool haveNeighborReference=false; + std::vector neighborReferencePositions; + Tensor neighborReferenceBox; + }; + std::shared_ptr shared_; + bool noShare_=false; + unsigned long evaluations_=0, hits_=0, geometryHits_=0; + Assignment independent_; + std::shared_ptr independentCuda_; + CudaNeighbors independentCudaNeighbors_; + std::string backend_="CPU"; + std::string autoCudaFailure_; + std::string lastBackendMessage_; + void logBackend(const std::string&, const std::string&); + std::shared_ptr cudaContext(); + bool sharedCoordinatesMatch() const; + Assignment computeAssignment(); + void packCudaNeighbors(CudaNeighbors&); + bool pbc_; bool serial_; bool invalidateList_; @@ -186,7 +231,7 @@ class SoftVoronoiBase : public Colvar { double kappa_; double neighborCutoff_; double neighborSkin_; - std::unique_ptr neighborList_; + std::shared_ptr neighborList_; std::vector centers_; std::vector assigned_; std::vector reference_; @@ -205,7 +250,7 @@ class SoftVoronoiBase : public Colvar { const std::string&, bool) const; bool neighborListNeedsUpdate(); void saveNeighborListReference(); - Assignment calculateAssignment(); + const Assignment& calculateAssignment(); std::vector defects(const Assignment&) const; void addAssignmentDerivatives(const Assignment&, const std::vector&, std::vector&, Tensor&); @@ -216,6 +261,7 @@ class SoftVoronoiBase : public Colvar { public: explicit SoftVoronoiBase(const ActionOptions&); void prepare() override; + ~SoftVoronoiBase() override; }; void SoftVoronoiBase::registerCommonKeywords(Keywords& keys) { @@ -224,6 +270,8 @@ void SoftVoronoiBase::registerCommonKeywords(Keywords& keys) { keys.add("compulsory","KAPPA","Positive soft-assignment sharpness in inverse PLUMED length units"); keys.add("compulsory","REFERENCE", "One intended occupancy broadcast to all CENTERS, or one value per CENTER in CENTERS order"); + keys.add("compulsory","BACKEND","CPU","Assignment backend: CPU, CUDA, or opt-in AUTO detection"); + keys.addFlag("NO_SHARE",false,"Disable instance-local reuse of compatible assignment calculations"); keys.addFlag("SERIAL",false,"Perform the calculation redundantly on each rank for debugging"); keys.addFlag("NLIST",false,"Use an approximate neighbor-list truncation of the assignment candidates"); keys.add("optional","NL_CUTOFF","Candidate cutoff in PLUMED length units; every ASSIGNED atom must retain at least one CENTER"); @@ -420,6 +468,18 @@ SoftVoronoiBase::SoftVoronoiBase(const ActionOptions& ao): parseVector("REFERENCE",reference_); broadcastOrCheck(reference_,centers_.size(),"REFERENCE"); + parse("BACKEND",backend_); + std::transform(backend_.begin(),backend_.end(),backend_.begin(), + [](const char value) { + return static_cast(std::toupper(static_cast(value))); + }); + if(backend_!="CPU" && backend_!="CUDA" && backend_!="AUTO") { + error("BACKEND must be CPU, CUDA or AUTO"); + } + if(backend_=="CUDA" && comm.Get_size()!=1) { + error("CUDA prototype requires a single MPI rank"); + } + parseFlag("NO_SHARE",noShare_); parseFlag("SERIAL",serial_); bool noPbc=false; parseFlag("NOPBC",noPbc); @@ -505,6 +565,34 @@ std::vector SoftVoronoiBase::mapSelection( void SoftVoronoiBase::finishSetup(const std::string& displayName) { checkRead(); + // Compatible actions share the candidate-list history as well as each evaluation. + // The cutoff and skin are exact cache keys: even a small change can select a different pair. + if(!noShare_) { + for(auto* other: plumed.getActionSet().select()) { + if(other->shared_ && other->centers_==centers_ && + other->assigned_==assigned_ && other->pbc_==pbc_ && + other->serial_==serial_ && other->backend_==backend_ && + std::tie(other->neighborCutoff_,other->neighborSkin_)== + std::tie(neighborCutoff_,neighborSkin_) && + other->neighborList_->getStride()==neighborList_->getStride() && + other->useCellList_==useCellList_) { + shared_=other->shared_; + ++shared_->consumers; + // Use the same ordering as the assignment cache for exact KAPPA keys. + const auto less=shared_->assignments.key_comp(); + shared_->mixedKappa=shared_->mixedKappa || + less(shared_->firstKappa,kappa_) || + less(kappa_,shared_->firstKappa); + neighborList_=other->neighborList_; + log.printf(" sharing reactive Voronoi geometry with %s\n",other->getLabel().c_str()); + break; + } + } + if(!shared_) { + shared_=std::make_shared(); + shared_->firstKappa=kappa_; + } + } addValueWithDerivatives(); setNotPeriodic(); // PLUMED 2.8 needs the full atom list to preserve absolute-index mapping. @@ -539,18 +627,21 @@ void SoftVoronoiBase::prepare() { } bool SoftVoronoiBase::neighborListNeedsUpdate() { - if(neighborSkin_<=0.0 || !haveNeighborReference_) { + const bool haveReference=shared_ ? shared_->haveNeighborReference : haveNeighborReference_; + const auto& referencePositions=shared_ ? shared_->neighborReferencePositions : neighborReferencePositions_; + const Tensor& referenceBox=shared_ ? shared_->neighborReferenceBox : neighborReferenceBox_; + if(neighborSkin_<=0.0 || !haveReference) { return false; } const std::vector& positions=getPositions(); - if(positions.size()!=neighborReferencePositions_.size()) { + if(positions.size()!=referencePositions.size()) { return true; } if(pbc_) { const Tensor box=getPbc().getBox(); for(unsigned i=0; i<3; ++i) { for(unsigned j=0; j<3; ++j) { - if(box(i,j)!=neighborReferenceBox_(i,j)) { + if(box(i,j)!=referenceBox(i,j)) { return true; } } @@ -559,9 +650,9 @@ bool SoftVoronoiBase::neighborListNeedsUpdate() { const double thresholdSquared=0.25*neighborSkin_*neighborSkin_; for(unsigned i=0; ithresholdSquared) { return true; @@ -574,23 +665,218 @@ void SoftVoronoiBase::saveNeighborListReference() { if(neighborSkin_<=0.0) { return; } - neighborReferencePositions_=getPositions(); - if(pbc_) { - neighborReferenceBox_=getPbc().getBox(); + if(shared_) { + shared_->neighborReferencePositions=getPositions(); + if(pbc_) { + shared_->neighborReferenceBox=getPbc().getBox(); + } + shared_->haveNeighborReference=true; + } else { + neighborReferencePositions_=getPositions(); + if(pbc_) { + neighborReferenceBox_=getPbc().getBox(); + } + haveNeighborReference_=true; } - haveNeighborReference_=true; } -SoftVoronoiBase::Assignment SoftVoronoiBase::calculateAssignment() { - // Refresh the buffered candidate list on schedule or after a safe-skin exit. - if(neighborList_->getStride()>0) { - const bool updateList=invalidateList_ || neighborListNeedsUpdate(); - if(updateList) { - neighborList_->update(getPositions()); - saveNeighborListReference(); +SoftVoronoiBase::~SoftVoronoiBase() { + log.printf(" reactive Voronoi %s: assignments=%lu cache_hits=%lu geometry_hits=%lu\n", + getLabel().c_str(),evaluations_,hits_,geometryHits_); +} + +bool SoftVoronoiBase::sharedCoordinatesMatch() const { + if(!shared_->valid || shared_->step!=getStep() || + shared_->positions.size()!=getPositions().size()) { + return false; + } + const auto& positions=getPositions(); + for(unsigned i=0; ipositions[i][k]) { + return false; + } + } + } + const Tensor& box=getPbc().getBox(); + for(unsigned i=0; i<3; ++i) { + for(unsigned j=0; j<3; ++j) { + if(box(i,j)!=shared_->box(i,j)) { + return false; + } + } + } + return true; +} + +const SoftVoronoiBase::Assignment& SoftVoronoiBase::calculateAssignment() { + if(!shared_ || shared_->consumers==1) { + ++evaluations_; + independent_=computeAssignment(); + return independent_; + } + if(!sharedCoordinatesMatch()) { + shared_->valid=false; + shared_->geometry.clear(); + shared_->assignments.clear(); + shared_->positions=getPositions(); + shared_->box=getPbc().getBox(); + shared_->step=getStep(); + } else { + const auto found=shared_->assignments.find(kappa_); + if(found!=shared_->assignments.end()) { + ++hits_; + return found->second; + } + } + ++evaluations_; + Assignment result=computeAssignment(); + auto inserted=shared_->assignments.emplace(kappa_,std::move(result)); + shared_->valid=true; + return inserted.first->second; +} + +void SoftVoronoiBase::logBackend(const std::string& selected, + const std::string& reason) { + const std::string message=selected+" ("+reason+")"; + if(message!=lastBackendMessage_) { + log.printf(" reactive Voronoi %s requested %s; selected %s\n", + getLabel().c_str(),backend_.c_str(),message.c_str()); + lastBackendMessage_=message; + } +} + +std::shared_ptr SoftVoronoiBase::cudaContext() { + if(backend_=="CPU") { + logBackend("CPU","shared evaluation enabled unless NO_SHARE is set"); + return nullptr; + } + std::string unsupported; + if(comm.Get_size()!=1) { + unsupported="multiple MPI ranks"; + } else if(pbc_) { + const Tensor& box=getPbc().getBox(); + const double determinant=box.determinant(); + if(!getPbc().isSet() || !std::isfinite(determinant) || std::fabs(determinant)<=1.0e-14) { + error("non-finite or degenerate periodic box at step="+std::to_string(getStep())); + } + for(unsigned i=0; i<3; ++i) { + if(!std::isfinite(box(i,i)) || box(i,i)<=0) { + unsupported="PBC requires a finite positive orthorhombic box"; + } + for(unsigned j=0; j<3; ++j) { + if(i!=j && box(i,j)!=0) { + unsupported="triclinic PBC requires the CPU backend"; + } + } + } + } + if(!unsupported.empty()) { + if(backend_=="CUDA") { + error("CUDA backend does not support "+unsupported); + } + logBackend("CPU",unsupported); + return nullptr; + } + if(!autoCudaFailure_.empty()) { + logBackend("CPU",autoCudaFailure_); + return nullptr; + } + auto& context=shared_ ? shared_->cuda[kappa_] : independentCuda_; + if(!context) { + try { + const auto& images=plumed.getLoadedLibraryHandles(); + const auto& registry=reactiveVoronoiBackendRegister(); + if(!registry.check(images,"CUDA")) { + throw std::runtime_error("No CUDA Voronoi backend is available. Build the reactive-voronoi-cuda plugin and LOAD it before the action."); + } + const auto create=registry.get(images,"CUDA"); + context=create(centers_.size(),assigned_.size(),plumed.getGpuDeviceId()); + } catch(const std::exception& failure) { + if(backend_=="CUDA") { + error(std::string("CUDA initialization failed: ")+failure.what()); + } + autoCudaFailure_=std::string("AUTO initialization fallback: ")+failure.what(); + logBackend("CPU",autoCudaFailure_); + return nullptr; } } + const std::string device="device "+std::to_string(context->device()); + logBackend("CUDA",device+(neighborCutoff_>0 ? "; NLIST assignment and assignment derivatives" : + "; assignment and assignment derivatives")); + return context; +} +void SoftVoronoiBase::packCudaNeighbors(CudaNeighbors& neighbors) { + const auto count=neighborList_->size(); + if(count>static_cast(std::numeric_limits::max())) { + error("CUDA NLIST exceeds the supported number of candidate pairs"); + } + neighbors.offsets.assign(assigned_.size()+1,0); + for(unsigned p=0; pgetClosePair(p); + if(pair.first>=centers_.size() || pair.second=assigned_.size()) { + error("internal CUDA NLIST pair mapping is invalid"); + } + ++neighbors.offsets[pair.second-centers_.size()+1]; + } + std::partial_sum(neighbors.offsets.begin(),neighbors.offsets.end(),neighbors.offsets.begin()); + auto cursor=neighbors.offsets; + neighbors.centers.resize(count); + for(unsigned p=0; pgetClosePair(p); + neighbors.centers[cursor[pair.second-centers_.size()]++]=pair.first; + } +} + +SoftVoronoiBase::Assignment SoftVoronoiBase::computeAssignment() { + const auto context=cudaContext(); + auto& neighbors=shared_ ? shared_->cudaNeighbors : independentCudaNeighbors_; + // CPU and CUDA use the same rebuild and safe-skin criteria. + if(neighborList_->getStride()>0 && !(shared_ && shared_->valid) && + (invalidateList_ || neighborListNeedsUpdate())) { + // The action that first created the list may be inactive on this step. + neighborList_->update(getPositions(),getPbc()); + saveNeighborListReference(); + ++neighbors.version; + neighbors.offsets.clear(); + } + if(context) { + Assignment result; + result.cuda=context; + result.occupancy.resize(centers_.size()); + std::vector positions(3*getPositions().size()); + for(unsigned atom=0; atom0) { + if(neighbors.offsets.empty()) { + packCudaNeighbors(neighbors); + } + const double cutoff=filterCandidatePairs_ ? neighborCutoff_ : + std::numeric_limits::infinity(); + context->forwardNeighbors(positions.data(),getPbc(),pbc_,kappa_,result.occupancy.data(), + cutoff,neighbors.offsets,neighbors.centers,neighbors.version); + } else { + context->forward(positions.data(),getPbc(),pbc_,kappa_,result.occupancy.data()); + } + } catch(const ReactiveVoronoiBackend::InvalidPair& failure) { + std::ostringstream message; + message << failure.what() << " step=" << getStep() + << " center_atom=" << centers_.at(failure.center).serial() + << " assigned_atom=" << assigned_.at(failure.assigned).serial(); + error(message.str()); + } catch(const std::exception& failure) { + error(std::string(failure.what())+" step="+std::to_string(getStep())); + } + return result; + } // Split candidate pairs into contiguous MPI-owned ranges. const unsigned numberOfPairs=neighborList_->size(); const unsigned stride=serial_ ? 1 : comm.Get_size(); @@ -603,6 +889,11 @@ SoftVoronoiBase::Assignment SoftVoronoiBase::calculateAssignment() { const double negativeInfinity=-std::numeric_limits::infinity(); Assignment result; + const bool reuseGeometry=shared_ && shared_->valid && + shared_->geometry.size()==localPairCount; + if(reuseGeometry) { + ++geometryHits_; + } unsigned numberOfThreads=1; #ifdef _OPENMP numberOfThreads=OpenMP::getGoodNumThreads( @@ -690,15 +981,16 @@ SoftVoronoiBase::Assignment SoftVoronoiBase::calculateAssignment() { recordFailure(boxFailure); return; } - pair.distance=pbc_ ? - pbcDistance(centerPosition,assignedPosition) : - delta(centerPosition,assignedPosition); + pair.distance=reuseGeometry ? shared_->geometry[pairIndex-start].distance : + (pbc_ ? pbcDistance(centerPosition,assignedPosition) : + delta(centerPosition,assignedPosition)); displacementAvailable=true; if(!finiteVector(pair.distance)) { recordFailure(InvalidDisplacement); return; } - pair.length=pair.distance.modulo(); + pair.length=reuseGeometry ? shared_->geometry[pairIndex-start].length : + pair.distance.modulo(); lengthAvailable=true; if(!std::isfinite(pair.length)) { recordFailure(InvalidLength); @@ -709,7 +1001,7 @@ SoftVoronoiBase::Assignment SoftVoronoiBase::calculateAssignment() { return; } if(filterCandidatePairs_ && pair.length>neighborCutoff_) { - pair.length=-1.0; + pair.score=std::numeric_limits::quiet_NaN(); return; } pair.score=-kappa_*pair.length; @@ -840,11 +1132,14 @@ SoftVoronoiBase::Assignment SoftVoronoiBase::calculateAssignment() { error(invalidPairMessage(selectedFailure)); } + if(shared_ && shared_->mixedKappa && !reuseGeometry) { + shared_->geometry=result.pairs; + } if(filterCandidatePairs_) { result.pairs.erase( std::remove_if(result.pairs.begin(),result.pairs.end(), [](const PairData& pair) { - return pair.length<0.0; + return std::isnan(pair.score); }),result.pairs.end()); } for(unsigned j=0; j gradient(3*derivatives.size()); + double boxGradient[9]; + try { + assignment.cuda->backward(derivativeByDefect.data(),gradient.data(),boxGradient); + } catch(const std::exception& failure) { + error(std::string(failure.what())+" step="+std::to_string(getStep())); + } + for(unsigned i=0; i defect=defects(assignment); std::vector derivativeByDefect(centers_.size(),0.0); double value=0.0; @@ -1745,7 +2077,7 @@ VoronoiDistance::VoronoiDistance(const ActionOptions& ao): } void VoronoiDistance::calculate() { - const Assignment assignment=calculateAssignment(); + const Assignment& assignment=calculateAssignment(); const std::vector defect=defects(assignment); std::vector derivativeByDefect(centers_.size(),0.0); std::vector derivatives(getNumberOfAtoms()); @@ -2051,9 +2383,9 @@ VoronoiPosition::VoronoiPosition(const ActionOptions& ao): } void VoronoiPosition::calculate() { - const Assignment assignment=calculateAssignment(); + const Assignment& assignment=calculateAssignment(); const std::vector defect=defects(assignment); - std::vector displacement(selected_.size(),0.0); + std::vector imagePositions(selected_.size()); std::vector function(selected_.size(),0.0); std::vector weight(selected_.size(),0.0); std::vector weightDerivative(selected_.size(),0.0); @@ -2068,15 +2400,16 @@ void VoronoiPosition::calculate() { const Vector relative=pbc_ ? pbcDistance(reference,getPosition(i)) : delta(reference,getPosition(i)); - displacement[s]=relative[axis_]; - if(!std::isfinite(displacement[s])) { + const double displacement=relative[axis_]; + imagePositions[s]=pbc_ ? reference+relative : getPosition(i); + if(!std::isfinite(displacement)) { error("VORONOI_POSITION displacement is non-finite"); } function[s]=absolute_ ? - std::fabs(displacement[s]) : displacement[s]; + std::fabs(displacement) : displacement; functionDerivative[s]=absolute_ ? - (displacement[s]>0.0 ? 1.0 : - (displacement[s]<0.0 ? -1.0 : 0.0)) : 1.0; + (displacement>0.0 ? 1.0 : + (displacement<0.0 ? -1.0 : 0.0)) : 1.0; const bool included= sign_=="ALL" || @@ -2116,11 +2449,8 @@ void VoronoiPosition::calculate() { Vector directDerivative; directDerivative[axis_]=directScalar; derivatives[i]+=directDerivative; - Vector imagePosition=getPosition(i); - if(pbc_) { - imagePosition[axis_]=origin_+displacement[s]; - } - virial-=Tensor(imagePosition,directDerivative); + // A triclinic lattice translation can change every Cartesian component. + virial-=Tensor(imagePositions[s],directDerivative); } } diff --git a/src/colvar/ReactiveVoronoiBackend.cpp b/src/colvar/ReactiveVoronoiBackend.cpp new file mode 100644 index 0000000000..f284e7941b --- /dev/null +++ b/src/colvar/ReactiveVoronoiBackend.cpp @@ -0,0 +1,38 @@ +/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + 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 "ReactiveVoronoiBackend.h" + +namespace PLMD { +namespace colvar { + +ReactiveVoronoiBackendRegister& reactiveVoronoiBackendRegister() { + static ReactiveVoronoiBackendRegister backends; + return backends; +} + +namespace { +// Construct the register before LOAD acquires the registration lock. +[[maybe_unused]] const auto& registerAtLoad=reactiveVoronoiBackendRegister(); +} + +} +} diff --git a/src/colvar/ReactiveVoronoiBackend.h b/src/colvar/ReactiveVoronoiBackend.h new file mode 100644 index 0000000000..91d41cd251 --- /dev/null +++ b/src/colvar/ReactiveVoronoiBackend.h @@ -0,0 +1,83 @@ +/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + 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 . +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ +#ifndef __PLUMED_colvar_ReactiveVoronoiBackend_h +#define __PLUMED_colvar_ReactiveVoronoiBackend_h + +#include "core/RegisterBase.h" + +#include +#include +#include +#include + +namespace PLMD { +class Pbc; +namespace colvar { + +/// Optional backend for the soft assignment and its contracted derivatives. +class ReactiveVoronoiBackend { +public: + /// Indices refer to the center and assigned selections of this context. + struct InvalidPair : std::runtime_error { + unsigned center; + unsigned assigned; + InvalidPair(unsigned c, unsigned a, const char* message): + std::runtime_error(message), center(c), assigned(a) {} + }; + virtual ~ReactiveVoronoiBackend() = default; + virtual int device() const = 0; + virtual void forward(const double* positions, const Pbc& box, bool pbc, + double kappa, double* occupancy) = 0; + /// The backend can reuse the uploaded candidate list for the same version. + virtual void forwardNeighbors(const double* positions, const Pbc& box, bool pbc, + double kappa, double* occupancy, double cutoff, + const std::vector& offsets, const std::vector& centers, + unsigned long version) = 0; + virtual void backward(const double* sensitivity, double* derivatives, double* virial) = 0; +}; + +using ReactiveVoronoiBackendFactory = std::unique_ptr(*)(int centers, + int assigned, int device); +using ReactiveVoronoiBackendRegister = RegisterBase; + +ReactiveVoronoiBackendRegister& reactiveVoronoiBackendRegister(); + +template +class ReactiveVoronoiBackendRegistration { + static std::unique_ptr create(int centers, int assigned, int device) { + return std::make_unique(centers,assigned,device); + } + ReactiveVoronoiBackendRegister::ID id; +public: + explicit ReactiveVoronoiBackendRegistration(const std::string& name): + id(reactiveVoronoiBackendRegister().add(name,create,reinterpret_cast(&create))) {} + ~ReactiveVoronoiBackendRegistration() { + reactiveVoronoiBackendRegister().remove(id); + } + ReactiveVoronoiBackendRegistration(const ReactiveVoronoiBackendRegistration&) = delete; + ReactiveVoronoiBackendRegistration& operator=(const ReactiveVoronoiBackendRegistration&) = delete; +}; + +} +} + +#endif diff --git a/src/core/PlumedMain.cpp b/src/core/PlumedMain.cpp index 14e4752c04..4f7b1e0e7c 100644 --- a/src/core/PlumedMain.cpp +++ b/src/core/PlumedMain.cpp @@ -2156,6 +2156,10 @@ void PlumedMain::getKeywordsForAction( const std::string& action, Keywords& keys bool PlumedMain::checkAction(const std::string& action) const { return actionRegister().check(dlloader.getHandles(),action); } + +const std::vector& PlumedMain::getLoadedLibraryHandles() const { + return dlloader.getHandles(); +} #ifdef __PLUMED_HAS_PYTHON // This is here to stop cppcheck throwing an error #endif diff --git a/src/core/PlumedMain.h b/src/core/PlumedMain.h index a74011d3f7..4382004bdd 100644 --- a/src/core/PlumedMain.h +++ b/src/core/PlumedMain.h @@ -576,6 +576,8 @@ class PlumedMain: bool hasBeenInitialized() const ; /// Check if an action with the given name has been registered by default or LOADed bool checkAction(const std::string& action) const; +/// Handles of libraries visible to this PLUMED instance, for plugin registers. + const std::vector& getLoadedLibraryHandles() const; }; ///// diff --git a/src/tools/NeighborList.cpp b/src/tools/NeighborList.cpp index 70f63eb070..113bc04c0a 100644 --- a/src/tools/NeighborList.cpp +++ b/src/tools/NeighborList.cpp @@ -201,6 +201,10 @@ struct KeepPairs { } void NeighborList::update(const std::vector& positions) { + update(positions,*pbc_); +} + +void NeighborList::update(const std::vector& positions, const Pbc& pbc) { neighbors_.clear(); // check if positions array has the correct length plumed_assert(positions.size()==fullatomlist_.size()); @@ -230,7 +234,7 @@ void NeighborList::update(const std::vector& positions) { // would cost more than the search cells.setLimitCellsByAtoms(true); if(do_pbc_) { - cells.setupCells(make_const_view(positions),*pbc_); + cells.setupCells(make_const_view(positions),pbc); } else { // without pbc the cells must enclose the atoms: cells built on the periodic // box would split close pairs across the planes where scaled coordinates wrap @@ -306,7 +310,7 @@ void NeighborList::update(const std::vector& positions) { } // the cells contain all the pairs within the cutoff, and many more: // only the pairs within the cutoff are kept - const Vector distance=do_pbc_ ? pbc_->distance(positions[A],positions[B]) : + const Vector distance=do_pbc_ ? pbc.distance(positions[A],positions[B]) : delta(positions[A],positions[B]); if(modulo2(distance)<=d2) { private_flat_nl.push_back(A); @@ -343,7 +347,7 @@ void NeighborList::update(const std::vector& positions) { pairs[j]= {index0,index1}; distances[j]=delta(positions[index0],positions[index1]); } - pbc_->apply(VectorView(distances[0].data(),count)); + pbc.apply(VectorView(distances[0].data(),count)); for(unsigned j=0; j& positions) { #pragma omp for schedule(static) nowait for(unsigned int i=start; idistance(positions[index0],positions[index1]) : + const Vector distance=do_pbc_ ? pbc.distance(positions[index0],positions[index1]) : delta(positions[index0],positions[index1]); double value=modulo2(distance); if(value<=d2) { diff --git a/src/tools/NeighborList.h b/src/tools/NeighborList.h index 54fa760670..5beecff700 100644 --- a/src/tools/NeighborList.h +++ b/src/tools/NeighborList.h @@ -107,6 +107,8 @@ class NeighborList { /// Update the neighbor list and prepare the new /// list of atoms that will be requested to the main code void update(const std::vector& positions); +/// Rebuild with the PBC of the action requesting this update. + void update(const std::vector& positions, const PLMD::Pbc& pbc); /// Get the update stride of the neighbor list unsigned getStride() const; /// Get the last step in which the neighbor list was updated diff --git a/src/tools/Tools.h b/src/tools/Tools.h index 92205eac23..1a2a3e6558 100644 --- a/src/tools/Tools.h +++ b/src/tools/Tools.h @@ -158,6 +158,9 @@ class Tools { static void trimComments(std::string & s); /// Apply pbc for a unitary cell template +#ifdef __CUDACC__ + __host__ __device__ +#endif static double pbc(T); /// Retrieve a key from a vector of options. /// It finds a key starting with "key=" or equal to "key" and copy the @@ -546,6 +549,9 @@ bool Tools::parseFlag(std::vector&line,const std::string&key,bool&v /// beware: this brings any number into a pbc that ranges from -0.5 to 0.5 template +#ifdef __CUDACC__ +__host__ __device__ +#endif inline double Tools::pbc(T x) { if constexpr (std::is_same_v) { // In single precision the offset used below costs accuracy: the spacing of floats