Skip to content

Add a native multi-threaded CPU platform: Simulation(platform="native") - #83

Closed
paulmenzel wants to merge 23 commits into
open2c:masterfrom
mpimg:add-native-cpu-engine
Closed

paulmenzel wants to merge 23 commits into
open2c:masterfrom
mpimg:add-native-cpu-engine

Conversation

@paulmenzel

@paulmenzel paulmenzel commented Nov 27, 2026 •

Copy link
Copy Markdown

AI disclaimer: Drafted by claude-opus-5.5 and reviewed by me. I am no scientist and just an IT guy, so consider this a proof of concept.

Description

GPUs are scarce and in high demand on shared clusters, while CPU nodes are far more common. This PR makes CPUs a practical alternative for polychrom: one two-socket Zen 3 node (2 × 64-core EPYC 7763) running independent simulations does the work of about two (N = 200,000) to ten (N = 10,000) A100 GPUs, each running one simulation with OpenMM’s CUDA platform (see Performance below).

Without it, polychrom on CPUs is slow, because OpenMM’s CPU platform spends most of each time step on overheads that don’t matter for coarse-grained polymer models. Profile of the loop extrusion benchmark below (N = 10,000), OpenMM 8.6.1 CPU platform, one thread on an EPYC 7551:

Forces ms/step
integrator only 0.96
+ HarmonicBondForce 1.40
+ CustomAngleForce 4.02
+ CustomNonbondedForce 7.81
all three 10.51 (95 steps/s)

More threads help little: on a 2 × 64-core EPYC 7763 node, OpenMM’s best over 1–256 threads is 92–190 steps/s at N = 10,000, depending on the run (at 32 or 64 threads), against 64 steps/s with one thread.

Add an optional platform, Simulation(platform="native"), backed by a small C++17/OpenMP engine (polychrom/_native/engine.hpp) with a Cython wrapper. Existing scripts run unchanged apart from the platform name: forces are still created by polychrom.forces as OpenMM force objects, and polychrom.native translates them and provides the parts of openmm.Context, Integrator and State that polychrom uses, including force.updateParametersInContext(sim.context) for loop extrusion (bondUpdater).

Usage

sim = Simulation(platform="native", integrator="variableLangevin", error_tol=0.01, collision_rate=0.03, N=N, ...)
  • Threads: POLYCHROM_NATIVE_THREADS, else OMP_NUM_THREADS, else OPENMM_CPU_THREADS, else one thread per 500 particles up to the number of usable CPUs.
  • On x86-64 CPUs with AVX2 and FMA, a second build of the engine (polychrom._native_engine_x86_64_v3) is used. It gives the same results and is about 16 % faster on Zen 3. POLYCHROM_NATIVE_ISA=baseline selects the generic build.

What is supported

  • Bonds: HarmonicBondForce is evaluated directly. CustomBondForce, CustomAngleForce and CustomNonbondedForce with any isotropic expression are tabulated once per distinct parameter set: a copy of the force is evaluated on OpenMM’s Reference platform, and cubic Hermite tables are refined until the force matches OpenMM to 1e-6 (relative to its maximum). Global parameters, tabulated functions and switching functions are kept; kinks are put on knots.
  • External forces: spherical_confinement and tether_particles.
  • Integrators: langevin, langevinMiddle, variableLangevin and brownian, following OpenMM 8’s Reference implementations. Random numbers differ from OpenMM’s, so trajectories agree statistically, not bit by bit.
  • Energy minimisation: OpenMM’s L-BFGS on a temporary CPU context.
  • Anything else raises NotImplementedError when the context is created.

How it works

  • One OpenMP parallel region per step(n) call; the phases of a step are work-sharing loops separated by barriers.
  • Verlet lists with a skin, built from cell-ordered coordinates with a branch-free (AVX2) candidate filter. Particles that moved more than half the skin since the last build (the "fast set", e.g. monomers pulled by a freshly placed LEF bond) get their pair interactions from a direct cell search, so lists are rebuilt only when the fast set exceeds max(64, N/32).
  • Full neighbour lists, so each thread accumulates the pair forces of its own particles without atomics.
  • Bonded forces are written into a contribution buffer and gathered per particle, in chunks of particles, so the buffer stays in the cache.
  • A counter-based Ziggurat Gaussian generator keyed by (seed, step, coordinate).

