metatensor-learn 0.3.1__tar.gz → 0.4.0__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 (37) hide show
  1. {metatensor_learn-0.3.1/metatensor_learn.egg-info → metatensor_learn-0.4.0}/PKG-INFO +7 -6
  2. metatensor_learn-0.4.0/git_version_info +2 -0
  3. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/_backend.py +23 -21
  4. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/data/_namedtuple.py +1 -1
  5. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/data/collate.py +9 -7
  6. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/__init__.py +1 -0
  7. metatensor_learn-0.4.0/metatensor/learn/nn/_module.py +410 -0
  8. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/equivariant_transformation.py +10 -10
  9. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/layer_norm.py +9 -10
  10. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/linear.py +5 -5
  11. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/module_map.py +29 -74
  12. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/relu.py +6 -6
  13. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/sequential.py +6 -4
  14. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/silu.py +6 -6
  15. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/tanh.py +6 -6
  16. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0/metatensor_learn.egg-info}/PKG-INFO +7 -6
  17. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/SOURCES.txt +1 -0
  18. metatensor_learn-0.4.0/metatensor_learn.egg-info/requires.txt +2 -0
  19. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/pyproject.toml +4 -4
  20. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/setup.py +7 -3
  21. metatensor_learn-0.3.1/git_version_info +0 -2
  22. metatensor_learn-0.3.1/metatensor_learn.egg-info/requires.txt +0 -1
  23. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/AUTHORS +0 -0
  24. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/LICENSE +0 -0
  25. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/MANIFEST.in +0 -0
  26. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/README.rst +0 -0
  27. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/__init__.py +0 -0
  28. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/_dispatch.py +0 -0
  29. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/data/__init__.py +0 -0
  30. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/data/dataloader.py +0 -0
  31. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/data/dataset.py +0 -0
  32. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor/learn/nn/_utils.py +0 -0
  33. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/dependency_links.txt +0 -0
  34. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/top_level.txt +0 -0
  35. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/zip-safe +0 -0
  36. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/setup.cfg +0 -0
  37. {metatensor_learn-0.3.1 → metatensor_learn-0.4.0}/tests/test_dummmy.py +0 -0
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: metatensor-learn
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
5
  Author: Guillaume Fraux, Philip Loche, Filippo Bigi, Joseph W. Abbott, Davide Tisi, Alexander Goscinski, Michele Ceriotti
6
- License: BSD-3-Clause
6
+ License-Expression: BSD-3-Clause
7
7
  Project-URL: homepage, https://docs.metatensor.org/latest/
8
8
  Project-URL: documentation, https://docs.metatensor.org/latest/
9
9
  Project-URL: repository, https://github.com/metatensor/metatensor
@@ -11,7 +11,6 @@ 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
14
- Classifier: License :: OSI Approved :: BSD License
15
14
  Classifier: Operating System :: POSIX
16
15
  Classifier: Operating System :: MacOS :: MacOS X
17
16
  Classifier: Operating System :: Microsoft :: Windows
@@ -23,12 +22,14 @@ Classifier: Topic :: Scientific/Engineering :: Chemistry
23
22
  Classifier: Topic :: Scientific/Engineering :: Physics
24
23
  Classifier: Topic :: Software Development :: Libraries
25
24
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
- Requires-Python: >=3.9
25
+ Requires-Python: >=3.10
27
26
  Description-Content-Type: text/x-rst
28
27
  License-File: LICENSE
29
28
  License-File: AUTHORS
30
- Requires-Dist: metatensor-operations<0.4.0,>=0.3.0
29
+ Requires-Dist: metatensor-operations<0.5.0,>=0.4.0
30
+ Requires-Dist: metatensor-core<0.2.0,>=0.1.15
31
31
  Dynamic: author
32
+ Dynamic: license-file
32
33
  Dynamic: requires-dist
33
34
 
34
35
  metatensor-learn
