Skip to content

Commit 59e07c6

Browse files
authored
Merge pull request #29 from michellab/refactor/single-context
Run all lambda windows in one Context
2 parents ec2b6dd + 8cdcf20 commit 59e07c6

17 files changed

Lines changed: 594 additions & 37 deletions

‎CHANGELOG.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,15 @@ All notable changes to fes-ml are listed here.
66

77
### Changed
88

9-
- **λ is an OpenMM global parameter** for LJSoftCore (`lambda_sterics`) and ChargeTransfer
10-
(`lambda_charge_transfer`), and for ChargeScaling (`lambda_electrostatics`, via NonbondedForce
11-
parameter offsets) with `modifications_kwargs={"ChargeScaling": {"use_global_parameter": True}}`;
12-
names are suffixed `_<group>` for named groups. A state's Context can move to another λ with
13-
`context.setParameter(...)`; `modification.lambda_parameter` gives the name. Energies unchanged.
9+
- **λ is an OpenMM global parameter** for LJSoftCore (`lambda_sterics`), ChargeScaling
10+
(`lambda_electrostatics`, via NonbondedForce parameter offsets) and ChargeTransfer
11+
(`lambda_charge_transfer`); names are suffixed `_<group>` for named groups. A state's Context can
12+
move to another λ with `context.setParameter(...)`; `modification.lambda_parameter` gives the
13+
name. Energies are unchanged on the Reference platform; on CUDA, OpenMM's PME path for parameter
14+
offsets shifts them by ~4e-4 kJ/mol (double precision). `{"ChargeScaling":
15+
{"use_global_parameter": False}}` scales the charges in place, as before.
16+
- **`shared_context=True`** in `FES.create_alchemical_states` builds one System and Context for
17+
all windows; each window is a set of λ parameter values and keeps its own coordinates.
1418
- **Checkpoints store plain data** (counters, reduced potentials, positions and box in nm, the
1519
arguments that created the states) instead of pickling the `FES` object. Checkpoints written by
1620
earlier versions are still read.

‎docs/guide/running.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,22 @@ np.save("U_kl_6.npy", np.asarray(U_kl))
3030

3131
Every job still creates all the states, because each sample is evaluated in all of them.
3232

