Skip to content

Commit 8cdcf20

Browse files
committed
shared_context: EMLE follows the windows through its calculator's lambda
Modifications may hold lambda outside OpenMM and expose callbacks (lambda_levers, LAMBDA_LEVER); SharedContext calls them with setParameter. EMLE registers EMLECalculator.set_lambda_interpolate under its group's lambda_interpolate (or lambda_emle_interpolate with its own row); without a lever (Torch backend) shared_context still refuses. Integration test: shared vs one Context per window agree within build noise (CUDA mixed, float32 ANI/EMLE).
1 parent 3d20e91 commit 8cdcf20

9 files changed

Lines changed: 188 additions & 20 deletions

File tree

‎src/fes_ml/alchemical/alchemical_state.py‎

Lines changed: 4 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 Any, 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
@@ -34,6 +34,8 @@ class AlchemicalState:
3434
windows (``FES.create_alchemical_states(..., shared_context=True)``).
3535
shared : fes_ml.sampling.SharedContext, optional
3636
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.
3739
"""
3840

3941
# OpenMM objects
@@ -52,6 +54,7 @@ class AlchemicalState:
5254
# Windows that share one Context (R3)
5355
parameters: Optional[Dict[str, float]] = field(repr=False, default=None)
5456
shared: Optional[Any] = field(repr=False, default=None)
57+
levers: Optional[Dict[str, List[Callable[[float], None]]]] = field(repr=False, default=None)
5558

5659
def activate(self) -> None:
5760
"""Make the Context simulate this window (a no-op unless the Context is shared)."""

‎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: 19 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

@@ -125,6 +125,24 @@ class BaseModification(ABC):
125125
LAMBDA_PARAMETER: Optional[str] = None # base name of the global parameter holding lambda (R3)
126126
# Modification (in the same group) whose lambda this one uses when it has none of its own
127127
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", {})
128146

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

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +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; the lambda is built into the EMLE calculator
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
4647
phase = Phase.POTENTIALS
4748
inputs = ("mols", "parm7", "mm_charges", "openmm_charges", "top_file", "crd_file")
4849

@@ -114,6 +115,7 @@ def apply(
114115
_sr = require("EMLEPotential", "sire")
115116
_EMLECalculator = require("EMLEPotential", "emle.calculator").EMLECalculator
116117

118+
inherited = lambda_value is None
117119
if lambda_value is None:
118120
# This can only occur when MLInterpolation is also being used: take the lambda value
119121
# of the MLInterpolation of the same group to create the EMLECalculator.
@@ -158,6 +160,14 @@ def apply(
158160
**kwargs,
159161
)
160162
_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}
161171

162172
# Create a perturbable molecular system and EMLEEngine. (First molecule is QM region.)
163173
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)

‎src/fes_ml/fes.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -224,9 +224,11 @@ def _create_shared_states(
224224
parameter_of: Dict[str, Optional[str]] = {}
225225
for key in lambda_schedule:
226226
name = ModificationName(key)
227-
parameter_of[key] = type(alchemist._create(name)).lambda_parameter_for(name.group)
227+
cls = type(alchemist._create(name))
228+
parameter_of[key] = cls.lambda_parameter_for(name.group) or cls.lambda_lever_for(name.group)
228229
built_in = [key for key, parameter in parameter_of.items() if parameter is None and len(set(lambda_schedule[key])) > 1]
229230
# Modifications added as dependencies may take their lambda from another one (EMLE from MLInterpolation)
231+
needs_lever: List[Tuple[str, str]] = []
230232
groups = alchemical_atoms if isinstance(alchemical_atoms, dict) else None
231233
alchemist.create_alchemical_graph(windows[0], modifications_kwargs=_deepcopy(modifications_kwargs), alchemical_groups=groups)
232234
for node in alchemist.application_order():
@@ -235,8 +237,12 @@ def _create_shared_states(
235237
if cls.LAMBDA_PARAMETER is not None or cls.LAMBDA_FROM is None or node in lambda_schedule or name.base in lambda_schedule:
236238
continue
237239
source = [key for key in lambda_schedule if ModificationName(key) == ModificationName(cls.LAMBDA_FROM, name.group)]
238-
if any(len(set(lambda_schedule[key])) > 1 for key in source):
240+
if not any(len(set(lambda_schedule[key])) > 1 for key in source):
241+
continue
242+
if cls.LAMBDA_LEVER is None:
239243
built_in.append(f"{node} (λ from {source[0]})")
244+
else:
245+
needs_lever.append((node, str(parameter_of[source[0]])))
240246
if built_in:
241247
raise ValueError(f"shared_context: {built_in} build λ into the System, so their λ must be the same in every window.")
242248

@@ -266,12 +272,16 @@ def _create_shared_states(
266272
modifications_kwargs=kwargs_by_name,
267273
**kwargs,
268274
)
275+
levers = first.levers or {}
269276
known = set(first.context.getParameters().keys())
270-
missing = sorted({p for values in parameters for p in values} - known)
277+
missing = sorted({p for values in parameters for p in values} - known - set(levers))
271278
if missing:
272279
raise ValueError(f"shared_context: the System has no global parameters {missing}.")
280+
without = [node for node, parameter in needs_lever if parameter not in levers]
281+
if without:
282+
raise ValueError(f"shared_context: {without} cannot change λ after the System is built (no lever, e.g. EMLE's Torch backend).")
273283

274-
shared = SharedContext(first.context)
284+
shared = SharedContext(first.context, levers)
275285
states = []
276286
for window, values in zip(windows, parameters):
277287
modifications = dict(first.modifications or {})
@@ -288,6 +298,7 @@ def _create_shared_states(
288298
work_dir=first.work_dir,
289299
parameters=values,
290300
shared=shared,
301+
levers=first.levers,
291302
)
292303
)
293304
shared.activate(states[0])

‎src/fes_ml/sampling.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Energy evaluation shared by the samplers, and λ windows that share one OpenMM Context (R3, R4)."""
22

