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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {metatensor_learn-0.2.2/metatensor_learn.egg-info → metatensor_learn-0.2.3}/PKG-INFO +2 -2
  2. metatensor_learn-0.2.3/metatensor/learn/data/_namedtuple.py +148 -0
  3. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/data/collate.py +2 -1
  4. metatensor_learn-0.2.3/metatensor/learn/data/dataset.py +398 -0
  5. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/layer_norm.py +25 -26
  6. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3/metatensor_learn.egg-info}/PKG-INFO +2 -2
  7. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/SOURCES.txt +1 -0
  8. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/pyproject.toml +1 -1
  9. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/setup.py +1 -1
  10. metatensor_learn-0.2.3/tests/test_dummmy.py +7 -0
  11. metatensor_learn-0.2.2/metatensor/learn/data/dataset.py +0 -231
  12. metatensor_learn-0.2.2/tests/test_dummmy.py +0 -7
  13. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/AUTHORS +0 -0
  14. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/LICENSE +0 -0
  15. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/MANIFEST.in +0 -0
  16. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/README.rst +0 -0
  17. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/__init__.py +0 -0
  18. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/_backend.py +0 -0
  19. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/data/__init__.py +0 -0
  20. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/data/dataloader.py +0 -0
  21. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/__init__.py +0 -0
  22. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/_utils.py +0 -0
  23. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/linear.py +0 -0
  24. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/module_map.py +0 -0
  25. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/relu.py +0 -0
  26. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/sequential.py +0 -0
  27. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/silu.py +0 -0
  28. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor/learn/nn/tanh.py +0 -0
  29. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/dependency_links.txt +0 -0
  30. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/requires.txt +0 -0
  31. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/top_level.txt +0 -0
  32. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/zip-safe +0 -0
  33. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/n_commits_since_last_tag +0 -0
  34. {metatensor_learn-0.2.2 → metatensor_learn-0.2.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: metatensor-learn
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
5
  Author: Guillaume Fraux, Davide Tisi, Philip Loche, Joseph W. Abbott, Jigyasa Nigam, Chiheb Ben Mahmoud
6
6
  License: BSD-3-Clause
@@ -23,7 +23,7 @@ Classifier: Topic :: Scientific/Engineering :: Chemistry
23
23
  Classifier: Topic :: Scientific/Engineering :: Physics
24
24
  Classifier: Topic :: Software Development :: Libraries
25
25
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
- Requires-Python: >=3.7
26
+ Requires-Python: >=3.9
27
27
  Description-Content-Type: text/x-rst
28
28
  License-File: LICENSE
29
29
  License-File: AUTHORS
@@ -0,0 +1,148 @@
1
+ """
2
+ This contains a custom version of `collections.namedtuple` that supports field names
3
+ which are not valid Python identifiers.
4
+ """
5
+
6
+ import keyword
7
+ import sys
8
+ from operator import itemgetter
9
+
10
+
11
+ def _tuplegetter(index, doc):
12
+ return property(itemgetter(index), doc=doc)
13
+
14
+
15
+ def namedtuple(typename, field_names):
16
+ field_names = list(map(str, field_names))
17
+ typename = sys.intern(str(typename))
18
+
19
+ if keyword.iskeyword(typename):
20
+ raise ValueError(f"Type names cannot be a keyword: {typename!r}")
21
+
22
+ arg_names = []
23
+ fmt_names = []
24
+ for index, name in enumerate(field_names):
25
+ if name.isidentifier() and not keyword.iskeyword(name):
26
+ arg_names.append(name)
27
+ fmt_names.append(name)
28
+ else:
29
+ arg_names.append(f"_{index}")
30
+ fmt_names.append(f"'{name}'")
31
+
32
+ seen = set()
33
+ for name in field_names:
34
+ if name in seen:
35
+ raise ValueError(f"Encountered duplicate field name: {name!r}")
36
+ seen.add(name)
37
+
38
+ # Variables used in the methods and docstrings
39
+ field_names = tuple(map(sys.intern, field_names))
40
+ num_fields = len(field_names)
41
+ arg_list = ", ".join(arg_names)
42
+ if num_fields == 1:
43
+ arg_list += ","
44
+ repr_fmt = "(" + ", ".join(f"{name}=%r" for name in fmt_names) + ")"
45
+ tuple_new = tuple.__new__
46
+ tuple_getitem = tuple.__getitem__
47
+ _dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
48
+
49
+ # Create all the named tuple methods to be added to the class namespace
50
+
51
+ namespace = {
52
+ "_tuple_new": tuple_new,
53
+ "__builtins__": {},
54
+ "__name__": f"namedtuple_{typename}",
55
+ }
56
+ code = f"lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))"
57
+ __new__ = eval(code, namespace)
58
+ __new__.__name__ = "__new__"
59
+ __new__.__doc__ = f"Create new instance of {typename}({arg_list})"
60
+
61
+ @classmethod
62
+ def _make(cls, iterable):
63
+ result = tuple_new(cls, iterable)
64
+ if _len(result) != num_fields:
65
+ raise TypeError(f"Expected {num_fields} arguments, got {len(result)}")
66
+ return result
67
+
68
+ _make.__func__.__doc__ = (
69
+ f"Make a new {typename} object from a sequence " "or iterable"
70
+ )
71
+
72
+ def _replace(self, /, **kwds):
73
+ result = self._make(_map(kwds.pop, field_names, self))
74
+ if kwds:
75
+ raise TypeError(f"Got unexpected field names: {list(kwds)!r}")
76
+ return result
77
+
78
+ _replace.__doc__ = (
79
+ f"Return a new {typename} object replacing specified fields with new values"
80
+ )
81
+
82
+ def __repr__(self):
83
+ "Return a nicely formatted representation string"
84
+ return self.__class__.__name__ + repr_fmt % self
85
+
86
+ def _asdict(self):
87
+ "Return a new dict which maps field names to their values."
88
+ return _dict(_zip(self._fields, self))
89
+
90
+ def __getnewargs__(self):
91
+ "Return self as a plain tuple. Used by copy and pickle."
92
+ return _tuple(self)
93
+
94
+ def __getitem__(self, key):
95
+ if isinstance(key, str):
96
+ return self._asdict()[key]
97
+ else:
98
+ return tuple_getitem(self, key)
99
+
100
+ # Modify function metadata to help with introspection and debugging
101
+ for method in (
102
+ __new__,
103
+ _make.__func__,
104
+ _replace,
105
+ __repr__,
106
+ _asdict,
107
+ __getnewargs__,
108
+ __getitem__,
109
+ ):
110
+ method.__qualname__ = f"{typename}.{method.__name__}"
111
+
112
+ # Build-up the class namespace dictionary
113
+ # and use type() to build the result class
114
+ class_namespace = {
115
+ "__doc__": f"{typename}({arg_list})",
116
+ "__slots__": (),
117
+ "_fields": field_names,
118
+ "__new__": __new__,
119
+ "_make": _make,
120
+ "__replace__": _replace,
121
+ "_replace": _replace,
122
+ "__repr__": __repr__,
123
+ "_asdict": _asdict,
124
+ "__getnewargs__": __getnewargs__,
125
+ "__getitem__": __getitem__,
126
+ "__match_args__": field_names,
127
+ }
128
+ for index, name in enumerate(field_names):
129
+ if name.isidentifier():
130
+ doc = sys.intern(f"Alias for field number {index}")
131
+ class_namespace[name] = _tuplegetter(index, doc)
132
+
133
+ result = type(typename, (tuple,), class_namespace)
134
+
135
+ # For pickling to work, the __module__ variable needs to be set to the frame
136
+ # where the named tuple is created.
137
+ try:
138
+ module = sys._getframemodulename(1) or "__main__"
139
+ except AttributeError:
140
+ try:
141
+ module = sys._getframe(1).f_globals.get("__name__", "__main__")
142
+ except (AttributeError, ValueError):
143
+ pass
144
+
145
+ if module is not None:
146
+ result.__module__ = module
147
+
148
+ return result
@@ -2,7 +2,6 @@
2
2
  Module containing a collate function for use in a Dataloader.
3
3
  """
4
4
 
5
- from collections import namedtuple
6
5
  from typing import List, NamedTuple, Optional, Union
7
6
 
8
7
  import torch
@@ -10,6 +9,8 @@ import torch
10
9
  import metatensor
11
10
  from metatensor import TensorMap
12
11
 
12
+ from ._namedtuple import namedtuple
13
+
13
14
 
14
15
  def group(batch: List[NamedTuple]) -> NamedTuple:
15
16
  """
@@ -0,0 +1,398 @@
1
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Union
2
+
3
+ import torch
4
+
5
+ from ._namedtuple import namedtuple
6
+
7
+
8
+ class _BaseDataset(torch.utils.data.Dataset):
9
+ """
10
+ Defines the base private class for a metatensor-learn dataset.
11
+ """
12
+
13
+ def __init__(
14
+ self,
15
+ data: Dict[str, Any],
16
+ size_arg_name: str,
17
+ size: Optional[int] = None,
18
+ ):
19
+ super(_BaseDataset, self).__init__()
20
+
21
+ field_names = []
22
+ fields = []
23
+ field_sizes = []
24
+
25
+ # Check type consistency in kwarg fields
26
+ for name, field in data.items():
27
+ if isinstance(field, list):
28
+ if name != "sample_id":
29
+ # sample_id is allowed to used different types for different entries
30
+ if not all([isinstance(field[0], type(f)) for f in field]):
31
+ raise TypeError(
32
+ f"Data field {name} must be a list of the same type"
33
+ )
34
+ field_sizes.append(len(field))
35
+ else:
36
+ if not callable(field):
37
+ raise TypeError(
38
+ f"Data field must be a List or Callable, not {type(field)}"
39
+ )
40
+ field_names.append(name)
41
+ fields.append(field)
42
+
43
+ # Check size consistency
44
+ if size is None:
45
+ if len(field_sizes) == 0:
46
+ raise ValueError(
47
+ "If passing all data fields as callables, argument "
48
+ f"'{size_arg_name}' must also be provided."
49
+ )
50
+ else:
51
+ if not all([s == field_sizes[0] for s in field_sizes]):
52
+ raise ValueError(
53
+ "Number of samples inconsistent between data fields: "
54
+ f"{field_sizes}"
55
+ )
56
+ size = field_sizes[0]
57
+ else:
58
+ if len(field_sizes) > 0:
59
+ if not all([s == size for s in field_sizes]):
60
+ raise ValueError(
61
+ "Number of samples inconsistent between argument "
62
+ f"'{size_arg_name}' ({size}) and data fields: ({field_sizes})"
63
+ )
64
+
65
+ # Define an internal numeric index list as a range from 0 to size
66
+ self._indices = list(range(size))
67
+ self._field_names = field_names
68
+ self._data = data
69
+ self._size = size
70
+
71
+ self._sample_class = namedtuple("Sample", self._field_names)
72
+
73
+ def __len__(self) -> int:
74
+ """
75
+ Returns the length (i.e. number of samples) of the dataset
76
+ """
77
+ return self._size
78
+
79
+ def __iter__(self):
80
+ """
81
+ Returns an iterator over the dataset.
82
+ """
83
+ for idx in self._indices:
84
+ yield self[idx]
85
+
86
+
87
+ class Dataset(_BaseDataset):
88
+ """
89
+ Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
90
+ data fields.
91
+
92
+ The data fields are specified as keyword arguments to the constructor, where the
93
+ keyword is the name of the field, and the value is either a list of data objects or
94
+ a callable.
95
+
96
+ ``size`` specifies the number of samples in the dataset. This only needs to be
97
+ passed if all data fields are passed as callables. Otherwise, the size is inferred
98
+ from the length of the data fields passed as lists.
99
+
100
+ Every sample in the dataset is assigned a numeric ID from 0 to ``size - 1``. This ID
101
+ can be used to access the corresponding sample. For instance, ``dataset[0]`` returns
102
+ a named tuple of all data fields for the first sample in the dataset.
103
+
104
+ A data field kwarg passed as a list must be comprised of the same type of object,
105
+ and its length must be consistent with the ``size`` argument (if specified) and the
106
+ length of all other data fields passed as lists.
107
+
108
+ Otherwise a data field kwarg passed as a callable must take a single argument
109
+ corresponding to the numeric sample ID and return the data object for that sample
110
+ ID. This data field for a given sample is then only lazily loaded into memory when
111
+ the :py:meth:`Dataset.__getitem__` method is called.
112
+
113
+ >>> # create a Dataset with only lists
114
+ >>> dataset = Dataset(num=[1, 2, 3], string=["a", "b", "c"])
115
+ >>> dataset[0]
116
+ Sample(num=1, string='a')
117
+ >>> dataset[2]
118
+ Sample(num=3, string='c')
119
+
120
+ >>> # create a Dataset with callables for lazy loading of data
121
+ >>> def call_me(sample_id: int):
122
+ ... # this could also read from a file
123
+ ... return f"compute something with sample {sample_id}"
124
+ >>> dataset = Dataset(num=[1, 2, 3], call_me=call_me)
125
+ >>> dataset[0]
126
+ Sample(num=1, call_me='compute something with sample 0')
127
+ >>> dataset[2]
128
+ Sample(num=3, call_me='compute something with sample 2')
129
+
130
+ >>> # iterating over a dataset
131
+ >>> for num, called in dataset:
132
+ ... print(num, " -- ", called)
133
+ ...
134
+ 1 -- compute something with sample 0
135
+ 2 -- compute something with sample 1
136
+ 3 -- compute something with sample 2
137
+ >>> for sample in dataset:
138
+ ... print(sample.num, " -- ", sample.call_me)
139
+ ...
140
+ 1 -- compute something with sample 0
141
+ 2 -- compute something with sample 1
142
+ 3 -- compute something with sample 2
143
+ """
144
+
145
+ def __init__(self, size: Optional[int] = None, **kwargs):
146
+ """
147
+ :param size: Optional, an integer indicating the size of the dataset, i.e. the
148
+ number of samples. This only needs to be specified if all the fields are
149
+ callable.
150
+ :param kwargs: List or Callable. Keyword arguments specifying the data fields
151
+ for the dataset.
152
+ """
153
+ if "sample_id" in kwargs:
154
+ raise ValueError(
155
+ "Keyword argument 'sample_id' is not accepted by Dataset."
156
+ " For an indexed dataset, use the IndexedDataset class"
157
+ " instead."
158
+ )
159
+
160
+ super().__init__(data=kwargs, size_arg_name="size", size=size)
161
+
162
+ @classmethod
163
+ def from_dict(
164
+ cls,
165
+ data: Dict[str, Union[List, Callable]],
166
+ size: Optional[int] = None,
167
+ ) -> "Dataset":
168
+ """
169
+ Create a :py:class:`Dataset` from the given ``data``. This function behave like
170
+ ``Dataset(size=size, **data)``, but allows to use names for the different fields
171
+ that would not be valid in the main constructor.
172
+
173
+ >>> dataset = Dataset.from_dict(
174
+ ... {
175
+ ... "valid": [0, 0, 0],
176
+ ... "with space": [-1, 2, -3],
177
+ ... "with/slash": ["a", "b", "c"],
178
+ ... }
179
+ ... )
180
+ >>> sample = dataset[1]
181
+ >>> sample
182
+ Sample(valid=0, 'with space'=2, 'with/slash'='b')
183
+ >>> # fields for which the name is a valid identifier can be accessed as usual
184
+ >>> sample.valid
185
+ 0
186
+ >>> # fields which are not valid identifiers can be accessed like this
187
+ >>> sample["with space"]
188
+ 2
189
+ >>> sample["with/slash"]
190
+ 'b'
191
+
192
+ :param data: Dictionary of List or Callable containing the data. This will
193
+ behave as if all the entries of the dictionary where passed as keyword
194
+ arguments to ``__init__``.
195
+ :param size: Optional, an integer indicating the size of the dataset, i.e. the
196
+ number of samples. This only needs to be specified if all the fields are
197
+ callable.
198
+ """
199
+ if "sample_id" in data:
200
+ raise ValueError(
201
+ "'sample_id' is not accepted by Dataset. For an indexed dataset, "
202
+ "use the IndexedDataset class instead."
203
+ )
204
+
205
+ dataset = cls.__new__(cls)
206
+ _BaseDataset.__init__(self=dataset, data=data, size_arg_name="size", size=size)
207
+ return dataset
208
+
209
+ def __getitem__(self, idx: int) -> NamedTuple:
210
+ """
211
+ Returns the data for each field corresponding to the internal index ``idx``.
212
+
213
+ Each item can be accessed with ``self[idx]``. Returned is a named tuple with
214
+ fields corresponding to those passed (in order) to the constructor upon class
215
+ initialization.
216
+ """
217
+ if idx not in self._indices:
218
+ raise ValueError(f"Index {idx} not in dataset")
219
+ sample_data = []
220
+ for name in self._field_names:
221
+ if callable(self._data[name]): # lazy load
222
+ try:
223
+ sample_data.append(self._data[name](idx))
224
+ except Exception as e:
225
+ raise ValueError(
226
+ f"Error loading data field '{name}' at sample index {idx}"
227
+ ) from e
228
+ else:
229
+ assert isinstance(self._data[name], list)
230
+ sample_data.append(self._data[name][idx])
231
+
232
+ return self._sample_class(*sample_data)
233
+
234
+
235
+ class IndexedDataset(_BaseDataset):
236
+ """
237
+ Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
238
+ data fields, with sample indexed by a list of unique sample IDs.
239
+
240
+ The data fields are specified as keyword arguments to the constructor, where the
241
+ keyword is the name of the field, and the value is either a list of data objects or
242
+ a callable.
243
+
244
+ ``sample_id`` must be a unique list of any hashable object. Each respective sample
245
+ ID is assigned an internal numeric index from 0 to ``len(sample_id) - 1``. This is
246
+ used to internally index the dataset, and can be used to access a given sample. For
247
+ instance, ``dataset[0]`` returns a named tuple of all data fields for the first
248
+ sample in the dataset, i.e. the one with unique sample ID at ``sample_id[0]``. In
249
+ order to access a sample by its ID, use the :py:meth:`IndexedDataset.get_sample`
250
+ method.
251
+
252
+ A data field kwarg passed as a list must be comprised of the same type of object,
253
+ and its length must be consistent with the length of ``sample_id`` and the length of
254
+ all other data fields passed as lists.
255
+
256
+ Otherwise a data field kwarg passed as a callable must take a single argument
257
+ corresponding to the unique sample ID (i.e. those passed in ``sample_id``) and
258
+ return the data object for that sample ID. This data field for a given sample is
259
+ then only lazily loaded into memory when :py:meth:`IndexedDataset.__getitem__` or
260
+ :py:meth:`IndexedDataset.get_sample` methods are called.
261
+
262
+ >>> # create an IndexedDataset with lists
263
+ >>> dataset = IndexedDataset(sample_id=["cat", "bird", "dog"], y=[11, 22, 33])
264
+ >>> dataset[0]
265
+ Sample(sample_id='cat', y=11)
266
+ >>> dataset[2]
267
+ Sample(sample_id='dog', y=33)
268
+
269
+ >>> # create an IndexedDataset with callables for lazy loading of data
270
+ >>> def call_me(sample_id: int):
271
+ ... # this could also read from a file
272
+ ... return f"compute something with sample {sample_id}"
273
+ >>> dataset = IndexedDataset(sample_id=["cat", "bird", "dog"], call_me=call_me)
274
+ >>> dataset[0]
275
+ Sample(sample_id='cat', call_me='compute something with sample cat')
276
+ >>> dataset[2]
277
+ Sample(sample_id='dog', call_me='compute something with sample dog')
278
+ >>> dataset.get_sample("bird")
279
+ Sample(sample_id='bird', call_me='compute something with sample bird')
280
+
281
+ :param sample_id: A list of unique IDs for each sample in the dataset.
282
+ :param kwargs: Keyword arguments specifying the data fields for the dataset.
283
+ """
284
+
285
+ def __init__(self, sample_id: List, **kwargs):
286
+ if "size" in kwargs:
287
+ raise ValueError(
288
+ "Keyword argument 'size' is not accepted by IndexedDataset."
289
+ " For a dataset defined on size rather than explicit sample IDs,"
290
+ " use the Dataset class instead."
291
+ )
292
+ if len(set(sample_id)) != len(sample_id):
293
+ raise ValueError("Sample IDs must be unique, found some duplicate")
294
+
295
+ data = {"sample_id": sample_id}
296
+ data.update(kwargs)
297
+ super().__init__(data=data, size_arg_name="sample_id", size=len(sample_id))
298
+
299
+ self._sample_id = sample_id
300
+ self._sample_id_to_idx = {sample: i for i, sample in enumerate(sample_id)}
301
+
302
+ @classmethod
303
+ def from_dict(
304
+ cls,
305
+ data: Dict[str, Any],
306
+ sample_id: List,
307
+ ) -> "IndexedDataset":
308
+ """
309
+ Create a :py:class:`IndexedDataset` from the given ``data``. This function
310
+ behave like ``IndexedDataset(sample_id=sample_id, **data)``, but allows to use
311
+ names for the different fields that would not be valid in the main constructor.
312
+
313
+ >>> dataset = IndexedDataset.from_dict(
314
+ ... {
315
+ ... "valid": [0, 0, 0],
316
+ ... "with space": [-1, 2, -3],
317
+ ... "with/slash": ["a", "b", "c"],
318
+ ... },
319
+ ... sample_id=[11, 22, 33],
320
+ ... )
321
+ >>> sample = dataset[1]
322
+ >>> sample
323
+ Sample(sample_id=22, valid=0, 'with space'=2, 'with/slash'='b')
324
+ >>> # fields for which the name is a valid identifier can be accessed as usual
325
+ >>> sample.valid
326
+ 0
327
+ >>> # fields which are not valid identifiers can be accessed like this
328
+ >>> sample["with space"]
329
+ 2
330
+ >>> sample["with/slash"]
331
+ 'b'
332
+
333
+ :param data: Dictionary of List or Callable containing the data. This will
334
+ behave as if all the entries of the dictionary where passed as keyword
335
+ arguments to ``__init__``.
336
+ :param sample_id: A list of unique IDs for each sample in the dataset.
337
+ """
338
+ if "size" in data:
339
+ raise ValueError(
340
+ "'size' is not accepted by IndexedDataset. For a dataset defined on "
341
+ "size rather than explicit sample IDs, use the Dataset class instead."
342
+ )
343
+
344
+ if len(set(sample_id)) != len(sample_id):
345
+ raise ValueError("Sample IDs must be unique, found some duplicate")
346
+
347
+ clean_data = {"sample_id": sample_id}
348
+ clean_data.update(data)
349
+
350
+ dataset = cls.__new__(cls)
351
+ _BaseDataset.__init__(
352
+ self=dataset,
353
+ data=clean_data,
354
+ size_arg_name="sample_id",
355
+ size=len(sample_id),
356
+ )
357
+
358
+ dataset._sample_id = sample_id
359
+ dataset._sample_id_to_idx = {sample: i for i, sample in enumerate(sample_id)}
360
+ return dataset
361
+
362
+ def __getitem__(self, idx: int) -> NamedTuple:
363
+ """
364
+ Returns the data for each field corresponding to the internal index ``idx``.
365
+
366
+ Each item can be accessed with ``self[idx]``. Returned is a named tuple, whose
367
+ first field is the sample ID, and the remaining fields correspond those passed
368
+ (in order) to the constructor upon class initialization.
369
+ """
370
+ if idx not in self._indices:
371
+ raise ValueError(f"Index {idx} not in dataset")
372
+
373
+ sample_id = self._sample_id[idx]
374
+
375
+ sample_data = []
376
+ for name in self._field_names:
377
+ if name == "sample_id":
378
+ sample_data.append(sample_id)
379
+ elif callable(self._data[name]): # lazy load using sample ID
380
+ try:
381
+ sample_data.append(self._data[name](sample_id))
382
+ except Exception as e:
383
+ raise ValueError(
384
+ f"Error loading data field '{name}' for sample '{sample_id}'"
385
+ ) from e
386
+ else:
387
+ assert isinstance(self._data[name], list)
388
+ sample_data.append(self._data[name][idx])
389
+
390
+ return self._sample_class(*sample_data)
391
+
392
+ def get_sample(self, sample_id) -> NamedTuple:
393
+ """
394
+ Returns a named tuple for the sample corresponding to the given ``sample_id``.
395
+ """
396
+ if sample_id not in self._sample_id_to_idx:
397
+ raise ValueError(f"Sample ID '{sample_id}' not in dataset")
398
+ return self[self._sample_id_to_idx[sample_id]]
@@ -25,12 +25,11 @@ class LayerNorm(Module):
25
25
 
26
26
  The main difference from :py:class:`torch.nn.LayerNorm` is that there is no
27
27
  `normalized_shape` parameter. Instead, the standard deviation and mean (if
28
- applicable) are calculated over the property dimension of each
29
- :py:class:`TensorBlock`.
28
+ applicable) are calculated over all dimensions except the samples (first) dimension
29
+ of each :py:class:`TensorBlock`.
30
30
 