33+
## One Context for all windows
34+
35+
With `shared_context=True`, fes-ml builds one System and one OpenMM Context, and each window is a
36+
set of λ global-parameter values:
37+
38+
```python
39+
fes.create_alchemical_states(lambda_schedule=schedule, alchemical_atoms=ligand,
40+
top_file="system.prm7", crd_file="system.rst7", shared_context=True)
41+
```
42+
43+
The states are created once instead of once per window, and use the GPU memory of one Context;
44+
with ML potentials, one copy of the model. Each window still keeps its own coordinates and
45+
velocities: they are saved and restored when the Context switches window. Every λ that changes
46+
between windows must be a global parameter (see [λ schedules](schedules.md#as-openmm-global-parameters)),
47+
and `None` is not allowed in the schedule, since leaving a modification out changes the System.
48+
3349
## Checkpoints and restarts
3450

3551
Every `checkpoint_frequency` iterations, `FES` writes `<output_prefix>.pickle` and the OpenMM state

‎docs/guide/schedules.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,21 @@ The options of each modification are the keyword arguments of its `apply` method
5151

5252
## λ as OpenMM global parameters
5353

54-
`LJSoftCore`, `ChargeTransfer`, `MLInterpolation` and `MLCorrection` keep λ in an OpenMM global
54+
`LJSoftCore`, `ChargeScaling`, `ChargeTransfer`, `MLInterpolation` and `MLCorrection` keep λ in an OpenMM global
5555
parameter, so an existing Context can be moved to another λ with `context.setParameter(...)`:
5656

5757
| Modification | Parameter |
5858
|---|---|
5959
| `LJSoftCore` | `lambda_sterics` |
60-
| `ChargeScaling` | `lambda_electrostatics`, only with `{"ChargeScaling": {"use_global_parameter": True}}` |
60+
| `ChargeScaling` | `lambda_electrostatics` (NonbondedForce parameter offsets) |
6161
| `ChargeTransfer` | `lambda_charge_transfer` |
6262
| `MLInterpolation`, `MLCorrection` | `lambda_interpolate` |
6363

6464
For a named [group](groups.md), the name gets the suffix `_<group>`, for example
65-
`lambda_sterics_ligand`. `ChargeScaling` builds the scaled charges into the System by default: its
66-
parameter-offset form agrees to 1e-8 kJ/mol on the Reference platform, but OpenMM's CUDA platform
67-
gives energies that differ by about 4e-4 kJ/mol for the same charges.
65+
`lambda_sterics_ligand`. `CustomLJ` and `EMLEPotential` build their λ into the System.
66+
67+
`{"ChargeScaling": {"use_global_parameter": False}}` writes the scaled charges into the System
68+
instead. The two forms agree exactly on the Reference platform. On CUDA, OpenMM's PME takes a
69+
different code path when parameter offsets exist, which shifts energies by about 4e-4 kJ/mol
70+
(double precision, 5,000 atoms); CUDA itself differs from the Reference platform by 1e-2 to
71+
6e-2 kJ/mol on the same system.

‎src/fes_ml/alchemical/alchemical_state.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Module that defines the AlchemicalState dataclass."""
22

33
from dataclasses import dataclass, field
4-
from typing import Dict, Optional, Union
4+
from typing import Any, Callable, Dict, List, Optional, Union
55

66
import openmm as _mm
77
import openmm.app as _app
@@ -29,6 +29,13 @@ class AlchemicalState:
2929
applied to the system to the λ value.
3030
work_dir : str, optional
3131
Directory with the files the creation strategy wrote for this state (None if removed).
32+
parameters : dict, optional
33+
Global-parameter values that define this window when it shares its Context with other
34+
windows (``FES.create_alchemical_states(..., shared_context=True)``).
35+
shared : fes_ml.sampling.SharedContext, optional
36+
The shared Context, or None if the state has a Context of its own.
37+
levers : dict, optional
38+
Callbacks that change lambdas held outside OpenMM (EMLE's calculator), by parameter name.
3239
"""
3340

3441
# OpenMM objects
@@ -44,6 +51,16 @@ class AlchemicalState:
4451
# Files written by the creation strategy
4552
work_dir: Optional[str] = field(repr=False, default=None)
4653

54+
# Windows that share one Context (R3)
55+
parameters: Optional[Dict[str, float]] = field(repr=False, default=None)
56+
shared: Optional[Any] = field(repr=False, default=None)
57+
levers: Optional[Dict[str, List[Callable[[float], None]]]] = field(repr=False, default=None)
58+
59+
def activate(self) -> None:
60+
"""Make the Context simulate this window (a no-op unless the Context is shared)."""
61+
if self.shared is not None:
62+
self.shared.activate(self)
63+
4764
def check_integrity(self):
4865
"""Check that the state holds OpenMM objects and a modifications dict; raise ``TypeError`` if not."""
4966
if not isinstance(self.system, _mm.System):

‎src/fes_ml/alchemical/alchemist.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,10 @@ def remove_modification_from_graph(self, modification: str) -> None:
134134
"""
135135
self._graph.remove_node(ModificationName(modification))
136136

137+
def modifications(self) -> List[BaseModification]:
138+
"""The modification instances of the graph, in application order."""
139+
return [self._graph.nodes[name]["modification"] for name in self.application_order()]
140+
137141
def application_order(self) -> List[str]:
138142
"""The order in which :meth:`apply_modifications` applies the modifications."""
139143
nodes = self._graph.nodes

‎src/fes_ml/alchemical/modifications/base_modification.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from abc import ABC, abstractmethod
44
from dataclasses import dataclass
55
from enum import IntEnum
6-
from typing import Dict, List, Optional, Sequence, Tuple
6+
from typing import Callable, Dict, List, Optional, Sequence, Tuple
77

88
import openmm as _mm
99

@@ -123,6 +123,26 @@ class BaseModification(ABC):
123123
inputs: Tuple[str, ...] = ()
124124

125125
LAMBDA_PARAMETER: Optional[str] = None # base name of the global parameter holding lambda (R3)
126+
# Modification (in the same group) whose lambda this one uses when it has none of its own
127+
LAMBDA_FROM: Optional[str] = None
128+
# Base name of a lambda held outside OpenMM (e.g. in a Python calculator) that a callback can change
129+
LAMBDA_LEVER: Optional[str] = None
130+
131+
@classmethod
132+
def lambda_lever_for(cls, group: str) -> Optional[str]:
133+
"""Name of the external lambda lever of ``group``, or None."""
134+
if cls.LAMBDA_LEVER is None:
135+
return None
136+
return cls.LAMBDA_LEVER if group in ("", "default") else f"{cls.LAMBDA_LEVER}_{group}"
137+
138+
@property
139+
def lambda_levers(self) -> Dict[str, Callable[[float], None]]:
140+
"""
141+
Callbacks that change a lambda held outside OpenMM, by name, set by ``apply`` (R3).
142+
143+
A shared Context calls them together with ``Context.setParameter`` for the same name.
144+
"""
145+
return getattr(self, "_lambda_levers", {})
126146

127147
@classmethod
128148
def lambda_parameter_for(cls, group: str) -> Optional[str]:

‎src/fes_ml/alchemical/modifications/charge_scaling.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,15 @@ def __init__(self, *args, **kwargs) -> None:
4343

4444
@property
4545
def lambda_parameter(self) -> Optional[str]:
46-
"""``lambda_electrostatics[_<group>]`` once applied with ``use_global_parameter=True``, else None."""
46+
"""``lambda_electrostatics[_<group>]`` once applied (None if applied with ``use_global_parameter=False``)."""
4747
return super().lambda_parameter if self._uses_parameter else None
4848

4949
def apply(
5050
self,
5151
system: _mm.System,
5252
alchemical_atoms: List[int],
5353
lambda_value: float,
54-
use_global_parameter: bool = False,
54+
use_global_parameter: bool = True,
5555
*args,
5656
**kwargs,
5757
) -> _mm.System:
@@ -68,11 +68,13 @@ def apply(
6868
The value of the alchemical state parameter.
6969
alchemical_atoms : list of int
7070
The indices of the alchemical atoms in the System.
71-
use_global_parameter : bool, optional
71+
use_global_parameter : bool, optional, default=True
7272
Keep lambda in the global parameter ``lambda_electrostatics[_<group>]`` (NonbondedForce
73-
particle-parameter offsets), so that ``Context.setParameter`` changes it (R3). Off by
74-
default: the energies agree to 1e-8 kJ/mol on the Reference platform, but OpenMM's CUDA
75-
offset path differs from scaled charges by ~4e-4 kJ/mol on a 2,500-atom PME box.
73+
particle-parameter offsets), so that ``Context.setParameter`` changes it (R3). With False
74+
the scaled charges are written into the System. The two agree exactly on the Reference
75+
platform; on CUDA, OpenMM's PME takes a different code path when offsets exist, which
76+
shifts energies by ~4e-4 kJ/mol (double) on a 5,000-atom box, 25-100x less than CUDA's
77+
own difference from the Reference platform.
7678
7779
Returns
7880
-------

‎src/fes_ml/alchemical/modifications/emle_potential.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ class EMLEPotentialModification(BaseModification):
4242
"""Modification to add the EMLE potential to the OpenMM System."""
4343

4444
NAME = "EMLEPotential"
45+
LAMBDA_FROM = "MLInterpolation" # B2: without its own lambda, EMLE takes its group's MLInterpolation lambda
46+
LAMBDA_LEVER = "lambda_emle_interpolate" # EMLECalculator.set_lambda_interpolate
4547
phase = Phase.POTENTIALS
4648
inputs = ("mols", "parm7", "mm_charges", "openmm_charges", "top_file", "crd_file")
4749

@@ -113,6 +115,7 @@ def apply(
113115
_sr = require("EMLEPotential", "sire")
114116
_EMLECalculator = require("EMLEPotential", "emle.calculator").EMLECalculator
115117

118+
inherited = lambda_value is None
116119
if lambda_value is None:
117120
# This can only occur when MLInterpolation is also being used: take the lambda value
118121
# of the MLInterpolation of the same group to create the EMLECalculator.
@@ -157,6 +160,14 @@ def apply(
157160
**kwargs,
158161
)
159162
_EMLE_CALCULATORS.append(calculator)
163+
# The calculator reads lambda on every call, so a shared Context can change it (R3)
164+
if inherited:
165+
from .ml_interpolation import MLInterpolationModification
166+
167+
lever = MLInterpolationModification.lambda_parameter_for(self.alchemical_group)
168+
else:
169+
lever = self.lambda_lever_for(self.alchemical_group)
170+
self._lambda_levers = {str(lever): calculator.set_lambda_interpolate}
160171

161172
# Create a perturbable molecular system and EMLEEngine. (First molecule is QM region.)
162173
mols, engine = _sr.qm.emle(

‎src/fes_ml/alchemical/strategies/base_strategy.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ def _run_alchemist(
7272
modifications_kwargs: Optional[Dict[str, Dict[str, Any]]] = None,
7373
*args,
7474
**kwargs,
75-
) -> None:
75+
) -> Alchemist:
7676
"""
77-
Run the alchemist to apply the alchemical modifications to the system.
77+
Run the alchemist to apply the alchemical modifications to the system; returns the Alchemist.
7878
7979
Parameters
8080
----------
@@ -113,6 +113,7 @@ def _run_alchemist(
113113
*args,
114114
**kwargs,
115115
)
116+
return alchemist
116117

117118
@staticmethod
118119
def _report_dict(
@@ -171,7 +172,11 @@ def _finish_state(
171172
modifications_kwargs = deepcopy(modifications_kwargs) or {}
172173
planned = self._planned_modifications(lambda_schedule, base.alchemical_atoms, modifications_kwargs)
173174
self._provide_inputs(planned, modifications_kwargs, base.inputs, groups, all_atoms)
174-
self._run_alchemist(base.system, base.alchemical_atoms, lambda_schedule, modifications_kwargs=modifications_kwargs)
175+
alchemist = self._run_alchemist(base.system, base.alchemical_atoms, lambda_schedule, modifications_kwargs=modifications_kwargs)
176+
levers: Dict[str, List[Any]] = {}
177+
for modification in alchemist.modifications():
178+
for name, lever in modification.lambda_levers.items():
179+
levers.setdefault(name, []).append(lever)
175180

176181
integrator = base.integrator if integrator is None else integrator
177182
if not isinstance(integrator, _mm.Integrator):
@@ -194,6 +199,7 @@ def _finish_state(
194199
simulation=simulation,
195200
topology=base.topology,
196201
modifications=lambda_schedule,
202+
levers=levers or None,
197203
)
198204
if base.after_state is not None:
199205
base.after_state(state)

0 commit comments

Comments
 (0)