@@ -0,0 +1,2 @@
1
+ 0
2
+ git.3b4a9b2
@@ -43,26 +43,28 @@ def _version_at_least(version, expected):
43
43
  return version >= expected
44
44
 
45
45
 
46
- def is_metatensor_class(value, typ):
47
- assert typ in (Labels, TensorBlock, TensorMap)
48
-
49
- if isinstance(value, typ):
50
- return True
46
+ # Warning: this function (as all functions in this module) is part of the public API of
47
+ # metatensor-learn, updating it means that new versions of metatensor-torch will not be
48
+ # able to work with old versions of metatensor-learn, so any update should be treated as
49
+ # a breaking change.
50
+ def isinstance_metatensor(value, typename):
51
+ assert typename in ("Labels", "TensorBlock", "TensorMap")
52
+
53
+ if _HAS_TORCH and isinstance(value, torch.ScriptObject):
54
+ is_metatensor_torch_class = "metatensor" in str(value._type())
55
+ if is_metatensor_torch_class:
56
+ warnings.warn(
57
+ "Trying to use code from ``metatensor.learn`` with objects from "
58
+ "metatensor-torch, you should use the code from "
59
+ "`metatensor.torch.learn` instead",
60
+ stacklevel=2,
61
+ )
62
+
63
+ if typename == "Labels":
64
+ return isinstance(value, Labels)
65
+ elif typename == "TensorBlock":
66
+ return isinstance(value, TensorBlock)
67
+ elif typename == "TensorMap":
68
+ return isinstance(value, TensorMap)
51
69
  else:
52
- if _HAS_TORCH and isinstance(value, torch.ScriptObject):
53
- if _version_at_least(torch.__version__, "2.1.0"):
54
- # _type() is only working for torch >= 2.1
55
- is_metatensor_torch_class = "metatensor" in str(value._type())
56
- else:
57
- # we don't know, it's fine
58
- is_metatensor_torch_class = False
59
-
60
- if is_metatensor_torch_class:
61
- warnings.warn(
62
- "Trying to use code from ``metatensor.learn`` with objects from "
63
- "metatensor-torch, you should use the code from "
64
- "`metatensor.torch.learn` instead",
65
- stacklevel=2,
66
- )
67
-
68
70
  return False
@@ -83,7 +83,7 @@ def namedtuple(typename, field_names):
83
83
 
84
84
  def _asdict(self):
85
85
  "Return a new dict which maps field names to their values."
86
- return _dict(_zip(self._fields, self))
86
+ return _dict(_zip(self._fields, self, strict=True))
87
87
 
88
88
  def __getnewargs__(self):
89
89
  "Return self as a plain tuple. Used by copy and pickle."
@@ -31,7 +31,7 @@ def group(batch: List[NamedTuple]) -> NamedTuple:
31
31
  :return: a named tuple, with the named fields the same as in the original
32
32
  samples in the batch, but with the samples grouped by data field.
