diff --git a/CHANGELOG.md b/CHANGELOG.md index 42727b50..0c7fd10e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ Changelog * Pass `opencl_platform_index` to the GCMC sampler, so that GCMC runs on the same OpenCL device as the dynamics when there are multiple OpenCL platforms [#266](https://github.com/OpenBioSim/somd2/pull/266). * Fixed energy trajectory times for ABFE bound legs without a Boresch restraint being offset by up to the `restraint_search_time`, since production started from the time of the restraint search frame rather than the input system [#268](https://github.com/OpenBioSim/somd2/pull/268). * Raise an error when a `perturbed_system` with a different periodic box from the reference system is used for GCMC in the NVT ensemble, since every replica must share the same box. GCMC in the osmotic ensemble, with a pressure set, is unaffected [#271](https://github.com/OpenBioSim/somd2/pull/271). +* Add a `chain_equilibration` option for replica exchange, which speeds up setup by starting each replica from a neighbour that has already been set up. Replicas in the first parallel batch, which is spread across lambda, are minimised and equilibrated from the input system. The rest skip minimisation and are equilibrated for `chain_equilibration_scale` times the `equilibration_time`, which defaults to a quarter [#273](https://github.com/OpenBioSim/somd2/pull/273). [2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 679e5fdd..af4005f3 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -103,6 +103,8 @@ class Config: "equilibration_time", "equilibration_timestep", "equilibration_constraints", + "chain_equilibration", + "chain_equilibration_scale", "energy_frequency", "frame_frequency", "save_velocities", @@ -176,6 +178,8 @@ def __init__( equilibration_time="0 ps", equilibration_timestep="2 fs", equilibration_constraints=True, + chain_equilibration=False, + chain_equilibration_scale=0.25, energy_frequency="1 ps", save_trajectories=True, frame_frequency="100 ps", @@ -421,6 +425,23 @@ def __init__( will be used. If True, then the values specified by 'constraint' and 'perturbable_constraint' will be used. + chain_equilibration: bool + Whether to start each replica from the state of a neighbouring one + that has already been set up, for replica exchange simulations. The + replicas set up in the first parallel batch, which are spread across + lambda, are minimised and equilibrated from the input system. Every + other replica starts from the equilibrated state of the closest one + already set up, and is equilibrated for 'chain_equilibration_scale' + times the 'equilibration_time', without minimisation. If there is no + equilibration, then each replica is minimised from the minimised + state of its neighbour instead. Replicas never start from one that + was seeded from the other end state by 'perturbed_system'. + + chain_equilibration_scale: float + The fraction of the 'equilibration_time' for which replicas started + from a neighbour's state are equilibrated when 'chain_equilibration' + is True. + energy_frequency: str Frequency at which to output energy data. If running using 'replica_exchange', then this will also be the frequency at which replica swaps are attempted. @@ -825,6 +846,8 @@ def __init__( self.equilibration_time = equilibration_time self.equilibration_timestep = equilibration_timestep self.equilibration_constraints = equilibration_constraints + self.chain_equilibration = chain_equilibration + self.chain_equilibration_scale = chain_equilibration_scale self.energy_frequency = energy_frequency self.save_trajectories = save_trajectories self.frame_frequency = frame_frequency @@ -1924,6 +1947,32 @@ def equilibration_constraints(self, equilibration_constraints): "using a timestep greater than 1fs." ) + @property + def chain_equilibration(self): + return self._chain_equilibration + + @chain_equilibration.setter + def chain_equilibration(self, chain_equilibration): + if not isinstance(chain_equilibration, bool): + raise ValueError("'chain_equilibration' must be of type 'bool'") + self._chain_equilibration = chain_equilibration + + @property + def chain_equilibration_scale(self): + return self._chain_equilibration_scale + + @chain_equilibration_scale.setter + def chain_equilibration_scale(self, chain_equilibration_scale): + if isinstance(chain_equilibration_scale, bool): + raise ValueError("'chain_equilibration_scale' must be a float") + try: + chain_equilibration_scale = float(chain_equilibration_scale) + except Exception: + raise ValueError("'chain_equilibration_scale' must be a float") + if not 0.0 < chain_equilibration_scale <= 1.0: + raise ValueError("'chain_equilibration_scale' must be in (0, 1]") + self._chain_equilibration_scale = chain_equilibration_scale + @property def energy_frequency(self): return self._energy_frequency diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 66a3cfbc..a5defd3e 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -716,6 +716,19 @@ def _set_schedule(self, pert_idxs, ion_indices): _logger.error(msg) raise ValueError(msg) + if self._config.chain_equilibration: + if not self._config.replica_exchange: + msg = "'chain_equilibration' requires 'replica_exchange'." + _logger.error(msg) + raise ValueError(msg) + if isinstance(self._config.equilibration_time, list): + msg = ( + "'chain_equilibration' can't be used with a list of " + "'equilibration_time' values." + ) + _logger.error(msg) + raise ValueError(msg) + # Set the equilibration time for each window. if isinstance(self._config.equilibration_time, list): if len(self._config.equilibration_time) != len(self._lambda_values): diff --git a/src/somd2/runner/_dynamics_cache.py b/src/somd2/runner/_dynamics_cache.py index 0b956f55..7205dcba 100644 --- a/src/somd2/runner/_dynamics_cache.py +++ b/src/somd2/runner/_dynamics_cache.py @@ -402,6 +402,9 @@ def _create_dynamics( str(output_directory / f"gcmc_ghosts_{lam:.5f}.txt") for lam in lambdas ] + # Whether each replica starts from the perturbed end state coordinates. + self._start_perturbed = [False] * num_replicas + # Create the dynamics objects in serial. Each slot is created at the # lambda value of the first replica that it hosts. for i in range(self._num_slots): @@ -455,6 +458,8 @@ def _create_dynamics( # starting coordinates and periodic space. elif perturbed_system is not None and seed_perturbed: mols = perturbed_system + for replica in self._groups[i]: + self._start_perturbed[replica] = True else: mols = system @@ -853,6 +858,26 @@ def _apply_openmm_state(context, state): # format change. context.setState(state) + def copy_state(self, source, target): + """ + Copy the stored state of one replica to another, so that the target + starts from the source's positions, velocities, box and GCMC water + state when it is next loaded. + + Parameters + ---------- + + source: int + The index of the replica to copy from. + + target: int + The index of the replica to copy to. + """ + self._openmm_states[target] = dict(self._openmm_states[source]) + if self._gcmc_states[source] is not None: + self._gcmc_states[target] = self._gcmc_states[source].copy() + self._state_moved[target] = True + def save_gcmc_state(self, slot, replica): """ Save the current GCMC water state of a slot as that of a replica. @@ -1261,6 +1286,13 @@ def groups(self): """ return self._groups + @property + def start_perturbed(self): + """ + Whether each replica starts from the perturbed end state coordinates. + """ + return self._start_perturbed + @property def time(self): """ diff --git a/src/somd2/runner/_repex.py b/src/somd2/runner/_repex.py index c9b855ca..40b017b5 100644 --- a/src/somd2/runner/_repex.py +++ b/src/somd2/runner/_repex.py @@ -199,6 +199,10 @@ def __init__(self, system, config): self._set_num_slots() + # The replica whose state each replica starts from when chaining + # equilibration, or None to start from its own. + self._setup_sources = [None] * self._num_replicas + # The particles of the bond that is broken or made, whose distance is # used to rank the windows for adaptive replica exchange. self._ring_pair = ( @@ -1024,9 +1028,12 @@ def _prepare_replicas( """ from itertools import repeat + if not self._is_restart and (self._config.minimise or self._is_equilibration): + batches = self._plan_setup(replica_devices) + # Minimise at each lambda value. Don't minimise on restart. if self._config.minimise and not self._is_restart: - for batch in self._setup_batches(replica_devices): + for batch in batches: try: for results in dynamics_executor.map(self._minimise_slot, batch): self._report_minimisation(results) @@ -1037,7 +1044,7 @@ def _prepare_replicas( # Equilibrate the system. if self._is_equilibration and not self._is_restart: - for batch in self._setup_batches(replica_devices): + for batch in batches: try: for results in dynamics_executor.map(self._equilibrate_slot, batch): for success, index, e in results: @@ -1657,6 +1664,8 @@ def _minimise(self, index): _logger.info(f"Minimising at {_lam_sym} = {self._lambda_values[index]:.5f}") try: + self._copy_source(index) + # Make the replica resident in its slot. self._dynamics_cache.load_replica(index) @@ -1689,6 +1698,21 @@ def _minimise(self, index): return True, index, None + def _copy_source(self, index): + """ + Start a replica from the state of the replica it is chained from, if + any, when chaining equilibration. + + Parameters + ---------- + + index: int + The index of the replica. + """ + source = self._setup_sources[index] + if source is not None: + self._dynamics_cache.copy_state(source, index) + def _report_minimisation(self, results): """ Log any failed minimisations, raising the first error if they are @@ -1727,6 +1751,11 @@ def _minimise_slot(self, replicas): list of tuple The success, index and exception for each replica. """ + # Chained replicas start equilibration from a neighbour's state, so + # minimising them would be wasted. + if self._is_equilibration: + replicas = [r for r in replicas if self._setup_sources[r] is None] + results = [self._minimise(index) for index in replicas] # There's no need to rebuild if a failed minimisation stops the run. @@ -1895,6 +1924,9 @@ def _equilibrate_slot(self, replicas): list of tuple The success, index and exception for each replica equilibrated. """ + # Copied before the rebuild, which builds from the first replica's state. + self._copy_source(replicas[0]) + # Rebuild the slot's dynamics object for equilibration, starting from # the first replica. if self._is_equilibration_rebuild: @@ -1916,7 +1948,9 @@ def _equilibrate_slot(self, replicas): raise results = [] - for index in replicas: + for i, index in enumerate(replicas): + if i > 0: + self._copy_source(index) results.append(self._equilibrate(index)) if not results[-1][0]: return results @@ -2119,6 +2153,132 @@ def _setup_batches(self, devices): for batch in self._device_batches(firsts, devices): yield [groups[self._dynamics_cache.slot_for(r)] for r in batch] + def _plan_setup(self, devices): + """ + Work out the batches of slots to minimise and equilibrate at once. When + chaining equilibration, also choose the replica that each replica + starts from, and shorten the equilibration of those that have one. + + The first batch is spread across lambda. Each later batch takes the + slots closest to a replica that is already set up. A replica starts + from the closest one that is guaranteed to be set up before it, from + an earlier batch or earlier in its own slot, which started from the + same end state. + + Parameters + ---------- + + devices: list of int + The GPU that propagates each replica. + + Returns + ------- + + list of list of list of int + The batches of slots, each given by the replicas it hosts. + """ + if not self._config.chain_equilibration: + return list(self._setup_batches(devices)) + + cache = self._dynamics_cache + groups = cache.groups + lambdas = self._lambda_values + perturbed = cache.start_perturbed + per_device = self._config.oversubscription_factor + + # Rounded so that equal spacings tie, leaving the slot index to decide. + def gap(a, b): + return round(abs(lambdas[a] - lambdas[b]), 8) + + def distance(replica, others): + return min((gap(replica, o) for o in others), default=float("inf")) + + def same_side(replica, candidates): + return [c for c in candidates if perturbed[c] == perturbed[replica]] + + def nearest(replica, candidates): + return min( + same_side(replica, candidates), + key=lambda c: (gap(replica, c), c), + default=None, + ) + + def device_of(slot): + return devices[groups[slot][0]] + + def chain_key(slot): + first = groups[slot][0] + d = distance(first, same_side(first, done)) + # With nothing set up on its end state, start from the replica + # farthest from those that are, i.e. at the end state itself. + return (d, -distance(first, done) if d == float("inf") else 0.0, slot) + + remaining = list(range(len(groups))) + done = [] + batches = [] + + while remaining: + batch = [] + used = {} + + def eligible(): + return [ + s + for s in remaining + if s not in batch and used.get(device_of(s), 0) < per_device + ] + + while candidates := eligible(): + if not done: + # Farthest point sampling, starting from the first slot. + chosen = [r for s in batch for r in groups[s]] + slot = max( + candidates, + key=lambda s: (distance(groups[s][0], chosen), -s), + ) + else: + slot = min(candidates, key=chain_key) + batch.append(slot) + used[device_of(slot)] = used.get(device_of(slot), 0) + 1 + + for slot in batch: + group = groups[slot] + for i, replica in enumerate(group): + self._setup_sources[replica] = nearest(replica, done + group[:i]) + + for slot in batch: + remaining.remove(slot) + done.extend(groups[slot]) + + batches.append([groups[s] for s in sorted(batch)]) + + scale = self._config.chain_equilibration_scale + for replica, source in enumerate(self._setup_sources): + if source is not None: + self._equilibration_times[replica] = ( + self._equilibration_times[replica] * scale + ) + msg = ( + f"{_lam_sym} = {lambdas[replica]:.5f} starts from " + f"{_lam_sym} = {lambdas[source]:.5f}" + ) + if self._is_equilibration: + msg += f", equilibrating for {self._equilibration_times[replica]}" + _logger.info(msg) + + timestep = self._config.equilibration_timestep + if self._is_equilibration and any( + source is not None and self._equilibration_times[replica] < timestep + for replica, source in enumerate(self._setup_sources) + ): + _logger.warning( + "Chained replicas are equilibrated for less than one " + f"'equilibration_timestep' ({timestep}). Increase " + "'equilibration_time' or 'chain_equilibration_scale'." + ) + + return batches + def _window_samples(self): """ The number of energy samples each window has collected, from its clock. diff --git a/tests/runner/test_repex.py b/tests/runner/test_repex.py index 5d712a46..cf44c276 100644 --- a/tests/runner/test_repex.py +++ b/tests/runner/test_repex.py @@ -266,6 +266,236 @@ def disturb(): assert list(sampler.water) == list(cache._gcmc_states[replica]) +def test_copy_state(): + """ + Validate that a replica whose state is copied from another starts from the + source's configuration and water state, even if it is already resident. + """ + from somd2.runner._dynamics_cache import DynamicsCache + + n = 2 + + cache = object.__new__(DynamicsCache) + cache._lambdas = [0.0, 1.0] + cache._rest2_scale_factors = [1.0] * n + cache._num_replicas = n + cache._update_constraints = True + cache._strided = False + cache._energy_trajectories = [None] * n + cache._ghost_files = [None] * n + cache._state_moved = [False] * n + _fake_slots(cache, n) + + cache._openmm_states = [ + {"positions": np.array([r, 0]), "velocities": np.array([r]), "box": (r, r, r)} + for r in range(n) + ] + cache._gcmc_states = [np.eye(n, dtype=int)[r] for r in range(n)] + + cache.load_replica(1) + cache.copy_state(0, 1) + cache.load_replica(1) + + slot = cache.slot_for(1) + context = cache._dynamics[slot].context() + assert context.positions[0] == 0 + assert context.box == (0, 0, 0) + assert list(cache._gcmc_samplers[slot].water) == [1, 0] + + # The copy is independent of the source. + cache._gcmc_states[0][1] = 1 + assert list(cache._gcmc_states[1]) == [1, 0] + + +def _plan_setup(num_replicas, num_slots, num_gpus, oversubscription, perturbed): + """ + Plan a chained setup for a fake runner, returning the batches and runner. + """ + from types import SimpleNamespace + + import sire as sr + + from somd2.runner._dynamics_cache import DynamicsCache + + cache = object.__new__(DynamicsCache) + cache._num_replicas = num_replicas + cache._num_slots = num_slots + cache._strided = False + cache._build_slot_layout() + cache._slot_devices = [s % num_gpus for s in range(num_slots)] + + lambdas = [round(i / (num_replicas - 1), 5) for i in range(num_replicas)] + + # A slot's replicas start from the end state of its middle replica. + cache._start_perturbed = [None] * num_replicas + for group in cache._groups: + is_perturbed = perturbed and lambdas[group[len(group) // 2]] > 0.5 + for replica in group: + cache._start_perturbed[replica] = is_perturbed + + runner = SimpleNamespace( + _config=SimpleNamespace( + chain_equilibration=True, + chain_equilibration_scale=0.25, + oversubscription_factor=oversubscription, + equilibration_timestep=sr.u("2 fs"), + ), + _dynamics_cache=cache, + _lambda_values=lambdas, + _setup_sources=[None] * num_replicas, + _equilibration_times=[sr.u("10 ps")] * num_replicas, + _is_equilibration=True, + ) + + devices = [cache.device_for(cache.slot_for(r)) for r in range(num_replicas)] + + return RepexRunner._plan_setup(runner, devices), runner + + +@pytest.mark.parametrize("perturbed", [False, True]) +@pytest.mark.parametrize( + "num_replicas, num_slots, num_gpus, oversubscription", + [ + (11, 11, 1, 1), + (11, 11, 2, 1), + (11, 11, 2, 2), + (12, 12, 3, 1), + (11, 4, 2, 1), + (16, 8, 2, 1), + (4, 4, 4, 1), + ], +) +def test_plan_setup(num_replicas, num_slots, num_gpus, oversubscription, perturbed): + """ + Validate that a chained setup runs every slot once within the GPU limits, + and that each replica starts from one on the same end state that is set up + before it, with the equilibration time scaled. + """ + batches, runner = _plan_setup( + num_replicas, num_slots, num_gpus, oversubscription, perturbed + ) + cache = runner._dynamics_cache + sources = runner._setup_sources + + slots = [cache.slot_for(group[0]) for batch in batches for group in batch] + assert sorted(slots) == list(range(num_slots)) + + done = set() + for i, batch in enumerate(batches): + devices = [cache.device_for(cache.slot_for(group[0])) for group in batch] + assert all(devices.count(d) <= oversubscription for d in devices) + + for group in batch: + for j, replica in enumerate(group): + source = sources[replica] + if source is None: + # Only a replica with nothing set up before it on its own + # end state starts from the input system. + assert not any( + cache.start_perturbed[r] == cache.start_perturbed[replica] + for r in done | set(group[:j]) + ) + else: + assert source in done or source in group[:j] + assert ( + cache.start_perturbed[source] + == (cache.start_perturbed[replica]) + ) + + time = runner._equilibration_times[replica].to("ps") + assert time == pytest.approx(10.0 if source is None else 2.5) + + done.update(r for group in batch for r in group) + + +def test_plan_setup_spreads_first_batch(): + """ + Validate that the first batch of a chained setup is spread across lambda, + and that every replica after it starts from an adjacent one. + """ + batches, runner = _plan_setup(11, 11, 2, 1, False) + + assert batches[0] == [[0], [9]] + for replica, source in enumerate(runner._setup_sources): + if replica not in (0, 9): + assert abs(source - replica) == 1 + + +def test_plan_setup_perturbed_starts_at_end_state(): + """ + Validate that, when the replicas seeded from the perturbed end state have + none set up before them, their chain starts at the end state. + """ + batches, runner = _plan_setup(11, 11, 1, 1, True) + sources = runner._setup_sources + + assert sources[10] is None + for replica in range(6, 10): + assert sources[replica] == replica + 1 + + +def test_chain_equilibration_validation(ethane_methanol): + """ + Validate that chained equilibration requires replica exchange and a single + equilibration time. + """ + with pytest.raises(ValueError): + Config(chain_equilibration_scale=0.0) + with pytest.raises(ValueError): + Config(chain_equilibration_scale=1.5) + + with tempfile.TemporaryDirectory() as tmpdir: + config = { + "output_directory": tmpdir, + "platform": "CPU", + "max_threads": 1, + "num_lambda": 3, + "chain_equilibration": True, + } + + with pytest.raises(ValueError, match="replica_exchange"): + RunnerBase(ethane_methanol, Config(**config)) + + config["replica_exchange"] = True + config["overwrite"] = True + config["equilibration_time"] = ["1 ps", "1 ps", "1 ps"] + with pytest.raises(ValueError, match="equilibration_time"): + RunnerBase(ethane_methanol, Config(**config)) + + +@pytest.mark.skipif(not has_cuda, reason="CUDA not available.") +@pytest.mark.parametrize( + "max_contexts, equilibration_time", + [(None, "8fs"), (2, "8fs"), (None, "0fs")], +) +def test_repex_chain_equilibration(ethane_methanol, max_contexts, equilibration_time): + """ + Validate that a replica exchange simulation runs with chained setup. + """ + with tempfile.TemporaryDirectory() as tmpdir: + config = { + "runtime": "12fs", + "restart": False, + "output_directory": tmpdir, + "energy_frequency": "4fs", + "checkpoint_frequency": "4fs", + "frame_frequency": "4fs", + "platform": "cuda", + "max_threads": 1, + "num_lambda": 4, + "replica_exchange": True, + "max_contexts": max_contexts, + "equilibration_time": equilibration_time, + "chain_equilibration": True, + } + + runner = RepexRunner(ethane_methanol, Config(**config)) + runner.run() + + assert (Path(tmpdir) / "repex_matrix.txt").exists() + assert sum(s is not None for s in runner._setup_sources) > 0 + + @pytest.mark.parametrize( "slot_schedule, inverted", [