metatensor-learn 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {metatensor-learn-0.2.0/metatensor_learn.egg-info → metatensor_learn-0.2.2}/PKG-INFO +4 -4
  2. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor/learn/__init__.py +3 -5
  3. metatensor_learn-0.2.2/metatensor/learn/data/dataloader.py +25 -0
  4. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor/learn/data/dataset.py +68 -64
  5. metatensor_learn-0.2.2/metatensor/learn/nn/__init__.py +8 -0
  6. metatensor_learn-0.2.2/metatensor/learn/nn/_utils.py +53 -0
  7. metatensor_learn-0.2.2/metatensor/learn/nn/layer_norm.py +349 -0
  8. metatensor_learn-0.2.2/metatensor/learn/nn/linear.py +181 -0
  9. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor/learn/nn/module_map.py +13 -7
  10. metatensor_learn-0.2.2/metatensor/learn/nn/relu.py +114 -0
  11. metatensor_learn-0.2.2/metatensor/learn/nn/sequential.py +39 -0
  12. metatensor_learn-0.2.2/metatensor/learn/nn/silu.py +114 -0
  13. metatensor_learn-0.2.2/metatensor/learn/nn/tanh.py +108 -0
  14. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2/metatensor_learn.egg-info}/PKG-INFO +4 -4
  15. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor_learn.egg-info/SOURCES.txt +7 -1
  16. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/pyproject.toml +3 -3
  17. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/setup.py +1 -1
  18. metatensor-learn-0.2.0/metatensor/learn/data/dataloader.py +0 -30
  19. metatensor-learn-0.2.0/metatensor/learn/nn/__init__.py +0 -5
  20. metatensor-learn-0.2.0/metatensor/learn/nn/linear.py +0 -138
  21. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/AUTHORS +0 -0
  22. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/LICENSE +0 -0
  23. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/MANIFEST.in +0 -0
  24. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/README.rst +0 -0
  25. /metatensor-learn-0.2.0/metatensor/learn/_classes.py → /metatensor_learn-0.2.2/metatensor/learn/_backend.py +0 -0
  26. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor/learn/data/__init__.py +0 -0
  27. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor/learn/data/collate.py +0 -0
  28. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor_learn.egg-info/dependency_links.txt +0 -0
  29. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor_learn.egg-info/requires.txt +0 -0
  30. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor_learn.egg-info/top_level.txt +0 -0
  31. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/metatensor_learn.egg-info/zip-safe +0 -0
  32. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/n_commits_since_last_tag +0 -0
  33. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/setup.cfg +0 -0
  34. {metatensor-learn-0.2.0 → metatensor_learn-0.2.2}/tests/test_dummmy.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: metatensor-learn
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
5
  Author: Guillaume Fraux, Davide Tisi, Philip Loche, Joseph W. Abbott, Jigyasa Nigam, Chiheb Ben Mahmoud
6
6
  License: BSD-3-Clause
7
- Project-URL: homepage, https://lab-cosmo.github.io/metatensor/latest/
8
- Project-URL: documentation, https://lab-cosmo.github.io/metatensor/latest/
7
+ Project-URL: homepage, https://docs.metatensor.org/latest/
8
+ Project-URL: documentation, https://docs.metatensor.org/latest/
9
9
  Project-URL: repository, https://github.com/lab-cosmo/metatensor
10
- Project-URL: changelog, https://lab-cosmo.github.io/metatensor/latest/learn/CHANGELOG.html
10
+ Project-URL: changelog, https://docs.metatensor.org/latest/learn/CHANGELOG.html
11
11
  Keywords: machine learning,molecular modeling
12
12
  Classifier: Development Status :: 4 - Beta
13
13
  Classifier: Intended Audience :: Science/Research
@@ -12,8 +12,6 @@ except ImportError:
12
12
 
13
13
 
14
14
  if HAS_TORCH:
