metatensor-learn 0.2.3__tar.gz → 0.3.1__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.2.3 → metatensor_learn-0.3.1}/AUTHORS +4 -3
  2. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/MANIFEST.in +1 -1
  3. {metatensor_learn-0.2.3/metatensor_learn.egg-info → metatensor_learn-0.3.1}/PKG-INFO +7 -5
  4. metatensor_learn-0.3.1/git_version_info +2 -0
  5. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/__init__.py +1 -1
  6. metatensor_learn-0.3.1/metatensor/learn/_backend.py +68 -0
  7. metatensor_learn-0.3.1/metatensor/learn/_dispatch.py +35 -0
  8. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/data/_namedtuple.py +1 -3
  9. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/data/dataset.py +6 -7
  10. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/__init__.py +2 -2
  11. metatensor_learn-0.3.1/metatensor/learn/nn/equivariant_transformation.py +211 -0
  12. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/layer_norm.py +32 -26
  13. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/linear.py +32 -17
  14. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/module_map.py +0 -2
  15. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/relu.py +17 -8
  16. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/sequential.py +2 -3
  17. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/silu.py +17 -8
  18. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/tanh.py +15 -6
  19. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1/metatensor_learn.egg-info}/PKG-INFO +7 -5
  20. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor_learn.egg-info/SOURCES.txt +3 -1
  21. metatensor_learn-0.3.1/metatensor_learn.egg-info/requires.txt +1 -0
  22. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/pyproject.toml +1 -1
  23. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/setup.py +44 -40
  24. metatensor_learn-0.2.3/metatensor/learn/_backend.py +0 -28
  25. metatensor_learn-0.2.3/metatensor_learn.egg-info/requires.txt +0 -1
  26. metatensor_learn-0.2.3/n_commits_since_last_tag +0 -1
  27. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/LICENSE +0 -0
  28. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/README.rst +0 -0
  29. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/data/__init__.py +0 -0
  30. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/data/collate.py +0 -0
  31. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/data/dataloader.py +0 -0
  32. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor/learn/nn/_utils.py +0 -0
  33. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor_learn.egg-info/dependency_links.txt +0 -0
  34. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor_learn.egg-info/top_level.txt +0 -0
  35. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/metatensor_learn.egg-info/zip-safe +0 -0
  36. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/setup.cfg +0 -0
  37. {metatensor_learn-0.2.3 → metatensor_learn-0.3.1}/tests/test_dummmy.py +0 -0
@@ -1,6 +1,7 @@
1
1
  Guillaume Fraux
2
- Davide Tisi
3
2
  Philip Loche
3
+ Filippo Bigi
4
4
  Joseph W. Abbott
5
- Jigyasa Nigam
6
- Chiheb Ben Mahmoud
5
+ Davide Tisi
6
+ Alexander Goscinski
7
+ Michele Ceriotti
@@ -2,4 +2,4 @@ include pyproject.toml
2
2
  include AUTHORS
3
3
  include LICENSE
4
4
 
5
- include n_commits_since_last_tag
5
+ include git_version_info
@@ -1,12 +1,12 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: metatensor-learn
3
- Version: 0.2.3
3
+ Version: 0.3.1
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
- Author: Guillaume Fraux, Davide Tisi, Philip Loche, Joseph W. Abbott, Jigyasa Nigam, Chiheb Ben Mahmoud
5
+ Author: Guillaume Fraux, Philip Loche, Filippo Bigi, Joseph W. Abbott, Davide Tisi, Alexander Goscinski, Michele Ceriotti
6
6
  License: BSD-3-Clause
7
7
  Project-URL: homepage, https://docs.metatensor.org/latest/
8
8
  Project-URL: documentation, https://docs.metatensor.org/latest/
9
- Project-URL: repository, https://github.com/lab-cosmo/metatensor
9
+ Project-URL: repository, https://github.com/metatensor/metatensor
10
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
@@ -27,7 +27,9 @@ Requires-Python: >=3.9
27
27
  Description-Content-Type: text/x-rst
28
28
  License-File: LICENSE
29
29
  License-File: AUTHORS
30
- Requires-Dist: metatensor-operations<0.3.0,>=0.2.0
30
+ Requires-Dist: metatensor-operations<0.4.0,>=0.3.0
31
+ Dynamic: author
32
+ Dynamic: requires-dist
31
33
 
32
34
  metatensor-learn
33
35
  =====================
@@ -0,0 +1,2 @@
1
+ 0
2
+ git.93cdb84
@@ -14,4 +14,4 @@ except ImportError:
14
14
  if HAS_TORCH:
15
15
  from . import data, nn # noqa: F401
16
16
  from .data import DataLoader, Dataset, IndexedDataset # noqa: F401
17
- from .nn import ModuleMap, Linear # noqa: F401
17
+ from .nn import Linear, ModuleMap # noqa: F401
@@ -0,0 +1,68 @@
1
+ # This file defines the default set of classes to use in metatensor-learn
2
+ #
3
+ # The code from metatensor-learn can be used in two different modes: either pure Python
4
+ # mode or TorchScript mode. In the second case, we need to use a different version of
5
+ # the classes above; to do so without having to rewrite everything, we re-import
6
+ # metatensor-learn in a special context.
7
+ #
8
+ # See metatensor-torch/metatensor/torch/learn.py for more information.
9
+ #
10
+ # Any change to this file MUST be also be made to `metatensor/torch/learn.py`.
11
+
12
+ import re
13
+ import warnings
14
+
15
+ import metatensor
16
+
17
+
18
+ try:
19
+ import torch
20
+
21
+ _HAS_TORCH = True
22
+ except ImportError:
23
+ _HAS_TORCH = False
24
+
25
+
26
+ Labels = metatensor.Labels
27
+ LabelsEntry = metatensor.LabelsEntry
28
+ TensorBlock = metatensor.TensorBlock
29
+ TensorMap = metatensor.TensorMap
30
+
31
+
32
+ def torch_jit_is_scripting():
33
+ return False
34
+
35
+
36
+ _VERSION_REGEX = re.compile(r"(\d+)\.(\d+)\.*.")
37
+
38
+
39
+ def _version_at_least(version, expected):
40
+ version = tuple(map(int, _VERSION_REGEX.match(version).groups()))
41
+ expected = tuple(map(int, _VERSION_REGEX.match(expected).groups()))
42
+
43
+ return version >= expected
44
+
45
+
46
+ def is_metatensor_class(value, typ):
47
+ assert typ in (Labels, TensorBlock, TensorMap)
48
+
49
+ if isinstance(value, typ):
50
+ return True
51
+ 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
+ return False
@@ -0,0 +1,35 @@
1
+ """Helper functions to dispatch methods between numpy and torch."""
2
+
3
+ from typing import List, Union
4
+
5
+ import numpy as np
6
+
7
+
8
+ try:
9
+ import torch
10
+ from torch import Tensor as TorchTensor
11
+ except ImportError:
12
+
13
+ class TorchTensor:
14
+ pass
15
+
16
+
17
+ UNKNOWN_ARRAY_TYPE = (
18
+ "unknown array type, only numpy arrays and torch tensors are supported"
19
+ )
20
+
21
+
22
+ def int_array_like(int_list: Union[List[int], List[List[int]]], like):
23
+ """
24
+ Converts the input list of int to a numpy array or torch tensor
25
+ based on the type of `like`.
26
+ """
27
+ if isinstance(like, TorchTensor):
28
+ if torch.jit.isinstance(int_list, List[int]):
29
+ return torch.tensor(int_list, dtype=torch.int64, device=like.device)
30
+ else:
31
+ return torch.tensor(int_list, dtype=torch.int64, device=like.device)
32
+ elif isinstance(like, np.ndarray):
33
+ return np.array(int_list).astype(np.int64)
34
+ else:
35
+ raise TypeError(UNKNOWN_ARRAY_TYPE)
@@ -65,9 +65,7 @@ def namedtuple(typename, field_names):
65
65
  raise TypeError(f"Expected {num_fields} arguments, got {len(result)}")
66
66
  return result
67
67
 
68
- _make.__func__.__doc__ = (
69
- f"Make a new {typename} object from a sequence " "or iterable"
70
- )
68
+ _make.__func__.__doc__ = f"Make a new {typename} object from a sequence or iterable"
71
69
 
72
70
  def _replace(self, /, **kwds):
73
71
  result = self._make(_map(kwds.pop, field_names, self))
@@ -62,8 +62,6 @@ class _BaseDataset(torch.utils.data.Dataset):
62
62
  f"'{size_arg_name}' ({size}) and data fields: ({field_sizes})"
63
63
  )
64
64
 
65
- # Define an internal numeric index list as a range from 0 to size
66
- self._indices = list(range(size))
67
65
  self._field_names = field_names
68
66
  self._data = data
69
67
  self._size = size
@@ -80,7 +78,7 @@ class _BaseDataset(torch.utils.data.Dataset):
80
78
  """
81
79
  Returns an iterator over the dataset.
82
80
  """
83
- for idx in self._indices:
81
+ for idx in range(len(self)):
84
82
  yield self[idx]
85
83
 
86
84
 
@@ -130,13 +128,11 @@ class Dataset(_BaseDataset):
130
128
  >>> # iterating over a dataset
131
129
  >>> for num, called in dataset:
132
130
  ... print(num, " -- ", called)
133
- ...
134
131
  1 -- compute something with sample 0
135
132
  2 -- compute something with sample 1
136
133
  3 -- compute something with sample 2
137
134
  >>> for sample in dataset:
138
135
  ... print(sample.num, " -- ", sample.call_me)
139
- ...
140
136
  1 -- compute something with sample 0
141
137
  2 -- compute something with sample 1
142
138
  3 -- compute something with sample 2
@@ -214,8 +210,10 @@ class Dataset(_BaseDataset):
214
210
  fields corresponding to those passed (in order) to the constructor upon class
215
211
  initialization.
216
212
  """
217
- if idx not in self._indices:
213
+ idx = int(idx)
214
+ if idx >= len(self) or idx < 0:
218
215
  raise ValueError(f"Index {idx} not in dataset")
216
+
219
217
  sample_data = []
220
218
  for name in self._field_names:
221
219
  if callable(self._data[name]): # lazy load
@@ -367,7 +365,8 @@ class IndexedDataset(_BaseDataset):
367
365
  first field is the sample ID, and the remaining fields correspond those passed
368
366
  (in order) to the constructor upon class initialization.
369
367
  """
370
- if idx not in self._indices:
368
+ idx = int(idx)
369
+ if idx >= len(self) or idx < 0:
371
370
  raise ValueError(f"Index {idx} not in dataset")
372
371
 
373
372
  sample_id = self._sample_id[idx]
@@ -1,7 +1,7 @@
1
- from .module_map import ModuleMap # noqa: F401
2
-
1
+ from .equivariant_transformation import EquivariantTransformation # noqa: F401
3
2
  from .layer_norm import InvariantLayerNorm, LayerNorm # noqa: F401
4
3
  from .linear import EquivariantLinear, Linear # noqa: F401
4
+ from .module_map import ModuleMap # noqa: F401
5
5
  from .relu import InvariantReLU, ReLU # noqa: F401
6
6
  from .sequential import Sequential # noqa: F401
7
7
  from .silu import InvariantSiLU, SiLU # noqa: F401
@@ -0,0 +1,211 @@
1
+ from typing import List, Optional, Union
2
+
3
+ import torch
4
+
5
+ from .._backend import Labels, TensorMap
6
+ from .._dispatch import int_array_like
7
+ from ._utils import _check_module_map_parameter
8
+ from .module_map import ModuleMap
9
+
10
+
11
+ class EquivariantTransformation(torch.nn.Module):
12
+ """
13
+ A custom :py:class:`torch.nn.Module` that applies an arbitrary shape- and
14
+ equivariance-preserving transformation to an input :py:class:`TensorMap`.
15
+
16
+ For invariant blocks (specified with ``invariant_keys``), the respective
17
+ transformation contained in :param modules: is applied as is. For covariant blocks,
18
+ an invariant multiplier is created, applying the transformation to the norm of the
19
+ block over the component dimensions.
20
+
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.
25
+ :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
26
+ :py:class:`TensorMap` in the :py:meth:`forward` method.
27
+ :param in_features: :py:class:`list` of :py:class:`int`, the number of features in
28
+ the input tensor for each block indexed by the keys in :param in_keys:. If
29
+ passed as a single value, the same number of features is assumed for all blocks.
30
+ :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.
34
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
35
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
36
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
37
+ ``[0, 1]``.
38
+
39
+ >>> import torch
40
+ >>> import numpy as np
41
+ >>> from metatensor import Labels, TensorBlock, TensorMap
42
+ >>> from metatensor.learn.nn import EquivariantTransformation
43
+
44
+ Define a dummy invariant TensorBlock
45
+
46
+ >>> block_1 = TensorBlock(
47
+ ... values=torch.randn(2, 1, 3),
48
+ ... samples=Labels(
49
+ ... ["system", "atom"],
50
+ ... np.array(
51
+ ... [
52
+ ... [0, 0],
53
+ ... [0, 1],
54
+ ... ]
55
+ ... ),
56
+ ... ),
57
+ ... components=[Labels(["o3_mu"], np.array([[0]]))],
58
+ ... properties=Labels(["properties"], np.array([[0], [1], [2]])),
59
+ ... )
60
+
61
+ Define a dummy covariant TensorBlock
62
+
63
+ >>> block_2 = TensorBlock(
64
+ ... values=torch.randn(2, 3, 3),
65
+ ... samples=Labels(
66
+ ... ["system", "atom"],
67
+ ... np.array(
68
+ ... [
69
+ ... [0, 0],
70
+ ... [0, 1],
71
+ ... ]
72
+ ... ),
73
+ ... ),
74
+ ... components=[Labels(["o3_mu"], np.array([[-1], [0], [1]]))],
75
+ ... properties=Labels(["properties"], np.array([[3], [4], [5]])),
76
+ ... )
77
+
78
+ Create a TensorMap containing the dummy TensorBlocks
79
+
80
+ >>> keys = Labels(names=["o3_lambda"], values=np.array([[0], [1]]))
81
+ >>> tensor = TensorMap(keys, [block_1, block_2])
82
+
83
+ Define the transformation to apply to the TensorMap
84
+
85
+ >>> modules = [torch.nn.Tanh(), torch.nn.Tanh()]
86
+ >>> in_features = [len(tensor.block(key).properties) for key in tensor.keys]
87
+
88
+ Define the EquivariantTransformation module
89
+
90
+ >>> transformation = EquivariantTransformation(
91
+ ... modules,
92
+ ... tensor.keys,
93
+ ... in_features,
94
+ ... out_properties=[tensor.block(key).properties for key in tensor.keys],
95
+ ... invariant_keys=Labels(
96
+ ... ["o3_lambda"], np.array([0], dtype=np.int64).reshape(-1, 1)
97
+ ... ),
98
+ ... )
99
+
100
+ The output metadata are the same as the input
101
+
102
+ >>> transformation(tensor)
103
+ TensorMap with 2 blocks
104
+ keys: o3_lambda
105
+ 0
106
+ 1
107
+ >>> transformation(tensor)[0]
108
+ TensorBlock
109
+ samples (2): ['system', 'atom']
110
+ components (1): ['o3_mu']
111
+ properties (3): ['properties']
112
+ gradients: None
113
+
114
+ """
115
+
116
+ def __init__(
117
+ self,
118
+ modules: List[torch.nn.Module],
119
+ in_keys: Labels,
120
+ in_features: Union[int, List[int]],
121
+ out_features: Optional[Union[int, List[int]]] = None,
122
+ out_properties: Optional[List[Labels]] = None,
123
+ invariant_keys: Optional[Labels] = None,
124
+ ) -> None:
125
+ super().__init__()
126
+
127
+ # Set a default for invariant keys
128
+ if invariant_keys is None:
129
+ invariant_keys = Labels(
130
+ names=["o3_lambda", "o3_sigma"],
131
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
132
+ )
133
+ invariant_key_idxs = in_keys.select(invariant_keys)
134
+
135
+ # Infer `out_features` if not provided
136
+ if out_features is None:
137
+ if out_properties is None:
138
+ raise ValueError(
139
+ "If `out_features` is not provided,"
140
+ " `out_properties` must be provided."
141
+ )
142
+ out_features = [len(p) for p in out_properties]
143
+
144
+ # Check input parameters, convert to lists (for each key) if necessary
145
+ in_features = _check_module_map_parameter(
146
+ in_features, "in_features", int, len(in_keys), "in_keys"
147
+ )
148
+
149
+ modules_for_map: List[torch.nn.Module] = []
150
+ for i in range(len(in_keys)):
151
+ if i in invariant_key_idxs:
152
+ module_i = modules[i]
153
+ else:
154
+ module_i = _CovariantTransform(
155
+ module=modules[i],
156
+ )
157
+ modules_for_map.append(module_i)
158
+
159
+ self.module_map = ModuleMap(in_keys, modules_for_map, out_properties)
160
+
161
+ def forward(self, tensor: TensorMap) -> TensorMap:
162
+ """
163
+ Apply the transformation to the input tensor map `tensor`.
164
+
165
+ :param tensor: :py:class:`TensorMap` with the input tensor to be transformed.
166
+ :return: :py:class:`TensorMap` corresponding to the transformed input
167
+ ``tensor``.
168
+ """
169
+ return self.module_map(tensor)
170
+
171
+
172
+ class _CovariantTransform(torch.nn.Module):
173
+ """
174
+ Applies an arbitrary shape-preserving transformation defined in ``module`` to a
175
+ 3-dimensional tensor in a way that preserves equivariance. The transformation is
176
+ applied to the norm of the :py:class:`torch.Tensor` over the component dimension.
177
+ The resulting :py:class:`torch.Tensor` is elementwise multiplied back to the
178
+ original one, thus preserving covariance.
179
+
180
+ :param in_features: a :py:class:`int`, the input feature dimension. This also
181
+ corresponds to the output feature size as the shape of the tensor passed to
182
+ :py:meth:`forward` is preserved.
183
+ :param module: :py:class:`torch.nn.Module` containing the transformation to be
184
+ applied to the invariants constructed from the norms over the component
185
+ dimension of the input :py:class:`torch.Tensor` passed to the :py:meth:`forward`
186
+ method.
187
+ """
188
+
189
+ def __init__(
190
+ self,
191
+ module: torch.nn.Module,
192
+ ) -> None:
193
+ super().__init__()
194
+
195
+ self.module = module
196
+
197
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
198
+ """
199
+ Creates an invariant block from the ``input`` covariant, and transforms it by
200
+ applying the torch ``module`` passed to the class constructor. Then uses the
201
+ transformed invariant as an elementwise multiplier for the ``input`` block.
202
+
203
+ Transformations are applied consistently to components (axis 1) to preserve
204
+ equivariance.
205
+ """
206
+ assert len(input.shape) == 3, "``input`` must be a three-dimensional tensor"
207
+ invariant = input.norm(dim=1, keepdim=True)
208
+ invariant_transformed = self.module(invariant)
209
+ tensor_out = invariant_transformed * input
210
+
211
+ return tensor_out
@@ -4,13 +4,14 @@ module maps that apply layer norms in a generic and equivariant way,
4
4
  respectively.
5
5
  """
6
6
 
7
- from typing import List, Optional, Union
7
+ from typing import List, Optional
8
8
 
9
9
  import torch
10
10
  from torch.nn import Module, init
11
11
  from torch.nn.parameter import Parameter
12
12
 
13
13
  from .._backend import Labels, TensorMap
14
+ from .._dispatch import int_array_like
14
15
  from ._utils import _check_module_map_parameter
15
16
  from .module_map import ModuleMap
16
17
 
@@ -34,9 +35,8 @@ class LayerNorm(Module):
34
35
  Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
35
36
  description of the other parameters.
36
37
 
37
- Each parameter can be passed as a single value of its expected type, which is used
38
- as the parameter for all blocks. Alternatively, they can be passed as a list to
39
- control the parameters applied to each block indexed by the keys in :param in_keys:.
38
+ Each parameter is passed as a single value of its expected type, which is used
39
+ as the parameter for all blocks.
40
40
 
41
41
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
42
42
  tensor map in the :py:meth:`forward` method.
@@ -57,10 +57,10 @@ class LayerNorm(Module):
57
57
  in_features: List[int],
58
58
  out_properties: Optional[List[Labels]] = None,
59
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,
60
+ eps: float = 1e-5,
61
+ elementwise_affine: bool = True,
62
+ bias: bool = True,
63
+ mean: bool = True,
64
64
  device: Optional[torch.device] = None,
65
65
  dtype: Optional[torch.dtype] = None,
66
66
  ) -> None:
@@ -114,8 +114,9 @@ class InvariantLayerNorm(Module):
114
114
  the invariant blocks.
115
115
 
116
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:.
117
+ passed to :py:meth:`forward` method. These are indexed by
118
+ the keys in :param in_keys: that correspond to the selection passed in :param
119
+ invariant_keys:.
119
120
 
120
121
  The main difference from :py:class:`torch.nn.LayerNorm` is that there is no
121
122
  `normalized_shape` parameter. Instead, the standard deviation and mean (if
@@ -128,44 +129,50 @@ class InvariantLayerNorm(Module):
128
129
  Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
129
130
  description of the other parameters.
130
131
 
131
- Each parameter can be passed as a single value of its expected type, which is used
132
- as the parameter for all blocks. Alternatively, they can be passed as a list to
133
- control the parameters applied to each block indexed by the invariant keys in :param
134
- in_keys: at numeric poositions :param invariant_key_idxs:.
132
+ Each parameter is passed as a single value of its expected type, which is used
133
+ as the parameter for all blocks.
135
134
 
136
135
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
137
136
  tensor map in the :py:meth:`forward` method.
138
- :param invariant_key_idxs: list of int, the indices of the invariant keys present in
139
- `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
140
- have layer norm applied. The other blocks will have the identity operator
141
- applied.
142
137
  :param in_features: list of int, the number of features in the input tensor for each
143
138
  block indexed by the keys in :param in_keys:. If passed as a single value, the
144
139
  same number of features is assumed for all blocks.
145
140
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
146
141
  of the output. By default (if none) the output properties are relabeled using
147
142
  Labels.range.
143
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
144
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
145
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
146
+ ``[0, 1]``.
148
147
  :mean bool: whether or not to subtract the mean over all dimensions except the
149
148
  samples (first) dimension of each block of the input passed to
150
- :py:meth:`forward`. If passed as a list, must have the same length as :param
151
- invariant_key_idxs:.
149
+ :py:meth:`forward`.
152
150
  """
153
151
 
154
152
  def __init__(
155
153
  self,
156
154
  in_keys: Labels,
157
- invariant_key_idxs: List[int],
158
155
  in_features: List[int],
159
156
  out_properties: Optional[List[Labels]] = None,
157
+ invariant_keys: Optional[Labels] = None,
160
158
  *,
161
- eps: Union[float, List[float]] = 1e-5,
162
- elementwise_affine: Union[bool, List[bool]] = True,
163
- bias: Union[bool, List[bool]] = True,
164
- mean: Union[bool, List[bool]] = True,
159
+ eps: float = 1e-5,
160
+ elementwise_affine: bool = True,
161
+ bias: bool = True,
162
+ mean: bool = True,
165
163
  device: Optional[torch.device] = None,
166
164
  dtype: Optional[torch.dtype] = None,
167
165
  ) -> None:
168
166
  super().__init__()
167
+
168
+ # Set a default for invariant keys
169
+ if invariant_keys is None:
170
+ invariant_keys = Labels(
171
+ names=["o3_lambda", "o3_sigma"],
172
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
173
+ )
174
+ invariant_key_idxs = in_keys.select(invariant_keys)
175
+
169
176
  # Check input parameters, convert to lists (for each *invariant* key) if
170
177
  # necessary.
171
178
  in_features = _check_module_map_parameter(
@@ -263,7 +270,6 @@ class _LayerNorm(Module):
263
270
  dtype: Optional[torch.dtype] = None,
264
271
  mean: bool = True,
265
272
  ) -> None:
266
-
267
273
  super().__init__()
268
274
 
269
275
  self.in_features = in_features
@@ -4,6 +4,7 @@ import torch
4
4
  from torch.nn import Module
5
5
 
6
6
  from .._backend import Labels, TensorMap
7
+ from .._dispatch import int_array_like
7
8
  from ._utils import _check_module_map_parameter
8
9
  from .module_map import ModuleMap
9
10
 
@@ -19,12 +20,17 @@ class Linear(Module):
19
20
  Refer to the :py:class`torch.nn.Linear` documentation for a more detailed
20
21
  description of the other parameters.
21
22
 
22
- Each parameter can be passed as a single value of its expected type, which is used
23
- as the parameter for all blocks. Alternatively, they can be passed as a list to
24
- control the parameters applied to each block indexed by the keys in :param in_keys:.
23
+ Each parameter is passed as a single value of its expected type, which is used
24
+ as the parameter for all blocks.
25
25
 
26
26
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
27
27
  tensor map in the :py:meth:`forward` method.
28
+ :param in_features: :py:class:`int` or :py:class:`list` of :py:class:`int`, the
29
+ number of input features for each block. If passed as a single value, the same
30
+ feature size is taken for all blocks.
31
+ :param out_features: :py:class:`int` or :py:class:`lint` of :py:class:`int`, the
32
+ number of output features for each block. If passed as a single value, the same
33
+ feature size is taken for all blocks.
28
34
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
29
35
  of the output. By default the output properties are relabeled using
30
36
  Labels.range. If provided, :param out_features: can be inferred and need not be
@@ -38,7 +44,7 @@ class Linear(Module):
38
44
  out_features: Optional[Union[int, List[int]]] = None,
39
45
  out_properties: Optional[List[Labels]] = None,
40
46
  *,
41
- bias: Union[bool, List[bool]] = True,
47
+ bias: bool = True,
42
48
  device: Optional[torch.device] = None,
43
49
  dtype: Optional[torch.dtype] = None,
44
50
  ) -> None:
@@ -94,41 +100,50 @@ class EquivariantLinear(Module):
94
100
  Refer to the :py:class`torch.nn.Linear` documentation for a more detailed
95
101
  description of the other parameters.
96
102
 
97
- Each parameter can be passed as a single value of its expected type, which is used
98
- as the parameter for all blocks. Alternatively, they can be passed as a list to
99
- control the parameters applied to each block indexed by the keys in :param in_keys:.
100
-
101
103
  For :py:class:`EquivariantLinear`, by contrast to :py:class:`Linear`, the parameter
102
104
  :param bias: is only applied to modules corresponding to invariant blocks, i.e.
103
- those indexed by keys in :param in_keys` at numeric indices :param
104
- invariant_key_idxs:. If passed as a list, :param bias: must therefore have the same
105
- length as :param invariant_key_idxs:.
105
+ keys in :param in_keys: that correspond to the selection in :param invariant_keys:.
106
106
 
107
107
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
108
108
  tensor map in the :py:meth:`forward` method.
109
- :param invariant_key_idxs: list of int, the indices of the invariant keys present in
110
- `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
111
- have bias applied according to the user choice. Covariant blocks will not have
112
- bias applied.
109
+ :param in_features: :py:class:`int` or :py:class:`list` of :py:class:`int`, the
110
+ number of input features for each block. If passed as a single value, the same
111
+ feature size is taken for all blocks.
112
+ :param out_features: :py:class:`int` or :py:class:`lint` of :py:class:`int`, the
113
+ number of output features for each block. If passed as a single value, the same
114
+ feature size is taken for all blocks.
113
115
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
114
116
  of the output. By default the output properties are relabeled using
115
117
  Labels.range. If provided, :param out_features: can be inferred and need not be
116
118
  provided.
119
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
120
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
121
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
122
+ ``[0, 1]``.
117
123
  """
118
124
 
119
125
  def __init__(
120
126
  self,
121
127
  in_keys: Labels,
122
- invariant_key_idxs: List[int],
123
128
  in_features: Union[int, List[int]],
124
129
  out_features: Optional[Union[int, List[int]]] = None,
125
130
  out_properties: Optional[List[Labels]] = None,
131
+ invariant_keys: Optional[Labels] = None,
126
132
  *,
127
- bias: Union[bool, List[bool]] = True,
133
+ bias: bool = True,
128
134
  device: Optional[torch.device] = None,
129
135
  dtype: Optional[torch.dtype] = None,
130
136
  ) -> None:
131
137
  super().__init__()
138
+
139
+ # Set a default for invariant keys
140
+ if invariant_keys is None:
141
+ invariant_keys = Labels(
142
+ names=["o3_lambda", "o3_sigma"],
143
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
144
+ )
145
+ invariant_key_idxs = in_keys.select(invariant_keys)
146
+
132
147
  # Infer `out_features` if not provided
133
148
  if out_features is None:
134
149
  if out_properties is None:
@@ -105,7 +105,6 @@ class ModuleMap(ModuleList):
105
105
  >>> linear = torch.nn.Linear(3, 1, bias=False)
106
106
  >>> with torch.no_grad():
107
107
  ... _ = linear.weight.copy_(torch.tensor([1.0, 1.0, 1.0]))
108
- ...
109
108
  >>> modules = [linear, deepcopy(linear)]
110
109
  >>> # you could also extend the module by some nonlinear activation function
111
110
 
@@ -229,7 +228,6 @@ class ModuleMap(ModuleList):
229
228
  >>> linear = torch.nn.Linear(3, 1, bias=False)
230
229
  >>> with torch.no_grad():
231
230
  ... _ = linear.weight.copy_(torch.tensor([1.0, 1.0, 1.0]))
232
- ...
233
231
  >>> # you could also extend the module by some nonlinear activation function
234
232
  >>> from metatensor.learn.nn import ModuleMap
235
233
  >>> module_map = ModuleMap.from_module(tensor.keys, linear)
@@ -4,6 +4,7 @@ import torch
4
4
  from torch.nn import Module
5
5
 
6
6
  from .._backend import Labels, TensorMap
7
+ from .._dispatch import int_array_like
7
8
  from .module_map import ModuleMap
8
9
 
9
10
 
@@ -33,7 +34,7 @@ class ReLU(Module):
33
34
  in_place: bool = False,
34
35
  ) -> None:
35
36
  super().__init__()
36
- modules: List[Module] = [torch.nn.ReLU() for i in range(len(in_keys))]
37
+ modules: List[Module] = [torch.nn.ReLU(in_place) for i in range(len(in_keys))]
37
38
  self.module_map = ModuleMap(in_keys, modules, out_properties)
38
39
 
39
40
  def forward(self, tensor: TensorMap) -> TensorMap:
@@ -62,35 +63,43 @@ class InvariantReLU(torch.nn.Module):
62
63
 
63
64
  Applies a rectified linear unit transformation to each invariant block of a
64
65
  :py:class:`TensorMap` passed to its :py:meth:`forward` method. These are indexed by
65
- the keys in :param in_keys: at numeric indices passed in :param invariant_key_idxs:.
66
+ the keys in :param in_keys: that correspond to the selection passed in :param
67
+ invariant_keys:.
66
68
 
67
69
  Refer to the :py:class`torch.nn.ReLU` documentation for a more detailed description
68
70
  of the parameters.
69
71
 
70
72
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
71
73
  tensor map in the :py:meth:`forward` method.
72
- :param invariant_key_idxs: list of int, the indices of the invariant keys present in
73
- `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
74
- have the ReLU transformation applied. Covariant blocks will have the identity
75
- operator applied.
76
74
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
77
75
  of the output. By default the output properties are relabeled using
78
76
  Labels.range.
77
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
78
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
79
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
80
+ ``[0, 1]``.
79
81
  """
80
82
 
81
83
  def __init__(
82
84
  self,
83
85
  in_keys: Labels,
84
- invariant_key_idxs: List[int],
85
86
  out_properties: Optional[Labels] = None,
87
+ invariant_keys: Optional[Labels] = None,
86
88
  *,
87
89
  in_place: bool = False,
88
90
  ) -> None:
89
91
  super().__init__()
92
+ # Set a default for invariant keys
93
+ if invariant_keys is None:
94
+ invariant_keys = Labels(
95
+ names=["o3_lambda", "o3_sigma"],
96
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
97
+ )
98
+ invariant_key_idxs = in_keys.select(invariant_keys)
90
99
  modules: List[Module] = []
91
100
  for i in range(len(in_keys)):
92
101
  if i in invariant_key_idxs: # Invariant block: apply ReLU
93
- module = torch.nn.ReLU()
102
+ module = torch.nn.ReLU(in_place)
94
103
  else: # Covariant block: apply identity operator
95
104
  module = torch.nn.Identity()
96
105
  modules.append(module)
@@ -3,7 +3,7 @@ from typing import List
3
3
  import torch
4
4
  from torch.nn import Module
5
5
 
6
- from .._backend import Labels, TensorMap, check_isinstance
6
+ from .._backend import Labels, TensorMap, is_metatensor_class
7
7
  from .module_map import ModuleMap
8
8
 
9
9
 
@@ -20,9 +20,8 @@ class Sequential(Module):
20
20
  """
21
21
 
22
22
  def __init__(self, in_keys: Labels, *args: List[ModuleMap]):
23
-
24
23
  super().__init__()
25
- if not check_isinstance(in_keys, Labels):
24
+ if not is_metatensor_class(in_keys, Labels):
26
25
  raise TypeError("`in_keys` must be a `Labels` object.")
27
26
 
28
27
  modules: List[Module] = []
@@ -4,6 +4,7 @@ import torch
4
4
  from torch.nn import Module
5
5
 
6
6
  from .._backend import Labels, TensorMap
7
+ from .._dispatch import int_array_like
7
8
  from .module_map import ModuleMap
8
9
 
9
10
 
@@ -33,7 +34,7 @@ class SiLU(Module):
33
34
  in_place: bool = False,
34
35
  ) -> None:
35
36
  super().__init__()
36
- modules: List[Module] = [torch.nn.SiLU() for i in range(len(in_keys))]
37
+ modules: List[Module] = [torch.nn.SiLU(in_place) for i in range(len(in_keys))]
37
38
  self.module_map = ModuleMap(in_keys, modules, out_properties)
38
39
 
39
40
  def forward(self, tensor: TensorMap) -> TensorMap:
@@ -62,35 +63,43 @@ class InvariantSiLU(torch.nn.Module):
62
63
 
63
64
  Applies a sigmoid linear unit transformation to each invariant block of a
64
65
  :py:class:`TensorMap` passed to its :py:meth:`forward` method. These are indexed by
65
- the keys in :param in_keys: at numeric indices passed in :param invariant_key_idxs:.
66
+ the keys in :param in_keys: that correspond to the selection passed in :param
67
+ invariant_keys:.
66
68
 
67
69
  Refer to the :py:class`torch.nn.SiLU` documentation for a more detailed description
68
70
  of the parameters.
69
71
 
70
72
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
71
73
  tensor map in the :py:meth:`forward` method.
72
- :param invariant_key_idxs: list of int, the indices of the invariant keys present in
73
- `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
74
- have the SiLU transformation applied. Covariant blocks will have the identity
75
- operator applied.
76
74
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
77
75
  of the output. By default the output properties are relabeled using
78
76
  Labels.range.
77
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
78
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
79
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
80
+ ``[0, 1]``.
79
81
  """
80
82
 
81
83
  def __init__(
82
84
  self,
83
85
  in_keys: Labels,
84
- invariant_key_idxs: List[int],
85
86
  out_properties: Optional[Labels] = None,
87
+ invariant_keys: Optional[Labels] = None,
86
88
  *,
87
89
  in_place: bool = False,
88
90
  ) -> None:
89
91
  super().__init__()
92
+ # Set a default for invariant keys
93
+ if invariant_keys is None:
94
+ invariant_keys = Labels(
95
+ names=["o3_lambda", "o3_sigma"],
96
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
97
+ )
98
+ invariant_key_idxs = in_keys.select(invariant_keys)
90
99
  modules: List[Module] = []
91
100
  for i in range(len(in_keys)):
92
101
  if i in invariant_key_idxs: # Invariant block: apply SiLU
93
- module = torch.nn.SiLU()
102
+ module = torch.nn.SiLU(in_place)
94
103
  else: # Covariant block: apply identity operator
95
104
  module = torch.nn.Identity()
96
105
  modules.append(module)
@@ -4,6 +4,7 @@ import torch
4
4
  from torch.nn import Module
5
5
 
6
6
  from .._backend import Labels, TensorMap
7
+ from .._dispatch import int_array_like
7
8
  from .module_map import ModuleMap
8
9
 
9
10
 
@@ -58,29 +59,37 @@ class InvariantTanh(torch.nn.Module):
58
59
 
59
60
  Applies a hyperbolic tangent transformation to each invariant block of a
60
61
  :py:class:`TensorMap` passed to its :py:meth:`forward` method. These are indexed by
61
- the keys in :param in_keys: at numeric indices passed in :param invariant_key_idxs:.
62
+ the keys in :param in_keys: that correspond to the selection passed in :param
63
+ invariant_keys:.
62
64
 
63
65
  Refer to the :py:class`torch.nn.Tanh` documentation for a more detailed description
64
66
  of the parameters.
65
67
 
66
68
  :param in_keys: :py:class:`Labels`, the keys that are assumed to be in the input
67
69
  tensor map in the :py:meth:`forward` method.
68
- :param invariant_key_idxs: list of int, the indices of the invariant keys present in
69
- `in_keys` in the input :py:class:`TensorMap`. Only blocks for these keys will
70
- have the tanh transformation applied. Covariant blocks will have the identity
71
- operator applied.
72
70
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
73
71
  of the output. By default the output properties are relabeled using
74
72
  Labels.range.
73
+ :param invariant_keys: a :py:class:`Labels` object that is used to select the
74
+ invariant keys from ``in_keys``. If not provided, the invariant keys are assumed
75
+ to be those where key dimensions ``["o3_lambda", "o3_sigma"]`` are equal to
76
+ ``[0, 1]``.
75
77
  """
76
78
 
77
79
  def __init__(
78
80
  self,
79
81
  in_keys: Labels,
80
- invariant_key_idxs: List[int],
81
82
  out_properties: Optional[Labels] = None,
83
+ invariant_keys: Optional[Labels] = None,
82
84
  ) -> None:
83
85
  super().__init__()
86
+ # Set a default for invariant keys
87
+ if invariant_keys is None:
88
+ invariant_keys = Labels(
89
+ names=["o3_lambda", "o3_sigma"],
90
+ values=int_array_like([0, 1], like=in_keys.values).reshape(-1, 2),
91
+ )
92
+ invariant_key_idxs = in_keys.select(invariant_keys)
84
93
  modules: List[Module] = []
85
94
  for i in range(len(in_keys)):
86
95
  if i in invariant_key_idxs: # Invariant block: apply tanh
@@ -1,12 +1,12 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: metatensor-learn
3
- Version: 0.2.3
3
+ Version: 0.3.1
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
- Author: Guillaume Fraux, Davide Tisi, Philip Loche, Joseph W. Abbott, Jigyasa Nigam, Chiheb Ben Mahmoud
5
+ Author: Guillaume Fraux, Philip Loche, Filippo Bigi, Joseph W. Abbott, Davide Tisi, Alexander Goscinski, Michele Ceriotti
6
6
  License: BSD-3-Clause
7
7
  Project-URL: homepage, https://docs.metatensor.org/latest/
8
8
  Project-URL: documentation, https://docs.metatensor.org/latest/
9
- Project-URL: repository, https://github.com/lab-cosmo/metatensor
9
+ Project-URL: repository, https://github.com/metatensor/metatensor
10
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
@@ -27,7 +27,9 @@ Requires-Python: >=3.9
27
27
  Description-Content-Type: text/x-rst
28
28
  License-File: LICENSE
29
29
  License-File: AUTHORS
30
- Requires-Dist: metatensor-operations<0.3.0,>=0.2.0
30
+ Requires-Dist: metatensor-operations<0.4.0,>=0.3.0
31
+ Dynamic: author
32
+ Dynamic: requires-dist
31
33
 
32
34
  metatensor-learn
33
35
  =====================
@@ -2,11 +2,12 @@ AUTHORS
2
2
  LICENSE
3
3
  MANIFEST.in
4
4
  README.rst
5
- n_commits_since_last_tag
5
+ git_version_info
6
6
  pyproject.toml
7
7
  setup.py
8
8
  metatensor/learn/__init__.py
9
9
  metatensor/learn/_backend.py
10
+ metatensor/learn/_dispatch.py
10
11
  metatensor/learn/data/__init__.py
11
12
  metatensor/learn/data/_namedtuple.py
12
13
  metatensor/learn/data/collate.py
@@ -14,6 +15,7 @@ metatensor/learn/data/dataloader.py
14
15
  metatensor/learn/data/dataset.py
15
16
  metatensor/learn/nn/__init__.py
16
17
  metatensor/learn/nn/_utils.py
18
+ metatensor/learn/nn/equivariant_transformation.py
17
19
  metatensor/learn/nn/layer_norm.py
18
20
  metatensor/learn/nn/linear.py
19
21
  metatensor/learn/nn/module_map.py
@@ -0,0 +1 @@
1
+ metatensor-operations<0.4.0,>=0.3.0
@@ -28,7 +28,7 @@ classifiers = [
28
28
  [project.urls]
29
29
  homepage = "https://docs.metatensor.org/latest/"
30
30
  documentation = "https://docs.metatensor.org/latest/"
31
- repository = "https://github.com/lab-cosmo/metatensor"
31
+ repository = "https://github.com/metatensor/metatensor"
32
32
  changelog = "https://docs.metatensor.org/latest/learn/CHANGELOG.html"
33
33
 
34
34
  ### ======================================================================== ###
@@ -1,7 +1,6 @@
1
1
  import os
2
2
  import subprocess
3
3
  import sys
4
- import uuid
5
4
 
6
5
  import packaging.version
7
6
  from setuptools import setup
@@ -11,10 +10,10 @@ from setuptools.command.sdist import sdist
11
10
 
12
11
  ROOT = os.path.realpath(os.path.dirname(__file__))
13
12
  METATENSOR_OPERATIONS = os.path.realpath(
14
- os.path.join(ROOT, "..", "metatensor-operations")
13
+ os.path.join(ROOT, "..", "metatensor_operations")
15
14
  )
16
15
 
17
- METATENSOR_LEARN_VERSION = "0.2.3"
16
+ METATENSOR_LEARN_VERSION = "0.3.1"
18
17
 
19
18
 
20
19
  class bdist_egg_disabled(bdist_egg):
@@ -39,54 +38,62 @@ class sdist_git_version(sdist):
39
38
  """
40
39
 
41
40
  def run(self):
42
- with open("n_commits_since_last_tag", "w") as fd:
43
- fd.write(str(n_commits_since_last_tag()))
41
+ n_commits, git_hash = git_version_info()
42
+ with open("git_version_info", "w") as fd:
43
+ fd.write(f"{n_commits}\n{git_hash}\n")
44
44
 
45
45
  # run original sdist
46
46
  super().run()
47
47
 
48
- os.unlink("n_commits_since_last_tag")
48
+ os.unlink("git_version_info")
49
49
 
50
50
 
51
- def n_commits_since_last_tag():
51
+ def git_version_info():
52
52
  """
53
53
  If git is available and we are building from a checkout, get the number of commits
54
- since the last tag. Otherwise, this always returns 0.
54
+ since the last tag & full hash of the code. Otherwise, this always returns (0, "").
55
55
  """
56
- script = os.path.join(ROOT, "..", "..", "scripts", "n-commits-since-last-tag.py")
57
- assert os.path.exists(script)
58
-
59
56
  TAG_PREFIX = "metatensor-learn-v"
60
- output = subprocess.run(
61
- [sys.executable, script, TAG_PREFIX],
62
- stderr=subprocess.PIPE,
63
- stdout=subprocess.PIPE,
64
- encoding="utf8",
65
- )
66
57
 
67
- if output.returncode != 0:
68
- raise Exception(
69
- "failed to get number of commits since last tag.\n"
70
- f"stdout: {output.stdout}\n"
71
- f"stderr: {output.stderr}\n"
72
- )
73
- elif output.stderr:
74
- print(output.stderr, file=sys.stderr)
75
- return 0
58
+ if os.path.exists("git_version_info"):
59
+ # we are building from a sdist, without git available, but the git
60
+ # version was recorded in the `git_version_info` file
61
+ with open("git_version_info") as fd:
62
+ n_commits = int(fd.readline().strip())
63
+ git_hash = fd.readline().strip()
76
64
  else:
77
- return int(output.stdout)
65
+ script = os.path.join(ROOT, "..", "..", "scripts", "git-version-info.py")
66
+ assert os.path.exists(script)
67
+
68
+ output = subprocess.run(
69
+ [sys.executable, script, TAG_PREFIX],
70
+ stderr=subprocess.PIPE,
71
+ stdout=subprocess.PIPE,
72
+ encoding="utf8",
73
+ )
74
+
75
+ if output.returncode != 0:
76
+ raise Exception(
77
+ "failed to get git version info.\n"
78
+ f"stdout: {output.stdout}\n"
79
+ f"stderr: {output.stderr}\n"
80
+ )
81
+ elif output.stderr:
82
+ print(output.stderr, file=sys.stderr)
83
+ n_commits = 0
84
+ git_hash = ""
85
+ else:
86
+ lines = output.stdout.splitlines()
87
+ n_commits = int(lines[0].strip())
88
+ git_hash = lines[1].strip()
89
+
90
+ return n_commits, git_hash
78
91
 
79
92
 
80
93
  def create_version_number(version):
81
94
  version = packaging.version.parse(version)
82
95
 
83
- if os.path.exists("n_commits_since_last_tag"):
84
- # we are building from a sdist, without git available, but the git
85
- # version was recorded in the `n_commits_since_last_tag` file
86
- with open("n_commits_since_last_tag") as fd:
87
- n_commits = int(fd.read().strip())
88
- else:
89
- n_commits = n_commits_since_last_tag()
96
+ n_commits, git_hash = git_version_info()
90
97
 
91
98
  if n_commits != 0:
92
99
  # if we have commits since the last tag, this mean we are in a pre-release of
@@ -107,6 +114,7 @@ def create_version_number(version):
107
114
  version._version = version._version._replace(release=release)
108
115
  version._version = version._version._replace(pre=pre)
109
116
  version._version = version._version._replace(dev=("dev", n_commits))
117
+ version._version = version._version._replace(local=(git_hash,))
110
118
 
111
119
  return str(version)
112
120
 
@@ -127,16 +135,12 @@ if __name__ == "__main__":
127
135
 
128
136
  if not METATENSOR_NO_LOCAL_DEPS and os.path.exists(METATENSOR_OPERATIONS):
129
137
  # we are building from a git checkout or full repo archive
130
-
131
- # add a random uuid to the file url to prevent pip from using a cached
132
- # wheel for metatensor-core, and force it to re-build from scratch
133
- uuid = uuid.uuid4()
134
138
  install_requires.append(
135
- f"metatensor-operations @ file://{METATENSOR_OPERATIONS}?{uuid}"
139
+ f"metatensor-operations @ file://{METATENSOR_OPERATIONS}"
136
140
  )
137
141
  else:
138
142
  # we are building from a sdist/installing from a wheel
139
- install_requires.append("metatensor-operations >=0.2.0,<0.3.0")
143
+ install_requires.append("metatensor-operations >=0.3.0,<0.4.0")
140
144
 
141
145
  setup(
142
146
  version=create_version_number(METATENSOR_LEARN_VERSION),
@@ -1,28 +0,0 @@
1
- # This file defines the default set of classes to use in metatensor-learn
2
- #
3
- # The code from metatensor-learn can be used in two different modes: either pure Python
4
- # mode or TorchScript mode. In the second case, we need to use a different version of
5
- # the classes above; to do so without having to rewrite everything, we re-import
6
- # metatensor-learn in a special context.
7
- #
8
- # See metatensor-torch/metatensor/torch/learn.py for more information.
9
- #
10
- # Any change to this file MUST be also be made to `metatensor/torch/learn.py`.
11
-
12
- from metatensor import Labels, LabelsEntry, TensorBlock, TensorMap
13
-
14
-
15
- def torch_jit_is_scripting():
16
- return False
17
-
18
-
19
- check_isinstance = isinstance
20
-
21
- __all__ = [
22
- "Labels",
23
- "LabelsEntry",
24
- "TensorBlock",
25
- "TensorMap",
26
- "torch_jit_is_scripting",
27
- "check_isinstance",
28
- ]
@@ -1 +0,0 @@
1
- metatensor-operations<0.3.0,>=0.2.0
@@ -1 +0,0 @@
1
- 0