31
- This module also has an extra parameter :param mean: that controls whether or not
32
- the mean over the properties dimension is subtracted from the input tensor in the
33
- transformation.
31
+ The extra parameter :param mean: controls whether or not the mean over these
32
+ dimensions is subtracted from the input tensor in the transformation.
34
33
 
35
34
  Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
36
35
  description of the other parameters.
@@ -47,8 +46,9 @@ class LayerNorm(Module):
47
46
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
48
47
  of the output. By default (if none) the output properties are relabeled using
49
48
  Labels.range.
50
- :mean bool: whether or not to subtract the mean over the properties (final)
51
- dimension of each block of the input passed to :py:meth:`forward`.
49
+ :mean bool: whether or not to subtract the mean over all dimensions except the
50
+ samples (first) dimension of each block of the input passed to
51
+ :py:meth:`forward`.
52
52
  """
53
53
 
54
54
  def __init__(
@@ -119,12 +119,11 @@ class InvariantLayerNorm(Module):
119
119
 
120
120
  The main difference from :py:class:`torch.nn.LayerNorm` is that there is no
121
121
  `normalized_shape` parameter. Instead, the standard deviation and mean (if
122
- applicable) are calculated over the property dimension of each
123
- :py:class:`TensorBlock`.
122
+ applicable) are calculated over all dimensions except the samples (first) dimension
123
+ of each :py:class:`TensorBlock`.
124
124
 
125
- This module also has an extra parameter :param mean: that controls whether or not
126
- the mean over the properties dimension is subtracted from the input tensor in the
127
- transformation.
125
+ The extra parameter :param mean: controls whether or not the mean over these
126
+ dimensions is subtracted from the input tensor in the transformation.
128
127
 
129
128
  Refer to the :py:class`torch.nn.LayerNorm` documentation for a more detailed
130
129
  description of the other parameters.
@@ -146,8 +145,8 @@ class InvariantLayerNorm(Module):
146
145
  :param out_properties: list of :py:class`Labels` (optional), the properties labels
147
146
  of the output. By default (if none) the output properties are relabeled using
148
147
  Labels.range.
149
- :param mean: bool or list of bool. Whether or not to subtract the mean over the
150
- properties (final) dimension of each invariant block of the input passed to
148
+ :mean bool: whether or not to subtract the mean over all dimensions except the
149
+ samples (first) dimension of each block of the input passed to
151
150
  :py:meth:`forward`. If passed as a list, must have the same length as :param
152
151
  invariant_key_idxs:.
153
152
  """