3-
from typing import Any, Dict, List, Optional, Sequence
3+
from typing import Any, Callable, Dict, List, Optional, Sequence
44

55
import openmm as _mm
66
import openmm.unit as _unit
@@ -17,15 +17,20 @@ class SharedContext:
1717
each window keeps its own trajectory, as it would with its own Context.
1818
"""
1919

20-
def __init__(self, context: _mm.Context) -> None:
20+
def __init__(self, context: _mm.Context, levers: Optional[Dict[str, List[Callable[[float], None]]]] = None) -> None:
2121
self.context = context
22+
self.levers = levers or {}
2223
self.active: Optional[AlchemicalState] = None
2324
self._saved: Dict[int, _mm.State] = {}
25+
self._known = set(context.getParameters().keys())
2426

2527
def set_parameters(self, parameters: Dict[str, float]) -> None:
26-
"""Set global parameters, without touching coordinates."""
28+
"""Set global parameters, and call the levers of lambdas held outside OpenMM, without touching coordinates."""
2729
for name, value in parameters.items():
28-
self.context.setParameter(name, value)
30+
if name in self._known:
31+
self.context.setParameter(name, value)
32+
for lever in self.levers.get(name, ()):
33+
lever(value)
2934

3035
def activate(self, state: AlchemicalState) -> None:
3136
"""Make ``state`` the window the Context simulates."""

‎tests/integration/test_sire_emle.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,42 @@ def test_emle_without_lambda_and_without_interpolation_raises(in_tmp_path, benze
4949
alchemical_state(top, crd, ligand, {"LJSoftCore": [1.0]}, dynamics_pme, modifications_kwargs=_emle_kwargs())
5050
finally:
5151
LJSoftCoreModification.remove_post_dependency("EMLEPotential")
52+
53+
54+
def test_shared_context_emle_matches_one_context_per_window(in_tmp_path, benzene_water_files, dynamics_pme, emle_after_interpolation):
55+
"""R3: EMLE's λ lives in its Python calculator; a shared Context changes it through set_lambda_interpolate."""
56+
from copy import deepcopy
57+
58+
import openmm.unit as unit
59+
60+
from fes_ml import FES
61+
62+
top, crd, ligand = benzene_water_files
63+
lambdas = [0.0, 0.4, 1.0]
64+
options = dict(top_file=top, crd_file=crd, alchemical_atoms=ligand, minimise_iterations=0, modifications_kwargs=_emle_kwargs())
65+
shared = FES(restart=False).create_alchemical_states(
66+
lambda_schedule={"MLInterpolation": lambdas}, dynamics_kwargs=deepcopy(dynamics_pme), shared_context=True, **options
67+
)
68+
positions = shared[0].context.getState(getPositions=True).getPositions()
69+
70+
def energy(state):
71+
state.context.setPositions(positions)
72+
return state.context.getState(getEnergy=True).getPotentialEnergy().value_in_unit(unit.kilojoule_per_mole)
73+
74+
# Two builds of the same window differ by ~1e-2 kJ/mol (Sire's mixed-precision CUDA, float32 ANI and EMLE)
75+
tolerance = 0.05 # kJ/mol
76+
expected = []
77+
for lam, state in zip(lambdas, shared):
78+
separate = FES(restart=False).create_alchemical_states(
79+
lambda_schedule={"MLInterpolation": [lam]}, dynamics_kwargs=deepcopy(dynamics_pme), **options
80+
)[0]
81+
expected.append(energy(separate))
82+
state.activate()
83+
assert energy(state) == pytest.approx(expected[-1], abs=tolerance), lam
84+
assert max(expected) - min(expected) > 100 * tolerance # the windows differ far more than the tolerance
85+
# Switching back gives the first window's energy again (nothing cached at the old λ)
86+
shared[0].activate()
87+
first = FES(restart=False).create_alchemical_states(
88+
lambda_schedule={"MLInterpolation": [lambdas[0]]}, dynamics_kwargs=deepcopy(dynamics_pme), **options
89+
)[0]
90+
assert energy(shared[0]) == pytest.approx(energy(first), abs=tolerance)