Forces and trajectories therefore don’t depend on the number of threads (only the summation order of the reported potential energy does), and the generic and AVX2 builds give the same results.

Validation

  • tests/test_native.py (17 tests) compares forces and energies with OpenMM’s Reference platform (relative force error below 2e-6, 1e-5 for two cases). It covers open, ring and periodic chains; harmonic, constant-force and FENE bonds; angle forces; polynomial_repulsive, smooth_square_well and heteropolymer_SSW with several particle types; confinement and tethers; parameter updates; the fast set; and bonded terms spanning many particles. It also checks that all four integrators thermalise, that unsupported forces raise, and that trajectories are bit-identical for 1, 3 and 4 threads.

  • Equilibrium statistics compared with OpenMM’s CPU platform: N = 400, PBC, loop extrusion force set, variableLangevin, 16 seeds × 400 blocks × 1000 steps each (mean ± standard error over seeds):

    Observable OpenMM CPU native difference / SE
    kinetic energy / particle (kT) 1.4616 ± 0.0008 1.4621 ± 0.0006 +0.5
    potential energy / particle (kT) 1.2617 ± 0.0010 1.2621 ± 0.0005 +0.3
    mean bond length 1.00970 ± 0.00005 1.00970 ± 0.00005 +0.6
    bond length spread 0.07067 ± 0.00004 0.07070 ± 0.00002 +0.7
    mean cos(angle) 0.5772 ± 0.0004 0.5772 ± 0.0002 −0.0
    radius of gyration 15.3 ± 0.6 14.8 ± 0.5 −0.7
    mean step size (ps) 0.16927 ± 0.00014 0.16935 ± 0.00011 +0.4

    (Run with an earlier version of the code, which summed the step-size error in a different order; that changes only the last bits of the variable step size.)

Performance

Loop extrusion benchmark modelled on examples/loopExtrusion: chain of N monomers in a periodic box at density 0.1, polymer_chains (harmonic bonds, angle k = 1.5, polynomial_repulsive trunc 1.5), N/100 LEFs with 10 candidate bonds each whose stiffness is toggled every 750 steps with updateParametersInContext, variableLangevin (error_tol 0.01, collision rate 0.03). EPYC 7763 (Zen 3, 2 × 64 cores), OpenMM 8.6.1:

N OpenMM CPU, 1 thread OpenMM CPU, best of 1–256 threads native, 1 thread native, best (32 threads)
10,000 64 190 756 5,844
50,000 11 34.47 145 1,361
200,000 2.47 9.11 32 338

(steps/s; OpenMM’s best is the maximum over several runs with 1, 8, 16, 32, 64, 128 and 256 threads.) A single simulation stops scaling at about 32 threads, so one simulation should stay within one socket.

Many independent simulations on one node (the usual case for replicates and parameter scans), each pinned to its own cores:

N runs × threads steps/s, all runs together per run
10,000 64 × 2 76,913 1,182–1,208
200,000 16 × 8 2,378 146–154
200,000 128 × 1 1,921 15–16

With large systems the node is then limited by memory bandwidth: with 128 single-thread runs at N = 200,000, each runs at about half its stand-alone speed.

For comparison, one A100 (PCIe, 40 GB) with OpenMM’s CUDA platform (mixed precision) runs one simulation of this benchmark at 7,508 steps/s (N = 10,000) and 1,189 steps/s (N = 200,000), so the node matches about ten and two A100s, respectively. Running several simulations on one GPU (e.g. with MPS) was not tested.

Building

The engine is a Cython extension built by setup.py; it uses OpenMP where available (not on macOS) and builds single-threaded without it (POLYCHROM_NO_OPENMP). Extra compiler flags can be passed with POLYCHROM_NATIVE_CFLAGS. Both builds use -ffp-contract=off, so that results don’t depend on the build. Tested only on Linux x86-64 (GCC 12, Python 3.14, Zen 1 and Zen 3); not yet in this repository’s CI.