33
33
  """
34
- return namedtuple("Batch", batch[0]._fields)(*list(zip(*batch)))
34
+ return namedtuple("Batch", batch[0]._fields)(*list(zip(*batch, strict=True)))
35
35
 
36
36
 
37
37
  def group_and_join(
@@ -87,20 +87,22 @@ def group_and_join(
87
87
  fields_to_join = names
88
88
  if join_kwargs is None:
89
89
  join_kwargs = {}
90
- for name, field in zip(names, list(zip(*batch))):
90
+ for name, field in zip(names, list(zip(*batch, strict=True)), strict=True):
91
91
  if name == "sample_id": # special case, keep as is
92
92
  data.append(field)
93
93
  continue
94
94
 
95
95
  if name in fields_to_join: # Join tensors if requested
96
96
  if isinstance(field[0], TensorMap):
97
- # metatensor.TensorMap type
97
+ # metatensor.TensorMap
98
98
  data.append(metatensor.join(field, axis="samples", **join_kwargs))
99
- elif isinstance(field[0], torch.ScriptObject) and field[0]._has_method(
100
- "keys_to_properties"
101
- ): # inferred metatensor.torch.TensorMap type
99
+ elif (
100
+ isinstance(field[0], torch.ScriptObject)
101
+ and field[0]._type().name() == "TensorMap"
102
+ ):
103
+ # metatensor.torch.TensorMap
102
104
  data.append(metatensor.torch.join(field, axis="samples", **join_kwargs))
103
- elif isinstance(field[0], torch.Tensor): # torch.Tensor type
105
+ elif isinstance(field[0], torch.Tensor):
104
106
  data.append(torch.vstack(field))
105
107
  else:
106
108
  data.append(field)
@@ -1,3 +1,4 @@
1
+ from ._module import Module # noqa: F401
1
2
  from .equivariant_transformation import EquivariantTransformation # noqa: F401
2
3
  from .layer_norm import InvariantLayerNorm, LayerNorm # noqa: F401
3
4
  from .linear import EquivariantLinear, Linear # noqa: F401
@@ -0,0 +1,410 @@
1
+ import numpy as np
2
+ import torch
3
+
4
+ from .._backend import Labels, TensorBlock, TensorMap, isinstance_metatensor
5
+
6
+
7
+ class Module(torch.nn.Module):
8
+ """
9
+ This class should be used instead of :py:class:`torch.nn.Module` when your module
10
+ contains data stored inside :py:class:`metatensor.torch.Labels`,
11
+ :py:class:`metatensor.torch.TensorBlock` or :py:class:`metatensor.torch.TensorMap`.
12
+
13
+ It ensures that this data is properly moved to other dtype and devices when calling
14
+ ``.to()``, ``.cuda()``, ``.float()`` and other related functions. We also handle the
15
+ corresponding data in ``state_dict()`` and ``load_state_dict()``.
16
+
17
+ We support storing these class either directly as attributes (``self.name = ...``),
18
+ or inside arbitrarily nested dict, list, or tuple (``self.name = {"dict": [...]}``).
19
+
20
+ Below is an example creating a custom linear model, that stores the output
21
+ ``properties`` as an attribute. The corresponding labels will automatically be moved
22
+ on device at the same time as the module.
23
+
24
+ >>> import torch
25
+ >>> from typing import List
26
+ >>> from metatensor.torch.learn import nn
27
+ >>> from metatensor.torch import Labels, TensorMap, TensorBlock
28
+ >>>
29
+ >>> class CustomLinear(nn.Module):
30
+ ... def __init__(self, in_features, out_features):
31
+ ... super().__init__()
32
+ ... self.properties = Labels(
33
+ ... ["out_features"], torch.arange(out_features).reshape(-1, 1)
34
+ ... )
35
+ ... self.linear = torch.nn.Linear(in_features, out_features)
36
+ ...
37
+ ... def forward(self, tensor: TensorMap) -> TensorMap:
38
+ ... blocks: List[TensorBlock] = []
39
+ ... for block in tensor:
40
+ ... new_values = self.linear(block.values)
41
+ ... new_block = TensorBlock(
42
+ ... values,
43
+ ... block.samples,
44
+ ... block.components,
45
+ ... self.properties,
46
+ ... )
47
+ ... blocks.append(new_block)
48
+ ... return TensorBlock(tensor.keys, blocks)
49
+ """
50
+
51
+ def __init__(self):
52
+ """"""
53
+ super().__init__()
54
+ self.register_buffer("_mts_helper", torch.zeros(0))
55
+
56
+ def get_extra_state(self):
57
+ extra = {}
58
+ for name, value in self.__dict__.items():
59
+ serialized_value, needs_storing = _serialize_metatensor(value)
60
+ if needs_storing:
61
+ extra[name] = serialized_value
62
+ return extra
63
+
64
+ def set_extra_state(self, extra):
65
+ for name, value in extra.items():
66
+ deserialized_value, needs_storing = _deserialize_metatensor(value)
67
+ if needs_storing:
68
+ self.__setattr__(name, deserialized_value)
69
+
70
+ # _apply is used to define all of the data movement functions (`to()`, `cuda()`,
71
+ # `double()`, …), so we only need to override this one.
72
+ def _apply(self, fn, recurse=True):
73
+ result = super()._apply(fn, recurse=recurse)
74
+ # the _apply call should have moved everything to the correct device/dtype,
75
+ # including our `_mts_helper` buffer. Now we can move all metatensor data to
76
+ # the same device/dtype
77
+ device = self._mts_helper.device
78
+ dtype = self._mts_helper.dtype
79
+
80
+ for name, value in self.__dict__.items():
81
+ value, changed = _metatensor_data_to(value, dtype=dtype, device=device)
82
+ if changed:
83
+ self.__dict__[name] = value
84
+
85
+ return result
86
+
87
+
88
+ # WARNING: this is duplicated in metatensor.torch._module, make sure to change both
89
+ # versions of the function at the same time
90
+ def _metatensor_data_to(value, dtype, device):
91
+ """
92
+ Convert metatensor data to the given dtype/device, returning the new data and a
93
+ bool to indicate if the value was modified.
94
+ """
95
+ if isinstance_metatensor(value, "Labels"):
96
+ return value.to(device=device), True
97
+ elif isinstance_metatensor(value, "TensorBlock"):
98
+ return value.to(device=device, dtype=dtype), True
99
+ elif isinstance_metatensor(value, "TensorMap"):
100
+ return value.to(device=device, dtype=dtype), True
101
+ elif isinstance(value, dict):
102
+ if len(value) == 0:
103
+ return value, True
104
+
105
+ updated = {}
106
+ all_changed = True
107
+ some_changed = False
108
+ for name, dict_value in value.items():
109
+ updated_value, changed = _metatensor_data_to(dict_value, dtype, device)
110
+ all_changed = all_changed and changed
111
+ some_changed = some_changed or changed
112
+ updated[name] = updated_value
113
+
114
+ if some_changed:
115
+ if not all_changed:
116
+ # we got some unexpected type somewhere
117
+ raise ValueError(
118
+ "dicts containing both metatensor and non-metatensor data as "
119
+ "values are not supported"
120
+ )
121
+ return updated, True
122
+
123
+ elif isinstance(value, list):
124
+ if len(value) == 0:
125
+ return value, True
126
+
127
+ updated = []
128
+ all_changed = True
129
+ some_changed = False
130
+ for list_value in value:
131
+ updated_value, changed = _metatensor_data_to(list_value, dtype, device)
132
+ all_changed = all_changed and changed
133
+ some_changed = some_changed or changed
134
+ updated.append(updated_value)
135
+
136
+ if some_changed:
137
+ if not all_changed:
138
+ # we got some unexpected type somewhere
139
+ raise ValueError(
140
+ "lists containing both metatensor and non-metatensor data "
141
+ "are not supported"
142
+ )
143
+ return updated, True
144
+
145
+ elif isinstance(value, tuple):
146
+ if len(value) == 0:
147
+ return value, True
148
+
149
+ updated = []
150
+ some_changed = False
151
+ for tuple_value in value:
152
+ updated_value, changed = _metatensor_data_to(tuple_value, dtype, device)
153
+ some_changed = some_changed or changed
154
+ updated.append(updated_value)
155
+
156
+ if some_changed:
157
+ return tuple(updated), True
158
+
159
+ return value, False
160
+
161
+
162
+ def _serialize_metatensor(value):
163
+ """
164
+ If ``value`` is an instance of one of the metatensor classes (Labels, TensorBlock,
165
+ TensorMap), transform it into a format that can more easily be used in a PyTorch
166
+ state dict.
167
+
168
+ This format is a tuple with three elements: ``(class_name, buffer, tensor)``, where
169
+ the class name is a string (``"metatensor.Labels"``, ``"metatensor.TensorBlock"``,
170
+ or ``"metatensor.TensorMap"``); the buffer is the result of
171
+ ``metatensor.save_buffer``; and the tensor is an empty tensor carrying information
172
+ about the origin device and dtype of the data.
173
+
174
+ If ``value`` is an (arbitrarily nested) container with metatensor data (i.e.
175
+ ``Dict[..., Labels]``, ``List[Tuple[Labels, TensorBlock]]``, etc.), then the
176
+ metatensor data is replaced in place with the data described above.
177
+
178
+ This function then returns the serialized data, and a boolean indicating if
179
+ ``value`` contained metatensor data at any point.
180
+ """
181
+ if isinstance_metatensor(value, "Labels"):
182
+ serialized = (
183
+ "metatensor.Labels",
184
+ _buffer_to_picklable(value.save_buffer()),
185
+ _empty_tensor_like(value.values),
186
+ )
187
+ return serialized, True
188
+
189
+ elif isinstance_metatensor(value, "TensorBlock"):
190
+ # we only support torch Tensors as the block values
191
+ assert isinstance(value.values, torch.Tensor), (
192
+ "data must be stored in torch Tensors"
193
+ )
194
+ serialized = (
195
+ "metatensor.TensorBlock",
196
+ # until we have https://github.com/metatensor/metatensor/issues/775,
197
+ # move everything to CPU/float64
198
+ _buffer_to_picklable(
199
+ value.to(device="cpu").to(dtype=torch.float64).save_buffer()
200
+ ),
201
+ _empty_tensor_like(value.values),
202
+ )
203
+ return serialized, True
204
+
205
+ elif isinstance_metatensor(value, "TensorMap"):
206
+ if len(value) == 0:
207
+ empty_tensor = _empty_tensor_like(value.keys.values)
208
+ else:
209
+ # we only support torch Tensors as the block values
210
+ assert isinstance(value.block(0).values, torch.Tensor), (
211
+ "data must be stored in torch Tensors"
212
+ )
213
+ empty_tensor = _empty_tensor_like(value.block(0).values)
214
+
215
+ serialized = (
216
+ "metatensor.TensorMap",
217
+ # same as above
218
+ _buffer_to_picklable(
219
+ value.to(device="cpu").to(dtype=torch.float64).save_buffer()
220
+ ),
221
+ empty_tensor,
222
+ )
223
+ return serialized, True
224
+
225
+ elif isinstance(value, dict):
226
+ if len(value) == 0:
227
+ return value, True
228
+
229
+ serialized = {}
230
+ all_contains_mts = True
231
+ some_contains_mts = False
232
+ for key, dict_value in value.items():
233
+ serialized_value, contains_mts = _serialize_metatensor(dict_value)
234
+ all_contains_mts = all_contains_mts and contains_mts
235
+ some_contains_mts = some_contains_mts or contains_mts
236
+ serialized[key] = serialized_value
237
+
238
+ if some_contains_mts:
239
+ if not all_contains_mts:
240
+ # we got some unexpected type somewhere
241
+ raise TypeError(
242
+ "Dict containing both metatensor and other data together "
243
+ "are not supported"
244
+ )
245
+ return serialized, True
246
+
247
+ elif isinstance(value, list):
248
+ if len(value) == 0:
249
+ return value, True
250
+
251
+ serialized = []
252
+ all_contains_mts = True
253
+ some_contains_mts = False
254
+ for list_value in value:
255
+ serialized_value, contains_mts = _serialize_metatensor(list_value)
256
+ all_contains_mts = all_contains_mts and contains_mts
257
+ some_contains_mts = some_contains_mts or contains_mts
258
+ serialized.append(serialized_value)
259
+
260
+ if some_contains_mts:
261
+ if not all_contains_mts:
262
+ # we got some unexpected type somewhere
263
+ raise TypeError(
264
+ "List containing both metatensor and other data together "
265
+ "are not supported"
266
+ )
267
+ return serialized, True
268
+
269
+ elif isinstance(value, tuple):
270
+ if len(value) == 0:
271
+ return value, True
272
+
273
+ serialized = []
274
+ some_contains_mts = False
275
+ for tuple_value in value:
276
+ serialized_value, contains_mts = _serialize_metatensor(tuple_value)
277
+ some_contains_mts = some_contains_mts or contains_mts
278
+ serialized.append(serialized_value)
279
+
280
+ if some_contains_mts:
281
+ return tuple(serialized), True
282
+
283
+ return None, False
284
+
285
+
286
+ def _empty_tensor_like(value):
287
+ """Get a tensor with no data and the same dtype/device as ``value``"""
288
+ if isinstance(value, torch.Tensor):
289
+ return torch.empty(0, dtype=value.dtype, device=value.device)
290
+ else:
291
+ assert isinstance(value, np.ndarray)
292
+ array = np.empty(0, dtype=value.dtype)
293
+ return torch.from_numpy(array)
294
+
295
+
296
+ def _buffer_to_picklable(buffer):
297
+ """
298
+ Convert the buffer type used in metatensor-core (memoryview) to something pickle can
299
+ handle while leaving the buffer type in metatensor-torch (torch.Tensor) alone
300
+ """
301
+ if isinstance(buffer, torch.Tensor):
302
+ return buffer
303
+ else:
304
+ return buffer.tobytes()
305
+
306
+
307
+ def _deserialize_metatensor(value):
308
+ """
309
+ This function does the inverse of ``_serialize_metatensor``, re-creating metatensor
310
+ data from the tuple representation.
311
+
312
+ The function returns the deserialized data, and a boolean indicating if ``value``
313
+ contains some metatensor data somewhere.
314
+ """
315
+
316
+ if (
317
+ isinstance(value, tuple)
318
+ and len(value) == 3
319
+ and isinstance(value[0], str)
320
+ and value[0].startswith("metatensor.")
321
+ ):
322
+ class_name, buffer, dtype_device_tensor = value
323
+
324
+ if isinstance(buffer, torch.Tensor):
325
+ buffer = buffer.to(device="cpu")
326
+
327
+ if class_name == "metatensor.Labels":
328
+ labels = Labels.load_buffer(buffer).to(dtype_device_tensor.device)
329
+ return labels, True
330
+
331
+ elif class_name == "metatensor.TensorBlock":
332
+ block = TensorBlock.load_buffer(buffer)
333
+ block = block.to(
334
+ dtype=dtype_device_tensor.dtype,
335
+ device=dtype_device_tensor.device,
336
+ arrays="torch",
337
+ )
338
+ return block, True
339
+
340
+ elif class_name == "metatensor.TensorMap":
341
+ tensor = TensorMap.load_buffer(buffer)
342
+ tensor = tensor.to(
343
+ dtype=dtype_device_tensor.dtype,
344
+ device=dtype_device_tensor.device,
345
+ arrays="torch",
346
+ )
347
+ return tensor, True
348
+
349
+ else:
350
+ raise ValueError(f"got unexpected class name: '{class_name}'")
351
+
352
+ elif isinstance(value, dict):
353
+ if len(value) == 0:
354
+ return value, True
355
+
356
+ deserialized = {}
357
+ all_contains_mts = True
358
+ some_contains_mts = False
359
+ for name, dict_value in value.items():
360
+ deserialized_value, contains_mts = _deserialize_metatensor(dict_value)
361
+ all_contains_mts = all_contains_mts and contains_mts
362
+ some_contains_mts = some_contains_mts or contains_mts
363
+ deserialized[name] = deserialized_value
364
+
365
+ if some_contains_mts:
366
+ if not all_contains_mts:
367
+ # we got some unexpected type somewhere
368
+ raise TypeError(
369
+ "Dict containing both metatensor and other data together "
370
+ "are not supported"
371
+ )
372
+ return deserialized, True
373
+
374
+ elif isinstance(value, list):
375
+ if len(value) == 0:
376
+ return value, True
377
+
378
+ deserialized = []
379
+ all_contains_mts = True
380
+ some_contains_mts = False
381
+ for list_value in value:
382
+ deserialized_value, contains_mts = _deserialize_metatensor(list_value)
383
+ all_contains_mts = all_contains_mts and contains_mts
384
+ some_contains_mts = some_contains_mts or contains_mts
385
+ deserialized.append(deserialized_value)
386
+
387
+ if some_contains_mts:
388
+ if not all_contains_mts:
389
+ # we got some unexpected type somewhere
390
+ raise TypeError(
391
+ "List containing both metatensor and other data together "
392
+ "are not supported"
393
+ )
394
+ return deserialized, True
395
+
396
+ elif isinstance(value, tuple):
397
+ if len(value) == 0:
398
+ return value, True
399
+
400
+ deserialized = []
401
+ some_contains_mts = False
402
+ for tuple_value in value:
403
+ deserialized_value, contains_mts = _deserialize_metatensor(tuple_value)
404
+ some_contains_mts = some_contains_mts or contains_mts
405
+ deserialized.append(deserialized_value)
406
+
407
+ if some_contains_mts:
408
+ return tuple(deserialized), True
409
+
410
+ return None, False
@@ -4,13 +4,14 @@ import torch
4
4
 
5
5
  from .._backend import Labels, TensorMap
6
6
  from .._dispatch import int_array_like
7
+ from ._module import Module
7
8
  from ._utils import _check_module_map_parameter
8
9
  from .module_map import ModuleMap
9
10
 
10
11
 
11
- class EquivariantTransformation(torch.nn.Module):
12
+ class EquivariantTransformation(Module):
12
13
  """