@@ -237,8 +236,8 @@ class _LayerNorm(Module):
237
236
  Custom :py:class:`Module` re-implementing :py:class:`torch.nn.LayerNorm`.
238
237
 
239
238
  In this case, `normalized_shape` is not provided as a parameter. Instead, the
240
- standard deviation and mean (if applicable) are calculated over the final dimension
241
- of the input tensor.
239
+ standard deviation and mean (if applicable) are calculated over all dimensions
240
+ except the samples of the input tensor.
242
241
 
243
242
  Subtraction of this mean can be switched on or off using the extra :param mean:
244
243
  parameter.
@@ -246,8 +245,8 @@ class _LayerNorm(Module):
246
245
  Refer to :py:class:`torch.nn.LayerNorm` documentation for more information on the
247
246
  other parameters.
248
247
 
249
- :param mean: bool, whether or not to subtract the mean over the final dimension of
250
- the input tensor passed to :py:meth:`forward`.
248
+ :param mean: bool, whether or not to subtract the mean over all dimension except the
249
+ samples of the input tensor passed to :py:meth:`forward`.
251
250
  """
252
251
 
253
252
  __constants__ = ["in_features", "eps", "elementwise_affine"]
@@ -314,23 +313,23 @@ def _layer_norm(
314
313
  """
