Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 36 additions & 21 deletions src/somd2/runner/_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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):
Expand All @@ -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):
"""
Expand Down
53 changes: 53 additions & 0 deletions tests/runner/test_runner.py
Original file line number Diff line number Diff line change
@@ -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()