15
- from . import data, nn # noqa
16
-
17
- __all__ = ["data", "nn"]
18
-
19
- __all__ = []
15
+ from . import data, nn # noqa: F401
16
+ from .data import DataLoader, Dataset, IndexedDataset # noqa: F401
17
+ from .nn import ModuleMap, Linear # noqa: F401
@@ -0,0 +1,25 @@
1
+ """
2
+ Module containing the DataLoader.
3
+ """
4
+
5
+ import torch
6
+
7
+ from .collate import group_and_join
8
+
9
+
10
+ class DataLoader(torch.utils.data.DataLoader):
11
+ """
12
+ Class for loading data from an :py:class:`torch.utils.data.Dataset` object with a
13
+ default collate function (:py:func:`metatensor.learn.data.group_and_join`) that
14
+ supports :py:class:`torch.Tensor`, :py:class:`metatensor.torch.atomistic.System`,
15
+ :py:class:`metatensor.TensorMap`, and :py:class:`metatensor.torch.TensorMap`.
16
+
17
+ The dataset wil typically be :py:class:`metatensor.learn.Dataset` or
18
+ :py:class:`metatensor.learn.IndexedDataset`.
19
+
20
+ Any argument as accepted by the torch :py:class:`torch.utils.data.DataLoader` parent
21
+ class is supported.
22
+ """
23
+
24
+ def __init__(self, dataset, collate_fn=group_and_join, **kwargs):
25
+ super().__init__(dataset, collate_fn=collate_fn, **kwargs)
@@ -70,37 +70,44 @@ class _BaseDataset(torch.utils.data.Dataset):
70
70
  """
71
71
  return self._size
72
72
 
73
+ def __iter__(self):
74
+ """
75
+ Returns an iterator over the dataset.
76
+ """
77
+ for idx in self._indices:
78
+ yield self[idx]
79
+
73
80
 
74
81
  class Dataset(_BaseDataset):
75
82
  """
76
- Defines a dataset class for various named data fields.
77
-
78
- The data fields are specified as keyword arguments to the constructor, where
79
- the keyword is the name of the field, and the value is either a list of data
80
- objects or a callable.
81
-
82
- `size` specifies the number of samples in the dataset. This only needs to be
83
- passed if all data fields are passed as callables. Otherwise, the size is
84
- inferred from the length of the data fields passed as lists.
85
-
86
- Every sample in the dataset is assigned a numeric ID from 0 to `size` - 1.
87
- This ID can be used to access the corresponding sample. For instance,
88
- `dataset[0]` returns a named tuple of all data fields for the first sample
89
- in the dataset.
90
-
91
- A data field kwarg passed as a list must be comprised of the same type of
92
- object, and its length must be consistent with the `size` argument (if
93
- specified) and the length of all other data fields passed as lists.
94
-
95
- Otherwise a data field kwarg passed as a callable must take a single
96
- argument corresponding to the numeric sample ID and return the data object
97
- for that sample ID. This data field for a given sample is then only lazily
98
- loaded into memory when the Dataset.__getitem__ method is called.
99
-
100
- :param size: Optional, an integer indicating the size of the dataset, i.e.
101
- the number of samples. This only needs to be specified if all data
102
- :param kwargs: List or Callable. Keyword arguments specifying the data
103
- fields for the dataset.
83
+ Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
84
+ data fields.
85
+
86
+ The data fields are specified as keyword arguments to the constructor, where the
87
+ keyword is the name of the field, and the value is either a list of data objects or
88
+ a callable.
89
+
90
+ ``size`` specifies the number of samples in the dataset. This only needs to be
91
+ passed if all data fields are passed as callables. Otherwise, the size is inferred
92
+ from the length of the data fields passed as lists.
93
+
94
+ Every sample in the dataset is assigned a numeric ID from 0 to ``size - 1``. This ID
95
+ can be used to access the corresponding sample. For instance, ``dataset[0]`` returns
96
+ a named tuple of all data fields for the first sample in the dataset.
97
+
98
+ A data field kwarg passed as a list must be comprised of the same type of object,
99
+ and its length must be consistent with the ``size`` argument (if specified) and the
100
+ length of all other data fields passed as lists.
101
+
102
+ Otherwise a data field kwarg passed as a callable must take a single argument
103
+ corresponding to the numeric sample ID and return the data object for that sample
104
+ ID. This data field for a given sample is then only lazily loaded into memory when
105
+ the :py:meth:`Dataset.__getitem__` method is called.
106
+
107
+ :param size: Optional, an integer indicating the size of the dataset, i.e. the
108
+ number of samples. This only needs to be specified if all data
109
+ :param kwargs: List or Callable. Keyword arguments specifying the data fields for
110
+ the dataset.
104
111
  """
105
112
 
106
113
  def __init__(self, size: Optional[int] = None, **kwargs):
@@ -115,12 +122,11 @@ class Dataset(_BaseDataset):
115
122
 
116
123
  def __getitem__(self, idx: int) -> NamedTuple:
117
124
  """
