metatensor-learn 0.3.2__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.
- {metatensor_learn-0.3.2/metatensor_learn.egg-info → metatensor_learn-0.4.0}/PKG-INFO +4 -3
- metatensor_learn-0.4.0/git_version_info +2 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/_backend.py +4 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/data/_namedtuple.py +1 -1
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/data/collate.py +9 -7
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/__init__.py +1 -0
- metatensor_learn-0.4.0/metatensor/learn/nn/_module.py +410 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/equivariant_transformation.py +10 -10
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/layer_norm.py +9 -10
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/linear.py +5 -5
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/module_map.py +29 -74
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/relu.py +6 -6
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/sequential.py +4 -2
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/silu.py +6 -6
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/tanh.py +6 -6
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0/metatensor_learn.egg-info}/PKG-INFO +4 -3
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/SOURCES.txt +1 -0
- metatensor_learn-0.4.0/metatensor_learn.egg-info/requires.txt +2 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/pyproject.toml +2 -1
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/setup.py +7 -3
- metatensor_learn-0.3.2/git_version_info +0 -2
- metatensor_learn-0.3.2/metatensor_learn.egg-info/requires.txt +0 -1
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/AUTHORS +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/LICENSE +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/MANIFEST.in +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/README.rst +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/__init__.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/_dispatch.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/data/__init__.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/data/dataloader.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/data/dataset.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/_utils.py +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/dependency_links.txt +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/top_level.txt +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/zip-safe +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/setup.cfg +0 -0
- {metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/tests/test_dummmy.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: metatensor-learn
|
|
3
|
-
Version: 0.
|
|
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
6
|
License-Expression: BSD-3-Clause
|
|
@@ -22,11 +22,12 @@ Classifier: Topic :: Scientific/Engineering :: Chemistry
|
|
|
22
22
|
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
23
23
|
Classifier: Topic :: Software Development :: Libraries
|
|
24
24
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
-
Requires-Python: >=3.
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
26
|
Description-Content-Type: text/x-rst
|
|
27
27
|
License-File: LICENSE
|
|
28
28
|
License-File: AUTHORS
|
|
29
|
-
Requires-Dist: metatensor-operations<0.
|
|
29
|
+
Requires-Dist: metatensor-operations<0.5.0,>=0.4.0
|
|
30
|
+
Requires-Dist: metatensor-core<0.2.0,>=0.1.15
|
|
30
31
|
Dynamic: author
|
|
31
32
|
Dynamic: license-file
|
|
32
33
|
Dynamic: requires-dist
|
|
@@ -43,6 +43,10 @@ def _version_at_least(version, expected):
|
|
|
43
43
|
return version >= expected
|
|
44
44
|
|
|
45
45
|
|
|
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.
|
|
46
50
|
def isinstance_metatensor(value, typename):
|
|
47
51
|
assert typename in ("Labels", "TensorBlock", "TensorMap")
|
|
48
52
|
|
|
@@ -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
|
|
97
|
+
# metatensor.TensorMap
|
|
98
98
|
data.append(metatensor.join(field, axis="samples", **join_kwargs))
|
|
99
|
-
elif
|
|
100
|
-
|
|
101
|
-
|
|
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):
|
|
105
|
+
elif isinstance(field[0], torch.Tensor):
|
|
104
106
|
data.append(torch.vstack(field))
|
|
105
107
|
else:
|
|
106
108
|
data.append(field)
|
|
@@ -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
|
{metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor/learn/nn/equivariant_transformation.py
RENAMED
|
@@ -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(
|
|
12
|
+
class EquivariantTransformation(Module):
|
|
12
13
|
"""
|
|
13
|
-
A custom :py:class:`
|
|
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`
|
|
22
|
-
transformations to be applied to
|
|
23
|
-
:param in_keys:. Transformations for invariant and
|
|
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
|
-
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
from typing import List, Optional, Union
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
|
-
from torch.nn import Module
|
|
5
4
|
|
|
6
5
|
from .._backend import Labels, TensorMap
|
|
7
6
|
from .._dispatch import int_array_like
|
|
7
|
+
from ._module import Module
|
|
8
8
|
from ._utils import _check_module_map_parameter
|
|
9
9
|
from .module_map import ModuleMap
|
|
10
10
|
|
|
@@ -17,7 +17,7 @@ class Linear(Module):
|
|
|
17
17
|
Applies a linear transformation to each block of a :py:class:`TensorMap` passed to
|
|
18
18
|
its forward method, indexed by :param in_keys:.
|
|
19
19
|
|
|
20
|
-
Refer to the :py:class
|
|
20
|
+
Refer to the :py:class:`torch.nn.Linear` documentation for a more detailed
|
|
21
21
|
description of the other parameters.
|
|
22
22
|
|
|
23
23
|
Each parameter is passed as a single value of its expected type, which is used
|
|
@@ -31,7 +31,7 @@ class Linear(Module):
|
|
|
31
31
|
:param out_features: :py:class:`int` or :py:class:`lint` of :py:class:`int`, the
|
|
32
32
|
number of output features for each block. If passed as a single value, the same
|
|
33
33
|
feature size is taken for all blocks.
|
|
34
|
-
:param out_properties: list of :py:class
|
|
34
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
35
35
|
of the output. By default the output properties are relabeled using
|
|
36
36
|
Labels.range. If provided, :param out_features: can be inferred and need not be
|
|
37
37
|
provided.
|
|
@@ -97,7 +97,7 @@ class EquivariantLinear(Module):
|
|
|
97
97
|
Applies a linear transformation to each block of a :py:class:`TensorMap` passed to
|
|
98
98
|
its forward method, indexed by :param in_keys:.
|
|
99
99
|
|
|
100
|
-
Refer to the :py:class
|
|
100
|
+
Refer to the :py:class:`torch.nn.Linear` documentation for a more detailed
|
|
101
101
|
description of the other parameters.
|
|
102
102
|
|
|
103
103
|
For :py:class:`EquivariantLinear`, by contrast to :py:class:`Linear`, the parameter
|
|
@@ -112,7 +112,7 @@ class EquivariantLinear(Module):
|
|
|
112
112
|
:param out_features: :py:class:`int` or :py:class:`lint` of :py:class:`int`, the
|
|
113
113
|
number of output features for each block. If passed as a single value, the same
|
|
114
114
|
feature size is taken for all blocks.
|
|
115
|
-
:param out_properties: list of :py:class
|
|
115
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
116
116
|
of the output. By default the output properties are relabeled using
|
|
117
117
|
Labels.range. If provided, :param out_features: can be inferred and need not be
|
|
118
118
|
provided.
|
|
@@ -2,11 +2,11 @@ from copy import deepcopy
|
|
|
2
2
|
from typing import List, Optional, Union
|
|
3
3
|
|
|
4
4
|
import torch
|
|
5
|
-
from torch.nn import Module, ModuleList
|
|
6
5
|
|
|
7
6
|
from metatensor.operations import _dispatch
|
|
8
7
|
|
|
9
8
|
from .._backend import Labels, LabelsEntry, TensorBlock, TensorMap
|
|
9
|
+
from ._module import Module
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
@torch.jit.interface
|
|
@@ -28,7 +28,7 @@ class ModuleMapInterface(torch.nn.Module):
|
|
|
28
28
|
pass
|
|
29
29
|
|
|
30
30
|
|
|
31
|
-
class ModuleMap(
|
|
31
|
+
class ModuleMap(Module):
|
|
32
32
|
"""
|
|
33
33
|
A class that imitates :py:class:`torch.nn.ModuleDict`. In its forward function the
|
|
34
34
|
module at position `i` given on construction by :param modules: is applied to the
|
|
@@ -42,7 +42,7 @@ class ModuleMap(ModuleList):
|
|
|
42
42
|
A sequence of modules applied in the :py:meth:`forward` function on the input
|
|
43
43
|
:py:class:`TensorMap`. Each module corresponds to one :py:class:`LabelsEntry` in
|
|
44
44
|
:param in_keys: that determines on which :py:class:`TensorBlock` the module is
|
|
45
|
-
applied on.
|
|
45
|
+
applied on. :param modules: and :param in_keys: must match in length.
|
|
46
46
|
|
|
47
47
|
:param out_properties:
|
|
48
48
|
A list of labels that is used to determine the properties labels of the
|
|
@@ -150,12 +150,15 @@ class ModuleMap(ModuleList):
|
|
|
150
150
|
modules: List[Module],
|
|
151
151
|
out_properties: Optional[List[Labels]] = None,
|
|
152
152
|
):
|
|
153
|
-
super().__init__(
|
|
153
|
+
super().__init__()
|
|
154
|
+
|
|
155
|
+
self.module_list = torch.nn.ModuleList(modules)
|
|
154
156
|
if len(in_keys) != len(modules):
|
|
155
157
|
raise ValueError(
|
|
156
158
|
"in_keys and modules must match in length, but found "
|
|
157
159
|
f"{len(in_keys) != len(modules)} [len(in_keys) != len(modules)]"
|
|
158
160
|
)
|
|
161
|
+
|
|
159
162
|
self._in_keys: Labels = in_keys
|
|
160
163
|
self._out_properties = out_properties
|
|
161
164
|
|
|
@@ -167,8 +170,9 @@ class ModuleMap(ModuleList):
|
|
|
167
170
|
out_properties: Optional[List[Labels]] = None,
|
|
168
171
|
):
|
|
169
172
|
"""
|
|
170
|
-
A wrapper around one :py:class:`torch.nn.Module`
|
|
171
|
-
module on each
|
|
173
|
+
A wrapper around one :py:class:`torch.nn.Module` or
|
|
174
|
+
:py:class:`metatensor.learn.nn.Module` applying the same type of module on each
|
|
175
|
+
tensor block.
|
|
172
176
|
|
|
173
177
|
:param in_keys:
|
|
174
178
|
A :py:class:`metatensor.Labels` object that determines the keys of the
|
|
@@ -177,10 +181,10 @@ class ModuleMap(ModuleList):
|
|
|
177
181
|
:param module:
|
|
178
182
|
The module that is applied on each block.
|
|
179
183
|
:param out_properties:
|
|
180
|
-
A list of labels that is used to determine the properties labels of
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
+
A list of labels that is used to determine the properties labels of the
|
|
185
|
+
output. Because a module could change the number of properties, the labels
|
|
186
|
+
of the properties cannot be persevered. By default the output properties are
|
|
187
|
+
relabeled using Labels.range with "_" as key.
|
|
184
188
|
|
|
185
189
|
>>> import torch
|
|
186
190
|
>>> import numpy as np
|
|
@@ -192,15 +196,7 @@ class ModuleMap(ModuleList):
|
|
|
192
196
|
... [3.0, 5.0, 6.0],
|
|
193
197
|
... ]
|
|
194
198
|
... ),
|
|
195
|
-
... samples=Labels(
|
|
196
|
-
... ["system", "atom"],
|
|
197
|
-
... np.array(
|
|
198
|
-
... [
|
|
199
|
-
... [0, 0],
|
|
200
|
-
... [0, 1],
|
|
201
|
-
... ]
|
|
202
|
-
... ),
|
|
203
|
-
... ),
|
|
199
|
+
... samples=Labels(["system", "atom"], np.array([[0, 0], [0, 1]])),
|
|
204
200
|
... components=[],
|
|
205
201
|
... properties=Labels(["properties"], np.array([[0], [1], [2]])),
|
|
206
202
|
... )
|
|
@@ -211,15 +207,7 @@ class ModuleMap(ModuleList):
|
|
|
211
207
|
... [1.0, 2.0, 8.0],
|
|
212
208
|
... ]
|
|
213
209
|
... ),
|
|
214
|
-
... samples=Labels(
|
|
215
|
-
... ["system", "atom"],
|
|
216
|
-
... np.array(
|
|
217
|
-
... [
|
|
218
|
-
... [0, 0],
|
|
219
|
-
... [0, 1],
|
|
220
|
-
... ]
|
|
221
|
-
... ),
|
|
222
|
-
... ),
|
|
210
|
+
... samples=Labels(["system", "atom"], np.array([[0, 0], [0, 1]])),
|
|
223
211
|
... components=[],
|
|
224
212
|
... properties=Labels(["properties"], np.array([[0], [1], [2]])),
|
|
225
213
|
... )
|
|
@@ -254,15 +242,9 @@ class ModuleMap(ModuleList):
|
|
|
254
242
|
:param tensor:
|
|
255
243
|
input tensor map
|
|
256
244
|
"""
|
|
257
|
-
self._in_keys = self._in_keys.to(tensor.device)
|
|
258
|
-
if self._out_properties is not None:
|
|
259
|
-
self._out_properties = [
|
|
260
|
-
label.to(tensor.device) for label in self._out_properties
|
|
261
|
-
]
|
|
262
|
-
|
|
263
245
|
out_blocks: List[TensorBlock] = []
|
|
264
246
|
for key, block in tensor.items():
|
|
265
|
-
out_block = self.
|
|
247
|
+
out_block = self._forward_block(key, block)
|
|
266
248
|
|
|
267
249
|
for parameter, gradient in block.gradients():
|
|
268
250
|
if len(gradient.gradients_list()) != 0:
|
|
@@ -271,30 +253,33 @@ class ModuleMap(ModuleList):
|
|
|
271
253
|
)
|
|
272
254
|
out_block.add_gradient(
|
|
273
255
|
parameter=parameter,
|
|
274
|
-
gradient=self.
|
|
256
|
+
gradient=self._forward_block(key, gradient),
|
|
275
257
|
)
|
|
276
258
|
out_blocks.append(out_block)
|
|
277
259
|
|
|
278
260
|
return TensorMap(tensor.keys, out_blocks)
|
|
279
261
|
|
|
280
|
-
def
|
|
281
|
-
|
|
282
|
-
if
|
|
262
|
+
def _forward_block(self, key: LabelsEntry, block: TensorBlock) -> TensorBlock:
|
|
263
|
+
module_idx = self.in_keys.position(key)
|
|
264
|
+
if module_idx is None:
|
|
283
265
|
raise KeyError(f"key {key} not found in modules.")
|
|
284
|
-
|
|
285
|
-
module: ModuleMapInterface = self[module_idx]
|
|
266
|
+
|
|
267
|
+
module: ModuleMapInterface = self.module_list[module_idx]
|
|
286
268
|
|
|
287
269
|
out_values = module.forward(block.values)
|
|
288
270
|
if self._out_properties is None:
|
|
289
|
-
# we do not use range because of metatensor/issues/410
|
|
271
|
+
# we do not use `Labels.range` because of metatensor/issues/410
|
|
290
272
|
properties = Labels(
|
|
291
273
|
"_",
|
|
292
274
|
_dispatch.int_array_like(
|
|
293
275
|
list(range(out_values.shape[-1])), block.samples.values
|
|
294
276
|
).reshape(-1, 1),
|
|
277
|
+
# unique because `list(range(...))` produces unique entries
|
|
278
|
+
assume_unique=True,
|
|
295
279
|
)
|
|
296
280
|
else:
|
|
297
281
|
properties = self._out_properties[module_idx]
|
|
282
|
+
|
|
298
283
|
return TensorBlock(
|
|
299
284
|
values=out_values,
|
|
300
285
|
properties=properties,
|
|
@@ -302,46 +287,16 @@ class ModuleMap(ModuleList):
|
|
|
302
287
|
samples=block.samples,
|
|
303
288
|
)
|
|
304
289
|
|
|
305
|
-
@torch.jit.export
|
|
306
|
-
def get_module(self, key: LabelsEntry):
|
|
307
|
-
"""
|
|
308
|
-
:param key:
|
|
309
|
-
key of module which should be returned
|
|
310
|
-
|
|
311
|
-
:return module:
|
|
312
|
-
returns he torch.nn.Module corresponding to the :param key:
|
|
313
|
-
"""
|
|
314
|
-
# type annotation in function signature had to be removed because of TorchScript
|
|
315
|
-
position = self._in_keys.position(key)
|
|
316
|
-
if position is None:
|
|
317
|
-
raise KeyError(f"key {key} not found in modules.")
|
|
318
|
-
module_idx: int = position
|
|
319
|
-
module: ModuleMapInterface = self[module_idx]
|
|
320
|
-
return module
|
|
321
|
-
|
|
322
290
|
@property
|
|
323
291
|
def in_keys(self) -> Labels:
|
|
324
292
|
"""
|
|
325
|
-
|
|
326
|
-
of this module map.
|
|
293
|
+
Labels that defines the keys this module map expects as input
|
|
327
294
|
"""
|
|
328
295
|
return self._in_keys
|
|
329
296
|
|
|
330
297
|
@property
|
|
331
298
|
def out_properties(self) -> Union[None, List[Labels]]:
|
|
332
299
|
"""
|
|
333
|
-
A list of labels that is used to determine properties
|
|
334
|
-
output of forward function.
|
|
300
|
+
A list of labels that is used to determine properties of the output
|
|
335
301
|
"""
|
|
336
302
|
return self._out_properties
|
|
337
|
-
|
|
338
|
-
def repr_as_module_dict(self) -> str:
|
|
339
|
-
"""
|
|
340
|
-
Returns a string that is easier to read that the standard __repr__ showing the
|
|
341
|
-
mapping from label entry key to module.
|
|
342
|
-
"""
|
|
343
|
-
representation = "ModuleMap(\n"
|
|
344
|
-
for i, key in enumerate(self._in_keys):
|
|
345
|
-
representation += f" ({key!r}): {self[i]!r}\n"
|
|
346
|
-
representation += ")"
|
|
347
|
-
return representation
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
from typing import List, Optional
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
|
-
from torch.nn import Module
|
|
5
4
|
|
|
6
5
|
from .._backend import Labels, TensorMap
|
|
7
6
|
from .._dispatch import int_array_like
|
|
7
|
+
from ._module import Module
|
|
8
8
|
from .module_map import ModuleMap
|
|
9
9
|
|
|
10
10
|
|
|
@@ -16,12 +16,12 @@ class ReLU(Module):
|
|
|
16
16
|
Applies a rectified linear unit transformation transformation to each block of a
|
|
17
17
|
:py:class:`TensorMap` passed to its forward method, indexed by :param in_keys:.
|
|
18
18
|
|
|
19
|
-
Refer to the :py:class
|
|
19
|
+
Refer to the :py:class:`torch.nn.ReLU` documentation for a more detailed description
|
|
20
20
|
of the parameters.
|
|
21
21
|
|
|
22
22
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
23
23
|
tensor map in the :py:meth:`forward` method.
|
|
24
|
-
:param out_properties: list of :py:class
|
|
24
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
25
25
|
of the output. By default the output properties are relabeled using
|
|
26
26
|
Labels.range.
|
|
27
27
|
"""
|
|
@@ -55,7 +55,7 @@ class ReLU(Module):
|
|
|
55
55
|
return self.module_map(tensor)
|
|
56
56
|
|
|
57
57
|
|
|
58
|
-
class InvariantReLU(
|
|
58
|
+
class InvariantReLU(Module):
|
|
59
59
|
"""
|
|
60
60
|
Module similar to :py:class:`torch.nn.ReLU` that works with
|
|
61
61
|
:py:class:`metatensor.torch.TensorMap` objects, applying the transformation only to
|
|
@@ -66,12 +66,12 @@ class InvariantReLU(torch.nn.Module):
|
|
|
66
66
|
the keys in :param in_keys: that correspond to the selection passed in :param
|
|
67
67
|
invariant_keys:.
|
|
68
68
|
|
|
69
|
-
Refer to the :py:class
|
|
69
|
+
Refer to the :py:class:`torch.nn.ReLU` documentation for a more detailed description
|
|
70
70
|
of the parameters.
|
|
71
71
|
|
|
72
72
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
73
73
|
tensor map in the :py:meth:`forward` method.
|
|
74
|
-
:param out_properties: list of :py:class
|
|
74
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
75
75
|
of the output. By default the output properties are relabeled using
|
|
76
76
|
Labels.range.
|
|
77
77
|
:param invariant_keys: a :py:class:`Labels` object that is used to select the
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
from typing import List
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
|
-
from torch.nn import Module
|
|
5
4
|
|
|
6
5
|
from .._backend import Labels, TensorMap, isinstance_metatensor
|
|
6
|
+
from ._module import Module
|
|
7
7
|
from .module_map import ModuleMap
|
|
8
8
|
|
|
9
9
|
|
|
@@ -26,7 +26,9 @@ class Sequential(Module):
|
|
|
26
26
|
|
|
27
27
|
modules: List[Module] = []
|
|
28
28
|
for i in range(len(in_keys)):
|
|
29
|
-
modules.append(
|
|
29
|
+
modules.append(
|
|
30
|
+
torch.nn.Sequential(*[arg.module_map.module_list[i] for arg in args])
|
|
31
|
+
)
|
|
30
32
|
self.module_map = ModuleMap(
|
|
31
33
|
in_keys, modules, out_properties=args[-1].module_map.out_properties
|
|
32
34
|
)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
from typing import List, Optional
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
|
-
from torch.nn import Module
|
|
5
4
|
|
|
6
5
|
from .._backend import Labels, TensorMap
|
|
7
6
|
from .._dispatch import int_array_like
|
|
7
|
+
from ._module import Module
|
|
8
8
|
from .module_map import ModuleMap
|
|
9
9
|
|
|
10
10
|
|
|
@@ -16,12 +16,12 @@ class SiLU(Module):
|
|
|
16
16
|
Applies a sigmoid linear unit transformation transformation to each block of a
|
|
17
17
|
:py:class:`TensorMap` passed to its forward method, indexed by :param in_keys:.
|
|
18
18
|
|
|
19
|
-
Refer to the :py:class
|
|
19
|
+
Refer to the :py:class:`torch.nn.SiLU` documentation for a more detailed description
|
|
20
20
|
of the parameters.
|
|
21
21
|
|
|
22
22
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
23
23
|
tensor map in the :py:meth:`forward` method.
|
|
24
|
-
:param out_properties: list of :py:class
|
|
24
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
25
25
|
of the output. By default the output properties are relabeled using
|
|
26
26
|
Labels.range.
|
|
27
27
|
"""
|
|
@@ -55,7 +55,7 @@ class SiLU(Module):
|
|
|
55
55
|
return self.module_map(tensor)
|
|
56
56
|
|
|
57
57
|
|
|
58
|
-
class InvariantSiLU(
|
|
58
|
+
class InvariantSiLU(Module):
|
|
59
59
|
"""
|
|
60
60
|
Module similar to :py:class:`torch.nn.SiLU` that works with
|
|
61
61
|
:py:class:`metatensor.torch.TensorMap` objects, applying the transformation only to
|
|
@@ -66,12 +66,12 @@ class InvariantSiLU(torch.nn.Module):
|
|
|
66
66
|
the keys in :param in_keys: that correspond to the selection passed in :param
|
|
67
67
|
invariant_keys:.
|
|
68
68
|
|
|
69
|
-
Refer to the :py:class
|
|
69
|
+
Refer to the :py:class:`torch.nn.SiLU` documentation for a more detailed description
|
|
70
70
|
of the parameters.
|
|
71
71
|
|
|
72
72
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
73
73
|
tensor map in the :py:meth:`forward` method.
|
|
74
|
-
:param out_properties: list of :py:class
|
|
74
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
75
75
|
of the output. By default the output properties are relabeled using
|
|
76
76
|
Labels.range.
|
|
77
77
|
:param invariant_keys: a :py:class:`Labels` object that is used to select the
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
from typing import List, Optional
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
|
-
from torch.nn import Module
|
|
5
4
|
|
|
6
5
|
from .._backend import Labels, TensorMap
|
|
7
6
|
from .._dispatch import int_array_like
|
|
7
|
+
from ._module import Module
|
|
8
8
|
from .module_map import ModuleMap
|
|
9
9
|
|
|
10
10
|
|
|
@@ -16,12 +16,12 @@ class Tanh(Module):
|
|
|
16
16
|
Applies a hyperbolic tangent transformation to each block of a :py:class:`TensorMap`
|
|
17
17
|
passed to its forward method, indexed by :param in_keys:.
|
|
18
18
|
|
|
19
|
-
Refer to the :py:class
|
|
19
|
+
Refer to the :py:class:`torch.nn.Tanh` documentation for a more detailed description
|
|
20
20
|
of the parameters.
|
|
21
21
|
|
|
22
22
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
23
23
|
tensor map in the :py:meth:`forward` method.
|
|
24
|
-
:param out_properties: list of :py:class
|
|
24
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
25
25
|
of the output. By default the output properties are relabeled using
|
|
26
26
|
Labels.range.
|
|
27
27
|
"""
|
|
@@ -51,7 +51,7 @@ class Tanh(Module):
|
|
|
51
51
|
return self.module_map(tensor)
|
|
52
52
|
|
|
53
53
|
|
|
54
|
-
class InvariantTanh(
|
|
54
|
+
class InvariantTanh(Module):
|
|
55
55
|
"""
|
|
56
56
|
Module similar to :py:class:`torch.nn.Tanh` that works with
|
|
57
57
|
:py:class:`metatensor.torch.TensorMap` objects, applying the transformation only to
|
|
@@ -62,12 +62,12 @@ class InvariantTanh(torch.nn.Module):
|
|
|
62
62
|
the keys in :param in_keys: that correspond to the selection passed in :param
|
|
63
63
|
invariant_keys:.
|
|
64
64
|
|
|
65
|
-
Refer to the :py:class
|
|
65
|
+
Refer to the :py:class:`torch.nn.Tanh` documentation for a more detailed description
|
|
66
66
|
of the parameters.
|
|
67
67
|
|
|
68
68
|
:param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
|
|
69
69
|
tensor map in the :py:meth:`forward` method.
|
|
70
|
-
:param out_properties: list of :py:class
|
|
70
|
+
:param out_properties: list of :py:class:`Labels` (optional), the properties labels
|
|
71
71
|
of the output. By default the output properties are relabeled using
|
|
72
72
|
Labels.range.
|
|
73
73
|
:param invariant_keys: a :py:class:`Labels` object that is used to select the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: metatensor-learn
|
|
3
|
-
Version: 0.
|
|
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
6
|
License-Expression: BSD-3-Clause
|
|
@@ -22,11 +22,12 @@ Classifier: Topic :: Scientific/Engineering :: Chemistry
|
|
|
22
22
|
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
23
23
|
Classifier: Topic :: Software Development :: Libraries
|
|
24
24
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
-
Requires-Python: >=3.
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
26
|
Description-Content-Type: text/x-rst
|
|
27
27
|
License-File: LICENSE
|
|
28
28
|
License-File: AUTHORS
|
|
29
|
-
Requires-Dist: metatensor-operations<0.
|
|
29
|
+
Requires-Dist: metatensor-operations<0.5.0,>=0.4.0
|
|
30
|
+
Requires-Dist: metatensor-core<0.2.0,>=0.1.15
|
|
30
31
|
Dynamic: author
|
|
31
32
|
Dynamic: license-file
|
|
32
33
|
Dynamic: requires-dist
|
|
@@ -14,6 +14,7 @@ metatensor/learn/data/collate.py
|
|
|
14
14
|
metatensor/learn/data/dataloader.py
|
|
15
15
|
metatensor/learn/data/dataset.py
|
|
16
16
|
metatensor/learn/nn/__init__.py
|
|
17
|
+
metatensor/learn/nn/_module.py
|
|
17
18
|
metatensor/learn/nn/_utils.py
|
|
18
19
|
metatensor/learn/nn/equivariant_transformation.py
|
|
19
20
|
metatensor/learn/nn/layer_norm.py
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "metatensor-learn"
|
|
3
3
|
dynamic = ["version", "authors", "dependencies"]
|
|
4
|
-
requires-python = ">=3.
|
|
4
|
+
requires-python = ">=3.10"
|
|
5
5
|
|
|
6
6
|
readme = "README.rst"
|
|
7
7
|
license = "BSD-3-Clause"
|
|
@@ -49,3 +49,4 @@ namespaces = true
|
|
|
49
49
|
[tool.pytest.ini_options]
|
|
50
50
|
python_files = ["*.py"]
|
|
51
51
|
testpaths = ["tests"]
|
|
52
|
+
filterwarnings = ["error"]
|
|
@@ -9,11 +9,12 @@ from setuptools.command.sdist import sdist
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
ROOT = os.path.realpath(os.path.dirname(__file__))
|
|
12
|
+
METATENSOR_CORE = os.path.realpath(os.path.join(ROOT, "..", "metatensor_core"))
|
|
12
13
|
METATENSOR_OPERATIONS = os.path.realpath(
|
|
13
14
|
os.path.join(ROOT, "..", "metatensor_operations")
|
|
14
15
|
)
|
|
15
16
|
|
|
16
|
-
METATENSOR_LEARN_VERSION = "0.
|
|
17
|
+
METATENSOR_LEARN_VERSION = "0.4.0"
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class bdist_egg_disabled(bdist_egg):
|
|
@@ -133,14 +134,17 @@ if __name__ == "__main__":
|
|
|
133
134
|
# when packaging a sdist for release, we should never use local dependencies
|
|
134
135
|
METATENSOR_NO_LOCAL_DEPS = os.environ.get("METATENSOR_NO_LOCAL_DEPS", "0") == "1"
|
|
135
136
|
|
|
136
|
-
if not METATENSOR_NO_LOCAL_DEPS and os.path.exists(
|
|
137
|
+
if not METATENSOR_NO_LOCAL_DEPS and os.path.exists(METATENSOR_CORE):
|
|
138
|
+
assert os.path.exists(METATENSOR_OPERATIONS)
|
|
137
139
|
# we are building from a git checkout or full repo archive
|
|
138
140
|
install_requires.append(
|
|
139
141
|
f"metatensor-operations @ file://{METATENSOR_OPERATIONS}"
|
|
140
142
|
)
|
|
143
|
+
install_requires.append(f"metatensor-core @ file://{METATENSOR_CORE}")
|
|
141
144
|
else:
|
|
142
145
|
# we are building from a sdist/installing from a wheel
|
|
143
|
-
install_requires.append("metatensor-operations >=0.
|
|
146
|
+
install_requires.append("metatensor-operations >=0.4.0,<0.5.0")
|
|
147
|
+
install_requires.append("metatensor-core >=0.1.15,<0.2.0")
|
|
144
148
|
|
|
145
149
|
setup(
|
|
146
150
|
version=create_version_number(METATENSOR_LEARN_VERSION),
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
metatensor-operations<0.4.0,>=0.3.0
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{metatensor_learn-0.3.2 → metatensor_learn-0.4.0}/metatensor_learn.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|