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
11 changes: 6 additions & 5 deletions doc/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,10 @@ organisation on `GitHub <https://github.com/openbiosim/sire>`__.

* Added a ``gpu_resident`` option to ``sire.qm.create_engine`` and ``sire.qm.emle`` that
evaluates a PyTorch ML/MM callback on GPU-resident data on the OpenMM CUDA platform,
avoiding copies between the GPU and host. All MM atoms are passed to the callback, so
that the model applies its own cutoff, e.g. with ``emle.models.preprocess``, and
link atoms use the same charge-shift scheme as the host implementation. The
avoiding copies between the GPU and host. A fixed number of the MM atoms nearest the
QM region are passed to the callback, set by the ``max_mm_atoms`` option, which by
default is sized on the first call and increased as needed, and link atoms use the
same charge-shift scheme as the host implementation. The
``cuda_graph`` option captures the callback in a CUDA graph. On Linux, the CUDA code is
built as a separate library, which needs only the CUDA headers, and is only loaded when
used. ``sire.qm.emle`` restricts ``ANI2xEMLE`` models to the elements in the QM region,
Expand Down Expand Up @@ -331,8 +332,8 @@ organisation on `GitHub <https://github.com/openbiosim/sire>`__.
to the callback are subtracted, with excluded and scaled pairs as in the MM force.
The embedding energy only replaces short-range interactions, so truncating it at the
cutoff no longer causes artefacts for charged QM regions. MM atoms are selected and
switched individually rather than by residue. GPU-resident callbacks are passed all
MM atoms, re-imaged about the QM region, with switched charges that are zero beyond
switched individually rather than by residue. GPU-resident callbacks are passed the
nearest MM atoms, re-imaged about the QM region, with switched charges that are zero beyond
the cutoff, and may return the gradient with respect to the MM charges. The ``embed``
lever of an ``interpolate="end_states"`` engine now scales the embedding energy less
the Coulomb energy it replaces, rather than the MM charges of the QM atoms, and the
Expand Down
9 changes: 6 additions & 3 deletions doc/source/tutorial/part08/01_intro.rst
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,12 @@ callback then has the following signature:

The arguments and return values have the same meaning and units as above,
but are ``torch`` tensors on the GPU, and the gradient with respect to the MM
charges is again optional. Unlike the default callback, *all* MM atoms are
passed, so that the shapes don't change between calls. They are re-imaged
around the QM region, and the charges of those beyond the cutoff are zero.
charges is again optional. Unlike the default callback, a fixed number of the
MM atoms nearest the QM region are passed, so that the shapes don't change
between calls. They are re-imaged around the QM region, and the charges of
those beyond the cutoff are zero. The number is set by the ``max_mm_atoms``
option. By default, it is set from the number within the cutoff after the
first call, with some headroom, and increased as needed.
Link atoms and their virtual charges are appended
to the QM and MM tensors, and their forces are mapped back onto the real atoms
automatically. Passing ``cuda_graph=True`` captures the callback in a CUDA
Expand Down
15 changes: 9 additions & 6 deletions doc/source/tutorial/part08/02_emle.rst
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,15 @@ The engine can then be used with the ``CUDA`` platform:
... platform="cuda",
... )

All MM atoms are passed to the model, re-imaged around the QM region, with
their charges scaled by the switching function and zero beyond the cutoff,
using the ``cutoff`` and ``switch_width`` passed to ``sr.qm.emle``. The model
therefore doesn't need to be created with a cutoff, and the
``neighbour_list_frequency`` option isn't used. Link atoms are supported,
using the same charge-shift scheme as the default engines.
A fixed number of the MM atoms nearest the QM region are passed to the model,
re-imaged around the QM region, with their charges scaled by the switching
function and zero beyond the cutoff, using the ``cutoff`` and ``switch_width``
passed to ``sr.qm.emle``. The model therefore doesn't need to be created with a
cutoff, and the ``neighbour_list_frequency`` option isn't used. The number of
MM atoms is set automatically after the first step and increased as needed, or
can be given with ``max_mm_atoms``. When it is increased, the CUDA graph is
captured again. Link atoms are supported, using the same charge-shift scheme as
the default engines.