Limitations

  • Only isotropic, distance- or angle-only custom forces; CustomExternalForce only for spherical_confinement and tether_particles.
  • At most 2^27 particles; a moderate number of distinct parameter sets per tabulated force (64).
  • With more than one nonbonded force, the lists are rebuilt whenever a particle enters the fast set (slower, still correct).

Commits

The branch is meant to be reviewed commit by commit; each commit message has its measurements:

  1. The engine, the platform, the tests and fixes found while benchmarking (Add a native multi-threaded CPU engine … to Find fast-fast pairs through the cell grid …).
  2. Per-core optimisations (Filter list-build candidates from cell-ordered coordinates to Describe the per-core techniques …). Each one keeps trajectories bit-identical; together they make one thread about 1.4× faster and a fully packed node 1.3–1.5× faster.
  3. Fix black and flake8 findings in the native platform.

The branch is based on 0cd8519 (delta storage for polychrom (#81)).

PR Checklist

  • apply "black" (on the files this PR changes: polychrom/native.py, polychrom/simulation.py, tests/test_native.py, setup.py)
  • apply isort (same files)
  • run flake8 (max line length 120: no findings in these files)

OpenMM's CPU platform spends most of its time on per-step overheads that do
not matter for coarse-grained polymer models.  Profile of the loop extrusion
benchmark (N = 10,000, density 0.1, harmonic bonds, polychrom angle force,
polynomial_repulsive, LangevinMiddle 70 fs), OpenMM 8.6.1 CPU platform, one
thread on an EPYC 7551:

    integrator only, no forces       0.96 ms/step
    + HarmonicBondForce              1.40 ms/step
    + CustomAngleForce               4.02 ms/step
    + CustomNonbondedForce           7.81 ms/step
    all three                       10.51 ms/step  (95 steps/s)

and 6 threads only reach 7.9 ms/step; on the Zen 3 nodes 256 threads are
slower than 32.

Add polychrom/_native/engine.hpp, a small C++17/OpenMP engine with a Cython
wrapper (polychrom._native_engine), reproducing the subset of OpenMM used by
polychrom:

- harmonic bonds, tabulated bonds, tabulated angles (in cos(theta) where
  smooth, avoiding atan2), tabulated pair potentials with per-type tables and
  exclusions, spherical confinement and tethers;
- OpenMM 8's LangevinMiddle (= Langevin), VariableLangevin (same step size
  rule as ReferenceVariableStochasticDynamics) and Brownian integrators;
- Verlet lists with a skin, packed 32-bit entries (index and periodic image),
  built per occupied cell with a branch-free candidate filter;
- one OpenMP parallel region per step(n) call, owner-computes pair forces and
  a CSR gather of bonded contributions, a counter-based Ziggurat RNG, and
  the variable Langevin error summed over fixed blocks of 64 particles, so
  forces and trajectories do not depend on the number of threads.

Same benchmark, native engine, one thread on the same EPYC 7551:
1.80 ms/step (555 steps/s), 5.8x faster.  Zen 3 measurements are in the following commits.

Assisted-by: claude-opus-5.5 (Claude Code)
polychrom.native translates the OpenMM force objects created by
polychrom.forces into native engine terms and provides stand-ins for the
parts of openmm.Context, Integrator and State that polychrom code uses, so
existing scripts run unchanged:

- HarmonicBondForce is evaluated natively; CustomBondForce, CustomAngleForce
  and CustomNonbondedForce of any isotropic expression are tabulated once per
  distinct parameter set.  A copy of the force (via XmlSerializer, so global
  parameters, tabulated functions and switching are kept) is evaluated for
  1024 configurations per call on the Reference platform.  Energies are
  integrated from the exact derivatives (Simpson), and tables are refined
  until the interpolated force matches OpenMM at the quarter points to 1e-6.
  Kinks (smooth_square_well at REPsigma and at the cutoff) are put on knots.
- spherical_confinement and tether_particles are recognised by expression.
- force.updateParametersInContext(sim.context) is redirected to the engine,
  so polychrom.lib.extrusion.bondUpdater works; context.setParameter
  re-tabulates the affected force.
- Energy minimisation uses OpenMM's L-BFGS on a temporary CPU context.
- Unsupported forces and integrators raise NotImplementedError.

Tabulating the heteropolymer_SSW test case (6 particle types) took 39 s with
one OpenMM call per point; batching brings it to about 1 s.

In OpenMM 8, LangevinIntegrator subclasses LangevinMiddleIntegrator and
VariableLangevinIntegrator uses the same middle scheme
(ReferenceVariableStochasticDynamics.cpp, OpenMM 8.2.0), which the engine
follows.

Assisted-by: claude-opus-5.5 (Claude Code)
Compare forces and energies for open, ring and periodic chains with
harmonic, constant-force and FENE bonds, angle forces (theta_0 = pi and not),
polynomial_repulsive, smooth_square_well, heteropolymer_SSW with three types
and extra-hard particles, spherical confinement, anisotropic tethers, bond
parameter updates and global parameter changes.  Also check that all four
integrators thermalise, that unsupported forces raise, and that trajectories
do not depend on the number of threads.

The variableLangevin integrator test uses the loop extrusion parameters:
with the default polymer_chains bonds (wiggle 0.05) and no minimisation,
OpenMM's CPU platform fails as well:

    variableLangevin CPU     EKExceedsError('Ek=18.92304825791721 exceeds 10')
    variableLangevin native  EKExceedsError('Ek=20.55497869700652 exceeds 10')

Assisted-by: claude-opus-5.5 (Claude Code)
…lignment

Near theta = pi, OpenMM's derivative of an angle potential is accurate to
only ~1e-5, so the refinement of the polychrom angle_force table never met
the 1e-6 target and always went to the 8193-knot maximum (256 KiB):

    [('angle force angle', 8193), ('angle force angle', 2049), ...]

Refine while doubling the resolution reduces the error; cubic Hermite
interpolation gains ~8x per doubling where the force is smooth.  When it
gains less than 3x, first try to put a knot on a kink (and on the cutoff),
then keep doubling, which keeps both on knots; stop when a doubling no
longer helps, keeping the best table.  The angle table now has 1025 knots;
smooth_square_well converges at the kink instead of stalling:

    knots 2049: err 1.21e-01 at x=0.99941
    knots 1038: err 7.21e-05 at x=1.00000   (kink aligned)
    knots 4149: err 1.47e-06 at x=1.00000

On Zen 3 (wallaby, EPYC 7763, one thread, loop extrusion benchmark,
N = 10,000) the smaller angle table makes no measurable difference
(375-386 steps/s before and after); it mainly removes wasted tabulation.

Assisted-by: claude-opus-5.5 (Claude Code)
_Batch deep-copied the serialized force, including all particles,
exclusions, bonds or angles, and then removed those children one by one
(quadratic).  Setting up the loop extrusion benchmark with N = 200,000:

    599997   15.622    0.000   15.622    0.000 {method 'remove' of 'xml.etree.ElementTree.Element' objects}
      4/2    1.310    0.328    6.217    3.109 {method '__deepcopy__' of 'xml.etree.ElementTree.Element' objects}
    _apply_forces cumulative 34.3 s

Copy only the small children (expression, parameters, functions) and start
with empty lists.  _apply_forces now takes 12.6 s, of which 4.5 s are
OpenMM's own XmlSerializer.serialize.

Assisted-by: claude-opus-5.5 (Claude Code)
In the loop extrusion benchmark, the LEF bonds that are switched on pull
their (distant) monomers together by up to ~0.4 nm per step, so the "rebuild
when any particle moved more than half the skin" rule rebuilt the lists
every 1.5 steps:

    native N=10000: 366 steps/s, dt 148 fs, steps/rebuild 1.5, list 3.5/particle

Keep lists valid for the particles that moved less than half the skin, and
give the others (the fast set) their pair interactions from a direct search
every step: fast-slow pairs through the cell grid of the last build (a slow
particle is still within the 27-cell stencil), fast-fast pairs directly.
Each such pair is computed once, the force on the partner is buffered and
applied by one thread in the order of the fast list, so results stay
independent of the thread count.
Lists are rebuilt when the fast set exceeds max(64, N/32) particles, or
with several pair forces or fewer than 3 cells per periodic dimension
whenever it is not empty.

Zen 3 (wallaby, EPYC 7763), one thread, same benchmark, three runs each:

    before: 377, 389, 388 steps/s, steps/rebuild 1.5-1.6
    after:  549, 550, 558 steps/s, steps/rebuild 3.3-3.4

Assisted-by: claude-opus-5.5 (Claude Code)
With the OpenMP default (all CPUs in the affinity mask), a small system on a
busy shared host spent almost all its time waiting at barriers.  N = 200,
70 blocks of 200 steps, 6 CPUs, load average 16.8:

    POLYCHROM_NATIVE_THREADS=1:    1.73 s
    POLYCHROM_NATIVE_THREADS=2:    1.56 s
    unset (6 threads):           150.96 s

Use min(available CPUs, N / 500) threads unless POLYCHROM_NATIVE_THREADS,
OMP_NUM_THREADS or OPENMM_CPU_THREADS is set.  The unset case now takes
1.83 s, and tests/test_native.py runs in 9 s instead of 25 s on that host.

Assisted-by: claude-opus-5.5 (Claude Code)
Profile of the loop extrusion benchmark, N = 200,000, 64 threads on Zen 3
(wallaby), 254-259 steps/s:

    36.59%  forces_inner
    30.38%  gomp_team_barrier_wait_end
    14.37%  build_list_inner
     5.62%  fast_set_forces

With max(64, N/32) the fast set could hold 6250 particles at N = 200,000,
and its fast-fast pairs are checked directly (~2e7 pairs per step).  Limit
it to 1024 particles.  Also move the per-particle cell assignment of the
list build out of the serial section, which the other threads wait for.

Assisted-by: claude-opus-5.5 (Claude Code)
Capping the fast set at 1024 particles (to bound the direct fast-fast
check) made rebuilds more frequent at large N and was slower overall.
Loop extrusion benchmark, N = 200,000, 64 threads, Zen 3 (wallaby):

    max(64, N/32) cap, O(nfast^2):  254, 259 steps/s, steps/rebuild 3.4
    cap 1024:                       246, 231 steps/s, steps/rebuild 2.3-2.4

Bin the fast set by its current cell instead (sorted (cell, particle)
pairs, looked up for the same 27-cell stencil), which costs
O(nfast log nfast), and restore the max(64, N/32) limit.

Add a test in which stiff long bonds pull particles fast enough to enter
the fast set, stepping until two non-bonded fast particles are within the
cutoff, and comparing forces with the Reference platform without a list
rebuild in between.  With the fast-fast lookup disabled the test fails:

    E       Mismatched elements: 6 / 1200 (0.5%)

Also extend test_trajectory_independent_of_threads to variable Langevin,
add stiff long bonds that pull particles into the fast set, and compare
1, 3 and 4 threads.  Before the summation-order fixes in "Add a native
multi-threaded CPU engine ..." and "Handle fast particles without
rebuilding the neighbour lists", it failed, also between runs of one
build:

    E           Mismatched elements: 574 / 1500 (38.3%)
    E           Mismatched elements: 1500 / 1500 (100%)
    2 failed, 14 deselected in 3.03s

Assisted-by: claude-opus-5.5 (Claude Code)
The candidate buffer of each cell was filled with four push_back calls
per particle, gathered from the per-particle coordinate array, and each
accepted candidate was checked with a binary search over the particle's
exclusions.

Copy the wrapped coordinates into cell order once per build, so that the
nine stencil columns of a cell are contiguous ranges that are copied into
the buffer with plain loops, and compare against up to eight exclusions
without branches.  The candidate order is unchanged, so trajectories are
bit-identical (position hashes of a 4,000-particle loop extrusion run
with variable and fixed-step Langevin, one thread).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1),
per particle and step in the timed region:

                  steps/s  cycles  instructions  branch misses
    before:       360-361     782          1756              7
    after:        364-369     763          1597              5