‎tests/unit/test_shared_context.py‎

Lines changed: 78 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,83 @@ def test_lambda_built_into_the_system_must_not_change(tmp_path, toy_factory, mon
121121
assert len(_create(tmp_path, {"LJSoftCore": [1.0, 0.5], "BuiltInLambda": [1.0, 1.0]}, shared_context=True).alchemical_states) == 2
122122

123123

124-
def test_inherited_lambda_built_into_the_system_is_rejected(tmp_path, toy_factory, monkeypatch):
125-
"""EMLE added as a dependency takes MLInterpolation's lambda into its calculator: it cannot change by parameter."""
126-
from fes_ml.alchemical.modifications.ml_interpolation import MLInterpolationModification
124+
class _Source(BaseModification):
125+
"""λ as an OpenMM parameter; adds _Follower, which inherits its λ (like MLInterpolation and EMLE)."""
127126

128-
monkeypatch.setattr(MLInterpolationModification, "post_dependencies", [*MLInterpolationModification.post_dependencies, "EMLEPotential"])
127+
NAME = "FakeSource"
128+
LAMBDA_PARAMETER = "lambda_fake"
129+
requires_lambda = True
130+
post_dependencies = ["FakeFollower"]
131+
132+
def apply(self, system, alchemical_atoms, lambda_value, *args, **kwargs):
133+
force = mm.CustomExternalForce("0*lambda_fake*x")
134+
force.addGlobalParameter("lambda_fake", lambda_value)
135+
force.addParticle(0, [])
136+
system.addForce(force)
137+
return system
138+
139+
140+
class _Follower(BaseModification):
141+
"""Holds λ outside OpenMM, like EMLE's calculator; with a lever unless WITH_LEVER is False."""
142+
143+
NAME = "FakeFollower"
144+
LAMBDA_FROM = "FakeSource"
145+
LAMBDA_LEVER = "lambda_follower"
146+
WITH_LEVER = True
147+
seen: list = []
148+
149+
def apply(self, system, alchemical_atoms, lambda_value=None, *args, **kwargs):
150+
if self.WITH_LEVER:
151+
self._lambda_levers = {"lambda_fake": _Follower.seen.append}
152+
return system
153+
154+
155+
@pytest.fixture
156+
def fake_pair(monkeypatch):
157+
for name in ("FakeSource", "FakeFollower"):
158+
monkeypatch.setitem(Alchemist._modification_factories, name, None)
159+
Alchemist.register_modification("FakeSource", _Source)
160+
Alchemist.register_modification("FakeFollower", _Follower)
161+
monkeypatch.setattr(_Follower, "seen", [])
162+
163+
164+
def test_inherited_lambda_outside_openmm_follows_the_windows(tmp_path, monkeypatch, reference_platform, fake_pair):
165+
"""A modification holding its λ outside OpenMM gets each window's value through its lever (EMLE)."""
166+
167+
def create(strategy_name, alchemical_atoms, lambda_schedule, modifications_kwargs=None, **kwargs):
168+
system = oracle.copy_system(_toy_system(periodic=False))
169+
alchemist = Alchemist()
170+
alchemist.create_alchemical_graph(lambda_schedule)
171+
alchemist.apply_modifications(system, LIGAND, modifications_kwargs or {})
172+
state = toy_alchemical_state(system, reference_platform, _positions(), modifications=dict(lambda_schedule))
173+
levers: dict = {}
174+
for modification in alchemist.modifications():
175+
for name, lever in modification.lambda_levers.items():
176+
levers.setdefault(name, []).append(lever)
177+
state.levers = levers or None
178+
return state
179+
180+
monkeypatch.setattr(fes_module.alchemical_factory, "create_alchemical_state", create)
181+
states = _create(tmp_path, {"FakeSource": [0.0, 0.5, 1.0]}, shared_context=True).alchemical_states
182+
_Follower.seen.clear()
183+
184+
states[2].activate()
185+
assert _Follower.seen == [1.0] and states[2].context.getParameter("lambda_fake") == 1.0
186+
_Follower.seen.clear()
187+
reduced_potentials(states, _positions(), [mm.Vec3(3, 0, 0), mm.Vec3(0, 3, 0), mm.Vec3(0, 0, 3)] * unit.nanometer, KT)
188+
assert _Follower.seen == [0.0, 0.5, 1.0, 1.0] # every window, then back to the active one
189+
190+
191+
def test_inherited_lambda_without_a_lever_is_rejected(tmp_path, toy_factory, monkeypatch, fake_pair):
192+
"""EMLE's Torch backend keeps λ fixed: it cannot follow the windows."""
193+
monkeypatch.setattr(_Follower, "WITH_LEVER", False)
194+
195+
with pytest.raises(ValueError, match=r"FakeFollower:default.*no lever"):
196+
_create(tmp_path, {"FakeSource": [0.0, 1.0]}, shared_context=True)
197+
198+
199+
def test_inherited_lambda_built_in_without_lever_support_is_rejected(tmp_path, toy_factory, monkeypatch, fake_pair):
200+
monkeypatch.setattr(_Follower, "LAMBDA_LEVER", None)
129201

130-
with pytest.raises(ValueError, match=r"EMLEPotential:default \(λ from MLInterpolation\)"):
131-
_create(tmp_path, {"MLInterpolation": [0.0, 1.0]}, shared_context=True)
202+
with pytest.raises(ValueError, match=r"FakeFollower:default \(λ from FakeSource\)"):
203+
_create(tmp_path, {"FakeSource": [0.0, 1.0]}, shared_context=True)

0 commit comments

Comments
 (0)