anemoi-models 0.1.0__py3-none-any.whl
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.
- anemoi/models/__init__.py +9 -0
- anemoi/models/__main__.py +28 -0
- anemoi/models/_version.py +16 -0
- anemoi/models/commands/__init__.py +24 -0
- anemoi/models/commands/hello.py +32 -0
- anemoi/models/data_indices/__init__.py +0 -0
- anemoi/models/data_indices/collection.py +74 -0
- anemoi/models/data_indices/index.py +93 -0
- anemoi/models/data_indices/tensor.py +114 -0
- anemoi/models/distributed/__init__.py +0 -0
- anemoi/models/distributed/graph.py +298 -0
- anemoi/models/distributed/khop_edges.py +102 -0
- anemoi/models/distributed/primitives.py +142 -0
- anemoi/models/distributed/shapes.py +28 -0
- anemoi/models/distributed/transformer.py +173 -0
- anemoi/models/distributed/utils.py +31 -0
- anemoi/models/interface/__init__.py +110 -0
- anemoi/models/layers/__init__.py +0 -0
- anemoi/models/layers/attention.py +104 -0
- anemoi/models/layers/block.py +589 -0
- anemoi/models/layers/chunk.py +233 -0
- anemoi/models/layers/conv.py +141 -0
- anemoi/models/layers/graph.py +42 -0
- anemoi/models/layers/mapper.py +682 -0
- anemoi/models/layers/mlp.py +88 -0
- anemoi/models/layers/processor.py +335 -0
- anemoi/models/layers/utils.py +38 -0
- anemoi/models/models/__init__.py +0 -0
- anemoi/models/models/encoder_processor_decoder.py +264 -0
- anemoi/models/preprocessing/__init__.py +167 -0
- anemoi/models/preprocessing/imputer.py +210 -0
- anemoi/models/preprocessing/normalizer.py +182 -0
- anemoi_models-0.1.0.dist-info/LICENSE +201 -0
- anemoi_models-0.1.0.dist-info/METADATA +295 -0
- anemoi_models-0.1.0.dist-info/RECORD +38 -0
- anemoi_models-0.1.0.dist-info/WHEEL +5 -0
- anemoi_models-0.1.0.dist-info/entry_points.txt +2 -0
- anemoi_models-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# (C) Copyright 2024 European Centre for Medium-Range Weather Forecasts.
|
|
2
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
3
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
4
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
5
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
6
|
+
# nor does it submit to any jurisdiction.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
from ._version import __version__
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# (C) Copyright 2024 ECMWF.
|
|
3
|
+
#
|
|
4
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
5
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
6
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
7
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
8
|
+
# nor does it submit to any jurisdiction.
|
|
9
|
+
#
|
|
10
|
+
|
|
11
|
+
from anemoi.utils.cli import cli_main
|
|
12
|
+
from anemoi.utils.cli import make_parser
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .commands import COMMANDS
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# For read-the-docs
|
|
19
|
+
def create_parser():
|
|
20
|
+
return make_parser(__doc__, COMMANDS)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main():
|
|
24
|
+
cli_main(__version__, __doc__, COMMANDS)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if __name__ == "__main__":
|
|
28
|
+
main()
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# file generated by setuptools_scm
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
TYPE_CHECKING = False
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from typing import Tuple, Union
|
|
6
|
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
7
|
+
else:
|
|
8
|
+
VERSION_TUPLE = object
|
|
9
|
+
|
|
10
|
+
version: str
|
|
11
|
+
__version__: str
|
|
12
|
+
__version_tuple__: VERSION_TUPLE
|
|
13
|
+
version_tuple: VERSION_TUPLE
|
|
14
|
+
|
|
15
|
+
__version__ = version = '0.1.0'
|
|
16
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# (C) Copyright 2024 ECMWF.
|
|
3
|
+
#
|
|
4
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
5
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
6
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
7
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
8
|
+
# nor does it submit to any jurisdiction.
|
|
9
|
+
#
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
from anemoi.utils.cli import Command
|
|
14
|
+
from anemoi.utils.cli import Failed
|
|
15
|
+
from anemoi.utils.cli import register_commands
|
|
16
|
+
|
|
17
|
+
__all__ = ["Command"]
|
|
18
|
+
|
|
19
|
+
COMMANDS = register_commands(
|
|
20
|
+
os.path.dirname(__file__),
|
|
21
|
+
__name__,
|
|
22
|
+
lambda x: x.command(),
|
|
23
|
+
lambda name, error: Failed(name, error),
|
|
24
|
+
)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# (C) Copyright 2024 ECMWF.
|
|
3
|
+
#
|
|
4
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
5
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
6
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
7
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
8
|
+
# nor does it submit to any jurisdiction.
|
|
9
|
+
#
|
|
10
|
+
|
|
11
|
+
"""Command place holder. Delete when we have real commands.
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from . import Command
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def say_hello(greetings, who):
|
|
19
|
+
print(greetings, who)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Hello(Command):
|
|
23
|
+
|
|
24
|
+
def add_arguments(self, command_parser):
|
|
25
|
+
command_parser.add_argument("--greetings", default="hello")
|
|
26
|
+
command_parser.add_argument("--who", default="world")
|
|
27
|
+
|
|
28
|
+
def run(self, args):
|
|
29
|
+
say_hello(args.greetings, args.who)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
command = Hello
|
|
File without changes
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# (C) Copyright 2024 ECMWF.
|
|
2
|
+
#
|
|
3
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
4
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
5
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
6
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
7
|
+
# nor does it submit to any jurisdiction.
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
import operator
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
from omegaconf import OmegaConf
|
|
14
|
+
|
|
15
|
+
from anemoi.models.data_indices.index import BaseIndex
|
|
16
|
+
from anemoi.models.data_indices.index import DataIndex
|
|
17
|
+
from anemoi.models.data_indices.index import ModelIndex
|
|
18
|
+
from anemoi.models.data_indices.tensor import BaseTensorIndex
|
|
19
|
+
from anemoi.models.data_indices.tensor import InputTensorIndex
|
|
20
|
+
from anemoi.models.data_indices.tensor import OutputTensorIndex
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class IndexCollection:
|
|
24
|
+
"""Collection of data and model indices."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, config, name_to_index) -> None:
|
|
27
|
+
self.config = OmegaConf.to_container(config, resolve=True)
|
|
28
|
+
|
|
29
|
+
self.forcing = [] if config.data.forcing is None else OmegaConf.to_container(config.data.forcing, resolve=True)
|
|
30
|
+
self.diagnostic = (
|
|
31
|
+
[] if config.data.diagnostic is None else OmegaConf.to_container(config.data.diagnostic, resolve=True)
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
assert set(self.diagnostic).isdisjoint(self.forcing), (
|
|
35
|
+
f"Diagnostic and forcing variables overlap: {set(self.diagnostic).intersection(self.forcing)}. ",
|
|
36
|
+
"Please drop them at a dataset-level to exclude them from the training data.",
|
|
37
|
+
)
|
|
38
|
+
self.name_to_index = dict(sorted(name_to_index.items(), key=operator.itemgetter(1)))
|
|
39
|
+
name_to_index_model_input = {
|
|
40
|
+
name: i for i, name in enumerate(key for key in self.name_to_index if key not in self.diagnostic)
|
|
41
|
+
}
|
|
42
|
+
name_to_index_model_output = {
|
|
43
|
+
name: i for i, name in enumerate(key for key in self.name_to_index if key not in self.forcing)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
self.data = DataIndex(self.diagnostic, self.forcing, self.name_to_index)
|
|
47
|
+
self.model = ModelIndex(self.diagnostic, self.forcing, name_to_index_model_input, name_to_index_model_output)
|
|
48
|
+
|
|
49
|
+
def __repr__(self) -> str:
|
|
50
|
+
return f"IndexCollection(config={self.config}, name_to_index={self.name_to_index})"
|
|
51
|
+
|
|
52
|
+
def __eq__(self, other):
|
|
53
|
+
if not isinstance(other, IndexCollection):
|
|
54
|
+
# don't attempt to compare against unrelated types
|
|
55
|
+
return NotImplemented
|
|
56
|
+
|
|
57
|
+
return self.model == other.model and self.data == other.data
|
|
58
|
+
|
|
59
|
+
def __getitem__(self, key):
|
|
60
|
+
return getattr(self, key)
|
|
61
|
+
|
|
62
|
+
def todict(self):
|
|
63
|
+
return {
|
|
64
|
+
"data": self.data.todict(),
|
|
65
|
+
"model": self.model.todict(),
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def representer(dumper, data):
|
|
70
|
+
return dumper.represent_scalar(f"!{data.__class__.__name__}", repr(data))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
for cls in [BaseTensorIndex, InputTensorIndex, OutputTensorIndex, BaseIndex, DataIndex, ModelIndex, IndexCollection]:
|
|
74
|
+
yaml.add_representer(cls, cls.representer)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# (C) Copyright 2024 ECMWF.
|
|
2
|
+
#
|
|
3
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
4
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
5
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
6
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
7
|
+
# nor does it submit to any jurisdiction.
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
from anemoi.models.data_indices.tensor import InputTensorIndex
|
|
11
|
+
from anemoi.models.data_indices.tensor import OutputTensorIndex
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BaseIndex:
|
|
15
|
+
"""Base class for data and model indices."""
|
|
16
|
+
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
self.input = NotImplementedError
|
|
19
|
+
self.output = NotImplementedError
|
|
20
|
+
|
|
21
|
+
def __eq__(self, other):
|
|
22
|
+
if not isinstance(other, BaseIndex):
|
|
23
|
+
# don't attempt to compare against unrelated types
|
|
24
|
+
return NotImplemented
|
|
25
|
+
|
|
26
|
+
return self.input == other.input and self.output == other.output
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"{self.__class__.__name__}(input={self.input}, output={self.output})"
|
|
30
|
+
|
|
31
|
+
def __getitem__(self, key):
|
|
32
|
+
return getattr(self, key)
|
|
33
|
+
|
|
34
|
+
def todict(self):
|
|
35
|
+
return {
|
|
36
|
+
"input": self.input.todict(),
|
|
37
|
+
"output": self.output.todict(),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def representer(dumper, data):
|
|
42
|
+
return dumper.represent_scalar(f"!{data.__class__.__name__}", repr(data))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class DataIndex(BaseIndex):
|
|
46
|
+
"""Indexing for data variables."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, diagnostic, forcing, name_to_index) -> None:
|
|
49
|
+
self._diagnostic = diagnostic
|
|
50
|
+
self._forcing = forcing
|
|
51
|
+
self._name_to_index = name_to_index
|
|
52
|
+
self.input = InputTensorIndex(
|
|
53
|
+
includes=forcing,
|
|
54
|
+
excludes=diagnostic,
|
|
55
|
+
name_to_index=name_to_index,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
self.output = OutputTensorIndex(
|
|
59
|
+
includes=diagnostic,
|
|
60
|
+
excludes=forcing,
|
|
61
|
+
name_to_index=name_to_index,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def __repr__(self) -> str:
|
|
65
|
+
return f"{self.__class__.__name__}(diagnostic={self._input}, forcing={self._output}, name_to_index={self._name_to_index})"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ModelIndex(BaseIndex):
|
|
69
|
+
"""Indexing for model variables."""
|
|
70
|
+
|
|
71
|
+
def __init__(self, diagnostic, forcing, name_to_index_model_input, name_to_index_model_output) -> None:
|
|
72
|
+
self._diagnostic = diagnostic
|
|
73
|
+
self._forcing = forcing
|
|
74
|
+
self._name_to_index_model_input = name_to_index_model_input
|
|
75
|
+
self._name_to_index_model_output = name_to_index_model_output
|
|
76
|
+
self.input = InputTensorIndex(
|
|
77
|
+
includes=forcing,
|
|
78
|
+
excludes=[],
|
|
79
|
+
name_to_index=name_to_index_model_input,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
self.output = OutputTensorIndex(
|
|
83
|
+
includes=diagnostic,
|
|
84
|
+
excludes=[],
|
|
85
|
+
name_to_index=name_to_index_model_output,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def __repr__(self) -> str:
|
|
89
|
+
return (
|
|
90
|
+
f"{self.__class__.__name__}(diagnostic={self._input}, forcing={self._output}, "
|
|
91
|
+
f"name_to_index_model_input={self._name_to_index_model_input}, "
|
|
92
|
+
f"name_to_index_model_output={self._name_to_index_model_output})"
|
|
93
|
+
)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# (C) Copyright 2024 ECMWF.
|
|
2
|
+
#
|
|
3
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
4
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
5
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
6
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
7
|
+
# nor does it submit to any jurisdiction.
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BaseTensorIndex:
|
|
14
|
+
"""Indexing for variables in index as Tensor."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, *, includes: list[str], excludes: list[str], name_to_index: dict[str, int]) -> None:
|
|
17
|
+
"""Initialize indexing tensors from includes and excludes using name_to_index.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
includes : list[str]
|
|
22
|
+
Variables to include in the indexing that are exclusive to this indexing.
|
|
23
|
+
e.g. Forcing variables for the input indexing, diagnostic variables for the output indexing
|
|
24
|
+
excludes : list[str]
|
|
25
|
+
Variables to exclude from the indexing.
|
|
26
|
+
e.g. Diagnostic variables for the input indexing, forcing variables for the output indexing
|
|
27
|
+
name_to_index : dict[str, int]
|
|
28
|
+
Dictionary mapping variable names to their index in the Tensor.
|
|
29
|
+
"""
|
|
30
|
+
self.includes = includes
|
|
31
|
+
self.excludes = excludes
|
|
32
|
+
self.name_to_index = name_to_index
|
|
33
|
+
|
|
34
|
+
assert set(self.excludes).issubset(
|
|
35
|
+
self.name_to_index.keys(),
|
|
36
|
+
), f"Data indexing has invalid entries {[var for var in self.excludes if var not in self.name_to_index]}, not in dataset."
|
|
37
|
+
assert set(self.includes).issubset(
|
|
38
|
+
self.name_to_index.keys(),
|
|
39
|
+
), f"Data indexing has invalid entries {[var for var in self.includes if var not in self.name_to_index]}, not in dataset."
|
|
40
|
+
|
|
41
|
+
self.full = self._build_idx_from_excludes()
|
|
42
|
+
self._only = self._build_idx_from_includes()
|
|
43
|
+
self._removed = self._build_idx_from_includes(self.excludes)
|
|
44
|
+
self.prognostic = self._build_idx_prognostic()
|
|
45
|
+
self.diagnostic = NotImplementedError
|
|
46
|
+
self.forcing = NotImplementedError
|
|
47
|
+
|
|
48
|
+
def __len__(self) -> int:
|
|
49
|
+
return len(self.full)
|
|
50
|
+
|
|
51
|
+
def __repr__(self) -> str:
|
|
52
|
+
return f"{self.__class__.__name__}(includes={self.includes}, excludes={self.excludes}, name_to_index={self.name_to_index})"
|
|
53
|
+
|
|
54
|
+
def __eq__(self, other):
|
|
55
|
+
if not isinstance(other, BaseTensorIndex):
|
|
56
|
+
# don't attempt to compare against unrelated types
|
|
57
|
+
return NotImplemented
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
torch.allclose(self.full, other.full)
|
|
61
|
+
and torch.allclose(self._only, other._only)
|
|
62
|
+
and torch.allclose(self._removed, other._removed)
|
|
63
|
+
and torch.allclose(self.prognostic, other.prognostic)
|
|
64
|
+
and torch.allclose(self.diagnostic, other.diagnostic)
|
|
65
|
+
and torch.allclose(self.forcing, other.forcing)
|
|
66
|
+
and self.includes == other.includes
|
|
67
|
+
and self.excludes == other.excludes
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def __getitem__(self, key):
|
|
71
|
+
return getattr(self, key)
|
|
72
|
+
|
|
73
|
+
def todict(self):
|
|
74
|
+
return {
|
|
75
|
+
"full": self.full,
|
|
76
|
+
"prognostic": self.prognostic,
|
|
77
|
+
"diagnostic": self.diagnostic,
|
|
78
|
+
"forcing": self.forcing,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def representer(dumper, data):
|
|
83
|
+
return dumper.represent_scalar(f"!{data.__class__.__name__}", repr(data))
|
|
84
|
+
|
|
85
|
+
def _build_idx_from_excludes(self, excludes=None) -> "torch.Tensor[int]":
|
|
86
|
+
if excludes is None:
|
|
87
|
+
excludes = self.excludes
|
|
88
|
+
return torch.Tensor(sorted(i for name, i in self.name_to_index.items() if name not in excludes)).to(torch.int)
|
|
89
|
+
|
|
90
|
+
def _build_idx_from_includes(self, includes=None) -> "torch.Tensor[int]":
|
|
91
|
+
if includes is None:
|
|
92
|
+
includes = self.includes
|
|
93
|
+
return torch.Tensor(sorted(self.name_to_index[name] for name in includes)).to(torch.int)
|
|
94
|
+
|
|
95
|
+
def _build_idx_prognostic(self) -> "torch.Tensor[int]":
|
|
96
|
+
return self._build_idx_from_excludes(self.includes + self.excludes)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class InputTensorIndex(BaseTensorIndex):
|
|
100
|
+
"""Indexing for input variables."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, *, includes: list[str], excludes: list[str], name_to_index: dict[str, int]) -> None:
|
|
103
|
+
super().__init__(includes=includes, excludes=excludes, name_to_index=name_to_index)
|
|
104
|
+
self.forcing = self._only
|
|
105
|
+
self.diagnostic = self._removed
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class OutputTensorIndex(BaseTensorIndex):
|
|
109
|
+
"""Indexing for output variables."""
|
|
110
|
+
|
|
111
|
+
def __init__(self, *, includes: list[str], excludes: list[str], name_to_index: dict[str, int]) -> None:
|
|
112
|
+
super().__init__(includes=includes, excludes=excludes, name_to_index=name_to_index)
|
|
113
|
+
self.forcing = self._removed
|
|
114
|
+
self.diagnostic = self._only
|
|
File without changes
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# (C) Copyright 2024 ECMWF.
|
|
2
|
+
#
|
|
3
|
+
# This software is licensed under the terms of the Apache Licence Version 2.0
|
|
4
|
+
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
|
|
5
|
+
# In applying this licence, ECMWF does not waive the privileges and immunities
|
|
6
|
+
# granted to it by virtue of its status as an intergovernmental organisation
|
|
7
|
+
# nor does it submit to any jurisdiction.
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
from torch import Tensor
|
|
13
|
+
from torch.distributed.distributed_c10d import ProcessGroup
|
|
14
|
+
|
|
15
|
+
from anemoi.models.distributed.primitives import _gather
|
|
16
|
+
from anemoi.models.distributed.primitives import _reduce
|
|
17
|
+
from anemoi.models.distributed.primitives import _split
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def shard_tensor(
|
|
21
|
+
input_: Tensor, dim: int, shapes: tuple, mgroup: ProcessGroup, gather_in_backward: bool = True
|
|
22
|
+
) -> Tensor:
|
|
23
|
+
"""Shard tensor.
|
|
24
|
+
|
|
25
|
+
Keeps only part of the tensor that is relevant for the current rank.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
input_ : Tensor
|
|
30
|
+
Input
|
|
31
|
+
dim : int
|
|
32
|
+
dimension along which to shard
|
|
33
|
+
shapes : tuple
|
|
34
|
+
Shapes of sharded Tensors
|
|
35
|
+
mgroup : ProcessGroup
|
|
36
|
+
model communication group
|
|
37
|
+
gather_in_backward : bool
|
|
38
|
+
perform gather in backward, default True
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
Tensor
|
|
43
|
+
Sharded tensor.
|
|
44
|
+
"""
|
|
45
|
+
return _ShardParallelSection.apply(input_, dim, shapes, gather_in_backward, mgroup)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def gather_tensor(input_: Tensor, dim: int, shapes: tuple, mgroup: ProcessGroup) -> Tensor:
|
|
49
|
+
"""Gather tensor.
|
|
50
|
+
|
|
51
|
+
Gathers tensor shards from ranks.
|
|
52
|
+
|
|
53
|
+
Parameters
|
|
54
|
+
----------
|
|
55
|
+
input_ : Tensor
|
|
56
|
+
Input
|
|
57
|
+
dim : int
|
|
58
|
+
dimension along which to gather
|
|
59
|
+
shapes : tuple
|
|
60
|
+
Shapes of sharded Tensors
|
|
61
|
+
mgroup : ProcessGroup
|
|
62
|
+
model communication group
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
Tensor
|
|
67
|
+
Gathered tensor.
|
|
68
|
+
"""
|
|
69
|
+
return _GatherParallelSection.apply(input_, dim, shapes, mgroup)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def reduce_tensor(input_: Tensor, mgroup: ProcessGroup) -> Tensor:
|
|
73
|
+
"""Reduce tensor.
|
|
74
|
+
|
|
75
|
+
Reduces tensor across ranks.
|
|
76
|
+
|
|
77
|
+
Parameters
|
|
78
|
+
----------
|
|
79
|
+
input_ : Tensor
|
|
80
|
+
Input
|
|
81
|
+
mgroup : ProcessGroup
|
|
82
|
+
model communication group
|
|
83
|
+
|
|
84
|
+
Returns
|
|
85
|
+
-------
|
|
86
|
+
Tensor
|
|
87
|
+
Reduced tensor.
|
|
88
|
+
"""
|
|
89
|
+
return _ReduceParallelSection.apply(input_, mgroup)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def sync_tensor(input_: Tensor, dim: int, shapes: tuple, mgroup: ProcessGroup) -> Tensor:
|
|
93
|
+
"""Sync tensor.
|
|
94
|
+
|
|
95
|
+
Perform a gather in the forward pass and an allreduce followed by a split in the backward pass.
|
|
96
|
+
|
|
97
|
+
Parameters
|
|
98
|
+
----------
|
|
99
|
+
input_ : Tensor
|
|
100
|
+
Input
|
|
101
|
+
dim : int
|
|
102
|
+
dimension along which to gather
|
|
103
|
+
shapes : tuple
|
|
104
|
+
Shapes of sharded Tensors
|
|
105
|
+
mgroup : ProcessGroup
|
|
106
|
+
model communication group
|
|
107
|
+
|
|
108
|
+
Returns
|
|
109
|
+
-------
|
|
110
|
+
Tensor
|
|
111
|
+
Synced tensor.
|
|
112
|
+
"""
|
|
113
|
+
return _SyncParallelSection.apply(input_, dim, shapes, mgroup)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def reduce_shard_tensor(input_: Tensor, dim: int, shapes: tuple, mgroup: ProcessGroup) -> Tensor:
|
|
117
|
+
"""Reduces and then shards tensor.
|
|
118
|
+
|
|
119
|
+
Perform an allreduce followed by a split in the forward pass and a gather in the backward pass.
|
|
120
|
+
|
|
121
|
+
Parameters
|
|
122
|
+
----------
|
|
123
|
+
input_ : Tensor
|
|
124
|
+
Input
|
|
125
|
+
dim : int
|
|
126
|
+
dimension along which to gather
|
|
127
|
+
shapes : tuple
|
|
128
|
+
Shapes of sharded Tensors
|
|
129
|
+
mgroup : ProcessGroup
|
|
130
|
+
model communication group
|
|
131
|
+
|
|
132
|
+
Returns
|
|
133
|
+
-------
|
|
134
|
+
Tensor
|
|
135
|
+
Reduced sharded tensor.
|
|
136
|
+
"""
|
|
137
|
+
return _ReduceShardParallelSection.apply(input_, dim, shapes, mgroup)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _SyncParallelSection(torch.autograd.Function):
|
|
141
|
+
"""Sync the input from parallel section."""
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def forward(ctx, input_, dim_, shapes_, mgroup_):
|
|
145
|
+
ctx.dim = dim_
|
|
146
|
+
ctx.comm_group = mgroup_
|
|
147
|
+
ctx.shapes = shapes_
|
|
148
|
+
if mgroup_:
|
|
149
|
+
return _gather(input_, dim_, shapes_, group=mgroup_)
|
|
150
|
+
return input_
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def backward(ctx, grad_output):
|
|
154
|
+
if ctx.comm_group:
|
|
155
|
+
grad_output = _reduce(grad_output, group=ctx.comm_group)
|
|
156
|
+
return (
|
|
157
|
+
_split(grad_output, ctx.dim, ctx.shapes, group=ctx.comm_group),
|
|
158
|
+
None,
|
|
159
|
+
None,
|
|
160
|
+
None,
|
|
161
|
+
)
|
|
162
|
+
return grad_output, None, None, None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class _ReduceShardParallelSection(torch.autograd.Function):
|
|
166
|
+
"""All-reduce and shard the input from the parallel section."""
|
|
167
|
+
|
|
168
|
+
# Modified from
|
|
169
|
+
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
170
|
+
#
|
|
171
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
172
|
+
# you may not use this file except in compliance with the License.
|
|
173
|
+
# You may obtain a copy of the License at
|
|
174
|
+
#
|
|
175
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
176
|
+
#
|
|
177
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
178
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
179
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
180
|
+
# See the License for the specific language governing permissions and
|
|
181
|
+
# limitations under the License.
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def forward(ctx, input_, dim_, shapes_, mgroup_):
|
|
185
|
+
ctx.dim = dim_
|
|
186
|
+
ctx.comm_group = mgroup_
|
|
187
|
+
ctx.shapes = shapes_
|
|
188
|
+
if mgroup_:
|
|
189
|
+
input_ = _reduce(input_, group=mgroup_)
|
|
190
|
+
return _split(input_, dim_, shapes_, group=mgroup_)
|
|
191
|
+
return input_
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def backward(ctx, grad_output):
|
|
195
|
+
if ctx.comm_group:
|
|
196
|
+
return (
|
|
197
|
+
_gather(grad_output, ctx.dim, ctx.shapes, group=ctx.comm_group),
|
|
198
|
+
None,
|
|
199
|
+
None,
|
|
200
|
+
None,
|
|
201
|
+
)
|
|
202
|
+
return grad_output, None, None, None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class _ShardParallelSection(torch.autograd.Function):
|
|
206
|
+
"""Split the input and keep only the relevant chunck to the rank."""
|
|
207
|
+
|
|
208
|
+
# Modified from
|
|
209
|
+
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
210
|
+
#
|
|
211
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
212
|
+
# you may not use this file except in compliance with the License.
|
|
213
|
+
# You may obtain a copy of the License at
|
|
214
|
+
#
|
|
215
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
216
|
+
#
|
|
217
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
218
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
219
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
220
|
+
# See the License for the specific language governing permissions and
|
|
221
|
+
# limitations under the License.
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def forward(ctx, input_, dim_, shapes_, gather_in_backward_, mgroup_):
|
|
225
|
+
ctx.dim = dim_
|
|
226
|
+
ctx.comm_group = mgroup_
|
|
227
|
+
ctx.shapes = shapes_
|
|
228
|
+
ctx.gather_in_backward = gather_in_backward_
|
|
229
|
+
if mgroup_:
|
|
230
|
+
return _split(input_, dim_, shapes_, group=mgroup_)
|
|
231
|
+
return input_
|
|
232
|
+
|
|
233
|
+
@staticmethod
|
|
234
|
+
def backward(ctx, grad_output):
|
|
235
|
+
if ctx.comm_group:
|
|
236
|
+
return (
|
|
237
|
+
_gather(
|
|
238
|
+
grad_output, ctx.dim, ctx.shapes, gather_in_backward=ctx.gather_in_backward, group=ctx.comm_group
|
|
239
|
+
),
|
|
240
|
+
None,
|
|
241
|
+
None,
|
|
242
|
+
None,
|
|
243
|
+
None,
|
|
244
|
+
)
|
|
245
|
+
return grad_output, None, None, None, None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class _GatherParallelSection(torch.autograd.Function):
|
|
249
|
+
"""Gather the input from parallel section and concatenate."""
|
|
250
|
+
|
|
251
|
+
# Modified from
|
|
252
|
+
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
253
|
+
#
|
|
254
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
255
|
+
# you may not use this file except in compliance with the License.
|
|
256
|
+
# You may obtain a copy of the License at
|
|
257
|
+
#
|
|
258
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
259
|
+
#
|
|
260
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
261
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
262
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
263
|
+
# See the License for the specific language governing permissions and
|
|
264
|
+
# limitations under the License.
|
|
265
|
+
|
|
266
|
+
@staticmethod
|
|
267
|
+
def forward(ctx, input_, dim_, shapes_, mgroup_):
|
|
268
|
+
ctx.dim = dim_
|
|
269
|
+
ctx.comm_group = mgroup_
|
|
270
|
+
ctx.shapes = shapes_
|
|
271
|
+
if mgroup_:
|
|
272
|
+
return _gather(input_, dim_, shapes_, group=mgroup_)
|
|
273
|
+
return input_
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def backward(ctx, grad_output):
|
|
277
|
+
if ctx.comm_group:
|
|
278
|
+
return (
|
|
279
|
+
_split(grad_output, ctx.dim, ctx.shapes, group=ctx.comm_group),
|
|
280
|
+
None,
|
|
281
|
+
None,
|
|
282
|
+
None,
|
|
283
|
+
)
|
|
284
|
+
return grad_output, None, None, None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
class _ReduceParallelSection(torch.autograd.Function):
|
|
288
|
+
"""All-reduce the input from the parallel section."""
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def forward(ctx, input_, mgroup_):
|
|
292
|
+
if mgroup_:
|
|
293
|
+
return _reduce(input_, group=mgroup_)
|
|
294
|
+
return input_
|
|
295
|
+
|
|
296
|
+
@staticmethod
|
|
297
|
+
def backward(ctx, grad_output):
|
|
298
|
+
return grad_output, None
|