Assisted-by: claude-opus-5.5 (Claude Code)
The engine was compiled for baseline x86-64 (SSE2), so the compiler could
use neither AVX2 nor FMA.  Build a second extension module,
polychrom._native_engine_x86_64_v3 (-mavx2 -mfma -mbmi2), from the same
Cython source, and import it in polychrom.native when the CPU supports
these instructions (__builtin_cpu_supports, which also checks that the OS
saves the AVX state).  POLYCHROM_NATIVE_ISA=baseline selects the generic
build; polychrom.native.ENGINE_ISA tells which one is in use.

Compile both with -ffp-contract=off, so that the compiler does not fuse
multiplications and additions into FMA instructions in one build only:
both builds give bit-identical trajectories (position hashes of a 4,000-
particle loop extrusion run with variable and fixed-step Langevin).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1),
per particle and step:

                         cycles  instructions
    baseline:           675-685          1586
    -march=native:          660          1453

The node is shared and the cycle counts vary by about 10 % between runs.
On a dedicated EPYC 7763 (Zen 3), the two builds were equally fast at
this commit (574 and 575 cycles per particle and step); with the AVX2
code of the following commits, the x86-64-v3 build is 16 % faster
(at "Keep the rare Ziggurat rejection path out of the integrator loop",
one thread, three runs each; cycles per particle and step in parentheses):

                       N = 10,000           N = 200,000
    baseline build:    628 steps/s (554)    26 steps/s (683)
    x86-64-v3 build:   730 steps/s (477)    30 steps/s (578)

Assisted-by: claude-opus-5.5 (Claude Code)
Each step refreshed the wrapped coordinates (xw = x - img) in a pass of
its own, and variable Langevin summed (f/m)^2 in another pass over the
forces, followed by a barrier.  For large systems, whose data does not
fit into the caches, every pass streams the arrays from memory.

Update xw in the integrator, right after the new x (and once after a
list rebuild, when img changes); without PBC, the pair loop reads x.
Accumulate the error sum in the loop that gathers the bonded forces,
which is the last update of f, and select the step size in the single
block that follows it.  If the forces were already valid when a step
starts (after getState), the integrator selects it as before.

Trajectories are bit-identical to the previous commit (position hashes of
a 4,000-particle loop extrusion run, 1 and 3 threads).  The thread test
now queries the energy between steps, so that variable Langevin also
starts steps with valid forces: a first version of this change, which
set the "step size selected" flag inside the single block that the
threads test it for, deadlocked there.

Assisted-by: claude-opus-5.5 (Claude Code)
The bonded terms wrote the force on every particle they involve into the
contribution buffer, 2 vectors per bond and 3 per angle, although the
force on j is -f_i for a bond and -f_i - f_k for an angle.  For a chain
that is 120 bytes per particle and step written and read back by the
gather, the largest single item of the per-step memory traffic.

Store only f_i for bonds and f_i, f_k for angles, and let the gather
index say whether to add the vector, subtract it, or subtract it and the
next one (the same expression as before, so trajectories are
bit-identical: position hashes of a 4,000-particle loop extrusion run, 1
and 3 threads).  This saves 72 of the 120 bytes for a chain.

Assisted-by: claude-opus-5.5 (Claude Code)
In the x86-64-v3 build, compare four candidates per iteration and move the
accepted entries to the front with a byte shuffle chosen by the
comparison mask (16-entry table), instead of one candidate per
iteration.  The candidate buffer is padded to a multiple of four with
far-away entries.  The arithmetic is the same as in the scalar loop
(no FMA, same order), so the lists and trajectories are bit-identical,
also between the two builds (position hashes of a 4,000-particle loop
extrusion run, 1 and 3 threads, both builds).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared
node, cycles vary by ~10 %), per particle and step:

                        cycles  instructions
    baseline build:        664          1612
    x86-64-v3 build:       626          1352

Assisted-by: claude-opus-5.5 (Claude Code)
The nine stencil columns of a cell hold a few particles each (about 3.5
in the loop extrusion benchmark), and the compiler's vectorised copy
loop spends most of its time in its prologue and epilogue.  In the
x86-64-v3 build, copy each run in whole groups of four, reading up to
three entries past the run from padded arrays and writing past it into
the candidate buffer, where the next run or the far-away padding
overwrites them.  Trajectories are bit-identical (both builds, 1 and 3
threads).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared
node), per particle and step: 1352 -> 1301 instructions, 626 -> 600
cycles.

Assisted-by: claude-opus-5.5 (Claude Code)
The integrator stored x[c] and read it back twice (for the wrapped
coordinate and the displacement since the last list build); as all
arrays are double, the compiler had to assume that each store may
change the other inputs.  Use the new coordinate from the register and
restrict-qualified local pointers.  Also skip the square root of the
inverse mass per particle when all masses are equal (polychrom's
default).  Trajectories are bit-identical (both builds, 1 and 3 threads).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared
node), per particle and step: 1301 -> 1294 instructions, 600 -> 584
cycles (within the noise of this node).

Assisted-by: claude-opus-5.5 (Claude Code)
polychrom gives all particles the same mass, all chain bonds the same
length and stiffness, and all angles the same potential, yet the
gather, the integrator and the bonded loops loaded the inverse mass,
r0 and k, and the angle table index per particle or term: 8 + 16 + 4
bytes per particle and step from memory for large systems.  Detect the
uniform case when the parameters are set and use the first value.
Trajectories are bit-identical (1 and 3 threads).

Assisted-by: claude-opus-5.5 (Claude Code)
The image offset of each coordinate at the last list build (a multiple
of the box) was stored as a double and read by the integrator every
step to update the wrapped coordinates.  Store the count as a 32-bit
integer instead: 12 instead of 24 bytes per particle and step.  The
product count * box is the same double as before, so trajectories are
bit-identical (1 and 3 threads).  A count beyond 2e9 boxes (or NaN) is
reported as an exploded simulation.

Assisted-by: claude-opus-5.5 (Claude Code)
The bonded terms wrote their forces into the contribution buffer in one
pass over all terms, and a second pass after a barrier gathered them per
particle.  For large systems the buffer (72 bytes per particle for a
chain) goes to memory and back every step, and the coordinates are
streamed twice, once for the bonds and once for the angles.

Process the terms in chunks of 64 particles instead (the blocks of the
error sum), by the chunk of
their lowest particle, and gather a chunk right after its terms: the
terms of chunks 0..k are all that reach chunk k.  Each thread takes a
contiguous range of chunks; a chunk that terms from an earlier range
reach into (a ring's closing bond, long bonds, or a chain crossing the
range boundary) is gathered after a barrier.  Terms that are not sorted
by their lowest particle (loop extrusion bonds) are processed through an
index.  Contribution slots, the gather order and the error-sum blocks
are unchanged, so trajectories are bit-identical (both builds, 1, 3 and
4 threads).

Add a test with a ring and bonds spanning 1500 particles at N = 2600,
compared with the Reference platform with 1 and 4 threads.  With every
chunk gathered right away (ignoring terms from other ranges), it fails:

    E           Mismatched elements: 11 / 7800 (0.141%)
    1 failed, 16 deselected in 3.07s

The chunks are small so that all threads get some: with chunks of 1024
particles, a single run at N = 10,000 had only 10 of them, and became
slower than before this optimisation work at 32 and 64 threads.  Loop
extrusion benchmark, EPYC 7763 (Zen 3), one run on contiguous cores, at
the end of this series, steps/s (two runs each):

    threads                         1      8      32      64
    before the series             546   3328    4843    4572
    chunks of 1024 particles      759   3880    4526    3946
    chunks of 256 particles       742   4276    5316    4740
    chunks of 64 particles        747   4322    5714    4916

At N = 200,000 (8, 32 and 64 threads) the chunk size makes no
measurable difference.

Assisted-by: claude-opus-5.5 (Claude Code)
The normal deviate generator was inlined three times per particle with
its rejection loop, tail sampling and exp/log calls, which are needed
for about 1 % of the draws.  The integrator loop ran out of registers
and kept the displacement sum and its array pointers on the stack.
Inline only the first draw and the fast acceptance test, continue in a
separate cold function from the same state otherwise, and draw the three
deviates of a particle before updating its coordinates.  The random
numbers and trajectories are bit-identical (both builds, 1 and 3
threads).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared
node), per particle and step: 1369 -> 1286 instructions, 618-634 -> 579-581
cycles.

Assisted-by: claude-opus-5.5 (Claude Code)
After the distance filter, every accepted candidate was compared with
the particle itself and its exclusions in a second loop.  In a polymer,
almost every particle excludes just its two chain neighbours, which are
always within the list radius.  For particles with at most two
exclusions, compare the candidates' indices with them (and the entry
with the particle itself) in the filter, four at a time with AVX2, and
leave them out of the same compaction.  Lists and trajectories are
bit-identical (both builds, 1 and 3 threads).

Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared
node), per particle and step: 1286 -> 1249 instructions, 579-581 -> 556-563
cycles, 5 -> 4 branch misses.

Assisted-by: claude-opus-5.5 (Claude Code)
Assisted-by: claude-opus-5.5 (Claude Code)
The pull request template asks for black, isort and flake8.  Before this
commit:

    would reformat tests/test_native.py
    would reformat polychrom/native.py
    polychrom/native.py:679:121: E501 line too long (124 > 120 characters)
    polychrom/native.py:871:9: F841 local variable 'globals_' is assigned to but never used
    tests/test_native.py:249:5: F841 local variable 'rng' is assigned to but never used
    tests/test_native.py:255:121: E501 line too long (131 > 120 characters)

Wrap the long lines as black does, drop the unused random generator, and
keep the call of _globals in _add_external (it registers the global
parameters that g() reads) without assigning its result.  black, isort
and flake8 (max line length 120, as in pyproject.toml) now pass for
polychrom/native.py, polychrom/simulation.py, tests/test_native.py and
setup.py.

Assisted-by: claude-opus-5.5 (Claude Code)
@mimakaev

Copy link
Copy Markdown
Collaborator

hi Paul! This looks like an exciting contribution, and it does seem to be a truly faster local executor. However, I wonder if it should live in polychrom or in a separate package.

I'd be definitely down to merge the tooling needed to adopt a different engine in polychrom, and even hard-code the "native" integrator reference and the link to a package (please install ...) as well as documentation / mention of it in the main README, benchmarks, etc.

My concern with merging this entire PR is that it brings some nontrivial compile flags with it, and installation may fail e.g. on the older clusters, people who run polychrom on native Windows (I have certainly met someone a few years ago), etc. - hence separation between the two.

What do you think?

@paulmenzel

Copy link
Copy Markdown
Author

Dear Max, thank you for taking a look and the time to reply. As written this is a proof of concept, and I am no scientist, so cannot say for certain it’s correct. Having it in a separate project sounds good, and thank you for being open. I won’t be able to maintain it, so I am going to close this merge/pull request, and should somebody need a CPU based version, they can start a separate package. Let’s see how our scientists are going to use polychrom, and if there is going to arise a need for the native engine, or if our few GPU nodes are going to be enough for them. Thanks again, and all the best with polychrom.

@paulmenzel paulmenzel closed this Nov 30, 2026
@mimakaev

Copy link
Copy Markdown
Collaborator

In the age of AI, maintaining a project per se is not very difficult. Even for polychrom, something turns up maybe once a year. If you publish this somewhere on github, I'd gladly link to it. I think it is a good contribution and is useful for other researchers.

Alternatively I can actually incorporate this into polychrom, but as an optional build flag. It would be something like POLYCHROM_BUILD_NATIVE=1 pip install -e . and will work with pip install git+... as well - so by default it would not build the native backend, but will actually build it if needed. It's a reasonable middle ground I think, keeps it in the repo but avoids conflicts for people using weird hardware.

Let me know what you'd prefer.

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