From f1ed361774abd6ac23b3ca3159990b721103f0f6 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 10:13:17 +0000 Subject: [PATCH] Backport fix from PR #285. [ci skip] --- src/somd2/runner/_runner.py | 57 +++++++++++++++++++++++-------------- tests/runner/test_runner.py | 53 ++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 21 deletions(-) create mode 100644 tests/runner/test_runner.py diff --git a/src/somd2/runner/_runner.py b/src/somd2/runner/_runner.py index b9c1e06e..3846b61f 100644 --- a/src/somd2/runner/_runner.py +++ b/src/somd2/runner/_runner.py @@ -254,17 +254,17 @@ def run(self): # If the number of lambda windows is greater than the number of threads, then # the number of threads per worker is set to 1. if self._config.num_lambda > self._config.max_threads: - self.max_workers = self._config.max_threads + self._max_workers = self._config.max_threads threads_per_worker = 1 # Otherwise, divide the number of threads equally between workers. else: - self.max_workers = self._config.num_lambda + self._max_workers = self._config.num_lambda threads_per_worker = self._config.max_threads // self._config.num_lambda self._config._extra_args["threads"] = threads_per_worker # GPU platform. elif self._is_gpu: - self.max_workers = len(self._gpu_pool) + self._max_workers = len(self._gpu_pool) # All other platforms. else: @@ -275,9 +275,11 @@ def run(self): import concurrent.futures as _futures import multiprocessing as _mp - success = True + failed = [] + interrupted = False + total_time = 0 with _futures.ProcessPoolExecutor( - max_workers=self.max_workers, mp_context=_mp.get_context("spawn") + max_workers=self._max_workers, mp_context=_mp.get_context("spawn") ) as executor: jobs = {} for index, lambda_value in enumerate(self._lambda_values): @@ -292,34 +294,47 @@ def run(self): f"Exception raised for {_lam_sym} = {lambda_value}: {e}" ) success = False + if success: + total_time += time.to("ns") + else: + failed.append(lambda_value) # Kill all current and future jobs if keyboard interrupt. except KeyboardInterrupt: _logger.error("Cancelling job...") for pid in executor._processes: executor._processes[pid].terminate() - success = False + interrupted = True - if success: - # Record the end time. - end = _timer() + if interrupted: + raise RuntimeError("Simulation was cancelled.") - # Work how many fractional days the simulation took. - days = (end - start) / 86400 + if failed: + failed = ", ".join(str(lam) for lam in sorted(failed)) + raise RuntimeError( + f"Failed for {_lam_sym} = {failed}. These windows can be re-run " + "using '--lambda-values' with '--restart'." + ) - # Calculate the speed in nanoseconds per day. - speed = time.to("ns") / days + # Record the end time. + end = _timer() - # Log the speed. - _logger.info(f"Overall performance: {speed:.2f} ns day-1") + # Work how many fractional days the simulation took. + days = (end - start) / 86400 - # Log the run time in minutes. - _logger.success( - f"Simulation finished. Run time: {(end - start) / 60:.2f} minutes" - ) + # Calculate the speed in nanoseconds per day, summed over all windows. + speed = total_time / days + + # Log the speed. + _logger.info(f"Overall performance: {speed:.2f} ns day-1") + + # Log the run time in minutes. + _logger.success( + f"Simulation finished. Run time: {(end - start) / 60:.2f} minutes" + ) - # Cleanup backup files. - self._cleanup() + # Cleanup backup files. + self._cleanup() def _check_restart(self): """ diff --git a/tests/runner/test_runner.py b/tests/runner/test_runner.py new file mode 100644 index 00000000..7653ebb8 --- /dev/null +++ b/tests/runner/test_runner.py @@ -0,0 +1,53 @@ +from pathlib import Path + +import pytest +import tempfile + +from somd2.runner import Runner +from somd2.config import Config + + +def test_failed_window(ethane_methanol, monkeypatch): + """ + Validate that a failed window doesn't stop the others from running, and + that the run raises an error naming the failed window. + """ + import concurrent.futures + + # Run windows in threads so that the patched _run is used. + monkeypatch.setattr( + concurrent.futures, + "ProcessPoolExecutor", + lambda max_workers, mp_context: concurrent.futures.ThreadPoolExecutor( + max_workers=max_workers + ), + ) + + run = Runner._run + + def failing_run(self, system, index, **kwargs): + if index == 0: + raise RuntimeError("Forced failure") + return run(self, system, index, **kwargs) + + monkeypatch.setattr(Runner, "_run", failing_run) + + with tempfile.TemporaryDirectory() as tmpdir: + config = { + "runtime": "4fs", + "restart": False, + "output_directory": tmpdir, + "energy_frequency": "4fs", + "checkpoint_frequency": "4fs", + "frame_frequency": "4fs", + "platform": "CPU", + "max_threads": 1, + "num_lambda": 2, + } + + runner = Runner(ethane_methanol, Config(**config)) + with pytest.raises(RuntimeError, match="Failed for λ = 0.0"): + runner.run() + + assert not (Path(tmpdir) / "energy_traj_0.00000.parquet").exists() + assert (Path(tmpdir) / "energy_traj_1.00000.parquet").exists()