315
314
  Apply layer normalization to the input `tensor`.
316
315
 
317
- See :py:class:`torch.nn.functional.layer_norm` for more information on the
318
- other parameters.
316
+ See :py:class:`torch.nn.functional.layer_norm` for more information on the other
317
+ parameters.
319
318
 
320
319
  In addition to base torch implementation, this function has the added control of
321
- whether or not the mean over the properties (final) dimension is subtracted from the
322
- input tensor.
320
+ whether or not the mean over all dimensions except the samples (first) dimension is
321
+ subtracted from the input tensor.
323
322
 
324
323
  :param mean: whether or not to subtract from the input :param tensor: the mean over
325
- the dimensions not included in :param normalized_shape:.
324
+ all dimensions except the samples (first) dimension.
326
325
 
327
326
  :return: :py:class:`torch.Tensor` with layer normalization applied.
328
327
  """
329
- # Contract over all dimensions except properties
330
- dim: List[int] = list(range(0, len(tensor.shape) - 1))
328
+ # Contract over all dimensions except samples
329
+ dim: List[int] = list(range(1, len(tensor.shape)))
331
330
 
332
331
  if mean: # subtract mean over properties dimension
333
- tensor_out = tensor - torch.mean(tensor, dim=dim)
332
+ tensor_out = tensor - torch.mean(tensor, dim=dim, keepdim=True)
334
333
  else:
335
334
  tensor_out = tensor
336
335
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: metatensor-learn
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Building blocks for the atomistic machine learning models based on PyTorch and NumPy
5
5
  Author: Guillaume Fraux, Davide Tisi, Philip Loche, Joseph W. Abbott, Jigyasa Nigam, Chiheb Ben Mahmoud
6
6
  License: BSD-3-Clause
@@ -23,7 +23,7 @@ Classifier: Topic :: Scientific/Engineering :: Chemistry
23
23
  Classifier: Topic :: Scientific/Engineering :: Physics
24
24
  Classifier: Topic :: Software Development :: Libraries
25
25
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
- Requires-Python: >=3.7
26
+ Requires-Python: >=3.9
27
27
  Description-Content-Type: text/x-rst
28
28
  License-File: LICENSE
29
29
  License-File: AUTHORS
@@ -8,6 +8,7 @@ setup.py
8
8
  metatensor/learn/__init__.py
9
9
  metatensor/learn/_backend.py
10
10
  metatensor/learn/data/__init__.py
11
+ metatensor/learn/data/_namedtuple.py
11
12
  metatensor/learn/data/collate.py
12
13
  metatensor/learn/data/dataloader.py
13
14
  metatensor/learn/data/dataset.py
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "metatensor-learn"
3
3
  dynamic = ["version", "authors", "dependencies"]
4
- requires-python = ">=3.7"
4
+ requires-python = ">=3.9"
5
5
 
6
6
  readme = "README.rst"
7
7
  license = {text = "BSD-3-Clause"}
@@ -14,7 +14,7 @@ METATENSOR_OPERATIONS = os.path.realpath(
14
14
  os.path.join(ROOT, "..", "metatensor-operations")
15
15
  )
16
16
 
17
- METATENSOR_LEARN_VERSION = "0.2.2"
17
+ METATENSOR_LEARN_VERSION = "0.2.3"
18
18
 
19
19
 
20
20
  class bdist_egg_disabled(bdist_egg):
@@ -0,0 +1,7 @@
1
+ # placeholder test that will be removed once the first pure numpy test is added
2
+ import metatensor.learn
3
+
4
+
5
+ def test_dummy():
6
+ metatensor.learn
7
+ pass
@@ -1,231 +0,0 @@
1
- """
2
- Module for defining a Dataset or IndexedDataset.
3
- """
4
-
5
- from collections import namedtuple
6
- from typing import List, NamedTuple, Optional
7
-
8
- import torch
9
-
10
-
11
- class _BaseDataset(torch.utils.data.Dataset):
12
- """
13
- Defines the base private class for a metatensor-learn dataset.
14
- """
15
-
16
- def __init__(self, arg_name: str, size: Optional[int] = None, **kwargs):
17
- super(_BaseDataset, self).__init__()
18
-
19
- field_names = []
20
- fields = []
21
- field_sizes = []
22
-
23
- # Check type consistency in kwarg fields
24
- for name, field in kwargs.items():
25
- if isinstance(field, list):
26
- if not all([isinstance(field[0], type(f)) for f in field]):
27
- raise TypeError(
28
- f"Data field {name} must be a list of the same type"
29
- )
30
- field_sizes.append(len(field))
31
- else:
32
- if not callable(field):
33
- raise TypeError(
34
- f"Data field must be a List or Callable, not {type(field)}"
35
- )
36
- field_names.append(name)
37
- fields.append(field)
38
-
39
- # Check size consistency
40
- if size is None:
41
- if len(field_sizes) == 0:
42
- raise ValueError(
43
- "If passing all data fields as callables, argument "
44
- f"'{arg_name}' must also be provided."
45
- )
46
- else:
47
- if not all([s == field_sizes[0] for s in field_sizes]):
48
- raise ValueError(
49
- "Number of samples inconsistent between data fields: "
50
- f"{field_sizes}"
51
- )
52
- size = field_sizes[0]
53
- else:
54
- if len(field_sizes) > 0:
55
- if not all([s == size for s in field_sizes]):
56
- raise ValueError(
57
- f"Number of samples inconsistent between argument '{arg_name}' "
58
- f"({size}) and data fields in kwargs: ({field_sizes})"
59
- )
60
-
61
- # Define an internal numeric index list as a range from 0 to size
62
- self._indices = list(range(size))
63
- self._field_names = field_names
64
- self._data = {name: kwargs[name] for name in self._field_names}
65
- self._size = size
66
-
67
- def __len__(self) -> int:
68
- """
69
- Returns the length (i.e. number of samples) of the dataset
70
- """
71
- return self._size
72
-
73
- def __iter__(self):
74
- """
75
- Returns an iterator over the dataset.
76
- """
77
- for idx in self._indices:
78
- yield self[idx]
79
-
80
-
81
- class Dataset(_BaseDataset):
82
- """
83
- Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
84
- data fields.
85
-
86
- The data fields are specified as keyword arguments to the constructor, where the
87
- keyword is the name of the field, and the value is either a list of data objects or
88
- a callable.
89
-
90
- ``size`` specifies the number of samples in the dataset. This only needs to be
91
- passed if all data fields are passed as callables. Otherwise, the size is inferred
92
- from the length of the data fields passed as lists.
93
-
94
- Every sample in the dataset is assigned a numeric ID from 0 to ``size - 1``. This ID
95
- can be used to access the corresponding sample. For instance, ``dataset[0]`` returns
96
- a named tuple of all data fields for the first sample in the dataset.
97
-
98
- A data field kwarg passed as a list must be comprised of the same type of object,
99
- and its length must be consistent with the ``size`` argument (if specified) and the
100
- length of all other data fields passed as lists.
101
-
102
- Otherwise a data field kwarg passed as a callable must take a single argument
103
- corresponding to the numeric sample ID and return the data object for that sample
104
- ID. This data field for a given sample is then only lazily loaded into memory when
105
- the :py:meth:`Dataset.__getitem__` method is called.
106
-
107
- :param size: Optional, an integer indicating the size of the dataset, i.e. the
108
- number of samples. This only needs to be specified if all data
109
- :param kwargs: List or Callable. Keyword arguments specifying the data fields for
110
- the dataset.
111
- """
112
-
113
- def __init__(self, size: Optional[int] = None, **kwargs):
114
- if "sample_id" in kwargs:
115
- raise ValueError(
116
- "Keyword argument 'sample_id' is not accepted by Dataset."
117
- " For an indexed dataset, use the IndexedDataset class"
118
- " instead."
119
- )
120
-
121
- super(Dataset, self).__init__(arg_name="size", size=size, **kwargs)
122
-
123
- def __getitem__(self, idx: int) -> NamedTuple:
124
- """
125
- Returns the data for each field corresponding to the internal index ``idx``.
126
-
127
- Each item can be accessed with ``self[idx]``. Returned is a named tuple with
128
- fields corresponding to those passed (in order) to the constructor upon class
129
- initialization.
130
- """
131
- if idx not in self._indices:
132
- raise ValueError(f"Index {idx} not in dataset")
133
- names = self._field_names
134
- sample_data = []
135
- for name in self._field_names:
136
- if callable(self._data[name]): # lazy load
137
- try:
138
- sample_data.append(self._data[name](idx))
139
- except Exception as e:
140
- raise IOError(
141
- f"Error loading data field '{name}' at numeric"
142
- f" sample index {idx}: {e}"
143
- )
144
- else:
145
- assert isinstance(self._data[name], list)
146
- sample_data.append(self._data[name][idx])
147
-
148
- return namedtuple("Sample", names)(*sample_data)
149
-
150
-
151
- class IndexedDataset(_BaseDataset):
152
- """
153
- Defines a PyTorch compatible :py:class:`torch.data.Dataset` class for various named
154
- data fields, with sample indexed by a list of unique sample IDs.
155
-
156
- The data fields are specified as keyword arguments to the constructor, where the
157
- keyword is the name of the field, and the value is either a list of data objects or
158
- a callable.
159
-
160
- ``sample_id`` must be a unique list of any hashable object. Each respective sample
161
- ID is assigned an internal numeric index from 0 to ``len(sample_id) - 1``. This is
162
- used to internally index the dataset, and can be used to access a given sample. For
163
- instance, ``dataset[0]`` returns a named tuple of all data fields for the first
164
- sample in the dataset, i.e. the one with unique sample ID at ``sample_id[0]``. In
165
- order to access a sample by its ID, use the :py:meth:`IndexedDataset.get_sample`
166
- method.
167
-
168
- A data field kwarg passed as a list must be comprised of the same type of object,
169
- and its length must be consistent with the length of ``sample_id`` and the length of
170
- all other data fields passed as lists.
171
-
172
- Otherwise a data field kwarg passed as a callable must take a single argument
173
- corresponding to the unique sample ID (i.e. those passed in ``sample_id``) and
174
- return the data object for that sample ID. This data field for a given sample is
175
- then only lazily loaded into memory when :py:meth:`IndexedDataset.__getitem__` or
176
- :py:meth:`IndexedDataset.get_sample` methods are called.
177
-
178
- :param sample_id: A list of unique IDs for each sample in the dataset.
179
- :param kwargs: Keyword arguments specifying the data fields for the dataset.
180
- """
181
-
182
- def __init__(self, sample_id: List, **kwargs):
183
- if "size" in kwargs:
184
- raise ValueError(
185
- "Keyword argument 'size' is not accepted by IndexedDataset."
186
- " For a dataset defined on size rather than explicit sample IDs,"
187
- " use the Dataset class instead."
188
- )
189
- if len(set(sample_id)) != len(sample_id):
190
- raise ValueError("Sample IDs must be unique. Found duplicate sample IDs.")
191
-
192
- super(IndexedDataset, self).__init__(
193
- arg_name="sample_id", size=len(sample_id), **kwargs
194
- )
195
- self._sample_id = sample_id
196
- self._sample_id_to_idx = {smpl_id: idx for idx, smpl_id in enumerate(sample_id)}
197
-
198
- def __getitem__(self, idx: int) -> NamedTuple:
199
- """
200
- Returns the data for each field corresponding to the internal index ``idx``.
201
-
202
- Each item can be accessed with ``self[idx]``. Returned is a named tuple, whose
203
- first field is the sample ID, and the remaining fields correspond those passed
204
- (in order) to the constructor upon class initialization.
205
- """
206
- if idx not in self._indices:
207
- raise ValueError(f"Index {idx} not in dataset")
208
- names = ["sample_id"] + self._field_names
209
- sample_data = [self._sample_id[idx]]
210
- for name in self._field_names:
211
- if callable(self._data[name]): # lazy load using sample ID
212
- try:
213
- sample_data.append(self._data[name](self._sample_id[idx]))
214
- except Exception as e:
215
- raise IOError(
216
- f"Error loading data field '{name}' for sample"
217
- f" ID {self._sample_id[idx]}: {e}"
218
- )
219
- else:
220
- assert isinstance(self._data[name], list)
221
- sample_data.append(self._data[name][idx])
222
-
223
- return namedtuple("Sample", names)(*sample_data)
224
-
225
- def get_sample(self, sample_id) -> NamedTuple:
226
- """
227
- Returns a named tuple for the sample corresponding to the given ``sample_id``.
228
- """
229
- if sample_id not in self._sample_id_to_idx:
230
- raise ValueError(f"Sample ID '{sample_id}' not in dataset")
231
- return self[self._sample_id_to_idx[sample_id]]
@@ -1,7 +0,0 @@
1
- # placeholder test that is removed once the first test is add
2
- import metatensor.learn
3
-
4
-
5
- def test_dummpy():
6
- metatensor.learn
7
- pass