metatensor-learn 0.2.1__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.
- {metatensor-learn-0.2.1/metatensor_learn.egg-info → metatensor_learn-0.2.3}/PKG-INFO +5 -5
- metatensor_learn-0.2.3/metatensor/learn/data/_namedtuple.py +148 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/data/collate.py +2 -1
- metatensor_learn-0.2.3/metatensor/learn/data/dataset.py +398 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/__init__.py +8 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/_utils.py +53 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/layer_norm.py +348 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/linear.py +181 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/nn/module_map.py +6 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/relu.py +114 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/sequential.py +39 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/silu.py +114 -0
- metatensor_learn-0.2.3/metatensor/learn/nn/tanh.py +108 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3/metatensor_learn.egg-info}/PKG-INFO +5 -5
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/SOURCES.txt +7 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/pyproject.toml +4 -4
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/setup.py +1 -1
- metatensor_learn-0.2.3/tests/test_dummmy.py +7 -0
- metatensor-learn-0.2.1/metatensor/learn/data/dataset.py +0 -231
- metatensor-learn-0.2.1/metatensor/learn/nn/__init__.py +0 -5
- metatensor-learn-0.2.1/metatensor/learn/nn/linear.py +0 -138
- metatensor-learn-0.2.1/tests/test_dummmy.py +0 -7
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/AUTHORS +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/LICENSE +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/MANIFEST.in +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/README.rst +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/__init__.py +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/_backend.py +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/data/__init__.py +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor/learn/data/dataloader.py +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/dependency_links.txt +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/requires.txt +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/top_level.txt +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/metatensor_learn.egg-info/zip-safe +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/n_commits_since_last_tag +0 -0
- {metatensor-learn-0.2.1 → metatensor_learn-0.2.3}/setup.cfg +0 -0
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: metatensor-learn
|
|
3
|
-
Version: 0.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
|
|
7
|
-
Project-URL: homepage, https://
|
|
8
|
-
Project-URL: documentation, https://
|
|
7
|
+
Project-URL: homepage, https://docs.metatensor.org/latest/
|
|
8
|
+
Project-URL: documentation, https://docs.metatensor.org/latest/
|
|
9
9
|
Project-URL: repository, https://github.com/lab-cosmo/metatensor
|
|
10
|
-
Project-URL: changelog, https://
|
|
10
|
+
Project-URL: changelog, https://docs.metatensor.org/latest/learn/CHANGELOG.html
|
|
11
11
|
Keywords: machine learning,molecular modeling
|
|
12
12
|
Classifier: Development Status :: 4 - Beta
|
|
13
13
|
Classifier: Intended Audience :: Science/Research
|
|
@@ -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.
|
|
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]]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from .module_map import ModuleMap # noqa: F401
|
|
2
|
+
|
|
3
|
+
from .layer_norm import InvariantLayerNorm, LayerNorm # noqa: F401
|
|
4
|
+
from .linear import EquivariantLinear, Linear # noqa: F401
|
|
5
|
+
from .relu import InvariantReLU, ReLU # noqa: F401
|
|
6
|
+
from .sequential import Sequential # noqa: F401
|
|
7
|
+
from .silu import InvariantSiLU, SiLU # noqa: F401
|
|
8
|
+
from .tanh import InvariantTanh, Tanh # noqa: F401
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _check_module_map_parameter(
|
|
5
|
+
parameter, name: str, types: type, num_keys: int, keys_param_name: str
|
|
6
|
+
) -> List:
|
|
7
|
+
"""
|
|
8
|
+
A helper function that checks the type of an input parameter passed to classes that
|
|
9
|
+
are children of :py:class:`ModuleMap`, and raises the appropriate errors.
|
|
10
|
+
|
|
11
|
+
Raises a TypeError if not one of the valid `types`. Raises a ValueError if passed as
|
|
12
|
+
a list and not the same length as `num_keys`.
|
|
13
|
+
|
|
14
|
+
:param parameter: the parameter value to check
|
|
15
|
+
:param name: str, the name of the parameter used in the ModuleMap child class
|
|
16
|
+
:param types: the type that is valid for the `parameter`
|
|
17
|
+
:param num_keys: int, the number of relevant keys in the ModuleMap child class for
|
|
18
|
+
which the parameter is used. Used to check the length of `parameter` if passed
|
|
19
|
+
as a list.
|
|
20
|
+
:param keys_param_name: str, the name of the relevant keys parameter for the
|
|
21
|
+
ModuleMap child class. Used to raise a ValueError if the length of `parameter`
|
|
22
|
+
does not match the length of the keys.
|
|
23
|
+
|
|
24
|
+
:return: `parameter` as a list, one for each key.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# Convert to list if not already
|
|
28
|
+
if isinstance(parameter, types):
|
|
29
|
+
parameter = [parameter] * num_keys
|
|
30
|
+
|
|
31
|
+
# Check if it is a list
|
|
32
|
+
if isinstance(parameter, list):
|
|
33
|
+
if len(parameter) != num_keys:
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"`{name}` must have same length as `{keys_param_name}`,"
|
|
36
|
+
f" but len({name}) != len({keys_param_name})"
|
|
37
|
+
f" [{len(parameter)} != {num_keys}]"
|
|
38
|
+
)
|
|
39
|
+
# Check each element
|
|
40
|
+
for p in parameter:
|
|
41
|
+
if not isinstance(p, types):
|
|
42
|
+
raise TypeError(
|
|
43
|
+
f"`{name}` must be of type {types} or List of {types}, but not"
|
|
44
|
+
f" {type(p)}."
|
|
45
|
+
)
|
|
46
|
+
# Raise if not a list
|
|
47
|
+
else:
|
|
48
|
+
raise TypeError(
|
|
49
|
+
f"`{name}` must be type {types} or List of {types},"
|
|
50
|
+
f" but not {type(parameter)}."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
return parameter
|