assassinlike commited on
Commit
504ed7c
·
verified ·
1 Parent(s): 2c66237

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/__init__.cpython-38.pyc +0 -0
  2. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_composable_state.cpython-38.pyc +0 -0
  3. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-38.pyc +0 -0
  4. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-38.pyc +0 -0
  5. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-38.pyc +0 -0
  6. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/argparse_util.cpython-38.pyc +0 -0
  7. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-38.pyc +0 -0
  8. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/collective_utils.cpython-38.pyc +0 -0
  9. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/constants.cpython-38.pyc +0 -0
  10. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/device_mesh.cpython-38.pyc +0 -0
  11. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/launch.cpython-38.pyc +0 -0
  12. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-38.pyc +0 -0
  13. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/remote_device.cpython-38.pyc +0 -0
  14. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/rendezvous.cpython-38.pyc +0 -0
  15. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/run.cpython-38.pyc +0 -0
  16. data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/utils.cpython-38.pyc +0 -0
  17. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__init__.py +4 -0
  18. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/__init__.cpython-38.pyc +0 -0
  19. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-38.pyc +0 -0
  20. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/contract.cpython-38.pyc +0 -0
  21. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/fully_shard.cpython-38.pyc +0 -0
  22. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/replicate.cpython-38.pyc +0 -0
  23. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/checkpoint_activation.py +95 -0
  24. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/contract.py +195 -0
  25. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__init__.py +2 -0
  26. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-38.pyc +0 -0
  27. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_api.cpython-38.pyc +0 -0
  28. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_collectives.cpython-38.pyc +0 -0
  29. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_common.cpython-38.pyc +0 -0
  30. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_init.cpython-38.pyc +0 -0
  31. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param.cpython-38.pyc +0 -0
  32. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param_group.cpython-38.pyc +0 -0
  33. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_state.cpython-38.pyc +0 -0
  34. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-38.pyc +0 -0
  35. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_api.py +80 -0
  36. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_collectives.py +315 -0
  37. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py +153 -0
  38. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_init.py +148 -0
  39. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_param.py +661 -0
  40. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_param_group.py +544 -0
  41. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_state.py +256 -0
  42. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/fully_shard.py +348 -0
  43. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fully_shard.py +131 -0
  44. data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/replicate.py +248 -0
  45. data/home/.local/lib/python3.8/site-packages/torch/distributed/_cuda_p2p/__init__.py +491 -0
  46. data/home/.local/lib/python3.8/site-packages/torch/distributed/_cuda_p2p/__pycache__/__init__.cpython-38.pyc +0 -0
  47. data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/__init__.py +6 -0
  48. data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/_utils.py +28 -0
  49. data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/api.py +291 -0
  50. data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/common_op_utils.py +62 -0
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (4 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_composable_state.cpython-38.pyc ADDED
Binary file (1.32 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-38.pyc ADDED
Binary file (31 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-38.pyc ADDED
Binary file (2.76 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-38.pyc ADDED
Binary file (18.4 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/argparse_util.cpython-38.pyc ADDED
Binary file (3.94 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-38.pyc ADDED
Binary file (3.16 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/collective_utils.cpython-38.pyc ADDED
Binary file (5.48 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/constants.cpython-38.pyc ADDED
Binary file (528 Bytes). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/device_mesh.cpython-38.pyc ADDED
Binary file (22.4 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/launch.cpython-38.pyc ADDED
Binary file (7.8 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-38.pyc ADDED
Binary file (375 Bytes). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/remote_device.cpython-38.pyc ADDED
Binary file (3.82 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/rendezvous.cpython-38.pyc ADDED
Binary file (8.84 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/run.cpython-38.pyc ADDED
Binary file (29.6 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/__pycache__/utils.cpython-38.pyc ADDED
Binary file (11.1 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .checkpoint_activation import checkpoint
2
+ from .contract import _get_registry, contract
3
+ from .fully_shard import fully_shard
4
+ from .replicate import replicate
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (342 Bytes). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-38.pyc ADDED
Binary file (3.34 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/contract.cpython-38.pyc ADDED
Binary file (5.16 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/fully_shard.cpython-38.pyc ADDED
Binary file (3.83 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/__pycache__/replicate.cpython-38.pyc ADDED
Binary file (7.05 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/checkpoint_activation.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from contextlib import contextmanager, nullcontext
3
+ from typing import Any, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.utils.checkpoint import (
8
+ _checkpoint_without_reentrant_generator,
9
+ _DEFAULT_DETERMINISM_MODE,
10
+ )
11
+
12
+ from .contract import contract
13
+
14
+
15
+ @contextmanager
16
+ def _no_hook(module: nn.Module):
17
+ r"""
18
+ Disable hooks installed by checkpoint to avoid unintentional recursion
19
+ during backward recomputation.
20
+ """
21
+ orig_enable_hook = checkpoint.state(module).enable_hook
22
+ checkpoint.state(module).enable_hook = False
23
+ try:
24
+ yield
25
+ finally:
26
+ checkpoint.state(module).enable_hook = orig_enable_hook
27
+
28
+
29
+ @contract()
30
+ def checkpoint(module: nn.Module) -> nn.Module:
31
+ r"""
32
+ This is a composable activation checkpointing API. Unlike functional
33
+ activation checkpointing APIs, this one does not require changing model
34
+ source code. Unlike ``nn.Module`` wrapper activation checkpointing APIs,
35
+ this one does not modify model structure or fully-qualified names either.
36
+ Under the hood, it registers activation checkpointing logic as pre- and
37
+ post-forward hooks. Hence, this API can be easily applied to any model or
38
+ sub-modules in the model.
39
+
40
+ Args:
41
+ module (nn.Module): the target model or sub-module to apply activation
42
+ checkpointing.
43
+
44
+ Example::
45
+ >>> # xdoctest: +SKIP
46
+ >>> import torch.nn as nn
47
+ >>>
48
+ >>> class MyModel(nn.Module):
49
+ >>> def __init__(self):
50
+ >>> super().__init__()
51
+ >>> self.l1 = nn.Linear(10, 10)
52
+ >>> self.l2 = nn.Linear(10, 10)
53
+ >>>
54
+ >>> def forward(self, x):
55
+ >>> return self.l2(self.l1(x))
56
+ >>>
57
+ >>> model = MyModel()
58
+ >>> checkpoint(model.l1) # apply activation checkpointing only to l1
59
+ >>> model(torch.zeros(2, 10)).sum().backward()
60
+
61
+ """
62
+ torch._C._log_api_usage_once("torch.distributed.checkpoint")
63
+
64
+ def forward_pre_hook(module: nn.Module, inputs: Tuple[Any, ...]) -> None:
65
+ if checkpoint.state(module).enable_hook:
66
+
67
+ def context_fns():
68
+ return nullcontext(), _no_hook(module)
69
+
70
+ checkpoint.state(
71
+ module
72
+ )._ac_generator = _checkpoint_without_reentrant_generator(
73
+ module, True, context_fns, _DEFAULT_DETERMINISM_MODE, False, *inputs
74
+ )
75
+ next(checkpoint.state(module)._ac_generator)
76
+
77
+ def forward_hook(module: nn.Module, inputs: Tuple[Any, ...], output: Any) -> Any:
78
+ if checkpoint.state(module).enable_hook:
79
+ try:
80
+ next(checkpoint.state(module)._ac_generator)
81
+ except StopIteration:
82
+ pass
83
+ else:
84
+ raise RuntimeError(
85
+ "Expected non-reentrant activation checkpoint generator to be exhausted, but it was not!"
86
+ )
87
+
88
+ # Ensure that we no longer hold on to the generator. always_call=True helps ensure we
89
+ # clear this even in the case of exception in fwd pass.
90
+ checkpoint.state(module)._ac_generator = None
91
+
92
+ checkpoint.state(module).enable_hook = True
93
+ module.register_forward_pre_hook(forward_pre_hook)
94
+ module.register_forward_hook(forward_hook, prepend=True, always_call=True)
95
+ return module
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/contract.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import uuid
3
+ from collections import OrderedDict
4
+ from functools import wraps
5
+ from typing import Callable, Dict, List, Optional, Type
6
+
7
+ import torch.nn as nn
8
+ from torch.distributed._composable_state import _State
9
+
10
+
11
+ def generate_state_key(string="__composable_api_state_key"):
12
+ return f"{string}_{str(uuid.uuid4())}"
13
+
14
+
15
+ STATE_KEY = generate_state_key()
16
+ REGISTRY_KEY = generate_state_key()
17
+
18
+
19
+ # TODO: we can add additional info to RegistryItem to share across APIs. E.g.,
20
+ # we can add args and kwargs here, and then we can detect whether fully_shard
21
+ # is combined with reentrant activation checkpointing and error out with a clear
22
+ # message.
23
+ class RegistryItem:
24
+ pass
25
+
26
+
27
+ def contract(state_cls: Type[_State] = _State):
28
+ r"""
29
+ Decorate a function as a composable distributed API, where the first
30
+ argument of the function must be an :class:`nn.Module` instance. The
31
+ decorator verifies that the wrapped function does not modify parameter,
32
+ buffer or sub-module fully-qualified names (FQN).
33
+
34
+ When a function ``func`` is decorated by ``@contract()``, a
35
+ ``.state(module: nn.Module)`` method will be installed to the decorated
36
+ function. Then you can retrieve and modify the state on a module by calling
37
+ ``func.state(module)``.
38
+
39
+ Example::
40
+ >>> # xdoctest: +SKIP
41
+ >>> import torch.nn as nn
42
+ >>>
43
+ >>> class MyModel(nn.Module):
44
+ >>> def __init__(self):
45
+ >>> super().__init__()
46
+ >>> self.l1 = nn.Linear(10, 10)
47
+ >>> self.l2 = nn.Linear(10, 10)
48
+ >>>
49
+ >>> def forward(self, x):
50
+ >>> return self.l2(self.l1(x))
51
+ >>>
52
+ >>> @contract()
53
+ >>> def my_feature(module: nn.Module) -> nn.Module:
54
+ >>> my_feature.state(module).some_state = "any value"
55
+ >>> return module
56
+ >>>
57
+ >>> model = MyModel()
58
+ >>> my_feature(model.l1)
59
+ >>> assert my_feature.state(model.l1).some_state == "any value"
60
+ >>> my_feature(model.l2)
61
+ >>> model(torch.randn(2, 10)).sum().backward()
62
+ """
63
+
64
+ # wraps will make functions decorated with contract() pickleable - needed for integration with torch.package
65
+ @wraps(state_cls)
66
+ def inner(func):
67
+ @wraps(func)
68
+ def wrapper(module: nn.Module, *args, **kwargs) -> Optional[nn.Module]:
69
+ # get existing global states
70
+ default_all_state: Dict[Callable, _State] = OrderedDict()
71
+ all_state: Dict[Callable, _State] = module.__dict__.setdefault( # type: ignore[call-overload]
72
+ STATE_KEY, default_all_state
73
+ )
74
+ assert isinstance(
75
+ all_state, dict
76
+ ), "Distributed composable API states corrupted"
77
+
78
+ # get global registry
79
+ default_registry: Dict[str, RegistryItem] = OrderedDict()
80
+ registry: Dict[str, RegistryItem] = module.__dict__.setdefault( # type: ignore[call-overload]
81
+ REGISTRY_KEY, default_registry
82
+ )
83
+
84
+ assert isinstance(
85
+ registry, dict
86
+ ), "Distributed composable API registry corrupted"
87
+
88
+ # make sure the API func has not been applied to the input module yet.
89
+ assert func not in all_state and func.__name__ not in registry, (
90
+ "Each distinct composable distributed API can only be applied to a "
91
+ f"module once. {func.__name__} has already been applied to the "
92
+ f"following module.\n{module}"
93
+ )
94
+
95
+ # install states specific to the wrapped ``func``
96
+ all_state.setdefault(func, state_cls())
97
+ # register ``func`` in the global registry by name
98
+ registry.setdefault(func.__name__, RegistryItem())
99
+
100
+ orig_named_params = OrderedDict(module.named_parameters())
101
+ orig_named_buffers = OrderedDict(
102
+ module.named_buffers(remove_duplicate=False)
103
+ )
104
+ orig_named_modules = OrderedDict(
105
+ module.named_modules(remove_duplicate=False)
106
+ )
107
+
108
+ updated = func(module, *args, **kwargs)
109
+
110
+ if updated is None:
111
+ updated = module
112
+
113
+ new_named_params = OrderedDict(updated.named_parameters())
114
+ new_named_buffers = OrderedDict(
115
+ updated.named_buffers(remove_duplicate=False)
116
+ )
117
+ new_named_modules = OrderedDict(
118
+ updated.named_modules(remove_duplicate=False)
119
+ )
120
+
121
+ assert isinstance(updated, nn.Module), (
122
+ "Output of composable distributed APIs must be either None or "
123
+ f"nn.Module, but got {type(updated)}"
124
+ )
125
+
126
+ def check_fqn(orig_fqns: List[str], new_fqns: List[str], check_key: str):
127
+ if orig_fqns == new_fqns:
128
+ return
129
+
130
+ orig_fqn_set, new_fqn_set = set(orig_fqns), set(new_fqns)
131
+ orig_only = orig_fqn_set - new_fqn_set
132
+ new_only = new_fqn_set - orig_fqn_set
133
+ if len(orig_only) or len(new_only):
134
+ raise RuntimeError(
135
+ f"{check_key}"
136
+ "Composable distributed API implementations cannot modify "
137
+ "FQNs.\n"
138
+ f"Only in original FQNs: {orig_only},\n"
139
+ f"Only in new FQNs: {new_only}"
140
+ )
141
+ else:
142
+ raise RuntimeError(
143
+ f"{check_key}"
144
+ "Composable distributed API implementations cannot modify "
145
+ "the order of FQNs.\n"
146
+ f"Original FQNs: {orig_only}\n"
147
+ f"New FQNs: {new_only}"
148
+ )
149
+
150
+ check_fqn(
151
+ list(orig_named_params.keys()),
152
+ list(new_named_params.keys()),
153
+ "Check parameters, ",
154
+ )
155
+ check_fqn(
156
+ list(orig_named_buffers.keys()),
157
+ list(new_named_buffers.keys()),
158
+ "Check buffer, ",
159
+ )
160
+ check_fqn(
161
+ list(orig_named_modules.keys()),
162
+ list(new_named_modules.keys()),
163
+ "Check modules, ",
164
+ )
165
+
166
+ # TODO: a stricter verification should also reject changing module
167
+ # types and monkey-patching forward() method implementations.
168
+
169
+ # TODO: verify that installed distributed paradigms are compatible with
170
+ # each other.
171
+
172
+ return updated
173
+
174
+ def get_state(module: nn.Module) -> Optional[_State]:
175
+ return module.__dict__.setdefault( # type: ignore[call-overload]
176
+ STATE_KEY,
177
+ {}, # TODO(@yhcharles): this is a temporary fix, need a better way
178
+ ).get(
179
+ func
180
+ ) # type: ignore[call-overload]
181
+
182
+ wrapper.state = get_state # type: ignore[attr-defined]
183
+
184
+ return wrapper
185
+
186
+ return inner
187
+
188
+
189
+ def _get_registry(module: nn.Module) -> Optional[Dict[str, RegistryItem]]:
190
+ r"""
191
+ Get an ``OrderedDict`` of composable APIs that have been applied to the
192
+ ``module``, indexed by the API name. If no API has been applied, then this
193
+ returns ``None``.
194
+ """
195
+ return getattr(module, REGISTRY_KEY, None)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
2
+ from .fully_shard import FSDPModule, fully_shard, register_fsdp_forward_method
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (369 Bytes). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_api.cpython-38.pyc ADDED
Binary file (4.02 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_collectives.cpython-38.pyc ADDED
Binary file (8.31 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_common.cpython-38.pyc ADDED
Binary file (5.26 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_init.cpython-38.pyc ADDED
Binary file (4.5 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param.cpython-38.pyc ADDED
Binary file (19.2 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_param_group.cpython-38.pyc ADDED
Binary file (16.9 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/_fsdp_state.cpython-38.pyc ADDED
Binary file (8.33 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-38.pyc ADDED
Binary file (14 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_api.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class MixedPrecisionPolicy:
10
+ """
11
+ This configures FSDP's mixed precision. Unlike autocast, this applies mixed
12
+ precision at the module level, not op level, which means low-precision
13
+ activations are saved for backward and high-to-low-precision casts are
14
+ incurred only at module boundaries.
15
+
16
+ FSDP works well with module-level mixed precision since it keeps the
17
+ high-precision sharded parameters in memory anyway. In other words, FSDP
18
+ does not require any extra memory to keep a high-precision copy of the
19
+ parameters for the optimizer step.
20
+
21
+ Attributes:
22
+ param_dtype (Optional[torch.dtype]): This specifies the dtype for
23
+ the unsharded parameter and hence the dtype for forward/backward
24
+ computation and the parameter all-gather. If this is ``None``, then
25
+ the unsharded parameter uses the original dtype. The optimizer step
26
+ uses the sharded parameter in the original dtype. (Default:
27
+ ``None``)
28
+ reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
29
+ gradient reduction (i.e. reduce-scatter or all-reduce). If this is
30
+ ``None`` but ``param_dtype`` is not ``None``, then the reduction
31
+ uses the compute dtype. This can be used to run gradient reduction
32
+ in full precision while using low precision for compute. If also
33
+ gradient reduction is disabled via :meth:`set_requires_gradient_sync`,
34
+ then FSDP will accumulate gradients using ``reduce_dtype``.
35
+ (Default: ``None``)
36
+ output_dtype (Optional[torch.dtype]): This specifies the dtype for
37
+ casting floating-point forward outputs. This can be used to
38
+ help implement cases where different modules have different mixed
39
+ precision policies. (Default: ``None``)
40
+ cast_forward_inputs (bool): This specifies whether FSDP should cast the
41
+ forward's floating-point input tensors to ``param_dtype`` or not.
42
+ """
43
+
44
+ param_dtype: Optional[torch.dtype] = None
45
+ reduce_dtype: Optional[torch.dtype] = None
46
+ output_dtype: Optional[torch.dtype] = None
47
+ cast_forward_inputs: bool = True
48
+
49
+ def __post_init__(self):
50
+ # Clamp `reduce_dtype` to `None` if no casting is required: since
51
+ # gradients are computed in `param_dtype`, if `reduce_dtype` matches,
52
+ # then we do not need extra casting
53
+ if self.param_dtype == self.reduce_dtype:
54
+ # Bypass the frozen dataclass checks
55
+ object.__setattr__(self, "reduce_dtype", None)
56
+
57
+
58
+ @dataclass
59
+ class OffloadPolicy:
60
+ """This base class represents the policy of no offloading."""
61
+
62
+
63
+ @dataclass
64
+ class CPUOffloadPolicy(OffloadPolicy):
65
+ """
66
+ This offload policy offloads parameters, gradients, and optimizer states to
67
+ CPU. Sharded parameters are copied host-to-device before all-gather. The
68
+ all-gathered parameters are freed according to ``reshard_after_forward``.
69
+ Sharded gradients are copied device-to-host in backward, and the optimizer
70
+ step runs on CPU with CPU optimizer states.
71
+
72
+ Attributes:
73
+ pin_memory (bool): Whether to pin sharded parameter and gradient
74
+ memory. Pinning memory allows H2D/D2H copying without blocking the
75
+ CPU and in turn, overlap with compute, but pinned memory cannot be
76
+ used by other processes. Set this to ``False`` if you have
77
+ insufficient CPU memory. (Default: ``True``)
78
+ """
79
+
80
+ pin_memory: bool = True
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_collectives.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, NamedTuple, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch._dynamo.compiled_autograd as ca
5
+ import torch.distributed as dist
6
+ from torch.distributed._tensor import DTensor
7
+ from torch.distributed.distributed_c10d import ReduceOp
8
+ from ._fsdp_common import (
9
+ _get_dim0_padded_size,
10
+ _raise_assert_with_print,
11
+ _to_dtype_if_needed,
12
+ )
13
+ from ._fsdp_param import FSDPParam
14
+
15
+
16
+ class AllGatherResult(NamedTuple):
17
+ all_gather_output: torch.Tensor
18
+ all_gather_event: Optional[torch.cuda.Event]
19
+ all_gather_work: Optional[dist.distributed_c10d.Work]
20
+ # For each parameter, the all-gather input dtype for each input
21
+ param_all_gather_input_dtypes: List[List[torch.dtype]]
22
+ # For each parameter, the all-gather input numel for each input
23
+ param_all_gather_input_numels: List[List[int]]
24
+ # 1D flattened version of `param_all_gather_input_numels` saved to avoid
25
+ # CPU overhead from recomputing
26
+ all_gather_input_split_sizes: List[int]
27
+
28
+
29
+ @torch.no_grad()
30
+ def foreach_all_gather(
31
+ fsdp_params: List[FSDPParam],
32
+ group: dist.ProcessGroup,
33
+ async_op: bool,
34
+ all_gather_copy_in_stream: torch.cuda.Stream,
35
+ all_gather_stream: torch.cuda.Stream,
36
+ device: torch.device,
37
+ ) -> Optional[AllGatherResult]:
38
+ world_size, rank = group.size(), group.rank()
39
+ with torch.cuda.stream(all_gather_copy_in_stream):
40
+ param_all_gather_inputs: List[List[torch.Tensor]] = [
41
+ fsdp_param.all_gather_inputs for fsdp_param in fsdp_params
42
+ ]
43
+ (
44
+ param_all_gather_input_dtypes,
45
+ param_all_gather_input_numels,
46
+ dtype,
47
+ ) = _get_all_gather_input_metadatas(param_all_gather_inputs)
48
+ if dtype == torch.uint8:
49
+ all_gather_inputs = [
50
+ t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
51
+ ]
52
+ else:
53
+ all_gather_inputs = [t for ts in param_all_gather_inputs for t in ts]
54
+ inp_split_sizes = [t.numel() for t in all_gather_inputs]
55
+ all_gather_input_numel = sum(inp_split_sizes)
56
+ all_gather_output = torch.empty(
57
+ (all_gather_input_numel * world_size,), dtype=dtype, device=device
58
+ )
59
+ all_gather_input = all_gather_output.narrow(
60
+ 0, all_gather_input_numel * rank, all_gather_input_numel
61
+ )
62
+ foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
63
+ torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
64
+ del param_all_gather_inputs
65
+ all_gather_stream.wait_stream(all_gather_copy_in_stream)
66
+ with torch.cuda.stream(all_gather_stream):
67
+ all_gather_work = dist.all_gather_into_tensor(
68
+ output_tensor=all_gather_output,
69
+ input_tensor=all_gather_input,
70
+ group=group,
71
+ async_op=async_op,
72
+ )
73
+ all_gather_event = all_gather_stream.record_event()
74
+ return AllGatherResult(
75
+ all_gather_output,
76
+ all_gather_event,
77
+ all_gather_work,
78
+ param_all_gather_input_dtypes,
79
+ param_all_gather_input_numels,
80
+ inp_split_sizes,
81
+ )
82
+
83
+
84
+ @torch.no_grad()
85
+ def foreach_all_gather_copy_out(
86
+ all_gather_result: AllGatherResult,
87
+ fsdp_params: List[FSDPParam],
88
+ group: dist.ProcessGroup,
89
+ ) -> None:
90
+ (
91
+ all_gather_output,
92
+ all_gather_event,
93
+ all_gather_work,
94
+ param_all_gather_input_dtypes,
95
+ param_all_gather_input_numels,
96
+ all_gather_input_split_sizes,
97
+ ) = all_gather_result
98
+ if all_gather_event is not None: # sync op
99
+ torch.cuda.current_stream().wait_event(all_gather_event)
100
+ if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
101
+ all_gather_work.wait()
102
+ world_size, device = group.size(), all_gather_output.device
103
+ for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
104
+ param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
105
+ ):
106
+ if ca.compiled_autograd_enabled:
107
+ fsdp_param.init_all_gather_outputs(
108
+ all_gather_input_numels,
109
+ all_gather_input_dtypes,
110
+ world_size,
111
+ device,
112
+ # NOTE: Under compile, make sure we always recreate all_gather_outputs
113
+ # per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
114
+ force_recreate=True,
115
+ )
116
+ else:
117
+ fsdp_param.init_all_gather_outputs(
118
+ all_gather_input_numels, all_gather_input_dtypes, world_size, device
119
+ ) # no-op after 1st call
120
+ fsdp_param.alloc_all_gather_outputs()
121
+ all_gather_output = all_gather_output.view(world_size, -1)
122
+ gen = (t for fsdp_param in fsdp_params for t in fsdp_param.all_gather_outputs)
123
+ if all_gather_output.dtype == torch.uint8:
124
+ out = [t.view(world_size, -1).view(torch.uint8) for t in gen]
125
+ else:
126
+ out = [t.view(world_size, -1) for t in gen]
127
+ torch.split_with_sizes_copy(
128
+ all_gather_output, all_gather_input_split_sizes, dim=1, out=out
129
+ )
130
+
131
+
132
+ @torch.no_grad()
133
+ def foreach_reduce(
134
+ fsdp_params: List[FSDPParam],
135
+ unsharded_grads: List[torch.Tensor],
136
+ reduce_scatter_group: dist.ProcessGroup,
137
+ reduce_scatter_stream: torch.cuda.Stream,
138
+ orig_dtype: torch.dtype,
139
+ reduce_dtype: Optional[torch.dtype],
140
+ device: torch.device,
141
+ all_reduce_group: Optional[dist.ProcessGroup], # not `None` iff HSDP
142
+ all_reduce_stream: torch.cuda.Stream,
143
+ all_reduce_grads: bool,
144
+ partial_reduce_output: Optional[torch.Tensor], # only used for HSDP
145
+ ) -> Tuple[torch.cuda.Event, Optional[torch.Tensor]]:
146
+ """
147
+ ``unsharded_grads`` owns the references to the gradients computed by
148
+ autograd, so clearing the list frees the gradients.
149
+ """
150
+ grad_dtypes = {grad.dtype for grad in unsharded_grads}
151
+ if len(grad_dtypes) != 1:
152
+ # Check this at runtime since it could be a real runtime error if e.g.
153
+ # fp8 weights do not produce the correct higher precision gradients
154
+ _raise_assert_with_print(
155
+ f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
156
+ )
157
+ grad_dtype = unsharded_grads[0].dtype
158
+ reduce_dtype = reduce_dtype or grad_dtype
159
+ predivide_factor, postdivide_factor = _get_gradient_divide_factors(
160
+ reduce_scatter_group, all_reduce_group, reduce_dtype
161
+ )
162
+ world_size = reduce_scatter_group.size()
163
+ padded_unsharded_sizes = tuple(
164
+ _get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
165
+ )
166
+ reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
167
+ reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
168
+ current_stream = torch.cuda.current_stream()
169
+ reduce_scatter_stream.wait_stream(current_stream)
170
+ with torch.cuda.stream(reduce_scatter_stream):
171
+ reduce_scatter_input = torch.empty(
172
+ (reduce_scatter_input_numel,), dtype=reduce_dtype, device=device
173
+ )
174
+ foreach_reduce_scatter_copy_in(
175
+ unsharded_grads, reduce_scatter_input, world_size
176
+ )
177
+ # Only after the copy-in finishes can we free the gradients, which were
178
+ # computed in the default stream
179
+ current_stream.wait_stream(reduce_scatter_stream)
180
+ unsharded_grads.clear()
181
+ reduce_output = reduce_scatter_input.new_empty((reduce_scatter_output_numel,))
182
+ _div_if_needed(reduce_scatter_input, predivide_factor)
183
+ dist.reduce_scatter_tensor(
184
+ output=reduce_output,
185
+ input=reduce_scatter_input,
186
+ group=reduce_scatter_group,
187
+ op=ReduceOp.AVG if predivide_factor is None else ReduceOp.SUM,
188
+ )
189
+ post_reduce_stream = reduce_scatter_stream
190
+ if all_reduce_group is not None: # HSDP
191
+ # Accumulations must run in the reduce-scatter stream
192
+ if not all_reduce_grads:
193
+ if partial_reduce_output is not None:
194
+ partial_reduce_output += reduce_output
195
+ else:
196
+ partial_reduce_output = reduce_output
197
+ return post_reduce_stream.record_event(), partial_reduce_output
198
+ if partial_reduce_output is not None:
199
+ reduce_output += partial_reduce_output
200
+ post_reduce_stream = all_reduce_stream
201
+ all_reduce_stream.wait_stream(reduce_scatter_stream)
202
+ with torch.cuda.stream(all_reduce_stream):
203
+ dist.all_reduce(
204
+ reduce_output,
205
+ group=all_reduce_group,
206
+ op=ReduceOp.AVG if predivide_factor is None else ReduceOp.SUM,
207
+ )
208
+ with torch.cuda.stream(post_reduce_stream):
209
+ _div_if_needed(reduce_output, postdivide_factor)
210
+ reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
211
+ # View out and accumulate sharded gradients
212
+ flat_grad_offset = 0 # [0, reduce_scatter_output_numel - 1]
213
+ for padded_unsharded_size, fsdp_param in zip(
214
+ padded_unsharded_sizes, fsdp_params
215
+ ):
216
+ new_sharded_grad = torch.as_strided(
217
+ reduce_output,
218
+ size=fsdp_param.sharded_size,
219
+ stride=fsdp_param.contiguous_sharded_stride,
220
+ storage_offset=flat_grad_offset,
221
+ )
222
+ to_accumulate_grad = fsdp_param.sharded_param.grad is not None
223
+ if fsdp_param.offload_to_cpu:
224
+ # Only overlap the D2H copy (copying to pinned memory) if not
225
+ # accumulating gradients since the CPU add kernel depends on
226
+ # the copy result and we cannot run the add as a callback
227
+ non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
228
+ # Since the GPU sharded gradient is allocated in the RS stream,
229
+ # we can free it here by not keeping a ref without waiting for
230
+ # the D2H copy since future RS-stream ops run after the copy
231
+ new_sharded_grad = new_sharded_grad.to(
232
+ torch.device("cpu"), non_blocking=non_blocking
233
+ )
234
+ if non_blocking:
235
+ # Record an event on which to block the CPU thread to
236
+ # ensure that the D2H copy finishes before the optimizer
237
+ fsdp_param.grad_offload_event = reduce_scatter_stream.record_event()
238
+ if to_accumulate_grad:
239
+ assert isinstance(fsdp_param.sharded_param.grad, DTensor)
240
+ fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
241
+ else:
242
+ new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
243
+ new_sharded_grad
244
+ )
245
+ fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
246
+ padded_sharded_numel = padded_unsharded_size.numel() // world_size
247
+ flat_grad_offset += padded_sharded_numel
248
+ post_reduce_event = post_reduce_stream.record_event()
249
+ # The RS output is allocated in the RS stream and used in the default
250
+ # stream (for optimizer). To ensure its memory is not reused for later
251
+ # RSs, we do not need extra synchronization since the sharded parameters
252
+ # hold refs through the end of backward.
253
+ return post_reduce_event, None
254
+
255
+
256
+ def foreach_reduce_scatter_copy_in(
257
+ unsharded_grads: List[torch.Tensor],
258
+ reduce_scatter_input: torch.Tensor,
259
+ world_size: int,
260
+ ) -> None:
261
+ reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
262
+ torch._chunk_cat(
263
+ unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
264
+ )
265
+
266
+
267
+ def _get_all_gather_input_metadatas(
268
+ param_all_gather_inputs: List[List[torch.Tensor]],
269
+ ) -> Tuple[List[List[torch.dtype]], List[List[int]], torch.dtype]:
270
+ param_all_gather_input_dtypes: List[List[torch.dtype]] = []
271
+ param_all_gather_input_numels: List[List[int]] = []
272
+ all_gather_dtype = param_all_gather_inputs[0][0].dtype
273
+ for all_gather_inputs in param_all_gather_inputs:
274
+ input_dtypes: List[torch.dtype] = []
275
+ input_numels: List[int] = []
276
+ for all_gather_input in all_gather_inputs:
277
+ if all_gather_input.dtype != all_gather_dtype:
278
+ all_gather_dtype = torch.uint8
279
+ input_dtypes.append(all_gather_input.dtype)
280
+ input_numels.append(all_gather_input.numel())
281
+ param_all_gather_input_dtypes.append(input_dtypes)
282
+ param_all_gather_input_numels.append(input_numels)
283
+ return (
284
+ param_all_gather_input_dtypes,
285
+ param_all_gather_input_numels,
286
+ all_gather_dtype,
287
+ )
288
+
289
+
290
+ def _get_gradient_divide_factors(
291
+ reduce_scatter_group: dist.ProcessGroup,
292
+ all_reduce_group: Optional[dist.ProcessGroup],
293
+ reduce_dtype: torch.dtype,
294
+ ) -> Union[Tuple[None, None], Tuple[float, float]]:
295
+ # For fp32/bf16, we do not need to worry about overflow/underflow, so we
296
+ # use NCCL's built-in division to avoid separate div kernels
297
+ if reduce_dtype in (torch.float32, torch.bfloat16):
298
+ return None, None
299
+ data_parallel_size = reduce_scatter_group.size()
300
+ if all_reduce_group is not None:
301
+ data_parallel_size *= all_reduce_group.size()
302
+ # Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
303
+ # overflow/underflow. For N data parallel workers, each worker computes
304
+ # g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
305
+ # overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
306
+ factor: int = 1
307
+ while data_parallel_size % factor == 0 and data_parallel_size / factor > factor:
308
+ factor *= 2
309
+ factor = float(factor)
310
+ return (factor, data_parallel_size / factor)
311
+
312
+
313
+ def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
314
+ if div_factor is not None and div_factor > 1:
315
+ tensor.div_(div_factor)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_common.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ import traceback
4
+
5
+ from dataclasses import dataclass
6
+ from enum import auto, Enum
7
+ from typing import Any, cast, List, Optional
8
+
9
+ import torch
10
+ import torch._dynamo.compiled_autograd as ca
11
+ import torch.distributed as dist
12
+ import torch.nn as nn
13
+ from torch.distributed._composable.contract import _get_registry
14
+ from torch.distributed._tensor import DeviceMesh, DTensor
15
+ from torch.distributed._tensor.placement_types import DTensorSpec
16
+
17
+
18
+ @dataclass
19
+ class DataParallelMeshInfo:
20
+ mesh: DeviceMesh
21
+ shard_mesh_dim: Optional[int] = None
22
+ replicate_mesh_dim: Optional[int] = None
23
+
24
+ def __post_init__(self):
25
+ if self.shard_mesh_dim is None and self.replicate_mesh_dim is None:
26
+ raise AssertionError(
27
+ "At least one of shard_mesh_dim and replicate_mesh_dim must not be None"
28
+ )
29
+
30
+
31
+ @dataclass
32
+ class FSDPMeshInfo(DataParallelMeshInfo):
33
+ def __post_init__(self):
34
+ super().__post_init__()
35
+ if self.shard_mesh_dim is None:
36
+ raise AssertionError("Expects non-None shard_mesh_dim")
37
+ self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim)
38
+ self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim)
39
+ self.shard_mesh_rank: int = self.shard_process_group.rank()
40
+
41
+
42
+ @dataclass
43
+ class DDPMeshInfo(DataParallelMeshInfo):
44
+ def __post_init__(self):
45
+ super().__post_init__()
46
+ if self.replicate_mesh_dim is None:
47
+ raise AssertionError("Expects non-None replicate_mesh_dim")
48
+ self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim)
49
+ self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim)
50
+ self.replicate_mesh_rank: int = self.replicate_process_group.rank()
51
+
52
+
53
+ @dataclass
54
+ class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo):
55
+ def __post_init__(self):
56
+ # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo`
57
+ super().__post_init__()
58
+
59
+
60
+ class TrainingState(Enum):
61
+ """Describes the training state of one FSDP state / parameter group."""
62
+
63
+ # Transition to forward starting pre-forward until post-forward
64
+ FORWARD = auto()
65
+ # Transition to pre-backward when unsharding in backward
66
+ PRE_BACKWARD = auto()
67
+ # Transition to post-backward when resharding and reducing gradients
68
+ POST_BACKWARD = auto()
69
+ # Idle before/after forward or before pre-backward/after post-backward
70
+ IDLE = auto()
71
+
72
+
73
+ def _raise_assert_with_print(*args: Any, **kwargs: Any):
74
+ print(f"[Rank {dist.get_rank()}] ", end="")
75
+ print(*args, **kwargs)
76
+ traceback.print_stack()
77
+ raise AssertionError(*args, **kwargs)
78
+
79
+
80
+ def _is_composable_with_fsdp(module: nn.Module) -> bool:
81
+ registry = _get_registry(module)
82
+ if registry is None:
83
+ return True
84
+ # Registry keys by function name
85
+ return "replicate" not in registry
86
+
87
+
88
+ def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size:
89
+ padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor
90
+ return cast(torch.Size, torch.Size([padded_dim0]) + tensor_size[1:])
91
+
92
+
93
+ def _chunk_with_empty(
94
+ tensor: torch.Tensor, num_chunks: int, dim: int
95
+ ) -> List[torch.Tensor]:
96
+ chunks = list(torch.chunk(tensor, num_chunks, dim=dim))
97
+ while len(chunks) < num_chunks:
98
+ chunks.append(chunks[0].new_empty(0))
99
+ return chunks
100
+
101
+
102
+ def _get_dim0_chunked_size(
103
+ chunk: torch.Tensor, unchunked_size: torch.Size
104
+ ) -> torch.Size:
105
+ if chunk.numel() > 0:
106
+ return chunk.size()
107
+ # For 0 numel, we need to preserve trailing dims for DTensor APIs
108
+ return cast(torch.Size, torch.Size([0]) + unchunked_size[1:])
109
+
110
+
111
+ def _from_local_no_grad(
112
+ local_tensor: torch.Tensor,
113
+ sharding_spec: DTensorSpec,
114
+ ) -> DTensor:
115
+ """
116
+ This method is similar to ``DTensor.from_local()`` except that in eager mode
117
+ it avoids some CPU overhead by avoiding default args and not being differentiable.
118
+ """
119
+
120
+ if not ca.compiled_autograd_enabled:
121
+ return DTensor(
122
+ # Use the local tensor directly instead of constructing a new tensor
123
+ # variable, e.g. with `view_as()`, since this is not differentiable
124
+ local_tensor,
125
+ sharding_spec,
126
+ requires_grad=local_tensor.requires_grad,
127
+ )
128
+ else:
129
+ return DTensor.from_local(
130
+ local_tensor,
131
+ sharding_spec.mesh,
132
+ sharding_spec.placements,
133
+ shape=sharding_spec.shape,
134
+ stride=sharding_spec.stride,
135
+ )
136
+
137
+
138
+ def _to_dtype_if_needed(
139
+ tensor: torch.Tensor, dtype: Optional[torch.dtype]
140
+ ) -> torch.Tensor:
141
+ if dtype is not None and tensor.dtype != dtype:
142
+ return tensor.to(dtype)
143
+ return tensor
144
+
145
+
146
+ def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor:
147
+ if (
148
+ not isinstance(x, torch.Tensor)
149
+ or not torch.is_floating_point(x)
150
+ or x.dtype == dtype
151
+ ):
152
+ return x
153
+ return x.to(dtype)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_init.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from typing import List, Optional, Set, Tuple, Union
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.nn as nn
7
+
8
+ from torch.distributed._tensor import DeviceMesh, DTensor, init_device_mesh
9
+ from torch.distributed.device_mesh import _get_device_handle
10
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
11
+ from ._fsdp_common import _is_composable_with_fsdp, FSDPMeshInfo, HSDPMeshInfo
12
+ from ._fsdp_state import _get_module_fsdp_state
13
+
14
+
15
+ def _get_post_forward_mesh_info(
16
+ reshard_after_forward: Union[bool, int], mesh_info: FSDPMeshInfo
17
+ ) -> Optional[FSDPMeshInfo]:
18
+ shard_mesh_size = mesh_info.shard_mesh_size
19
+ if not isinstance(reshard_after_forward, (bool, int)):
20
+ raise ValueError(
21
+ "reshard_after_forward should be a bool or an int representing the "
22
+ f"group size to reshard to, not {reshard_after_forward}"
23
+ )
24
+ # NOTE: `isinstance(False, int)` returns `True`.
25
+ if not isinstance(reshard_after_forward, bool) and isinstance(
26
+ reshard_after_forward, int
27
+ ):
28
+ if (
29
+ reshard_after_forward < 1
30
+ or reshard_after_forward > shard_mesh_size
31
+ or shard_mesh_size % reshard_after_forward != 0
32
+ ):
33
+ raise ValueError(
34
+ "If passing reshard_after_forward as an int, it should be a "
35
+ f"factor of {shard_mesh_size}, not {reshard_after_forward}"
36
+ )
37
+ elif reshard_after_forward == 1:
38
+ reshard_after_forward = False
39
+ elif reshard_after_forward == shard_mesh_size:
40
+ reshard_after_forward = True
41
+ post_forward_mesh_info = None
42
+ if reshard_after_forward is True:
43
+ post_forward_mesh_info = mesh_info
44
+ elif reshard_after_forward is not False: # int case
45
+ # For HSDP, we can flatten the two replicate dims into the 0th dim
46
+ post_forward_mesh_tensor = mesh_info.mesh.mesh.view(-1, reshard_after_forward)
47
+ post_forward_mesh = DeviceMesh(
48
+ mesh_info.mesh.device_type, post_forward_mesh_tensor
49
+ )
50
+ post_forward_mesh_info = HSDPMeshInfo(
51
+ post_forward_mesh, shard_mesh_dim=1, replicate_mesh_dim=0
52
+ )
53
+ return post_forward_mesh_info
54
+
55
+
56
+ def _init_default_fully_shard_mesh() -> DeviceMesh:
57
+ """Default to global CUDA mesh if possible else global CPU mesh."""
58
+ if not dist.distributed_c10d.is_initialized():
59
+ dist.distributed_c10d.init_process_group()
60
+ default_pg = dist.distributed_c10d._get_default_group()
61
+ device_type = "cuda" if torch.cuda.is_available() else "cpu"
62
+ mesh = init_device_mesh(device_type, mesh_shape=(default_pg.size(),))
63
+ return mesh
64
+
65
+
66
+ def _get_device_from_mesh(mesh: DeviceMesh) -> torch.device:
67
+ if mesh.device_type == "cpu":
68
+ return torch.device("cpu")
69
+ device_handle = _get_device_handle(mesh.device_type)
70
+ return torch.device(mesh.device_type, device_handle.current_device())
71
+
72
+
73
+ def _get_managed_modules(root_module: nn.Module) -> List[nn.Module]:
74
+ modules: List[nn.Module] = []
75
+ # Track visisted modules to avoid visiting shared modules multiple times
76
+ visited_modules: Set[nn.Module] = set()
77
+
78
+ def dfs(module: nn.Module) -> None:
79
+ """
80
+ Runs a DFS to collect managed modules, not recursing into modules with
81
+ a non-composable API or ``fully_shard`` already applied.
82
+ """
83
+ if not _is_composable_with_fsdp(module):
84
+ return
85
+ elif module is not root_module and _get_module_fsdp_state(module) is not None:
86
+ return # nested `fully_shard` module
87
+ visited_modules.add(module)
88
+ for submodule in module.children():
89
+ if submodule not in visited_modules:
90
+ dfs(submodule)
91
+ modules.append(module)
92
+
93
+ dfs(root_module)
94
+ return modules
95
+
96
+
97
+ def _get_managed_states(
98
+ modules: List[nn.Module],
99
+ ) -> Tuple[List[nn.Parameter], List[torch.Tensor]]:
100
+ params: List[nn.Parameter] = []
101
+ buffers: List[torch.Tensor] = []
102
+ # Track visited parameters/buffers to avoid visiting shared parameters and
103
+ # buffers multiple times
104
+ visited_params: Set[nn.Parameter] = set()
105
+ visited_buffers: Set[torch.Tensor] = set()
106
+ for module in modules:
107
+ for param in module.parameters(recurse=False):
108
+ if param not in visited_params:
109
+ params.append(param)
110
+ visited_params.add(param)
111
+ for buffer in module.buffers(recurse=False):
112
+ if buffer not in visited_buffers:
113
+ buffers.append(buffer)
114
+ visited_buffers.add(buffer)
115
+ return params, buffers
116
+
117
+
118
+ def _move_states_to_device(
119
+ params: List[nn.Parameter],
120
+ buffers: List[torch.Tensor],
121
+ device: torch.device,
122
+ ) -> None:
123
+ """
124
+ We have FSDP move states to device for simpler and faster initialization
125
+ since FSDP almost always uses CUDA for training. We move parameters/buffers
126
+ rather than modules since modules to support ignoring parameters/buffers in
127
+ the future.
128
+ """
129
+ # Follow the logic in `nn.Module._apply`
130
+ for tensor in itertools.chain(params, buffers):
131
+ if tensor.device == device or tensor.device.type == "meta":
132
+ # Keep meta-device tensors on meta device for deferred init
133
+ continue
134
+ if isinstance(tensor, DTensor):
135
+ if (dtensor_mesh_type := tensor.device_mesh.device_type) != device.type:
136
+ raise ValueError(
137
+ "Requires DTensor to have mesh of the same type as the FSDP mesh "
138
+ f"but got {dtensor_mesh_type} for DTensor and {device.type} for FSDP"
139
+ )
140
+ raise AssertionError(
141
+ f"Expects DTensor to be moved to {dtensor_mesh_type} but got {tensor.device}"
142
+ )
143
+ if is_traceable_wrapper_subclass(tensor):
144
+ with torch.no_grad(): # avoid autograd increasing C++ refcount by 1
145
+ tensor_on_device = nn.Parameter(tensor.to(device))
146
+ torch.utils.swap_tensors(tensor, tensor_on_device)
147
+ else:
148
+ tensor.data = tensor.to(device)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_param.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ from dataclasses import dataclass, field
4
+ from enum import auto, Enum
5
+ from typing import Any, cast, List, Optional, Sequence, Tuple
6
+
7
+ import torch
8
+ import torch._dynamo.compiled_autograd as ca
9
+ import torch.nn as nn
10
+
11
+ from torch._prims_common import make_contiguous_strides_for
12
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
13
+ from torch.distributed._tensor import DTensor, Replicate, Shard
14
+ from torch.distributed._tensor.device_mesh import _mesh_resources
15
+ from torch.distributed._tensor.placement_types import DTensorSpec, Placement, TensorMeta
16
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
17
+ from ._fsdp_common import (
18
+ _chunk_with_empty,
19
+ _from_local_no_grad,
20
+ _get_dim0_chunked_size,
21
+ _raise_assert_with_print,
22
+ _to_dtype_if_needed,
23
+ FSDPMeshInfo,
24
+ HSDPMeshInfo,
25
+ )
26
+
27
+ """
28
+ [Note: FSDP tensors]
29
+ FSDP considers the following tensors:
30
+ - Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
31
+ on the module when applying FSDP
32
+ - Sharded parameter: sharding the original parameter on dim-0 as a DTensor
33
+ over the main mesh
34
+ - All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
35
+ derived from the sharded parameter
36
+ - All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
37
+ all-gathering the all-gather inputs
38
+ - Unsharded parameter: parameter used for forward/backward computation, derived
39
+ from the all-gather output; autograd leaf
40
+
41
+ We define these tensors to describe the general framework that can accomodate
42
+ extensions, where:
43
+ - all-gather-inputs = pre-all-gather-transform(sharded-parameter)
44
+ - unsharded-parameter = post-all-gather-transform(all-gather-outputs)
45
+
46
+ For the default ``torch.Tensor`` case, there is only one all-gather input, and
47
+ it shares the same underlying tensor data as the sharded parameter, meaning
48
+ that they can be thought of as the same tensors. The same applies for the
49
+ all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
50
+ these equivalences may no longer hold due to the pre/post-all-gather
51
+ transforms, and some may have multiple all-gather inputs/outputs (e.g.
52
+ quantized data and scales).
53
+
54
+ [Note: FSDP and autograd]
55
+ FSDP dynamically frees and allocates the unsharded parameter. Since autograd
56
+ can pack a reference to it or a view to save for backward, we use storage
57
+ resizing to implement the freeing/allocation since that preserves the aliasing.
58
+ This implies that we construct the unsharded parameter object once and write to
59
+ it in-place thereafter. For the default ``torch.Tensor` original parameter
60
+ case, the all-gather output and unsharded parameter share the same
61
+ data, so we use storage resizing on the all-gather output.
62
+ """
63
+
64
+
65
+ class ShardedState(Enum):
66
+ """
67
+ - ``SHARDED``: The sharded parameter is registered to the module. It is the
68
+ only contributor to parameter memory.
69
+ - ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
70
+ smaller world size. Since this data should not be used for computation,
71
+ we do not register it to the module. Users should reshard the module
72
+ before any in-place modifications. Both it and the sharded parameter
73
+ contribute to parameter memory.
74
+ - ``UNSHARDED``: The unsharded parameter is registered to the module. Both
75
+ it and the sharded parameter contribute to parameter memory.
76
+ """
77
+
78
+ SHARDED = auto()
79
+ SHARDED_POST_FORWARD = auto()
80
+ UNSHARDED = auto()
81
+
82
+
83
+ @dataclass
84
+ class ParamModuleInfo:
85
+ """
86
+ For a parameter, this stores the module and the parameter name to be able
87
+ to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
88
+ the parameter via ``getattr(module, param_name)``. We additionally save
89
+ shared modules and shared parameter names to update them accordingly.
90
+ """
91
+
92
+ # Parameter names are unprefixed, e.g. "weight", not "lin.weight"
93
+ module: nn.Module
94
+ param_name: str
95
+ shared_modules: List[nn.Module] = field(default_factory=list)
96
+ shared_param_names: List[str] = field(default_factory=list)
97
+
98
+
99
+ @dataclass
100
+ class ExtensionsData:
101
+ # User-defined metadata passed from pre to post-all-gather
102
+ all_gather_metadata: Optional[Any] = None
103
+ # Save the all-gather input sizes to unflatten the all-gather outputs to ND
104
+ all_gather_input_sizes: Sequence[torch.Size] = () # ND
105
+
106
+ def clear(self):
107
+ self.all_gather_metadata = None
108
+ self.all_gather_input_sizes = ()
109
+
110
+
111
+ class FSDPParam:
112
+ """
113
+ This class manages a parameter with FSDP or FSDP variants applied,
114
+ implementing dim-0 per-parameter sharding.
115
+ """
116
+
117
+ orig_dtype: torch.dtype
118
+ param_dtype: Optional[torch.dtype]
119
+ reduce_dtype: Optional[torch.dtype]
120
+ _orig_size: torch.Size # ND
121
+ sharded_size: torch.Size # ND
122
+ contiguous_sharded_stride: Tuple[int, ...]
123
+ padded_sharded_param_size: torch.Size # ND
124
+ sharded_post_forward_size: torch.Size # ND
125
+ contiguous_sharded_post_forward_stride: Tuple[int, ...]
126
+ _sharded_param_data: torch.Tensor # 1D
127
+ sharded_param: nn.Parameter # ND
128
+ _sharded_post_forward_param_data: Optional[torch.Tensor] # 1D
129
+ _sharded_post_forward_param: Optional[nn.Parameter] # ND
130
+ _unsharded_param: nn.Parameter # ND
131
+ unsharded_accumulated_grad: Optional[torch.Tensor] # ND
132
+ _sharding_spec: DTensorSpec
133
+ # DTensor attributes (only defined for DTensor `param`):
134
+ _tp_spec: DTensorSpec
135
+ all_gather_outputs: List[torch.Tensor] # 1D
136
+ # All-gather extension attributes
137
+ _extensions_data: ExtensionsData
138
+ _unsharded_inner_tensors: List[torch.Tensor]
139
+
140
+ def __init__(
141
+ self,
142
+ param: nn.Parameter,
143
+ module_info: ParamModuleInfo,
144
+ mesh_info: FSDPMeshInfo,
145
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
146
+ device: torch.device,
147
+ mp_policy: MixedPrecisionPolicy,
148
+ offload_policy: OffloadPolicy,
149
+ ):
150
+ self._module_info: ParamModuleInfo = module_info
151
+ self.mesh_info = mesh_info
152
+ self.post_forward_mesh_info = post_forward_mesh_info
153
+ self.device = device
154
+ self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
155
+ self.pin_memory = (
156
+ self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
157
+ )
158
+ self.grad_offload_event: Optional[torch.cuda.Event] = None
159
+ self._init_sharded_param(param, device)
160
+ if self.post_forward_mesh_info:
161
+ self._init_sharded_post_forward_param_metadata(param)
162
+ self._init_extensions()
163
+ self.all_gather_outputs: List[torch.Tensor] = []
164
+ self.unsharded_accumulated_grad = None
165
+ self._param_fqn: Optional[str] = None # prefixed from root module
166
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
167
+ # https://github.com/pytorch/pytorch/issues/113045
168
+ self._post_load_hook_handle = (
169
+ module_info.module.register_load_state_dict_post_hook(
170
+ lambda *args, **kwargs: self.reset_sharded_param()
171
+ )
172
+ )
173
+
174
+ @torch.no_grad()
175
+ def _init_sharded_param(self, param: nn.Parameter, device: torch.device):
176
+ if param.device != device and param.device.type != "meta":
177
+ raise AssertionError(
178
+ f"Expects the parameter to already be moved to device {device} but got {param.device}"
179
+ )
180
+ # TODO: Replace the sharded DTensor parameter construction logic with
181
+ # `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
182
+ # TODO: Simplify the following sharded parameter padding logic after
183
+ # https://github.com/pytorch/pytorch/issues/113045
184
+ self.is_dtensor = isinstance(param, DTensor)
185
+ if self.is_dtensor:
186
+ self._tp_spec = cast(DTensor, param)._spec
187
+ if (
188
+ self.mesh_info.shard_mesh_dim != 0
189
+ or self.mesh_info.replicate_mesh_dim is not None
190
+ ):
191
+ raise NotImplementedError("Using TP with HSDP is not supported")
192
+ dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
193
+ dp_global_mesh = _mesh_resources.get_parent_mesh(dp_mesh)
194
+ tp_global_mesh = _mesh_resources.get_parent_mesh(tp_mesh)
195
+ if dp_global_mesh != tp_global_mesh or (
196
+ dp_global_mesh is None or tp_global_mesh is None
197
+ ):
198
+ raise AssertionError(
199
+ "FSDP requires the DP and TP mesh to have the same parent mesh but got: \n"
200
+ f"DP's global mesh: {dp_global_mesh}\nTP's global mesh: {tp_global_mesh}"
201
+ )
202
+
203
+ name_dims_error = "FSDP requires named DeviceMesh dims for ND parallelism"
204
+ assert dp_mesh.mesh_dim_names is not None, name_dims_error
205
+ assert tp_mesh.mesh_dim_names is not None, name_dims_error
206
+
207
+ submesh_names = dp_mesh.mesh_dim_names + tp_mesh.mesh_dim_names
208
+ self._spmd_mesh = dp_global_mesh[submesh_names]
209
+ if len(self._tp_spec.placements) != 1:
210
+ raise NotImplementedError(
211
+ f"FSDP only supports 1D TP, not {self._tp_spec.placements}"
212
+ )
213
+
214
+ # TODO: Hard code FSDP + TP; need to support HSDP + TP
215
+ self._spmd_placements: Tuple[Placement, ...] = (
216
+ Shard(0),
217
+ self._tp_spec.placements[0],
218
+ )
219
+
220
+ self._sharding_spec = DTensorSpec(
221
+ self._spmd_mesh,
222
+ self._spmd_placements,
223
+ tensor_meta=self._tp_spec.tensor_meta,
224
+ )
225
+ param_data = cast(DTensor, param)._local_tensor
226
+ else:
227
+ self._spmd_mesh = self.mesh_info.mesh
228
+ if isinstance(self.mesh_info, HSDPMeshInfo):
229
+ self._spmd_placements = (Replicate(), Shard(0))
230
+ else:
231
+ self._spmd_placements = (Shard(0),)
232
+ self._sharding_spec = DTensorSpec(
233
+ self._spmd_mesh,
234
+ self._spmd_placements,
235
+ tensor_meta=TensorMeta(
236
+ param.size(),
237
+ param.stride(),
238
+ param.dtype,
239
+ ),
240
+ )
241
+ param_data = param
242
+ self._orig_size = param_data.size()
243
+ self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
244
+ shard_rank = self.mesh_info.shard_mesh_rank
245
+ shard_world_size = self.mesh_info.shard_mesh_size
246
+ chunks = _chunk_with_empty(param_data, shard_world_size, dim=0)
247
+ sharded_param = chunks[shard_rank]
248
+ self.sharded_size = _get_dim0_chunked_size(sharded_param, param_data.size())
249
+ self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
250
+ padded_sharded_size = chunks[0].size() # 0th always padded
251
+ padded_sharded_param = param_data.new_zeros(padded_sharded_size)
252
+ self.padded_sharded_param_size = padded_sharded_param.size()
253
+ if sharded_param.numel() > 0:
254
+ padded_sharded_param[: sharded_param.size(0)].copy_(sharded_param)
255
+ if self.offload_to_cpu and not padded_sharded_param.is_meta:
256
+ padded_sharded_param = padded_sharded_param.cpu()
257
+ if self.pin_memory:
258
+ padded_sharded_param = padded_sharded_param.pin_memory()
259
+ self._sharded_param_data = padded_sharded_param.view(-1)
260
+ self.sharded_param = nn.Parameter(
261
+ self.to_sharded_dtensor(padded_sharded_param[: sharded_param.size(0)])
262
+ )
263
+ self.sharded_param.requires_grad_(param.requires_grad)
264
+ # Let `param_data` be freed normally when its ref count reaches 0 when
265
+ # the `fully_shard` call returns to allow provided parameters to alias
266
+ self._setattr_on_modules(self.sharded_param)
267
+ self.sharded_state = ShardedState.SHARDED
268
+
269
+ def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
270
+ mesh_info = self.post_forward_mesh_info
271
+ assert mesh_info is not None # mypy
272
+ param_data = param._local_tensor if isinstance(param, DTensor) else param
273
+ chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
274
+ self.sharded_post_forward_size = _get_dim0_chunked_size(
275
+ chunks[mesh_info.shard_mesh_rank], param_data.size()
276
+ )
277
+ self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
278
+ self.sharded_post_forward_size
279
+ )
280
+
281
+ def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
282
+ param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
283
+ self.orig_dtype = self.sharded_param.dtype
284
+ # Clamp `param_dtype` to `None` if no casting is required
285
+ if param_dtype == self.orig_dtype:
286
+ param_dtype = None
287
+ self.param_dtype = param_dtype
288
+ self.reduce_dtype = reduce_dtype
289
+ # None indicates that the mixed precision is not enabled
290
+
291
+ def _init_extensions(self) -> None:
292
+ inner_tensor = self._sharded_local_tensor
293
+ has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
294
+ has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
295
+ if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
296
+ raise AssertionError(
297
+ "Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
298
+ f"if using all-gather extensions: {inner_tensor}"
299
+ )
300
+ if has_fsdp_pre_all_gather:
301
+ if self.padded_sharded_param_size != self._sharded_local_tensor.size():
302
+ raise NotImplementedError(
303
+ "FSDP all-gather extensions require even sharding on dim-0.\n"
304
+ f"{self._orig_size} is not divisible by FSDP world size {self.mesh_info.mesh.size()}."
305
+ )
306
+ self._extensions_data = ExtensionsData()
307
+ self._unsharded_inner_tensors: List[torch.Tensor] = []
308
+
309
+ def init_all_gather_outputs(
310
+ self,
311
+ all_gather_input_numels: List[int],
312
+ all_gather_input_dtypes: List[torch.dtype],
313
+ world_size: int,
314
+ device: torch.device,
315
+ force_recreate: bool = False,
316
+ ):
317
+ if not force_recreate and len(self.all_gather_outputs) > 0:
318
+ return # already initialized
319
+ self.all_gather_outputs = [
320
+ torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
321
+ for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
322
+ ]
323
+
324
+ def init_unsharded_param(self):
325
+ """
326
+ [Note: Invariants for torch.compile Traceable FSDP2]
327
+ 1. Under compile, we always re-populate the content of `self._unsharded_param`
328
+ per AllGather using the slow path.
329
+ 2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
330
+ This is to ensure the buffer creation is internal to the graph and
331
+ avoid `self.all_gather_outputs` being captured as a graph input.
332
+ 3. Under compile, at the end of `free_unsharded_param()`, we always clean up
333
+ `self.all_gather_outputs` and `self._unsharded_inner_tensors`,
334
+ to avoid them being captured as graph output.
335
+
336
+ With these invariants, only these tensors will be inputs to the graph:
337
+ - Sharded parameters
338
+ - Placeholders for the `self._unsharded_param` nn.Parameter
339
+ """
340
+ if not ca.compiled_autograd_enabled and hasattr(
341
+ self, "_unsharded_param"
342
+ ): # after the 1st all-gather
343
+ inner_tensor = self._sharded_local_tensor
344
+ if not hasattr(inner_tensor, "fsdp_post_all_gather"):
345
+ return # already initialized
346
+ for tensor in self._unsharded_inner_tensors:
347
+ alloc_storage(tensor)
348
+ all_gather_outputs = self._unflatten_all_gather_outputs()
349
+ inner_tensor.fsdp_post_all_gather(
350
+ all_gather_outputs,
351
+ self._extensions_data.all_gather_metadata,
352
+ self.param_dtype or self.orig_dtype,
353
+ out=self._unsharded_param,
354
+ )
355
+ self._extensions_data.clear()
356
+ return
357
+ inner_tensor = self._sharded_local_tensor
358
+ if not ca.compiled_autograd_enabled and hasattr(
359
+ inner_tensor, "fsdp_post_all_gather"
360
+ ):
361
+ all_gather_outputs = self._unflatten_all_gather_outputs()
362
+ (
363
+ unsharded_tensor,
364
+ self._unsharded_inner_tensors,
365
+ ) = inner_tensor.fsdp_post_all_gather(
366
+ all_gather_outputs,
367
+ self._extensions_data.all_gather_metadata,
368
+ self.param_dtype or self.orig_dtype,
369
+ )
370
+ self._extensions_data.clear()
371
+ else:
372
+ # For the default path (no post-all-gather), the all-gather output
373
+ # gives the unsharded parameter data directly
374
+ assert len(self.all_gather_outputs) == 1, f"{len(self.all_gather_outputs)}"
375
+ unsharded_tensor = self.all_gather_outputs[0]
376
+ unsharded_param = torch.as_strided(
377
+ unsharded_tensor,
378
+ self._orig_size,
379
+ self._contiguous_orig_stride,
380
+ storage_offset=0,
381
+ )
382
+ if self.is_dtensor:
383
+ unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
384
+ if hasattr(self, "_unsharded_param"):
385
+ assert ca.compiled_autograd_enabled
386
+ with torch.no_grad():
387
+ alloc_storage(self._unsharded_param)
388
+ self._unsharded_param.copy_(unsharded_param)
389
+ else:
390
+ self._unsharded_param = nn.Parameter(
391
+ unsharded_param, requires_grad=self.sharded_param.requires_grad
392
+ )
393
+
394
+ def _unflatten_all_gather_outputs(self) -> Tuple[torch.Tensor, ...]:
395
+ return tuple(
396
+ t.view(-1, *s[1:])
397
+ for t, s in zip(
398
+ self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
399
+ )
400
+ )
401
+
402
+ def to_sharded(self) -> None:
403
+ self._setattr_on_modules(self.sharded_param)
404
+ self.free_unsharded_param()
405
+ self.sharded_state = ShardedState.SHARDED
406
+
407
+ def to_sharded_post_forward(self) -> None:
408
+ if self.is_dtensor:
409
+ raise NotImplementedError(
410
+ "Resharding to smaller mesh with TP is not supported yet"
411
+ )
412
+ self._assert_in_states(ShardedState.UNSHARDED)
413
+ assert self.post_forward_mesh_info is not None # mypy
414
+ assert len(self.all_gather_outputs) == 1
415
+ shard_world_size = self.post_forward_mesh_info.shard_mesh_size
416
+ if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
417
+ _raise_assert_with_print(
418
+ f"All-gather output size ({numel}) must be divisible by the shard "
419
+ f"world size ({shard_world_size})"
420
+ )
421
+ shard_rank = self.post_forward_mesh_info.shard_mesh_rank
422
+ sharded_numel = numel // shard_world_size
423
+ self._sharded_post_forward_param_data = (
424
+ self.all_gather_outputs[0].narrow(
425
+ 0, sharded_numel * shard_rank, sharded_numel
426
+ )
427
+ ).clone() # clone to be able to free all-gather output
428
+ sharded_post_forward_tensor = torch.as_strided(
429
+ self._sharded_post_forward_param_data,
430
+ size=self.sharded_post_forward_size,
431
+ stride=self.contiguous_sharded_post_forward_stride,
432
+ storage_offset=0,
433
+ )
434
+ self._sharded_post_forward_param = nn.Parameter(
435
+ self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
436
+ )
437
+ self._setattr_on_modules(self._sharded_post_forward_param)
438
+ self.free_unsharded_param()
439
+ self.sharded_state = ShardedState.SHARDED_POST_FORWARD
440
+
441
+ def to_unsharded(self) -> None:
442
+ # Assume that the data has been allocated and all-gathered
443
+ set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
444
+ self._setattr_on_modules(self._unsharded_param)
445
+ if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
446
+ # The data is allocated in the default stream via the post-forward
447
+ # reshard and must be kept alive for the next all-gather copy-in.
448
+ # Since we call this method after the copy-out, the data's lifetime
449
+ # is ensured without further synchronization.
450
+ self._sharded_post_forward_param = None
451
+ self._sharded_post_forward_param_data = None # free
452
+ self.sharded_state = ShardedState.UNSHARDED
453
+
454
+ def _setattr_on_modules(self, param: nn.Parameter) -> None:
455
+ unsafe_setattr_param(
456
+ self._module_info.module, self._module_info.param_name, param
457
+ )
458
+ for shared_module, shared_param_name in zip(
459
+ self._module_info.shared_modules, self._module_info.shared_param_names
460
+ ):
461
+ unsafe_setattr_param(shared_module, shared_param_name, param)
462
+
463
+ def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
464
+ """
465
+ Converts a local tensor representing either the sharded parameter or
466
+ sharded gradient to DTensor.
467
+ """
468
+ if tensor.shape != self.sharded_size:
469
+ _raise_assert_with_print(
470
+ f"Expects size {self.sharded_size} but got {tensor.shape}"
471
+ )
472
+ return _from_local_no_grad(
473
+ tensor,
474
+ self._sharding_spec,
475
+ )
476
+
477
+ def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
478
+ if tensor.shape != self.sharded_post_forward_size:
479
+ _raise_assert_with_print(
480
+ f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
481
+ )
482
+ assert isinstance(self.post_forward_mesh_info, HSDPMeshInfo)
483
+ # TODO: Prefer this DTensor to be read-only and generalize the
484
+ # placement once we support TP.
485
+ post_forward_sharding_spec = DTensorSpec(
486
+ self.post_forward_mesh_info.mesh,
487
+ (Replicate(), Shard(0)),
488
+ tensor_meta=self._sharding_spec.tensor_meta,
489
+ )
490
+ return _from_local_no_grad(tensor, post_forward_sharding_spec)
491
+
492
+ def to_accumulated_grad_if_needed(self) -> None:
493
+ # Access `_unsharded_param` to bypass the sharded state check since we
494
+ # prefer to reshard before upcasting the gradient to save memory
495
+ if (
496
+ self.reduce_dtype is None
497
+ or self._unsharded_param.grad is None
498
+ or self._unsharded_param.grad.dtype == self.reduce_dtype
499
+ ):
500
+ return
501
+ unsharded_grad = self._unsharded_param.grad
502
+ self._unsharded_param.grad = None
503
+ self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
504
+
505
+ def accumulate_unsharded_grad_if_needed(self) -> None:
506
+ if (
507
+ self.unsharded_accumulated_grad is not None
508
+ and self.unsharded_param.grad is not None
509
+ ):
510
+ self.unsharded_accumulated_grad += self.unsharded_param.grad
511
+ self.unsharded_param.grad = None
512
+
513
+ def alloc_all_gather_outputs(self) -> None:
514
+ for tensor in self.all_gather_outputs:
515
+ alloc_storage(tensor)
516
+
517
+ def free_unsharded_param(self) -> None:
518
+ for tensor in itertools.chain(
519
+ self.all_gather_outputs, self._unsharded_inner_tensors
520
+ ):
521
+ free_storage(tensor)
522
+ if ca.compiled_autograd_enabled:
523
+ self.all_gather_outputs = []
524
+ self._unsharded_inner_tensors = []
525
+
526
+ @property
527
+ def all_gather_inputs(self) -> List[torch.Tensor]: # 1D
528
+ self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
529
+ if self.sharded_state == ShardedState.SHARDED:
530
+ if not ca.compiled_autograd_enabled and hasattr(
531
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
532
+ ):
533
+ sharded_local_tensor = self._sharded_local_tensor
534
+ if self.offload_to_cpu:
535
+ sharded_local_tensor = sharded_local_tensor.to(
536
+ self.device, non_blocking=True
537
+ )
538
+ (
539
+ all_gather_inputs,
540
+ self._extensions_data.all_gather_metadata,
541
+ ) = sharded_local_tensor.fsdp_pre_all_gather(self.mesh_info.mesh)
542
+ self._extensions_data.all_gather_input_sizes = [
543
+ t.size() for t in all_gather_inputs
544
+ ]
545
+ return [t.view(-1) for t in all_gather_inputs]
546
+ sharded_param_data = self._sharded_param_data
547
+ if self.offload_to_cpu:
548
+ sharded_param_data = sharded_param_data.to(
549
+ self.device, non_blocking=True
550
+ )
551
+ return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
552
+ elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
553
+ if not ca.compiled_autograd_enabled and hasattr(
554
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
555
+ ):
556
+ raise NotImplementedError
557
+ all_gather_input = _to_dtype_if_needed(
558
+ cast(torch.Tensor, self._sharded_post_forward_param_data),
559
+ self.param_dtype,
560
+ )
561
+ return [all_gather_input]
562
+ return [torch.empty(0)] # mypy
563
+
564
+ @property
565
+ def unsharded_param(self) -> nn.Parameter: # ND
566
+ self._assert_in_states(ShardedState.UNSHARDED)
567
+ return self._unsharded_param
568
+
569
+ @property
570
+ def unsharded_grad_data(self) -> torch.Tensor:
571
+ grad = self.unsharded_param.grad
572
+ assert grad is not None, "Expects unsharded_param.grad to not be None"
573
+ return self._get_grad_inner_tensor(grad)
574
+
575
+ @property
576
+ def unsharded_accumulated_grad_data(self) -> torch.Tensor:
577
+ grad = self.unsharded_accumulated_grad
578
+ assert grad is not None, "Expects unsharded_accumulated_grad to not be None"
579
+ return self._get_grad_inner_tensor(grad)
580
+
581
+ def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
582
+ if self.is_dtensor:
583
+ if isinstance(grad, AsyncCollectiveTensor):
584
+ grad = grad.wait()
585
+ assert isinstance(grad, DTensor), f"{type(grad)}"
586
+ if any(pl.is_partial() for pl in grad.placements):
587
+ placements = [
588
+ Replicate() if pl.is_partial() else pl for pl in grad.placements
589
+ ]
590
+ grad = grad.redistribute(placements=placements)
591
+ grad = grad._local_tensor
592
+ return grad
593
+
594
+ @property
595
+ def _sharded_local_tensor(self) -> torch.Tensor:
596
+ return cast(DTensor, self.sharded_param)._local_tensor
597
+
598
+ def _assert_in_states(self, *states: ShardedState) -> None:
599
+ if self.sharded_state not in states:
600
+ _raise_assert_with_print(
601
+ f"Expects to be in one of {states}, not {self.sharded_state}"
602
+ )
603
+
604
+ def reset_sharded_param(self):
605
+ # For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
606
+ # that change the sharded parameter tensor, we may need to re-pad the
607
+ # sharded local tensor and re-save the reference.
608
+ module_info = self._module_info
609
+ new_param = getattr(module_info.module, module_info.param_name)
610
+ if new_param is not self.sharded_param:
611
+ if torch.__future__.get_swap_module_params_on_conversion():
612
+ raise AssertionError(
613
+ f"Expects swap_tensors to preserve object but got {new_param} "
614
+ f"instead of {self.sharded_param}"
615
+ )
616
+ self.sharded_param = new_param
617
+ local_tensor = new_param._local_tensor
618
+ if local_tensor.is_meta:
619
+ return
620
+ padded_sharded_size = self.padded_sharded_param_size
621
+ if local_tensor.size() != padded_sharded_size:
622
+ padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
623
+ padded_local_tensor[: local_tensor.size(0)].copy_(local_tensor)
624
+ local_tensor = padded_local_tensor
625
+ if self.pin_memory and not local_tensor.is_pinned():
626
+ local_tensor = local_tensor.cpu().pin_memory()
627
+ self._sharded_param_data = local_tensor.view(-1)
628
+ assert isinstance(self.sharded_param, DTensor) # mypy
629
+ self.sharded_param._local_tensor = local_tensor[: self.sharded_size[0]]
630
+
631
+
632
+ def alloc_storage(tensor: torch.Tensor) -> None:
633
+ size = tensor.numel() * tensor.itemsize
634
+ if (storage := tensor.untyped_storage()).size() != size:
635
+ storage.resize_(size)
636
+
637
+
638
+ def free_storage(tensor: torch.Tensor) -> None:
639
+ if (storage := tensor.untyped_storage()).size() != 0:
640
+ storage.resize_(0)
641
+
642
+
643
+ # NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
644
+ # CPU overhead, if the module did not override it. For FSDP, we know we do not
645
+ # need those checks when transitioning between sharded/unsharded parameters.
646
+ def unsafe_setattr_param(
647
+ module: nn.Module, param_name: str, param: nn.Parameter
648
+ ) -> None:
649
+ if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
650
+ module._parameters[param_name] = param
651
+ else: # slow path
652
+ setattr(module, param_name, param)
653
+
654
+
655
+ def set_requires_grad_if_needed(
656
+ src_tensor: torch.Tensor, dst_tensor: torch.Tensor
657
+ ) -> None:
658
+ # Only call `requires_grad_` if needed to avoid the Python <> C++ context
659
+ # switch overhead
660
+ if src_tensor.requires_grad != dst_tensor.requires_grad:
661
+ dst_tensor.requires_grad_(src_tensor.requires_grad)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_param_group.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+
4
+ from typing import Any, cast, Dict, List, NamedTuple, Optional, Set, Tuple
5
+
6
+ import torch
7
+ import torch._dynamo.compiled_autograd as ca
8
+ import torch.distributed as dist
9
+ import torch.nn as nn
10
+ from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
11
+ from torch.utils._pytree import tree_flatten, tree_unflatten
12
+ from torch.utils.hooks import RemovableHandle
13
+ from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
14
+ from ._fsdp_collectives import (
15
+ AllGatherResult,
16
+ foreach_all_gather,
17
+ foreach_all_gather_copy_out,
18
+ foreach_reduce,
19
+ )
20
+ from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo, TrainingState
21
+ from ._fsdp_param import FSDPParam, ParamModuleInfo, ShardedState
22
+
23
+ _ModuleToHandleDict = Dict[nn.Module, RemovableHandle] # for state dict
24
+
25
+
26
+ """
27
+ [Note: Overlapping all-gather copy-in and all-gather]
28
+ For implicit forward prefetching, we want to overlap the next copy-in with the
29
+ current all-gather. We do so using a separate copy-in stream. However, since
30
+ we have the all-gather input as a view into the output, we must make sure to
31
+ copy into different memory from the current all-gather's output. Thus, we keep
32
+ a reference to the current all-gather's output and have the next FSDP parameter
33
+ group free it after its copy-in. Finally, we have the last FSDP state flush the
34
+ reference to avoid holding onto memory after forward.
35
+ """
36
+
37
+
38
+ class FSDPCommContext:
39
+ """This has the communication state shared across FSDP states/parameter groups."""
40
+
41
+ def init(self):
42
+ # Setting the all-gather/reduce-scatter streams to be higher priority
43
+ # can help avoid some issues where their copies in/out are delayed and
44
+ # block computation
45
+ high_priority = -1
46
+ # All-gather state and copy-in stream allow overlapping the next
47
+ # copy-in with the current all-gather in forward; copy-in overlaps with
48
+ # reduce-scatter in backward without the separate copy-in stream
49
+ self.all_gather_copy_in_stream = torch.cuda.Stream(priority=high_priority)
50
+ self.all_gather_state: Optional[AllGatherState] = None
51
+ # All-gather stream allows overlapping next all-gather with current
52
+ # forward compute
53
+ self.all_gather_stream = torch.cuda.Stream(priority=high_priority)
54
+ # Reduce-scatter stream gives separate execution "thread" for post-
55
+ # backward logic like pre/post-gradient division and reduce-scatter
56
+ self.reduce_scatter_stream = torch.cuda.Stream(priority=high_priority)
57
+ # Run the HSDP all-reduces concurrently with all-gather/reduce-scatter
58
+ # since collectives use different network resources and can overlap
59
+ # in the typical intra-node sharding / inter-node replication case
60
+ self.all_reduce_stream = torch.cuda.Stream()
61
+ # Post-forward order for explicit backward prefetching
62
+ self.post_forward_order: List[FSDPParamGroup] = [] # will cause ref cycles
63
+
64
+ def get_all_gather_streams(
65
+ self, training_state: TrainingState
66
+ ) -> Tuple[torch.cuda.Stream, torch.cuda.Stream]:
67
+ if training_state in (TrainingState.FORWARD, TrainingState.PRE_BACKWARD):
68
+ # Use separate streams for implicit prefetching
69
+ return self.all_gather_copy_in_stream, self.all_gather_stream
70
+ current_stream = torch.cuda.current_stream()
71
+ return current_stream, current_stream
72
+
73
+
74
+ # See [Note: Overlapping all-gather copy-in and all-gather]
75
+ class AllGatherState(NamedTuple):
76
+ all_gather_result: AllGatherResult
77
+ event: torch.cuda.Event # all-gather copy-out
78
+
79
+
80
+ class FSDPParamGroup:
81
+ """This class represents a parameter group to communicate together."""
82
+
83
+ _orig_dtype: torch.dtype
84
+ _reduce_dtype: Optional[torch.dtype]
85
+
86
+ def __init__(
87
+ self,
88
+ params: List[nn.Parameter],
89
+ module: nn.Module,
90
+ mesh_info: FSDPMeshInfo,
91
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
92
+ device: torch.device,
93
+ mp_policy: MixedPrecisionPolicy,
94
+ offload_policy: OffloadPolicy,
95
+ ):
96
+ self.module = module # permit ref cycle because 1:1 lifetime
97
+ param_module_infos = _get_param_module_infos(params, module)
98
+ self.fsdp_params = [
99
+ FSDPParam(
100
+ param,
101
+ module_info,
102
+ mesh_info,
103
+ post_forward_mesh_info,
104
+ device,
105
+ mp_policy,
106
+ offload_policy,
107
+ )
108
+ for param, module_info in zip(params, param_module_infos)
109
+ ]
110
+ self.mesh_info = mesh_info
111
+ self.post_forward_mesh_info = post_forward_mesh_info
112
+ self.device = device
113
+ self.mp_policy = mp_policy
114
+ self._training_state = TrainingState.IDLE
115
+ # Group's sharded state always matches its parameters' sharded states
116
+ self._sharded_state = ShardedState.SHARDED
117
+ self._module_fqn: Optional[str] = None # prefixed from root module
118
+
119
+ # - Hook state
120
+ self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
121
+ self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
122
+
123
+ # - Communication and communication/computation overlap
124
+ self.comm_ctx = FSDPCommContext()
125
+ # Group's indices in the shared post-forward order
126
+ self._post_forward_indices: List[int] = []
127
+ # Whether to reduce gradients at all (whether for FSDP or HSDP)
128
+ self.reduce_grads: bool = True
129
+ # Whether to all-reduce gradients for HSDP; only used if
130
+ # `self.reduce_grads` is true, in which case setting this to false
131
+ # means reduce-scatter but no all-reduce
132
+ self.all_reduce_grads: bool = True
133
+ # Whether to reshard parameters after backward (only useful for
134
+ # gradient accumulation)
135
+ self.reshard_after_backward: bool = True
136
+
137
+ # - CUDA events for stream synchronization
138
+ # Holds the all-gather output buffer, sync objects, and metadata
139
+ self._all_gather_result: Optional[AllGatherResult] = None
140
+ # Holds the reduce-scatter/all-reduce view-out CUDA event that marks the end of
141
+ # the group's post-backward (e.g. reduce-scatter, all-reduce and div), which
142
+ # should be waited on at the end of backward
143
+ self._post_reduce_event: Optional[torch.cuda.Event] = None
144
+ # Holds the reshard-after-forward CUDA event when resharding to a
145
+ # different world size, which should be waited on in the next unshard
146
+ self._reshard_after_forward_event: Optional[torch.cuda.Event] = None
147
+
148
+ # Only for HSDP, if accumulating gradients without all-reduce, save the
149
+ # partial reduce output (only reduce-scattered but not all-reduced)
150
+ self._partial_reduce_output: Optional[torch.Tensor] = None
151
+
152
+ # TODO: remove this hook and hook register once 2D state dict is supported.
153
+ def _raise_not_implemented_if_2d(*args: Any, **kwargs: Any) -> None:
154
+ raise NotImplementedError(
155
+ "2D state_dict is under development. Please check "
156
+ "https://github.com/pytorch/pytorch/issues/129627 for more details."
157
+ )
158
+
159
+ modules_with_2d_params: Set[nn.Module] = set()
160
+ for fsdp_param in self.fsdp_params:
161
+ module = fsdp_param._module_info.module
162
+ if len(fsdp_param._spmd_placements) > 1:
163
+ modules_with_2d_params.add(module)
164
+ for module in modules_with_2d_params:
165
+ module.register_state_dict_pre_hook(_raise_not_implemented_if_2d)
166
+ module._register_load_state_dict_pre_hook(_raise_not_implemented_if_2d)
167
+
168
+ # Initialization #
169
+ def _init_mp_dtypes(self) -> None:
170
+ for fsdp_param in self.fsdp_params:
171
+ fsdp_param.init_dtype_attrs(self.mp_policy)
172
+ orig_dtypes = {fsdp_param.orig_dtype for fsdp_param in self.fsdp_params}
173
+ if len(orig_dtypes) != 1:
174
+ # This can be relaxed if we copy-out for the reduce-scatter
175
+ raise AssertionError(
176
+ f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
177
+ )
178
+ self._orig_dtype = next(iter(orig_dtypes))
179
+ reduce_dtypes = {fsdp_param.reduce_dtype for fsdp_param in self.fsdp_params}
180
+ if len(reduce_dtypes) != 1:
181
+ # This can be relaxed if we issue one reduce-scatter per reduce
182
+ # dtype (but we would need a way for users to specify multiple
183
+ # reduce dtypes)
184
+ raise AssertionError(
185
+ f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
186
+ )
187
+ self._reduce_dtype = next(iter(reduce_dtypes))
188
+
189
+ def lazy_init(self):
190
+ # Lazy init should be idempotent
191
+ param_names_on_meta = [
192
+ fsdp_param._param_fqn
193
+ for fsdp_param in self.fsdp_params
194
+ if fsdp_param.sharded_param.device.type == "meta"
195
+ ]
196
+ if param_names_on_meta:
197
+ raise RuntimeError(
198
+ "FSDP parameters should be materialized from meta device before training, "
199
+ f"but the following were still on meta device: {param_names_on_meta}\n"
200
+ "For example, call module.to_empty(device) to materialize to device and "
201
+ "call module.reset_parameters() on each module to initialize values."
202
+ )
203
+ # Initialize mixed precision attributes lazily in case the user changes
204
+ # the parameter dtypes after construction time but before forward
205
+ self._init_mp_dtypes()
206
+ self._register_state_dict_hooks()
207
+
208
+ # Runtime #
209
+ def unshard(self, async_op: bool = False):
210
+ if self._all_gather_result is not None: # already called, pending wait
211
+ return
212
+ if self.is_unsharded:
213
+ return # no-op
214
+ if self._reshard_after_forward_event is not None:
215
+ # Resharded parameter data is allocated in the default stream and
216
+ # used in the all-gather streams
217
+ self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
218
+ self._reshard_after_forward_event = None
219
+ self._all_gather_result = foreach_all_gather(
220
+ self.fsdp_params,
221
+ self._all_gather_process_group,
222
+ async_op,
223
+ *self.comm_ctx.get_all_gather_streams(self._training_state),
224
+ self.device,
225
+ )
226
+
227
+ def wait_for_unshard(self):
228
+ """
229
+ 1. In forward with implict prefetching, to overlap the current copy-out
230
+ with the next all-gather, we save a reference to the current all-gather
231
+ result to free after the next copy-out.
232
+ 2. Otherwise (explicit prefetching or in backward), we free the
233
+ all-gather result immediately after the current copy-out since we can
234
+ already overlap the current copy-out with the previous reduce-scatter.
235
+ """
236
+ if not self._all_gather_result:
237
+ return # no preceding unshard
238
+ if self._training_state == TrainingState.FORWARD: # implicit prefetch
239
+ if prev_all_gather_state := self.comm_ctx.all_gather_state:
240
+ self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
241
+ self.comm_ctx.all_gather_state = None # free the all-gather result
242
+ foreach_all_gather_copy_out(
243
+ self._all_gather_result, self.fsdp_params, self._all_gather_process_group
244
+ )
245
+ for fsdp_param in self.fsdp_params:
246
+ fsdp_param.init_unsharded_param()
247
+ self._to_unsharded()
248
+ all_gather_copy_out_event = torch.cuda.Event()
249
+ all_gather_copy_out_event.record()
250
+ if self._training_state == TrainingState.FORWARD:
251
+ self.comm_ctx.all_gather_state = AllGatherState(
252
+ self._all_gather_result, all_gather_copy_out_event
253
+ )
254
+ else:
255
+ self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
256
+ self._all_gather_result = None # free unless saved in `all_gather_state`
257
+
258
+ def _wait_all_gather_streams_on_event(self, event: torch.cuda.Event):
259
+ self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
260
+ self.comm_ctx.all_gather_stream.wait_event(event)
261
+
262
+ def reshard(self):
263
+ if self._training_state == TrainingState.FORWARD:
264
+ if not self._reshard_after_forward:
265
+ return
266
+ if self._use_post_forward_mesh:
267
+ self._to_sharded_post_forward()
268
+ self._reshard_after_forward_event = torch.cuda.Event()
269
+ self._reshard_after_forward_event.record()
270
+ return
271
+ self._to_sharded()
272
+
273
+ def pre_forward(
274
+ self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
275
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
276
+ with torch.profiler.record_function("FSDP::pre_forward"):
277
+ self._training_state = TrainingState.FORWARD
278
+ self.unshard()
279
+ self.wait_for_unshard()
280
+ args, kwargs = self._register_post_backward_hook(args, kwargs)
281
+ return args, kwargs
282
+
283
+ def post_forward(self, module: nn.Module, input: Any, output: Any):
284
+ with torch.profiler.record_function("FSDP::post_forward"):
285
+ self.reshard()
286
+ self._record_post_forward()
287
+ self._training_state = TrainingState.IDLE
288
+ return output
289
+
290
+ def _record_post_forward(self) -> None:
291
+ # Since a group has one pre-backward unshard for each forward call
292
+ # before the backward, we record each usage (with multiplicity)
293
+ post_forward_index = len(self.comm_ctx.post_forward_order)
294
+ self.comm_ctx.post_forward_order.append(self)
295
+ self._post_forward_indices.append(post_forward_index)
296
+
297
+ def pre_backward(self, *unused: Any):
298
+ if self._training_state == TrainingState.PRE_BACKWARD:
299
+ return
300
+ with torch.profiler.record_function("FSDP::pre_backward"):
301
+ self._training_state = TrainingState.PRE_BACKWARD
302
+ self.unshard() # no-op if prefetched
303
+ self.wait_for_unshard()
304
+ self._prefetch_unshard()
305
+
306
+ def post_backward(self, *unused: Any):
307
+ self._training_state = TrainingState.POST_BACKWARD
308
+ with torch.profiler.record_function("FSDP::post_backward_accumulate"):
309
+ for fsdp_param in self.fsdp_params:
310
+ fsdp_param.accumulate_unsharded_grad_if_needed()
311
+ with torch.profiler.record_function("FSDP::post_backward_reshard"):
312
+ if not self.reduce_grads:
313
+ if self.reshard_after_backward:
314
+ self.reshard()
315
+ for fsdp_param in self.fsdp_params:
316
+ fsdp_param.to_accumulated_grad_if_needed()
317
+ return
318
+ # Save the autograd-computed gradients before resharding to only
319
+ # access the unsharded parameters when their data is present
320
+ fsdp_params_with_grad: List[FSDPParam] = []
321
+ unsharded_grads: List[torch.Tensor] = []
322
+ for fsdp_param in self.fsdp_params:
323
+ # May have an accumulated gradient of the reduce dtype if the
324
+ # previous backward did not reduce-scatter
325
+ if fsdp_param.unsharded_accumulated_grad is not None:
326
+ fsdp_params_with_grad.append(fsdp_param)
327
+ unsharded_grads.append(fsdp_param.unsharded_accumulated_grad_data)
328
+ fsdp_param.unsharded_accumulated_grad = None
329
+ elif fsdp_param.unsharded_param.grad is not None:
330
+ fsdp_params_with_grad.append(fsdp_param)
331
+ unsharded_grads.append(fsdp_param.unsharded_grad_data)
332
+ fsdp_param.unsharded_param.grad = None
333
+ if self.reshard_after_backward:
334
+ self.reshard()
335
+ if len(fsdp_params_with_grad) == 0:
336
+ return
337
+ with torch.profiler.record_function("FSDP::post_backward_reduce"):
338
+ self._post_reduce_event, self._partial_reduce_output = foreach_reduce(
339
+ fsdp_params_with_grad,
340
+ unsharded_grads,
341
+ self._reduce_scatter_process_group,
342
+ self.comm_ctx.reduce_scatter_stream,
343
+ self._orig_dtype,
344
+ self._reduce_dtype,
345
+ self.device,
346
+ self._all_reduce_process_group if self._is_hsdp else None,
347
+ self.comm_ctx.all_reduce_stream,
348
+ self.all_reduce_grads,
349
+ self._partial_reduce_output,
350
+ )
351
+
352
+ def finalize_backward(self):
353
+ if self._post_reduce_event is not None:
354
+ torch.cuda.current_stream().wait_event(self._post_reduce_event)
355
+ self._post_reduce_event = None
356
+ for fsdp_param in self.fsdp_params:
357
+ if fsdp_param.grad_offload_event is not None:
358
+ fsdp_param.grad_offload_event.synchronize()
359
+ fsdp_param.grad_offload_event = None
360
+ self._post_forward_indices.clear()
361
+
362
+ def _prefetch_unshard(self):
363
+ if self._training_state == TrainingState.PRE_BACKWARD:
364
+ if not self._post_forward_indices:
365
+ # Can be cleared if running multiple `backward`s
366
+ return
367
+ curr_index = self._post_forward_indices.pop()
368
+ if (target_index := curr_index - 1) < 0:
369
+ return
370
+ # Prefetch naively using the reverse post-forward order, which may
371
+ # have mistargeted prefetches if not all modules used in forward
372
+ # are used in this backward
373
+ target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
374
+ with torch.profiler.record_function(
375
+ "FSDP::backward_prefetch"
376
+ ), target_fsdp_param_group.use_training_state(TrainingState.PRE_BACKWARD):
377
+ target_fsdp_param_group.unshard()
378
+
379
+ # Utilities #
380
+ def _to_sharded(self):
381
+ if not self.is_sharded:
382
+ for fsdp_param in self.fsdp_params:
383
+ fsdp_param.to_sharded()
384
+ self._sharded_state = ShardedState.SHARDED
385
+
386
+ def _to_sharded_post_forward(self):
387
+ if not self.is_sharded_post_forward:
388
+ for fsdp_param in self.fsdp_params:
389
+ fsdp_param.to_sharded_post_forward()
390
+ self._sharded_state = ShardedState.SHARDED_POST_FORWARD
391
+
392
+ def _to_unsharded(self):
393
+ if not self.is_unsharded:
394
+ for fsdp_param in self.fsdp_params:
395
+ fsdp_param.to_unsharded()
396
+ self._sharded_state = ShardedState.UNSHARDED
397
+
398
+ @property
399
+ def is_sharded(self) -> bool:
400
+ return self._sharded_state == ShardedState.SHARDED
401
+
402
+ @property
403
+ def is_sharded_post_forward(self) -> bool:
404
+ return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
405
+
406
+ @property
407
+ def is_unsharded(self) -> bool:
408
+ return self._sharded_state == ShardedState.UNSHARDED
409
+
410
+ @contextlib.contextmanager
411
+ def use_training_state(self, training_state: TrainingState):
412
+ old_training_state = self._training_state
413
+ self._training_state = training_state
414
+ try:
415
+ yield
416
+ finally:
417
+ self._training_state = old_training_state
418
+
419
+ # Hook Registration #
420
+ def _register_post_backward_hook(
421
+ self, args: Tuple[Any, ...], kwargs: Dict[str, Any]
422
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
423
+ # Compile relies on `root_post_backward_callback` to call each `FSDPParamGroup.post_backward`
424
+ if ca.compiled_autograd_enabled:
425
+ return args, kwargs
426
+ if not torch.is_grad_enabled():
427
+ return args, kwargs
428
+ args_list, args_spec = tree_flatten(args)
429
+ kwargs_list, kwargs_spec = tree_flatten(kwargs)
430
+ args_kwargs_list = list(args_list) + list(kwargs_list)
431
+ inp_tensor_indices: List[int] = []
432
+ inp_tensors: List[torch.Tensor] = []
433
+ for i, obj in enumerate(args_kwargs_list):
434
+ if torch.is_tensor(obj) and obj.requires_grad:
435
+ inp_tensor_indices.append(i)
436
+ inp_tensors.append(obj)
437
+ if len(inp_tensors) == 0:
438
+ return args, kwargs # no tensors that require gradients
439
+ inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
440
+ for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
441
+ args_kwargs_list[inp_tensor_idx] = inp_tensor
442
+ args_list = args_kwargs_list[: len(args_list)]
443
+ kwargs_list = args_kwargs_list[len(args_list) :]
444
+ args = tree_unflatten(args_list, args_spec)
445
+ kwargs = tree_unflatten(kwargs_list, kwargs_spec)
446
+ return args, kwargs
447
+
448
+ def _register_state_dict_hooks(self) -> None:
449
+ num_pre_save_hooks = len(self._module_to_pre_save_state_dict_hook_handle)
450
+ num_pre_load_hooks = len(self._module_to_pre_load_state_dict_hook_handle)
451
+ assert (
452
+ num_pre_save_hooks == num_pre_load_hooks
453
+ ), f"Pre-save: {num_pre_save_hooks} pre-load: {num_pre_load_hooks}"
454
+ if num_pre_save_hooks > 0:
455
+ return # already registered
456
+ modules_with_fsdp_params: Set[nn.Module] = {
457
+ fsdp_param._module_info.module for fsdp_param in self.fsdp_params
458
+ }
459
+
460
+ def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
461
+ self._to_sharded()
462
+
463
+ for module in modules_with_fsdp_params:
464
+ self._module_to_pre_save_state_dict_hook_handle[
465
+ module
466
+ ] = module.register_state_dict_pre_hook(to_sharded_hook)
467
+ self._module_to_pre_load_state_dict_hook_handle[
468
+ module
469
+ ] = module._register_load_state_dict_pre_hook(to_sharded_hook)
470
+
471
+ # Properties #
472
+ @property
473
+ def _reshard_after_forward(self) -> bool:
474
+ return self.post_forward_mesh_info is not None
475
+
476
+ @property
477
+ def _use_post_forward_mesh(self) -> bool:
478
+ return (
479
+ self._reshard_after_forward
480
+ and self.mesh_info != self.post_forward_mesh_info
481
+ )
482
+
483
+ @property
484
+ def _is_hsdp(self) -> bool:
485
+ return isinstance(self.mesh_info, HSDPMeshInfo)
486
+
487
+ @property
488
+ def _all_gather_process_group(self) -> dist.ProcessGroup:
489
+ mesh_info = (
490
+ cast(FSDPMeshInfo, self.post_forward_mesh_info)
491
+ if self.is_sharded_post_forward
492
+ else self.mesh_info
493
+ )
494
+ assert isinstance(mesh_info, FSDPMeshInfo)
495
+ return mesh_info.shard_process_group
496
+
497
+ @property
498
+ def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
499
+ assert isinstance(self.mesh_info, FSDPMeshInfo)
500
+ return self.mesh_info.shard_process_group
501
+
502
+ @property
503
+ def _all_reduce_process_group(self) -> dist.ProcessGroup:
504
+ assert isinstance(self.mesh_info, HSDPMeshInfo)
505
+ return self.mesh_info.replicate_process_group
506
+
507
+
508
+ def _get_param_module_infos(
509
+ params: List[nn.Parameter], module: nn.Module
510
+ ) -> List[ParamModuleInfo]:
511
+ """
512
+ Shared parameter: lin1.weight = lin2.weight
513
+ Shared module: mlp.lin1 = mlp.lin2
514
+ We do not remove duplicates when traversing both modules and parameters to
515
+ find shared modules' parameters and shared parameters within a module.
516
+ """
517
+ params_set = set(params)
518
+ param_to_module_info: Dict[nn.Parameter, ParamModuleInfo] = {}
519
+ for _, submodule in module.named_modules(remove_duplicate=False):
520
+ for param_name, param in _named_parameters_with_duplicates(
521
+ submodule, recurse=False
522
+ ):
523
+ if param in params_set:
524
+ if param not in param_to_module_info:
525
+ param_to_module_info[param] = ParamModuleInfo(submodule, param_name)
526
+ else:
527
+ param_to_module_info[param].shared_modules.append(submodule)
528
+ param_to_module_info[param].shared_param_names.append(param_name)
529
+ if len(param_to_module_info) != len(params):
530
+ raise AssertionError(f"Some parameters are not in the module tree of {module}")
531
+ return [param_to_module_info[param] for param in params]
532
+
533
+
534
+ class RegisterPostBackwardFunction(torch.autograd.Function):
535
+ @staticmethod
536
+ def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
537
+ # All tensors in `inputs` should require gradient
538
+ ctx.param_group = param_group
539
+ return inputs
540
+
541
+ @staticmethod
542
+ def backward(ctx, *grads: torch.Tensor):
543
+ ctx.param_group.post_backward()
544
+ return (None,) + grads
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/_fsdp_state.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+
4
+ from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.autograd import Variable
9
+ from torch.distributed._composable_state import (
10
+ _get_module_state,
11
+ _insert_module_state,
12
+ _State,
13
+ )
14
+ from torch.distributed.utils import _to_kwargs
15
+ from torch.utils._pytree import tree_flatten, tree_map
16
+ from ._fsdp_api import MixedPrecisionPolicy
17
+ from ._fsdp_common import _cast_fp_tensor, TrainingState
18
+ from ._fsdp_param_group import FSDPCommContext, FSDPParamGroup
19
+
20
+ if TYPE_CHECKING:
21
+ from ._fsdp_param import FSDPParam
22
+
23
+
24
+ class FSDPStateContext:
25
+ """This has state shared across FSDP states."""
26
+
27
+ def __init__(self):
28
+ # All FSDP states in the root state's module tree
29
+ self.all_states: List[FSDPState] = []
30
+ # Iteration's forward root runs the once-per-forward logic; this root
31
+ # may not be the overall root set by lazy initialization in cases where
32
+ # only a submodule runs forward (e.g. encoder-only for eval)
33
+ self.iter_forward_root: Optional[FSDPState] = None
34
+ # Final callback should only be queued once per backward
35
+ self.post_backward_final_callback_queued: bool = False
36
+ # Whether to finalize backward in this backward's final callback
37
+ self.is_last_backward: bool = True
38
+
39
+
40
+ def disable_if_config_true(func):
41
+ @functools.wraps(func)
42
+ def fsdp_hook_wrapper(*args, **kwargs):
43
+ if torch._dynamo.config.skip_fsdp_hooks:
44
+ return torch._dynamo.disable(func, recursive=True)(*args, **kwargs)
45
+ else:
46
+ return func(*args, **kwargs)
47
+
48
+ return fsdp_hook_wrapper
49
+
50
+
51
+ class FSDPState(_State):
52
+ def __init__(self):
53
+ super().__init__()
54
+ self._fsdp_param_group: Optional[FSDPParamGroup] = None
55
+ self._is_root: Optional[bool] = None # root set during lazy init
56
+ self._state_ctx = FSDPStateContext()
57
+ self._comm_ctx = FSDPCommContext()
58
+ self._training_state: TrainingState = TrainingState.IDLE
59
+
60
+ # Define a separate init since `__init__` is called in the contract
61
+ def init(
62
+ self, module: nn.Module, device: torch.device, mp_policy: MixedPrecisionPolicy
63
+ ) -> None:
64
+ _insert_module_state(module, self)
65
+ self._module = module
66
+ self._device = device
67
+ self._mp_policy = mp_policy
68
+ self._pre_forward_hook_handle = module.register_forward_pre_hook(
69
+ self._pre_forward, prepend=True, with_kwargs=True
70
+ )
71
+ self._post_forward_hook_handle = module.register_forward_hook(
72
+ self._post_forward, prepend=False
73
+ )
74
+
75
+ def _root_pre_forward(
76
+ self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
77
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
78
+ self._lazy_init()
79
+ if self._state_ctx.iter_forward_root is not None:
80
+ return args, kwargs
81
+ self._state_ctx.iter_forward_root = self
82
+ with torch.profiler.record_function("FSDP::root_pre_forward"):
83
+ # Wait for optimizer before implicitly prefetched all-gathers
84
+ current_stream = torch.cuda.current_stream()
85
+ self._comm_ctx.all_gather_copy_in_stream.wait_stream(current_stream)
86
+ self._comm_ctx.all_gather_stream.wait_stream(current_stream)
87
+ if self._device.type == "cuda":
88
+ with torch.profiler.record_function("FSDP::inputs_to_device"):
89
+ args_tuple, kwargs_tuple = _to_kwargs(
90
+ args, kwargs, self._device, False
91
+ ) # same as DDP
92
+ args, kwargs = args_tuple[0], kwargs_tuple[0]
93
+ return args, kwargs
94
+
95
+ def _lazy_init(self) -> None:
96
+ """
97
+ Lazy initialization represents when all modules' parallelisms have
98
+ finalized (e.g. FSDP has been applied to all desired modules). This
99
+ means that we can determine which state is the root, and we do so by
100
+ the 1st state to run forward.
101
+ """
102
+ if self._is_root is not None:
103
+ return # no-op: already initialized
104
+ self._is_root = True
105
+ root_module = self._module
106
+ for module_name, module in root_module.named_modules():
107
+ if (state := _get_module_fsdp_state(module)) is None:
108
+ continue
109
+ if module is not root_module:
110
+ if state._is_root is not None:
111
+ raise RuntimeError(
112
+ "FSDP state has already been lazily initialized for "
113
+ f"{module_name}\nFSDP requires running forward through "
114
+ "the root module first"
115
+ )
116
+ state._is_root = False
117
+ self._state_ctx.all_states.append(state)
118
+ if self._fsdp_param_group:
119
+ # For the root, do not reshard after forward since for training,
120
+ # the parameters would be freed and all-gathered immediately
121
+ self._fsdp_param_group.post_forward_mesh_info = None
122
+ self._init_fqns()
123
+ self._init_shared_state()
124
+ # Run parameter group lazy inits after initializing FQNs for improved
125
+ # error messages
126
+ for state in self._state_ctx.all_states:
127
+ if state._fsdp_param_group:
128
+ state._fsdp_param_group.lazy_init()
129
+
130
+ def _init_shared_state(self) -> None:
131
+ self._comm_ctx.init()
132
+ for state in self._state_ctx.all_states:
133
+ state._state_ctx = self._state_ctx
134
+ state._comm_ctx = self._comm_ctx
135
+ if fsdp_param_group := state._fsdp_param_group:
136
+ fsdp_param_group.comm_ctx = self._comm_ctx
137
+
138
+ def _init_fqns(self) -> None:
139
+ """Sets module and parameter FQN attributes for debugging."""
140
+ assert self._is_root
141
+ root_module = self._module
142
+ param_to_fsdp_param: Dict[nn.Parameter, FSDPParam] = {}
143
+ module_to_fsdp_param_group: Dict[nn.Module, FSDPParamGroup] = {}
144
+ for state in self._state_ctx.all_states:
145
+ if fsdp_param_group := state._fsdp_param_group:
146
+ for fsdp_param in fsdp_param_group.fsdp_params:
147
+ param_to_fsdp_param[fsdp_param.sharded_param] = fsdp_param
148
+ module_to_fsdp_param_group[fsdp_param_group.module] = fsdp_param_group
149
+ for param_name, param in root_module.named_parameters():
150
+ if param in param_to_fsdp_param:
151
+ param_to_fsdp_param[param]._param_fqn = param_name
152
+ for module_name, module in root_module.named_modules():
153
+ if module in module_to_fsdp_param_group:
154
+ module_to_fsdp_param_group[module]._module_fqn = module_name
155
+
156
+ @disable_if_config_true
157
+ def _pre_forward(
158
+ self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
159
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
160
+ # When composing with module-hook-based activation checkpointing, the
161
+ # the pre-backward hook is responsible for the unshard
162
+ if self._training_state == TrainingState.PRE_BACKWARD:
163
+ return args, kwargs
164
+ self._training_state = TrainingState.FORWARD
165
+ args, kwargs = self._root_pre_forward(module, args, kwargs)
166
+ if self._mp_policy.cast_forward_inputs and self._mp_policy.param_dtype:
167
+ with torch.profiler.record_function("FSDP::cast_forward_inputs"):
168
+ cast_fn = functools.partial(
169
+ _cast_fp_tensor, self._mp_policy.param_dtype
170
+ )
171
+ args, kwargs = tree_map(cast_fn, args), tree_map(cast_fn, kwargs)
172
+ if self._fsdp_param_group:
173
+ args, kwargs = self._fsdp_param_group.pre_forward(module, args, kwargs)
174
+ return args, kwargs
175
+
176
+ @disable_if_config_true
177
+ def _post_forward(self, module: nn.Module, input: Any, output: Any) -> Any:
178
+ # When composing with module-hook-based activation checkpointing, the
179
+ # post-backward hook is responsible for the reshard
180
+ if self._training_state == TrainingState.PRE_BACKWARD:
181
+ return output
182
+ if self._fsdp_param_group:
183
+ output = self._fsdp_param_group.post_forward(module, input, output)
184
+ output = self._register_pre_backward_hook(output)
185
+ self._training_state = TrainingState.IDLE
186
+ if self._state_ctx.iter_forward_root is self:
187
+ if all_gather_state := self._comm_ctx.all_gather_state:
188
+ # Free the last all-gather result if needed; refer to
189
+ # [Note: Overlapping all-gather copy-in and all-gather]
190
+ self._comm_ctx.all_gather_copy_in_stream.wait_event(
191
+ all_gather_state.event
192
+ )
193
+ self._comm_ctx.all_gather_stream.wait_event(all_gather_state.event)
194
+ self._comm_ctx.all_gather_state = None # free the all-gather result
195
+ self._state_ctx.iter_forward_root = None
196
+ if self._mp_policy.output_dtype is not None:
197
+ with torch.profiler.record_function("FSDP::cast_forward_outputs"):
198
+ output = tree_map(
199
+ functools.partial(_cast_fp_tensor, self._mp_policy.output_dtype),
200
+ output,
201
+ )
202
+ return output
203
+
204
+ def _pre_backward(self, grad: torch.Tensor) -> torch.Tensor:
205
+ self._training_state = TrainingState.PRE_BACKWARD
206
+ self._register_root_post_backward_final_callback()
207
+ if self._fsdp_param_group:
208
+ self._fsdp_param_group.pre_backward()
209
+ return grad
210
+
211
+ def _root_post_backward_final_callback(self) -> None:
212
+ with torch.profiler.record_function("FSDP::root_post_backward_callback"):
213
+ for state in self._state_ctx.all_states:
214
+ if state._fsdp_param_group and state._fsdp_param_group.is_unsharded:
215
+ # Run post-backward in case forward inputs did not require
216
+ # gradient so the autograd backward did not run
217
+ state._fsdp_param_group.post_backward()
218
+ state._training_state = TrainingState.IDLE
219
+ if state._fsdp_param_group:
220
+ state._fsdp_param_group._training_state = TrainingState.IDLE
221
+ if self._state_ctx.is_last_backward:
222
+ state._finalize_backward()
223
+ if self._state_ctx.is_last_backward:
224
+ self._comm_ctx.post_forward_order.clear()
225
+ self._state_ctx.post_backward_final_callback_queued = False
226
+
227
+ def _finalize_backward(self) -> None:
228
+ if self._fsdp_param_group:
229
+ self._fsdp_param_group.finalize_backward()
230
+
231
+ def _register_pre_backward_hook(self, output: Any) -> Any:
232
+ if not torch.is_grad_enabled():
233
+ return output
234
+ flat_outputs, _ = tree_flatten(output)
235
+ tensors = tuple(
236
+ t for t in flat_outputs if (torch.is_tensor(t) and t.requires_grad)
237
+ )
238
+ if tensors:
239
+ for tensor in tensors:
240
+ tensor.register_hook(self._pre_backward)
241
+ return output
242
+
243
+ def _register_root_post_backward_final_callback(self):
244
+ if self._state_ctx.post_backward_final_callback_queued:
245
+ return
246
+ self._state_ctx.post_backward_final_callback_queued = True
247
+ Variable._execution_engine.queue_callback(
248
+ self._root_post_backward_final_callback
249
+ )
250
+
251
+
252
+ def _get_module_fsdp_state(module: nn.Module) -> Optional[FSDPState]:
253
+ state = _get_module_state(module)
254
+ if isinstance(state, FSDPState):
255
+ return state
256
+ return None
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fsdp/fully_shard.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+
4
+ from typing import Any, cast, NoReturn, Optional, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.distributed._composable import contract
9
+ from torch.distributed._tensor import DeviceMesh
10
+
11
+ from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
12
+ from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo
13
+ from ._fsdp_init import (
14
+ _get_device_from_mesh,
15
+ _get_managed_modules,
16
+ _get_managed_states,
17
+ _get_post_forward_mesh_info,
18
+ _init_default_fully_shard_mesh,
19
+ _move_states_to_device,
20
+ )
21
+ from ._fsdp_param_group import FSDPParamGroup
22
+ from ._fsdp_state import _get_module_fsdp_state, FSDPState
23
+
24
+
25
+ # The decorator adds a state object to `module` that can be accessed via
26
+ # `fully_shard.state(module)`. The state object and module are 1:1.
27
+ @contract(state_cls=FSDPState)
28
+ def fully_shard(
29
+ module: nn.Module,
30
+ *,
31
+ mesh: Optional[DeviceMesh] = None,
32
+ reshard_after_forward: Union[bool, int] = True,
33
+ mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
34
+ offload_policy: OffloadPolicy = OffloadPolicy(),
35
+ ):
36
+ """
37
+ Shard module parameters across data parallel workers.
38
+
39
+ This function applies fully sharded data parallelism (FSDP) or a variant to
40
+ ``module``, a technique for memory savings at the cost of communication.
41
+ Parameters are sharded across ``mesh``, and in turn, so are their gradients
42
+ and optimizer states.
43
+
44
+ The sharded parameters are all-gathered to construct the unsharded
45
+ parameters for forward or backward computation. The unsharded parameters
46
+ are freed after computation to save memory. The gradients are reduced
47
+ across the mesh and divided by the mesh size for data parallelism. The
48
+ optimizer step runs on the sharded parameters.
49
+
50
+ Each call to ``fully_shard`` constructs one communication group that
51
+ includes the parameters in ``module.parameters()`` except those already
52
+ assigned to a group from a nested call. Each group's parameters and its
53
+ gradients are communicated together in one collective, respectively.
54
+ Constructing multiple groups across the model (e.g. "layer by layer")
55
+ allows for peak memory savings and communication/computation overlap.
56
+
57
+ Implementation-wise, the sharded parameters are represented as
58
+ :class:`DTensor` s, sharded on dim-0, and the unsharded parameters are
59
+ represented as :class:`Tensor` s. A module forward pre-hook all-gathers the
60
+ parameters, and a module forward hook frees them. Similar backward hooks
61
+ gather parameters and later free parameters/reduce gradients.
62
+
63
+ Args:
64
+ mesh (Optional[DeviceMesh]): This data parallel mesh defines the
65
+ sharding and device. If 1D, then parameters are fully sharded
66
+ across the 1D mesh (FSDP). If 2D, then parameters are sharded
67
+ across the 0th dim and replicated across the 1st dim (HSDP). The
68
+ mesh's device type gives the device type used for communication;
69
+ if a CUDA or CUDA-like device type, then we use the current device.
70
+ reshard_after_forward (Union[bool, int]): This controls the parameter
71
+ behavior after forward and can trade off memory and communication:
72
+ - If ``True``, then this reshards parameters after forward and
73
+ all-gathers in backward.
74
+ - If ``False``, then this keeps the unsharded parameters in memory
75
+ after forward and avoids the all-gather in backward.
76
+ - If an ``int``, then this represents the world size to reshard to
77
+ after forward. It should be a non-trivial divisor of the ``mesh``
78
+ shard dim size (i.e. excluding 1 and the dim size itself). A choice
79
+ may be the intra-node size (e.g. ``torch.cuda.device_count()``).
80
+ This allows the all-gather in backward to be over a smaller world
81
+ size at the cost of higher memory usage than setting to ``True``.
82
+ - The root FSDP state has its value specially set to ``False`` as a
83
+ heuristic since its parameters would typically be immediately
84
+ all-gathered for backward.
85
+ - After forward, the parameters registered to the module depend on
86
+ to this: The registered parameters are the sharded parameters if
87
+ ``True``; unsharded parameters if ``False``; and the paramters
88
+ resharded to the smaller mesh otherwise. To modify the parameters
89
+ between forward and backward, the registered parameters must be the
90
+ sharded parameters. For ``False`` or an ``int``, this can be done
91
+ by manually resharding via :meth:`reshard`.
92
+ mp_policy (MixedPrecisionPolicy): This controls the mixed precision
93
+ policy, which offers parameter/reduction mixed precision for this
94
+ module. See :class:`MixedPrecisionPolicy` for details.
95
+ offload_policy (OffloadPolicy): This controls the offloading policy,
96
+ which offers parameter/gradient/optimizer state offloading. See
97
+ :class:`OffloadPolicy` and its subclasses for details.
98
+ """
99
+ if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
100
+ raise ValueError(
101
+ f"fully_shard does not support containers that do not implement forward: {module}"
102
+ )
103
+ mesh = mesh or _init_default_fully_shard_mesh()
104
+ if mesh.ndim not in (1, 2):
105
+ raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}")
106
+ elif mesh.ndim == 1:
107
+ mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0)
108
+ else:
109
+ mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0)
110
+ device = _get_device_from_mesh(mesh)
111
+ post_forward_mesh_info = _get_post_forward_mesh_info(
112
+ reshard_after_forward, mesh_info
113
+ )
114
+
115
+ state = fully_shard.state(module)
116
+ state.init(module, device, mp_policy)
117
+
118
+ managed_modules = _get_managed_modules(module)
119
+ params, buffers = _get_managed_states(managed_modules)
120
+ _move_states_to_device(params, buffers, device)
121
+ if params:
122
+ state._fsdp_param_group = FSDPParamGroup(
123
+ params,
124
+ module,
125
+ mesh_info,
126
+ post_forward_mesh_info,
127
+ device,
128
+ mp_policy,
129
+ offload_policy,
130
+ )
131
+
132
+ # For Dynamo
133
+ for managed_module in managed_modules:
134
+ managed_module._is_fsdp_managed_module = True # type: ignore[assignment]
135
+ managed_module._fsdp_use_orig_params = True # type: ignore[assignment]
136
+
137
+ # Place FSDP leftmost for highest priority in the method resolution order
138
+ cls = module.__class__
139
+ dct = {"__deepcopy__": unimplemented_deepcopy}
140
+ new_cls = type(f"FSDP{cls.__name__}", (FSDPModule, cls), dct)
141
+ module.__class__ = new_cls
142
+ return module
143
+
144
+
145
+ def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
146
+ raise AssertionError(
147
+ "FSDP does not support deepcopy. Please use state dict for serialization."
148
+ )
149
+
150
+
151
+ class FSDPModule:
152
+ def __new__(cls, *args, **kwargs):
153
+ """
154
+ Override ``__new__`` to remove the FSDP class and directly construct
155
+ the original class for cases like indexing into a container module.
156
+ """
157
+ # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
158
+ # and index 1 is the `FSDPModule` class itself
159
+ orig_cls = cls.__mro__[2]
160
+ self = orig_cls.__new__(orig_cls, *args, **kwargs)
161
+ self.__init__(*args, **kwargs)
162
+ return self
163
+
164
+ def reshard(self) -> None:
165
+ """
166
+ Reshards the module's parameters, registering the sharded parameters
167
+ to the module and freeing the unsharded parameters if needed. This
168
+ method is *not* recursive.
169
+ """
170
+ state = self._get_fsdp_state()
171
+ if fsdp_param_group := state._fsdp_param_group:
172
+ fsdp_param_group.reshard()
173
+
174
+ def unshard(self, async_op: bool = False) -> Optional["UnshardHandle"]:
175
+ """
176
+ Unshards the module's parameters by allocating memory and all-gathering
177
+ the parameters. This method is *not* recursive.
178
+
179
+ Args:
180
+ async_op (bool): If ``True``, then returns a :class:`UnshardHandle`
181
+ that has a :meth:`wait` method to wait on the unshard op. If
182
+ ``False``, then returns ``None`` and waits on the handle inside
183
+ this function.
184
+
185
+ .. warning:: This method is experimental and subject to change.
186
+
187
+ .. note:: If ``async_op=True``, then the user does not have to call
188
+ :meth:`wait` on the returned handle if waiting on the unshard op
189
+ in the module's pre-forward is tolerable. FSDP will wait on the
190
+ pending unshard op in the pre-forward automatically.
191
+ """
192
+ state = self._get_fsdp_state()
193
+ fsdp_param_group = state._fsdp_param_group
194
+ if fsdp_param_group is not None:
195
+ fsdp_param_group.lazy_init()
196
+ fsdp_param_group.unshard(async_op=async_op)
197
+ handle = UnshardHandle(fsdp_param_group)
198
+ if async_op:
199
+ return handle
200
+ handle.wait()
201
+ return None
202
+
203
+ def set_is_last_backward(self, is_last_backward: bool) -> None:
204
+ """
205
+ Sets whether the next backward is the last one, meaning that FSDP
206
+ should wait for gradient reduction to finish and clear internal data
207
+ structures used for explicit prefetching.
208
+ """
209
+ state = self._get_fsdp_state()
210
+ state._state_ctx.is_last_backward = is_last_backward
211
+
212
+ def set_requires_gradient_sync(
213
+ self, requires_gradient_sync: bool, *, recurse: bool = True
214
+ ) -> None:
215
+ """
216
+ Sets if the module should sync gradients. This can be used to implement
217
+ gradient accumulation without communication. For HSDP, this controls
218
+ both reduce-scatter and all-reduce together.
219
+
220
+ Args:
221
+ requires_gradient_sync (bool): Whether to reduce gradients for the
222
+ module's parameters.
223
+ recurse (bool): Whether to set for all submodules or just the
224
+ passed-in module.
225
+ """
226
+ self_module = cast(nn.Module, self)
227
+ modules = list(self_module.modules()) if recurse else [self_module]
228
+ for module in modules:
229
+ if isinstance(module, FSDPModule):
230
+ state = module._get_fsdp_state()
231
+ if fsdp_param_group := state._fsdp_param_group:
232
+ fsdp_param_group.reduce_grads = requires_gradient_sync
233
+ fsdp_param_group.all_reduce_grads = requires_gradient_sync
234
+
235
+ def set_requires_all_reduce(
236
+ self, requires_all_reduce: bool, *, recurse: bool = True
237
+ ) -> None:
238
+ """
239
+ Sets if the module should all-reduce gradients. This can be used to
240
+ implement gradient accumulation with only reduce-scatter but not
241
+ all-reduce for HSDP.
242
+ """
243
+ self_module = cast(nn.Module, self)
244
+ modules = list(self_module.modules()) if recurse else [self_module]
245
+ for module in modules:
246
+ if isinstance(module, FSDPModule):
247
+ state = module._get_fsdp_state()
248
+ if fsdp_param_group := state._fsdp_param_group:
249
+ fsdp_param_group.all_reduce_grads = requires_all_reduce
250
+
251
+ def set_reshard_after_backward(
252
+ self, reshard_after_backward: bool, *, recurse: bool = True
253
+ ) -> None:
254
+ """
255
+ Sets if the module should reshard parameters after backward. This can
256
+ be used during gradient accumulation to trade off higher memory for
257
+ reduced communication.
258
+
259
+ Args:
260
+ reshard_after_backward (bool): Whether to reshard parameters after
261
+ backward.
262
+ recurse (bool): Whether to set for all submodules or just the
263
+ passed-in module.
264
+ """
265
+ self_module = cast(nn.Module, self)
266
+ modules = list(self_module.modules()) if recurse else [self_module]
267
+ for module in modules:
268
+ if isinstance(module, FSDPModule):
269
+ state = module._get_fsdp_state()
270
+ if fsdp_param_group := state._fsdp_param_group:
271
+ fsdp_param_group.reshard_after_backward = reshard_after_backward
272
+
273
+ def _get_fsdp_state(self) -> FSDPState:
274
+ if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None:
275
+ raise AssertionError(f"No FSDP state found on {self}")
276
+ return state
277
+
278
+ def _apply(self, *args: Any, **kwargs: Any) -> Any:
279
+ # Reshard to ensure that sharded parameters are registered
280
+ self.reshard()
281
+ ret = super()._apply(*args, **kwargs) # type: ignore[misc]
282
+ state = self._get_fsdp_state()
283
+ if not (fsdp_param_group := state._fsdp_param_group):
284
+ return ret
285
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
286
+ # https://github.com/pytorch/pytorch/issues/113045
287
+ with torch.no_grad():
288
+ for fsdp_param in fsdp_param_group.fsdp_params:
289
+ fsdp_param.reset_sharded_param()
290
+ return ret
291
+
292
+
293
+ class UnshardHandle:
294
+ """
295
+ A handle to wait on the unshard op.
296
+
297
+ Args:
298
+ fsdp_param_group (FSDPParamGroup, optional): FSDP parameter group to
299
+ unshard. This should be ``None`` iff the FSDP module does not
300
+ manage any parameters, meaning the unshard is a no-op.
301
+ """
302
+
303
+ def __init__(self, fsdp_param_group: Optional[FSDPParamGroup]):
304
+ self._fsdp_param_group = fsdp_param_group
305
+
306
+ def wait(self):
307
+ """
308
+ Waits on the unshard op.
309
+
310
+ This ensures that the current stream can use the unsharded parameters,
311
+ which are now registered to the module.
312
+ """
313
+ if self._fsdp_param_group is not None:
314
+ self._fsdp_param_group.wait_for_unshard()
315
+ # Avoid keeping a reference
316
+ self._fsdp_param_group = None
317
+
318
+
319
+ def register_fsdp_forward_method(module: nn.Module, method_name: str) -> None:
320
+ """
321
+ Registers a method on ``module`` to be a forward method for FSDP.
322
+
323
+ FSDP only knows to run its pre-forward and post-forward hooks on the
324
+ default :meth:`nn.Module.forward` method. This function patches a user
325
+ specified method to run the pre/post-forward hooks before/after the method,
326
+ respectively. If ``module`` is not an :class:`FSDPModule`, then this is a
327
+ no-op.
328
+
329
+ Args:
330
+ module (nn.Module): Module to register the forward method on.
331
+ method_name (str): Name of the forward method.
332
+ """
333
+ if not isinstance(module, FSDPModule):
334
+ # Make no-op to allow including both when using/not using FSDP
335
+ return
336
+ if not hasattr(module, method_name):
337
+ raise ValueError(f"{type(module)} does not have a method {method_name}")
338
+ orig_method = getattr(module, method_name)
339
+
340
+ @functools.wraps(orig_method)
341
+ def wrapped_method(self, *args, **kwargs):
342
+ fsdp_state = self._get_fsdp_state()
343
+ args, kwargs = fsdp_state._pre_forward(self, args, kwargs)
344
+ out = orig_method(*args, **kwargs)
345
+ return fsdp_state._post_forward(self, args, out)
346
+
347
+ # Use `__get__` to make `wrapped_method` an instance method
348
+ setattr(module, method_name, wrapped_method.__get__(module, type(module)))
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/fully_shard.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Iterable, Optional, Union
2
+ from typing_extensions import deprecated
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.nn as nn
7
+ from torch.distributed._composable.contract import contract
8
+ from torch.distributed._composable_state import _get_module_state, _insert_module_state
9
+ from torch.distributed.fsdp._common_utils import _FSDPState
10
+ from torch.distributed.fsdp._dynamo_utils import _annotate_modules_for_dynamo
11
+
12
+ from torch.distributed.fsdp._init_utils import (
13
+ _init_buffer_state,
14
+ _init_core_state,
15
+ _init_device_handle,
16
+ _init_ignored_module_states,
17
+ _init_param_handle_from_module,
18
+ _init_prefetching_state,
19
+ _init_process_group_state,
20
+ _init_runtime_state,
21
+ _init_state_dict_state,
22
+ HYBRID_SHARDING_STRATEGIES,
23
+ )
24
+ from torch.distributed.fsdp._runtime_utils import (
25
+ _register_post_forward_hook,
26
+ _register_pre_forward_hook,
27
+ _register_root_pre_forward_hook,
28
+ )
29
+ from torch.distributed.fsdp._state_dict_utils import _register_all_state_dict_hooks
30
+ from torch.distributed.fsdp._wrap_utils import _auto_wrap
31
+ from torch.distributed.fsdp.api import (
32
+ BackwardPrefetch,
33
+ CPUOffload,
34
+ MixedPrecision,
35
+ ShardingStrategy,
36
+ )
37
+ from torch.distributed.fsdp.wrap import _Policy
38
+
39
+
40
+ @contract(state_cls=_FSDPState)
41
+ @deprecated(
42
+ "`torch.distributed._composable.fully_shard` is being deprecated. "
43
+ "You can continue to use the wrapper based FSDP. "
44
+ "See usage in: https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/fully_sharded_data_parallel.py. "
45
+ "`torch.distributed._composable.fully_shard` will be removed after PyTorch 2.5.",
46
+ category=FutureWarning,
47
+ )
48
+ def fully_shard(
49
+ module: nn.Module,
50
+ *,
51
+ process_group: Optional[dist.ProcessGroup] = None,
52
+ policy: Optional[_Policy] = None,
53
+ strategy: Optional[ShardingStrategy] = None,
54
+ mixed_precision: Optional[MixedPrecision] = None,
55
+ cpu_offload: Optional[CPUOffload] = None,
56
+ ignored_modules: Optional[Iterable[torch.nn.Module]] = None,
57
+ device_id: Optional[Union[int, torch.device]] = None,
58
+ param_init_fn: Optional[Callable[[nn.Module], None]] = None,
59
+ sync_module_states: bool = False,
60
+ forward_prefetch: bool = False,
61
+ ignored_states: Union[
62
+ Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
63
+ ] = None,
64
+ ) -> nn.Module:
65
+ """Applies ``FullyShardedDataParallel`` (FSDP) semantics to ``module``."""
66
+ torch._C._log_api_usage_once("torch.distributed.fully_shard")
67
+ # Enforce the new auto wrap policy
68
+ if policy is not None and not isinstance(policy, _Policy):
69
+ raise ValueError(f"Expects a `_Policy` but got {policy}")
70
+ state = fully_shard.state(module)
71
+ state = _init_ignored_module_states(state, module, ignored_modules, ignored_states)
72
+ state = _init_device_handle(state, module, state._ignored_params, device_id)
73
+ _annotate_modules_for_dynamo(module, state._ignored_modules, True)
74
+ state = _init_process_group_state(state, process_group, strategy, policy)
75
+ if policy is not None:
76
+ root_kwargs = {
77
+ "process_group": process_group,
78
+ "strategy": strategy,
79
+ "mixed_precision": mixed_precision,
80
+ "cpu_offload": cpu_offload,
81
+ "ignored_modules": ignored_modules,
82
+ "device_id": device_id,
83
+ "param_init_fn": param_init_fn,
84
+ "sync_module_states": sync_module_states,
85
+ "forward_prefetch": forward_prefetch,
86
+ "ignored_states": ignored_states,
87
+ }
88
+ if strategy in HYBRID_SHARDING_STRATEGIES:
89
+ root_kwargs["process_group"] = (state.process_group, state._inter_node_pg)
90
+ _auto_wrap(
91
+ module,
92
+ policy,
93
+ state._ignored_modules,
94
+ state._ignored_params,
95
+ root_kwargs,
96
+ fully_shard,
97
+ )
98
+ state = _init_core_state(
99
+ state,
100
+ strategy or ShardingStrategy.FULL_SHARD,
101
+ mixed_precision,
102
+ cpu_offload,
103
+ limit_all_gathers=True,
104
+ use_orig_params=True,
105
+ backward_prefetch_limit=1,
106
+ forward_prefetch_limit=1,
107
+ )
108
+ state = _init_runtime_state(state)
109
+ state = _init_prefetching_state(
110
+ state, BackwardPrefetch.BACKWARD_PRE, forward_prefetch=forward_prefetch
111
+ )
112
+ state = _init_buffer_state(state, module)
113
+ state = _init_param_handle_from_module(
114
+ state, module, device_id, param_init_fn, sync_module_states
115
+ )
116
+ state = _init_state_dict_state(state)
117
+ _register_all_state_dict_hooks(state)
118
+ _register_pre_forward_hook(state, module)
119
+ _register_post_forward_hook(state, module)
120
+ _register_root_pre_forward_hook(state, module) # prepend last
121
+ # Always insert the state for the passed-in module even if it has no
122
+ # managed parameters, in which case it has no handles and does not appear
123
+ # in `_fully_sharded_module_to_handles`
124
+ _insert_module_state(module, state)
125
+ for submodule in module.modules():
126
+ if (
127
+ submodule in state._fully_sharded_module_to_handle
128
+ and _get_module_state(submodule) is None
129
+ ):
130
+ _insert_module_state(submodule, state)
131
+ return module
data/home/.local/lib/python3.8/site-packages/torch/distributed/_composable/replicate.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import weakref
3
+ from typing import Any, cast, Dict, Iterable, List, NoReturn, Optional, Set, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.distributed._composable_state import _State
8
+ from torch.nn.parallel import DistributedDataParallel
9
+
10
+ from .contract import _get_registry, contract
11
+
12
+ _ROOT_MODULE_PREFIX = ""
13
+
14
+
15
+ class _ReplicateState(_State):
16
+ def __init__(self) -> None:
17
+ super().__init__()
18
+ self.module: nn.Module = nn.ParameterList()
19
+ self.has_initialized: bool = False
20
+ self._param_list: nn.ParameterList = nn.ParameterList()
21
+ # TODO(@fegin): this variable is originally create for testing, we
22
+ # should remove this if possible.
23
+ self._orig_module = self.module
24
+ self._param_names: List[str] = []
25
+ self._no_sync: bool = False
26
+ self._init_args: Optional[Tuple[Any, ...]] = None
27
+ self._init_kwargs: Dict[str, Any] = {}
28
+ self._comm_hook_args: List[Any] = []
29
+
30
+ def _collect_params(
31
+ self,
32
+ module: nn.Module,
33
+ ignored_modules: Set[nn.Module],
34
+ ignored_params: Set[nn.Parameter],
35
+ prefix: str = _ROOT_MODULE_PREFIX,
36
+ ) -> None:
37
+ # skip if managed by fully_sharded API
38
+ if _is_fully_sharded(module):
39
+ return
40
+
41
+ # if a module is ignored, all descendants of the module are ignored.
42
+ if module in ignored_modules:
43
+ return
44
+
45
+ recurse_prefix = (
46
+ f"{prefix}." if prefix != _ROOT_MODULE_PREFIX else _ROOT_MODULE_PREFIX
47
+ )
48
+
49
+ for n, p in module.named_parameters(recurse=False):
50
+ if p not in ignored_params:
51
+ self._param_list.append(p)
52
+ self._param_names.append(f"{recurse_prefix}{n}")
53
+
54
+ for name, child_module in module.named_children():
55
+ self._collect_params(
56
+ child_module,
57
+ ignored_modules,
58
+ ignored_params,
59
+ prefix=f"{recurse_prefix}{name}",
60
+ )
61
+
62
+ def lazy_init(self) -> None:
63
+ @torch._disable_dynamo(recursive=True)
64
+ def _lazy_init():
65
+ assert self._init_args is not None
66
+ self.init(*self._init_args, **self._init_kwargs)
67
+ self.register_comm_hook()
68
+ self._init_args = tuple()
69
+ self._init_kwargs = {}
70
+
71
+ _lazy_init()
72
+
73
+ def init(
74
+ self,
75
+ module: nn.Module,
76
+ ignored_modules: Set[nn.Module],
77
+ **kwargs,
78
+ ) -> None:
79
+ if self.has_initialized:
80
+ return
81
+
82
+ self.has_initialized = True
83
+
84
+ device_mesh = kwargs.get("device_mesh", None)
85
+ self.module = module
86
+ ignored_params = {p for m in ignored_modules for p in m.parameters()}
87
+ from torch.distributed.tensor.parallel.ddp import _localize_dtensor
88
+
89
+ _localize_dtensor(module)
90
+ self._collect_params(module, ignored_modules, ignored_params)
91
+
92
+ if "device_id" in kwargs:
93
+ # replicate() supports a small usability enhancement where
94
+ # user can pass in device_id as a Union[int, torch.device] even for
95
+ # CPU devices so users don't have to change code for CPU/GPU runs.
96
+ # We derive the right device_ids to feed into DDP to support this.
97
+ if kwargs["device_id"] is not None:
98
+ device_id = kwargs["device_id"]
99
+ # Convert to device_ids that DDP expects.
100
+ if isinstance(device_id, torch.device) and device_id.type == "cpu":
101
+ # CPU modules receive device_ids None
102
+ kwargs["device_ids"] = None
103
+ else:
104
+ # GPU modules expect device_ids=[cuda_device]
105
+ kwargs["device_ids"] = [device_id]
106
+ else:
107
+ kwargs["device_ids"] = None
108
+ kwargs.pop("device_id")
109
+
110
+ self._ddp = DistributedDataParallel(self._param_list, **kwargs)
111
+ # Weakref to the DDP instance is currently only used for testing.
112
+ replicate.state(self.module)._ddp_weakref = weakref.ref(self._ddp)
113
+
114
+ def register_comm_hook(self) -> None:
115
+ for comm_args, comm_kwargs in self._comm_hook_args:
116
+ self._ddp.register_comm_hook(*comm_args, **comm_kwargs)
117
+ self._comm_hook_args.clear()
118
+
119
+ def record_init_args(self, *args, **kwargs) -> None:
120
+ self._init_args = args
121
+ self._init_kwargs = kwargs
122
+
123
+ def forward_pre_hook(
124
+ self, module: nn.Module, args: Tuple[Any, ...], kwargs: Dict[str, Any]
125
+ ) -> Any:
126
+ if self._init_args or self._init_kwargs:
127
+ self.lazy_init()
128
+ self._ddp.require_backward_grad_sync = not self._no_sync
129
+ return self._ddp._pre_forward(*args, **kwargs)
130
+
131
+ def forward_post_hook(
132
+ self,
133
+ module: nn.Module,
134
+ input: Tuple[torch.Tensor],
135
+ output: torch.Tensor,
136
+ ) -> torch.Tensor:
137
+ return self._ddp._post_forward(output)
138
+
139
+
140
+ def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
141
+ raise AssertionError(
142
+ "DDP does not support deepcopy. Please use state dict for serialization."
143
+ )
144
+
145
+
146
+ # Follow the same pattern as FSDP/fully_shard
147
+ class DDP:
148
+ def __new__(cls, *args, **kwargs):
149
+ """
150
+ Override ``__new__`` to remove the DDP class and directly construct
151
+ the original class for cases like indexing into a container module.
152
+ """
153
+ # Use index 2 since 0 is the dynamically constructed `DDP<...>` class
154
+ # and index 1 is the `DDP` class itself
155
+ orig_cls = cls.__mro__[2]
156
+ return orig_cls.__new__(orig_cls, *args, **kwargs)
157
+
158
+ def set_requires_gradient_sync(self, requires_gradient_sync: bool) -> None:
159
+ """
160
+ Sets if the module should sync gradients. This can be used to implement
161
+ gradient accumulation without communication.
162
+
163
+ Args:
164
+ requires_gradient_sync (bool): Whether to reduce gradients for the
165
+ module's parameters.
166
+ """
167
+ replicate.state(self)._no_sync = not requires_gradient_sync
168
+
169
+ def register_comm_hook(self, *args, **kwargs) -> None:
170
+ replicate.state(self)._comm_hook_args.append((args, kwargs))
171
+
172
+
173
+ @contract(state_cls=_ReplicateState)
174
+ def replicate(
175
+ module: nn.Module,
176
+ ignored_modules: Optional[Iterable[torch.nn.Module]] = None,
177
+ **kwargs,
178
+ ) -> nn.Module:
179
+ r"""Replicates a module
180
+
181
+ Args:
182
+ module (torch.nn.Module): module to replicate
183
+
184
+ Example::
185
+ >>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
186
+ >>> module = nn.Linear(3, 3)
187
+ >>> replicate(module)
188
+ """
189
+ torch._C._log_api_usage_once("torch.distributed.replicate")
190
+
191
+ # TODO(fegin): using kwargs is not a good idea if we would like to make
192
+ # replicate a formal API to replace DDP.
193
+ if "device_id" in kwargs:
194
+ if not isinstance(kwargs["device_id"], (int, torch.device)):
195
+ raise RuntimeError(
196
+ "Expected device_id to be int or torch.device, "
197
+ f"but got {type(kwargs['device_id'])}"
198
+ )
199
+
200
+ if _is_fully_sharded(module):
201
+ raise RuntimeError(
202
+ "Cannot apply `replicate()` on a Module already managed by `fully_shard`"
203
+ )
204
+
205
+ if ignored_modules is None:
206
+ ignored_modules = {}
207
+ else:
208
+ ignored_modules = set(ignored_modules)
209
+
210
+ state = cast(_ReplicateState, replicate.state(module))
211
+ module.register_forward_pre_hook(state.forward_pre_hook, with_kwargs=True)
212
+ device_mesh = kwargs.get("device_mesh", None)
213
+ if device_mesh is not None:
214
+ from torch.distributed.device_mesh import _mesh_resources
215
+
216
+ if _mesh_resources.get_parent_mesh(device_mesh) is not None:
217
+ # TODO: This is a temporary work around to enable DDP + TP.
218
+ # We should do the logic in DDP so that the 2D implementation is
219
+ # sound and the state_dict works out of the box.
220
+ #
221
+ # This won't conflict with what is done in DDP class as the module
222
+ # replicate is going to pass is NOT the original module.
223
+ from torch.distributed.tensor.parallel.ddp import (
224
+ _localize_dtensor,
225
+ _reconstruct_dtensor,
226
+ )
227
+
228
+ module.register_forward_pre_hook(_reconstruct_dtensor)
229
+ module.register_forward_hook(_localize_dtensor)
230
+
231
+ module.register_forward_hook(state.forward_post_hook) # type: ignore[arg-type]
232
+
233
+ state.record_init_args(module, ignored_modules, **kwargs)
234
+
235
+ # Place DDP leftmost for highest priority in the method resolution order
236
+ cls = module.__class__
237
+ dct = {"__deepcopy__": unimplemented_deepcopy}
238
+ new_cls = type(f"DDP{cls.__name__}", (DDP, cls), dct)
239
+ module.__class__ = new_cls
240
+ return module
241
+
242
+
243
+ def _is_fully_sharded(module: nn.Module) -> bool:
244
+ r"""Check if module is marked with fully_shard."""
245
+ registry = _get_registry(module)
246
+ if registry is None:
247
+ return False
248
+ return "fully_shard" in registry
data/home/.local/lib/python3.8/site-packages/torch/distributed/_cuda_p2p/__init__.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections import defaultdict
3
+ from contextlib import contextmanager
4
+
5
+ from functools import partial
6
+ from typing import Callable, cast, Dict, List, Optional, Tuple, TYPE_CHECKING, Union
7
+
8
+ import torch
9
+ import torch.distributed._functional_collectives as funcol
10
+
11
+ import torch.distributed.distributed_c10d as c10d
12
+
13
+ if TYPE_CHECKING:
14
+ from torch._C._distributed_c10d import _DistributedBackendOptions, Backend
15
+
16
+
17
+ """
18
+ This file contains the registration logic and Python APIs for
19
+ ``ProcessGroupCudaP2P`` (experimental).
20
+
21
+ ``ProcessGroupCudaP2P`` is a thin wrapper around ``ProcessGroupNCCL``. By
22
+ default, it routes all collectives to the underlying ``ProcessGroupNCCL``. In
23
+ addition, ``ProcessGroupCudaP2P`` initializes a P2P workspace that allows
24
+ direct GPU memory access among the members. The workspace can be used in Python
25
+ to optimize intra-node communication patterns or to create custom intra-node
26
+ collectives in CUDA.
27
+
28
+ ``ProcessGroupCudaP2P`` aims to bridge the gap where certain important patterns
29
+ can be better optimized via fine-grained P2P memory access than with
30
+ collectives in the latest version of NCCL. It is meant to complement NCCL
31
+ rather than replacing it.
32
+
33
+ Usage:
34
+
35
+ # Using ProcessGroupCudaP2P
36
+ dist.init_process_group(backend="cuda_p2p", ...)
37
+
38
+ # Using ProcessGroupCudaP2P while specifying ProcessGroupCudaP2P.Options
39
+ pg_options = ProcessGroupCudaP2P.Options()
40
+ dist.init_process_group(backend="cuda_p2p", pg_options=pg_options, ...)
41
+
42
+ # Using ProcessGroupCudaP2P while specifying ProcessGroupNCCL.Options
43
+ pg_options = ProcessGroupNCCL.Options()
44
+ dist.init_process_group(backend="cuda_p2p", pg_options=pg_options, ...)
45
+
46
+ # Using ProcessGroupCudaP2P while specifying both
47
+ # ProcessGroupCudaP2P.Options and ProcessGroupNCCL.Options
48
+ pg_options = ProcessGroupCudaP2P.Options()
49
+ pg_options.nccl_options = ProcessGroupNCCL.Options()
50
+ dist.init_process_group(backend="cuda_p2p", pg_options=pg_options, ...)
51
+
52
+ # Down-casting the backend to access p2p buffers for cuda_p2p specific
53
+ # optimizations
54
+ if is_cuda_p2p_group(group):
55
+ backend = get_cuda_p2p_backend(group)
56
+ if required_p2p_buffer_size > backend.get_buffer_size():
57
+ # fallback
58
+ p2p_buffer = backend.get_p2p_buffer(...)
59
+ else:
60
+ # fallback
61
+ """
62
+
63
+
64
+ def _create_cuda_p2p_group(
65
+ dist_backend_opts: "_DistributedBackendOptions",
66
+ options: Union[
67
+ "c10d.ProcessGroupCudaP2P.Options", "c10d.ProcessGroupNCCL.Options", None
68
+ ],
69
+ ) -> "Backend":
70
+ if not c10d.is_nccl_available():
71
+ raise RuntimeError("The cuda_p2p backend is not available")
72
+ if options is None:
73
+ options = c10d.ProcessGroupCudaP2P.Options()
74
+ options.nccl_options = c10d.ProcessGroupNCCL.Options()
75
+ elif isinstance(options, c10d.ProcessGroupNCCL.Options):
76
+ nccl_options = options
77
+ options = c10d.ProcessGroupCudaP2P.Options()
78
+ options.nccl_options = nccl_options
79
+ elif isinstance(options, c10d.ProcessGroupCudaP2P.Options):
80
+ if options.nccl_options is None:
81
+ options.nccl_options = c10d.ProcessGroupNCCL.Options()
82
+ else:
83
+ raise TypeError(
84
+ "options for cuda_p2p must be ProcessGroupCudaP2P.Options "
85
+ f"or ProcessGroupNCCL.Options (got: {type(options)})"
86
+ )
87
+
88
+ return c10d.ProcessGroupCudaP2P(
89
+ dist_backend_opts.store,
90
+ dist_backend_opts.group_rank,
91
+ dist_backend_opts.group_size,
92
+ options,
93
+ )
94
+
95
+
96
+ def is_cuda_p2p_group(group: c10d.ProcessGroup) -> bool:
97
+ if _test_with_non_cuda_p2p_group:
98
+ return True
99
+ if not c10d.is_nccl_available():
100
+ return False
101
+ try:
102
+ backend = group._get_backend(torch.device("cuda"))
103
+ except Exception:
104
+ return False
105
+ return isinstance(backend, c10d.ProcessGroupCudaP2P) and backend.is_p2p_available()
106
+
107
+
108
+ def get_cuda_p2p_backend(group: c10d.ProcessGroup) -> "c10d.ProcessGroupCudaP2P":
109
+ if not is_cuda_p2p_group(group):
110
+ raise TypeError("group is not a cuda_p2p process group.")
111
+ return cast(
112
+ c10d.ProcessGroupCudaP2P,
113
+ group._get_backend(torch.device("cuda")),
114
+ )
115
+
116
+
117
+ def get_p2p_buffer_size(group: c10d.ProcessGroup) -> int:
118
+ if not is_cuda_p2p_group(group):
119
+ return 0
120
+ backend = get_cuda_p2p_backend(group)
121
+ return backend.get_buffer_size()
122
+
123
+
124
+ c10d.Backend.register_backend(
125
+ "cuda_p2p",
126
+ _create_cuda_p2p_group,
127
+ extended_api=True,
128
+ devices=["cuda"],
129
+ )
130
+
131
+
132
+ _test_with_non_cuda_p2p_group: bool = False
133
+
134
+
135
+ @contextmanager
136
+ def test_with_non_cuda_p2p_group():
137
+ """
138
+ Force ops in this file to work with non-cuda_p2p groups for testing
139
+ purposes. Not thread safe.
140
+ """
141
+ global _test_with_non_cuda_p2p_group
142
+ prev = _test_with_non_cuda_p2p_group
143
+ try:
144
+ _test_with_non_cuda_p2p_group = True
145
+ yield
146
+ finally:
147
+ _test_with_non_cuda_p2p_group = prev
148
+
149
+
150
+ _current_p2p_usage_counter: Optional[Dict[str, int]] = None
151
+
152
+
153
+ @contextmanager
154
+ def p2p_usage_counter():
155
+ """
156
+ Record the number of ops that utilized p2p capability for testing purposes.
157
+ Fallbacks are excluded.
158
+ """
159
+ global _current_p2p_usage_counter
160
+ prev = _current_p2p_usage_counter
161
+ try:
162
+ _current_p2p_usage_counter = defaultdict(int)
163
+ yield _current_p2p_usage_counter
164
+ finally:
165
+ _current_p2p_usage_counter = prev
166
+
167
+
168
+ def _pipelined_all_gather_and_consume(
169
+ shard: torch.Tensor,
170
+ shard_consumer: Callable[[torch.Tensor, int], None],
171
+ ag_out: torch.Tensor,
172
+ group: c10d.ProcessGroup,
173
+ ) -> None:
174
+ """
175
+ Perform the following logic with micro-pipelined computation and
176
+ communication:
177
+
178
+ tensor = all_gather_tensor(shard, gather_dim=1, group=group)
179
+ chunks = tensor.chunk(group.size())
180
+ for src_rank, chunk in enumerate(chunks):
181
+ shard_consumer(chunk, src_rank)
182
+
183
+ NOTE:
184
+ - The shard passed to shard consumer will always be contiguous.
185
+ """
186
+ p2p_buf_sz_req = shard.numel() * shard.element_size()
187
+ if get_p2p_buffer_size(group) < p2p_buf_sz_req:
188
+ # We preferred the caller to handle fallback so that the computation
189
+ # doesn't need to be decomposed.
190
+ raise RuntimeError(
191
+ f"_pipelined_all_gather_and_consume on input with shape={shard.shape} "
192
+ f"and dtype={shard.dtype} requires {p2p_buf_sz_req} bytes of p2p buffers "
193
+ f"(got {get_p2p_buffer_size(group)} bytes)."
194
+ )
195
+
196
+ backend = get_cuda_p2p_backend(group)
197
+ group_size = group.size()
198
+ rank = group.rank()
199
+
200
+ backend.stream().wait_stream(torch.cuda.current_stream())
201
+ local_p2p_buf = backend.get_p2p_buffer(rank, shard.shape, shard.dtype)
202
+
203
+ chunks = ag_out.chunk(group.size())
204
+
205
+ # While consuming local shard, copy it to the local p2p buffer
206
+ # in another stream.
207
+ shard_consumer(shard, rank)
208
+ chunks[rank].copy_(shard)
209
+
210
+ with torch.cuda.stream(backend.stream()):
211
+ local_p2p_buf.copy_(shard)
212
+ work = backend.intra_node_barrier()
213
+ work.wait()
214
+
215
+ # At this point, all ranks have copied their local shard to
216
+ # their local p2p buffer. Each rank can now copy and consume
217
+ # remote shards.
218
+ for i in range(1, group_size):
219
+ if i % 2 == 0:
220
+ stream = torch.cuda.current_stream()
221
+ else:
222
+ stream = backend.stream()
223
+ remote_rank = (i + rank) % group_size
224
+ remote_p2p_buf = backend.get_p2p_buffer(remote_rank, shard.shape, shard.dtype)
225
+ with torch.cuda.stream(stream):
226
+ chunks[remote_rank].copy_(remote_p2p_buf)
227
+ shard_consumer(chunks[remote_rank], remote_rank)
228
+
229
+ torch.cuda.current_stream().wait_stream(backend.stream())
230
+
231
+ with torch.cuda.stream(backend.stream()):
232
+ work = backend.intra_node_barrier()
233
+ work.wait()
234
+
235
+
236
+ def _pipelined_produce_and_all2all(
237
+ chunk_producer: Callable[[int, torch.Tensor], None],
238
+ output: torch.Tensor,
239
+ group: c10d.ProcessGroup,
240
+ ) -> None:
241
+ """
242
+ Perform the following logic with micro-pipelined computation and
243
+ communication:
244
+
245
+ chunks = [
246
+ chunk_producer(dst_rank, chunks[dst_rank])
247
+ for dst_rank in range(group.size()):
248
+ ]
249
+ dist.all_to_all_single(output=output, input=torch.cat(chunks))
250
+ """
251
+ group_size = group.size()
252
+ rank = group.rank()
253
+
254
+ out_chunks = output.chunk(group_size)
255
+ p2p_buf_sz_req = out_chunks[0].numel() * out_chunks[0].element_size() * 2
256
+ if get_p2p_buffer_size(group) < p2p_buf_sz_req:
257
+ # We preferred the caller to handle fallback so that the computation
258
+ # doesn't need to be decomposed.
259
+ raise RuntimeError(
260
+ f"_pipelined_produce_and_all2all on output with shape={output.shape} "
261
+ f"and dtype={output.dtype} requires {p2p_buf_sz_req} bytes of p2p buffers "
262
+ f"(got {get_p2p_buffer_size(group)} bytes)."
263
+ )
264
+
265
+ backend = get_cuda_p2p_backend(group)
266
+ backend.stream().wait_stream(torch.cuda.current_stream())
267
+
268
+ def get_p2p_buf(rank: int, idx: int) -> torch.Tensor:
269
+ assert idx in (0, 1)
270
+ offset = 0 if idx == 0 else out_chunks[0].numel()
271
+ return backend.get_p2p_buffer(
272
+ rank, out_chunks[0].shape, out_chunks[0].dtype, offset
273
+ )
274
+
275
+ # Prepare two local p2p buffers, so that a remote rank can pull the result
276
+ # of step [i] in one p2p buffer while the local rank can compute the
277
+ # result of step [i+1] and write it directly the other p2p buffer.
278
+ local_p2p_buf_0 = get_p2p_buf(rank, 0)
279
+ local_p2p_buf_1 = get_p2p_buf(rank, 1)
280
+
281
+ # Directly write the local result to the destination.
282
+ # No need to go through the p2p buffers.
283
+ chunk_producer(rank, out_chunks[rank])
284
+
285
+ with torch.cuda.stream(backend.stream()):
286
+ chunk_producer((rank + 1) % group_size, local_p2p_buf_0)
287
+ backend.intra_node_barrier()
288
+ remote_p2p_buf = get_p2p_buf((rank - 1) % group_size, 0)
289
+ out_chunks[(rank - 1) % group_size].copy_(remote_p2p_buf)
290
+
291
+ for step in range(2, group_size):
292
+ remote_rank = (rank - step) % group_size
293
+ if step % 2 == 0:
294
+ stream = torch.cuda.current_stream()
295
+ p2p_buf = local_p2p_buf_1
296
+ remote_p2p_buf = get_p2p_buf(remote_rank, 1)
297
+ else:
298
+ stream = backend.stream()
299
+ p2p_buf = local_p2p_buf_0
300
+ remote_p2p_buf = get_p2p_buf(remote_rank, 0)
301
+ with torch.cuda.stream(stream):
302
+ chunk_producer((rank + step) % group_size, p2p_buf)
303
+ backend.intra_node_barrier()
304
+ out_chunks[remote_rank].copy_(remote_p2p_buf)
305
+
306
+ torch.cuda.current_stream().wait_stream(backend.stream())
307
+ backend.intra_node_barrier()
308
+
309
+
310
+ lib = torch.library.Library("cuda_p2p", "DEF") # noqa: TOR901
311
+ lib.define(
312
+ "fused_all_gather_matmul(Tensor A, Tensor[] Bs, int gather_dim, str group_name) -> (Tensor, Tensor[])"
313
+ )
314
+ lib.define(
315
+ "fused_matmul_reduce_scatter(Tensor A, Tensor B, str reduce_op, int scatter_dim, str group_name) -> Tensor"
316
+ )
317
+
318
+
319
+ @torch.library.impl(lib, "fused_all_gather_matmul", "Meta")
320
+ def _fused_all_gather_matmul_fallback(
321
+ A_shard: torch.Tensor,
322
+ Bs: List[torch.Tensor],
323
+ gather_dim: int,
324
+ group_name: str,
325
+ ) -> Tuple[torch.Tensor, List[torch.Tensor]]:
326
+ group_size = c10d._get_group_size_by_name(group_name)
327
+ A = torch.ops._c10d_functional.all_gather_into_tensor(
328
+ A_shard.contiguous(), group_size, group_name
329
+ )
330
+ A = torch.ops._c10d_functional.wait_tensor(A)
331
+ A = A.view(group_size, *A_shard.shape).movedim(gather_dim + 1, 1).flatten(0, 1)
332
+ return A.movedim(0, gather_dim), [
333
+ torch.matmul(A, B).movedim(0, gather_dim) for B in Bs
334
+ ]
335
+
336
+
337
+ @torch.library.impl(lib, "fused_all_gather_matmul", "CUDA")
338
+ def _fused_all_gather_matmul(
339
+ A_shard: torch.Tensor,
340
+ Bs: List[torch.Tensor],
341
+ gather_dim: int,
342
+ group_name: str,
343
+ ) -> Tuple[torch.Tensor, List[torch.Tensor]]:
344
+ """
345
+ Perform the following logic with micro-pipelined computation and
346
+ communication:
347
+
348
+ all_gather_tensor(A_shard, gather_dim, group_name) @ B
349
+ """
350
+ if A_shard.dim() < 2:
351
+ raise ValueError("A_shard must be a matrix")
352
+ for B in Bs:
353
+ if B.dim() != 2:
354
+ raise ValueError("B must be a matrix")
355
+ if gather_dim < 0 or gather_dim >= A_shard.dim():
356
+ raise ValueError("Invalid gather_dim")
357
+
358
+ group = c10d._resolve_process_group(group_name)
359
+ p2p_buf_sz_req = A_shard.numel() * A_shard.element_size()
360
+ if (
361
+ _test_with_non_cuda_p2p_group
362
+ or get_p2p_buffer_size(group) < p2p_buf_sz_req
363
+ # Pipelining a mamtul with split-k is not supported
364
+ or gather_dim == len(A_shard.shape) - 1
365
+ ):
366
+ return _fused_all_gather_matmul_fallback(A_shard, Bs, gather_dim, group_name)
367
+
368
+ if _current_p2p_usage_counter is not None:
369
+ _current_p2p_usage_counter["fused_all_gather_matmul"] += 1
370
+
371
+ # Move the gather_dim to the front and flatten the tensor into a 2D matrix.
372
+ # The flattened tensor doesn't need to be contiguous (for computation
373
+ # efficiency), as _pipelined_all_gather_and_consume guarantees that shards
374
+ # passed to shard_consumer are contiguous.
375
+ x = A_shard.movedim(gather_dim, 0)
376
+ leading_dims = [group.size()] + list(x.shape[:-1])
377
+ x = x.flatten(0, -2)
378
+
379
+ # Helper function for reverting the above transformation
380
+ def unflatten(t):
381
+ return t.view(*leading_dims, -1).flatten(0, 1).movedim(0, gather_dim)
382
+
383
+ ag_out = x.new_empty(
384
+ x.shape[0] * group.size(),
385
+ x.shape[1],
386
+ )
387
+ outputs = [
388
+ x.new_empty(
389
+ x.shape[0] * group.size(),
390
+ B.shape[1],
391
+ )
392
+ for B in Bs
393
+ ]
394
+ output_shards = [output.chunk(group.size()) for output in outputs]
395
+
396
+ # Computing block-wise matmul along the first dim of A
397
+ def shard_consumer(shard: torch.Tensor, rank: int) -> None:
398
+ for idx, B in enumerate(Bs):
399
+ torch.mm(shard, B, out=output_shards[idx][rank])
400
+
401
+ _pipelined_all_gather_and_consume(
402
+ x,
403
+ shard_consumer,
404
+ ag_out,
405
+ group,
406
+ )
407
+ return unflatten(ag_out), [unflatten(output) for output in outputs]
408
+
409
+
410
+ @torch.library.impl(lib, "fused_matmul_reduce_scatter", "Meta")
411
+ def _fused_matmul_reduce_scatter_fallback(
412
+ A: torch.Tensor,
413
+ B: torch.Tensor,
414
+ reduce_op: str,
415
+ scatter_dim: int,
416
+ group_name: str,
417
+ ) -> torch.Tensor:
418
+ res = funcol.reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
419
+ res = funcol.wait_tensor(res)
420
+ return res
421
+
422
+
423
+ @torch.library.impl(lib, "fused_matmul_reduce_scatter", "CUDA")
424
+ def _fused_matmul_reduce_scatter(
425
+ A: torch.Tensor,
426
+ B: torch.Tensor,
427
+ reduce_op: str,
428
+ scatter_dim: int,
429
+ group_name: str,
430
+ ) -> torch.Tensor:
431
+ """
432
+ Perform the following logic with micro-pipelined computation and
433
+ communication:
434
+
435
+ reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
436
+
437
+ NOTE:
438
+ - The K dim across ranks are currently accumulated with bf16 with results
439
+ in accuracy loss.
440
+ """
441
+ if A.dim() < 2:
442
+ raise ValueError("A_shard must be a matrix")
443
+ if scatter_dim < 0 or scatter_dim >= A.dim():
444
+ raise ValueError("Invalid gather_dim")
445
+ if B.dim() != 2:
446
+ raise ValueError("B must be a matrix")
447
+ if reduce_op == "sum":
448
+ reduce_fn = partial(torch.sum, dim=0)
449
+ elif reduce_op == "avg":
450
+ reduce_fn = partial(torch.mean, dim=0)
451
+ else:
452
+ raise ValueError("reduce_op must be sum or avg")
453
+
454
+ group = c10d._resolve_process_group(group_name)
455
+ out_shape = [*A.shape[:-1], B.shape[1]]
456
+ out_shape[scatter_dim] //= group.size()
457
+ p2p_buf_sz_req = torch.Size(out_shape).numel() * A.element_size() * 2
458
+ if _test_with_non_cuda_p2p_group or get_p2p_buffer_size(group) < p2p_buf_sz_req:
459
+ return _fused_matmul_reduce_scatter_fallback(
460
+ A, B, reduce_op, scatter_dim, group_name
461
+ )
462
+
463
+ if _current_p2p_usage_counter is not None:
464
+ _current_p2p_usage_counter["fused_matmul_reduce_scatter"] += 1
465
+
466
+ # Move the gather_dim to the front and flatten the tensor into a 2D matrix
467
+ x = A.movedim(scatter_dim, 0)
468
+ leading_dims = [group.size()] + list(x.shape[:-1])
469
+ leading_dims[1] //= group.size()
470
+ x = x.flatten(0, -2)
471
+ shards = x.chunk(group.size())
472
+
473
+ # Computing block-wise matmul along the first dim of A
474
+ def chunk_producer(rank: int, out: torch.Tensor) -> None:
475
+ torch.matmul(shards[rank], B, out=out)
476
+
477
+ stacked_partials = x.new_empty(x.shape[0], B.shape[1])
478
+
479
+ _pipelined_produce_and_all2all(
480
+ chunk_producer,
481
+ stacked_partials,
482
+ group,
483
+ )
484
+ # Ensures that the transpose and reduction produce contiguous result
485
+ # in a single reduction kernel.
486
+ return reduce_fn(
487
+ stacked_partials.view(*leading_dims, -1)
488
+ .movedim(1, scatter_dim + 1)
489
+ .movedim(0, scatter_dim),
490
+ dim=scatter_dim,
491
+ )
data/home/.local/lib/python3.8/site-packages/torch/distributed/_cuda_p2p/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (11.2 kB). View file
 
data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .api import (
2
+ _shard_tensor,
3
+ load_with_process_group,
4
+ shard_module,
5
+ shard_parameter,
6
+ )
data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/_utils.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.distributed._shard.metadata import ShardMetadata
3
+ from typing import Sequence
4
+
5
+ DEPRECATE_MSG = "Please use DTensor instead and we are deprecating ShardedTensor."
6
+
7
+ def narrow_tensor_by_index(tensor: torch.Tensor, offsets: Sequence[int], sizes: Sequence[int]) -> torch.Tensor:
8
+ """
9
+ Narrow the tensor according to ``offsets`` and ``sizes``.
10
+ """
11
+ narrowed_tensor = tensor
12
+ for idx, (offset, size) in enumerate(zip(offsets, sizes)):
13
+ if size < tensor.size(idx):
14
+ # Reshape to get shard for this rank and we don't want autograd
15
+ # recording here for the narrow op and 'local_shard' should be a
16
+ # leaf variable in the autograd graph.
17
+ narrowed_tensor = narrowed_tensor.narrow(
18
+ idx,
19
+ offset,
20
+ size
21
+ )
22
+ return narrowed_tensor
23
+
24
+ def narrow_tensor(tensor: torch.Tensor, metadata: ShardMetadata) -> torch.Tensor:
25
+ """
26
+ Narrow the tensor according to the metadata
27
+ """
28
+ return narrow_tensor_by_index(tensor, metadata.shard_offsets, metadata.shard_sizes)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/api.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from contextlib import contextmanager
3
+ from typing import Optional
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.nn as nn
7
+ from torch.distributed import distributed_c10d
8
+ from torch.distributed._shard.sharded_tensor import (
9
+ ShardedTensor,
10
+ )
11
+ from .sharding_spec import (
12
+ ShardingSpec,
13
+ ChunkShardingSpec
14
+ )
15
+ from .sharding_plan import (
16
+ ShardingPlan
17
+ )
18
+ from .sharder import Sharder
19
+
20
+ def _shard_tensor(
21
+ tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None
22
+ ) -> ShardedTensor:
23
+ """
24
+ Given a :class:`torch.Tensor`, it shards that tensor according to the provided
25
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
26
+ used as the ground truth of the data which would be scattered as shards
27
+ across the rest of the ranks.
28
+
29
+ Args:
30
+ tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
31
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
32
+ describing how to shard the Tensor.
33
+
34
+ Keyword args:
35
+ src_rank (int, optional): The source rank which is used as the ground truth of
36
+ the data for the parameter that would be sharded and scattered
37
+ across the rest of the ranks.
38
+ Default: 0.
39
+ process_group (ProcessGroup, optional): The process group to work on. If None,
40
+ the default process group will be used.
41
+
42
+ Returns:
43
+ A :class:`ShardedTensor` sharded from the given tensor.
44
+
45
+ .. warning::
46
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
47
+ currently supported as the ``sharding_spec``.
48
+ """
49
+ if not tensor.is_contiguous():
50
+ raise ValueError('input tensor is not a contiguous Tensor')
51
+
52
+ pg = process_group if process_group is not None else distributed_c10d._get_default_group()
53
+ world_size = dist.get_world_size(pg)
54
+ current_rank = dist.get_rank(pg)
55
+
56
+ # Validate src_rank and sharding_spec are same across all ranks.
57
+ gathered_list = [None] * world_size
58
+ dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg)
59
+
60
+ for idx, entry in enumerate(gathered_list):
61
+ if src_rank != entry[0]: # type: ignore[index]
62
+ raise ValueError(
63
+ f'src_rank={src_rank} on rank: {current_rank} does not ' # type: ignore[index]
64
+ f'match with src_rank={entry[0]} on rank: {idx}')
65
+ if sharding_spec != entry[1]: # type: ignore[index]
66
+ raise ValueError(
67
+ f'sharding_spec={sharding_spec} on rank: {current_rank} does not ' # type: ignore[index]
68
+ f'match with sharding_spec={entry[1]} on rank: {idx}')
69
+
70
+ st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg)
71
+
72
+ return st
73
+
74
+ def shard_parameter(
75
+ module: torch.nn.Module,
76
+ param_name: str,
77
+ sharding_spec: ShardingSpec,
78
+ src_rank=0,
79
+ process_group=None):
80
+ """
81
+ Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
82
+ module, it shards that parameter according to the provided
83
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
84
+ used as the ground truth of the data which would be scattered as shards
85
+ across the rest of the ranks.
86
+
87
+ This method replaces ``module.param_name`` with a
88
+ :class:`torch.distributed._sharded_tensor.ShardedTensor`
89
+
90
+ Args:
91
+ module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
92
+ param_name (str): Name of the parameter of ``module`` that needs to be sharded.
93
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
94
+ describing how to shard the Tensor.
95
+
96
+ Keyword args:
97
+ src_rank (int, optional): The source rank which is used as the ground truth of
98
+ the data for the parameter that would be sharded and scattered
99
+ across the rest of the ranks.
100
+ Default: 0.
101
+ process_group (ProcessGroup, optional): The process group to work on. If None,
102
+ the default process group will be used.
103
+
104
+ .. warning::
105
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
106
+ currently supported as the ``sharding_spec``.
107
+ """
108
+ # Perform some validation first.
109
+ if not hasattr(module, param_name):
110
+ raise AttributeError(f'{module._get_name()} has no attribute `{param_name}`')
111
+
112
+ tensor = getattr(module, param_name)
113
+ if not isinstance(tensor, torch.Tensor):
114
+ raise ValueError(f'Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}')
115
+
116
+ if not tensor.is_contiguous():
117
+ raise ValueError(f'param: {param_name} is not a contiguous Tensor')
118
+
119
+ st = _shard_tensor(tensor, sharding_spec, src_rank, process_group)
120
+
121
+ # Replace param with ShardedTensor.
122
+ module.register_parameter(param_name, nn.Parameter(st))
123
+
124
+ # Tracks the current process group in the load context manager.
125
+ _CURRENT_PROCESS_GROUP: Optional[dist.ProcessGroup] = None
126
+
127
+ @contextmanager
128
+ def load_with_process_group(process_group):
129
+ """
130
+ Context manager to set the process group with which to load a ShardedTensor.
131
+ """
132
+ global _CURRENT_PROCESS_GROUP
133
+ if _CURRENT_PROCESS_GROUP is not None:
134
+ raise RuntimeError(
135
+ 'ProcessGroup already set by previous "load_with_process_group" '
136
+ 'context manager')
137
+ _CURRENT_PROCESS_GROUP = process_group
138
+ try:
139
+ yield process_group
140
+ finally:
141
+ _CURRENT_PROCESS_GROUP = None
142
+
143
+ def _get_current_process_group():
144
+ """
145
+ Retrieves the current process group set by ``load_with_process_group``.
146
+ If not set, it just returns the default group.
147
+ """
148
+ global _CURRENT_PROCESS_GROUP
149
+ if _CURRENT_PROCESS_GROUP is None:
150
+ return distributed_c10d._get_default_group()
151
+ else:
152
+ return _CURRENT_PROCESS_GROUP
153
+
154
+ def _reshard_output(
155
+ module: torch.nn.Module,
156
+ resharding_spec: ShardingSpec) -> torch.nn.Module:
157
+ """
158
+ Hook a module with output resharding in the forward pass according
159
+ to the given ``resharding_spec``.
160
+
161
+ Args:
162
+ module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
163
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
164
+ The specification describing how the output of the module will be resharded.
165
+
166
+ Returns:
167
+ A :class:`torch.nn.Module` object with reshard API hooked.
168
+ """
169
+ def hook_func(_module, _input, output):
170
+ if isinstance(output, ShardedTensor):
171
+ return output.reshard(resharding_spec)
172
+ return output
173
+ module.register_forward_hook(hook_func)
174
+ return module
175
+
176
+ def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module:
177
+ """
178
+ Hook a module with local shards collection in the forward pass.
179
+
180
+ This API is typically used to convert a sharded representation back to data parallel
181
+ representation. In particular, it returns the local tensor for this Shard. If the
182
+ size along the sharding dimension for the local tensor is 1, this dimension is removed
183
+ from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
184
+ a local Tensor of size [16] across each rank and not [1, 16] across each rank.
185
+
186
+ Args:
187
+ module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
188
+ local tensor value needs to be returned.
189
+
190
+ Returns:
191
+ A :class:`torch.nn.Module` object with collection API hooked.
192
+ """
193
+
194
+ def hook_func(_module, _input, output):
195
+ if isinstance(output, ShardedTensor):
196
+ local_tensor = output.local_tensor()
197
+ # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec
198
+ sharding_spec = output._sharding_spec
199
+ if isinstance(sharding_spec, ChunkShardingSpec) \
200
+ and local_tensor.size(sharding_spec.dim) == 1: # type: ignore[attr-defined, arg-type]
201
+ local_tensor = local_tensor.squeeze(
202
+ output._sharding_spec.dim # type: ignore[attr-defined]
203
+ )
204
+ return local_tensor
205
+ module.register_forward_hook(hook_func)
206
+ return module
207
+
208
+ def shard_module(
209
+ module: nn.Module,
210
+ plan: ShardingPlan,
211
+ src_rank=0,
212
+ process_group=None
213
+ ):
214
+ """
215
+ Shards a given module according to the provided sharding `plan`. This method
216
+ first shards all the parameters according to the given sharding `plan`. Then if
217
+ `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
218
+ will tag the output of modules according `output_plan`, convert the module's
219
+ output back to data parallel according to `return_local_tensor`.
220
+
221
+ Needs to be called on all ranks in an SPMD fashion.
222
+
223
+ Args:
224
+ module (:class:`torch.nn.Module`): The module to apply sharding to
225
+ plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
226
+ The ShardingPlan which specified param name to ShardingSpec to apply to
227
+ each parameter.
228
+
229
+ Keyword args:
230
+ src_rank (int, optional): The source rank which is used as the ground truth of
231
+ the data for the module that would be sharded and scattered across the rest
232
+ of the ranks.
233
+ Default: 0.
234
+ process_group (ProcessGroup, optional): The process group to work on. If None,
235
+ the default process group will be used.
236
+ """
237
+ # record Sharder paths for sanity check on the plan to ensure items in the plan
238
+ # does not conflict with the submodule tree that the Sharder is working with
239
+ sharder_paths = []
240
+ for name, spec in plan.plan.items():
241
+ if isinstance(spec, Sharder):
242
+ sharder_paths.append(name)
243
+
244
+ # shard the parameter according to the ShardingPlan
245
+ for name, spec in plan.plan.items():
246
+ if isinstance(spec, ShardingSpec):
247
+ # if found a sharding spec, try to shard the parameter
248
+ module_path, _, param_name = name.rpartition(".")
249
+
250
+ for sharder_path in sharder_paths:
251
+ if module_path.startswith(sharder_path):
252
+ raise RuntimeError(f"ShardingPlan is in-valid, trying to shard a parameter: {name},"
253
+ f" but there's already a Sharder entry for module {sharder_path},"
254
+ f" parameter sharding should not conflict with the submodule tree"
255
+ f" that a Sharder is working with!")
256
+
257
+ mod = module.get_submodule(module_path)
258
+ shard_parameter(
259
+ mod,
260
+ param_name,
261
+ spec,
262
+ src_rank=src_rank,
263
+ process_group=process_group
264
+ )
265
+ elif isinstance(spec, Sharder):
266
+ parent_mod_path, _, mod_name = name.rpartition(".")
267
+ if name == "":
268
+ raise KeyError("Module path must not be empty for custom sharder!")
269
+ mod = module.get_submodule(name)
270
+ parent_mod = module.get_submodule(parent_mod_path)
271
+ sharded_mod = spec.shard(mod)
272
+ # swap this submodule with the sharded module
273
+ parent_mod.mod_name = sharded_mod
274
+ else:
275
+ raise TypeError(f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'")
276
+
277
+ # reshard output if there's an entry in `reshard_output` for this module
278
+ if plan.output_plan is not None:
279
+ for module_path, output_spec in plan.output_plan.items():
280
+ if isinstance(output_spec, ShardingSpec):
281
+ mod = module.get_submodule(module_path)
282
+ _reshard_output(mod, output_spec)
283
+ else:
284
+ raise TypeError(f"Only `ShardingSpec` is supported as output_plan for '{module_path}'")
285
+ # convert the output back to data parallel for the modules appears in
286
+ # `return_local_tensor` of the plan, we will call `_collect_local_shard`
287
+ # to collect the local tensor for output of modules
288
+ if plan.return_local_tensor is not None:
289
+ for module_path in plan.return_local_tensor:
290
+ mod = module.get_submodule(module_path)
291
+ _collect_local_shard(mod)
data/home/.local/lib/python3.8/site-packages/torch/distributed/_shard/common_op_utils.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch.utils import _pytree as pytree
4
+ from typing import Optional
5
+
6
+ def _basic_validation(op, args=(), kwargs=None):
7
+ """
8
+ Common validation across all ops go in here.
9
+ """
10
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
11
+
12
+ if len(args) == 0 and (kwargs is None or len(kwargs) == 0):
13
+ raise ValueError(f" No input for '{op.__name__}'!")
14
+
15
+ # Validate types
16
+ has_distributed_tensor = False
17
+
18
+ def is_distributed_tensor(e):
19
+ nonlocal has_distributed_tensor
20
+ if isinstance(e, ShardedTensor):
21
+ has_distributed_tensor = True
22
+
23
+ pytree.tree_map_(is_distributed_tensor, args)
24
+ pytree.tree_map_(is_distributed_tensor, kwargs)
25
+
26
+ if not has_distributed_tensor:
27
+ raise TypeError(
28
+ f"torch function '{op.__name__}', with args: {args} and "
29
+ f"kwargs: {kwargs} are called without any distributed tensor!"
30
+ )
31
+
32
+ # Validate all distributed tensors use the same PG.
33
+ cur_pg: Optional[torch.distributed.ProcessGroup] = None
34
+
35
+ def validate_pg(e):
36
+ nonlocal cur_pg
37
+ if isinstance(e, ShardedTensor):
38
+ if cur_pg is not None and e._process_group is not cur_pg:
39
+ raise RuntimeError(
40
+ 'All distributed tensors should use the '
41
+ 'same ProcessGroup if used together in an op.'
42
+ )
43
+ cur_pg = e._process_group
44
+
45
+ pytree.tree_map_(validate_pg, args)
46
+ pytree.tree_map_(validate_pg, kwargs)
47
+
48
+ def _register_default_op(op, decorator):
49
+ @decorator(op)
50
+ def tensor_default_op(types, args=(), kwargs=None, pg=None):
51
+ """
52
+ Handles ``__torch_function__`` dispatch for the default tensor ops that
53
+ behave the same as ``torch.Tensor`` such as ``torch.Tensor.shape`` or
54
+ ``torch.Tensor.dtype``. We simply lower to the real op call with
55
+ DisableTorchFunctionSubclass context like ``torch.Tensor.__torch_function__``
56
+ to avoid recursions.
57
+ """
58
+ if kwargs is None:
59
+ kwargs = {}
60
+
61
+ with torch._C.DisableTorchFunctionSubclass():
62
+ return op(*args, **kwargs)