Setting ``cuda_graph=True`` captures the model in a
`CUDA graph <https://developer.nvidia.com/blog/cuda-graphs/>`_ after a few
Expand Down
39 changes: 30 additions & 9 deletions src/sire/qm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def create_engine(
switch_width=0.2,
gpu_resident=False,
cuda_graph=False,
max_mm_atoms=None,
interpolate="mm_ml",
map=None,
_engine_class=None,
Expand Down Expand Up @@ -106,13 +107,14 @@ def create_engine(
callback is called as callback(numbers, charges_mm, xyz_qm, xyz_mm, cell)
with torch tensors on the GPU: the atomic numbers, the MM charges, the
QM and MM positions in Angstrom and the cell vectors in Angstrom, or
None for non-periodic systems. All MM atoms are passed (none with
mechanical embedding), so that the shapes don't change, re-imaged about
the centre of the QM region, with their charges scaled by the switching
function and zero beyond the cutoff. 'neighbour_list_frequency' isn't
used. It should return the energy in kJ/mol, the QM and MM forces in
kJ/mol/nm and, optionally, the gradient of the energy with respect to
the MM charges in kJ/mol/e, as torch tensors.
None for non-periodic systems. A fixed number of the MM atoms nearest
the QM region are passed (none with mechanical embedding), set by
'max_mm_atoms', re-imaged about the centre of the QM region, with their
charges scaled by the switching function and zero beyond the cutoff.
'neighbour_list_frequency' isn't used. It should return the energy in
kJ/mol, the QM and MM forces in kJ/mol/nm and, optionally, the
gradient of the energy with respect to the MM charges in kJ/mol/e, as
torch tensors.

On its own this gives little speed-up, since the model usually
dominates. The gain comes with a capturable model and 'cuda_graph',
Expand All @@ -124,6 +126,14 @@ def create_engine(
removes most of the per-call overhead. The callback must be
capturable, i.e. have no host synchronisation or data-dependent shapes.

max_mm_atoms : int, optional, default=None
The number of MM atoms passed to the GPU-resident callback with
electrostatic embedding. If None, it is set from the number within the
cutoff on the first call, plus 25%. Every 100 calls, it is increased if
the most within the cutoff so far is close to it, and the CUDA graph is
recaptured. MM atoms within the cutoff that don't fit interact with the
QM region at the MM level, with a warning when it is increased.

interpolate : str, optional, default="mm_ml"
How the QM energy is interpolated with lambda. With "mm_ml", the
QM atoms are interpolated from MM at lambda = 0 to QM at lambda = 1.
Expand Down Expand Up @@ -267,20 +277,31 @@ def create_engine(
if cuda_graph and not gpu_resident:
raise ValueError("'cuda_graph' requires 'gpu_resident'")

if max_mm_atoms is not None:
if not isinstance(max_mm_atoms, int) or isinstance(max_mm_atoms, bool):
raise TypeError("'max_mm_atoms' must be of type 'int'")
if max_mm_atoms < 1:
raise ValueError("'max_mm_atoms' must be >= 1")
if not gpu_resident or mechanical_embedding:
raise ValueError(
"'max_mm_atoms' requires 'gpu_resident' and electrostatic embedding"
)

if gpu_resident:
if neighbour_list_frequency > 0:
import warnings as _warnings

_warnings.warn(
"'neighbour_list_frequency' is ignored with 'gpu_resident', since all MM "
"atoms are passed to the callback."
"'neighbour_list_frequency' is ignored with 'gpu_resident', since the "
"nearest MM atoms are selected on the GPU at every step."
)

from ._gpu_resident import GpuResidentCallback

py_object = GpuResidentCallback(
getattr(py_object, callback) if callback else py_object,
cuda_graph=cuda_graph,
max_mm_atoms=max_mm_atoms,
)
callback = ""

Expand Down
10 changes: 10 additions & 0 deletions src/sire/qm/_emle.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ def emle(
switch_width=0.2,
gpu_resident=False,
cuda_graph=False,
max_mm_atoms=None,
interpolate="mm_ml",
mechanical_embedding=False,
map=None,
Expand Down Expand Up @@ -184,6 +185,11 @@ def emle(
speed-up is largest when OpenMM shares PyTorch's CUDA context, i.e.
with SIRE_SHARED_CUDA_CONTEXT=1 set before importing Sire.

max_mm_atoms : int, optional, default=None
The number of MM atoms nearest the QM region passed to the model when
'gpu_resident' is True, as for sire.qm.create_engine. If None, it is
set automatically, and it is increased as needed.

interpolate : str, optional, default="mm_ml"
How the QM energy is interpolated with lambda, as for
sire.qm.create_engine. With "end_states", 'qm_atoms' must be in a
Expand Down Expand Up @@ -234,6 +240,9 @@ def emle(
if not isinstance(cuda_graph, bool):
raise TypeError("'cuda_graph' must be of type 'bool'")

if max_mm_atoms is not None and not gpu_resident:
raise ValueError("'max_mm_atoms' requires 'gpu_resident'")

if interpolate not in ("mm_ml", "end_states"):
raise ValueError("'interpolate' must be 'mm_ml' or 'end_states'")

Expand Down Expand Up @@ -382,6 +391,7 @@ def emle(
switch_width=switch_width,
gpu_resident=True,
cuda_graph=cuda_graph,
max_mm_atoms=max_mm_atoms,
interpolate=interpolate,
map=user_map,
_engine_class=EMLEEngine,
Expand Down
119 changes: 103 additions & 16 deletions src/sire/qm/_gpu_resident.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
"_unswitched",
"_coulomb_tensors",
"_reaction_field",
"_max_mm_atoms",
"_max_mm_seen",
)


Expand Down Expand Up @@ -67,9 +69,15 @@ class GpuResidentCallback:

_num_warmup = 3

def __init__(self, func, cuda_graph=False):
# How often the number of MM atoms within the cutoff is checked, in calls,
# and the headroom added when 'max_mm_atoms' is set or grown.
_check_interval = 100
_headroom = 1.25

def __init__(self, func, cuda_graph=False, max_mm_atoms=None):
self._func = func
self._cuda_graph = cuda_graph
self._initial_max_mm_atoms = max_mm_atoms
self._numbers = None
self._is_mechanical = False
self._links = None
Expand Down Expand Up @@ -270,6 +278,13 @@ def _setup(
unswitched[num_mm:] = True
self._unswitched = unswitched

num_ext = self._charges_ext.shape[-1]
num_unswitched = int(unswitched.sum())
self._max_mm_atoms = min(
max(self._initial_max_mm_atoms or num_ext, num_unswitched), num_ext
)
self._max_mm_seen = torch.zeros((), dtype=torch.int64, device=device)

self._coulomb_tensors = [
(
torch.tensor(qm, dtype=torch.int64, device=device),
Expand Down Expand Up @@ -413,8 +428,9 @@ def _embed(self, xyz_qm, xyz_mm):
state, including link atoms, and scale their charges by the switching
function at the distance to the nearest of them, which is zero beyond
the cutoff. 'xyz_qm' has shape (S, N, 3), for S states, and 'xyz_mm'
includes the virtual point charges. Returns the MM positions and charges,
with shapes (S, M, 3) and (S, M), and the Coulomb energy of each state,
includes the virtual point charges. Returns the positions and charges of
the nearest 'max_mm_atoms' MM atoms of each state, with shapes (S, M, 3)
and (S, M), and the Coulomb energy of each state with those atoms,
in kJ/mol, between the MM charges of the QM atoms and the switched MM
charges, with the pairs scaled and the reaction field applied as in the
MM force, which the embedding replaces.
Expand Down Expand Up @@ -445,45 +461,74 @@ def _embed(self, xyz_qm, xyz_mm):
switch = (r_min < self._cutoff).to(r_min.dtype)

switch = torch.where(self._unswitched, 1.0, switch)

needed = ((r_min < self._cutoff) | self._unswitched).sum(dim=-1).max()
self._max_mm_seen.copy_(torch.maximum(self._max_mm_seen, needed))

# Pass only the nearest MM atoms, always including the unswitched ones.
# Any others within the cutoff are left to the MM force.
idx = None
if self._max_mm_atoms < switch.shape[-1]:
key = torch.where(self._unswitched, -1.0, r_min)
idx = torch.topk(
key, self._max_mm_atoms, dim=-1, largest=False, sorted=False
).indices
selected = torch.zeros_like(self._unswitched).expand_as(switch).clone()
switch = switch * selected.scatter_(1, idx, True)

charges = switch * self._charges_ext.expand(num_states, -1)

# The QM atoms' MM charges with the switched MM charges, excluding link
# atoms and virtual point charges.
charges_qm = self._charges_qm
charges_mm = switch[:, :num_mm] * self._charges_mm.expand(num_states, -1)
inv_r = 1.0 / r[:, :num_mm, :num_qm]
r_qm_mm = r[:, :, :num_qm]

if self._reaction_field is None:
kernel = inv_r
# Only the selected MM atoms have non-zero switched charges.
if idx is None:
q_sel, r_sel = charges_mm, r_qm_mm[:, :num_mm]
else:
k_rf, c_rf, cutoff_rf = self._reaction_field
r_qm_mm = r[:, :num_mm, :num_qm]
kernel = torch.where(
r_qm_mm < cutoff_rf, inv_r + k_rf * r_qm_mm**2 - c_rf, 0.0
)
# The virtual point charges aren't in the MM force.
q_pad = torch.nn.functional.pad(charges_mm, (0, switch.shape[-1] - num_mm))
q_sel = torch.gather(q_pad, 1, idx)
r_sel = torch.gather(r_qm_mm, 1, idx.unsqueeze(-1).expand(-1, -1, num_qm))

coulomb = (charges_mm.unsqueeze(-1) * charges_qm.unsqueeze(1) * kernel).sum(
dim=(1, 2)
)
coulomb = (
q_sel.unsqueeze(-1) * charges_qm.unsqueeze(1) * self._coulomb_kernel(r_sel)
).sum(dim=(1, 2))

# Exceptions are scaled plain Coulomb, without the reaction field.
corrections = []
for i in range(num_states):
qm, mm, scales = self._coulomb_tensors[
min(i, len(self._coulomb_tensors) - 1)
]
r_exc = r_qm_mm[i, mm, qm]
corrections.append(
(
charges_qm[i, qm]
* charges_mm[i, mm]
* (scales * inv_r[i, mm, qm] - kernel[i, mm, qm])
* (scales / r_exc - self._coulomb_kernel(r_exc))
).sum()
)

coulomb = _COULOMB_CONSTANT * (coulomb + torch.stack(corrections))

if idx is not None:
xyz_mm = torch.gather(xyz_mm, 1, idx.unsqueeze(-1).expand(-1, -1, 3))
charges = torch.gather(charges, 1, idx)

return xyz_mm, charges, coulomb

def _coulomb_kernel(self, r):
"""The QM-MM Coulomb kernel of the MM force, with any reaction field."""
import torch

if self._reaction_field is None:
return 1.0 / r
k_rf, c_rf, cutoff_rf = self._reaction_field
return torch.where(r < cutoff_rf, 1.0 / r + k_rf * r**2 - c_rf, 0.0)

def _run(self):
import torch

Expand Down Expand Up @@ -654,6 +699,8 @@ def __call__(
"graph": None,
"calls": 0,
"stream": stream,
"sized": False,
"since_check": 0,
}
self._states[key] = state
else:
Expand Down Expand Up @@ -694,7 +741,47 @@ def __call__(
else:
self._run()

state["calls"] += 1
state["calls"] += 1

if not self._is_mechanical:
state["since_check"] += 1
if not state["sized"] or state["since_check"] >= self._check_interval:
self._resize(state)

def _resize(self, state):
"""
Set 'max_mm_atoms' from the most MM atoms within the cutoff after the
first call, unless it was given, and grow it when that approaches it.
"""
import math

state["since_check"] = 0
num_ext = self._charges_ext.shape[-1]
limit = self._max_mm_atoms
seen = int(self._max_mm_seen.item())

if seen > limit:
import warnings

warnings.warn(
f"Up to {seen} MM atoms were within the QM/MM cutoff, but only the "
f"nearest {limit} were passed to the model, and the rest interacted "
f"with the QM region at the MM level. Increasing 'max_mm_atoms'."
)

target = limit
if seen > 0.9 * limit or (
not state["sized"] and self._initial_max_mm_atoms is None
):
target = min(max(math.ceil(self._headroom * seen), 1), num_ext)
state["sized"] = True

if target != limit:
self._max_mm_atoms = target
state["tensors"]["_max_mm_atoms"] = target
# Recapture with the new shapes, after warming up.
state["graph"] = None
state["calls"] = 0


def emle_callback(model, qm_charge):
Expand Down
Loading
Loading