Skip to content

Grid unification (METAD/PBMETAD grid and KDE/gridtools grid) - #1707

Open
carlocamilloni wants to merge 5 commits into
masterfrom
grid-unification
Open

carlocamilloni wants to merge 5 commits into
masterfrom
grid-unification

Conversation

@carlocamilloni

@carlocamilloni carlocamilloni commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

PR: Grid unification (METAD/PBMETAD grid and KDE/gridtools grid)

Branch: grid-unification (from master a430df5). Open as a draft: steps B and C will be added to the same PR.
Push from the Mac: git push -u origin grid-unification (the remote is SSH, the sandbox cannot push).

Title

Grids: one implementation for METAD/PBMETAD and KDE/gridtools, where possible

Body

PLUMED has two grid implementations: tools/Grid (GridBase, Grid, SparseGrid; used by METAD/PBMETAD, EXTERNAL, FUNCSUMHILLS, funnel, ves) and tools/GridCoordinatesObject (geometry only, data in the Value; used by KDE and the rest of gridtools, contour, fourier, ACCUMULATE). Since #1666 both extend their grids with the same rules, in two copies. This PR removes the duplication step by step, without changing the METAD/PBMETAD results and without slowing METAD down. Data storage stays separate: the METAD bias is not a grid of the action graph.

