diff --git a/doc/source/changelog.rst b/doc/source/changelog.rst index 897b53715..0b4e3514b 100644 --- a/doc/source/changelog.rst +++ b/doc/source/changelog.rst @@ -254,9 +254,10 @@ organisation on `GitHub `__. * 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, @@ -331,8 +332,8 @@ organisation on `GitHub `__. 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 diff --git a/doc/source/tutorial/part08/01_intro.rst b/doc/source/tutorial/part08/01_intro.rst index 260e2118e..c17740e97 100644 --- a/doc/source/tutorial/part08/01_intro.rst +++ b/doc/source/tutorial/part08/01_intro.rst @@ -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 diff --git a/doc/source/tutorial/part08/02_emle.rst b/doc/source/tutorial/part08/02_emle.rst index 175b44ae8..3ab602b49 100644 --- a/doc/source/tutorial/part08/02_emle.rst +++ b/doc/source/tutorial/part08/02_emle.rst @@ -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 `_ after a few diff --git a/src/sire/qm/__init__.py b/src/sire/qm/__init__.py index 5d753dfaf..f6eba6577 100644 --- a/src/sire/qm/__init__.py +++ b/src/sire/qm/__init__.py @@ -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, @@ -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', @@ -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. @@ -267,13 +277,23 @@ 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 @@ -281,6 +301,7 @@ def create_engine( py_object = GpuResidentCallback( getattr(py_object, callback) if callback else py_object, cuda_graph=cuda_graph, + max_mm_atoms=max_mm_atoms, ) callback = "" diff --git a/src/sire/qm/_emle.py b/src/sire/qm/_emle.py index 4962aa399..8471612b4 100644 --- a/src/sire/qm/_emle.py +++ b/src/sire/qm/_emle.py @@ -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, @@ -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 @@ -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'") @@ -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, diff --git a/src/sire/qm/_gpu_resident.py b/src/sire/qm/_gpu_resident.py index 0f5a0be56..0b22fe84c 100644 --- a/src/sire/qm/_gpu_resident.py +++ b/src/sire/qm/_gpu_resident.py @@ -29,6 +29,8 @@ "_unswitched", "_coulomb_tensors", "_reaction_field", + "_max_mm_atoms", + "_max_mm_seen", ) @@ -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 @@ -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), @@ -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. @@ -445,26 +461,41 @@ 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 = [] @@ -472,18 +503,32 @@ def _embed(self, xyz_qm, xyz_mm): 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 @@ -654,6 +699,8 @@ def __call__( "graph": None, "calls": 0, "stream": stream, + "sized": False, + "since_check": 0, } self._states[key] = state else: @@ -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): diff --git a/tests/qm/test_qm_gpu_resident.py b/tests/qm/test_qm_gpu_resident.py index 9cb786f78..da1f488bc 100644 --- a/tests/qm/test_qm_gpu_resident.py +++ b/tests/qm/test_qm_gpu_resident.py @@ -116,11 +116,21 @@ def callback(numbers_qm, charges_mm, xyz_qm, xyz_mm, cell=None, idx_mm=None): def _energy_and_forces( - mols, qm_atoms, electrostatic, gpu_resident, cuda_graph=False, cutoff_type="pme" + mols, + qm_atoms, + electrostatic, + gpu_resident, + cuda_graph=False, + cutoff_type="pme", + callback=None, + max_mm_atoms=None, ): - callback = ( - _gpu_callback(electrostatic) if gpu_resident else _host_callback(electrostatic) - ) + if callback is None: + callback = ( + _gpu_callback(electrostatic) + if gpu_resident + else _host_callback(electrostatic) + ) qm_mols, engine = sr.qm.create_engine( mols, @@ -131,6 +141,7 @@ def _energy_and_forces( switch_width=0.0, gpu_resident=gpu_resident, cuda_graph=cuda_graph, + max_mm_atoms=max_mm_atoms, ) d = qm_mols.dynamics( @@ -176,6 +187,51 @@ def _compare(mols, qm_atoms, electrostatic, cuda_graph=False, cutoff_type="pme") assert np.abs(f_dev - f_host).max() < 1e-2 +def test_gpu_resident_max_mm_atoms_left_to_mm(ala_mols, monkeypatch): + """ + MM atoms within the cutoff that don't fit in 'max_mm_atoms' are left to the + MM force, rather than having their Coulomb energy subtracted. + """ + from sire.qm._gpu_resident import GpuResidentCallback + + monkeypatch.setattr(GpuResidentCallback, "_resize", lambda self, state: None) + + mols = ala_mols.clone() + charges_qm = torch.tensor( + [atom.charge().value() for atom in mols[0].atoms()], + dtype=torch.float64, + device="cuda", + ) + + # The Coulomb energy that the embedding replaces, so only the MM energy and + # the pair energy remain. + def callback(numbers, charges_mm, xyz_qm, xyz_mm, cell): + xyz_qm = xyz_qm.detach().requires_grad_(True) + xyz_mm = xyz_mm.detach().requires_grad_(True) + r = torch.linalg.norm(xyz_mm.unsqueeze(1) - xyz_qm.unsqueeze(0), dim=2) + energy = ( + _pair_energy(xyz_qm) + + COULOMB * (charges_mm.unsqueeze(1) * charges_qm / r).sum() + ) + f_qm, f_mm = _forces(energy, [xyz_qm, xyz_mm]) + return energy, f_qm, f_mm + + results = [ + _energy_and_forces( + mols, + mols[0], + True, + gpu_resident=True, + callback=callback, + max_mm_atoms=max_mm_atoms, + ) + for max_mm_atoms in (None, 10) + ] + + assert results[1][0] == pytest.approx(results[0][0], abs=1e-3) + assert np.abs(results[1][1] - results[0][1]).max() < 1e-2 + + @pytest.mark.parametrize("electrostatic", [False, True]) @pytest.mark.parametrize("cuda_graph", [False, True]) def test_gpu_resident_matches_host(ala_mols, electrostatic, cuda_graph): @@ -220,6 +276,67 @@ def test_gpu_resident_requires_flag_types(ala_mols): with pytest.raises(ValueError): sr.qm.create_engine(mols, mols[0], _host_callback(False), cuda_graph=True) + with pytest.raises(ValueError): + sr.qm.create_engine(mols, mols[0], _host_callback(False), max_mm_atoms=10) + + with pytest.raises(ValueError): + sr.qm.create_engine( + mols, mols[0], _gpu_callback(False), gpu_resident=True, max_mm_atoms=0 + ) + + with pytest.raises(ValueError): + sr.qm.create_engine( + mols, + mols[0], + _gpu_callback(False), + gpu_resident=True, + mechanical_embedding=True, + max_mm_atoms=10, + ) + + +@pytest.mark.parametrize("max_mm_atoms", [None, 10]) +@pytest.mark.parametrize("cuda_graph", [False, True]) +def test_gpu_resident_max_mm_atoms(ala_mols, max_mm_atoms, cuda_graph): + """ + After the first call, only the MM atoms nearest the QM region are passed, + and a 'max_mm_atoms' that is too small is increased, with a warning. + """ + mols = ala_mols.clone() + num_mm = mols.num_atoms() - mols[0].num_atoms() + + sizes = [] + gpu_callback = _gpu_callback(True) + + def callback(numbers, charges_mm, xyz_qm, xyz_mm, cell): + sizes.append(xyz_mm.shape[0]) + return gpu_callback(numbers, charges_mm, xyz_qm, xyz_mm, cell) + + e_host, f_host = _energy_and_forces(mols, mols[0], True, gpu_resident=False) + + import warnings + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + e_dev, f_dev = _energy_and_forces( + mols, + mols[0], + True, + gpu_resident=True, + cuda_graph=cuda_graph, + callback=callback, + max_mm_atoms=max_mm_atoms, + ) + + warned = any("max_mm_atoms" in str(x.message) for x in w) + assert warned == (max_mm_atoms is not None) + + assert sizes[0] == (num_mm if max_mm_atoms is None else max_mm_atoms) + assert 10 < sizes[-1] < num_mm + + assert e_dev == pytest.approx(e_host, abs=1e-3) + assert np.abs(f_dev - f_host).max() < 1e-2 + def test_gpu_resident_graph_per_context(ala_mols): """Each OpenMM context keeps its own CUDA graph, including when another is destroyed."""