13
- A custom :py:class:`torch.nn.Module` that applies an arbitrary shape- and
14
+ A custom :py:class:`metatensor.learn.nn.Module` that applies an arbitrary shape- and
14
15
  equivariance-preserving transformation to an input :py:class:`TensorMap`.
15
16
 
16
17
  For invariant blocks (specified with ``invariant_keys``), the respective
@@ -18,19 +19,18 @@ class EquivariantTransformation(torch.nn.Module):
18
19
  an invariant multiplier is created, applying the transformation to the norm of the
19
20
  block over the component dimensions.
20
21
 
21
- :param modules: a :py:class:`list` of :py:class:`torch.nn.Module` containing the
22
- transformations to be applied to each block indexed by
23
- :param in_keys:. Transformations for invariant and covariant blocks differ. See
24
- above.
22
+ :param modules: a :py:class:`list` of :py:class:`torch.nn.Module` or
23
+ :py:class:`metatensor.nn.Module` containing the transformations to be applied to
24
+ each block indexed by :param in_keys:. Transformations for invariant and
25
+ covariant blocks differ. See above.
25
26
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
26
27
  :py:class:`TensorMap` in the :py:meth:`forward` method.
27
28
  :param in_features: :py:class:`list` of :py:class:`int`, the number of features in
28
29
  the input tensor for each block indexed by the keys in :param in_keys:. If