Plan

  • A: shared extension planner + exact lattice in GridCoordinatesObject (8d0dc0b)
  • B: one geometry (tools/GridLattice, GridBase's code, used by both) (23f938e)
  • GridCoordinatesObject indices to size_t; KDE memory proportional to the kernel-point pairs; no OpenMP region per METAD hill with one thread (a941d4c)
  • C, part 1: one spline interpolation (GridLattice::splineInterpolation, used by GridBase and the gridtools Interpolator) (2cc5cf0)
  • C, part 2: one grid file reader/writer (tools/GridFile, used by GridBase, DUMPGRID and REFERENCE_GRID) (patch delivered 2026-11-29, not committed yet; also fixes rt-make-gridlattice on macOS/Intel)

A: shared extension planner and exact lattice

  • tools/GridExtension plans the extensions of the METAD/PBMETAD grid and of the KDE grid with the same rules: the points needed plus one zero point on each side, growth by at least a quarter of the points, GRID_SIZE_LIMIT (raised to twice the size of a larger initial grid). It replaces the two copies in MetaDBiasGrid::extend and KDEGridTools::extendGridBounds. It only computes numbers of points; the callers apply them and write their own errors and log lines.
  • GridCoordinatesObject keeps its bounds as doubles: setLattice sets a grid without parsing strings; extend adds points on the same lattice with the same arithmetic and bounds as GridBase::resize (so that in B GridBase can use it and METAD stays bitwise); onSameLattice/getShiftFrom give the exact shift between a grid and its extension; writeCheckpoint/readCheckpoint store it.
  • KDE no longer re-parses its own 12-digit bounds. ACCUMULATE places its data in an extended grid with the exact integer shift instead of a tolerance. Both store the grid through the GridCoordinatesObject checkpoint (new checkpoint keys; the checkpoint is new in 2.11).
  • Changes of results (KDE only, new in 2.11 with Automated finding of GRID_MIN and GRID_MAX in KDE #1666):
    • the growth of the KDE grid is based on the number of points, as in METAD (it was based on the number of bins): an extended KDE grid can have one more point. References updated: gridtools/rt-flatkde, rt-histogram, rt-q6-histogram (one more point at the lower end, data otherwise identical) and fourier/rt-fftw (the input histogram has 126 bins instead of 125, so the transform changes);
    • the placement of a KDE grid with GRID_SPACING and no bounds is checked against GRID_SIZE_LIMIT, as in METAD;
    • grid coordinates are on the exact lattice (e.g. a point that was 4.4e-16 is now 0).
  • New unit test regtest/basic/rt-make-gridextension.

B: one geometry

  • tools/GridLattice is the geometry of a grid without data: range, spacing, periodicity, indices (column-major), points, neighbours, spline neighbours, extension and lattice shift. It is GridBase's code, with its dimension-templated Accelerator, moved unchanged.
  • GridBase derives from it (public interface unchanged: METAD, PBMETAD, EXTERNAL, FUNCSUMHILLS, funnel and ves are not touched); the flat grids of GridCoordinatesObject contain one (its interface is unchanged and stays unsigned for now; fibonacci grids are unchanged).
  • Behaviour changes, only where the old code gave an error or a wrong result:
    • along a periodic direction the indices of a point at the upper end (e.g. pi) or outside the range are brought back into the grid (before: "Looking for a value outside the grid");
    • the neighbours of a point outside the grid are computed from its own lattice position. GridCoordinatesObject converted a negative position to unsigned (undefined behaviour): right by accident on x86, but on arm64 the neighbours of a kernel centred below GRID_MIN (with NO_EXTEND) were those of the first point, so the kernel was also added beyond its support;
    • GridCoordinatesObject flat grids are limited to 16 dimensions, and an index outside the grid is an error, as in GridBase.
  • New unit test regtest/basic/rt-make-gridlattice.

Follow-up of B

  • GridCoordinatesObject indices are std::size_t (as GridBase), and so are the neighbour lists of the KDE grid tools.
  • KDE/HISTOGRAM stored a table of grid points x kernels (e.g. 1000 kernels in 3D on ~80^3 points: 4.2 GB; 10000 kernels on 400x450 points: out of memory). Now only the pairs of a kernel and a point where it is not zero are stored (compressed rows, same order of the kernels at each point, so the results are bitwise identical): 160 MB and 310 MB in those cases, and KDE/HISTOGRAM are 2-2.8 times faster.
  • METAD/PBMETAD grids: no OpenMP parallel region per hill when running on one thread (libgomp sets up a team at every region): 2-3% faster with small hills, bitwise identical.
  • gcc 13 at -O3 with -Werror=array-bounds (false positive in vector<bool>::resize in the GridBase constructor): fixed.

C, part 1: one spline interpolation

  • The spline of GridBase (METAD, EXTERNAL, ves...) and that of the gridtools Interpolator (EVALUATE_FUNCTION_FROM_GRID, INTERPOLATE_GRID) were the same code. GridLattice::splineInterpolation is the only copy, reading the values and derivatives through a function given by the caller (the grid's own data, or the Value).
  • Bitwise identical results; the gridtools spline is about twice as fast (no allocations per call: -55% instructions); the GridBase spline costs the same.
  • Fixed: at the upper end of a periodic argument (e.g. pi), the gridtools spline used the wrong cell offset (the point is brought back into the grid, the polynomial was not).
  • Unit test in rt-make-gridlattice (the spline lines print 10 decimals since part 2: with 17 digits the test failed on macOS and with the Intel compiler, from FMA/libm differences in the last digits).

C, part 2: one grid file reader/writer

  • There were two writers and two readers of the same #! SET min_x max_x nbins_x periodic_x grid files, with two incompatible conventions: GridBase (METAD, PBMETAD, sum_hills, EXTERNAL, ves...) writes nbins_x = number of points (bins+1 along a direction that is not periodic) and derivatives der_x; DUMPGRID writes nbins_x = number of bins and derivatives d<function>_x. So REFERENCE_GRID could not read a METAD grid, and EXTERNAL could not read a DUMPGRID file.
  • tools/GridFile: GridFileWriter writes either style (same columns, formats and blank lines as before, so no file written by PLUMED changes); GridFileReader reads both, recognising the style from the derivative columns (der_x points, d<f>_x bins, none points), and gives the number of bins. GridBase::writeToFile/create (Grid and SparseGrid), the flat-grid branch of DUMPGRID and the FILE branch of REFERENCE_GRID use them; GridBase::writeHeader is removed. Fibonacci grids, cube and xyz outputs are unchanged.
  • Now REFERENCE_GRID reads METAD/PBMETAD grids (GRID_WFILE) and sum_hills free energies, and EXTERNAL (and METAD GRID_RFILE) read DUMPGRID files. Same error messages as before for missing columns, periodicity and domain mismatches; a file with the derivatives of only some variables, or a bad periodic_x/nbins_x, is an error.
  • New regtest gridtools/rt-grid-file-styles: a METAD grid and a DUMPGRID grid (phi periodic, d not) are each read by EXTERNAL and by REFERENCE_GRID + EVALUATE_FUNCTION_FROM_GRID, which give identical values; both are written again by DUMPGRID with the same nbins_d.

Checks for C part 2 (Linux, gcc 13, --enable-modules=all):

  • full regtest: all pass, no reference changes (ves/rt-le-2d-welltempered-mpi skipped: 4 thread-MPI ranks on 2 cores);
  • bitwise against step A with 17-digit output on 221 tests (METAD/PBMETAD grids written and read, EXTERNAL, sum_hills, funnel, ves, gridtools, contour, fourier): only the known differences (MPI log timings, rt-pbmetad-grid-mpi replica files), same return codes;
  • -O3 -Wall -pedantic -Wshadow -Werror on the changed files: clean; astyle applied;
  • codecheck: nothing new in the changed code (only cppcheck's header-only unusedStructMember notes on GridFile.h, whose members are used in GridFile.cpp);
  • CodeQL: not run in the sandbox (running the CodeQL bundle there is not allowed); to be checked on the PR's CodeQL workflow (security-and-quality). Manual review of the new code against its usual patterns: no narrowing in loop bounds, parsed values validated.

Checks for B:

  • full regtest with all modules: no reference changes;
  • bitwise against step A with 17-digit output on 196 tests (METAD/PBMETAD/EXTERNAL/sum_hills, funnel, ves, gridtools, contour, fourier);
  • -O2 benchmarks (median wall time, B/A): METAD 1D/2D/3D 1.03/0.99/0.99, PBMETAD 1.00, EXTERNAL 0.99, ves 0.99; KDE and HISTOGRAM with 1e3-1e5 kernels 0.89-0.97 (callgrind: KDE -3.8%, HISTOGRAM -3.5% instructions; METAD/ves within 0.3%);
  • codecheck: no new messages.

Checks for A (Linux, gcc 13, --enable-modules=all, FFTW):

  • full regtest: all pass (ves/rt-le-2d-welltempered-mpi skipped: 4 thread-MPI ranks on 2 cores);
  • METAD/PBMETAD bitwise against master with 17-digit output: rt-metad-grid-extend, -interval, -mpi, -restart, -scan, -large-sigma, rt-metad-adaptive-grid(-restart), rt-pbmetad-grid-mpi;
  • callgrind on METAD with 7 grid biases: +0.2% instructions in total; KDE with 2000 kernels: same time;
  • codecheck (cppcheck 2.22.0): no new messages above style on the changed files; astyle: no changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016vwxtU1YMqwpKiqhUECCP4

…bject

First step towards one grid implementation for METAD/PBMETAD (tools/Grid)
and KDE/gridtools (tools/GridCoordinatesObject).

- tools/GridExtension plans the extensions of the METAD/PBMETAD grid and of
  the KDE grid with the same rules: the points needed plus one zero point on
  each side, growth by at least a quarter of the points, GRID_SIZE_LIMIT
  (raised to twice the size of a larger initial grid). It replaces the two
  copies in MetaDBiasGrid::extend and KDEGridTools::extendGridBounds.
- GridCoordinatesObject keeps its bounds as doubles: setLattice sets a grid
  without parsing strings, extend adds points on the same lattice (same
  arithmetic and bounds as GridBase::resize), onSameLattice/getShiftFrom give
  the exact shift between a grid and its extension, writeCheckpoint and
  readCheckpoint store it.
- KDE no longer re-parses its own 12-digit bounds; ACCUMULATE places its data
  in an extended grid with the exact integer shift instead of a tolerance;
  both store the grid through the GridCoordinatesObject checkpoint.
- The growth of the KDE grid is now based on the number of points, as in
  METAD (it was based on the number of bins): extended KDE grids can have one
  more point (references of rt-flatkde, rt-histogram, rt-q6-histogram,
  rt-fftw updated). The placement of a KDE grid is checked against
  GRID_SIZE_LIMIT.
- METAD/PBMETAD results are bitwise unchanged.
- New unit test regtest/basic/rt-make-gridextension.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016vwxtU1YMqwpKiqhUECCP4
@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.00578% with 83 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.28%. Comparing base (a430df5) to head (2cc5cf0).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/tools/GridLattice.cpp 81.57% 56 Missing ⚠️
src/tools/GridLattice.h 92.63% 7 Missing ⚠️
src/bias/MetaDGrid.cpp 76.00% 6 Missing ⚠️
src/gridtools/KDEGridTools.h 88.23% 6 Missing ⚠️
src/tools/GridCoordinatesObject.cpp 93.25% 6 Missing ⚠️
src/generic/Accumulate.cpp 90.00% 1 Missing ⚠️
src/tools/GridCoordinatesObject.h 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1707      +/-   ##
==========================================
- Coverage   89.32%   89.28%   -0.04%     
==========================================
  Files         662      666       +4     
  Lines       84504    84600      +96     
==========================================
+ Hits        75482    75536      +54     
- Misses       9022     9064      +42     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…sObject

Second step towards one grid implementation for METAD/PBMETAD (tools/Grid)
and KDE/gridtools (tools/GridCoordinatesObject).

- tools/GridLattice is the geometry of a grid without data: range, spacing,
  periodicity, indices (column-major), points, neighbours, spline
  neighbours, extension and lattice shift. It is the code of GridBase, with
  its dimension-templated Accelerator, moved unchanged.
- GridBase derives from GridLattice; its public interface does not change
  (METAD, PBMETAD, EXTERNAL, FUNCSUMHILLS, funnel and ves are not touched).
- The flat grids of GridCoordinatesObject contain a GridLattice and use it
  for all their geometry; the interface of GridCoordinatesObject does not
  change (indices stay unsigned for now), fibonacci grids are unchanged.
- Behaviour changes only where the old code gave an error or a wrong result:
  along a periodic direction the indices of a point at the upper end or
  outside the range are brought back into the grid; the neighbours of a
  point outside the grid are computed from its own lattice position
  (GridCoordinatesObject converted a negative position to unsigned: on
  arm64 the neighbours of a kernel centred below GRID_MIN were those of the
  first point); flat GridCoordinatesObject grids are limited to 16
  dimensions and an index outside the grid is an error, as in GridBase.
- METAD/PBMETAD/EXTERNAL/ves results are bitwise unchanged; no reference
  changes. KDE and HISTOGRAM are 3-11% faster.
- New unit test regtest/basic/rt-make-gridlattice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016vwxtU1YMqwpKiqhUECCP4
Comment thread src/tools/GridLattice.cpp
template<typename T>
unsigned GridLattice::splineNeighbors(const unsigned* indices, std::size_t indices_size, T* neighbors, std::size_t neighbors_size) const {
plumed_assert(indices_size==dimension_);
unsigned nneigh=1<<dimension_; // same as unsigned(pow(2.0,dimension_));
carlocamilloni and others added 2 commits November 28, 2026 21:30
- GridCoordinatesObject indices are std::size_t (getIndex, getNumberOfPoints,
  getIndices, getGridPointCoordinates, getNeighbors, getSplineNeighbors,
  getStride...), as in GridBase; the KDE grid tools and the callers in
  gridtools, contour and ACCUMULATE are updated.
- KDE/HISTOGRAM stored a table of grid points x kernels (e.g. 1000 kernels
  in 3D on about 80^3 points: 4.2 GB; 10000 kernels on 400x450 points: out
  of memory). Now only the pairs of a kernel and a grid point where it is
  not zero are stored, in compressed rows with the kernels of each point in
  the same order, so the results are bitwise identical (160 MB and 310 MB in
  those cases); KDE and HISTOGRAM are 2-2.8 times faster.
- MetaDBiasGrid::addHillToPoints does not open an OpenMP parallel region
  when it runs on one thread (libgomp sets up a team at every region, i.e.
  at every hill): METAD/PBMETAD with grids 2-3% faster, bitwise identical.
- GridBase constructor: the vectors are built with their size (gcc 13 at -O3
  gave a -Warray-bounds false positive on a vector<bool> resized from empty,
  an error with -Werror).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016vwxtU1YMqwpKiqhUECCP4
- The spline interpolation of GridBase (METAD, EXTERNAL, ves...) and that
  of the gridtools Interpolator (EVALUATE_FUNCTION_FROM_GRID,
  INTERPOLATE_GRID) were two copies of the same code. GridLattice::
  splineInterpolation is the only one: the values and derivatives at the
  corners of the cell are read through a function given by the caller (the
  data of the grid, or the Value).
- Results are bitwise identical. The gridtools spline is about twice as
  fast (no allocations per call); the GridBase spline costs the same.
- At the upper end of a periodic argument (e.g. pi) the point is brought
  back into the grid and the polynomial now uses the right cell offset
  (the gridtools spline used a wrong one).
- The spline is tested in regtest/basic/rt-make-gridlattice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016vwxtU1YMqwpKiqhUECCP4
Comment thread src/tools/GridLattice.h
// a point outside the range of a periodic direction (e.g. at its upper end) has been brought back into the grid:
// the cell is the same, but xfloor must be next to x
const double f=std::floor((x[j]-min_[j])/dx_[j]);
if(f!=static_cast<double>(indices[j])) {
…the grid files. METAD's grids (GridBase), DUMPGRID and REFERENCE_GRID now all use them.

Files written: nothing changes. Each action still writes the same style as before: METAD/sum_hills count nbins as points and name derivatives der_x; DUMPGRID counts bins and names them d<f>_x.
Files read: the reader works out the style from the derivative columns. So REFERENCE_GRID can now read METAD/PBMETAD grids and sum_hills free energies, and EXTERNAL (or METAD with GRID_RFILE) can read DUMPGRID files.
New regtest gridtools/rt-grid-file-styles: one grid in each style, each read by EXTERNAL and by REFERENCE_GRID. Both give identical values.
CHANGES/v2.11.md: one user entry and one developer entry.

Your rt-make-gridlattice failure (macOS and Intel) came from the part 1 test printing the spline results with 17 digits. The last digits depend on how the compiler fuses operations and on the maths library. The spline lines now print 10 decimals, with noise below 1e-10 shown as zero; the reference is updated. The fix is in the same patch.

Checks:

Full regtest, all modules: everything passes and no reference files changed. As before, I stopped the ves MPI test that hangs on 2 cores.
Comparison with step A at 17 digits, 221 tests: only the known differences (MPI log timings and the rt-pbmetad-grid-mpi replica files), with the same exit codes. So METAD/PBMETAD results and the grid files they write are bitwise unchanged.
Compiler warnings: -O3 -Wall -pedantic -Wshadow -Werror is clean on the changed files, and astyle has been applied.
codecheck: nothing new in the changed code. The run was cut short, so I compared the touched files by hand. What it flags is either in the part 1 code too, or cppcheck's usual header-only "unused member" false positive on GridFile.h.
CodeQL: your repo's CodeQL workflow runs on pull requests to master, so it will check these changes once they're on the PR. Meanwhile I reviewed the new code by hand against CodeQL's usual patterns and found nothing.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants