|
| 1 | +import torch |
| 2 | +from metatensor.torch import TensorBlock, TensorMap |
| 3 | +from metatomic.torch import ModelOutput, System |
| 4 | +from typing_extensions import TypedDict |
| 5 | + |
| 6 | +from metatrain.utils.data import DatasetInfo, TargetInfo |
| 7 | +from metatrain.utils.data.target_info import get_generic_target_info |
| 8 | +from metatrain.utils.sum_over_atoms import sum_over_atoms |
| 9 | + |
| 10 | + |
| 11 | +class HookHypers(TypedDict): |
| 12 | + """ |
| 13 | + Hyperparameters for the global multipole hook. |
| 14 | + """ |
| 15 | + |
| 16 | + inputs: str |
| 17 | + |
| 18 | + outputs: str |
| 19 | + |
| 20 | + |
| 21 | +class GlobalMultipole(torch.nn.Module): |
| 22 | + """ |
| 23 | + Computes a global multipole from local predictions. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, hypers: HookHypers, dataset_info: DatasetInfo): |
| 27 | + super().__init__() |
| 28 | + |
| 29 | + self.hypers = hypers |
| 30 | + |
| 31 | + # Get the information about the output target from the dataset info |
| 32 | + self.out_name = hypers["outputs"] |
| 33 | + self.out_target = dataset_info.targets[self.out_name] |
| 34 | + |
| 35 | + self.degrees = self.out_target.layout.keys["o3_lambda"] |
| 36 | + self.max_degree = self.degrees.max().item() |
| 37 | + |
| 38 | + if self.max_degree > 1: |
| 39 | + raise ValueError( |
| 40 | + f"Global multipoles hook only supports multipoles up " |
| 41 | + f"to l=1 for now, but {self.out_name} has max degree " |
| 42 | + f"{self.max_degree}" |
| 43 | + ) |
| 44 | + |
| 45 | + # Build the input target that we will request from the model, |
| 46 | + # which is the local multipoles |
| 47 | + self._input_name = "mtt::aux::local_multipoles" |
| 48 | + |
| 49 | + self._input_target_info = get_generic_target_info( |
| 50 | + self._input_name, |
| 51 | + { |
| 52 | + "quantity": "", |
| 53 | + "unit": "", |
| 54 | + "type": { |
| 55 | + "spherical": { |
| 56 | + "irreps": [ |
| 57 | + {"o3_lambda": i, "o3_sigma": 1} |
| 58 | + for i in range(self.max_degree + 1) |
| 59 | + ] |
| 60 | + } |
| 61 | + }, |
| 62 | + "num_subtargets": 1, |
| 63 | + "sample_kind": "atom", |
| 64 | + }, |
| 65 | + ) |
| 66 | + |
| 67 | + def requested_target_infos(self) -> dict[str, TargetInfo]: |
| 68 | + """ |
| 69 | + Returns the list of requested target infos for the hook. |
| 70 | +
|
| 71 | + :return: A list of requested target names. |
| 72 | + """ |
| 73 | + return {self._input_name: self._input_target_info} |
| 74 | + |
| 75 | + def requested_inputs(self) -> dict[str, ModelOutput]: |
| 76 | + """ |
| 77 | + Returns the list of requested inputs for the hook. |
| 78 | +
|
| 79 | + :return: A list of requested input names. |
| 80 | + """ |
| 81 | + return { |
| 82 | + self._input_name: ModelOutput( |
| 83 | + quantity="", |
| 84 | + unit="", |
| 85 | + sample_kind="atom", |
| 86 | + ) |
| 87 | + } |
| 88 | + |
| 89 | + def forward( |
| 90 | + self, systems: list[System], inputs: dict[str, TensorMap] |
| 91 | + ) -> dict[str, TensorMap]: |
| 92 | + """ |
| 93 | + Computes the global multipole from the local predictions. |
| 94 | + """ |
| 95 | + # Get the concatenated positions of all atoms in the systems, |
| 96 | + # and reorder the axes to match the spherical harmonics convention |
| 97 | + # (x, y, z) -> (y, z, x) |
| 98 | + positions = torch.cat([s.positions for s in systems], dim=0) |
| 99 | + positions = positions[:, [1, 2, 0]] |
| 100 | + |
| 101 | + # Get the local predictions for each degree in the multipole expansion |
| 102 | + input_tmap = inputs[self._input_name] |
| 103 | + local_values = [ |
| 104 | + input_tmap.block(dict(o3_lambda=ell, o3_sigma=1)).values |
| 105 | + for ell in range(self.max_degree + 1) |
| 106 | + ] |
| 107 | + |
| 108 | + # Compute the local contributions to the global multipole for each degree |
| 109 | + local_contribs = [] |
| 110 | + for ell in range(self.max_degree + 1): |
| 111 | + if ell == 0: |
| 112 | + local_contribs.append(local_values[ell]) |
| 113 | + elif ell == 1: |
| 114 | + local_contribs.append( |
| 115 | + torch.einsum( |
| 116 | + "sp, sx -> sxp", local_contribs[ell - 1].squeeze(1), positions |
| 117 | + ) |
| 118 | + + local_values[ell] |
| 119 | + ) |
| 120 | + else: |
| 121 | + raise ValueError( |
| 122 | + "Global multipoles hook only supports multipoles up to l=1 for now" |
| 123 | + f", but {self.out_name} has degree {ell}" |
| 124 | + ) |
| 125 | + |
| 126 | + # Build a tensor map with the requested multipole degrees. |
| 127 | + local_tmap = TensorMap( |
| 128 | + keys=self.out_target.layout.keys, |
| 129 | + blocks=[ |
| 130 | + TensorBlock( |
| 131 | + values=local_contribs[degree], |
| 132 | + samples=input_tmap.block(0).samples, |
| 133 | + components=self.out_target.component_labels[i], |
| 134 | + properties=self.out_target.property_labels[i], |
| 135 | + ) |
| 136 | + for i, degree in enumerate(self.degrees) |
| 137 | + ], |
| 138 | + ) |
| 139 | + |
| 140 | + # Return the global multipole by summing over the atoms in the system |
| 141 | + return {self.out_name: sum_over_atoms(local_tmap)} |
0 commit comments