118
- Returns the data for each field corresponding to the internal index
119
- `idx`.
125
+ Returns the data for each field corresponding to the internal index ``idx``.
120
126
 
121
- Each item can be accessed with `self[idx]`. Returned is a named tuple
122
- with fields corresponding to those passed (in order) to the constructor
123
- upon class initialization.
127
+ Each item can be accessed with ``self[idx]``. Returned is a named tuple with
128
+ fields corresponding to those passed (in order) to the constructor upon class
129
+ initialization.
124
130
  """
125
131
  if idx not in self._indices:
126
132
  raise ValueError(f"Index {idx} not in dataset")
@@ -144,30 +150,30 @@ class Dataset(_BaseDataset):
144
150
 
145
151
  class IndexedDataset(_BaseDataset):
146
152
  """
147
- Defines a dataset class for various named data fields, with sample indexed
148
- by a list of unique sample IDs.
149
-
150
- The data fields are specified as keyword arguments to the constructor, where
151
- the keyword is the name of the field, and the value is either a list of data
152
- objects or a callable.
153
-
154
- `sample_id` must be a unique list of any hashable object. Each respective
155
- sample ID is assigned an internal numeric index from 0 to `len(sample_id)`
156
- - 1. This is used to internally index the dataset, and can be used to access
157
- a given sample. For instance, `dataset[0]` returns a named tuple of all data
158
- fields for the first sample in the dataset, i.e. the one with unique sample
159
- ID at `sample_id[0]`. In order to access a sample by its ID, use the
160
- Dataset.get_sample method.
161
-
162
- A data field kwarg passed as a list must be comprised of the same type of
163
- object, and its length must be consistent with the length of `sample_id`
164
- and the length of all other data fields passed as lists.
165
-
166
- Otherwise a data field kwarg passed as a callable must take a single
167
- argument corresponding to the unique sample ID (i.e. those passed in
168
- `sample_id`) and return the data object for that sample ID. This data field
169
- for a given sample is then only lazily loaded into memory when the
170
- Dataset.__getitem__ or Dataset.get_sample methods are called.
153
+ Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
154
+ data fields, with sample indexed by a list of unique sample IDs.
155
+
156
+ The data fields are specified as keyword arguments to the constructor, where the
157
+ keyword is the name of the field, and the value is either a list of data objects or
158
+ a callable.
159
+
160
+ ``sample_id`` must be a unique list of any hashable object. Each respective sample
161
+ ID is assigned an internal numeric index from 0 to ``len(sample_id) - 1``. This is
162
+ used to internally index the dataset, and can be used to access a given sample. For
163
+ instance, ``dataset[0]`` returns a named tuple of all data fields for the first
164
+ sample in the dataset, i.e. the one with unique sample ID at ``sample_id[0]``. In
165
+ order to access a sample by its ID, use the :py:meth:`IndexedDataset.get_sample`
166
+ method.
167
+
168
+ A data field kwarg passed as a list must be comprised of the same type of object,
169
+ and its length must be consistent with the length of ``sample_id`` and the length of
170
+ all other data fields passed as lists.
171
+
172
+ Otherwise a data field kwarg passed as a callable must take a single argument
173
+ corresponding to the unique sample ID (i.e. those passed in ``sample_id``) and
174
+ return the data object for that sample ID. This data field for a given sample is
175
+ then only lazily loaded into memory when :py:meth:`IndexedDataset.__getitem__` or
176
+ :py:meth:`IndexedDataset.get_sample` methods are called.
171
177
 