29
30
  passed as a single value, the same number of features is assumed for all blocks.
30
31
  :param out_properties: :py:class:`list` of :py:class`Labels` (optional), the
31
- properties labels
32
- of the output. By default the output properties are relabeled using
33
- Labels.range.
32
+ properties labels of the output. By default the output properties are relabeled
33
+ using ``Labels.range``.
34
34
  :param invariant_keys: a :py:class:`Labels` object that is used to select the
35
35
  invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
36
36
  to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
@@ -169,7 +169,7 @@ class EquivariantTransformation(torch.nn.Module):
169
169
  return self.module_map(tensor)
170
170
 
171
171
 
172
- class _CovariantTransform(torch.nn.Module):
172
+ class _CovariantTransform(Module):
173
173
  """
174
174
  Applies an arbitrary shape-preserving transformation defined in ``module`` to a
175
175
  3-dimensional tensor in a way that preserves equivariance. The transformation is
@@ -7,11 +7,10 @@ respectively.
7
7
  from typing import List, Optional
8
8
 
9
9
  import torch
10
- from torch.nn import Module, init
11
- from torch.nn.parameter import Parameter
12
10
 
13
11
  from .._backend import Labels, TensorMap
14
12
  from .._dispatch import int_array_like
13
+ from ._module import Module
15
14
  from ._utils import _check_module_map_parameter
16
15
  from .module_map import ModuleMap
17
16
 
@@ -32,7 +31,7 @@ class LayerNorm(Module):
32
31
  The extra parameter :param mean: controls whether or not the mean over these
33
32
  dimensions is subtracted from the input tensor in the transformation.
34
33
 
35
- Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
34
+ Refer to the :py:class:`torch.nn.LayerNorm` documentation for a more detailed
36
35
  description of the other parameters.
37
36
 
38
37
  Each parameter is passed as a single value of its expected type, which is used
@@ -43,7 +42,7 @@ class LayerNorm(Module):
43
42
  :param in_features: list of int, the number of features in the input tensor for each
44
43
  block indexed by the keys in :param in_keys:. If passed as a single value, the
45
44
  same number of features is assumed for all blocks.
46
- :param out_properties: list of :py:class`Labels` (optional), the properties labels
45
+ :param out_properties: list of :py:class:`Labels` (optional), the properties labels
47
46
  of the output. By default (if none) the output properties are relabeled using
48
47
  Labels.range.
49
48
  :mean bool: whether or not to subtract the mean over all dimensions except the
@@ -126,7 +125,7 @@ class InvariantLayerNorm(Module):
126
125
  The extra parameter :param mean: controls whether or not the mean over these
127
126
  dimensions is subtracted from the input tensor in the transformation.
128
127
 
129
- Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
128
+ Refer to the :py:class:`torch.nn.LayerNorm` documentation for a more detailed
130
129
  description of the other parameters.
131
130
 
132
131
  Each parameter is passed as a single value of its expected type, which is used
@@ -137,7 +136,7 @@ class InvariantLayerNorm(Module):
137
136
  :param in_features: list of int, the number of features in the input tensor for each
138
137
  block indexed by the keys in :param in_keys:. If passed as a single value, the
139
138
  same number of features is assumed for all blocks.
140
- :param out_properties: list of :py:class`Labels` (optional), the properties labels
139
+ :param out_properties: list of :py:class:`Labels` (optional), the properties labels
141
140
  of the output. By default (if none) the output properties are relabeled using
142
141
  Labels.range.
143
142
  :param invariant_keys: a :py:class:`Labels` object that is used to select the
@@ -277,11 +276,11 @@ class _LayerNorm(Module):
277
276
  self.elementwise_affine = elementwise_affine
278
277
  self.mean = mean
279
278
  if self.elementwise_affine:
280
- self.weight = Parameter(
279
+ self.weight = torch.nn.Parameter(
281
280
  torch.empty(in_features, device=device, dtype=dtype)
282
281
  )
283
282
  if bias:
284
- self.bias = Parameter(
283
+ self.bias = torch.nn.Parameter(
285
284
  torch.empty(in_features, device=device, dtype=dtype)
286
285
  )
287
286
  else:
@@ -294,9 +293,9 @@ class _LayerNorm(Module):
294
293
 
295
294
  def reset_parameters(self) -> None:
296
295
  if self.elementwise_affine:
297
- init.ones_(self.weight)
296
+ torch.nn.init.ones_(self.weight)
298
297
  if self.bias is not None:
299
- init.zeros_(self.bias)
298
+ torch.nn.init.zeros_(self.bias)
300
299
 
301
300
  def forward(self, input: torch.Tensor) -> torch.Tensor:
302
301
  return _layer_norm(