172
178
  :param sample_id: A list of unique IDs for each sample in the dataset.
173
179
  :param kwargs: Keyword arguments specifying the data fields for the dataset.
@@ -191,12 +197,11 @@ class IndexedDataset(_BaseDataset):
191
197
 
192
198
  def __getitem__(self, idx: int) -> NamedTuple:
193
199
  """
194
- Returns the data for each field corresponding to the internal index
195
- `idx`.
200
+ Returns the data for each field corresponding to the internal index ``idx``.
196
201
 
197
- Each item can be accessed with `self[idx]`. Returned is a named tuple,
198
- whose first field is the sample ID, and the remaining fields correspond
199
- those passed (in order) to the constructor upon class initialization.
202
+ Each item can be accessed with ``self[idx]``. Returned is a named tuple, whose
203
+ first field is the sample ID, and the remaining fields correspond those passed
204
+ (in order) to the constructor upon class initialization.
200
205
  """
201
206
  if idx not in self._indices:
202
207
  raise ValueError(f"Index {idx} not in dataset")
@@ -219,8 +224,7 @@ class IndexedDataset(_BaseDataset):
219
224
 
220
225
  def get_sample(self, sample_id) -> NamedTuple:
221
226
  """
222
- Returns a named tuple for the sample corresponding to the given
223
- `sample_id`.
227
+ Returns a named tuple for the sample corresponding to the given ``sample_id``.
224
228
  """
225
229
  if sample_id not in self._sample_id_to_idx:
226
230
  raise ValueError(f"Sample ID '{sample_id}' not in dataset")
@@ -0,0 +1,8 @@
1
+ from .module_map import ModuleMap # noqa: F401
2
+
3
+ from .layer_norm import InvariantLayerNorm, LayerNorm # noqa: F401
4
+ from .linear import EquivariantLinear, Linear # noqa: F401
5
+ from .relu import InvariantReLU, ReLU # noqa: F401
6
+ from .sequential import Sequential # noqa: F401
7
+ from .silu import InvariantSiLU, SiLU # noqa: F401
8
+ from .tanh import InvariantTanh, Tanh # noqa: F401
@@ -0,0 +1,53 @@
1
+ from typing import List
2
+
3
+
4
+ def _check_module_map_parameter(
5
+ parameter, name: str, types: type, num_keys: int, keys_param_name: str
6
+ ) -> List:
7
+ """
8
+ A helper function that checks the type of an input parameter passed to classes that
9
+ are children of :py:class:`ModuleMap`, and raises the appropriate errors.
10
+
11
+ Raises a TypeError if not one of the valid `types`. Raises a ValueError if passed as
12
+ a list and not the same length as `num_keys`.
13
+
14
+ :param parameter: the parameter value to check
15
+ :param name: str, the name of the parameter used in the ModuleMap child class
16
+ :param types: the type that is valid for the `parameter`
17
+ :param num_keys: int, the number of relevant keys in the ModuleMap child class for
18
+ which the parameter is used. Used to check the length of `parameter` if passed
19
+ as a list.
20
+ :param keys_param_name: str, the name of the relevant keys parameter for the
21
+ ModuleMap child class. Used to raise a ValueError if the length of `parameter`
22
+ does not match the length of the keys.
23
+
24
+ :return: `parameter` as a list, one for each key.
25
+ """
26
+
27
+ # Convert to list if not already
28
+ if isinstance(parameter, types):
29
+ parameter = [parameter] * num_keys
30
+
31
+ # Check if it is a list
32
+ if isinstance(parameter, list):
33
+ if len(parameter) != num_keys:
34
+ raise ValueError(
35
+ f"`{name}` must have same length as `{keys_param_name}`,"
36
+ f" but len({name}) != len({keys_param_name})"
37
+ f" [{len(parameter)} != {num_keys}]"
38
+ )
39
+ # Check each element
40
+ for p in parameter:
41
+ if not isinstance(p, types):
42
+ raise TypeError(
43
+ f"`{name}` must be of type {types} or List of {types}, but not"
44
+ f" {type(p)}."
45
+ )
46
+ # Raise if not a list
47
+ else:
48
+ raise TypeError(
49
+ f"`{name}` must be type {types} or List of {types},"
50
+ f" but not {type(parameter)}."
51
+ )
52
+
53
+ return parameter
@@ -0,0 +1,349 @@
1
+ """
2
+ Module containing classes :class:`LayerNorm` and :class:`InvariantLayerNorm`, i.e.
3
+ module maps that apply layer norms in a generic and equivariant way,
4
+ respectively.
5
+ """
6
+
7
+ from typing import List, Optional, Union
8
+
9
+ import torch
10
+ from torch.nn import Module, init
11
+ from torch.nn.parameter import Parameter
12
+
13
+ from .._backend import Labels, TensorMap
14
+ from ._utils import _check_module_map_parameter
15
+ from .module_map import ModuleMap
16
+
17
+
18
+ class LayerNorm(Module):
19
+ """
20
+ Module similar to :py:class:`torch.nn.LayerNorm` that works with
21
+ :py:class:`metatensor.torch.TensorMap` objects.
22
+
23
+ Applies a layer normalization to each block of a :py:class:`TensorMap` passed to its
24
+ :py:meth:`forward` method, indexed by :param in_keys:.
25
+
26
+ The main difference from :py:class:`torch.nn.LayerNorm` is that there is no
27
+ `normalized_shape` parameter. Instead, the standard deviation and mean (if
28
+ applicable) are calculated over the property dimension of each
29
+ :py:class:`TensorBlock`.
30
+
31
+ This module also has an extra parameter :param mean: that controls whether or not
32
+ the mean over the properties dimension is subtracted from the input tensor in the
33
+ transformation.
34
+
35
+ Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
36
+ description of the other parameters.
37
+
38
+ Each parameter can be passed as a single value of its expected type, which is used
39
+ as the parameter for all blocks. Alternatively, they can be passed as a list to
40
+ control the parameters applied to each block indexed by the keys in :param in_keys:.
41
+
42
+ :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
43
+ tensor map in the :py:meth:`forward` method.
44
+ :param in_features: list of int, the number of features in the input tensor for each
45
+ block indexed by the keys in :param in_keys:. If passed as a single value, the
46
+ same number of features is assumed for all blocks.
47
+ :param out_properties: list of :py:class`Labels` (optional), the properties labels
48
+ of the output. By default (if none) the output properties are relabeled using
49
+ Labels.range.
50
+ :mean bool: whether or not to subtract the mean over the properties (final)
51
+ dimension of each block of the input passed to :py:meth:`forward`.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ in_keys: Labels,
57
+ in_features: List[int],
58
+ out_properties: Optional[List[Labels]] = None,
59
+ *,
60
+ eps: Union[float, List[float]] = 1e-5,
61
+ elementwise_affine: Union[bool, List[bool]] = True,
62
+ bias: Union[bool, List[bool]] = True,
63
+ mean: Union[bool, List[bool]] = True,
64
+ device: Optional[torch.device] = None,
65
+ dtype: Optional[torch.dtype] = None,
66
+ ) -> None:
67
+ super().__init__()
68
+ # Check input parameters, convert to lists (for each key) if necessary
69
+ in_features = _check_module_map_parameter(
70
+ in_features, "in_features", int, len(in_keys), "in_keys"
71
+ )
72
+ eps = _check_module_map_parameter(eps, "eps", float, len(in_keys), "in_keys")
73
+ elementwise_affine = _check_module_map_parameter(
74
+ elementwise_affine, "elementwise_affine", bool, len(in_keys), "in_keys"
75
+ )
76
+ bias = _check_module_map_parameter(bias, "bias", bool, len(in_keys), "in_keys")
77
+ mean = _check_module_map_parameter(mean, "mean", bool, len(in_keys), "in_keys")
78
+
79
+ # Build module list
80
+ modules: List[Module] = []
81
+ for i in range(len(in_keys)):
82
+ module = _LayerNorm(
83
+ in_features=in_features[i],
84
+ eps=eps[i],
85
+ elementwise_affine=elementwise_affine[i],
86
+ bias=bias[i],
87
+ mean=mean[i],
88
+ device=device,
89
+ dtype=dtype,
90
+ )
91
+ modules.append(module)
92
+ self.module_map = ModuleMap(in_keys, modules, out_properties)
93
+
94
+ def forward(self, tensor: TensorMap) -> TensorMap:
95
+ """
96
+ Apply the transformation to the input tensor map `tensor`.
97
+
98
+ :param tensor: :py:class:`TensorMap` with the input tensor to be transformed.
99
+ :return: :py:class:`TensorMap`
100
+ """
101
+ # Currently not supporting gradients
102
+ if len(tensor[0].gradients_list()) != 0:
103
+ raise ValueError(
104
+ "Gradients not supported. Please use metatensor.remove_gradients()"
105
+ " before using this module"
106
+ )
107
+ return self.module_map(tensor)
108
+
109
+
110
+ class InvariantLayerNorm(Module):
111
+ """
112
+ Module similar to :py:class:`torch.nn.LayerNorm` that works with
113
+ :py:class:`metatensor.torch.TensorMap` objects, applying the transformation only to
114
+ the invariant blocks.
115
+
116
+ Applies a layer normalization to each invariant block of a :py:class:`TensorMap`
117
+ passed to :py:meth:`forward` method. These correspond to the blocks indexed by
118
+ :param in_keys: at numeric positions passed in :param invariant_key_idxs:.
119
+
120
+ The main difference from :py:class:`torch.nn.LayerNorm` is that there is no
121
+ `normalized_shape` parameter. Instead, the standard deviation and mean (if
122
+ applicable) are calculated over the property dimension of each
123
+ :py:class:`TensorBlock`.
124
+
125
+ This module also has an extra parameter :param mean: that controls whether or not
126
+ the mean over the properties dimension is subtracted from the input tensor in the
127
+ transformation.
128
+
129
+ Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
130
+ description of the other parameters.
131
+
132
+ Each parameter can be passed as a single value of its expected type, which is used
133
+ as the parameter for all blocks. Alternatively, they can be passed as a list to
134
+ control the parameters applied to each block indexed by the invariant keys in :param
135
+ in_keys: at numeric poositions :param invariant_key_idxs:.
136
+
137
+ :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
138
+ tensor map in the :py:meth:`forward` method.
139
+ :param invariant_key_idxs: list of int, the indices of the invariant keys present in
140
+ `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
141
+ have layer norm applied. The other blocks will have the identity operator
142
+ applied.
143
+ :param in_features: list of int, the number of features in the input tensor for each
144
+ block indexed by the keys in :param in_keys:. If passed as a single value, the
145
+ same number of features is assumed for all blocks.
146
+ :param out_properties: list of :py:class`Labels` (optional), the properties labels
147
+ of the output. By default (if none) the output properties are relabeled using
148
+ Labels.range.
149
+ :param mean: bool or list of bool. Whether or not to subtract the mean over the
150
+ properties (final) dimension of each invariant block of the input passed to
151
+ :py:meth:`forward`. If passed as a list, must have the same length as :param
152
+ invariant_key_idxs:.
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ in_keys: Labels,
158
+ invariant_key_idxs: List[int],
159
+ in_features: List[int],
160
+ out_properties: Optional[List[Labels]] = None,
161
+ *,
162
+ eps: Union[float, List[float]] = 1e-5,
163
+ elementwise_affine: Union[bool, List[bool]] = True,
164
+ bias: Union[bool, List[bool]] = True,
165
+ mean: Union[bool, List[bool]] = True,
166
+ device: Optional[torch.device] = None,
167
+ dtype: Optional[torch.dtype] = None,
168
+ ) -> None:
169
+ super().__init__()
170
+ # Check input parameters, convert to lists (for each *invariant* key) if
171
+ # necessary.
172
+ in_features = _check_module_map_parameter(
173
+ in_features,
174
+ "in_features",
175
+ int,
176
+ len(invariant_key_idxs),
177
+ "invariant_key_idxs",
178
+ )
179
+ eps = _check_module_map_parameter(
180
+ eps, "eps", float, len(invariant_key_idxs), "invariant_key_idxs"
181
+ )
182
+ elementwise_affine = _check_module_map_parameter(
183
+ elementwise_affine,
184
+ "elementwise_affine",
185
+ bool,
186
+ len(invariant_key_idxs),
187
+ "invariant_key_idxs",
188
+ )
189
+ bias = _check_module_map_parameter(
190
+ bias, "bias", bool, len(invariant_key_idxs), "invariant_key_idxs"
191
+ )
192
+ mean = _check_module_map_parameter(
193
+ mean, "mean", bool, len(invariant_key_idxs), "invariant_key_idxs"
194
+ )
195
+
196
+ # Build module list
197
+ modules: List[Module] = []
198
+ invariant_idx: int = 0
199
+ for i in range(len(in_keys)):
200
+ if i in invariant_key_idxs: # Invariant block: apply LayerNorm
201
+ for j in range(len(invariant_key_idxs)):
202
+ if invariant_key_idxs[j] == i:
203
+ invariant_idx = j
204
+
205
+ module = _LayerNorm(
206
+ in_features=in_features[invariant_idx],
207
+ eps=eps[invariant_idx],
208
+ elementwise_affine=elementwise_affine[invariant_idx],
209
+ bias=bias[invariant_idx],
210
+ mean=mean[invariant_idx],
211
+ device=device,
212
+ dtype=dtype,
213
+ )
214
+ else: # Covariant block: apply the identity operator
215
+ module = torch.nn.Identity()
216
+ modules.append(module)
217
+ self.module_map = ModuleMap(in_keys, modules, out_properties)
218
+
219
+ def forward(self, tensor: TensorMap) -> TensorMap:
220
+ """
221
+ Apply the layer norm to the input tensor map `tensor`.
222
+
223
+ :param tensor: :py:class:`TensorMap` with the input tensor to be transformed.
224
+ :return: :py:class:`TensorMap`
225
+ """
226
+ # Currently not supporting gradients
227
+ if len(tensor[0].gradients_list()) != 0:
228
+ raise ValueError(
229
+ "Gradients not supported. Please use metatensor.remove_gradients()"
230
+ " before using this module"
231
+ )
232
+ return self.module_map(tensor)
233
+
234
+
235
+ class _LayerNorm(Module):
236
+ """
237
+ Custom :py:class:`Module` re-implementing :py:class:`torch.nn.LayerNorm`.
238
+
239
+ In this case, `normalized_shape` is not provided as a parameter. Instead, the
240
+ standard deviation and mean (if applicable) are calculated over the final dimension
241
+ of the input tensor.
242
+
243
+ Subtraction of this mean can be switched on or off using the extra :param mean:
244
+ parameter.
245
+
246
+ Refer to :py:class:`torch.nn.LayerNorm` documentation for more information on the
247
+ other parameters.
248
+
249
+ :param mean: bool, whether or not to subtract the mean over the final dimension of
250
+ the input tensor passed to :py:meth:`forward`.
251
+ """
252
+
253
+ __constants__ = ["in_features", "eps", "elementwise_affine"]
254
+ eps: float
255
+ elementwise_affine: bool
256
+
257
+ def __init__(
258
+ self,
259
+ in_features: int,
260
+ eps: float = 1e-5,
261
+ elementwise_affine: bool = True,
262
+ bias: bool = True,
263
+ device: Optional[torch.device] = None,
264
+ dtype: Optional[torch.dtype] = None,
265
+ mean: bool = True,
266
+ ) -> None:
267
+
268
+ super().__init__()
269
+
270
+ self.in_features = in_features
271
+ self.eps = eps
272
+ self.elementwise_affine = elementwise_affine
273
+ self.mean = mean
274
+ if self.elementwise_affine:
275
+ self.weight = Parameter(
276
+ torch.empty(in_features, device=device, dtype=dtype)
277
+ )
278
+ if bias:
279
+ self.bias = Parameter(
280
+ torch.empty(in_features, device=device, dtype=dtype)
281
+ )
282
+ else:
283
+ self.register_parameter("bias", None)
284
+ else:
285
+ self.register_parameter("weight", None)
286
+ self.register_parameter("bias", None)
287
+
288
+ self.reset_parameters()
289
+
290
+ def reset_parameters(self) -> None:
291
+ if self.elementwise_affine:
292
+ init.ones_(self.weight)
293
+ if self.bias is not None:
294
+ init.zeros_(self.bias)
295
+
296
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
297
+ return _layer_norm(
298
+ input, weight=self.weight, bias=self.bias, eps=self.eps, mean=self.mean
299
+ )
300
+
301
+ def extra_repr(self) -> str:
302
+ return "eps={eps}, elementwise_affine={elementwise_affine}".format(
303
+ **self.__dict__
304
+ )
305
+
306
+
307
+ def _layer_norm(
308
+ tensor: torch.Tensor,
309
+ weight: Optional[torch.Tensor],
310
+ bias: Optional[torch.Tensor],
311
+ eps: float,
312
+ mean: bool,
313
+ ) -> torch.Tensor:
314
+ """
315
+ Apply layer normalization to the input `tensor`.
316
+
317
+ See :py:class:`torch.nn.functional.layer_norm` for more information on the
318
+ other parameters.
319
+
320
+ In addition to base torch implementation, this function has the added control of
321
+ whether or not the mean over the properties (final) dimension is subtracted from the
322
+ input tensor.
323
+
324
+ :param mean: whether or not to subtract from the input :param tensor: the mean over
325
+ the dimensions not included in :param normalized_shape:.
326
+
327
+ :return: :py:class:`torch.Tensor` with layer normalization applied.
328
+ """
329
+ # Contract over all dimensions except properties
330
+ dim: List[int] = list(range(0, len(tensor.shape) - 1))
331
+
332
+ if mean: # subtract mean over properties dimension
333
+ tensor_out = tensor - torch.mean(tensor, dim=dim)
334
+ else:
335
+ tensor_out = tensor
336
+
337
+ # Divide by standard deviation over properties dimension. `correction=0` for biased
338
+ # estimator, in accordance with the torch implementation.
339
+ tensor_out /= torch.sqrt(
340
+ torch.var(tensor, dim=dim, correction=0, keepdim=True) + eps
341
+ )
342
+
343
+ if weight is not None: # apply affine transformation
344
+ tensor_out *= weight
345
+
346
+ if bias is not None: # apply bias
347
+ tensor_out += bias
348
+
349
+ return tensor_out