jasonfan commited on
Commit
0a0db4a
·
verified ·
1 Parent(s): f08da31

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. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py +128 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/utils.py +285 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/__init__.py +54 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/api.py +281 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/debug_info_logging.py +24 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py +444 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/local_timer.py +128 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/__init__.py +9 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/api.py +62 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/__init__.py +10 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py +57 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py +93 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/distributed.py +183 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/log_level.py +14 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/logging.py +69 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/store.py +225 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/__init__.py +0 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/__init__.py +0 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/builder.py +457 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/config_manager.py +110 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/fr_logger.py +54 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/loader.py +98 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/types.py +661 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/utils.py +789 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/fr_trace.py +67 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/__init__.py +69 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_common_utils.py +550 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_debug_utils.py +159 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_dynamo_utils.py +43 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_exec_order_utils.py +366 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_flat_param.py +0 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fsdp_extensions.py +180 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/__init__.py +20 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_api.py +155 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py +762 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_common.py +181 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_init.py +243 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_param.py +966 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py +901 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_state.py +408 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fully_shard.py +746 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_init_utils.py +1206 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_limiter_utils.py +33 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_optim_utils.py +2139 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_runtime_utils.py +1654 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_shard_utils.py +140 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_state_dict_utils.py +932 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_trace_utils.py +240 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_traversal_utils.py +112 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_unshard_param_utils.py +340 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+ import datetime
11
+ import logging
12
+ from typing import cast
13
+
14
+ from torch.distributed import PrefixStore, Store, TCPStore
15
+ from torch.distributed.elastic.rendezvous import (
16
+ RendezvousHandler,
17
+ RendezvousInfo,
18
+ RendezvousParameters,
19
+ RendezvousStoreInfo,
20
+ )
21
+ from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint
22
+
23
+
24
+ __all__ = ["StaticTCPRendezvous", "create_rdzv_handler"]
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _default_timeout_seconds = 600
29
+
30
+
31
+ class StaticTCPRendezvous(RendezvousHandler):
32
+ """
33
+ Static rendezvous that is a wrapper around the TCPStore.
34
+
35
+ Creates TCPStore based on the input parameters with the
36
+ listener on the agent with group_rank=0
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ master_addr: str,
42
+ master_port: int,
43
+ rank: int,
44
+ world_size: int,
45
+ run_id: str,
46
+ timeout: int,
47
+ ):
48
+ self.master_addr = master_addr
49
+ self.master_port = master_port
50
+ self.rank = rank
51
+ self.world_size = world_size
52
+ self.run_id = run_id
53
+ self.timeout = datetime.timedelta(seconds=timeout)
54
+ self._store: Store | None = None
55
+
56
+ def get_backend(self) -> str:
57
+ return "static"
58
+
59
+ @property
60
+ def use_agent_store(self) -> bool:
61
+ return True
62
+
63
+ def next_rendezvous(self) -> RendezvousInfo:
64
+ logger.info("Creating TCPStore as the c10d::Store implementation")
65
+ is_master = self.rank == 0
66
+ if not self._store:
67
+ self._store = TCPStore( # type: ignore[call-arg]
68
+ self.master_addr,
69
+ self.master_port,
70
+ self.world_size,
71
+ is_master,
72
+ self.timeout,
73
+ multi_tenant=True,
74
+ )
75
+ store = PrefixStore(self.run_id, self._store)
76
+ # TCPStore server instance is used by trainer code
77
+ bootstrap_store_info = RendezvousStoreInfo(self.master_addr, self.master_port)
78
+ return RendezvousInfo(
79
+ store,
80
+ self.rank,
81
+ self.world_size,
82
+ bootstrap_store_info,
83
+ )
84
+
85
+ def is_closed(self):
86
+ return False
87
+
88
+ def set_closed(self):
89
+ pass
90
+
91
+ def num_nodes_waiting(self):
92
+ return 0
93
+
94
+ def get_run_id(self) -> str:
95
+ return self.run_id
96
+
97
+ def shutdown(self) -> bool:
98
+ return True
99
+
100
+
101
+ def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler:
102
+ if "rank" not in params.config:
103
+ raise ValueError(
104
+ "rank is absent in RendezvousParameters."
105
+ "Try add --node-rank to the cmd request"
106
+ )
107
+ endpoint = params.endpoint.strip()
108
+ if not endpoint:
109
+ raise ValueError(
110
+ "endpoint is absent in RendezvousParameters"
111
+ "Try add --master-port and --master-addr to the cmd request"
112
+ )
113
+ master_addr, master_port = parse_rendezvous_endpoint(endpoint, -1)
114
+ if master_port == -1:
115
+ raise ValueError(
116
+ f"Port is absent in endpoint: {endpoint}. Try launching with --master-port"
117
+ )
118
+ world_size = params.max_nodes
119
+ rank = cast(int, params.config.get("rank"))
120
+ run_id = params.run_id
121
+ if "timeout" in params.config:
122
+ timeout = int(params.config["timeout"])
123
+ else:
124
+ timeout = _default_timeout_seconds
125
+
126
+ return StaticTCPRendezvous(
127
+ master_addr, master_port, rank, world_size, run_id, timeout
128
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/utils.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import ipaddress
9
+ import random
10
+ import re
11
+ import socket
12
+ import time
13
+ import weakref
14
+ from collections.abc import Callable
15
+ from datetime import timedelta
16
+ from threading import Event, Thread
17
+ from typing import Any
18
+
19
+
20
+ __all__ = ["parse_rendezvous_endpoint"]
21
+
22
+
23
+ def _parse_rendezvous_config(config_str: str) -> dict[str, str]:
24
+ """Extract key-value pairs from a rendezvous configuration string.
25
+
26
+ Args:
27
+ config_str:
28
+ A string in format <key1>=<value1>,...,<keyN>=<valueN>.
29
+ """
30
+ config: dict[str, str] = {}
31
+
32
+ config_str = config_str.strip()
33
+ if not config_str:
34
+ return config
35
+
36
+ key_values = config_str.split(",")
37
+ for kv in key_values:
38
+ key, *values = kv.split("=", 1)
39
+
40
+ key = key.strip()
41
+ if not key:
42
+ raise ValueError(
43
+ "The rendezvous configuration string must be in format "
44
+ "<key1>=<value1>,...,<keyN>=<valueN>."
45
+ )
46
+
47
+ value: str | None
48
+ if values:
49
+ value = values[0].strip()
50
+ else:
51
+ value = None
52
+ if not value:
53
+ raise ValueError(
54
+ f"The rendezvous configuration option '{key}' must have a value specified."
55
+ )
56
+
57
+ config[key] = value
58
+ return config
59
+
60
+
61
+ def _try_parse_port(port_str: str) -> int | None:
62
+ """Try to extract the port number from ``port_str``."""
63
+ if port_str and re.match(r"^[0-9]{1,5}$", port_str):
64
+ return int(port_str)
65
+ return None
66
+
67
+
68
+ def parse_rendezvous_endpoint(
69
+ endpoint: str | None, default_port: int
70
+ ) -> tuple[str, int]:
71
+ """Extract the hostname and the port number from a rendezvous endpoint.
72
+
73
+ Args:
74
+ endpoint:
75
+ A string in format <hostname>[:<port>].
76
+ default_port:
77
+ The port number to use if the endpoint does not include one.
78
+
79
+ Returns:
80
+ A tuple of hostname and port number.
81
+ """
82
+ if endpoint is not None:
83
+ endpoint = endpoint.strip()
84
+
85
+ if not endpoint:
86
+ return ("localhost", default_port)
87
+
88
+ # An endpoint that starts and ends with brackets represents an IPv6 address.
89
+ if endpoint[0] == "[" and endpoint[-1] == "]":
90
+ host, *rest = endpoint, *[]
91
+ else:
92
+ host, *rest = endpoint.rsplit(":", 1)
93
+
94
+ # Sanitize the IPv6 address.
95
+ if len(host) > 1 and host[0] == "[" and host[-1] == "]":
96
+ host = host[1:-1]
97
+
98
+ if len(rest) == 1:
99
+ port = _try_parse_port(rest[0])
100
+ if port is None or port >= 2**16:
101
+ raise ValueError(
102
+ f"The port number of the rendezvous endpoint '{endpoint}' must be an integer "
103
+ "between 0 and 65536."
104
+ )
105
+ else:
106
+ port = default_port
107
+
108
+ if not re.match(r"^[\w\.:-]+$", host):
109
+ raise ValueError(
110
+ f"The hostname of the rendezvous endpoint '{endpoint}' must be a dot-separated list of "
111
+ "labels, an IPv4 address, or an IPv6 address."
112
+ )
113
+
114
+ return host, port
115
+
116
+
117
+ def _matches_machine_hostname(host: str) -> bool:
118
+ """Indicate whether ``host`` matches the hostname of this machine.
119
+
120
+ This function compares ``host`` to the hostname as well as to the IP
121
+ addresses of this machine. Note that it may return a false negative if this
122
+ machine has CNAME records beyond its FQDN or IP addresses assigned to
123
+ secondary NICs.
124
+ """
125
+ if host == "localhost":
126
+ return True
127
+
128
+ try:
129
+ addr = ipaddress.ip_address(host)
130
+ except ValueError:
131
+ addr = None
132
+
133
+ if addr and addr.is_loopback:
134
+ return True
135
+
136
+ try:
137
+ host_addr_list = socket.getaddrinfo(
138
+ host, None, proto=socket.IPPROTO_TCP, flags=socket.AI_CANONNAME
139
+ )
140
+ except (ValueError, socket.gaierror) as _:
141
+ host_addr_list = []
142
+
143
+ host_ip_list = [host_addr_info[4][0] for host_addr_info in host_addr_list]
144
+
145
+ this_host = socket.gethostname()
146
+ if host == this_host:
147
+ return True
148
+
149
+ addr_list = socket.getaddrinfo(
150
+ this_host, None, proto=socket.IPPROTO_TCP, flags=socket.AI_CANONNAME
151
+ )
152
+ for addr_info in addr_list:
153
+ # If we have an FQDN in the addr_info, compare it to `host`.
154
+ if addr_info[3] and addr_info[3] == host:
155
+ return True
156
+
157
+ # Otherwise if `host` represents an IP address, compare it to our IP
158
+ # address.
159
+ if addr and addr_info[4][0] == str(addr):
160
+ return True
161
+
162
+ # If the IP address matches one of the provided host's IP addresses
163
+ if addr_info[4][0] in host_ip_list:
164
+ return True
165
+
166
+ return False
167
+
168
+
169
+ def _delay(seconds: float | tuple[float, float]) -> None:
170
+ """Suspend the current thread for ``seconds``.
171
+
172
+ Args:
173
+ seconds:
174
+ Either the delay, in seconds, or a tuple of a lower and an upper
175
+ bound within which a random delay will be picked.
176
+ """
177
+ if isinstance(seconds, tuple):
178
+ seconds = random.uniform(*seconds)
179
+ # Ignore delay requests that are less than 10 milliseconds.
180
+ if seconds >= 0.01:
181
+ time.sleep(seconds)
182
+
183
+
184
+ class _PeriodicTimer:
185
+ """Represent a timer that periodically runs a specified function.
186
+
187
+ Args:
188
+ interval:
189
+ The interval, in seconds, between each run.
190
+ function:
191
+ The function to run.
192
+ """
193
+
194
+ # The state of the timer is hold in a separate context object to avoid a
195
+ # reference cycle between the timer and the background thread.
196
+ class _Context:
197
+ interval: float
198
+ function: Callable[..., None]
199
+ args: tuple[Any, ...]
200
+ kwargs: dict[str, Any]
201
+ stop_event: Event
202
+
203
+ _name: str | None
204
+ _thread: Thread | None
205
+ _finalizer: weakref.finalize | None
206
+
207
+ # The context that is shared between the timer and the background thread.
208
+ _ctx: _Context
209
+
210
+ def __init__(
211
+ self,
212
+ interval: timedelta,
213
+ function: Callable[..., None],
214
+ *args: Any,
215
+ **kwargs: Any,
216
+ ) -> None:
217
+ self._name = None
218
+
219
+ self._ctx = self._Context()
220
+ self._ctx.interval = interval.total_seconds()
221
+ self._ctx.function = function # type: ignore[assignment]
222
+ self._ctx.args = args or ()
223
+ self._ctx.kwargs = kwargs or {}
224
+ self._ctx.stop_event = Event()
225
+
226
+ self._thread = None
227
+ self._finalizer = None
228
+
229
+ @property
230
+ def name(self) -> str | None:
231
+ """Get the name of the timer."""
232
+ return self._name
233
+
234
+ def set_name(self, name: str) -> None:
235
+ """Set the name of the timer.
236
+
237
+ The specified name will be assigned to the background thread and serves
238
+ for debugging and troubleshooting purposes.
239
+ """
240
+ if self._thread:
241
+ raise RuntimeError("The timer has already started.")
242
+
243
+ self._name = name
244
+
245
+ def start(self) -> None:
246
+ """Start the timer."""
247
+ if self._thread:
248
+ raise RuntimeError("The timer has already started.")
249
+
250
+ self._thread = Thread(
251
+ target=self._run,
252
+ name=self._name or "PeriodicTimer",
253
+ args=(self._ctx,),
254
+ daemon=True,
255
+ )
256
+
257
+ # We avoid using a regular finalizer (a.k.a. __del__) for stopping the
258
+ # timer as joining a daemon thread during the interpreter shutdown can
259
+ # cause deadlocks. The weakref.finalize is a superior alternative that
260
+ # provides a consistent behavior regardless of the GC implementation.
261
+ self._finalizer = weakref.finalize(
262
+ self, self._stop_thread, self._thread, self._ctx.stop_event
263
+ )
264
+
265
+ # We do not attempt to stop our background thread during the interpreter
266
+ # shutdown. At that point we do not even know whether it still exists.
267
+ self._finalizer.atexit = False
268
+
269
+ self._thread.start()
270
+
271
+ def cancel(self) -> None:
272
+ """Stop the timer at the next opportunity."""
273
+ if self._finalizer:
274
+ self._finalizer()
275
+
276
+ @staticmethod
277
+ def _run(ctx) -> None:
278
+ while not ctx.stop_event.wait(ctx.interval):
279
+ ctx.function(*ctx.args, **ctx.kwargs)
280
+
281
+ @staticmethod
282
+ def _stop_thread(thread, stop_event):
283
+ stop_event.set()
284
+
285
+ thread.join()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Expiration timers are set up on the same process as the agent and
9
+ used from your script to deal with stuck workers. When you go into
10
+ a code-block that has the potential to get stuck you can acquire
11
+ an expiration timer, which instructs the timer server to kill the
12
+ process if it does not release the timer by the self-imposed expiration
13
+ deadline.
14
+
15
+ Usage::
16
+
17
+ import torchelastic.timer as timer
18
+ import torchelastic.agent.server as agent
19
+
20
+ def main():
21
+ start_method = "spawn"
22
+ message_queue = mp.get_context(start_method).Queue()
23
+ server = timer.LocalTimerServer(message, max_interval=0.01)
24
+ server.start() # non-blocking
25
+
26
+ spec = WorkerSpec(
27
+ fn=trainer_func,
28
+ args=(message_queue,),
29
+ ...<OTHER_PARAMS...>)
30
+ agent = agent.LocalElasticAgent(spec, start_method)
31
+ agent.run()
32
+
33
+ def trainer_func(message_queue):
34
+ timer.configure(timer.LocalTimerClient(message_queue))
35
+ with timer.expires(after=60): # 60 second expiry
36
+ # do some work
37
+
38
+ In the example above if ``trainer_func`` takes more than 60 seconds to
39
+ complete, then the worker process is killed and the agent retries the worker group.
40
+ """
41
+
42
+ from .api import ( # noqa: F401
43
+ configure,
44
+ expires,
45
+ TimerClient,
46
+ TimerRequest,
47
+ TimerServer,
48
+ )
49
+ from .file_based_local_timer import ( # noqa: F401
50
+ FileTimerClient,
51
+ FileTimerRequest,
52
+ FileTimerServer,
53
+ )
54
+ from .local_timer import LocalTimerClient, LocalTimerServer # noqa: F401
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/api.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+ import abc
8
+ import logging
9
+ import threading
10
+ import time
11
+ from contextlib import contextmanager
12
+ from inspect import getframeinfo, stack
13
+ from typing import Any
14
+
15
+
16
+ __all__ = [
17
+ "TimerRequest",
18
+ "TimerClient",
19
+ "RequestQueue",
20
+ "TimerServer",
21
+ "configure",
22
+ "expires",
23
+ ]
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class TimerRequest:
29
+ """
30
+ Data object representing a countdown timer acquisition and release
31
+ that is used between the ``TimerClient`` and ``TimerServer``.
32
+ A negative ``expiration_time`` should be interpreted as a "release"
33
+ request.
34
+
35
+ .. note:: the type of ``worker_id`` is implementation specific.
36
+ It is whatever the TimerServer and TimerClient implementations
37
+ have on to uniquely identify a worker.
38
+ """
39
+
40
+ __slots__ = ["worker_id", "scope_id", "expiration_time"]
41
+
42
+ def __init__(self, worker_id: Any, scope_id: str, expiration_time: float):
43
+ self.worker_id = worker_id
44
+ self.scope_id = scope_id
45
+ self.expiration_time = expiration_time
46
+
47
+ def __eq__(self, other):
48
+ if isinstance(other, TimerRequest):
49
+ return (
50
+ self.worker_id == other.worker_id
51
+ and self.scope_id == other.scope_id
52
+ and self.expiration_time == other.expiration_time
53
+ )
54
+ return False
55
+
56
+
57
+ class TimerClient(abc.ABC):
58
+ """
59
+ Client library to acquire and release countdown timers by communicating
60
+ with the TimerServer.
61
+ """
62
+
63
+ @abc.abstractmethod
64
+ def acquire(self, scope_id: str, expiration_time: float) -> None:
65
+ """
66
+ Acquires a timer for the worker that holds this client object
67
+ given the scope_id and expiration_time. Typically registers
68
+ the timer with the TimerServer.
69
+ """
70
+
71
+ @abc.abstractmethod
72
+ def release(self, scope_id: str):
73
+ """
74
+ Releases the timer for the ``scope_id`` on the worker this
75
+ client represents. After this method is
76
+ called, the countdown timer on the scope is no longer in effect.
77
+ """
78
+
79
+
80
+ class RequestQueue(abc.ABC):
81
+ """
82
+ Consumer queue holding timer acquisition/release requests
83
+ """
84
+
85
+ @abc.abstractmethod
86
+ def size(self) -> int:
87
+ """
88
+ Returns the size of the queue at the time this method is called.
89
+ Note that by the time ``get`` is called the size of the queue
90
+ may have increased. The size of the queue should not decrease
91
+ until the ``get`` method is called. That is, the following assertion
92
+ should hold:
93
+
94
+ size = q.size()
95
+ res = q.get(size, timeout=0)
96
+ assert size == len(res)
97
+
98
+ -- or --
99
+
100
+ size = q.size()
101
+ res = q.get(size * 2, timeout=1)
102
+ assert size <= len(res) <= size * 2
103
+ """
104
+
105
+ @abc.abstractmethod
106
+ def get(self, size: int, timeout: float) -> list[TimerRequest]:
107
+ """
108
+ Gets up to ``size`` number of timer requests in a blocking fashion
109
+ (no more than ``timeout`` seconds).
110
+ """
111
+
112
+
113
+ class TimerServer(abc.ABC):
114
+ """
115
+ Entity that monitors active timers and expires them
116
+ in a timely fashion. This server is responsible for
117
+ reaping workers that have expired timers.
118
+ """
119
+
120
+ def __init__(
121
+ self, request_queue: RequestQueue, max_interval: float, daemon: bool = True
122
+ ):
123
+ """
124
+ :param request_queue: Consumer ``RequestQueue``
125
+ :param max_interval: max time (in seconds) to wait
126
+ for an item in the request_queue
127
+ :param daemon: whether to run the watchdog thread as a daemon
128
+ """
129
+ super().__init__()
130
+ self._request_queue = request_queue
131
+ self._max_interval = max_interval
132
+ self._daemon = daemon
133
+ self._watchdog_thread: threading.Thread | None = None
134
+ self._stop_signaled = False
135
+
136
+ @abc.abstractmethod
137
+ def register_timers(self, timer_requests: list[TimerRequest]) -> None:
138
+ """
139
+ Processes the incoming timer requests and registers them with the server.
140
+ The timer request can either be a acquire-timer or release-timer request.
141
+ Timer requests with a negative expiration_time should be interpreted
142
+ as a release-timer request.
143
+ """
144
+
145
+ @abc.abstractmethod
146
+ def clear_timers(self, worker_ids: set[Any]) -> None:
147
+ """
148
+ Clears all timers for the given ``worker_ids``.
149
+ """
150
+
151
+ @abc.abstractmethod
152
+ def get_expired_timers(self, deadline: float) -> dict[str, list[TimerRequest]]:
153
+ """
154
+ Returns all expired timers for each worker_id. An expired timer
155
+ is a timer for which the expiration_time is less than or equal to
156
+ the provided deadline.
157
+ """
158
+
159
+ @abc.abstractmethod
160
+ def _reap_worker(self, worker_id: Any) -> bool:
161
+ """
162
+ Reaps the given worker. Returns True if the worker has been
163
+ successfully reaped, False otherwise. If any uncaught exception
164
+ is thrown from this method, the worker is considered reaped
165
+ and all associated timers will be removed.
166
+ """
167
+
168
+ def _reap_worker_no_throw(self, worker_id: Any) -> bool:
169
+ """
170
+ Wraps ``_reap_worker(worker_id)``, if an uncaught exception is
171
+ thrown, then it considers the worker as reaped.
172
+ """
173
+ try:
174
+ return self._reap_worker(worker_id)
175
+ except Exception:
176
+ logger.exception(
177
+ "Uncaught exception thrown from _reap_worker(), "
178
+ "check that the implementation correctly catches exceptions",
179
+ )
180
+ return True
181
+
182
+ def _watchdog_loop(self):
183
+ while not self._stop_signaled:
184
+ try:
185
+ self._run_watchdog()
186
+ except Exception:
187
+ logger.exception("Error running watchdog")
188
+
189
+ def _run_watchdog(self):
190
+ batch_size = max(1, self._request_queue.size())
191
+ timer_requests = self._request_queue.get(batch_size, self._max_interval)
192
+ self.register_timers(timer_requests)
193
+ now = time.time()
194
+ reaped_worker_ids = set()
195
+ for worker_id, expired_timers in self.get_expired_timers(now).items():
196
+ logger.info(
197
+ "Reaping worker_id=[%s]. Expired timers: %s",
198
+ worker_id,
199
+ self._get_scopes(expired_timers),
200
+ )
201
+ if self._reap_worker_no_throw(worker_id):
202
+ logger.info("Successfully reaped worker=[%s]", worker_id)
203
+ reaped_worker_ids.add(worker_id)
204
+ else:
205
+ logger.error(
206
+ "Error reaping worker=[%s]. Will retry on next watchdog.", worker_id
207
+ )
208
+ self.clear_timers(reaped_worker_ids)
209
+
210
+ def _get_scopes(self, timer_requests):
211
+ return [r.scope_id for r in timer_requests]
212
+
213
+ def start(self) -> None:
214
+ logger.info(
215
+ "Starting %s... max_interval=%s, daemon=%s",
216
+ type(self).__name__,
217
+ self._max_interval,
218
+ self._daemon,
219
+ )
220
+ self._watchdog_thread = threading.Thread(
221
+ target=self._watchdog_loop, daemon=self._daemon
222
+ )
223
+ logger.info("Starting watchdog thread...")
224
+ self._watchdog_thread.start()
225
+
226
+ def stop(self) -> None:
227
+ logger.info("Stopping %s", type(self).__name__)
228
+ self._stop_signaled = True
229
+ if self._watchdog_thread:
230
+ logger.info("Stopping watchdog thread...")
231
+ self._watchdog_thread.join(self._max_interval)
232
+ self._watchdog_thread = None
233
+ else:
234
+ logger.info("No watchdog thread running, doing nothing")
235
+
236
+
237
+ _timer_client: TimerClient | None = None
238
+
239
+
240
+ def configure(timer_client: TimerClient):
241
+ """
242
+ Configures a timer client. Must be called before using ``expires``.
243
+ """
244
+ global _timer_client
245
+ _timer_client = timer_client
246
+ logger.info("Timer client configured to: %s", type(_timer_client).__name__)
247
+
248
+
249
+ @contextmanager
250
+ def expires(after: float, scope: str | None = None, client: TimerClient | None = None):
251
+ """
252
+ Acquires a countdown timer that expires in ``after`` seconds from now,
253
+ unless the code-block that it wraps is finished within the timeframe.
254
+ When the timer expires, this worker is eligible to be reaped. The
255
+ exact meaning of "reaped" depends on the client implementation. In
256
+ most cases, reaping means to terminate the worker process.
257
+ Note that the worker is NOT guaranteed to be reaped at exactly
258
+ ``time.now() + after``, but rather the worker is "eligible" for being
259
+ reaped and the ``TimerServer`` that the client talks to will ultimately
260
+ make the decision when and how to reap the workers with expired timers.
261
+
262
+ Usage::
263
+
264
+ torch.distributed.elastic.timer.configure(LocalTimerClient())
265
+ with expires(after=10):
266
+ torch.distributed.all_reduce(...)
267
+ """
268
+ if client is None:
269
+ if _timer_client is None:
270
+ raise RuntimeError("Configure timer client before using countdown timers.")
271
+ client = _timer_client
272
+ if scope is None:
273
+ # grab the caller file + lineno
274
+ caller = getframeinfo(stack()[1][0])
275
+ scope = f"{caller.filename}#{caller.lineno}"
276
+ expiration = time.time() + after
277
+ client.acquire(scope, expiration)
278
+ try:
279
+ yield
280
+ finally:
281
+ client.release(scope)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/debug_info_logging.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+
11
+ from torch.distributed.elastic.utils.logging import get_logger
12
+
13
+
14
+ logger = get_logger(__name__)
15
+
16
+ __all__ = ["log_debug_info_for_expired_timers"]
17
+
18
+
19
+ def log_debug_info_for_expired_timers(
20
+ run_id: str,
21
+ expired_timers: dict[int, list[str]],
22
+ ):
23
+ if expired_timers:
24
+ logger.info("Timers expired for run:[%s] [%s].", run_id, expired_timers)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and its affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import io
9
+ import json
10
+ import os
11
+ import select
12
+ import signal
13
+ import sys
14
+ import threading
15
+ import time
16
+ from collections.abc import Callable
17
+ from typing import TypeVar
18
+ from typing_extensions import ParamSpec
19
+
20
+ from torch.distributed.elastic.timer.api import TimerClient, TimerRequest
21
+ from torch.distributed.elastic.timer.debug_info_logging import (
22
+ log_debug_info_for_expired_timers,
23
+ )
24
+ from torch.distributed.elastic.utils.logging import get_logger
25
+
26
+
27
+ _P = ParamSpec("_P")
28
+ _R = TypeVar("_R")
29
+
30
+ __all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"]
31
+
32
+ logger = get_logger(__name__)
33
+
34
+
35
+ def _retry(max_retries: int, sleep_time: float) -> Callable:
36
+ """
37
+ A simple retry wrapper.
38
+
39
+ Args:
40
+ max_retries: int, the maximum number of retries.
41
+ sleep_time: float, the time to sleep between retries.
42
+ """
43
+
44
+ def wrapper(func: Callable[_P, _R]) -> Callable[_P, _R]:
45
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs):
46
+ for i in range(max_retries):
47
+ try:
48
+ return func(*args, **kwargs)
49
+ except Exception:
50
+ logger.exception("Error running %s. Retrying...", func.__name__)
51
+ if i < max_retries - 1:
52
+ time.sleep(sleep_time)
53
+ else:
54
+ raise
55
+
56
+ return wrapper
57
+
58
+ return wrapper
59
+
60
+
61
+ class FileTimerRequest(TimerRequest):
62
+ """
63
+ Data object representing a countdown timer acquisition and release
64
+ that is used between the ``FileTimerClient`` and ``FileTimerServer``.
65
+ A negative ``expiration_time`` should be interpreted as a "release"
66
+ request.
67
+ ``signal`` is the signal to reap the worker process from the server
68
+ process.
69
+ """
70
+
71
+ __slots__ = ["version", "signal"]
72
+
73
+ def __init__(
74
+ self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0
75
+ ) -> None:
76
+ super().__init__(
77
+ worker_id=worker_pid, scope_id=scope_id, expiration_time=expiration_time
78
+ )
79
+ self.version = 1
80
+ self.signal = signal
81
+
82
+ @property
83
+ def worker_pid(self) -> int:
84
+ return self.worker_id
85
+
86
+ def __eq__(self, other) -> bool:
87
+ if isinstance(other, FileTimerRequest):
88
+ return (
89
+ super().__eq__(other)
90
+ and self.version == other.version
91
+ and self.signal == other.signal
92
+ )
93
+ return False
94
+
95
+ def to_json(self) -> str:
96
+ return json.dumps(
97
+ {
98
+ "version": self.version,
99
+ "pid": self.worker_pid,
100
+ "scope_id": self.scope_id,
101
+ "expiration_time": self.expiration_time,
102
+ "signal": self.signal,
103
+ },
104
+ )
105
+
106
+
107
+ class FileTimerClient(TimerClient):
108
+ """
109
+ Client side of ``FileTimerServer``. This client is meant to be used
110
+ on the same host that the ``FileTimerServer`` is running on and uses
111
+ pid to uniquely identify a worker.
112
+ This client uses a named_pipe to send timer requests to the
113
+ ``FileTimerServer``. This client is a producer while the
114
+ ``FileTimerServer`` is a consumer. Multiple clients can work with
115
+ the same ``FileTimerServer``.
116
+
117
+ Args:
118
+
119
+ file_path: str, the path of a FIFO special file. ``FileTimerServer``
120
+ must have created it by calling os.mkfifo().
121
+
122
+ signal: signal, the signal to use to kill the process. Using a
123
+ negative or zero signal will not kill the process.
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ file_path: str,
129
+ signal=(signal.SIGKILL if sys.platform != "win32" else signal.CTRL_C_EVENT), # type: ignore[attr-defined]
130
+ ) -> None:
131
+ super().__init__()
132
+ self._file_path = file_path
133
+ self.signal = signal
134
+
135
+ @_retry(max_retries=10, sleep_time=0.1)
136
+ def _open_non_blocking(self) -> io.TextIOWrapper | None:
137
+ # The server may have crashed or may haven't started yet.
138
+ # In such case, calling open() in blocking model blocks the client.
139
+ # To avoid such issue, open it in non-blocking mode, and an OSError will
140
+ # be raised if the server is not there.
141
+ fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK)
142
+ return os.fdopen(fd, "wt")
143
+
144
+ def _send_request(self, request: FileTimerRequest) -> None:
145
+ try:
146
+ file = self._open_non_blocking()
147
+ except Exception as e:
148
+ raise BrokenPipeError(
149
+ "Could not send the FileTimerRequest because FileTimerServer is not available."
150
+ ) from e
151
+ with file:
152
+ json_request = request.to_json()
153
+ # Write request with no greater than select.PIPE_BUF is guarantee to be atomic.
154
+ if len(json_request) > select.PIPE_BUF:
155
+ raise RuntimeError(
156
+ f"FileTimerRequest larger than {select.PIPE_BUF} bytes "
157
+ f"is not supported: {json_request}"
158
+ )
159
+ file.write(json_request + "\n")
160
+
161
+ def acquire(self, scope_id: str, expiration_time: float) -> None:
162
+ self._send_request(
163
+ request=FileTimerRequest(
164
+ worker_pid=os.getpid(),
165
+ scope_id=scope_id,
166
+ expiration_time=expiration_time,
167
+ signal=self.signal,
168
+ ),
169
+ )
170
+
171
+ def release(self, scope_id: str) -> None:
172
+ self._send_request(
173
+ request=FileTimerRequest(
174
+ worker_pid=os.getpid(), scope_id=scope_id, expiration_time=-1, signal=0
175
+ ),
176
+ )
177
+
178
+
179
+ class FileTimerServer:
180
+ """
181
+ Server that works with ``FileTimerClient``. Clients are expected to be
182
+ running on the same host as the process that is running this server.
183
+ Each host in the job is expected to start its own timer server locally
184
+ and each server instance manages timers for local workers (running on
185
+ processes on the same host).
186
+
187
+ Args:
188
+
189
+ file_path: str, the path of a FIFO special file to be created.
190
+
191
+ max_interval: float, max interval in seconds for each watchdog loop.
192
+
193
+ daemon: bool, running the watchdog thread in daemon mode or not.
194
+ A daemon thread will not block a process to stop.
195
+ log_event: Callable[[Dict[str, str]], None], an optional callback for
196
+ logging the events in JSON format.
197
+ """
198
+
199
+ def __init__(
200
+ self,
201
+ file_path: str,
202
+ run_id: str,
203
+ max_interval: float = 10,
204
+ daemon: bool = True,
205
+ log_event: Callable[[str, FileTimerRequest | None], None] | None = None,
206
+ ) -> None:
207
+ self._file_path = file_path
208
+ self._run_id = run_id
209
+ self._max_interval = max_interval
210
+ self._daemon = daemon
211
+ self._timers: dict[tuple[int, str], FileTimerRequest] = {}
212
+ self._stop_signaled = False
213
+ self._watchdog_thread: threading.Thread | None = None
214
+
215
+ self._is_client_started = False
216
+ if os.path.exists(self._file_path):
217
+ os.remove(self._file_path)
218
+ os.mkfifo(self._file_path)
219
+ # For test only. Count the number of requests received.
220
+ self._request_count = 0
221
+ # For test only. Process all requests and stop the server.
222
+ self._run_once = False
223
+ self._log_event = (
224
+ log_event if log_event is not None else lambda name, request: None
225
+ )
226
+ self._last_progress_time = int(time.time())
227
+
228
+ def start(self) -> None:
229
+ logger.info(
230
+ "Starting %s... max_interval=%s, daemon=%s, file_path=%s",
231
+ type(self).__name__,
232
+ self._max_interval,
233
+ self._daemon,
234
+ self._file_path,
235
+ )
236
+ self._watchdog_thread = threading.Thread(
237
+ target=self._watchdog_loop, daemon=self._daemon
238
+ )
239
+ logger.info("Starting watchdog thread...")
240
+ self._watchdog_thread.start()
241
+ self._log_event("watchdog started", None)
242
+
243
+ def stop(self) -> None:
244
+ logger.info("Stopping %s", type(self).__name__)
245
+ self._stop_signaled = True
246
+ if self._watchdog_thread:
247
+ logger.info("Stopping watchdog thread...")
248
+ self._watchdog_thread.join(self._max_interval)
249
+ self._watchdog_thread = None
250
+ else:
251
+ logger.info("No watchdog thread running, doing nothing")
252
+ if os.path.exists(self._file_path):
253
+ os.remove(self._file_path)
254
+ self._log_event("watchdog stopped", None)
255
+
256
+ def run_once(self) -> None:
257
+ self._run_once = True
258
+ if self._watchdog_thread:
259
+ logger.info("Stopping watchdog thread...")
260
+ self._watchdog_thread.join()
261
+ self._watchdog_thread = None
262
+ else:
263
+ logger.info("No watchdog thread running, doing nothing")
264
+ if os.path.exists(self._file_path):
265
+ os.remove(self._file_path)
266
+
267
+ @staticmethod
268
+ def is_process_running(pid: int):
269
+ """
270
+ function to check process is running or not
271
+ """
272
+ try:
273
+ # Check if the process exists and we can send signals to it
274
+ os.kill(pid, 0)
275
+ return True
276
+ except OSError:
277
+ return False
278
+
279
+ def _watchdog_loop(self) -> None:
280
+ # Open the pipe in blocking mode blocks the server thread.
281
+ # This is fine for the following reasons:
282
+ # 1. No client case usually does not happen.
283
+ # 2. We are running the watchdog loop in a separate daemon
284
+ # thread, which will not block the process to stop.
285
+ try:
286
+ with open(self._file_path) as fd:
287
+ self._is_client_started = True
288
+ while not self._stop_signaled:
289
+ try:
290
+ run_once = self._run_once
291
+ self._run_watchdog(fd)
292
+ if run_once:
293
+ break
294
+ self._last_progress_time = int(time.time())
295
+ except Exception:
296
+ logger.exception("Error running watchdog")
297
+
298
+ except Exception:
299
+ logger.exception("Could not open the FileTimerServer pipe")
300
+ raise
301
+
302
+ def _run_watchdog(self, fd: io.TextIOWrapper) -> None:
303
+ timer_requests = self._get_requests(fd, self._max_interval)
304
+ self.register_timers(timer_requests)
305
+ now = time.time()
306
+ reaped_worker_pids = set()
307
+ kill_process = False
308
+ reap_signal = 0
309
+
310
+ all_expired_timers = self.get_expired_timers(now)
311
+ log_debug_info_for_expired_timers(
312
+ self._run_id,
313
+ {
314
+ pid: [expired_timer.to_json() for expired_timer in expired_timers]
315
+ for pid, expired_timers in all_expired_timers.items()
316
+ },
317
+ )
318
+
319
+ for worker_pid, expired_timers in all_expired_timers.items():
320
+ logger.info(
321
+ "Reaping worker_pid=[%s]. Expired timers: %s",
322
+ worker_pid,
323
+ self._get_scopes(expired_timers),
324
+ )
325
+ reaped_worker_pids.add(worker_pid)
326
+ # In case we have multiple expired timers, we find the first timer
327
+ # with a valid signal (>0) in the expiration time order.
328
+ expired_timers.sort(key=lambda timer: timer.expiration_time)
329
+ signal = 0
330
+ expired_timer = None
331
+ for timer in expired_timers:
332
+ self._log_event("timer expired", timer)
333
+ if timer.signal > 0:
334
+ signal = timer.signal
335
+ expired_timer = timer
336
+ break
337
+ if signal <= 0:
338
+ logger.info(
339
+ "No signal specified with worker=[%s]. Do not reap it.", worker_pid
340
+ )
341
+ continue
342
+ if self._reap_worker(worker_pid, signal):
343
+ logger.info(
344
+ "Successfully reaped worker=[%s] with signal=%s", worker_pid, signal
345
+ )
346
+ self._log_event("kill worker process", expired_timer)
347
+ kill_process = True
348
+ reap_signal = signal
349
+ else:
350
+ logger.error(
351
+ "Error reaping worker=[%s]. Will retry on next watchdog.",
352
+ worker_pid,
353
+ )
354
+ if kill_process and reap_signal > 0:
355
+ logger.info(
356
+ "Terminating the server process=[%s] because of expired timers",
357
+ os.getpid(),
358
+ )
359
+ self._reap_worker(os.getpid(), reap_signal)
360
+
361
+ self.clear_timers(reaped_worker_pids)
362
+
363
+ def _get_scopes(self, timer_requests: list[FileTimerRequest]) -> list[str]:
364
+ return [r.scope_id for r in timer_requests]
365
+
366
+ def _get_requests(
367
+ self, fd: io.TextIOWrapper, max_interval: float
368
+ ) -> list[FileTimerRequest]:
369
+ start = time.time()
370
+ requests = []
371
+ while not self._stop_signaled or self._run_once:
372
+ # For named pipe, readline() is blocking when at least one writer opens.
373
+ # It returns only when flush() is called at the writer side.
374
+ # Note that flush() is automatically called inside close().
375
+ # After the last writer closes, readline() is not blocking.
376
+ # It will return an empty string when it's at end-of-file.
377
+ # Since the client side always opens the pipe, writes a message and closes
378
+ # the pipe immediately, the readline() call below is not blocking for long.
379
+ json_request = fd.readline()
380
+ if len(json_request) == 0:
381
+ if self._run_once:
382
+ break
383
+ time.sleep(min(max_interval, 1))
384
+ else:
385
+ request = json.loads(json_request)
386
+ pid = request["pid"]
387
+ scope_id = request["scope_id"]
388
+ expiration_time = request["expiration_time"]
389
+ signal = request["signal"]
390
+ requests.append(
391
+ FileTimerRequest(
392
+ worker_pid=pid,
393
+ scope_id=scope_id,
394
+ expiration_time=expiration_time,
395
+ signal=signal,
396
+ )
397
+ )
398
+ now = time.time()
399
+ if now - start > max_interval:
400
+ break
401
+ return requests
402
+
403
+ def register_timers(self, timer_requests: list[FileTimerRequest]) -> None:
404
+ for request in timer_requests:
405
+ pid = request.worker_pid
406
+ scope_id = request.scope_id
407
+ expiration_time = request.expiration_time
408
+ self._request_count += 1
409
+
410
+ key = (pid, scope_id)
411
+ # negative expiration is a proxy for a release call
412
+ if expiration_time < 0:
413
+ if key in self._timers:
414
+ del self._timers[key]
415
+ else:
416
+ self._timers[key] = request
417
+
418
+ def clear_timers(self, worker_pids: set[int]) -> None:
419
+ for pid, scope_id in list(self._timers.keys()):
420
+ if pid in worker_pids or not FileTimerServer.is_process_running(pid):
421
+ del self._timers[(pid, scope_id)]
422
+
423
+ def get_expired_timers(self, deadline: float) -> dict[int, list[FileTimerRequest]]:
424
+ # pid -> [timer_requests...]
425
+ expired_timers: dict[int, list[FileTimerRequest]] = {}
426
+ for request in self._timers.values():
427
+ if request.expiration_time <= deadline:
428
+ expired_scopes = expired_timers.setdefault(request.worker_pid, [])
429
+ expired_scopes.append(request)
430
+ return expired_timers
431
+
432
+ def _reap_worker(self, worker_pid: int, signal: int) -> bool:
433
+ try:
434
+ os.kill(worker_pid, signal)
435
+ return True
436
+ except ProcessLookupError:
437
+ logger.info("Process with pid=%s does not exist. Skipping", worker_pid)
438
+ return True
439
+ except Exception:
440
+ logger.exception("Error terminating pid=%s", worker_pid)
441
+ return False
442
+
443
+ def get_last_progress_time(self) -> int:
444
+ return self._last_progress_time if self._is_client_started else int(time.time())
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/timer/local_timer.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+ import logging
8
+ import multiprocessing as mp
9
+ import os
10
+ import signal
11
+ import time
12
+ from queue import Empty
13
+ from typing import Any
14
+
15
+ from .api import RequestQueue, TimerClient, TimerRequest, TimerServer
16
+
17
+
18
+ __all__ = ["LocalTimerClient", "MultiprocessingRequestQueue", "LocalTimerServer"]
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class LocalTimerClient(TimerClient):
24
+ """
25
+ Client side of ``LocalTimerServer``. This client is meant to be used
26
+ on the same host that the ``LocalTimerServer`` is running on and uses
27
+ pid to uniquely identify a worker. This is particularly useful in situations
28
+ where one spawns a subprocess (trainer) per GPU on a host with multiple
29
+ GPU devices.
30
+ """
31
+
32
+ def __init__(self, mp_queue):
33
+ super().__init__()
34
+ self._mp_queue = mp_queue
35
+
36
+ def acquire(self, scope_id, expiration_time):
37
+ pid = os.getpid()
38
+ acquire_request = TimerRequest(pid, scope_id, expiration_time)
39
+ self._mp_queue.put(acquire_request)
40
+
41
+ def release(self, scope_id):
42
+ pid = os.getpid()
43
+ release_request = TimerRequest(pid, scope_id, -1)
44
+ self._mp_queue.put(release_request)
45
+
46
+
47
+ class MultiprocessingRequestQueue(RequestQueue):
48
+ """
49
+ A ``RequestQueue`` backed by python ``multiprocessing.Queue``
50
+ """
51
+
52
+ def __init__(self, mp_queue: mp.Queue):
53
+ super().__init__()
54
+ self._mp_queue = mp_queue
55
+
56
+ def size(self) -> int:
57
+ return self._mp_queue.qsize()
58
+
59
+ def get(self, size, timeout: float) -> list[TimerRequest]:
60
+ requests = []
61
+ wait = timeout
62
+ for _ in range(size):
63
+ start = time.time()
64
+
65
+ try:
66
+ r = self._mp_queue.get(block=True, timeout=wait)
67
+ except Empty:
68
+ break
69
+
70
+ requests.append(r)
71
+ wait = wait - (time.time() - start)
72
+ if wait <= 0:
73
+ break
74
+
75
+ return requests
76
+
77
+
78
+ class LocalTimerServer(TimerServer):
79
+ """
80
+ Server that works with ``LocalTimerClient``. Clients are expected to be
81
+ subprocesses to the parent process that is running this server. Each host
82
+ in the job is expected to start its own timer server locally and each
83
+ server instance manages timers for local workers (running on processes
84
+ on the same host).
85
+ """
86
+
87
+ def __init__(
88
+ self, mp_queue: mp.Queue, max_interval: float = 60, daemon: bool = True
89
+ ):
90
+ super().__init__(MultiprocessingRequestQueue(mp_queue), max_interval, daemon)
91
+ self._timers: dict[tuple[Any, str], TimerRequest] = {}
92
+
93
+ def register_timers(self, timer_requests: list[TimerRequest]) -> None:
94
+ for request in timer_requests:
95
+ pid = request.worker_id
96
+ scope_id = request.scope_id
97
+ expiration_time = request.expiration_time
98
+
99
+ # negative expiration is a proxy for a release call
100
+ if expiration_time < 0:
101
+ self._timers.pop((pid, scope_id), None)
102
+ else:
103
+ self._timers[(pid, scope_id)] = request
104
+
105
+ def clear_timers(self, worker_ids: set[int]) -> None:
106
+ for pid, scope_id in list(self._timers.keys()):
107
+ if pid in worker_ids:
108
+ self._timers.pop((pid, scope_id))
109
+
110
+ def get_expired_timers(self, deadline: float) -> dict[Any, list[TimerRequest]]:
111
+ # pid -> [timer_requests...]
112
+ expired_timers: dict[Any, list[TimerRequest]] = {}
113
+ for request in self._timers.values():
114
+ if request.expiration_time <= deadline:
115
+ expired_scopes = expired_timers.setdefault(request.worker_id, [])
116
+ expired_scopes.append(request)
117
+ return expired_timers
118
+
119
+ def _reap_worker(self, worker_id: int) -> bool:
120
+ try:
121
+ os.kill(worker_id, signal.SIGKILL)
122
+ return True
123
+ except ProcessLookupError:
124
+ logger.info("Process with pid=%s does not exist. Skipping", worker_id)
125
+ return True
126
+ except Exception:
127
+ logger.exception("Error terminating pid=%s", worker_id)
128
+ return False
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ from .api import get_env_variable_or_raise, get_socket_with_port, macros # noqa: F401
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/api.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import os
10
+ import socket
11
+ from string import Template
12
+ from typing import Any
13
+
14
+
15
+ def get_env_variable_or_raise(env_name: str) -> str:
16
+ r"""
17
+ Tries to retrieve environment variable. Raises ``ValueError``
18
+ if no environment variable found.
19
+
20
+ Args:
21
+ env_name (str): Name of the env variable
22
+ """
23
+ value = os.environ.get(env_name, None)
24
+ if value is None:
25
+ msg = f"Environment variable {env_name} expected, but not set"
26
+ raise ValueError(msg)
27
+ return value
28
+
29
+
30
+ def get_socket_with_port() -> socket.socket:
31
+ addrs = socket.getaddrinfo(
32
+ host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
33
+ )
34
+ for addr in addrs:
35
+ family, type, proto, _, _ = addr
36
+ s = socket.socket(family, type, proto)
37
+ try:
38
+ s.bind(("localhost", 0))
39
+ s.listen(0)
40
+ return s
41
+ except OSError:
42
+ s.close()
43
+ raise RuntimeError("Failed to create a socket")
44
+
45
+
46
+ class macros:
47
+ """
48
+ Defines simple macros for caffe2.distributed.launch cmd args substitution
49
+ """
50
+
51
+ local_rank = "${local_rank}"
52
+
53
+ @staticmethod
54
+ def substitute(args: list[Any], local_rank: str) -> list[str]:
55
+ args_sub = []
56
+ for arg in args:
57
+ if isinstance(arg, str):
58
+ sub = Template(arg).safe_substitute(local_rank=local_rank)
59
+ args_sub.append(sub)
60
+ else:
61
+ args_sub.append(arg)
62
+ return args_sub
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ from .cycling_iterator import CyclingIterator # noqa: F401
10
+ from .elastic_distributed_sampler import ElasticDistributedSampler # noqa: F401
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from collections.abc import Callable, Iterator
4
+ from typing import TypeVar
5
+ from typing_extensions import Self
6
+
7
+
8
+ # Copyright (c) Facebook, Inc. and its affiliates.
9
+ # All rights reserved.
10
+ #
11
+ # This source code is licensed under the BSD-style license found in the
12
+ # LICENSE file in the root directory of this source tree.
13
+
14
+ _T = TypeVar("_T")
15
+
16
+ __all__ = ["CyclingIterator"]
17
+
18
+
19
+ class CyclingIterator(Iterator[_T]):
20
+ """
21
+ An iterator decorator that cycles through the
22
+ underlying iterator "n" times. Useful to "unroll"
23
+ the dataset across multiple training epochs.
24
+
25
+ The generator function is called as ``generator_fn(epoch)``
26
+ to obtain the underlying iterator, where ``epoch`` is a
27
+ number less than or equal to ``n`` representing the ``k``th cycle
28
+
29
+ For example if ``generator_fn`` always returns ``[1,2,3]``
30
+ then ``CyclingIterator(n=2, generator_fn)`` will iterate through
31
+ ``[1,2,3,1,2,3]``
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ n: int,
37
+ generator_fn: Callable[[int], Iterator[_T]],
38
+ start_epoch: int = 0,
39
+ ):
40
+ self._n = n
41
+ self._epoch = start_epoch
42
+ self._generator_fn = generator_fn
43
+ self._iter = generator_fn(self._epoch)
44
+
45
+ def __iter__(self) -> Self:
46
+ return self
47
+
48
+ def __next__(self) -> _T:
49
+ try:
50
+ return next(self._iter)
51
+ except StopIteration as eod: # eod == end of data
52
+ if self._epoch < self._n - 1:
53
+ self._epoch += 1
54
+ self._iter = self._generator_fn(self._epoch)
55
+ return self.__next__()
56
+ else:
57
+ raise eod
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import math
10
+ from collections.abc import Iterator, Sized
11
+ from typing import cast, TypeVar
12
+
13
+ import torch
14
+ from torch.utils.data import Dataset
15
+ from torch.utils.data.distributed import DistributedSampler
16
+
17
+
18
+ T = TypeVar("T")
19
+
20
+ __all__ = ["ElasticDistributedSampler"]
21
+
22
+
23
+ class ElasticDistributedSampler(DistributedSampler[T]):
24
+ """
25
+ Sampler that restricts data loading to a subset of
26
+ the dataset for elastic training.
27
+
28
+ It is especially useful in conjunction with
29
+ :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
30
+ process can pass a DistributedSampler instance as a DataLoader sampler,
31
+ and load a subset of the original dataset that is exclusive to it.
32
+
33
+ .. note::
34
+ Dataset is assumed to be of constant size.
35
+
36
+ Args:
37
+ dataset: Dataset used for sampling.
38
+ num_replicas (optional): Number of processes participating in
39
+ distributed training.
40
+ rank (optional): Rank of the current process within num_replicas.
41
+ start_index (optional): Which index of the dataset to start sampling from
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ dataset: Dataset[T],
47
+ num_replicas: int | None = None,
48
+ rank: int | None = None,
49
+ start_index: int = 0,
50
+ ):
51
+ super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
52
+ if not isinstance(dataset, Sized):
53
+ raise TypeError("Dataset must be an instance of collections.abc.Sized")
54
+
55
+ # Cast to Sized for mypy
56
+ # pyrefly: ignore [redundant-cast]
57
+ sized_dataset = cast(Sized, dataset)
58
+
59
+ if start_index >= len(sized_dataset):
60
+ raise ValueError(
61
+ f"Start index {start_index} should be less than dataset size {len(sized_dataset)}"
62
+ )
63
+
64
+ self.start_index = start_index
65
+ sized_dataset = cast(Sized, self.dataset)
66
+ self.num_samples = math.ceil(
67
+ float(len(sized_dataset) - self.start_index) / self.num_replicas
68
+ )
69
+ self.total_size = self.num_samples * self.num_replicas
70
+
71
+ def __iter__(self) -> Iterator[T]:
72
+ # deterministically shuffle based on epoch
73
+ g = torch.Generator()
74
+ g.manual_seed(self.epoch)
75
+ sized_dataset = cast(Sized, self.dataset)
76
+ indices = (
77
+ torch.randperm(len(sized_dataset) - self.start_index, generator=g)
78
+ .add(self.start_index)
79
+ .tolist()
80
+ )
81
+
82
+ # add extra samples to make it evenly divisible
83
+ indices += indices[: (self.total_size - len(indices))]
84
+ assert len(indices) == self.total_size
85
+
86
+ # subsample
87
+ indices = indices[self.rank : self.total_size : self.num_replicas]
88
+ assert len(indices) == self.num_samples
89
+
90
+ return iter(indices)
91
+
92
+ def __len__(self) -> int:
93
+ return self.num_samples
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/distributed.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+ import datetime
10
+ import os
11
+ import socket
12
+ from contextlib import closing
13
+
14
+ import torch.distributed as dist
15
+ from torch.distributed.elastic.utils.logging import get_logger
16
+ from torch.distributed.elastic.utils.store import barrier
17
+
18
+
19
+ __all__ = ["create_c10d_store", "get_free_port", "get_socket_with_port"]
20
+
21
+ logger = get_logger(__name__)
22
+
23
+ _ADDRESS_IN_USE = "Address already in use"
24
+ _SOCKET_TIMEOUT = "Socket Timeout"
25
+
26
+ _TCP_STORE_INIT = "_tcp_store/num_members"
27
+
28
+
29
+ def create_c10d_store(
30
+ is_server: bool,
31
+ server_addr: str,
32
+ server_port: int = -1,
33
+ world_size: int = 1,
34
+ timeout: float = (60 * 10), # 10 min
35
+ wait_for_workers: bool = True,
36
+ retries=3,
37
+ use_libuv: bool | None = None,
38
+ ):
39
+ if use_libuv is not None:
40
+ logger.warning(
41
+ "argument use_libuv is deprecated and ignored. Set USE_LIBUV environment "
42
+ 'variable to "0" to disable libuv, or "1" to enable it. If the env var '
43
+ "is not set, libuv will be used by default."
44
+ )
45
+
46
+ # check os.environ for use_libuv
47
+ use_libuv = os.environ.get("USE_LIBUV", "1") == "1" # libuv is the default option
48
+
49
+ if server_port == -1 and world_size > 1:
50
+ raise ValueError(
51
+ f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}"
52
+ )
53
+
54
+ if server_port != -1:
55
+ logger.info("sever_port: %s, specified, ignoring retries", server_port)
56
+
57
+ # only retry when server_port is NOT static
58
+ attempt = retries if server_port == -1 else 1
59
+ while True:
60
+ if server_port != -1:
61
+ port = server_port
62
+ else:
63
+ port = get_free_port()
64
+
65
+ logger.info(
66
+ "Creating c10d store on %s:%s\n"
67
+ " world_size : %s\n"
68
+ " is_server : %s\n"
69
+ " timeout(sec): %s\n"
70
+ " use_libuv : %s\n",
71
+ server_addr,
72
+ port,
73
+ world_size,
74
+ is_server,
75
+ timeout,
76
+ use_libuv,
77
+ )
78
+
79
+ try:
80
+ store = dist.TCPStore(
81
+ host_name=server_addr,
82
+ port=port,
83
+ world_size=world_size,
84
+ is_master=is_server,
85
+ timeout=datetime.timedelta(seconds=timeout),
86
+ wait_for_workers=wait_for_workers,
87
+ use_libuv=use_libuv,
88
+ )
89
+ # skips full rank check when we don't have to wait for all workers
90
+ if wait_for_workers:
91
+ _check_full_rank(store, world_size, timeout=timeout)
92
+ logger.info("Successfully created c10d store")
93
+ return store
94
+ except RuntimeError as e:
95
+ # this is brittle, but the underlying exception type is not properly pybinded
96
+ # so we parse the error msg for now, interestingly this is how torch itself
97
+ # detects timeouts and port conflicts in their own unittests
98
+ # see - caffe2/torch/testing/_internal/common_utils.py
99
+ # TODO properly map the exceptions in pybind (c10d/init.cpp)
100
+ if str(e) == _ADDRESS_IN_USE: # this will only happen on the server
101
+ if attempt < retries:
102
+ logger.warning(
103
+ "port: %s already in use, attempt: [%s/%s]",
104
+ port,
105
+ attempt,
106
+ retries,
107
+ )
108
+ attempt += 1
109
+ else:
110
+ raise RuntimeError(
111
+ f"on {server_addr}, port: {port} already in use"
112
+ ) from e
113
+ else:
114
+ raise
115
+
116
+
117
+ def _check_full_rank(store, world_size, timeout):
118
+ try:
119
+ barrier(store, world_size, key_prefix=_TCP_STORE_INIT, barrier_timeout=timeout)
120
+ except RuntimeError as e:
121
+ if str(e) == _SOCKET_TIMEOUT:
122
+ raise TimeoutError(
123
+ f"timed out waiting for all {world_size} members to join"
124
+ ) from e
125
+ else:
126
+ raise
127
+
128
+
129
+ def get_free_port():
130
+ """
131
+ Returns an unused port on localhost.
132
+
133
+ This function finds an unused port on localhost by opening to socket to bind
134
+ to a port and then closing it.
135
+
136
+ Returns:
137
+ int: an unused port on localhost
138
+
139
+ Example:
140
+ >>> # xdoctest: +SKIP("Nondeterministic")
141
+ >>> get_free_port()
142
+ 63976
143
+
144
+ .. note::
145
+ The port returned by :func:`get_free_port` is not reserved and may be
146
+ taken by another process after this function returns.
147
+ """
148
+ sock = get_socket_with_port()
149
+ with closing(sock):
150
+ return sock.getsockname()[1]
151
+
152
+
153
+ def get_socket_with_port() -> socket.socket:
154
+ """
155
+ Returns a free port on localhost that is "reserved" by binding a temporary
156
+ socket on it. Close the socket before passing the port to the entity
157
+ that requires it. Usage example
158
+
159
+ ::
160
+
161
+ sock = _get_socket_with_port()
162
+ with closing(sock):
163
+ port = sock.getsockname()[1]
164
+ sock.close()
165
+ # there is still a race-condition that some other process
166
+ # may grab this port before func() runs
167
+ func(port)
168
+ """
169
+
170
+ addrs = socket.getaddrinfo(
171
+ host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
172
+ )
173
+ for addr in addrs:
174
+ family, type, proto, _, _ = addr
175
+ s = socket.socket(family, type, proto)
176
+ try:
177
+ s.bind(("localhost", 0))
178
+ s.listen(0)
179
+ return s
180
+ except OSError as e:
181
+ s.close()
182
+ logger.warning("Socket creation attempt failed.", exc_info=e)
183
+ raise RuntimeError("Failed to create a socket")
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/log_level.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+
10
+ def get_log_level() -> str:
11
+ """
12
+ Return default log level for pytorch.
13
+ """
14
+ return "WARNING"
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/logging.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import inspect
10
+ import logging
11
+ import os
12
+ import warnings
13
+
14
+ from torch.distributed.elastic.utils.log_level import get_log_level
15
+
16
+
17
+ def get_logger(name: str | None = None) -> logging.Logger:
18
+ """
19
+ Util function to set up a simple logger that writes
20
+ into stderr. The loglevel is fetched from the LOGLEVEL
21
+ env. variable or WARNING as default. The function will use the
22
+ module name of the caller if no name is provided.
23
+
24
+ Args:
25
+ name: Name of the logger. If no name provided, the name will
26
+ be derived from the call stack.
27
+ """
28
+
29
+ # Derive the name of the caller, if none provided
30
+ # Use depth=2 since this function takes up one level in the call stack
31
+ return _setup_logger(name or _derive_module_name(depth=2))
32
+
33
+
34
+ def _setup_logger(name: str | None = None) -> logging.Logger:
35
+ logger = logging.getLogger(name)
36
+ logger.setLevel(os.environ.get("LOGLEVEL", get_log_level()))
37
+ return logger
38
+
39
+
40
+ def _derive_module_name(depth: int = 1) -> str | None:
41
+ """
42
+ Derives the name of the caller module from the stack frames.
43
+
44
+ Args:
45
+ depth: The position of the frame in the stack.
46
+ """
47
+ try:
48
+ stack = inspect.stack()
49
+ assert depth < len(stack)
50
+ # FrameInfo is just a named tuple: (frame, filename, lineno, function, code_context, index)
51
+ frame_info = stack[depth]
52
+
53
+ module = inspect.getmodule(frame_info[0])
54
+ if module:
55
+ module_name = module.__name__
56
+ else:
57
+ # inspect.getmodule(frame_info[0]) does NOT work (returns None) in
58
+ # binaries built with @mode/opt
59
+ # return the filename (minus the .py extension) as modulename
60
+ filename = frame_info[1]
61
+ module_name = os.path.splitext(os.path.basename(filename))[0]
62
+ return module_name
63
+ except Exception as e:
64
+ warnings.warn(
65
+ f"Error deriving logger module name, using <None>. Exception: {e}",
66
+ RuntimeWarning,
67
+ stacklevel=2,
68
+ )
69
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/elastic/utils/store.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+
10
+ from collections.abc import Callable, Iterable
11
+ from contextlib import contextmanager
12
+ from datetime import timedelta
13
+
14
+ import torch
15
+
16
+
17
+ DistStoreError = torch._C._DistStoreError
18
+
19
+ _NUM_MEMBERS = "/num_members"
20
+ _LAST_MEMBER_CHECKIN = "/last_member"
21
+ _TRACE = "/TRACE"
22
+ _TRACING_GATE = "/TRACING_GATE"
23
+ _MAX_TRACE_MISSING_RANKS = 16
24
+
25
+
26
+ __all__ = ["store_timeout", "get_all", "synchronize", "barrier"]
27
+
28
+
29
+ @contextmanager
30
+ def store_timeout(store, timeout: float):
31
+ """
32
+ This sets the timeout and then restores the old timeout when the context
33
+ manager exits.
34
+
35
+ Args:
36
+ store: the store to set the timeout on
37
+ timeout: the timeout to set
38
+ """
39
+
40
+ old_timeout = store.timeout
41
+ store.set_timeout(timedelta(seconds=timeout))
42
+ yield
43
+ store.set_timeout(old_timeout)
44
+
45
+
46
+ def get_all(store, rank: int, prefix: str, world_size: int):
47
+ r"""
48
+ Given a store and a prefix, the method goes through the array of keys
49
+ of the following format: ``{prefix}{idx}``, where idx is in a range
50
+ from 0 to size, and tries to retrieve the data.
51
+
52
+ The Rank0 process waits at the end to make sure all other processes
53
+ finished the procedure before exiting.
54
+
55
+ Usage
56
+
57
+ ::
58
+
59
+ values = get_all(store, "torchelastic/data", 3)
60
+ value1 = values[0] # retrieves the data for key torchelastic/data0
61
+ value2 = values[1] # retrieves the data for key torchelastic/data1
62
+ value3 = values[2] # retrieves the data for key torchelastic/data2
63
+
64
+ """
65
+ data_arr = store.multi_get([f"{prefix}{idx}" for idx in range(world_size)])
66
+
67
+ barrier_key = _barrier_nonblocking(
68
+ store=store,
69
+ world_size=world_size,
70
+ key_prefix=f"{prefix}/finished",
71
+ )
72
+ if rank == 0:
73
+ # Rank0 runs the TCPStore daemon, as a result it needs to exit last.
74
+ # Otherwise, the barrier may timeout if rank0 process finished the work
75
+ # before other processes finished `get_all` method
76
+ store.wait([barrier_key])
77
+
78
+ return data_arr
79
+
80
+
81
+ def synchronize(
82
+ store,
83
+ data: bytes,
84
+ rank: int,
85
+ world_size: int,
86
+ key_prefix: str,
87
+ timeout: float = 300,
88
+ ) -> list[bytes]:
89
+ """
90
+ Synchronizes ``world_size`` agents between each other using the underlying c10d store.
91
+ The ``data`` will be available on each of the agents.
92
+
93
+ Note: The data on the path is not deleted, as a result there can be stale data if
94
+ you use the same key_prefix twice.
95
+
96
+ Time complexity: O(N) per worker, O(N^2) globally.
97
+ """
98
+ with store_timeout(store, timeout):
99
+ store.set(f"{key_prefix}{rank}", data)
100
+ agent_data = get_all(store, rank, key_prefix, world_size)
101
+ return agent_data
102
+
103
+
104
+ def _try_detecting_missing_ranks(
105
+ store,
106
+ world_size: int,
107
+ key_prefix: str,
108
+ rank: int,
109
+ rank_decoder: Callable[[int], str],
110
+ trace_timeout: float,
111
+ ) -> Iterable[str] | None:
112
+ store.set(f"{key_prefix}{rank}{_TRACE}", "<val_ignored>")
113
+
114
+ def _find_missing_ranks():
115
+ missing_rank_info = set()
116
+ ranks_missing = 0
117
+ for i in range(1, world_size):
118
+ # reduce noise, assuming in general 8 ranks per node
119
+ # It is valuable to know that 1 or >1 nodes have timed-out.
120
+ if ranks_missing >= _MAX_TRACE_MISSING_RANKS:
121
+ break
122
+ try:
123
+ if ranks_missing == 0:
124
+ store.wait(
125
+ [f"{key_prefix}{i}{_TRACE}"], timedelta(seconds=trace_timeout)
126
+ )
127
+ else:
128
+ # use a shortest timeout, some ranks have failed to check-in
129
+ store.wait([f"{key_prefix}{i}{_TRACE}"], timedelta(milliseconds=1))
130
+ except DistStoreError:
131
+ ranks_missing += 1
132
+ missing_rank_info.add(rank_decoder(i))
133
+ return missing_rank_info
134
+
135
+ def _checkin():
136
+ try:
137
+ store.wait([f"{key_prefix}{_TRACING_GATE}"])
138
+ return [f"[<check rank 0 ({rank_decoder(0)}) for missing rank info>]"]
139
+ except DistStoreError:
140
+ # in case rank0 is the source of the timeout, original exception will be raised
141
+ return None
142
+
143
+ if rank == 0:
144
+ missing_rank_info = _find_missing_ranks()
145
+ store.set(f"{key_prefix}{_TRACING_GATE}", "<val_ignored>")
146
+ return missing_rank_info
147
+ else:
148
+ return _checkin()
149
+
150
+
151
+ def _barrier_nonblocking(store, world_size: int, key_prefix: str) -> str:
152
+ """
153
+ Does all the non-blocking operations for a barrier and returns the final key
154
+ that can be waited on.
155
+ """
156
+ num_members_key = key_prefix + _NUM_MEMBERS
157
+ last_member_key = key_prefix + _LAST_MEMBER_CHECKIN
158
+
159
+ idx = store.add(num_members_key, 1)
160
+ if idx == world_size:
161
+ store.set(last_member_key, "<val_ignored>")
162
+
163
+ return last_member_key
164
+
165
+
166
+ def barrier(
167
+ store,
168
+ world_size: int,
169
+ key_prefix: str,
170
+ barrier_timeout: float = 300,
171
+ rank: int | None = None,
172
+ rank_tracing_decoder: Callable[[int], str] | None = None,
173
+ trace_timeout: float = 10,
174
+ ) -> None:
175
+ """
176
+ A global lock between agents. This will pause all workers until at least
177
+ ``world_size`` workers respond.
178
+
179
+ This uses a fast incrementing index to assign waiting ranks and a success
180
+ flag set by the last worker.
181
+
182
+ Time complexity: O(1) per worker, O(N) globally.
183
+
184
+ Optionally, passing rank will enable tracing of missing ranks on timeouts.
185
+ `rank_tracing_decoder` lambda arg can be used to convert rank data
186
+ into a more meaningful information at an app level (e.g. hostname).
187
+
188
+ Note: Since the data is not removed from the store, the barrier can be used
189
+ once per unique ``key_prefix``.
190
+ """
191
+
192
+ if rank is None:
193
+ assert rank_tracing_decoder is None, "Tracing requires rank information"
194
+
195
+ with store_timeout(store, barrier_timeout):
196
+ last_member_key = _barrier_nonblocking(
197
+ store=store, world_size=world_size, key_prefix=key_prefix
198
+ )
199
+ try:
200
+ store.wait([last_member_key])
201
+ except DistStoreError as e:
202
+ if rank is None:
203
+ raise e
204
+ else:
205
+ missing_ranks = _try_detecting_missing_ranks(
206
+ store,
207
+ world_size,
208
+ key_prefix,
209
+ rank,
210
+ rank_tracing_decoder or (lambda x: str(x)),
211
+ trace_timeout,
212
+ )
213
+ if missing_ranks is not None:
214
+ raise DistStoreError(
215
+ "Timed out waiting on barrier on "
216
+ "rank {}, for key prefix: {} (world_size={}, missing_ranks={}, timeout={})".format(
217
+ rank,
218
+ key_prefix,
219
+ world_size,
220
+ f"[{', '.join(missing_ranks)}]",
221
+ barrier_timeout,
222
+ )
223
+ ) from None
224
+ else:
225
+ raise e
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/builder.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import argparse
8
+ import ast
9
+ import copy
10
+ import os
11
+ import sys
12
+ from typing import Any # type: ignore[attr-defined]
13
+
14
+ from torch.distributed.flight_recorder.components.fr_logger import FlightRecorderLogger
15
+ from torch.distributed.flight_recorder.components.types import (
16
+ Collective,
17
+ Database,
18
+ EntryState,
19
+ Group,
20
+ MatchStateRecord,
21
+ Membership,
22
+ NCCLCall,
23
+ Op,
24
+ Traceback,
25
+ )
26
+ from torch.distributed.flight_recorder.components.utils import (
27
+ add_stack_id_in_entries,
28
+ align_trace_from_beginning,
29
+ check_current_entry_match,
30
+ check_no_missing_dump_files,
31
+ check_version,
32
+ error_analysis,
33
+ find_coalesced_group as find_coalesced_group_p2p_only,
34
+ find_coalesced_group_with_non_p2p,
35
+ get_version_detail,
36
+ just_print_entries,
37
+ match_coalesced_groups as match_coalesced_groups_p2p_only,
38
+ match_coalesced_groups_with_non_p2p,
39
+ )
40
+
41
+
42
+ __all__ = [
43
+ "build_groups_memberships",
44
+ "build_collectives",
45
+ "transform_ft",
46
+ "build_db",
47
+ ]
48
+
49
+ # Set up logging
50
+ logger: FlightRecorderLogger = FlightRecorderLogger()
51
+
52
+
53
+ try:
54
+ from tabulate import tabulate
55
+ except ModuleNotFoundError:
56
+ logger.warning("tabulate is not installed. Proceeding without it.")
57
+
58
+ # Define a no-op tabulate function
59
+ def tabulate(data: Any, headers: Any = None) -> Any: # type: ignore[misc]
60
+ return data
61
+
62
+
63
+ """
64
+ Flat DB builder
65
+ """
66
+
67
+
68
+ def build_groups_memberships(
69
+ pg_config: Any,
70
+ ) -> tuple[
71
+ list[Group],
72
+ dict[Any, Group],
73
+ list[Membership],
74
+ dict[str, set[Any]],
75
+ dict[tuple[str, int], str],
76
+ ]:
77
+ """
78
+ pg_config: {
79
+ global_rank: {
80
+ (pg_guid, desc, ranks)
81
+ }
82
+ }
83
+
84
+ `pg_guid` is a system generated id, but depending on the mode of PG creation it could be a globally incrementing int
85
+ or a hash of the ranks. See `_process_group_name` in distributed_c10d.py.
86
+ `desc` is provided by the user (optionally) and should be 'meaningful' (e.g. TP/PP/DP group)
87
+ `ranks` is a list of the 'global ranks' that are members of the PG.
88
+
89
+ (pg_guid, desc, ranks) tuples are appended lazily to the flight buffer when `getNCCLComm` is called on a PG and
90
+ the `enabled_` flag is true for that PG.
91
+ - the order of calling (init_process_group, new_group, etc) does not affect the order of the tuples in the list
92
+
93
+ Returns:
94
+ `groups`: a groups table where each row is a Group namedtuple.
95
+ `_groups`: a dict that is indexed by pg_guid with Group namedtuple as value.
96
+ `memberships`: a membership table where each row is a Membership namedtuple.
97
+ `_memberships`: a dict that is indexed by pg_guid with set of ranks (int) as value.
98
+ `_pg_guids`: a dict that is indexed by (pg_uid, global_rank) with pg_guid as value.
99
+ """
100
+ # flat lists for return
101
+ groups = []
102
+ memberships = []
103
+
104
+ # dicts for faster cross-rank validation
105
+ _groups = {}
106
+ _memberships = {}
107
+ _pg_guids = {}
108
+ for global_rank in pg_config:
109
+ for pg_uid in pg_config[global_rank]:
110
+ desc = pg_config[global_rank][pg_uid]["desc"]
111
+ ranks = ast.literal_eval(pg_config[global_rank][pg_uid]["ranks"])
112
+ # With the adoption of the split_group API, we can have multiple PGs with the same pg_guid (PG Name)
113
+ # So we need to add the hash of all its ranks within the PG as well.
114
+ # Also guid must be a string because `_process_group_name` returns a string.
115
+ pg_guid = pg_uid + str(hash(frozenset(ranks)))
116
+ _pg_guids[(pg_uid, global_rank)] = pg_guid
117
+ if isinstance(ranks, str):
118
+ # TODO Bug in FR data format? ranks is '[0, 1,...]'
119
+ ranks = eval(ranks)
120
+
121
+ if pg_guid not in _groups:
122
+ groups.append(Group(id=pg_guid, desc=desc, size=len(ranks)))
123
+ for rank in ranks:
124
+ memberships.append(Membership(group_id=pg_guid, global_rank=rank))
125
+ _groups[pg_guid] = groups[-1]
126
+ _memberships[pg_guid] = set(ranks)
127
+ else:
128
+ # validation across ranks
129
+ assert _groups[pg_guid].desc == desc, (
130
+ f"mismatch in desc {_groups[pg_guid].desc} vs {desc} for group {pg_guid}"
131
+ )
132
+ assert _memberships[pg_guid] == set(ranks), (
133
+ f"mismatch in membership for group {pg_guid} {_memberships[pg_guid]} vs {set(ranks)}"
134
+ )
135
+ return groups, _groups, memberships, _memberships, _pg_guids
136
+
137
+
138
+ def build_collectives(
139
+ all_entries: dict[int, list[dict[str, Any]]],
140
+ _groups: dict[str, Group],
141
+ _memberships: dict[str, set[Any]],
142
+ _pg_guids: dict[tuple[str, int], str],
143
+ version: str,
144
+ mismatch_cap: int = 10,
145
+ ) -> tuple[list[Traceback], list[Collective], list[NCCLCall]]:
146
+ """
147
+ groups, memberships are the non-flat dicts that are indexable
148
+ all_entries is a raw dict from the original dumps:
149
+
150
+ all_entries: {
151
+ global_rank: [
152
+ {
153
+ record_id: ordered id of the event in the trace buffer
154
+ pg_id: ProcessGroupNCCL::uid_
155
+ *note: `pg_id` corresponds to nothing in groups table
156
+ process_group: (pg_name, desc)
157
+ *note: `pg_name`, `desc` corresponds to `pg_id`, `desc` in groups table
158
+ collective_seq_id: ordered id for collective operations and coalesced group operations
159
+ p2p_seq_id: ordered id for point-to-point operations
160
+ op_id: ordered id including individual ops inside coalescing group
161
+ profiling_name: descriptive name of the operation
162
+ 'time_created_ns',
163
+ 'input_sizes',
164
+ 'output_sizes',
165
+ 'state',
166
+ 'time_discovered_started_ns',
167
+ 'time_discovered_completed_ns',
168
+ 'retired',
169
+ 'frames',
170
+ }
171
+ ]
172
+ }
173
+ """
174
+ tracebacks: list[Traceback] = []
175
+
176
+ collectives: list[Collective] = []
177
+ nccl_calls: list[NCCLCall] = []
178
+
179
+ # once we find one mismatch, we stop pairing up collectives since the pairing is possibly incorrect
180
+ # instead, just record the remaining ops as NCCLCalls
181
+ mismatch = {_groups[g].id: 0 for g in _groups}
182
+
183
+ # For best effort partial analysis.
184
+ dumps_ranks = {int(key) for key in all_entries}
185
+ """
186
+ - it doesn't matter what order I put collectives/ncclops into their table. we can later on re-sort it by start time
187
+ - there could be multiple options for the "first" collective to pair up (rank 0,1 might do a bcast while rank 2,3 do a bcast)
188
+ - within a group, the first collective must be the same on all ranks in the group, then it can be marked as a
189
+ collective and removed
190
+ """
191
+ while all_entries:
192
+ # we greedily match collectives, starting arbitrarily with the trace from the first rank
193
+ # later, if we exhaust the first rank, we continue with the next 'first rank'
194
+ rank_iter = iter(all_entries)
195
+ first_rank = next(rank_iter)
196
+ other_ranks = list(rank_iter)
197
+
198
+ if len(all_entries[first_rank]) == 0:
199
+ all_entries.pop(first_rank)
200
+ continue
201
+
202
+ # lets match the first collective! we need to know which ranks are involved, and ensure that this same
203
+ # collective is also the first one on those ranks within that group
204
+ entries = all_entries[first_rank]
205
+ current_entry = entries[0]
206
+ desc = current_entry["process_group"][1]
207
+ # For db build and logs printing, we want to use the original pg_name, not the hash one.
208
+ original_pg_name = current_entry["process_group"][0]
209
+ pg_name = _pg_guids[(original_pg_name, first_rank)]
210
+ expected_ranks = set(_memberships[pg_name])
211
+ entry_state = EntryState(current_entry, expected_ranks)
212
+ match_record = MatchStateRecord(
213
+ expected_ranks=expected_ranks,
214
+ other_ranks=other_ranks,
215
+ entry_state=entry_state,
216
+ candidate_ranks={first_rank},
217
+ candidate_idx={},
218
+ found_ranks=set(),
219
+ found_idx={},
220
+ errors=set(),
221
+ )
222
+
223
+ major_v, minor_v = get_version_detail(version)
224
+ find_coalesced_group = (
225
+ find_coalesced_group_p2p_only
226
+ if major_v <= 2 and minor_v < 7
227
+ else find_coalesced_group_with_non_p2p
228
+ )
229
+ maybe_coalesced_group = find_coalesced_group(
230
+ pg_name, entries, _pg_guids, first_rank
231
+ )
232
+ if len(maybe_coalesced_group) > 1:
233
+ num_coalesced_entries = len(maybe_coalesced_group)
234
+ # We need a copy of the original expected ranks to avoid modifying it.
235
+ candidate_ranks = copy.deepcopy(expected_ranks)
236
+ done_ranks = set()
237
+ all_coalesced_entries = {}
238
+ while candidate_ranks:
239
+ curr = candidate_ranks.pop()
240
+ done_ranks.add(curr)
241
+ grp = (
242
+ find_coalesced_group(pg_name, all_entries[curr], _pg_guids, curr) # type: ignore[index]
243
+ if curr in all_entries # type: ignore[comparison-overlap]
244
+ else []
245
+ )
246
+ all_coalesced_entries[curr] = grp
247
+ for _, entry in grp:
248
+ op = Op(entry, _memberships, pg_name)
249
+ peer = None
250
+ if op.type == "send":
251
+ assert op._src_g == curr, (
252
+ f"Send src error: {curr} expected but {op._src_g} is set"
253
+ )
254
+ peer = op._dst_g
255
+ elif op.type == "recv":
256
+ assert op._dst_g == curr, (
257
+ f"Recv dst error: {curr} expected but {op._dst_g} is set"
258
+ )
259
+ peer = op._src_g
260
+ if peer and peer not in done_ranks:
261
+ candidate_ranks.add(peer)
262
+
263
+ if major_v <= 2 and minor_v < 7:
264
+ match = match_coalesced_groups_p2p_only(
265
+ all_coalesced_entries,
266
+ group_size=_groups[pg_name].size,
267
+ groups=_groups,
268
+ memberships=_memberships,
269
+ _pg_guids=_pg_guids,
270
+ )
271
+ else:
272
+ match = match_coalesced_groups_with_non_p2p(
273
+ copy.deepcopy(
274
+ all_coalesced_entries
275
+ ), # We want to keep a copy for cleanup.
276
+ pg_info=(pg_name, desc),
277
+ memberships=_memberships,
278
+ _pg_guids=_pg_guids,
279
+ mismatch=mismatch,
280
+ dumps_ranks=dumps_ranks,
281
+ version=version,
282
+ collectives=collectives,
283
+ match_record=match_record,
284
+ )
285
+
286
+ if match and mismatch[pg_name] == 0:
287
+ # We treat coalesced collectives as a single collective.
288
+ # TODO: we need to surface a merged collective info like input/output sizes to users.
289
+ collectives.append(
290
+ match_record.entry_state.to_collective(len(collectives))
291
+ )
292
+ else:
293
+ mismatch[pg_name] += 1
294
+ for r in all_coalesced_entries:
295
+ idx_map = {r: i for i, _ in reversed(all_coalesced_entries[r])} # noqa: B035
296
+ nccl_calls.extend(
297
+ reversed(
298
+ match_record.entry_state.to_nccl_call(
299
+ all_entries,
300
+ idx_map,
301
+ len(nccl_calls),
302
+ collectives[-1].id if match else None,
303
+ )
304
+ )
305
+ )
306
+ # This extra cleanup is needed because we need to pop all collectives within a coalesced collective.
307
+ for i, k in idx_map.items():
308
+ for _ in range(1, num_coalesced_entries):
309
+ all_entries[i].pop(k)
310
+ else:
311
+ # Iterate through all the ranks and check if there is a mismatch for the current entry.
312
+ check_current_entry_match(
313
+ all_entries,
314
+ _pg_guids,
315
+ (pg_name, desc),
316
+ current_entry,
317
+ _memberships,
318
+ mismatch,
319
+ match_record,
320
+ )
321
+
322
+ # Use heuristics to decide what type of errors and error messages we should print.
323
+ error_analysis(
324
+ all_entries,
325
+ match_record,
326
+ dumps_ranks,
327
+ first_rank,
328
+ current_entry,
329
+ mismatch,
330
+ get_version_detail(version),
331
+ pg_name,
332
+ )
333
+
334
+ # at this point there are 3 possibilities
335
+ # 1. we found a match on all the ranks that are members of the group
336
+ # -> we create a Collective and remove the individual entries from their original lists
337
+ if match_record.found_ranks == expected_ranks and mismatch[pg_name] == 0:
338
+ collectives.append(
339
+ match_record.entry_state.to_collective(len(collectives))
340
+ )
341
+ idx_map = {
342
+ r: match_record.found_idx[r] if r != first_rank else 0
343
+ for r in match_record.found_ranks
344
+ }
345
+ nccl_calls.extend(
346
+ match_record.entry_state.to_nccl_call(
347
+ all_entries, idx_map, len(nccl_calls), collectives[-1].id
348
+ )
349
+ )
350
+
351
+ # 2. we found a partial match but some ranks are missing
352
+ # 3. we found no match
353
+ # -> since its not a complete collective, no entry goes into collectives but we still record a nccl call
354
+ # TODO should there be a way to mark 'mismatches'?
355
+ else:
356
+ logger.debug("appending a non-matching collective")
357
+ idx_map = {
358
+ r: match_record.candidate_idx[r] if r != first_rank else 0
359
+ for r in match_record.candidate_ranks
360
+ }
361
+ collectives.append(
362
+ match_record.entry_state.to_collective(
363
+ len(collectives),
364
+ errors=match_record.errors,
365
+ idx_map=idx_map,
366
+ all_entries=all_entries,
367
+ )
368
+ )
369
+ nccl_calls.extend(
370
+ match_record.entry_state.to_nccl_call(
371
+ all_entries, idx_map, len(nccl_calls), None
372
+ )
373
+ )
374
+
375
+ if mismatch[pg_name] > mismatch_cap:
376
+ logger.error(
377
+ "Too many mismatches for process_group %s: %s aborting", pg_name, desc
378
+ )
379
+ break
380
+
381
+ return tracebacks, collectives, nccl_calls
382
+
383
+
384
+ def transform_ft(
385
+ details: dict[str, dict[str, Any]], group_world_size: int
386
+ ) -> dict[str, dict[str, Any]]:
387
+ for dump_key, dump in details.items():
388
+ rank = dump["rank"]
389
+ for key, pg_config in dump["pg_config"].items():
390
+ if pg_config["desc"] == "default_pg":
391
+ ranks = eval(pg_config["ranks"])
392
+ replica_id = rank // group_world_size
393
+ first_rank = replica_id * group_world_size
394
+ new_ranks = [r + first_rank for r in ranks]
395
+ details[dump_key]["pg_config"][key]["ranks"] = f"{new_ranks}"
396
+
397
+ return details
398
+
399
+
400
+ def build_db(
401
+ details: dict[str, dict[str, Any]], args: argparse.Namespace, version: str
402
+ ) -> Database:
403
+ if args.verbose:
404
+ os.environ["FR_TRACE_VERBOSE_OUTPUT"] = "1"
405
+ # temporary state used for building database
406
+ entries = {}
407
+ pg_config = {}
408
+ version_by_ranks = {}
409
+ for dump in details.values():
410
+ rank = dump["rank"]
411
+ entries[rank] = dump["entries"]
412
+ version_by_ranks[rank] = dump["version"]
413
+ pg_config[rank] = dump["pg_config"]
414
+
415
+ # Ensure version is consistent across all ranks.
416
+ check_version(version_by_ranks, version)
417
+ entries = align_trace_from_beginning(entries)
418
+ stack_id_trace_map: dict[str, int] = {}
419
+ if args.just_print_entries:
420
+ entries, stack_id_trace_map = add_stack_id_in_entries(entries)
421
+
422
+ # flattened database
423
+ groups, _groups, memberships, _memberships, _pg_guids = build_groups_memberships(
424
+ pg_config
425
+ )
426
+ logger.debug("built groups, memberships")
427
+
428
+ if args.just_print_entries:
429
+ just_print_entries(
430
+ entries, _groups, _memberships, _pg_guids, args, stack_id_trace_map
431
+ )
432
+ sys.exit(0)
433
+
434
+ if not args.allow_incomplete_ranks:
435
+ check_no_missing_dump_files(entries, memberships)
436
+
437
+ tracebacks, collectives, nccl_calls = build_collectives(
438
+ entries, _groups, _memberships, _pg_guids, version, args.mismatch_cap
439
+ )
440
+ logger.debug("built collectives, nccl_calls")
441
+ if args.verbose:
442
+ logger.debug("Groups")
443
+ logger.debug(tabulate(groups, headers=Group._fields))
444
+ logger.debug("Memberships")
445
+ logger.debug(tabulate(memberships, headers=Membership._fields))
446
+ logger.debug("Collectives")
447
+ logger.debug(tabulate(collectives, headers=Collective._fields))
448
+ logger.debug("NCCLCalls")
449
+ logger.debug(tabulate(nccl_calls, headers=NCCLCall._fields))
450
+ db = Database(
451
+ tracebacks=tracebacks,
452
+ collectives=collectives,
453
+ ncclcalls=nccl_calls,
454
+ groups=groups,
455
+ memberships=memberships,
456
+ )
457
+ return db
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/config_manager.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import argparse
8
+ import logging
9
+ from collections.abc import Sequence
10
+
11
+ from torch.distributed.flight_recorder.components.fr_logger import FlightRecorderLogger
12
+
13
+
14
+ __all__ = ["JobConfig"]
15
+
16
+
17
+ logger: FlightRecorderLogger = FlightRecorderLogger()
18
+
19
+
20
+ class JobConfig:
21
+ """
22
+ A helper class to manage the script configuration.
23
+ """
24
+
25
+ def __init__(self: "JobConfig"):
26
+ self.parser = argparse.ArgumentParser(
27
+ description="PyTorch Flight recorder analyzing script."
28
+ )
29
+ self.parser.add_argument(
30
+ "trace_dir",
31
+ nargs="?",
32
+ help="Directory containing one trace file per rank, named with <prefix>_<rank>.",
33
+ )
34
+ self.parser.add_argument(
35
+ "--selected-ranks",
36
+ default=None,
37
+ nargs="+",
38
+ type=int,
39
+ help="List of ranks we want to show traces for.",
40
+ )
41
+ self.parser.add_argument(
42
+ "--allow-incomplete-ranks",
43
+ action="store_true",
44
+ help=(
45
+ "FR trace require all ranks to have dumps for analysis. "
46
+ "This flag allows best-effort partial analysis of results "
47
+ "and printing of collected data."
48
+ ),
49
+ )
50
+ self.parser.add_argument(
51
+ "--pg-filters",
52
+ default=None,
53
+ nargs="+",
54
+ type=str,
55
+ help=(
56
+ "List of filter strings, it could be pg name or pg desc. "
57
+ "If specified, only show traces for the given pg."
58
+ ),
59
+ )
60
+ self.parser.add_argument("-o", "--output", default=None)
61
+ self.parser.add_argument(
62
+ "-p",
63
+ "--prefix",
64
+ help=(
65
+ "Common filename prefix to strip such that rank can be extracted. "
66
+ "If not specified, will attempt to infer a common prefix."
67
+ ),
68
+ default=None,
69
+ )
70
+ self.parser.add_argument("-j", "--just_print_entries", action="store_true")
71
+ self.parser.add_argument("-v", "--verbose", action="store_true")
72
+ self.parser.add_argument("--print_stack_trace", action="store_true")
73
+ self.parser.add_argument(
74
+ "--mismatch_cap",
75
+ type=int,
76
+ default=10,
77
+ help="Maximum number of mismatches we print (from earliest).",
78
+ )
79
+ self.parser.add_argument(
80
+ "--transform-ft",
81
+ action="store_true",
82
+ help="Transform PG config to use global ranks to analyze traces produced by torchft",
83
+ )
84
+ self.parser.add_argument(
85
+ "--group-world-size",
86
+ type=int,
87
+ default=None,
88
+ help="The number of ranks in 1 torchft replica group. Must be specified if --transform-ft is True",
89
+ )
90
+
91
+ def parse_args(self: "JobConfig", args: Sequence[str] | None) -> argparse.Namespace:
92
+ # pyrefly: ignore [bad-assignment]
93
+ args = self.parser.parse_args(args)
94
+ # pyrefly: ignore [missing-attribute]
95
+ if args.selected_ranks is not None:
96
+ # pyrefly: ignore [missing-attribute]
97
+ assert args.just_print_entries, (
98
+ "Not support selecting ranks without printing entries"
99
+ )
100
+ # pyrefly: ignore [missing-attribute]
101
+ if args.pg_filters is not None:
102
+ # pyrefly: ignore [missing-attribute]
103
+ assert args.just_print_entries, (
104
+ "Not support selecting pg filters without printing entries"
105
+ )
106
+ # pyrefly: ignore [missing-attribute]
107
+ if args.verbose:
108
+ logger.set_log_level(logging.DEBUG)
109
+ # pyrefly: ignore [bad-return]
110
+ return args
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/fr_logger.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+
12
+ __all__ = ["FlightRecorderLogger"]
13
+
14
+
15
+ class FlightRecorderLogger:
16
+ _instance: Any | None = None
17
+ logger: logging.Logger
18
+
19
+ def __init__(self) -> None:
20
+ self.logger: logging.Logger = logging.getLogger("Flight Recorder")
21
+
22
+ def __new__(cls) -> Any:
23
+ if cls._instance is None:
24
+ cls._instance = super().__new__(cls)
25
+ cls._instance.logger = logging.getLogger("Flight Recorder")
26
+ cls._instance.logger.setLevel(logging.INFO)
27
+ formatter = logging.Formatter("%(message)s")
28
+ ch = logging.StreamHandler()
29
+ ch.setFormatter(formatter)
30
+ cls._instance.logger.addHandler(ch)
31
+ return cls._instance
32
+
33
+ def set_log_level(self, level: int) -> None:
34
+ self.logger.setLevel(level)
35
+
36
+ @property
37
+ def debug(self) -> Callable[..., None]:
38
+ return self.logger.debug
39
+
40
+ @property
41
+ def info(self) -> Callable[..., None]:
42
+ return self.logger.info
43
+
44
+ @property
45
+ def warning(self) -> Callable[..., None]:
46
+ return self.logger.warning
47
+
48
+ @property
49
+ def error(self) -> Callable[..., None]:
50
+ return self.logger.error
51
+
52
+ @property
53
+ def critical(self) -> Callable[..., None]:
54
+ return self.logger.critical
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/loader.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import argparse
8
+ import gc
9
+ import os
10
+ import pickle
11
+ import re
12
+ import time
13
+ from collections import defaultdict
14
+ from typing import Any
15
+
16
+ from torch.distributed.flight_recorder.components.fr_logger import FlightRecorderLogger
17
+
18
+
19
+ __all__ = [
20
+ "read_dump",
21
+ "read_dir",
22
+ ]
23
+
24
+
25
+ logger: FlightRecorderLogger = FlightRecorderLogger()
26
+
27
+
28
+ def read_dump(prefix: str, filename: str) -> dict[str, str | int | list[Any]]:
29
+ basename = os.path.basename(filename)
30
+
31
+ rank = int(basename[len(prefix) :])
32
+ host_name = f"host_rank{rank}"
33
+
34
+ with open(filename, "rb") as infile:
35
+ dump = pickle.load(infile)
36
+
37
+ entries = dump["entries"]
38
+ version = dump["version"]
39
+ pg_config = dump["pg_config"]
40
+
41
+ return {
42
+ "host_name": host_name,
43
+ "rank": rank,
44
+ "entries": entries,
45
+ "version": version,
46
+ "pg_config": pg_config,
47
+ }
48
+
49
+
50
+ exp = re.compile(r"([\w\-\_]*?)(\d+)$")
51
+
52
+
53
+ def _determine_prefix(files: list[str]) -> str:
54
+ """If the user doesn't specify a prefix, but does pass a dir full of similarly-prefixed files, we should be able to
55
+ infer the common prefix most of the time. But if we can't confidently infer, just fall back to requiring the user
56
+ to specify it
57
+ """
58
+ possible_prefixes: defaultdict[str, set[int]] = defaultdict(set)
59
+ for f in files:
60
+ m = exp.search(f)
61
+ if m:
62
+ p, r = m.groups()
63
+ possible_prefixes[p].add(int(r))
64
+ if len(possible_prefixes) == 1:
65
+ prefix = next(iter(possible_prefixes))
66
+ logger.debug("Inferred common prefix %s", prefix)
67
+ return prefix
68
+ else:
69
+ raise ValueError(
70
+ "Unable to automatically determine the common prefix for the trace file names. "
71
+ "Please specify --prefix argument manually"
72
+ )
73
+
74
+
75
+ def read_dir(args: argparse.Namespace) -> tuple[dict[str, dict[str, Any]], str]:
76
+ gc.disable()
77
+ prefix = args.prefix
78
+ details = {}
79
+ t0 = time.time()
80
+ version = ""
81
+ filecount = 0
82
+ assert os.path.isdir(args.trace_dir), f"folder {args.trace_dir} does not exist"
83
+ for root, _, files in os.walk(args.trace_dir):
84
+ if prefix is None:
85
+ prefix = _determine_prefix(files)
86
+ for f in files:
87
+ if (offset := f.find(prefix)) == -1:
88
+ continue
89
+ details[f] = read_dump(f[:offset] + prefix, os.path.join(root, f))
90
+ filecount += 1
91
+ if not version:
92
+ version = str(details[f]["version"])
93
+ tb = time.time()
94
+ assert len(details) > 0, (
95
+ f"no files loaded from {args.trace_dir} with prefix {prefix}"
96
+ )
97
+ logger.debug("loaded %s files in %ss", filecount, tb - t0)
98
+ return details, version
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/types.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ import os
9
+ from enum import auto, Enum
10
+ from typing import ( # type: ignore[attr-defined]
11
+ _eval_type,
12
+ Any,
13
+ Generic,
14
+ NamedTuple,
15
+ TypeVar,
16
+ )
17
+
18
+ from torch.distributed.flight_recorder.components.fr_logger import FlightRecorderLogger
19
+
20
+
21
+ __all__ = [
22
+ "Ref",
23
+ "TypeInfo",
24
+ "MatchState",
25
+ "MatchInfo",
26
+ "Group",
27
+ "Membership",
28
+ "Traceback",
29
+ "Collective",
30
+ "NCCLCall",
31
+ "Database",
32
+ "EntryState",
33
+ "Op",
34
+ "MatchStateRecord",
35
+ ]
36
+
37
+
38
+ T = TypeVar("T", bound=NamedTuple)
39
+
40
+
41
+ class Ref(Generic[T]):
42
+ pass
43
+
44
+
45
+ class TypeInfo(NamedTuple):
46
+ name: str
47
+ fields: list[tuple[str, type]] # type: ignore[type-arg]
48
+
49
+ @classmethod
50
+ def from_type(cls, c: T) -> "TypeInfo":
51
+ if hasattr(c, "__name__"):
52
+ name = c.__name__
53
+ else:
54
+ name = str(c)
55
+ return cls(
56
+ name,
57
+ [(f, _eval_type(c.__annotations__[f], globals(), {})) for f in c._fields],
58
+ )
59
+
60
+
61
+ class MatchState(Enum):
62
+ """
63
+ Enum representing the possible states of matching for collective operations.
64
+
65
+ - FULLY_MATCHED: Indicates that all aspects of the collective operations match.
66
+ - COLLECTIVE_TYPE_MISMATCH: The types of the collective operations differ.
67
+ - SIZE_OR_SYNTAX_MISMATCH: There is a mismatch in input/output sizes or violation of collective syntax.
68
+ - COLLECTIVE_STATE_MISMATCH:
69
+ The states of the collective not same, such as one finished while another just started or scheduled.
70
+ - COLLECTIVE_DTYPE_MISMATCH: The data types of the collective input/output differ.
71
+ - UNDECIDED:
72
+ The match status is ambiguous or cannot be determined, e.g., we might need to check all ranks for alltoall_base.
73
+ """
74
+
75
+ FULLY_MATCHED = auto()
76
+ COLLECTIVE_TYPE_MISMATCH = auto()
77
+ SIZE_OR_SYNTAX_MISMATCH = auto()
78
+ COLLECTIVE_STATE_MISMATCH = auto()
79
+ COLLECTIVE_DTYPE_MISMATCH = auto()
80
+ UNDECIDED = auto()
81
+
82
+
83
+ class MatchInfo:
84
+ """
85
+ Aside from the match state, we also store some dynamic info for the match such as the culprit rank
86
+ or collective state that caused the mismatch.
87
+ """
88
+
89
+ def __init__(self, state: MatchState, culprit: str | None = None) -> None:
90
+ self._state = state
91
+ self.culprit = culprit
92
+
93
+ def __str__(self) -> str:
94
+ details = f", {self.culprit}" if getattr(self, "culprit", None) else ""
95
+ return f"Error type: {self._state.name}{details}"
96
+
97
+ @property
98
+ def state(self) -> MatchState:
99
+ return self._state
100
+
101
+
102
+ """
103
+ Schema for flat DB
104
+
105
+ TODO schemas not yet implemented
106
+ # threads as recorded at termination of process
107
+ Threads
108
+ id: int
109
+ traceback_id: int
110
+ process_id: int
111
+
112
+ Process:
113
+ id: int # Same as world groups RANK
114
+ pid: int
115
+ hostname: str
116
+
117
+ NCCLOp:
118
+ # nccl op implementation details (sends/recv)
119
+ id: int
120
+ nccl_call_id: int
121
+
122
+ """
123
+
124
+
125
+ class Group(NamedTuple):
126
+ id: str
127
+ desc: str
128
+ size: int
129
+
130
+
131
+ class Membership(NamedTuple):
132
+ group_id: str
133
+ global_rank: int
134
+
135
+
136
+ class Traceback(NamedTuple):
137
+ id: int
138
+ frames: str
139
+
140
+
141
+ class Collective(NamedTuple):
142
+ id: int
143
+ group_id: str
144
+ pass_check: bool
145
+ collective_seq_id: int
146
+ p2p_seq_id: int
147
+ record_id: int
148
+ pg_desc: str
149
+ collective_name: str
150
+ input_sizes: list[list[int]]
151
+ output_sizes: list[list[int]]
152
+ expected_ranks: set[int]
153
+ collective_state: str
154
+ collective_frames: list[dict[str, str]]
155
+ input_numel: int | None = None
156
+ output_numel: int | None = None
157
+ missing_ranks: set[int] | None = None
158
+ mismatch_collectives: dict[int, "Collective"] | None = None
159
+ type_of_mismatch: MatchInfo | None = None
160
+
161
+
162
+ class NCCLCall(NamedTuple):
163
+ id: int
164
+ collective_id: Ref[Collective]
165
+ group_id: str
166
+ global_rank: int # technically Ref[Process] once we have it
167
+ traceback_id: Ref[Traceback]
168
+ collective_type: str
169
+ sizes: list[list[int]]
170
+
171
+
172
+ class Database(NamedTuple):
173
+ groups: list[Group]
174
+ memberships: list[Membership]
175
+ tracebacks: list[Traceback]
176
+ collectives: list[Collective]
177
+ ncclcalls: list[NCCLCall]
178
+
179
+
180
+ # TODO: We need to add a schema for the following
181
+ types = [
182
+ TypeInfo.from_type(t) # type: ignore[type-var]
183
+ for t in [Database, NCCLCall, Collective, Traceback, Membership, Group]
184
+ if (
185
+ isinstance(t, type)
186
+ and issubclass(t, tuple)
187
+ and hasattr(t, "_fields")
188
+ and t is not TypeInfo
189
+ )
190
+ ]
191
+
192
+ """
193
+ Stacktrace cache
194
+ TODO
195
+ """
196
+
197
+
198
+ """
199
+ Collective Matching logic
200
+
201
+ NOTE: For now, these collectives need to be supported by NCCL,
202
+ https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/overview.html.
203
+ """
204
+ COLLECTIVES = {
205
+ "broadcast",
206
+ "_broadcast_oop",
207
+ "reduce",
208
+ "_reduce_oop",
209
+ "all_gather",
210
+ "all_reduce",
211
+ "_all_gather_base",
212
+ "all_gather_into_tensor_coalesced",
213
+ "reduce_scatter",
214
+ "reduce_scatter_tensor_coalesced",
215
+ "_reduce_scatter_base",
216
+ "gather",
217
+ "scatter",
218
+ "all_to_all",
219
+ "all_reduce_barrier",
220
+ "allreduce_coalesced",
221
+ "ALLGATHER_coalesced",
222
+ "REDUCE_SCATTER_coalesced",
223
+ }
224
+
225
+ P2P = {
226
+ "send",
227
+ "recv",
228
+ }
229
+
230
+
231
+ class EntryState:
232
+ """
233
+ Util class to keep track of the state of an entry and standardize the way we
234
+ log the error info during analysis.
235
+ """
236
+
237
+ def __init__(self, entry: dict[str, Any], expected_ranks: set[int]) -> None:
238
+ self.pg_name = entry["process_group"][0]
239
+ self.desc = entry["process_group"][1]
240
+ self.pg_desc = (
241
+ f"{self.pg_name}:{self.desc}" if self.desc != "undefined" else self.pg_name
242
+ )
243
+ self.profiling_name = entry["profiling_name"]
244
+ self.collective_seq_id = entry["collective_seq_id"]
245
+ self.p2p_seq_id = entry["p2p_seq_id"]
246
+ self.record_id = entry["record_id"]
247
+ self.input_sizes = entry["input_sizes"]
248
+ self.output_sizes = entry["output_sizes"]
249
+ self.collective_state = entry["state"]
250
+ self.collective_frames = entry.get("frames", [])
251
+ self.expected_ranks = expected_ranks
252
+ self.missing_ranks: set[int]
253
+ self.input_numel: int
254
+ self.output_numel: int
255
+ self.errors: set[tuple[int, MatchInfo]]
256
+
257
+ def log(
258
+ self,
259
+ logger: FlightRecorderLogger,
260
+ logger_msg: str,
261
+ frame_formatter: Any,
262
+ total_numel: tuple[int, int] | None = None,
263
+ errors: set[tuple[int, MatchInfo]] | None = None,
264
+ missing_ranks: set[int] | None = None,
265
+ ) -> None:
266
+ logger.info(
267
+ logger_msg,
268
+ self.collective_seq_id,
269
+ )
270
+ logger.info("internal record id: %s", self.record_id)
271
+ logger.info("group info: %s", self.pg_desc)
272
+ logger.info("collective: %s", self.profiling_name)
273
+ if missing_ranks:
274
+ self.missing_ranks = missing_ranks
275
+ logger.info("missing ranks: %s", missing_ranks)
276
+ if total_numel:
277
+ self.input_numel = total_numel[0]
278
+ self.output_numel = total_numel[1]
279
+ logger.info("total input numel: %d", total_numel[0])
280
+ logger.info("total output numel: %d", total_numel[1])
281
+ logger.info("input sizes: %s", self.input_sizes)
282
+ logger.info("output sizes: %s", self.output_sizes)
283
+ logger.info("world size: %d", len(self.expected_ranks))
284
+ logger.info("expected ranks: %s", str(self.expected_ranks))
285
+ logger.info("collective state: %s", self.collective_state)
286
+ if errors:
287
+ self.errors = errors
288
+ error_msg = ", ".join(
289
+ f"Culprit rank {error[0]}; {str(error[1])}" for error in errors
290
+ )
291
+ logger.info("error msg: %s", error_msg)
292
+ logger.info(
293
+ "collective stack trace: \n %s", frame_formatter(self.collective_frames)
294
+ )
295
+
296
+ def to_collective(
297
+ self,
298
+ id: int,
299
+ errors: set[tuple[int, MatchInfo]] | None = None,
300
+ idx_map: dict[int, int] | None = None,
301
+ all_entries: dict[int, list[dict[str, Any]]] | None = None,
302
+ ) -> Collective:
303
+ if not errors:
304
+ return Collective(
305
+ id=id,
306
+ group_id=self.pg_name,
307
+ record_id=self.record_id,
308
+ pg_desc=self.pg_desc,
309
+ pass_check=True,
310
+ collective_seq_id=self.collective_seq_id,
311
+ p2p_seq_id=self.p2p_seq_id,
312
+ collective_name=self.profiling_name,
313
+ input_sizes=self.input_sizes,
314
+ output_sizes=self.output_sizes,
315
+ expected_ranks=self.expected_ranks,
316
+ collective_state=self.collective_state,
317
+ collective_frames=self.collective_frames,
318
+ missing_ranks=getattr(self, "missing_ranks", None),
319
+ )
320
+ else:
321
+ assert idx_map is not None, "idx_map is None"
322
+ assert all_entries is not None, "all_entries is None"
323
+ mismatch_collectives = {}
324
+ for rank, error in errors:
325
+ idx = idx_map[rank]
326
+ entry = all_entries[rank][idx]
327
+ desc = entry["process_group"][1]
328
+ pg_name = entry["process_group"][0]
329
+ mismatch_collectives[rank] = Collective(
330
+ id=id,
331
+ group_id=entry["process_group"][0],
332
+ record_id=entry["record_id"],
333
+ pg_desc=f"{pg_name}:{desc}" if desc != "undefined" else pg_name,
334
+ pass_check=False,
335
+ collective_seq_id=entry["collective_seq_id"],
336
+ p2p_seq_id=entry["p2p_seq_id"],
337
+ collective_name=entry["profiling_name"],
338
+ input_sizes=entry["input_sizes"],
339
+ output_sizes=entry["output_sizes"],
340
+ expected_ranks=self.expected_ranks,
341
+ collective_state=entry["state"],
342
+ collective_frames=entry.get("frames", []),
343
+ type_of_mismatch=error,
344
+ )
345
+ return Collective(
346
+ id=id,
347
+ group_id=self.pg_name,
348
+ record_id=self.record_id,
349
+ pg_desc=self.pg_desc,
350
+ pass_check=False,
351
+ collective_seq_id=self.collective_seq_id,
352
+ p2p_seq_id=self.p2p_seq_id,
353
+ collective_name=self.profiling_name,
354
+ input_sizes=self.input_sizes,
355
+ output_sizes=self.output_sizes,
356
+ expected_ranks=self.expected_ranks,
357
+ collective_state=self.collective_state,
358
+ collective_frames=self.collective_frames,
359
+ input_numel=self.input_numel if hasattr(self, "input_numel") else None,
360
+ output_numel=self.output_numel
361
+ if hasattr(self, "output_numel")
362
+ else None,
363
+ missing_ranks=self.missing_ranks
364
+ if hasattr(self, "missing_ranks")
365
+ else None,
366
+ mismatch_collectives=mismatch_collectives,
367
+ )
368
+
369
+ def to_nccl_call(
370
+ self,
371
+ all_entries: dict[int, list[dict[str, Any]]],
372
+ idx_map: dict[int, int],
373
+ nccl_call_id: int,
374
+ collective_id: Any,
375
+ ) -> list[NCCLCall]:
376
+ result = []
377
+ for i, k in idx_map.items():
378
+ all_entries[i].pop(k)
379
+ result.append(
380
+ NCCLCall(
381
+ id=nccl_call_id,
382
+ collective_id=collective_id,
383
+ group_id=self.pg_name, # type: ignore[arg-type]
384
+ global_rank=i,
385
+ traceback_id=0, # type: ignore[arg-type]
386
+ collective_type=self.profiling_name,
387
+ sizes=self.input_sizes,
388
+ )
389
+ )
390
+ nccl_call_id += 1
391
+ return result
392
+
393
+
394
+ class Op:
395
+ """Parses relevant info about operation out of 'event' dict
396
+
397
+ examples of supported `profiling_name`s:
398
+ nccl:broadcast
399
+ nccl:send 1->2
400
+ nccl:recv 3<-0
401
+ """
402
+
403
+ def __init__(
404
+ self, event: dict[Any, Any], memberships: dict[str, set[Any]], pg_name: str
405
+ ):
406
+ self.profiling_name = event["profiling_name"]
407
+ comm_lib_backend, name = self.profiling_name.split(":")
408
+ assert comm_lib_backend in ["nccl", "xccl"], (
409
+ f"name formatting error? {comm_lib_backend} != 'nccl' or 'xccl'"
410
+ )
411
+ parts = name.split(" ")
412
+ type = parts[0]
413
+ meta = parts[1] if len(parts) == 2 else None
414
+ self.state = event["state"]
415
+ # Store the hashed pg_name for accessing memberships, and original pg info for display
416
+ self.pg_name = pg_name # This is the hashed version used for memberships lookup
417
+ self.original_pg_name, self.pg_desc = event["process_group"]
418
+ assert type in COLLECTIVES | P2P | {"coalesced"}, (
419
+ f"{type} is not a supported operation"
420
+ )
421
+ self.type = type
422
+ if type == "send":
423
+ assert isinstance(meta, str)
424
+ s, d = meta.split("->")
425
+ self._src, self._dst = int(s), int(d)
426
+ elif type == "recv":
427
+ assert isinstance(meta, str)
428
+ d, s = meta.split("<-")
429
+ self._dst, self._src = int(d), int(s)
430
+ else:
431
+ self._src, self._dst = -1, -1
432
+ self._init_global_src_dst(memberships[pg_name])
433
+ self.pg_size = len(memberships[pg_name])
434
+ if type in P2P | COLLECTIVES:
435
+ self.input_sizes = event["input_sizes"]
436
+ self.output_sizes = event["output_sizes"]
437
+ else:
438
+ self.input_sizes, self.output_sizes = None, None
439
+ self.collective_seq_id = event["collective_seq_id"]
440
+ self.stack_id = event.get("stack_id", -1)
441
+ self.p2p_seq_id = event["p2p_seq_id"]
442
+ self.input_dtypes = event["input_dtypes"]
443
+ self.output_dtypes = event["output_dtypes"]
444
+ self.time_created_ns = event["time_created_ns"]
445
+ self.collective_frames = event.get("frames", [])
446
+ self.is_verbose = os.getenv("FR_TRACE_VERBOSE_OUTPUT", "0") == "1"
447
+
448
+ def _init_global_src_dst(self, pg_ranks: set[Any]) -> None:
449
+ pg_ranks_sorted = sorted(pg_ranks)
450
+ self._src_g = pg_ranks_sorted[self._src] if self._src is not None else None
451
+ self._dst_g = pg_ranks_sorted[self._dst] if self._dst is not None else None
452
+
453
+ @property
454
+ def src(self) -> int:
455
+ assert self.type in P2P, "can't get src of non-p2p op"
456
+ return self._src
457
+
458
+ @property
459
+ def dst(self) -> int:
460
+ assert self.type in P2P, "can't get dst of non-p2p op"
461
+ return self._dst
462
+
463
+ def __repr__(self) -> str:
464
+ p2p_info = ""
465
+ if self.type in P2P:
466
+ p2p_info = f"s={self._src_g} d={self._dst_g}"
467
+ if self.is_verbose:
468
+ verbose_info = (
469
+ f"timestamp_created={self.time_created_ns}",
470
+ p2p_info,
471
+ f"input_sizes={self.input_sizes}",
472
+ f"output_sizes={self.output_sizes}",
473
+ f"input_dtypes={self.input_dtypes}",
474
+ f"output_dtypes={self.output_dtypes}",
475
+ "collective_seq_id | p2p_seq_id="
476
+ f"{self.p2p_seq_id if self.type in P2P else self.collective_seq_id}",
477
+ f"pg_name={self.pg_name}",
478
+ f"pg_description={self.pg_desc}",
479
+ f"pg_size={self.pg_size}",
480
+ f"stack_id={self.stack_id}",
481
+ f"state={self.state}",
482
+ )
483
+ return f"{self.type}(%s)" % ", ".join(s for s in verbose_info if s)
484
+ return f"{self.type}(%sinput_sizes={self.input_sizes}, state={self.state})" % (
485
+ f"{p2p_info}, " if p2p_info else ""
486
+ )
487
+
488
+ def dtype_mismatch(self, other: "Op") -> bool:
489
+ if (
490
+ (
491
+ self.type not in ["scatter", "gather", "broadcast"]
492
+ and set(self.input_dtypes) != set(self.output_dtypes)
493
+ and self.input_sizes[0]
494
+ and self.output_sizes[0]
495
+ )
496
+ or (
497
+ self.type not in ["scatter", "broadcast"]
498
+ and set(self.input_dtypes) != set(other.input_dtypes)
499
+ and self.input_sizes[0]
500
+ and other.input_sizes[0]
501
+ )
502
+ or (
503
+ self.type not in ["gather"]
504
+ and set(self.output_dtypes) != set(other.output_dtypes)
505
+ and self.output_sizes[0]
506
+ and other.output_sizes[0]
507
+ )
508
+ ):
509
+ return True
510
+ return False
511
+
512
+ def match(self, other: "Op") -> MatchInfo:
513
+ # TODO: I think this can validly not match,
514
+ # e.g. if one PG was used for p2p ops between only some of the peers?
515
+ # if self.seq_id != other.seq_id:
516
+ # return False
517
+
518
+ if self.type == "send":
519
+ # TODO: We need more states for p2p ops.
520
+ return (
521
+ MatchInfo(MatchState.FULLY_MATCHED)
522
+ if (
523
+ other.type == "recv"
524
+ and self.src == other.src
525
+ and self.dst == other.dst
526
+ and self.input_sizes == other.output_sizes
527
+ )
528
+ else MatchInfo(MatchState.SIZE_OR_SYNTAX_MISMATCH)
529
+ )
530
+ elif self.type == "recv":
531
+ return (
532
+ MatchInfo(MatchState.FULLY_MATCHED)
533
+ if (
534
+ other.type == "send"
535
+ and self.src == other.src
536
+ and self.dst == other.dst
537
+ and self.output_sizes == other.input_sizes
538
+ )
539
+ else MatchInfo(MatchState.SIZE_OR_SYNTAX_MISMATCH)
540
+ )
541
+ elif self.type in COLLECTIVES:
542
+ if self.type != other.type:
543
+ return MatchInfo(
544
+ MatchState.COLLECTIVE_TYPE_MISMATCH,
545
+ f"Expected collective type: '{self.type}' does not match found collective type: '{other.type}'",
546
+ )
547
+ if (
548
+ self.type not in ["all_to_all", "scatter"]
549
+ and self.input_sizes != other.input_sizes
550
+ ):
551
+ return MatchInfo(
552
+ MatchState.SIZE_OR_SYNTAX_MISMATCH,
553
+ f"Expected input sizes: '{self.input_sizes}' does not match found input sizes: "
554
+ f"'{other.input_sizes}'",
555
+ )
556
+ if (
557
+ self.type not in ["all_to_all", "gather"]
558
+ and self.output_sizes != other.output_sizes
559
+ ):
560
+ return MatchInfo(
561
+ MatchState.SIZE_OR_SYNTAX_MISMATCH,
562
+ f"Expected output sizes: '{self.output_sizes}' does not match found output sizes: "
563
+ f"'{other.output_sizes}'",
564
+ )
565
+ if (
566
+ self.type in ["all_reduce", "allreduce_coalesced"]
567
+ and self.input_sizes != other.output_sizes
568
+ ):
569
+ return MatchInfo(
570
+ MatchState.SIZE_OR_SYNTAX_MISMATCH,
571
+ f"Expected input sizes: '{self.input_sizes}' does not match found output sizes: '{other.output_sizes}'",
572
+ )
573
+ if (
574
+ self.type
575
+ in [
576
+ "all_gather",
577
+ "all_gather_base",
578
+ "all_gather_into_tensor_coalesced",
579
+ ]
580
+ and math.prod(other.output_sizes[0])
581
+ != math.prod(self.input_sizes[0]) * self.pg_size
582
+ ):
583
+ return MatchInfo(
584
+ MatchState.SIZE_OR_SYNTAX_MISMATCH,
585
+ f"Found input numel '{math.prod(other.input_sizes[0])} * pg size {self.pg_size}' "
586
+ f"does not match output numel '{math.prod(other.output_sizes[0])}'",
587
+ )
588
+ if (
589
+ self.type
590
+ in [
591
+ "reduce_scatter",
592
+ "_reduce_scatter_base",
593
+ "reduce_scatter_tensor_coalesced",
594
+ ]
595
+ and math.prod(other.input_sizes[0])
596
+ != math.prod(self.output_sizes[0]) * self.pg_size
597
+ ):
598
+ return MatchInfo(
599
+ MatchState.SIZE_OR_SYNTAX_MISMATCH,
600
+ f"Found input numel '{math.prod(other.input_sizes[0])}' does not match output numel "
601
+ f"'{math.prod(other.output_sizes[0])} * pg size {self.pg_size}'",
602
+ )
603
+ if self.dtype_mismatch(other):
604
+ return MatchInfo(
605
+ MatchState.COLLECTIVE_DTYPE_MISMATCH,
606
+ f"Expected dtypes: '{set(self.input_dtypes)}' does not "
607
+ f"match found dtype: '{set(self.output_dtypes)}/"
608
+ f"{set(other.input_dtypes)}/{set(other.output_dtypes)}'",
609
+ )
610
+ if self.state != other.state:
611
+ # MatchState()
612
+ return MatchInfo(
613
+ MatchState.COLLECTIVE_STATE_MISMATCH,
614
+ f"Expected state: '{self.state}' does not match found state: '{other.state}'",
615
+ )
616
+ if self.type == "all_to_all":
617
+ return MatchInfo(MatchState.UNDECIDED)
618
+ elif self.type in [
619
+ "coalesced",
620
+ "ALLGATHER_coalesced",
621
+ "REDUCE_SCATTER_coalesced",
622
+ ]:
623
+ return (
624
+ MatchInfo(MatchState.FULLY_MATCHED)
625
+ if (other.type == self.type)
626
+ else MatchInfo(MatchState.SIZE_OR_SYNTAX_MISMATCH)
627
+ )
628
+ return MatchInfo(MatchState.FULLY_MATCHED)
629
+
630
+
631
+ class MatchStateRecord:
632
+ def __init__(
633
+ self,
634
+ expected_ranks: set[int],
635
+ other_ranks: list[int],
636
+ entry_state: EntryState,
637
+ candidate_ranks: set[int],
638
+ candidate_idx: dict[int, int],
639
+ found_ranks: set[int],
640
+ found_idx: dict[int, int],
641
+ errors: set[tuple[int, MatchInfo]],
642
+ ) -> None:
643
+ self.expected_ranks = expected_ranks
644
+ self.other_ranks = other_ranks
645
+ self.entry_state = entry_state
646
+ self.candidate_ranks = candidate_ranks
647
+ self.candidate_idx = candidate_idx
648
+ self.found_ranks = found_ranks
649
+ self.found_idx = found_idx
650
+ self.errors = errors
651
+ self.has_undecided_case = False
652
+
653
+ def reset_for_coalesced(
654
+ self, entry_state: EntryState, candidate_ranks: set[int]
655
+ ) -> None:
656
+ self.entry_state = entry_state
657
+ self.candidate_ranks = candidate_ranks
658
+ self.candidate_idx = {}
659
+ self.found_ranks = set()
660
+ self.found_idx = {}
661
+ self.errors = set()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/components/utils.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import argparse
8
+ import math
9
+ from typing import Any
10
+
11
+ from torch.distributed.flight_recorder.components.fr_logger import FlightRecorderLogger
12
+ from torch.distributed.flight_recorder.components.types import (
13
+ Collective,
14
+ EntryState,
15
+ Group,
16
+ MatchInfo,
17
+ MatchState,
18
+ MatchStateRecord,
19
+ Membership,
20
+ Op,
21
+ P2P,
22
+ )
23
+
24
+
25
+ __all__ = [
26
+ "add_stack_id_in_entries",
27
+ "align_trace_from_beginning",
28
+ "check_current_entry_match",
29
+ "check_no_missing_dump_files",
30
+ "check_version",
31
+ "error_analysis",
32
+ "find_coalesced_group",
33
+ "find_coalesced_group_with_non_p2p",
34
+ "get_version_detail",
35
+ "just_print_entries",
36
+ "match_coalesced_groups_with_non_p2p",
37
+ "match_coalesced_groups",
38
+ "format_frame",
39
+ "format_frames",
40
+ "match_one_event",
41
+ "check_size_alltoall",
42
+ ]
43
+
44
+ logger: FlightRecorderLogger = FlightRecorderLogger()
45
+
46
+
47
+ try:
48
+ from tabulate import tabulate
49
+ except ModuleNotFoundError:
50
+ logger.debug("tabulate is not installed. Proceeding without it.")
51
+
52
+
53
+ def format_frame(frame: dict[str, str]) -> str:
54
+ name = frame["name"]
55
+ filename = frame["filename"]
56
+ line = frame["line"]
57
+ return f"{name} at {filename}:{line}"
58
+
59
+
60
+ def format_frames(frames: list[dict[str, str]]) -> str:
61
+ formatted_frames = []
62
+ for frame in frames:
63
+ # pyrefly: ignore [bad-argument-type]
64
+ formatted_frames.append(format_frame(frame))
65
+ return "\n".join(formatted_frames)
66
+
67
+
68
+ def match_one_event(
69
+ event_a: dict[Any, Any],
70
+ event_b: dict[Any, Any],
71
+ memberships: dict[str, set[Any]],
72
+ pg_name: str,
73
+ ) -> MatchInfo:
74
+ op_a = Op(event_a, memberships, pg_name)
75
+ op_b = Op(event_b, memberships, pg_name)
76
+ return op_a.match(op_b)
77
+
78
+
79
+ def match_coalesced_groups(
80
+ all_rank_events: dict[Any, Any],
81
+ group_size: int,
82
+ groups: dict[str, Group],
83
+ memberships: dict[str, set[Any]],
84
+ _pg_guids: dict[tuple[str, int], str],
85
+ ) -> bool:
86
+ """
87
+ all_rank_events: {
88
+ rank: [
89
+ (idx, event_dict)
90
+ ]
91
+ }
92
+
93
+ Note: it is possible for event dicts in a coalesced group to be asymmetric.
94
+ e.g. the following events lists form a valid coalescing group
95
+ events0 [send:1]
96
+ events1 [recv:0, send:2]
97
+ events2 [recv:1]
98
+
99
+ Rule 1: all ops should find a match
100
+ Rule 2: relative ordering of sends and recvs in one event list can be arbitrary
101
+ e.g.
102
+ events1 [recv:0, send:2] —> okay
103
+ events1 [send:2, recv:0] —> also okay
104
+ Rule 3: sends to the same dest or recvs from the src should be in a consistent order
105
+ e.g.
106
+ rank0 [send:1 (100B), send:1 (1000B)]
107
+ rank1 [recv:0 (1000B), recv:0 (100B)] —> not okay
108
+ """
109
+ all_ops = {
110
+ rank: [
111
+ Op(e, memberships, _pg_guids[(e["process_group"][0], rank)])
112
+ for i, e in all_rank_events[rank]
113
+ ]
114
+ for rank in all_rank_events
115
+ }
116
+
117
+ def visualize_ops(
118
+ match: bool,
119
+ _pg_guids: dict[tuple[str, int], str],
120
+ ) -> None:
121
+ all_ops = {
122
+ rank: [
123
+ Op(e, memberships, _pg_guids[(e["process_group"][0], rank)])
124
+ for i, e in all_rank_events[rank]
125
+ ]
126
+ for rank in all_rank_events
127
+ }
128
+
129
+ i = 0
130
+ row = []
131
+ progress = True
132
+ table = []
133
+ while progress:
134
+ progress = False
135
+ for r in all_ops:
136
+ if len(all_ops[r]) > i:
137
+ rank, event = all_rank_events[r][i]
138
+ # Check if the pg_guid exists for this rank and process group
139
+ pg_key = (event["process_group"][0], rank)
140
+ if pg_key in _pg_guids:
141
+ row.append(
142
+ Op(
143
+ event,
144
+ memberships,
145
+ _pg_guids[pg_key],
146
+ )
147
+ )
148
+ else:
149
+ # Skip this entry if pg_guid mapping doesn't exist
150
+ row.append(None) # type: ignore[arg-type]
151
+ progress = True
152
+ else:
153
+ row.append(None) # type: ignore[arg-type]
154
+ table.append(row)
155
+ row = []
156
+ i += 1
157
+ title = "Match" if match else "MISMATCH"
158
+ logger.info("%s \n", title)
159
+ logger.info("%s", tabulate(table)) # type: ignore[operator]
160
+
161
+ # TODO can't verify seq_id bc there might have been valid seq deltas between ranks even within a pg.
162
+ for op_list in all_ops.values():
163
+ if not op_list:
164
+ # print("TODO- not sure if its valid for only some ranks in a PG to participate in a coalesced op?")
165
+ return False
166
+ assert op_list[-1].type == "coalesced"
167
+ op_list.pop(-1)
168
+
169
+ while all_ops:
170
+ first_rank = next(iter(all_ops))
171
+ my_ops = all_ops[first_rank]
172
+
173
+ if len(all_ops[first_rank]) == 0:
174
+ all_ops.pop(first_rank)
175
+ continue
176
+
177
+ # lets match the first collective! we need to know which ranks are involved, and ensure that this same
178
+ # collective is also the first one on those ranks within that group
179
+ op = my_ops[0]
180
+ match_idx = -1
181
+ if op.type in P2P:
182
+ dst_global_rank = sorted(memberships[op.pg_name])[op.dst]
183
+ peer_ops = all_ops[dst_global_rank]
184
+ for i, other in enumerate(peer_ops):
185
+ if op.match(other).state == MatchState.FULLY_MATCHED:
186
+ match_idx = i
187
+ break
188
+ elif op.dst == other.src:
189
+ # Rule 3
190
+ break
191
+ else:
192
+ # Rule 1
193
+ continue
194
+ else:
195
+ raise NotImplementedError("coalesced collective ops")
196
+ if match_idx >= 0:
197
+ my_ops.pop(0)
198
+ peer_ops.pop(match_idx)
199
+ else:
200
+ visualize_ops(False, _pg_guids)
201
+ return False
202
+
203
+ visualize_ops(True, _pg_guids)
204
+ return True
205
+
206
+
207
+ # We enabled the creating FR entry for non-P2P slow path collective ops in v2.7.
208
+ def match_coalesced_groups_with_non_p2p(
209
+ all_rank_events: dict[Any, Any],
210
+ pg_info: tuple[str, str],
211
+ memberships: dict[str, set[Any]],
212
+ _pg_guids: dict[tuple[str, int], str],
213
+ mismatch: dict[str, int],
214
+ dumps_ranks: set[int],
215
+ version: str,
216
+ collectives: list[Collective],
217
+ match_record: MatchStateRecord,
218
+ ) -> bool:
219
+ """
220
+ all_rank_events: {
221
+ rank: [
222
+ (idx, event_dict)
223
+ ]
224
+ }
225
+
226
+ Note: it is possible for event dicts in a coalesced group to be asymmetric.
227
+ e.g. the following events lists form a valid coalescing group
228
+ events0 [send:1]
229
+ events1 [recv:0, send:2]
230
+ events2 [recv:1]
231
+
232
+ Rule 1: all ops should find a match
233
+ Rule 2: relative ordering of sends and recvs in one event list can be arbitrary
234
+ e.g.
235
+ events1 [recv:0, send:2] —> okay
236
+ events1 [send:2, recv:0] —> also okay
237
+ Rule 3: sends to the same dest or recvs from the src should be in a consistent order
238
+ e.g.
239
+ rank0 [send:1 (100B), send:1 (1000B)]
240
+ rank1 [recv:0 (1000B), recv:0 (100B)] —> not okay
241
+ """
242
+ all_ops = {
243
+ rank: [
244
+ Op(e, memberships, _pg_guids[(e["process_group"][0], rank)])
245
+ for _, e in all_rank_events[rank]
246
+ ]
247
+ for rank in all_rank_events
248
+ }
249
+ is_p2p = any(op.type in P2P for ops in all_ops.values() for op in ops)
250
+ pg_name = pg_info[0]
251
+
252
+ def visualize_ops(
253
+ match: bool,
254
+ _pg_guids: dict[tuple[str, int], str],
255
+ ) -> None:
256
+ all_ops = {
257
+ rank: [
258
+ Op(e, memberships, _pg_guids[(e["process_group"][0], rank)])
259
+ for _, e in all_rank_events[rank]
260
+ ]
261
+ for rank in all_rank_events
262
+ }
263
+
264
+ i = 0
265
+ row = []
266
+ progress = True
267
+ table = []
268
+ while progress:
269
+ progress = False
270
+ for r in all_ops:
271
+ if len(all_ops[r]) > i:
272
+ rank, event = all_rank_events[r][i]
273
+ # Check if the pg_guid exists for this rank and process group
274
+ pg_key = (event["process_group"][0], rank)
275
+ if pg_key in _pg_guids:
276
+ row.append(
277
+ Op(
278
+ event,
279
+ memberships,
280
+ _pg_guids[pg_key],
281
+ )
282
+ )
283
+ else:
284
+ # Skip this entry if pg_guid mapping doesn't exist
285
+ row.append(None) # type: ignore[arg-type]
286
+ progress = True
287
+ else:
288
+ row.append(None) # type: ignore[arg-type]
289
+ table.append(row)
290
+ row = []
291
+ i += 1
292
+ title = "Match" if match else "MISMATCH"
293
+ logger.info("%s \n", title)
294
+ logger.info("%s", tabulate(table)) # type: ignore[operator]
295
+
296
+ # TODO Need to verify no seq_id deltas for P2P ops.
297
+ for rank, op_list in all_ops.items():
298
+ if not op_list:
299
+ logger.error("Rank %s has an empty op list.", rank)
300
+ continue
301
+ if op_list[-1].type == "coalesced" and is_p2p:
302
+ op_list.pop(-1)
303
+
304
+ while all_ops:
305
+ first_rank = next(iter(all_ops))
306
+ my_ops = all_ops[first_rank]
307
+
308
+ if len(all_ops[first_rank]) == 0:
309
+ all_ops.pop(first_rank)
310
+ continue
311
+
312
+ # lets match the first collective! we need to know which ranks are involved, and ensure that this same
313
+ # collective is also the first one on those ranks within that group
314
+ op = my_ops[0]
315
+ match_idx = -1
316
+ if is_p2p:
317
+ dst_global_rank = sorted(memberships[op.pg_name])[op.dst]
318
+ peer_ops = all_ops[dst_global_rank]
319
+ for i, other in enumerate(peer_ops):
320
+ if op.match(other).state == MatchState.FULLY_MATCHED:
321
+ match_idx = i
322
+ break
323
+ elif op.dst == other.src:
324
+ # Rule 3
325
+ break
326
+ else:
327
+ # Rule 1
328
+ continue
329
+ if match_idx >= 0:
330
+ my_ops.pop(0)
331
+ peer_ops.pop(match_idx)
332
+ else:
333
+ visualize_ops(False, _pg_guids)
334
+ return False
335
+ else:
336
+ all_coalesced_entries = {
337
+ rank: [e for _, e in all_rank_events[rank]] for rank in all_rank_events
338
+ }
339
+ current_entry = all_coalesced_entries[first_rank][0]
340
+ my_ops.pop(0)
341
+
342
+ match_record.reset_for_coalesced(
343
+ EntryState(current_entry, match_record.expected_ranks),
344
+ {first_rank},
345
+ )
346
+
347
+ # Iterate through all the ranks and check if there is a mismatch for the current entry.
348
+ check_current_entry_match(
349
+ all_coalesced_entries,
350
+ _pg_guids,
351
+ pg_info,
352
+ current_entry,
353
+ memberships,
354
+ mismatch,
355
+ match_record,
356
+ )
357
+
358
+ # Use heuristics to decide what type of errors and error messages we should print.
359
+ error_analysis(
360
+ all_coalesced_entries,
361
+ match_record,
362
+ dumps_ranks,
363
+ first_rank,
364
+ current_entry,
365
+ mismatch,
366
+ get_version_detail(version),
367
+ pg_info[0],
368
+ )
369
+
370
+ # TODO: For now, we only check the correctness of individual collective within a coalesced one in
371
+ # this script. We need to merge (e.g, input/output sizes) together
372
+ # for downstream consumer.
373
+
374
+ # at this point there are 3 possibilities
375
+ # 1. we found a match on all the ranks that are members of the group
376
+ # -> we create a Collective and remove the individual entries from their original lists
377
+ if (
378
+ match_record.found_ranks == match_record.expected_ranks
379
+ and mismatch[pg_name] == 0
380
+ ):
381
+ # Just pop out this collective.
382
+ idx_map = {
383
+ r: match_record.found_idx[r] if r != first_rank else 0
384
+ for r in match_record.found_ranks
385
+ }
386
+ for i, k in idx_map.items():
387
+ all_rank_events[i].pop(k)
388
+ for r in match_record.found_ranks:
389
+ if r != first_rank:
390
+ all_ops[r].pop(0)
391
+
392
+ # 2. we found a partial match but some ranks are missing
393
+ # 3. we found no match
394
+ # -> since its not a complete collective, no entry goes into collectives but we still record a nccl call
395
+ else:
396
+ logger.debug("Non-matching collective inside coalesced group")
397
+ idx_map = {
398
+ r: match_record.candidate_idx[r] if r != first_rank else 0
399
+ for r in match_record.candidate_ranks
400
+ }
401
+ collectives.append(
402
+ match_record.entry_state.to_collective(
403
+ len(collectives),
404
+ errors=match_record.errors,
405
+ idx_map=idx_map,
406
+ all_entries=all_coalesced_entries,
407
+ )
408
+ )
409
+ return False
410
+
411
+ if is_p2p:
412
+ visualize_ops(True, _pg_guids)
413
+ return True
414
+
415
+
416
+ def check_size_alltoall(alltoall_cases: list[dict[str, Any]]) -> tuple[bool, int, int]:
417
+ input_numel = 0
418
+ output_numel = 0
419
+ for e in alltoall_cases:
420
+ input_numel += math.prod(e["input_sizes"][0])
421
+ output_numel += math.prod(e["output_sizes"][0])
422
+ return input_numel != output_numel, input_numel, output_numel
423
+
424
+
425
+ def check_current_entry_match(
426
+ all_entries: dict[int, list[dict[str, Any]]],
427
+ _pg_guids: dict[tuple[str, int], str],
428
+ pg_info: tuple[str, str],
429
+ current_entry: dict[str, Any],
430
+ _memberships: dict[str, set[Any]],
431
+ mismatch: dict[str, int],
432
+ match_record: MatchStateRecord,
433
+ ) -> None:
434
+ pg_name, desc = pg_info[0], pg_info[1]
435
+ for o in match_record.expected_ranks.intersection(set(match_record.other_ranks)):
436
+ for i, e in enumerate(all_entries[o]): # type: ignore[index]
437
+ # step over ops from other PGs
438
+ # only check match state when seq_id matches
439
+ if (
440
+ _pg_guids[(e["process_group"][0], o)] == pg_name
441
+ and e["process_group"][1] == desc
442
+ and e["collective_seq_id"] == match_record.entry_state.collective_seq_id
443
+ ):
444
+ match_info = match_one_event(current_entry, e, _memberships, pg_name)
445
+ if (
446
+ match_info.state in [MatchState.FULLY_MATCHED, MatchState.UNDECIDED]
447
+ and mismatch[pg_name] == 0
448
+ ):
449
+ match_record.found_ranks.add(o)
450
+ match_record.found_idx[o] = i
451
+ match_record.has_undecided_case = (
452
+ match_info.state == MatchState.UNDECIDED
453
+ )
454
+ else:
455
+ match_record.candidate_ranks.add(o)
456
+ match_record.candidate_idx[o] = i
457
+ if match_info.state not in [
458
+ MatchState.FULLY_MATCHED,
459
+ MatchState.UNDECIDED,
460
+ ]:
461
+ # Here we assume the current rank is not the source of the error.
462
+ # But it's possible that the current rank is the culprit, then users will
463
+ # see lots of normal ranks reported as culprit.
464
+ # TODO: we need to figure out a better way to handle the case mentioned above.
465
+ match_record.errors.add((o, match_info))
466
+ break
467
+
468
+
469
+ def error_analysis(
470
+ all_entries: dict[int, list[dict[str, Any]]],
471
+ match_record: MatchStateRecord,
472
+ dumps_ranks: set[int],
473
+ first_rank: int,
474
+ current_entry: dict[str, Any],
475
+ mismatch: dict[str, int],
476
+ version: tuple[int, int],
477
+ pg_name: str,
478
+ ) -> None:
479
+ major_v, minor_v = version[0], version[1]
480
+ # case one: not every rank join the collective or in the flight recorder.
481
+ if (
482
+ match_record.candidate_ranks | match_record.found_ranks
483
+ ) != match_record.expected_ranks and match_record.expected_ranks - (
484
+ match_record.candidate_ranks | match_record.found_ranks
485
+ ) <= dumps_ranks:
486
+ mismatch[pg_name] += 1
487
+ logger_msg = "Not all ranks joining collective, sequence number: %s"
488
+ missing_ranks = match_record.expected_ranks - (
489
+ match_record.candidate_ranks | match_record.found_ranks
490
+ )
491
+ match_record.entry_state.log(
492
+ logger, logger_msg, format_frames, missing_ranks=missing_ranks
493
+ )
494
+ match_record.candidate_ranks.update(match_record.found_ranks)
495
+ match_record.candidate_idx.update(match_record.found_idx)
496
+ match_record.found_idx.clear()
497
+ match_record.found_ranks.clear()
498
+ # We didn't see any mismatch and all expected ranks are in the dump.
499
+ elif len(
500
+ match_record.candidate_ranks
501
+ ) == 1 and match_record.expected_ranks.issubset(dumps_ranks):
502
+ # case two: alltoall or alltoall_base case.
503
+ if match_record.has_undecided_case:
504
+ alltoall_cases = [current_entry] + [
505
+ all_entries[o][match_record.found_idx[o]]
506
+ for o in match_record.found_ranks
507
+ ]
508
+ fail_check, total_input_numel, total_output_numel = check_size_alltoall(
509
+ alltoall_cases
510
+ )
511
+ if major_v <= 2 and minor_v <= 3:
512
+ # We don't log the input/output sizes for alltoall before v2.4,
513
+ # so we don't consider the size mismatch as an error for now.
514
+ fail_check = False
515
+ if fail_check:
516
+ # When we see errors in all_to_all, it's hard to tell which rank is the source of the error.
517
+ mismatch[pg_name] += 1
518
+ logger_msg = (
519
+ "Input/output mismatch in the collective sequence number: %s"
520
+ )
521
+ match_record.entry_state.log(
522
+ logger,
523
+ logger_msg,
524
+ format_frames,
525
+ total_numel=(total_input_numel, total_output_numel),
526
+ )
527
+ match_record.candidate_ranks.update(match_record.found_ranks)
528
+ match_record.candidate_idx.update(match_record.found_idx)
529
+ match_record.found_idx.clear()
530
+ match_record.found_ranks.clear()
531
+ match_record.errors.add(
532
+ (first_rank, MatchInfo(MatchState.SIZE_OR_SYNTAX_MISMATCH))
533
+ )
534
+ else:
535
+ match_record.found_ranks.update(match_record.candidate_ranks)
536
+ match_record.found_idx.update(match_record.candidate_idx)
537
+ match_record.candidate_idx.clear()
538
+ match_record.candidate_ranks.clear()
539
+ # case three: all joined and everything matches on all ranks.
540
+ else:
541
+ match_record.found_ranks.update(match_record.candidate_ranks)
542
+ match_record.found_idx.update(match_record.candidate_idx)
543
+ match_record.candidate_idx.clear()
544
+ match_record.candidate_ranks.clear()
545
+ # case four: mismatch cases due to not same type, size mismatch or state mismatch.
546
+ elif len(match_record.errors) > 0:
547
+ mismatch[pg_name] += 1
548
+ logger_msg = "Collective sequence number: %s has errors"
549
+ match_record.entry_state.log(
550
+ logger, logger_msg, format_frames, errors=match_record.errors
551
+ )
552
+ match_record.candidate_ranks.update(match_record.found_ranks)
553
+ match_record.candidate_idx.update(match_record.found_idx)
554
+ match_record.found_idx.clear()
555
+ match_record.found_ranks.clear()
556
+ # partial analysis case when we cannot decide what's wrong with this collective entry.
557
+ else:
558
+ match_record.candidate_ranks.update(match_record.found_ranks)
559
+ match_record.candidate_idx.update(match_record.found_idx)
560
+ match_record.found_idx.clear()
561
+ match_record.found_ranks.clear()
562
+ # if any element in expected_ranks not in dumps_ranks.
563
+ if match_record.expected_ranks - dumps_ranks:
564
+ mismatch[pg_name] += 1
565
+ logger.info(
566
+ "We cannot decide what's wrong with this collective entry "
567
+ "because we missed FR dumps from ranks (%s) so we don't have enough "
568
+ "information. If you want to debug further use -j to dump all raw trace",
569
+ str(match_record.expected_ranks - dumps_ranks),
570
+ )
571
+ else:
572
+ logger.info(
573
+ "No errors found for this collective entry, There could be some "
574
+ "other reasons why we see collective timeout."
575
+ )
576
+
577
+
578
+ def find_coalesced_group(
579
+ pg_name: str,
580
+ entries: list[dict[str, Any]],
581
+ _pg_guids: dict[tuple[str, int], str],
582
+ rank: int,
583
+ ) -> list[tuple[int, dict[str, Any]]]:
584
+ """Given a list of entries, if the collective_seq_id of the first entry matches that of subsequent ones,
585
+ build an return a list of entries terminating in a 'coalesced' op entry all sharing a collective_seq_id
586
+ """
587
+ found = []
588
+ collective_seq_id = None
589
+ for i, e in enumerate(entries):
590
+ if _pg_guids[(e["process_group"][0], rank)] != pg_name:
591
+ continue
592
+ elif collective_seq_id is None:
593
+ collective_seq_id = (
594
+ e["p2p_seq_id"] if e["is_p2p"] else e["collective_seq_id"]
595
+ )
596
+ found.append((i, e))
597
+ elif not e["is_p2p"] and e["collective_seq_id"] == collective_seq_id:
598
+ found.append((i, e))
599
+ elif e["is_p2p"] and e["p2p_seq_id"] == collective_seq_id:
600
+ found.append((i, e))
601
+ else:
602
+ break
603
+
604
+ if len(found) > 1:
605
+ assert found[-1][1]["profiling_name"] == "nccl:coalesced"
606
+ return found
607
+ return []
608
+
609
+
610
+ # We enabled the creating FR entry for non-P2P slow path collective ops in v2.7.
611
+ def find_coalesced_group_with_non_p2p(
612
+ pg_name: str,
613
+ entries: list[dict[str, Any]],
614
+ _pg_guids: dict[tuple[str, int], str],
615
+ rank: int,
616
+ ) -> list[tuple[int, dict[str, Any]]]:
617
+ """Given a list of entries, if the collective_seq_id of the first entry matches that of subsequent ones,
618
+ build an return a list of entries terminating in a 'coalesced' op entry all sharing a collective_seq_id
619
+ """
620
+ found = []
621
+ collective_seq_id = None
622
+ for i, e in enumerate(entries):
623
+ if _pg_guids[(e["process_group"][0], rank)] != pg_name:
624
+ continue
625
+ elif collective_seq_id is None:
626
+ collective_seq_id = (
627
+ e["p2p_seq_id"] if e["is_p2p"] else e["collective_seq_id"]
628
+ )
629
+ found.append((i, e))
630
+ elif not e["is_p2p"] and e["collective_seq_id"] == collective_seq_id:
631
+ found.append((i, e))
632
+ elif e["is_p2p"] and e["p2p_seq_id"] == collective_seq_id:
633
+ found.append((i, e))
634
+ else:
635
+ break
636
+
637
+ if len(found) > 1:
638
+ name = found[-1][1]["profiling_name"]
639
+ if name.startswith("nccl:") and not name.endswith("_coalesced"):
640
+ logger.error("Rank %s does not have a coalesced end.", rank)
641
+ return found
642
+ return []
643
+
644
+
645
+ def just_print_entries(
646
+ all_entries: dict[int, list[dict[str, Any]]],
647
+ _groups: dict[str, Group],
648
+ _memberships: dict[str, set[Any]],
649
+ _pg_guids: dict[tuple[str, int], str],
650
+ args: argparse.Namespace,
651
+ stack_id_trace_map: dict[str, int],
652
+ ) -> None:
653
+ rows = []
654
+ ranks = sorted(all_entries.keys())
655
+ headers = [
656
+ f"Rank {rank}"
657
+ for rank in ranks
658
+ if args.selected_ranks is None or rank in args.selected_ranks
659
+ ]
660
+ progress = True
661
+ while progress:
662
+ progress = False
663
+ row = []
664
+ for rank in ranks:
665
+ if args.selected_ranks is not None and rank not in args.selected_ranks:
666
+ continue
667
+ if len(all_entries[rank]) == 0:
668
+ row.append("")
669
+ else:
670
+ entry = all_entries[rank].pop(0)
671
+ pg_name = _pg_guids[(entry["process_group"][0], rank)]
672
+ if (
673
+ args.pg_filters is None
674
+ or entry["process_group"][1] in args.pg_filters
675
+ or entry["process_group"][0] in args.pg_filters
676
+ ):
677
+ row.append(str(Op(entry, _memberships, pg_name)))
678
+ else:
679
+ row.append("")
680
+ progress = True
681
+ if progress:
682
+ rows.append(row)
683
+
684
+ logger.info(tabulate(rows, headers=headers))
685
+
686
+ if stack_id_trace_map and args.print_stack_trace:
687
+ headers = ["stack_id", "frame_stack"]
688
+ rows = []
689
+
690
+ for frame, stack_id in sorted(
691
+ stack_id_trace_map.items(), key=lambda item: item[1]
692
+ ):
693
+ rows.append([str(stack_id), frame])
694
+
695
+ logger.info(tabulate(rows, headers=headers))
696
+
697
+
698
+ def check_no_missing_dump_files(
699
+ entries: dict[int, Any], memberships: list[Membership]
700
+ ) -> None:
701
+ all_ranks = set()
702
+ for membership in memberships:
703
+ all_ranks.add(int(membership.global_rank))
704
+ dumps_ranks = {int(key) for key in entries}
705
+ missing = all_ranks - dumps_ranks
706
+ assert len(missing) == 0, f"Missing dump files from ranks {missing}"
707
+
708
+
709
+ def check_version(version_by_ranks: dict[str, str], version: str) -> None:
710
+ for rank, v in version_by_ranks.items():
711
+ assert v == version, (
712
+ f"Rank {rank} has different version {v} from the given version {version}"
713
+ )
714
+
715
+
716
+ def get_version_detail(version: str) -> tuple[int, int]:
717
+ # pyrefly: ignore [bad-assignment]
718
+ version = version.split(".")
719
+ assert len(version) == 2, f"Invalid version {version}"
720
+ major, minor = map(int, version)
721
+ return major, minor
722
+
723
+
724
+ def add_stack_id_in_entries(
725
+ entries: dict[int, list[dict[str, Any]]],
726
+ ) -> tuple[dict[int, list[dict[str, Any]]], dict[str, int]]:
727
+ stack_id = 0
728
+ stack_id_trace_map = {}
729
+ for rank in entries:
730
+ for dump in entries[rank]:
731
+ if dump.get("frames", []):
732
+ frames = str(dump["frames"])
733
+ if frames not in stack_id_trace_map:
734
+ stack_id_trace_map[frames] = stack_id
735
+ dump["stack_id"] = stack_id
736
+ stack_id += 1
737
+ else:
738
+ dump["stack_id"] = stack_id_trace_map[frames]
739
+ else:
740
+ dump["stack_id"] = -1
741
+
742
+ return entries, stack_id_trace_map
743
+
744
+
745
+ def align_trace_from_beginning(
746
+ entries: dict[int, list[dict[str, Any]]],
747
+ ) -> dict[int, list[dict[str, Any]]]:
748
+ """
749
+ Align the trace entries by record ID for entries.
750
+ This function takes a dictionary of rank names to lists of trace entries as input.
751
+ Each trace entry is a dictionary containing information about a collective operation,
752
+ including its unique identifier (`record_id` is monotonically increasing as we write into the ring buffer).
753
+ The function finds the largest starting point across all ranks by taking the maximum
754
+ `record_id` value of the first entry in each rank. Finally, it filters out any
755
+ entries with `record_id` values less than the maximum starting point.
756
+ The function returns the updated dictionary of sorted and filtered trace entries.
757
+
758
+ Args:
759
+ entries (Dict[str, List[Dict[str, Any]]]): A dictionary of rank names to lists of trace entries.
760
+
761
+ Returns:
762
+ entries (Dict[str, List[Dict[str, Any]]]): Entries sorted by record ID and filtered by the maximum starting point.
763
+ """
764
+
765
+ maximum_starting_record_id = 0
766
+ for rank in entries:
767
+ # Although this is a ring buffer, we already sort the entries by `record_id` when dumping, we just
768
+ # need to find the largest starting point. For example, if the buffer has the following entries:
769
+ # Rank 0: [0, 1, 2, 3, 4, 5, 6]
770
+ # Rank 1: [1, 2, 3, 4, 5, 6, 7]
771
+ # Rank 2: [2, 3, 4, 5, 6, 7, 8]
772
+ # Rank 3: [0, 1, 2, 3, 4, 5, None]
773
+ # Then we should start from collective 2 not 0 because any collective before,
774
+ # we don't have complete records from all ranks so we need to ignore them.
775
+ # If we don't have any trace from some ranks, ignore them
776
+ # as well.
777
+ if len(entries[rank]) == 0:
778
+ continue
779
+ first_record_id = entries[rank][0]["record_id"]
780
+ maximum_starting_record_id = max(maximum_starting_record_id, first_record_id)
781
+
782
+ for rank in entries:
783
+ entries[rank] = [
784
+ entry
785
+ for entry in entries[rank]
786
+ if entry["record_id"] >= maximum_starting_record_id
787
+ ]
788
+
789
+ return entries
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/flight_recorder/fr_trace.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Flight Recorder Trace Analyzer
3
+
4
+ This script primarily merges data from individual flight recorder buffers from individual ranks in a
5
+ PyTorch Distributed program into a flattened database format that can be used for further analysis.
6
+
7
+ However as part of the merging process, it is necessary to perform some analysis in order to match operators
8
+ on one rank with corresponding operators on other ranks and register them as one 'collective' entry. During this
9
+ process, a significant amount of useful information can already be extracted such as where the first mismatch occurs
10
+ in cases of desync (when not all ranks issue a compatible collective in a particular process group).
11
+
12
+
13
+ Not Yet Implemented
14
+ - TODO- tracebacks aren't implemented
15
+
16
+ Known Issues
17
+ - Flight Recorder buffer sequence_id information is not sufficient to match collectives and coalesced collectives
18
+ unless we have the trace data from the beginning of the program. To enable confident analysis of trace buffers that
19
+ do not start from zero (and to simplify the script's matching logic) we need to add more information to the recorder.
20
+ - Currently, the script omits checking the 'status' of collectives. We can look for the first 'non completed'
21
+ collective easily enough and report that.
22
+
23
+ Usage
24
+ python fr_trace.py <dump dir containing trace files> [-o <output file>]
25
+
26
+ - Omitting the optional output file will still yield analysis information to stdout
27
+ - The output file is a pickle of the flat DB, which may change in format in the future.
28
+ - This script is versioned so that we can ensure our future changes to flight recorder are backwards compatible.
29
+ """
30
+
31
+ import pickle
32
+ from collections.abc import Sequence
33
+
34
+ from torch.distributed.flight_recorder.components.builder import build_db, transform_ft
35
+ from torch.distributed.flight_recorder.components.config_manager import JobConfig
36
+ from torch.distributed.flight_recorder.components.loader import read_dir
37
+ from torch.distributed.flight_recorder.components.types import types
38
+
39
+
40
+ __all__ = ["main"]
41
+
42
+
43
+ def main(args: Sequence[str] | None = None) -> None:
44
+ config = JobConfig()
45
+ # pyrefly: ignore [bad-assignment]
46
+ args = config.parse_args(args)
47
+ # pyrefly: ignore [missing-attribute]
48
+ assert args.trace_dir, "Trace directory trace_dir is required"
49
+ # pyrefly: ignore [bad-argument-type]
50
+ details, version = read_dir(args)
51
+ # pyrefly: ignore [missing-attribute]
52
+ if args.transform_ft:
53
+ # pyrefly: ignore [missing-attribute]
54
+ assert args.group_world_size, "World size is required for transform_ft"
55
+ # pyrefly: ignore [bad-argument-type]
56
+ details = transform_ft(details, args.group_world_size)
57
+ # pyrefly: ignore [bad-argument-type]
58
+ db = build_db(details, args, version)
59
+ # pyrefly: ignore [missing-attribute]
60
+ if args.output:
61
+ # pyrefly: ignore [no-matching-overload]
62
+ with open(args.output, "wb") as f:
63
+ pickle.dump((types, db), f)
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/__init__.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._flat_param import FlatParameter as FlatParameter
2
+ from ._fully_shard import (
3
+ CPUOffloadPolicy,
4
+ FSDPModule,
5
+ fully_shard,
6
+ MixedPrecisionPolicy,
7
+ OffloadPolicy,
8
+ register_fsdp_forward_method,
9
+ share_comm_ctx,
10
+ UnshardHandle,
11
+ )
12
+ from .fully_sharded_data_parallel import (
13
+ BackwardPrefetch,
14
+ CPUOffload,
15
+ FullOptimStateDictConfig,
16
+ FullStateDictConfig,
17
+ FullyShardedDataParallel,
18
+ LocalOptimStateDictConfig,
19
+ LocalStateDictConfig,
20
+ MixedPrecision,
21
+ OptimStateDictConfig,
22
+ OptimStateKeyType,
23
+ ShardedOptimStateDictConfig,
24
+ ShardedStateDictConfig,
25
+ ShardingStrategy,
26
+ StateDictConfig,
27
+ StateDictSettings,
28
+ StateDictType,
29
+ )
30
+
31
+
32
+ __all__ = [
33
+ # FSDP1
34
+ "BackwardPrefetch",
35
+ "CPUOffload",
36
+ "FullOptimStateDictConfig",
37
+ "FullStateDictConfig",
38
+ "FullyShardedDataParallel",
39
+ "LocalOptimStateDictConfig",
40
+ "LocalStateDictConfig",
41
+ "MixedPrecision",
42
+ "OptimStateDictConfig",
43
+ "OptimStateKeyType",
44
+ "ShardedOptimStateDictConfig",
45
+ "ShardedStateDictConfig",
46
+ "ShardingStrategy",
47
+ "StateDictConfig",
48
+ "StateDictSettings",
49
+ "StateDictType",
50
+ # FSDP2
51
+ "CPUOffloadPolicy",
52
+ "FSDPModule",
53
+ "fully_shard",
54
+ "MixedPrecisionPolicy",
55
+ "OffloadPolicy",
56
+ "register_fsdp_forward_method",
57
+ "UnshardHandle",
58
+ "share_comm_ctx",
59
+ ]
60
+
61
+ # Set namespace for exposed private names
62
+ CPUOffloadPolicy.__module__ = "torch.distributed.fsdp"
63
+ FSDPModule.__module__ = "torch.distributed.fsdp"
64
+ fully_shard.__module__ = "torch.distributed.fsdp"
65
+ MixedPrecisionPolicy.__module__ = "torch.distributed.fsdp"
66
+ OffloadPolicy.__module__ = "torch.distributed.fsdp"
67
+ register_fsdp_forward_method.__module__ = "torch.distributed.fsdp"
68
+ UnshardHandle.__module__ = "torch.distributed.fsdp"
69
+ share_comm_ctx.__module__ = "torch.distributed.fsdp"
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_common_utils.py ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This file includes private common utilities for FSDP.
4
+ """
5
+
6
+ import logging
7
+ import traceback
8
+ import warnings
9
+ import weakref
10
+ from collections.abc import Callable, Generator, Iterable
11
+ from enum import auto, Enum
12
+ from functools import partial
13
+ from itertools import chain
14
+ from typing import Any, cast, no_type_check, Optional, TYPE_CHECKING
15
+
16
+ import torch
17
+ import torch.distributed as dist
18
+ import torch.distributed.fsdp._flat_param as flat_param_file
19
+ import torch.nn as nn
20
+ from torch.distributed._composable_state import _get_module_state, _State
21
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
22
+ _CHECKPOINT_PREFIX,
23
+ )
24
+ from torch.distributed.utils import _apply_to_tensors
25
+ from torch.utils._mode_utils import no_dispatch
26
+
27
+ from .api import (
28
+ FullOptimStateDictConfig,
29
+ FullStateDictConfig,
30
+ OptimStateDictConfig,
31
+ ShardingStrategy,
32
+ StateDictConfig,
33
+ StateDictType,
34
+ )
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from torch.distributed.device_mesh import DeviceMesh
39
+ from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
40
+
41
+ from ._flat_param import FlatParamHandle
42
+
43
+ FSDP_WRAPPED_MODULE = "_fsdp_wrapped_module"
44
+ FSDP_PREFIX = FSDP_WRAPPED_MODULE + "."
45
+ FSDP_FLATTENED = "_fsdp_flattened"
46
+
47
+ # Save a global mapping from module to its input tensor dtype to be populated
48
+ # during the forward pre-hook and consumed in the forward post-hook when
49
+ # overriding a module's mixed precision
50
+ # NOTE: We currently take the last input tensor's dtype in the case of multiple
51
+ # floating-point input tensors, which may be incorrect. However, since there is
52
+ # not a 1:1 correspondence between input and output tensors, we must use *some*
53
+ # heuristic like this to predict the desired output dtype.
54
+ _MODULE_TO_INP_DTYPE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
55
+
56
+
57
+ class _FSDPDeviceHandle:
58
+ """
59
+ This is a simple abstraction for FSDP computing devices,
60
+ which enables custom backends that implement CUDA-like
61
+ semantics to be integrated with FSDP.
62
+ """
63
+
64
+ def __init__(self, device: torch.device, backend: Any = None):
65
+ if backend is None:
66
+ try:
67
+ self.__backend = getattr(torch, device.type)
68
+ # pyrefly: ignore [read-only]
69
+ self.__device = device
70
+ except AttributeError as exc:
71
+ raise AttributeError(
72
+ f"Device '{device}' does not have a corresponding backend registered as 'torch.{device.type}'."
73
+ ) from exc
74
+ else:
75
+ self.__backend = backend
76
+
77
+ @classmethod
78
+ def from_device(cls, device: torch.device) -> "_FSDPDeviceHandle":
79
+ """
80
+ Return a device handle corresponding to the device, and through this handle,
81
+ operations with the same semantics as CUDA can be performed on the device.
82
+ Just return torch.cuda if the device is cuda to make attribute-access faster.
83
+ Custom backend must first register a module with the same name with {device.type} on torch.
84
+ """
85
+ if device.type == "cuda":
86
+ return cast(_FSDPDeviceHandle, torch.cuda)
87
+ elif device.type == "mtia":
88
+ return cast(_FSDPDeviceHandle, torch.mtia)
89
+ return cls(device)
90
+
91
+ def __getattr__(self, name: str, /) -> Any:
92
+ try:
93
+ return getattr(self.__backend, name)
94
+ except AttributeError as exc:
95
+ raise AttributeError(
96
+ f"Custom backend '{self.__device.type}' not implement 'torch.{self.__device.type}.{name}'"
97
+ ) from exc
98
+
99
+
100
+ class _UninitializedDeviceHandle(_FSDPDeviceHandle):
101
+ def __init__(self) -> None:
102
+ pass
103
+
104
+ def __getattribute__(self, name: str, /) -> Any:
105
+ raise RuntimeError("Trying to use an uninitialized device handle.")
106
+
107
+
108
+ class _FSDPState(_State):
109
+ def __init__(self) -> None:
110
+ # TODO: Move all the attributes to this class to enable typing for
111
+ # FSDP/fully_shard.
112
+ self._ignored_modules: set[nn.Module] = set()
113
+ self._ignored_params: set[nn.Parameter] = set()
114
+ # Buffer names are cleaned (without wrapper prefixes)
115
+ self._ignored_buffer_names: set[str] = set()
116
+ self.process_group: Optional[dist.ProcessGroup] = None
117
+ self.rank: int = -1
118
+ self.world_size: int = -1
119
+ self._device_mesh: Optional[DeviceMesh] = None
120
+ self.sharding_strategy = ShardingStrategy.FULL_SHARD
121
+ self._use_orig_params: bool = False
122
+ self.training_state = TrainingState.IDLE
123
+ self._unshard_params_ctx: dict[nn.Module, Generator] = {}
124
+ self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT
125
+ self._state_dict_config: StateDictConfig = FullStateDictConfig()
126
+ self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig()
127
+ self._is_root: Optional[bool] = None
128
+ self._handle: Optional[flat_param_file.FlatParamHandle] = None
129
+ self._fully_sharded_module_to_handle: dict[
130
+ nn.Module, Optional[flat_param_file.FlatParamHandle]
131
+ ] = {}
132
+ self.compute_device: Optional[torch.device] = None
133
+ self._gradient_predivide_factor: int = 0
134
+ self._gradient_postdivide_factor: int = 0
135
+ self._comm_hook: Optional[Callable] = None
136
+ self._comm_hook_state: Optional[Any] = None
137
+ self._unshard_event: Optional[torch.Event] = None
138
+ # Abstract device handle for fsdp compute device. For now,
139
+ # the compute device must implement cuda semantics used by fsdp
140
+ self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle()
141
+ # All following attributes should only be used for root states:
142
+ # Save these static lists to avoid the repeated tree traversals
143
+ self._all_fsdp_states: list[_FSDPState] = []
144
+ self._all_handles: list[flat_param_file.FlatParamHandle] = []
145
+ self._fsdp_extension: Optional[FSDPExtensions] = None
146
+
147
+
148
+ def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]:
149
+ state = _get_module_state(module)
150
+ if state is None or not isinstance(state, _FSDPState):
151
+ return None
152
+ return state
153
+
154
+
155
+ def _get_module_fsdp_state_if_fully_sharded_module(
156
+ module: nn.Module,
157
+ ) -> Optional[_FSDPState]:
158
+ state = _get_module_fsdp_state(module)
159
+ if state is None:
160
+ return None
161
+ if state == module: # FullyShardedDataParallel module case.
162
+ return state
163
+ if module in state._fully_sharded_module_to_handle: # fully_shard case.
164
+ return state
165
+ return None
166
+
167
+
168
+ class TrainingState(Enum):
169
+ """
170
+ An enum that indicates the state of a ``FullyShardedDataParallel` instance.
171
+ """
172
+
173
+ IDLE = auto()
174
+ FORWARD_BACKWARD = auto()
175
+ SUMMON_FULL_PARAMS = auto()
176
+
177
+
178
+ class HandleTrainingState(Enum):
179
+ """
180
+ An enum that indicates the state of a ``FlatParamHandle`.
181
+ """
182
+
183
+ IDLE = auto()
184
+ FORWARD = auto()
185
+ BACKWARD_PRE = auto()
186
+ BACKWARD_POST = auto()
187
+ SUMMON_FULL_PARAMS = auto()
188
+
189
+
190
+ def _is_composable(state: _FSDPState):
191
+ # TODO: This is a temporary hack for differentiate between code paths.
192
+ return not isinstance(state, nn.Module)
193
+
194
+
195
+ @no_type_check
196
+ def _module_handle(state: _FSDPState, module: nn.Module) -> Optional["FlatParamHandle"]:
197
+ """
198
+ Returns the ``FlatParamHandle`` s corresponding to ``module``. This is
199
+ the handle that contains some parameter in ``module``.
200
+ """
201
+ if _is_composable(state):
202
+ # A valid FSDP state may have no managed parameters and hence no
203
+ # handles, meaning no entry in `_fully_sharded_module_to_handles`
204
+ if state._handle is None:
205
+ return None
206
+ if module not in state._fully_sharded_module_to_handle:
207
+ raise AssertionError(
208
+ f"Expects a fully sharded module but got {module} on rank {state.rank}"
209
+ )
210
+ return state._fully_sharded_module_to_handle[module]
211
+ else:
212
+ # NOTE: This assumes `module` is a `FullyShardedDataParallel` instance.
213
+ return module._handle
214
+
215
+
216
+ @no_type_check
217
+ def _has_fsdp_params(state: _FSDPState, module: nn.Module) -> bool:
218
+ """Returns if ``module`` has parameters managed by FSDP."""
219
+ return _module_handle(state, module) is not None
220
+
221
+
222
+ def _get_sharding_strategy(handle):
223
+ """
224
+ Returns the sharding strategy of the handle.
225
+ """
226
+ return handle._sharding_strategy if handle else None
227
+
228
+
229
+ def clean_tensor_name(tensor_name: str) -> str:
230
+ """
231
+ Cleans the parameter or buffer name by removing any module wrapper
232
+ prefixes.
233
+ """
234
+ tensor_name = tensor_name.replace(FSDP_PREFIX, "")
235
+ # TODO: Explicitly replacing the checkpoint wrapper prefix is not ideal as
236
+ # it couples `CheckpointWrapper` and FSDP and also does not scale for more
237
+ # module wrappers.
238
+ tensor_name = tensor_name.replace(_CHECKPOINT_PREFIX, "")
239
+ return tensor_name
240
+
241
+
242
+ def _set_fsdp_flattened(tensor: torch.Tensor) -> None:
243
+ """
244
+ Sets an attribute on ``tensor`` to mark it as flattened by FSDP. This is to
245
+ avoid re-flattening it during nested construction.
246
+ """
247
+ setattr(tensor, FSDP_FLATTENED, True)
248
+
249
+
250
+ def _is_fsdp_flattened(tensor: torch.Tensor) -> bool:
251
+ """Returns if ``tensor`` has been marked as flattened by FSDP."""
252
+ return getattr(tensor, FSDP_FLATTENED, False)
253
+
254
+
255
+ def _named_parameters_with_duplicates(
256
+ module: nn.Module, **kwargs: Any
257
+ ) -> list[tuple[str, nn.Parameter]]:
258
+ """
259
+ This API is required as some modules overwrite `named_parameters()` but do not support
260
+ `remove_duplicate`.
261
+ """
262
+ if "remove_duplicate" in kwargs:
263
+ raise AssertionError(
264
+ "_named_parameters_with_duplicates cannot be used with `remove_duplicate` argument."
265
+ )
266
+ kwargs["remove_duplicate"] = False
267
+ try:
268
+ ret = list(module.named_parameters(**kwargs))
269
+ except AssertionError:
270
+ kwargs.pop("remove_duplicate")
271
+ ret = list(module.named_parameters(**kwargs))
272
+ return ret
273
+
274
+
275
+ def _get_param_to_fqns(
276
+ model: torch.nn.Module,
277
+ dedup_shared_params: bool = True,
278
+ ) -> dict[nn.Parameter, list[str]]:
279
+ """
280
+ Constructs a mapping from parameter to a list of its \"canonical\" FQNs. Here,
281
+ we use canonical to mean the fully-qualified name assigned to the parameter
282
+ based on its position in the original nn.Module hierarchy before any wrapper
283
+ or parallelism has been applied to it. This is in contrast to FQNs that may be
284
+ generated after parallelisms or wrappers have been applied to the model.
285
+
286
+ Each normal parameter maps to a singleton list containing its FQN, while each
287
+ ``FlatParameter`` maps to a list of its original parameter FQNs, which may
288
+ have length greater than one. All FQNs are prefixed starting from ``model``.
289
+
290
+ In the case where FSDP was applied with ``use_orig_params=True``, there should be no
291
+ ``FlatParameter`` s registered to the model's modules and this mapping will only
292
+ contain mappings from ``nn.Parameter`` s to singleton FQN lists.
293
+
294
+ It is only in the case where FSDP was applied with ``use_orig_params=False`` where
295
+ a ``FlatParameter`` will be registered in place of the original parameters and there
296
+ will be mappings from each ``FlatParameter`` to lists of FQNs corresponding to the
297
+ original parameters.
298
+
299
+ Args:
300
+ model (torch.nn.Module): Root module (which may or may not be a
301
+ :class:`FullyShardedDataParallel` instance).
302
+ dedup_shared_params (bool): For shared parameters, if ``True``, only
303
+ includes the FQNs corresponding to the first encounter of the
304
+ shared parameter in the module traversal; if ``False``, then
305
+ includes the FQNs across all encounters. (Default: ``True``)
306
+ """
307
+
308
+ def module_fn(module, prefix, tree_level, param_to_fqns):
309
+ for param_name, param in _named_parameters_with_duplicates(
310
+ module, recurse=False
311
+ ):
312
+ local_fqns = (
313
+ param._fqns
314
+ if isinstance(param, flat_param_file.FlatParameter)
315
+ else [param_name]
316
+ ) # prefixed from `module`
317
+ global_fqns = [
318
+ clean_tensor_name(prefix + name) for name in local_fqns
319
+ ] # prefixed from the top level `model` (i.e. including `prefix`)
320
+ is_shared_param = param in param_to_fqns
321
+ if not is_shared_param:
322
+ param_to_fqns[param] = global_fqns
323
+ else:
324
+ if isinstance(param, flat_param_file.FlatParameter):
325
+ # DMP overwrites `named_parameters` and skip (advance to
326
+ # the next child module) the wrapped_module (e.g.,
327
+ # _dmp_wrapped_module and _fsdp_wrapped_module). When a user
328
+ # calls `named_child` to traverse the module recursively and
329
+ # calls `named_parameters` with `recurse=False`, parameters
330
+ # will be traversed more than once.
331
+ # This hack is specified designed for DMP + FSDP. We
332
+ # overwrite the flat_parameters traversal result to only obtain
333
+ # the last one, which happens to be the correct one.
334
+ #
335
+ # TODO: Remove this hack once DMP + FSDP is not supported.
336
+ warnings.warn(
337
+ "FlatParameter is being traversed more than once. "
338
+ "This case should only happen when using "
339
+ "DistributedModelParallel with FullyShardedDataParallel.",
340
+ stacklevel=2,
341
+ )
342
+ param_to_fqns[param] = global_fqns
343
+ elif not dedup_shared_params:
344
+ param_to_fqns[param].extend(global_fqns)
345
+
346
+ def return_fn(param_to_fqns):
347
+ return param_to_fqns
348
+
349
+ param_to_unflat_param_names: dict[torch.nn.Parameter, list[str]] = {}
350
+ return _apply_to_modules(
351
+ model,
352
+ module_fn,
353
+ return_fn,
354
+ [key for key, _ in _named_parameters_with_duplicates(model)],
355
+ param_to_unflat_param_names,
356
+ )
357
+
358
+
359
+ @no_type_check
360
+ def _log_post_backward_hook(
361
+ state: _FSDPState, handle: "FlatParamHandle", logger: logging.Logger
362
+ ) -> None:
363
+ # Under TORCH_DISTRIBUTED_DEBUG=INFO, log the module names this hook fires for.
364
+ # Below logging of module names this post-bwd hook fires for can help debug certain
365
+ # cases where hooks don't fire, such as under certain activation checkpoint configs.
366
+ if state._use_orig_params and handle._debug_level == dist.DebugLevel.INFO:
367
+ param_fqns = _get_handle_fqns_from_root(state, handle)
368
+ logger.warning("FSDP firing post-backward hooks for parameters %s", param_fqns)
369
+
370
+
371
+ @no_type_check
372
+ def _get_handle_fqns_from_root(
373
+ state: _FSDPState, handle: "FlatParamHandle"
374
+ ) -> Optional[list[str]]:
375
+ if handle is None:
376
+ return None
377
+ param_to_fqn = state._exec_order_data.param_to_fqn
378
+ handle_params = handle.flat_param._params # only populated for use_orig_params
379
+ param_fqns = [*chain.from_iterable(param_to_fqn[p] for p in handle_params)]
380
+ return param_fqns
381
+
382
+
383
+ def _apply_to_modules(
384
+ root_module: torch.nn.Module,
385
+ module_fn: Callable,
386
+ return_fn: Callable,
387
+ filter_fqns: Optional[list[str]] = None,
388
+ *args,
389
+ **kwargs,
390
+ ):
391
+ """
392
+ Performs a pre-order traversal of the modules in the hierarchy rooted at
393
+ ``root_module``, applying ``module_fn`` at each module and finally
394
+ returning a value using ``return_fn``. The traversal constructs the full
395
+ module prefix name (e.g. "module.submodule." just like in model state dict)
396
+ and makes that available to ``module_fn``.
397
+
398
+ ``filter_fqns`` is used because some module may have its own prefix similar
399
+ to ``FullyShardedDataParallel`` and the ``named_parameters()`` is overwritten
400
+ to remove the prefix.
401
+ """
402
+
403
+ def f(module: torch.nn.Module, prefix: str, tree_level: int, *args, **kwargs):
404
+ # Call the module function before recursing over children (pre-order)
405
+ module_fn(module, prefix, tree_level, *args, **kwargs)
406
+ for submodule_name, submodule in module.named_children():
407
+ if submodule is None:
408
+ continue
409
+ new_prefix = prefix + submodule_name + "."
410
+ new_tree_level = tree_level + 1
411
+ if filter_fqns is not None:
412
+ for fqn in filter_fqns:
413
+ if fqn.startswith(new_prefix):
414
+ break
415
+ else:
416
+ # DMP's named_parameter() will mess up the traversal with
417
+ # ``named_children`` + `named_parameter(recurse=False)``.
418
+ # This hack is a must to make the traversal work.
419
+ # TODO: Remove this hack once DMP + FSDP is not supported.
420
+ # It turns out that recursive wrapping may trigger this as
421
+ # well.
422
+ if (
423
+ submodule_name == "_fsdp_wrapped_module"
424
+ or submodule_name == "_dmp_wrapped_module"
425
+ ):
426
+ new_prefix = prefix
427
+ elif submodule_name == "module":
428
+ new_prefix = prefix
429
+ f(submodule, new_prefix, new_tree_level, *args, **kwargs)
430
+
431
+ f(root_module, "", 0, *args, **kwargs)
432
+ return return_fn(*args, **kwargs)
433
+
434
+
435
+ @no_type_check
436
+ def _assert_in_training_states(
437
+ state: _FSDPState,
438
+ training_states: list[TrainingState],
439
+ ) -> None:
440
+ """Asserts that FSDP is in the states ``_training_states``."""
441
+ # Raise a `ValueError` instead of using `assert` to ensure that these
442
+ # logical assertions run even if `assert`s are disabled
443
+ if state.training_state not in training_states:
444
+ msg = (
445
+ f"expected to be in states {training_states} but current state is "
446
+ f"{state.training_state}"
447
+ )
448
+ # Print the error on rank 0 in case this is called in the backward pass
449
+ if state.rank == 0:
450
+ if isinstance(state, nn.Module):
451
+ print(f"Asserting FSDP instance is: {state}")
452
+ print(f"ERROR: {msg}")
453
+ traceback.print_stack()
454
+ raise ValueError(msg)
455
+
456
+
457
+ def _get_root_modules(modules: set[nn.Module]) -> set[nn.Module]:
458
+ """
459
+ Returns:
460
+ Set[nn.Module]: The subset of ``modules`` that are root modules (i.e.
461
+ parent-less) with respect to the modules in the set itself. In other
462
+ words, these are the modules in ``modules`` that are not the child of
463
+ any other module in ``modules``.
464
+ """
465
+ root_modules: set[nn.Module] = set()
466
+ module_to_submodules = {module: set(module.modules()) for module in modules}
467
+ for candidate_module in modules:
468
+ is_root_module = True
469
+ for module, submodules in module_to_submodules.items():
470
+ is_child_module = (
471
+ candidate_module is not module and candidate_module in submodules
472
+ )
473
+ if is_child_module:
474
+ is_root_module = False
475
+ break
476
+ if is_root_module:
477
+ root_modules.add(candidate_module)
478
+ return root_modules
479
+
480
+
481
+ def _override_module_mixed_precision(
482
+ root: torch.nn.Module,
483
+ module_classes_to_override: Iterable[type[nn.Module]],
484
+ wrap_override_dict: dict[str, Any] = {"mixed_precision": None}, # noqa: B006
485
+ ) -> set[type[nn.Module]]:
486
+ module_classes_to_override = tuple(set(module_classes_to_override))
487
+ # Return a set of the actually overridden module classes
488
+ overridden_module_classes: set[type[nn.Module]] = set()
489
+ for mod in root.modules():
490
+ if isinstance(mod, module_classes_to_override):
491
+ overridden_module_classes.add(type(mod))
492
+ mod._wrap_overrides = wrap_override_dict # type: ignore[assignment]
493
+ # TODO: We need to run this mixed precision ignored module in fp32,
494
+ # but ensure subsequent modules, that may possibly be running with
495
+ # mixed precision, still receive the appropriate precision inputs
496
+ # without user having to adjust mixed precision config too much.
497
+ # As a result, we attach pre and post forward hooks to up / down
498
+ # cast. We should revisit this design.
499
+
500
+ def cast_fn(
501
+ dtype: torch.dtype, module: nn.Module, x: torch.Tensor
502
+ ) -> torch.Tensor:
503
+ if not torch.is_floating_point(x) or x.dtype == dtype:
504
+ return x
505
+ _MODULE_TO_INP_DTYPE[module] = x.dtype
506
+ return x.to(dtype)
507
+
508
+ def forward_pre_hook(module, args):
509
+ return _apply_to_tensors(partial(cast_fn, torch.float32, module), args)
510
+
511
+ def forward_post_hook(module, args, output):
512
+ # NOTE: If the forward did not have any floating-point tensors,
513
+ # then the dtype will not be set for this module, and we do not
514
+ # upcast the dtype.
515
+ if module in _MODULE_TO_INP_DTYPE:
516
+ old_dtype = _MODULE_TO_INP_DTYPE[module]
517
+ return _apply_to_tensors(
518
+ partial(cast_fn, old_dtype, module), output
519
+ )
520
+
521
+ # We intentionally append both of these hooks so that they run after
522
+ # all other hooks.
523
+ mod.register_forward_pre_hook(forward_pre_hook, prepend=False)
524
+ mod.register_forward_hook(forward_post_hook, prepend=False)
525
+ return overridden_module_classes
526
+
527
+
528
+ def _no_dispatch_record_stream(tensor: torch.Tensor, stream: torch.Stream) -> None:
529
+ # FIXME record_stream doesn't work with non-cuda/mtia/xpu tensors
530
+ if tensor.device.type not in [
531
+ "cuda",
532
+ "mtia",
533
+ "xpu",
534
+ torch._C._get_privateuse1_backend_name(),
535
+ ]:
536
+ return
537
+
538
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
539
+ return
540
+ # from @ezyang:
541
+ # The no_dispatch was added in https://github.com/pytorch/pytorch/pull/88014 cc @fegin
542
+ # Looking over the PR, it looks like this is because we don't actually support Stream arguments
543
+ # in torch dispatch, so it just chokes.
544
+ # If Dynamo is able to answer "are there any torch dispatch modes" active (it should answer False),
545
+ # a better version of this would just be to check if there are any modes before disabling dispatch.
546
+ # TODO(voz): Extend a dynamo util to answer the above, unify the codepaths here.
547
+ tensor.record_stream(stream)
548
+ else:
549
+ with no_dispatch():
550
+ tensor.record_stream(stream)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_debug_utils.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import time
4
+ from collections import defaultdict
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from enum import Enum
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.fsdp._flat_param as flat_param_file
12
+ from torch.distributed.fsdp._common_utils import (
13
+ _apply_to_modules,
14
+ _get_module_fsdp_state,
15
+ clean_tensor_name,
16
+ )
17
+
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class SimpleProfiler:
23
+ class Type(str, Enum):
24
+ ALL = "all"
25
+ ALLGATHER = "all_gather"
26
+ ALLGATHER_OBJ = "all_gather_object"
27
+ RESHARDING = "resharding"
28
+ H2D = "H2D"
29
+ D2H = "D2H"
30
+
31
+ results: dict[str, float] = defaultdict(float)
32
+ profiling: set[str] = set()
33
+
34
+ @classmethod
35
+ def reset(cls) -> None:
36
+ cls.results.clear()
37
+ cls.profiling.clear()
38
+
39
+ @classmethod
40
+ @contextmanager
41
+ def profile(cls, profile_type: str) -> Iterator[None]:
42
+ if profile_type in cls.profiling:
43
+ raise AssertionError(
44
+ f"{profile_type} is already being profiled. "
45
+ "SimpleProfiler does not support profiling multiple instances at "
46
+ "the same time. "
47
+ )
48
+
49
+ cls.profiling.add(profile_type)
50
+ begin = time.monotonic()
51
+ try:
52
+ yield
53
+ finally:
54
+ end = time.monotonic()
55
+ cls.results[profile_type] += end - begin
56
+ cls.profiling.remove(profile_type)
57
+
58
+ @classmethod
59
+ def dump_and_reset(cls, msg: str) -> None:
60
+ # This cannot be combined with DETAIL distributed log
61
+ # as the profiling will be very incorrect.
62
+ if dist.get_rank() == 0 and dist.get_debug_level() == dist.DebugLevel.INFO:
63
+ logger.info("%s %s", msg, cls.results)
64
+ cls.reset()
65
+
66
+
67
+ def _get_sharded_module_tree_with_module_name_to_fqns(
68
+ model: torch.nn.Module,
69
+ ) -> tuple[str, dict[str, list[str]]]:
70
+ """
71
+ It is used for composable fully_shard() code path, it returns
72
+ 1. sharded module tree info: each line represents a submodule name that contains the
73
+ submodule's FQN and its submodule class name, if the submodule is sharded by `fully_shard`,
74
+ the submodule name will add a postfix with ' FULLY SHARDED'. Each increased tree
75
+ level adds 4 spaces before the printed name. A printed sharded module tree info for a toy model
76
+ is like this:
77
+ [CompositeModel] FULLY SHARDED
78
+ l1[Linear]
79
+ u1[UnitModule] FULLY SHARDED
80
+ u1.l1[Linear]
81
+ u1.seq[Sequential]
82
+ u1.seq.0[ReLU]
83
+ u1.seq.1[Linear]
84
+ u1.seq.2[ReLU]
85
+ u1.l2[Linear]
86
+ u2[UnitModule] FULLY SHARDED
87
+ u2.l1[Linear]
88
+ u2.seq[Sequential]
89
+ u2.seq.0[ReLU]
90
+ u2.seq.1[Linear]
91
+ u2.seq.2[ReLU]
92
+ u2.l2[Linear]
93
+ l2[Linear]
94
+ 2. a dict mapping from the concated module FQN and class name to a list of its managed
95
+ original parameters' FQNs. An example of the dict for the above toy sharded model is like this:
96
+ {'[CompositeModel]': ['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'],
97
+ 'u1[UnitModule]': ['u1.l1.weight', 'u1.l1.bias', 'u1.seq.1.weight', 'u1.seq.1.bias', 'u1.l2.weight', 'u1.l2.bias'],
98
+ 'u2[UnitModule]': ['u2.l1.weight', 'u2.l1.bias', 'u2.seq.1.weight', 'u2.seq.1.bias', 'u2.l2.weight', 'u2.l2.bias']
99
+ }
100
+ All FQNs are prefixed starting from ``model``.
101
+
102
+ Args:
103
+ model (torch.nn.Module): Root module (which may or may not be passed to
104
+ composable `fully_shard()`).
105
+ """
106
+
107
+ def module_fn(
108
+ module, prefix, tree_level, sharded_tree_info, sharded_module_name_to_fqns
109
+ ):
110
+ num_spaces = tree_level * 4
111
+ trimed_prefix = (
112
+ prefix[:-1] if (len(prefix) > 0 and prefix[-1] == ".") else prefix
113
+ )
114
+ prefixed_module_name = trimed_prefix + "[" + module.__class__.__name__ + "]"
115
+ printed_prefixed_module_name = " " * num_spaces + prefixed_module_name
116
+
117
+ state = _get_module_fsdp_state(module)
118
+ if state is None:
119
+ sharded_tree_info[0] += printed_prefixed_module_name + "\n"
120
+ return
121
+
122
+ handle = state._fully_sharded_module_to_handle.get(module, None)
123
+
124
+ if handle:
125
+ sharded_tree_info[0] += (
126
+ printed_prefixed_module_name + " FULLY SHARDED" + "\n"
127
+ )
128
+ else:
129
+ sharded_tree_info[0] += printed_prefixed_module_name + "\n"
130
+
131
+ if handle:
132
+ param = handle.flat_param
133
+ if not isinstance(param, flat_param_file.FlatParameter):
134
+ raise AssertionError(f"Expected FlatParameter, got {type(param)}")
135
+ global_fqns = [
136
+ clean_tensor_name(prefix + name) for name in param._fqns
137
+ ] # prefixed from the top level `model` (i.e. including `prefix`)
138
+
139
+ if prefixed_module_name in sharded_module_name_to_fqns:
140
+ sharded_module_name_to_fqns[prefixed_module_name].extend(global_fqns)
141
+ else:
142
+ sharded_module_name_to_fqns[prefixed_module_name] = global_fqns
143
+
144
+ def return_fn(sharded_tree_info, sharded_module_name_to_fqns):
145
+ return sharded_tree_info[0], sharded_module_name_to_fqns
146
+
147
+ # Use List to mutate its value in place while running the recursive functions
148
+ sharded_tree_info: list[str] = [
149
+ "",
150
+ ]
151
+ sharded_module_name_to_fqns: dict[str, list[str]] = {}
152
+ return _apply_to_modules(
153
+ model,
154
+ module_fn,
155
+ return_fn,
156
+ [key for key, _ in model.named_parameters()],
157
+ sharded_tree_info,
158
+ sharded_module_name_to_fqns,
159
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_dynamo_utils.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def _annotate_modules_for_dynamo(
5
+ module: nn.Module,
6
+ ignored_modules: set[nn.Module],
7
+ use_orig_params: bool,
8
+ ) -> None:
9
+ """
10
+ Annotates the submodules in ``module`` 's tree, except those in
11
+ ``ignored_modules``, indicating that the submodules are FSDP-managed and
12
+ saving the ``use_orig_params`` setting passed to the FSDP constructor.
13
+ """
14
+ for submodule in module.modules():
15
+ if submodule not in ignored_modules:
16
+ """[note: Dynamo treats FSDP wrapped modules as UnspecializedNNModule]
17
+
18
+ Dynamo doesn't get to see this instance (FullyShardedDataParallel) during tracing, since
19
+ it skips tracing all the torch.distributed.fsdp code.
20
+ - Why? Running the FSDP code eagerly avoids lots of issues trying to trace complex hooks, and also
21
+ gets us graph-breaks on FSDP module boundaries which we want anyway for comm ops.
22
+ - However, we _also_ want dynamo to treat the wrapped module inside FSDP 'unspecially' (*),
23
+ and we need a way to indicate to dynamo which modules are wrapped by FSDP.
24
+
25
+ (*) UnspecializedNNModules in dynamo are traced-through without any assumptions, and with thorough
26
+ guards. NNModules otherwise are 'specialized', meaning there is less overhead due to assuming
27
+ their code is well-behaved.
28
+
29
+ One particular issue with specialized NNModules for FSDP is that the
30
+ views created for orig_params are captured into the compiled graph on the first iteration, and while
31
+ they are always going to point to the correct flatparameter and give correct results, their order
32
+ of creation influences the order of backward execution, preventing overlap of comm and computation
33
+ during backward. We need to _use_ the new parameter views created on each forward iteration, in
34
+ order for backward to interleave hooks with compute per layer. UnspecializedNNModule lets us achieve
35
+ this by capturing the module code more 'functionally' and passing parameters in as inputs each time.
36
+ """
37
+ submodule._is_fsdp_managed_module = True # type: ignore[assignment]
38
+
39
+ # Dynamo only supports FSDP with use_orig_params=True.
40
+ # This is hacky, but I could not think of another way to add an assertion to dynamo
41
+ # for this, since Dynamo skips all the FSDP code frames and thus can't inspect the
42
+ # FSDP module directly
43
+ submodule._fsdp_use_orig_params = use_orig_params # type: ignore[assignment]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_exec_order_utils.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ import warnings
4
+ from enum import auto, Enum
5
+ from typing import Optional, Union
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
10
+ import torch.nn as nn
11
+ from torch.distributed.fsdp._common_utils import _FSDPState, _get_param_to_fqns
12
+ from torch.distributed.fsdp._flat_param import FlatParamHandle
13
+
14
+
15
+ class _ExecOrderWarnStatus(Enum):
16
+ """Used internally for execution order validation."""
17
+
18
+ NONE = auto() # no deviation yet
19
+ WARNING = auto() # deviated this iteration; currently issuing warnings
20
+ WARNED = auto() # deviated in a previous iteration
21
+
22
+
23
+ class _ExecOrderData:
24
+ """
25
+ This contains the data structures to track the execution order. We track
26
+ the pre-forward order on the *first* iteration for forward prefetching
27
+ (which thus assumes static graph) and the post-forward order on *every*
28
+ iteration for backward prefetching (which thus does not assume static
29
+ graph but may be provide an incorrect order).
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ debug_level: dist.DebugLevel,
35
+ backward_prefetch_limit: int,
36
+ forward_prefetch_limit: int,
37
+ ) -> None:
38
+ # Tracks the (static) pre-forward order for execution order validation
39
+ # and forward prefetching
40
+ self.handles_pre_forward_order: list[FlatParamHandle] = []
41
+ # Tracks the post-forward order for pre-backward prefetching
42
+ self.handles_post_forward_order: list[Optional[FlatParamHandle]] = []
43
+ self._iter = 0
44
+
45
+ # Gives the max number of backward/forward prefetched all-gathers by a
46
+ # single module
47
+ self._backward_prefetch_limit = backward_prefetch_limit
48
+ self._forward_prefetch_limit = forward_prefetch_limit
49
+
50
+ # Data structures for execution order validation
51
+ self._checking_order: bool = debug_level == dist.DebugLevel.DETAIL
52
+ self.process_group: Optional[dist.ProcessGroup] = None
53
+ self.world_size: Optional[int] = None
54
+ self.all_handles: list[FlatParamHandle] = []
55
+ # Names are prefixed from the root module
56
+ self.param_to_fqn: dict[nn.Parameter, list[str]] = {}
57
+ # Current index in the pre-forward execution order
58
+ self.current_order_index = 0
59
+ self.warn_status = _ExecOrderWarnStatus.NONE
60
+
61
+ def init(
62
+ self,
63
+ state: _FSDPState,
64
+ root_module: nn.Module,
65
+ process_group: dist.ProcessGroup,
66
+ ) -> None:
67
+ """
68
+ Initializes the data structures needed for checking the forward order.
69
+ This should be called after a root FSDP instance has been set during
70
+ lazy initialization.
71
+ """
72
+ self.process_group = process_group
73
+ self.rank = process_group.rank()
74
+ self.world_size = process_group.size()
75
+ # Fix an order over the handles, which should be the same across ranks
76
+ for handle in traversal_utils._get_fsdp_handles(root_module):
77
+ index = len(self.all_handles)
78
+ self.all_handles.append(handle)
79
+ handle._handle_index = index
80
+ self.param_to_fqn = _get_param_to_fqns(root_module)
81
+ # TODO (awgu): We can broadcast the metadata of rank 0's `all_handles`
82
+ # to check that all ranks have the same handles in the same order.
83
+ # https://github.com/pytorch/pytorch/issues/79620
84
+
85
+ @property
86
+ def is_first_iter(self) -> bool:
87
+ return self._iter == 0
88
+
89
+ def get_handle_to_backward_prefetch(
90
+ self,
91
+ current_handle: FlatParamHandle,
92
+ ) -> Optional[FlatParamHandle]:
93
+ """
94
+ Returns a :class:`list` of the handles keys of the handles to backward
95
+ prefetch given the current handles key. If there are no valid handles
96
+ keys to prefetch, then this returns an empty :class:`list`.
97
+ """
98
+ current_index = current_handle._post_forward_index
99
+ if current_index is None:
100
+ return None
101
+ target_index = current_index - 1
102
+ target_handle: Optional[FlatParamHandle] = None
103
+ for _ in range(self._backward_prefetch_limit):
104
+ if target_index < 0:
105
+ break
106
+ target_handle = self.handles_post_forward_order[target_index]
107
+ target_index -= 1
108
+ return target_handle
109
+
110
+ def get_handle_to_forward_prefetch(
111
+ self,
112
+ current_handle: FlatParamHandle,
113
+ ) -> Optional[FlatParamHandle]:
114
+ """
115
+ Returns a :class:`list` of the handles keys of the handles to forward
116
+ prefetch given the current handles key. If there are no valid handles
117
+ keys to prefetch, then this returns an empty :class:`list`.
118
+ """
119
+ current_index = current_handle._pre_forward_order_index
120
+ if current_index is None:
121
+ return None
122
+ target_index = current_index + 1
123
+ target_handle: Optional[FlatParamHandle] = None
124
+ for _ in range(self._forward_prefetch_limit):
125
+ if target_index >= len(self.handles_pre_forward_order):
126
+ break
127
+ target_handle = self.handles_pre_forward_order[target_index]
128
+ target_index += 1
129
+ return target_handle
130
+
131
+ def record_post_forward(self, handle: Optional[FlatParamHandle]) -> None:
132
+ """
133
+ Records ``handles`` in the post-forward order, where ``handles`` should
134
+ be a group of handles used in the same module's forward. If ``handles``
135
+ is empty, then it is omitted.
136
+
137
+ Unlike :meth:`record_pre_forward`, this records the order *every*
138
+ iteration with the expectation that the recorded order is reset in
139
+ :meth:`next_iter`.
140
+ """
141
+ if not handle:
142
+ return
143
+ # Only record the first usage of a handles key
144
+ if handle._post_forward_index:
145
+ self.handles_post_forward_order.append(handle)
146
+ return
147
+ index = len(self.handles_post_forward_order)
148
+ handle._post_forward_index = index
149
+ self.handles_post_forward_order.append(handle)
150
+
151
+ def record_pre_forward(
152
+ self, handle: Optional[FlatParamHandle], is_training: bool
153
+ ) -> None:
154
+ """
155
+ Records ``handles`` in the pre-forward order, where ``handles`` should
156
+ be a group of handles used in the same module's forward. If ``handles``
157
+ is empty, then it is omitted.
158
+
159
+ On the first iteration, this checks the execution order across ranks.
160
+ See :meth:`_check_order` for details.
161
+ """
162
+ if not handle:
163
+ return
164
+ self._check_order(handle, is_training)
165
+ # Fix the order after the first iteration and only record the first
166
+ # usage of a handles key
167
+ if not self.is_first_iter or handle._pre_forward_order_index is not None:
168
+ return
169
+ index = len(self.handles_pre_forward_order)
170
+ handle._pre_forward_order_index = index
171
+ self.handles_pre_forward_order.append(handle)
172
+
173
+ def _check_order(self, handle: FlatParamHandle, is_training: bool) -> None:
174
+ """
175
+ Checks the forward execution order as long as ``is_training`` is
176
+ ``True`` since checking in eval mode is not supported. This only checks
177
+ if the distributed debug level is DETAIL.
178
+
179
+ - On the first iteration, this uses all-gathers to check that all ranks
180
+ are all-gathering the same handles and hence ``FlatParameter`` s,
181
+ raising an error if not.
182
+ - On subsequent iterations, this checks that each rank is locally
183
+ consistent with its own forward order from the first iteration, issuing
184
+ a warning if not. This issues a warning on the first deviating
185
+ iteration and stops warning thereafter.
186
+ """
187
+ # Do not check order in eval mode since the post-backward callback does
188
+ # not run so it cannot be used to mark the end of an iteration
189
+ if not is_training or not self._checking_order:
190
+ return
191
+ if self.is_first_iter:
192
+ msg_prefix = "Forward order differs across ranks:"
193
+ optional_local_indices: tuple[Optional[int], ...] = (
194
+ self._get_handle_indices(handle)
195
+ )
196
+ device = handle.device # guaranteed to be non-CPU
197
+ num_valid_indices = sum(
198
+ (index is not None) for index in optional_local_indices
199
+ )
200
+ tensor_kwargs: dict[str, Union[torch.dtype, torch.device]] = {
201
+ "dtype": torch.int32,
202
+ "device": device,
203
+ }
204
+ world_num_valid_indices = torch.zeros(self.world_size, **tensor_kwargs) # type: ignore[arg-type, call-overload]
205
+ local_num_valid_indices = torch.tensor([num_valid_indices], **tensor_kwargs) # type: ignore[arg-type, call-overload]
206
+ dist.all_gather_into_tensor(
207
+ world_num_valid_indices,
208
+ local_num_valid_indices,
209
+ group=self.process_group,
210
+ )
211
+ # Copy entire tensor from D2H once to avoid per element D2H copies
212
+ world_num_valid_indices = world_num_valid_indices.cpu()
213
+ # Check that all ranks plan to all-gather the same number of
214
+ # parameters
215
+ # TODO (awgu): Since every module has at most one handle in the
216
+ # current implementation, this should never raise the error.
217
+ if self.world_size is None:
218
+ raise AssertionError("Expected world_size to not be None")
219
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
220
+ # TODO(voz): Don't graph break on this - dynamo hates the n1 != n2
221
+ # tensor comparison control flow.
222
+ # https://github.com/pytorch/pytorch/issues/107055
223
+ for (r1, n1), (r2, n2) in itertools.combinations(
224
+ (
225
+ (rank, world_num_valid_indices[rank])
226
+ for rank in range(self.world_size)
227
+ ),
228
+ 2,
229
+ ):
230
+ if n1 != n2:
231
+ raise RuntimeError(
232
+ f"{msg_prefix} rank {r1} is all-gathering {n1} parameters "
233
+ f"while rank {r2} is all-gathering {n2} parameters"
234
+ )
235
+ world_indices = torch.zeros( # type: ignore[call-overload]
236
+ self.world_size * num_valid_indices, **tensor_kwargs
237
+ )
238
+ local_indices = torch.tensor(optional_local_indices, **tensor_kwargs) # type: ignore[arg-type]
239
+ dist.all_gather_into_tensor(
240
+ world_indices, local_indices, group=self.process_group
241
+ )
242
+ # Copy entire tensor from D2H once to avoid per element D2H copies
243
+ world_indices = world_indices.cpu()
244
+ # Check that all ranks plan to all-gather the same index parameters
245
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
246
+ # TODO(voz): Don't graph break on this - dynamo hates the i1 != i2
247
+ # tensor comparison control flow.
248
+ # https://github.com/pytorch/pytorch/issues/107055
249
+ for (r1, i1), (r2, i2) in itertools.combinations(
250
+ (
251
+ (
252
+ rank,
253
+ world_indices[
254
+ rank * num_valid_indices : (rank + 1)
255
+ * num_valid_indices
256
+ ],
257
+ )
258
+ for rank in range(self.world_size)
259
+ ),
260
+ 2,
261
+ ):
262
+ if i1 != i2:
263
+ r1_param_names = self._get_names_from_handle_indices(i1)
264
+ r2_param_names = self._get_names_from_handle_indices(i2)
265
+ raise RuntimeError(
266
+ f"{msg_prefix} rank {r1} is all-gathering parameters "
267
+ f"for {r1_param_names} while rank {r2} is all-gathering "
268
+ f"parameters for {r2_param_names}"
269
+ )
270
+ else:
271
+ # Only issue warnings on the first deviating iteration and stop
272
+ # checking thereafter to avoid flooding the console
273
+ if self.warn_status == _ExecOrderWarnStatus.WARNED:
274
+ return
275
+ msg_prefix = None # non-`None` means we should warn
276
+ if self.current_order_index >= len(self.handles_pre_forward_order):
277
+ # This iteration sees extra all-gather(s) compared to the first
278
+ msg_prefix = (
279
+ "Expected to not all-gather any more parameters in the "
280
+ "forward but trying to all-gather parameters for "
281
+ )
282
+ else:
283
+ expected_handle = self.handles_pre_forward_order[
284
+ self.current_order_index
285
+ ]
286
+ if expected_handle != handle:
287
+ expected_param_names = self._get_names_from_handles(expected_handle)
288
+ msg_prefix = (
289
+ f"Expected to all-gather for {expected_param_names} "
290
+ "but trying to all-gather parameters for "
291
+ )
292
+ if msg_prefix is not None:
293
+ param_names = self._get_names_from_handles(handle)
294
+ msg_suffix = (
295
+ f"{param_names}"
296
+ if param_names
297
+ else "a newly-added parameter since construction time"
298
+ )
299
+ warnings.warn(
300
+ "Forward order differs from that of the first iteration "
301
+ f"on rank {self.rank}. Collectives are unchecked and may "
302
+ f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}",
303
+ stacklevel=2,
304
+ )
305
+ self.warn_status = _ExecOrderWarnStatus.WARNING
306
+ self.current_order_index += 1
307
+
308
+ def _get_handle_indices(
309
+ self,
310
+ handle: FlatParamHandle,
311
+ ) -> tuple[Optional[int], ...]:
312
+ """
313
+ Returns the handle indices (i.e. indices into ``self.all_handles``)
314
+ corresponding to the handles in ``handle``. An entry in the
315
+ returned tuple is ``None`` if the handle is invalid.
316
+ """
317
+ indices: list[Optional[int]] = []
318
+ if handle:
319
+ indices.append(handle._handle_index)
320
+ return tuple(indices)
321
+
322
+ def _get_names_from_handle_indices(
323
+ self,
324
+ handle_indices: tuple[int, ...],
325
+ ) -> list[list[str]]:
326
+ """
327
+ Returns a list of FQNs for each handle in ``handle_indices``. If a
328
+ handle index is invalid, then its FQNs are omitted from the returned
329
+ list.
330
+ """
331
+ fqns: list[list[str]] = []
332
+ for index in handle_indices:
333
+ if index is None or index < 0 or index >= len(self.all_handles):
334
+ continue
335
+ handle = self.all_handles[index]
336
+ flat_param = handle.flat_param
337
+ fqns.append(self.param_to_fqn[flat_param])
338
+ return fqns
339
+
340
+ def _get_names_from_handles(
341
+ self,
342
+ handle: FlatParamHandle,
343
+ ) -> list[list[str]]:
344
+ """
345
+ Returns a list of FQNs for each handle in ``handles_key``. If a handle
346
+ is invalid, then its FQNs are omitted from the returned list.
347
+ """
348
+ fqns: list[list[str]] = []
349
+ if handle:
350
+ flat_param = handle.flat_param
351
+ if flat_param in self.param_to_fqn:
352
+ fqns.append(self.param_to_fqn[flat_param])
353
+ return fqns
354
+
355
+ def next_iter(self):
356
+ """
357
+ Advances the internal data structures per iteration. This should be
358
+ called in the post-backward callback since that marks the true end of
359
+ an iteration.
360
+ """
361
+ self._iter += 1
362
+ self.handles_post_forward_order.clear()
363
+ if self._checking_order:
364
+ self.current_order_index = 0
365
+ if self.warn_status == _ExecOrderWarnStatus.WARNING:
366
+ self.warn_status = _ExecOrderWarnStatus.WARNED
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_flat_param.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fsdp_extensions.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any, Optional
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ from torch.distributed._shard.sharded_tensor.api import ShardedTensor
7
+ from torch.distributed._shard.sharded_tensor.shard import Shard
8
+ from torch.distributed.fsdp._shard_utils import (
9
+ _all_gather_dtensor,
10
+ _create_chunk_dtensor,
11
+ _create_chunk_sharded_tensor,
12
+ )
13
+ from torch.distributed.tensor import DeviceMesh, DTensor
14
+
15
+
16
+ class FSDPExtensions(ABC):
17
+ """
18
+ This enables some customizable hooks to enable composability with tensor
19
+ parallelism. To activate these hooks, use :func:`_set_fsdp_extensions` to
20
+ set a custom :class:`FSDPExtensions` that implements the hooks.
21
+ """
22
+
23
+ @abstractmethod
24
+ def pre_flatten_transform(
25
+ self,
26
+ tensor: torch.Tensor,
27
+ ) -> tuple[torch.Tensor, Optional[Any]]:
28
+ """E.g. converting ``DistributedTensor`` to local tensor."""
29
+ ...
30
+
31
+ @abstractmethod
32
+ def post_unflatten_transform(
33
+ self,
34
+ tensor: torch.Tensor,
35
+ param_extension: Any,
36
+ ) -> torch.Tensor:
37
+ """E.g. converting local tensor to ``DistributedTensor``."""
38
+ ...
39
+
40
+ @abstractmethod
41
+ def chunk_tensor(
42
+ self,
43
+ tensor: torch.Tensor,
44
+ rank: int,
45
+ world_size: int,
46
+ num_devices_per_node: int,
47
+ pg: dist.ProcessGroup,
48
+ device: Optional[torch.device] = None,
49
+ ) -> torch.Tensor:
50
+ """Shards a tensor to chunks and returns the local chunk."""
51
+ ...
52
+
53
+ @abstractmethod
54
+ def chunk_dtensor(
55
+ self,
56
+ tensor: torch.Tensor,
57
+ rank: int,
58
+ device_mesh: DeviceMesh,
59
+ ) -> torch.Tensor:
60
+ """Shards a tensor/DTensor to DTensor and returns the local DTensor."""
61
+ ...
62
+
63
+ @abstractmethod
64
+ def pre_load_state_dict_transform(
65
+ self,
66
+ tensor: torch.Tensor,
67
+ ) -> tuple[torch.Tensor, list[Shard]]:
68
+ """
69
+ This is to be called before loading a *sharded* model state dict and
70
+ should return the tensor and list of shards from which to load data.
71
+ """
72
+ ...
73
+
74
+ @abstractmethod
75
+ def all_gather_dtensor(
76
+ self,
77
+ tensor: DTensor,
78
+ parent_mesh: Optional[DeviceMesh],
79
+ ) -> torch.Tensor:
80
+ """
81
+ This is to be called before loading a *sharded* DTensor state dict.
82
+ This gathers tensor in FSDP dimension and returns local tensor of
83
+ TP DTensor.
84
+ """
85
+ ...
86
+
87
+
88
+ _extensions: Optional[FSDPExtensions] = None
89
+
90
+
91
+ def _set_fsdp_extensions(flattener: FSDPExtensions) -> None:
92
+ global _extensions
93
+ _extensions = flattener
94
+
95
+
96
+ def _ext_pre_flatten_transform(
97
+ tensor: torch.Tensor,
98
+ fsdp_extension: Optional[FSDPExtensions] = None,
99
+ ) -> tuple[torch.Tensor, Optional[Any]]:
100
+ if fsdp_extension is not None:
101
+ new_tensor, param_extension = fsdp_extension.pre_flatten_transform(tensor)
102
+ if param_extension is not None:
103
+ return new_tensor, param_extension
104
+ return tensor, None
105
+
106
+
107
+ def _ext_post_unflatten_transform(
108
+ tensor: torch.Tensor,
109
+ param_extension: Any,
110
+ fsdp_extension: Optional[FSDPExtensions] = None,
111
+ ) -> torch.Tensor:
112
+ if fsdp_extension is not None and param_extension is not None:
113
+ return fsdp_extension.post_unflatten_transform(tensor, param_extension)
114
+ return tensor
115
+
116
+
117
+ def _ext_chunk_tensor(
118
+ tensor: torch.Tensor,
119
+ rank: int,
120
+ world_size: int,
121
+ num_devices_per_node: int,
122
+ pg: dist.ProcessGroup,
123
+ fsdp_extension: Optional[FSDPExtensions] = None,
124
+ ) -> torch.Tensor:
125
+ chunk_tensor_fn = (
126
+ fsdp_extension.chunk_tensor
127
+ if fsdp_extension is not None
128
+ else _create_chunk_sharded_tensor
129
+ )
130
+ return chunk_tensor_fn(
131
+ tensor,
132
+ rank,
133
+ world_size,
134
+ num_devices_per_node,
135
+ pg,
136
+ )
137
+
138
+
139
+ def _ext_chunk_dtensor(
140
+ tensor: torch.Tensor,
141
+ rank: int,
142
+ device_mesh: DeviceMesh,
143
+ fsdp_extension: Optional[FSDPExtensions] = None,
144
+ ) -> torch.Tensor:
145
+ chunk_dtensor_fn = (
146
+ fsdp_extension.chunk_dtensor
147
+ if fsdp_extension is not None
148
+ else _create_chunk_dtensor
149
+ )
150
+ return chunk_dtensor_fn(
151
+ tensor,
152
+ rank,
153
+ device_mesh,
154
+ )
155
+
156
+
157
+ def _ext_pre_load_state_dict_transform(
158
+ tensor: torch.Tensor,
159
+ fsdp_extension: Optional[FSDPExtensions] = None,
160
+ ) -> tuple[torch.Tensor, list[Shard]]:
161
+ if fsdp_extension is not None:
162
+ return fsdp_extension.pre_load_state_dict_transform(tensor)
163
+
164
+ if type(tensor) is not ShardedTensor:
165
+ raise AssertionError(f"Expected ShardedTensor, got {type(tensor)}")
166
+ shards = tensor.local_shards()
167
+ return (tensor, shards)
168
+
169
+
170
+ def _ext_all_gather_dtensor(
171
+ tensor: DTensor,
172
+ parent_mesh: Optional[DeviceMesh],
173
+ fsdp_extension: Optional[FSDPExtensions] = None,
174
+ ) -> torch.Tensor:
175
+ all_gather_dtensor_fn = (
176
+ fsdp_extension.all_gather_dtensor
177
+ if fsdp_extension is not None
178
+ else _all_gather_dtensor
179
+ )
180
+ return all_gather_dtensor_fn(tensor, parent_mesh)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
2
+ from ._fully_shard import (
3
+ FSDPModule,
4
+ fully_shard,
5
+ register_fsdp_forward_method,
6
+ share_comm_ctx,
7
+ UnshardHandle,
8
+ )
9
+
10
+
11
+ __all__ = [
12
+ "CPUOffloadPolicy",
13
+ "FSDPModule",
14
+ "fully_shard",
15
+ "MixedPrecisionPolicy",
16
+ "OffloadPolicy",
17
+ "register_fsdp_forward_method",
18
+ "UnshardHandle",
19
+ "share_comm_ctx",
20
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_api.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from abc import ABC, abstractmethod
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Optional, Union
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+
10
+
11
+ _ReduceOp = Union[dist.ReduceOp, dist.ReduceOp.RedOpType]
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class MixedPrecisionPolicy:
16
+ """
17
+ This configures FSDP's mixed precision. Unlike autocast, this applies mixed
18
+ precision at the module level, not op level, which means low-precision
19
+ activations are saved for backward and high-to-low-precision casts are
20
+ incurred only at module boundaries.
21
+
22
+ FSDP works well with module-level mixed precision since it keeps the
23
+ high-precision sharded parameters in memory anyway. In other words, FSDP
24
+ does not require any extra memory to keep a high-precision copy of the
25
+ parameters for the optimizer step.
26
+
27
+ Attributes:
28
+ param_dtype (Optional[torch.dtype]): This specifies the dtype for
29
+ the unsharded parameter and hence the dtype for forward/backward
30
+ computation and the parameter all-gather. If this is ``None``, then
31
+ the unsharded parameter uses the original dtype. The optimizer step
32
+ uses the sharded parameter in the original dtype. (Default:
33
+ ``None``)
34
+ reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
35
+ gradient reduction (i.e. reduce-scatter or all-reduce). If this is
36
+ ``None`` but ``param_dtype`` is not ``None``, then the reduction
37
+ uses the compute dtype. This can be used to run gradient reduction
38
+ in full precision while using low precision for compute. If also
39
+ gradient reduction is disabled via :meth:`set_requires_gradient_sync`,
40
+ then FSDP will accumulate gradients using ``reduce_dtype``.
41
+ (Default: ``None``)
42
+ output_dtype (Optional[torch.dtype]): This specifies the dtype for
43
+ casting floating-point forward outputs. This can be used to
44
+ help implement cases where different modules have different mixed
45
+ precision policies. (Default: ``None``)
46
+ cast_forward_inputs (bool): This specifies whether FSDP should cast the
47
+ forward's floating-point input tensors to ``param_dtype`` or not.
48
+ """
49
+
50
+ param_dtype: Optional[torch.dtype] = None
51
+ reduce_dtype: Optional[torch.dtype] = None
52
+ output_dtype: Optional[torch.dtype] = None
53
+ cast_forward_inputs: bool = True
54
+
55
+
56
+ class Comm(ABC):
57
+ """
58
+ Interface for communication primitives.
59
+ A primitive primarily needs to handle 3 tasks, namely:
60
+
61
+ 1. How to allocate memory for communication
62
+ Depending on the goal, an implementation can choose to:
63
+ a. associate each call to a temporary buffer
64
+ (best for flexibility and simplicity)
65
+ b. reuse an persistent buffer for efficiency reasons
66
+
67
+ 2. Where to allocate memory
68
+ (e.g. NCCL mem pool or regular cuda caching allocator)
69
+
70
+ 3. What to do/call upon the comm is called
71
+ (see `AllGather` interface as an example)
72
+ """
73
+
74
+ @abstractmethod
75
+ def allocate(
76
+ self,
77
+ size: Sequence[Union[int, torch.SymInt]],
78
+ *,
79
+ dtype: torch.dtype,
80
+ device: torch.device,
81
+ ) -> torch.Tensor:
82
+ """
83
+ This handles the "how to allocate memory" part.
84
+
85
+ A default implementation could be simply:
86
+
87
+ .. code-block:: python
88
+ with self.mem_pool:
89
+ torch.empty(...)
90
+
91
+ Args:
92
+ size (Sequence[Union[int, torch.SymInt]]): size of the tensor buffer
93
+ dtype (torch.dtype): dtype of the tensor buffer
94
+ device (torch.device): which device to allocate the tensor onto
95
+ """
96
+ ...
97
+
98
+
99
+ class AllGather(Comm):
100
+ """
101
+ Interface for all_gather comm primitive
102
+ """
103
+
104
+ @abstractmethod
105
+ def __call__(
106
+ self,
107
+ output_tensor: torch.Tensor,
108
+ input_tensor: torch.Tensor,
109
+ group: dist.ProcessGroup,
110
+ async_op: bool = False,
111
+ ) -> Optional[dist.Work]: ...
112
+
113
+
114
+ class ReduceScatter(Comm):
115
+ """
116
+ Interface for reduce_scatter comm primitive
117
+ """
118
+
119
+ @abstractmethod
120
+ def __call__(
121
+ self,
122
+ output_tensor: torch.Tensor,
123
+ input_tensor: torch.Tensor,
124
+ group: dist.ProcessGroup,
125
+ op: _ReduceOp,
126
+ async_op: bool = False,
127
+ ) -> Optional[dist.Work]: ...
128
+
129
+
130
+ @dataclass
131
+ class OffloadPolicy:
132
+ """
133
+ This base class represents the policy of no offloading and is only used as
134
+ the default value for the ``offload_policy`` arg.
135
+ """
136
+
137
+
138
+ @dataclass
139
+ class CPUOffloadPolicy(OffloadPolicy):
140
+ """
141
+ This offload policy offloads parameters, gradients, and optimizer states to
142
+ CPU. Sharded parameters are copied host-to-device before all-gather. The
143
+ all-gathered parameters are freed according to ``reshard_after_forward``.
144
+ Sharded gradients are copied device-to-host in backward, and the optimizer
145
+ step runs on CPU with CPU optimizer states.
146
+
147
+ Attributes:
148
+ pin_memory (bool): Whether to pin sharded parameter and gradient
149
+ memory. Pinning memory allows both more efficient H2D/D2H copies
150
+ and for the copies to overlap with compute. However, the pinned
151
+ memory cannot be used by other processes. Set this to ``False`` if
152
+ you have insufficient CPU memory. (Default: ``True``)
153
+ """
154
+
155
+ pin_memory: bool = True
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections.abc import Callable, Sequence
3
+ from itertools import chain
4
+ from typing import Any, cast, NamedTuple, Optional, Union
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from torch.distributed.device_mesh import _get_device_handle
9
+ from torch.distributed.distributed_c10d import ReduceOp
10
+ from torch.distributed.fsdp._fully_shard._fsdp_api import AllGather, ReduceScatter
11
+ from torch.distributed.tensor import DTensor
12
+
13
+ from ._fsdp_api import _ReduceOp
14
+ from ._fsdp_common import (
15
+ _get_dim0_padded_size,
16
+ _raise_assert_with_print,
17
+ _to_dtype_if_needed,
18
+ compiled_autograd_enabled,
19
+ )
20
+ from ._fsdp_param import FSDPParam, ShardedState
21
+
22
+
23
+ class AllGatherResult(NamedTuple):
24
+ all_gather_output: torch.Tensor
25
+ all_gather_event: Optional[torch.Event]
26
+ all_gather_work: Optional[dist.distributed_c10d.Work]
27
+ # For each parameter, the all-gather input dtype for each input
28
+ param_all_gather_input_dtypes: list[list[torch.dtype]]
29
+ # For each parameter, the all-gather input numel for each input
30
+ param_all_gather_input_numels: list[list[int]]
31
+ # 1D flattened version of `param_all_gather_input_numels` saved to avoid
32
+ # CPU overhead from recomputing
33
+ all_gather_input_split_sizes: list[int]
34
+
35
+
36
+ lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
37
+
38
+ lib.define(
39
+ """
40
+ all_gather_copy_in(
41
+ Tensor[] all_gather_inputs,
42
+ Tensor all_gather_output,
43
+ SymInt[] inp_split_sizes,
44
+ SymInt all_gather_input_numel,
45
+ SymInt rank
46
+ ) -> (Tensor, Tensor)
47
+ """
48
+ )
49
+
50
+
51
+ class DefaultAllocMixin:
52
+ def allocate(
53
+ self,
54
+ size: Sequence[Union[int, torch.SymInt]],
55
+ *,
56
+ dtype: torch.dtype,
57
+ device: torch.device,
58
+ ) -> torch.Tensor:
59
+ return torch.empty(*size, dtype=dtype, device=device)
60
+
61
+
62
+ class ProcessGroupAllocMixin:
63
+ def __init__(self, group: dist.ProcessGroup, *args: Any, **kwargs: Any):
64
+ self._group = group
65
+ super().__init__(*args, **kwargs)
66
+
67
+ def allocate(
68
+ self,
69
+ size: Sequence[Union[int, torch.SymInt]],
70
+ *,
71
+ dtype: torch.dtype,
72
+ device: torch.device,
73
+ ) -> torch.Tensor:
74
+ backend = self._group._get_backend(device)
75
+ if backend.supports_tensor_alloc(device):
76
+ size_1d = math.prod(int(s) for s in size)
77
+ return backend.allocate_tensor(size_1d, dtype=dtype, device=device)
78
+ return torch.empty(*size, dtype=dtype, device=device)
79
+
80
+
81
+ class DefaultAllGather(DefaultAllocMixin, AllGather):
82
+ def __call__(
83
+ self,
84
+ output_tensor: torch.Tensor,
85
+ input_tensor: torch.Tensor,
86
+ group: dist.ProcessGroup,
87
+ async_op: bool = False,
88
+ ) -> Optional[dist.Work]:
89
+ return dist.all_gather_into_tensor(
90
+ output_tensor,
91
+ input_tensor,
92
+ group=group,
93
+ async_op=async_op,
94
+ )
95
+
96
+
97
+ class ProcessGroupAllocAllGather(ProcessGroupAllocMixin, AllGather):
98
+ def __init__(self, group: dist.ProcessGroup) -> None:
99
+ super().__init__(group)
100
+
101
+ def __call__(
102
+ self,
103
+ output_tensor: torch.Tensor,
104
+ input_tensor: torch.Tensor,
105
+ group: dist.ProcessGroup,
106
+ async_op: bool = False,
107
+ ) -> Optional[dist.Work]:
108
+ return dist.all_gather_into_tensor(
109
+ output_tensor,
110
+ input_tensor,
111
+ group=group,
112
+ async_op=async_op,
113
+ )
114
+
115
+
116
+ class DefaultReduceScatter(DefaultAllocMixin, ReduceScatter):
117
+ def __call__(
118
+ self,
119
+ output_tensor: torch.Tensor,
120
+ input_tensor: torch.Tensor,
121
+ group: dist.ProcessGroup,
122
+ op: _ReduceOp,
123
+ async_op: bool = False,
124
+ ) -> dist.Work:
125
+ return dist.reduce_scatter_tensor(
126
+ output=output_tensor,
127
+ input=input_tensor,
128
+ group=group,
129
+ op=op,
130
+ async_op=async_op,
131
+ )
132
+
133
+
134
+ class ProcessGroupAllocReduceScatter(ProcessGroupAllocMixin, ReduceScatter):
135
+ def __init__(self, group: dist.ProcessGroup) -> None:
136
+ super().__init__(group)
137
+
138
+ def __call__(
139
+ self,
140
+ output_tensor: torch.Tensor,
141
+ input_tensor: torch.Tensor,
142
+ group: dist.ProcessGroup,
143
+ op: _ReduceOp,
144
+ async_op: bool = False,
145
+ ) -> dist.Work:
146
+ return dist.reduce_scatter_tensor(
147
+ output=output_tensor,
148
+ input=input_tensor,
149
+ group=group,
150
+ op=op,
151
+ async_op=async_op,
152
+ )
153
+
154
+
155
+ @torch.library.impl(lib, "all_gather_copy_in", "Meta")
156
+ def all_gather_copy_in_meta(
157
+ all_gather_inputs: list[torch.Tensor],
158
+ all_gather_output: torch.Tensor,
159
+ inp_split_sizes: list[int],
160
+ all_gather_input_numel: int,
161
+ rank: int,
162
+ ) -> tuple[torch.Tensor, torch.Tensor]:
163
+ all_gather_input = all_gather_output.narrow(
164
+ 0, all_gather_input_numel * rank, all_gather_input_numel
165
+ )
166
+ return all_gather_input, all_gather_output
167
+
168
+
169
+ @torch.library.impl(lib, "all_gather_copy_in", "CUDA")
170
+ @torch.library.impl(lib, "all_gather_copy_in", "XPU")
171
+ @torch.library.impl(lib, "all_gather_copy_in", "HPU")
172
+ @torch.library.impl(lib, "all_gather_copy_in", "CPU")
173
+ @torch.library.impl(lib, "all_gather_copy_in", "MTIA")
174
+ @torch.library.impl(lib, "all_gather_copy_in", "PrivateUse1")
175
+ def all_gather_copy_in_cuda(
176
+ all_gather_inputs: list[torch.Tensor],
177
+ all_gather_output: torch.Tensor,
178
+ inp_split_sizes: list[int],
179
+ all_gather_input_numel: int,
180
+ rank: int,
181
+ ) -> tuple[torch.Tensor, torch.Tensor]:
182
+ all_gather_input = all_gather_output.narrow(
183
+ 0, all_gather_input_numel * rank, all_gather_input_numel
184
+ )
185
+ foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
186
+ with torch.no_grad():
187
+ torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
188
+ return all_gather_input, all_gather_output
189
+
190
+
191
+ lib.define(
192
+ "split_with_sizes_copy(Tensor all_gather_output, SymInt[] all_gather_input_split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()"
193
+ )
194
+
195
+
196
+ @torch.library.impl(lib, "split_with_sizes_copy", "Meta")
197
+ @torch.library.impl(lib, "split_with_sizes_copy", "CUDA")
198
+ @torch.library.impl(lib, "split_with_sizes_copy", "XPU")
199
+ @torch.library.impl(lib, "split_with_sizes_copy", "HPU")
200
+ @torch.library.impl(lib, "split_with_sizes_copy", "CPU")
201
+ @torch.library.impl(lib, "split_with_sizes_copy", "MTIA")
202
+ @torch.library.impl(lib, "split_with_sizes_copy", "PrivateUse1")
203
+ def split_with_sizes_copy(
204
+ all_gather_output: torch.Tensor,
205
+ all_gather_input_split_sizes: list[int],
206
+ dim: int,
207
+ out: list[torch.Tensor],
208
+ ) -> None:
209
+ torch.split_with_sizes_copy(
210
+ all_gather_output, all_gather_input_split_sizes, dim=dim, out=out
211
+ )
212
+
213
+
214
+ lib.define(
215
+ "chunk_cat(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"
216
+ )
217
+
218
+
219
+ @torch.library.impl(lib, "chunk_cat", "Meta")
220
+ @torch.library.impl(lib, "chunk_cat", "CUDA")
221
+ @torch.library.impl(lib, "chunk_cat", "XPU")
222
+ @torch.library.impl(lib, "chunk_cat", "HPU")
223
+ @torch.library.impl(lib, "chunk_cat", "CPU")
224
+ @torch.library.impl(lib, "chunk_cat", "MTIA")
225
+ @torch.library.impl(lib, "chunk_cat", "PrivateUse1")
226
+ def chunk_cat(
227
+ tensors: list[torch.Tensor],
228
+ dim: int,
229
+ num_chunks: int,
230
+ out: torch.Tensor,
231
+ ) -> None:
232
+ torch._chunk_cat(tensors, dim, num_chunks, out=out)
233
+
234
+
235
+ @torch.no_grad()
236
+ def foreach_all_gather(
237
+ fsdp_params: list[FSDPParam],
238
+ group: dist.ProcessGroup,
239
+ async_op: bool,
240
+ all_gather_copy_in_stream: torch.Stream,
241
+ all_gather_stream: torch.Stream,
242
+ device: torch.device,
243
+ all_gather_comm: AllGather,
244
+ ) -> Optional[AllGatherResult]:
245
+ world_size, rank = group.size(), group.rank()
246
+ device_handle = _get_device_handle(device.type)
247
+ with device_handle.stream(all_gather_copy_in_stream):
248
+ param_all_gather_inputs = _get_param_all_gather_inputs(fsdp_params)
249
+ (
250
+ param_all_gather_input_dtypes,
251
+ param_all_gather_input_numels,
252
+ dtype,
253
+ ) = _get_all_gather_input_metadatas(param_all_gather_inputs)
254
+ if dtype == torch.uint8:
255
+ all_gather_inputs = [
256
+ t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
257
+ ]
258
+ else:
259
+ all_gather_inputs = [*chain.from_iterable(param_all_gather_inputs)]
260
+ inp_split_sizes = [t.numel() for t in all_gather_inputs]
261
+ all_gather_input_numel = sum(inp_split_sizes)
262
+ all_gather_output = all_gather_comm.allocate(
263
+ (all_gather_input_numel * world_size,), dtype=dtype, device=device
264
+ )
265
+ all_gather_input, all_gather_output = torch.ops.fsdp.all_gather_copy_in(
266
+ all_gather_inputs,
267
+ all_gather_output,
268
+ inp_split_sizes,
269
+ all_gather_input_numel,
270
+ rank,
271
+ )
272
+ del param_all_gather_inputs
273
+ all_gather_stream.wait_stream(all_gather_copy_in_stream)
274
+ with device_handle.stream(all_gather_stream):
275
+ all_gather_work = all_gather_comm(
276
+ output_tensor=all_gather_output,
277
+ input_tensor=all_gather_input,
278
+ group=group,
279
+ async_op=async_op,
280
+ )
281
+ all_gather_event = all_gather_stream.record_event()
282
+ return AllGatherResult(
283
+ all_gather_output,
284
+ all_gather_event,
285
+ all_gather_work,
286
+ param_all_gather_input_dtypes,
287
+ param_all_gather_input_numels,
288
+ inp_split_sizes,
289
+ )
290
+
291
+
292
+ @torch.no_grad()
293
+ def _get_param_all_gather_inputs(
294
+ fsdp_params: list[FSDPParam],
295
+ ) -> list[list[torch.Tensor]]:
296
+ if compiled_autograd_enabled():
297
+ return [fsdp_param.all_gather_inputs for fsdp_param in fsdp_params]
298
+
299
+ # Intentionally try to run a fast-path that bypasses abstractions for the
300
+ # common FSDP case of bf16/fp32 mixed precision in order to use foreach
301
+ # copy for lower CPU overhead and more efficient copying in eager
302
+ def use_foreach_copy(fsdp_param: FSDPParam) -> bool:
303
+ return (
304
+ fsdp_param.param_dtype is not None
305
+ and not fsdp_param.offload_to_cpu
306
+ and not hasattr(fsdp_param._sharded_local_tensor, "fsdp_pre_all_gather")
307
+ )
308
+
309
+ param_all_gather_inputs: list[list[torch.Tensor]] = [[] for _ in fsdp_params]
310
+ foreach_copy_indices: list[int] = []
311
+ foreach_copy_inputs: list[torch.Tensor] = []
312
+ foreach_copy_input_numels: list[int] = []
313
+
314
+ # 1st pass: for foreach-copy parameters, get inputs and metadata for the
315
+ # foreach copy, and for the others, actually get their all-gather inputs
316
+ for i, fsdp_param in enumerate(fsdp_params):
317
+ if use_foreach_copy(fsdp_param):
318
+ foreach_copy_indices.append(i)
319
+ all_gather_input = (
320
+ fsdp_param._sharded_param_data
321
+ if fsdp_param.sharded_state == ShardedState.SHARDED
322
+ else cast(torch.Tensor, fsdp_param._sharded_post_forward_param_data)
323
+ )
324
+ foreach_copy_inputs.append(all_gather_input)
325
+ foreach_copy_input_numels.append(all_gather_input.numel())
326
+ else:
327
+ param_all_gather_inputs[i] = fsdp_param.all_gather_inputs
328
+
329
+ # 2nd pass: use foreach copy to compute the remaining all-gather inputs
330
+ if foreach_copy_inputs:
331
+ fsdp_param_0 = fsdp_params[foreach_copy_indices[0]]
332
+ param_dtype, device = fsdp_param_0.param_dtype, fsdp_param_0.device
333
+ flat_foreach_copy_input = torch.empty(
334
+ (sum(foreach_copy_input_numels),), device=device, dtype=param_dtype
335
+ )
336
+ splits = torch.split(flat_foreach_copy_input, foreach_copy_input_numels)
337
+ torch._foreach_copy_(splits, foreach_copy_inputs)
338
+ for i, split in zip(foreach_copy_indices, splits):
339
+ param_all_gather_inputs[i] = [split]
340
+
341
+ return param_all_gather_inputs
342
+
343
+
344
+ @torch.no_grad()
345
+ def foreach_all_gather_copy_out(
346
+ all_gather_result: AllGatherResult,
347
+ fsdp_params: list[FSDPParam],
348
+ group: dist.ProcessGroup,
349
+ ) -> None:
350
+ (
351
+ all_gather_output,
352
+ all_gather_event,
353
+ all_gather_work,
354
+ param_all_gather_input_dtypes,
355
+ param_all_gather_input_numels,
356
+ all_gather_input_split_sizes,
357
+ ) = all_gather_result
358
+ _dtype, device = all_gather_output.dtype, all_gather_output.device
359
+ device_handle = _get_device_handle(device.type)
360
+ if all_gather_event is not None: # sync op
361
+ device_handle.current_stream().wait_event(all_gather_event)
362
+ if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
363
+ all_gather_work.wait()
364
+ world_size, device = group.size(), all_gather_output.device
365
+
366
+ split_with_sizes_out: list[torch.Tensor] = []
367
+ shard_i_copy_infos: list[tuple[FSDPParam, list[torch.Tensor]]] = []
368
+ for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
369
+ param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
370
+ ):
371
+ # NOTE: Under compile, make sure we always recreate all_gather_outputs
372
+ # per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
373
+ force_recreate = compiled_autograd_enabled()
374
+ fsdp_param.init_all_gather_outputs(
375
+ all_gather_input_numels,
376
+ all_gather_input_dtypes,
377
+ world_size,
378
+ device,
379
+ force_recreate=force_recreate,
380
+ )
381
+ if not force_recreate:
382
+ fsdp_param.alloc_all_gather_outputs()
383
+ param_all_gather_outputs = fsdp_param.all_gather_outputs
384
+ if fsdp_param.fsdp_placement.dim != 0:
385
+ # Copy to a temporary and then chunk-cat into the final all-gather
386
+ # output tensors
387
+ param_all_gather_outputs = [
388
+ torch.empty_like(t) for t in param_all_gather_outputs
389
+ ]
390
+ shard_i_copy_infos.append((fsdp_param, param_all_gather_outputs))
391
+ split_with_sizes_out.extend(param_all_gather_outputs)
392
+
393
+ all_gather_output = all_gather_output.view(world_size, -1)
394
+ if all_gather_output.dtype == torch.uint8:
395
+ out = [t.view(world_size, -1).view(torch.uint8) for t in split_with_sizes_out]
396
+ else:
397
+ out = [t.view(world_size, -1) for t in split_with_sizes_out]
398
+
399
+ # only avoid VC bump if we are not in inference mode
400
+ if torch._dynamo.is_compiling():
401
+ # For torch.compile, we turn off inference_mode for fake tensor
402
+ # propagation, and therefore graph break on is_inference. For `compile`,
403
+ # we don't care about VCs, so just skip the optimization.
404
+ non_inference_outs = []
405
+ else:
406
+ non_inference_outs = [o for o in out if not o.is_inference()]
407
+
408
+ if len(non_inference_outs) > 0:
409
+ with torch.autograd._unsafe_preserve_version_counter(tuple(non_inference_outs)):
410
+ torch.ops.fsdp.split_with_sizes_copy(
411
+ all_gather_output, all_gather_input_split_sizes, dim=1, out=out
412
+ )
413
+ else:
414
+ torch.ops.fsdp.split_with_sizes_copy(
415
+ all_gather_output, all_gather_input_split_sizes, dim=1, out=out
416
+ )
417
+
418
+ for fsdp_param, param_all_gather_outputs in shard_i_copy_infos:
419
+ # Chunk-cat from the temporary to the final all-gather output tensors
420
+ shard_dim = fsdp_param.fsdp_placement.dim
421
+
422
+ with torch.autograd._unsafe_preserve_version_counter(
423
+ tuple(fsdp_param.all_gather_outputs)
424
+ ):
425
+ for param_all_gather_output, target_all_gather_output in zip(
426
+ param_all_gather_outputs, fsdp_param.all_gather_outputs
427
+ ):
428
+ padded_sharded_size = (
429
+ fsdp_param.padded_sharded_param_size
430
+ if fsdp_param.sharded_state == ShardedState.SHARDED
431
+ else cast(
432
+ torch.Tensor, fsdp_param._sharded_post_forward_param_data
433
+ ).size()
434
+ )
435
+ pre_param_size = list(padded_sharded_size)
436
+ pre_param_size[0] *= world_size
437
+ chunks = torch.chunk(
438
+ param_all_gather_output.view(pre_param_size), world_size, dim=0
439
+ )
440
+ post_param_size = list(padded_sharded_size)
441
+ post_param_size[shard_dim] *= world_size
442
+ cat_out = target_all_gather_output.view(post_param_size)
443
+ torch.cat(chunks, dim=shard_dim, out=cat_out)
444
+
445
+
446
+ @torch.no_grad()
447
+ def foreach_reduce(
448
+ fsdp_params: list[FSDPParam],
449
+ unsharded_grads: list[torch.Tensor],
450
+ reduce_scatter_group: dist.ProcessGroup,
451
+ reduce_scatter_stream: torch.Stream,
452
+ reduce_scatter_comm: ReduceScatter,
453
+ orig_dtype: Optional[torch.dtype],
454
+ reduce_dtype: Optional[torch.dtype],
455
+ device: torch.device,
456
+ gradient_divide_factor: Optional[float],
457
+ all_reduce_group: Optional[dist.ProcessGroup], # not `None` iff HSDP
458
+ all_reduce_stream: torch.Stream,
459
+ all_reduce_grads: bool,
460
+ partial_reduce_output: Optional[torch.Tensor], # only used for HSDP
461
+ all_reduce_hook: Optional[Callable[[torch.Tensor], None]],
462
+ force_sum_reduction_for_comms: bool = False,
463
+ ) -> tuple[
464
+ torch.Tensor,
465
+ torch.Event,
466
+ torch.Event,
467
+ Optional[torch.Tensor],
468
+ Optional[torch.Event],
469
+ Optional[torch.Tensor],
470
+ ]:
471
+ """
472
+ ``unsharded_grads`` owns the references to the gradients computed by
473
+ autograd, so clearing the list frees the gradients.
474
+ """
475
+
476
+ grad_dtypes = {grad.dtype for grad in unsharded_grads}
477
+ if len(grad_dtypes) != 1:
478
+ # Check this at runtime since it could be a real runtime error if e.g.
479
+ # fp8 weights do not produce the correct higher precision gradients
480
+ _raise_assert_with_print(
481
+ f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
482
+ )
483
+ grad_dtype = unsharded_grads[0].dtype
484
+ reduce_dtype = reduce_dtype or grad_dtype
485
+ (predivide_factor, postdivide_factor, reduce_scatter_op, all_reduce_op) = (
486
+ _get_gradient_divide_factors(
487
+ reduce_scatter_group,
488
+ all_reduce_group,
489
+ reduce_dtype,
490
+ device.type,
491
+ gradient_divide_factor,
492
+ force_sum_reduction_for_comms,
493
+ )
494
+ )
495
+
496
+ if reduce_scatter_group is None:
497
+ world_size = 1
498
+ else:
499
+ world_size = reduce_scatter_group.size()
500
+ device_handle = _get_device_handle(device.type)
501
+ current_stream = device_handle.current_stream()
502
+
503
+ if world_size > 1:
504
+ for i, (fsdp_param, unsharded_grad) in enumerate(
505
+ zip(fsdp_params, unsharded_grads)
506
+ ):
507
+ if (shard_dim := fsdp_param.fsdp_placement.dim) == 0:
508
+ continue
509
+ if unsharded_grad.size(shard_dim) % world_size != 0:
510
+ raise AssertionError(
511
+ f"Shard({shard_dim}) requires even sharding: {unsharded_grad.size()=} {world_size=}"
512
+ )
513
+ chunks = torch.chunk(unsharded_grad, world_size, dim=shard_dim)
514
+ unsharded_grads[i] = torch.cat(chunks, dim=0)
515
+
516
+ padded_unsharded_sizes = tuple(
517
+ _get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
518
+ )
519
+ reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
520
+ reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
521
+ reduce_scatter_input = reduce_scatter_comm.allocate(
522
+ (reduce_scatter_input_numel,),
523
+ dtype=reduce_dtype,
524
+ device=device,
525
+ )
526
+
527
+ foreach_reduce_scatter_copy_in(unsharded_grads, reduce_scatter_input, world_size)
528
+
529
+ # Only after the copy-in finishes can we free the gradients
530
+ unsharded_grads.clear()
531
+ reduce_scatter_stream.wait_stream(current_stream)
532
+ all_reduce_input = None
533
+ all_reduce_event = None
534
+
535
+ with device_handle.stream(reduce_scatter_stream):
536
+ reduce_output = reduce_scatter_comm.allocate(
537
+ (reduce_scatter_output_numel,),
538
+ dtype=reduce_dtype,
539
+ device=device,
540
+ )
541
+ _div_if_needed(reduce_scatter_input, predivide_factor)
542
+ if world_size > 1:
543
+ reduce_scatter_comm(
544
+ output_tensor=reduce_output,
545
+ input_tensor=reduce_scatter_input,
546
+ group=reduce_scatter_group,
547
+ op=reduce_scatter_op,
548
+ )
549
+ else:
550
+ # For single GPU, just copy the input to output (no actual reduce-scatter needed), and
551
+ # account for a possible gradient_divide_factor.
552
+ if gradient_divide_factor is not None:
553
+ reduce_output.copy_(reduce_scatter_input / gradient_divide_factor)
554
+ else:
555
+ reduce_output.copy_(reduce_scatter_input)
556
+ reduce_scatter_event = reduce_scatter_stream.record_event()
557
+ post_reduce_stream = reduce_scatter_stream
558
+ if all_reduce_group is not None: # HSDP or DDP/replicate
559
+ # Accumulations must run in the reduce-scatter stream
560
+ if not all_reduce_grads:
561
+ if partial_reduce_output is not None:
562
+ partial_reduce_output += reduce_output
563
+ else:
564
+ partial_reduce_output = reduce_output
565
+ return (
566
+ reduce_scatter_input,
567
+ reduce_scatter_event,
568
+ post_reduce_stream.record_event(),
569
+ all_reduce_input,
570
+ all_reduce_event,
571
+ partial_reduce_output,
572
+ )
573
+ if partial_reduce_output is not None:
574
+ reduce_output += partial_reduce_output
575
+ post_reduce_stream = all_reduce_stream
576
+ if world_size >= 1:
577
+ all_reduce_stream.wait_stream(reduce_scatter_stream)
578
+ else:
579
+ all_reduce_stream.wait_stream(current_stream)
580
+ with device_handle.stream(all_reduce_stream):
581
+ dist.all_reduce(
582
+ reduce_output,
583
+ group=all_reduce_group,
584
+ op=all_reduce_op,
585
+ )
586
+ all_reduce_input = reduce_output
587
+ all_reduce_event = all_reduce_stream.record_event()
588
+ # -- END: ops in reduce_scatter stream
589
+
590
+ if all_reduce_hook is not None:
591
+ # Execute user-specified all reduce hook.
592
+ # If native HSDP is used, this is executed after the HSDP all reduce.
593
+ # If 1-d FSDP is used, this is executed post reduce-scatter.
594
+ post_reduce_stream = all_reduce_stream
595
+ all_reduce_stream.wait_stream(reduce_scatter_stream)
596
+ with device_handle.stream(all_reduce_stream):
597
+ all_reduce_hook(reduce_output)
598
+ # -- END: ops post reduce_scatter
599
+
600
+ with device_handle.stream(post_reduce_stream):
601
+ _div_if_needed(reduce_output, postdivide_factor)
602
+ reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
603
+ # View out and accumulate sharded gradients
604
+ flat_grad_offset = 0 # [0, reduce_scatter_output_numel - 1]
605
+ for padded_unsharded_size, fsdp_param in zip(
606
+ padded_unsharded_sizes, fsdp_params
607
+ ):
608
+ # Assume even sharding for Shard(i), i > 0; otherwise would require
609
+ # copy-out for contiguous strides
610
+ new_sharded_grad = torch.as_strided(
611
+ reduce_output,
612
+ size=fsdp_param.sharded_size,
613
+ stride=fsdp_param.contiguous_sharded_stride,
614
+ storage_offset=flat_grad_offset,
615
+ )
616
+ to_accumulate_grad = fsdp_param.sharded_param.grad is not None
617
+ if fsdp_param.offload_to_cpu:
618
+ # Only overlap the D2H copy (copying to pinned memory) if not
619
+ # accumulating gradients since the CPU add kernel depends on
620
+ # the copy result and we cannot run the add as a callback
621
+ non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
622
+ # Since the GPU sharded gradient is allocated in the RS stream,
623
+ # we can free it here by not keeping a ref without waiting for
624
+ # the D2H copy since future RS-stream ops run after the copy
625
+ new_sharded_grad = new_sharded_grad.to(
626
+ torch.device("cpu"), non_blocking=non_blocking
627
+ )
628
+ if non_blocking:
629
+ # Record an event on which to block the CPU thread to
630
+ # ensure that the D2H copy finishes before the optimizer
631
+ fsdp_param.grad_offload_event = post_reduce_stream.record_event()
632
+ if to_accumulate_grad:
633
+ if not isinstance(fsdp_param.sharded_param.grad, DTensor):
634
+ raise AssertionError(
635
+ f"Expected fsdp_param.sharded_param.grad to be DTensor, got {type(fsdp_param.sharded_param.grad)}"
636
+ )
637
+ fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
638
+ else:
639
+ new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
640
+ new_sharded_grad
641
+ )
642
+ fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
643
+ if not compiled_autograd_enabled():
644
+ for hook in (
645
+ getattr(fsdp_param.sharded_param, "_post_accumulate_grad_hooks", {})
646
+ or {}
647
+ ).values():
648
+ hook(fsdp_param.sharded_param)
649
+ padded_sharded_numel = padded_unsharded_size.numel() // world_size
650
+ flat_grad_offset += padded_sharded_numel
651
+ post_reduce_event = post_reduce_stream.record_event()
652
+ # The RS output is allocated in the RS stream and used in the default
653
+ # stream (for optimizer). To ensure its memory is not reused for later
654
+ # RSs, we do not need extra synchronization since the sharded parameters
655
+ # hold refs through the end of backward.
656
+ return (
657
+ reduce_scatter_input,
658
+ reduce_scatter_event,
659
+ post_reduce_event,
660
+ all_reduce_input,
661
+ all_reduce_event,
662
+ None,
663
+ )
664
+
665
+
666
+ def foreach_reduce_scatter_copy_in(
667
+ unsharded_grads: list[torch.Tensor],
668
+ reduce_scatter_input: torch.Tensor,
669
+ world_size: int,
670
+ ) -> None:
671
+ reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
672
+ torch.ops.fsdp.chunk_cat(
673
+ unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
674
+ )
675
+
676
+
677
+ def _get_all_gather_input_metadatas(
678
+ param_all_gather_inputs: list[list[torch.Tensor]],
679
+ ) -> tuple[list[list[torch.dtype]], list[list[int]], torch.dtype]:
680
+ param_all_gather_input_dtypes: list[list[torch.dtype]] = []
681
+ param_all_gather_input_numels: list[list[int]] = []
682
+ all_gather_dtype = param_all_gather_inputs[0][0].dtype
683
+ for all_gather_inputs in param_all_gather_inputs:
684
+ input_dtypes: list[torch.dtype] = []
685
+ input_numels: list[int] = []
686
+ for all_gather_input in all_gather_inputs:
687
+ if all_gather_input.dtype != all_gather_dtype:
688
+ all_gather_dtype = torch.uint8
689
+ input_dtypes.append(all_gather_input.dtype)
690
+ input_numels.append(all_gather_input.numel())
691
+ param_all_gather_input_dtypes.append(input_dtypes)
692
+ param_all_gather_input_numels.append(input_numels)
693
+ return (
694
+ param_all_gather_input_dtypes,
695
+ param_all_gather_input_numels,
696
+ all_gather_dtype,
697
+ )
698
+
699
+
700
+ def _get_gradient_divide_factors(
701
+ reduce_scatter_group: Optional[dist.ProcessGroup],
702
+ all_reduce_group: Optional[dist.ProcessGroup],
703
+ reduce_dtype: torch.dtype,
704
+ device_type: str = "",
705
+ factor: Optional[float] = None,
706
+ force_sum_reduction_for_comms: bool = False,
707
+ ) -> tuple[
708
+ Optional[float],
709
+ Optional[float],
710
+ Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
711
+ Union[dist.ReduceOp, dist.ReduceOp.RedOpType],
712
+ ]:
713
+ # MTIA appears to only support SUM reduction, hence we force it implicitly
714
+ if device_type == "mtia":
715
+ force_sum_reduction_for_comms = True
716
+
717
+ # For fp32/bf16, we do not need to worry about overflow/underflow, so we
718
+ # use NCCL's built-in division to avoid separate div kernels
719
+ overflow_risk = reduce_dtype not in (torch.float32, torch.bfloat16)
720
+ if reduce_scatter_group is not None:
721
+ data_parallel_size = reduce_scatter_group.size()
722
+ else:
723
+ data_parallel_size = 1
724
+
725
+ if all_reduce_group is not None:
726
+ data_parallel_size *= all_reduce_group.size()
727
+
728
+ if not overflow_risk and not force_sum_reduction_for_comms:
729
+ if factor is None:
730
+ # Warning: NCCL ReduceOp.AVG may produce incorrect results with
731
+ # world size 1.
732
+ if data_parallel_size == 1:
733
+ return None, None, ReduceOp.SUM, ReduceOp.SUM
734
+ return None, None, ReduceOp.AVG, ReduceOp.AVG
735
+ if reduce_scatter_group is not None and factor == reduce_scatter_group.size():
736
+ reduce_scatter_op = ReduceOp.AVG
737
+ else:
738
+ reduce_scatter_op = torch.distributed._make_nccl_premul_sum(1 / factor)
739
+ return None, None, reduce_scatter_op, ReduceOp.SUM
740
+
741
+ if factor is None:
742
+ factor = float(data_parallel_size)
743
+ pre_factor: Optional[float]
744
+ if overflow_risk:
745
+ # Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
746
+ # overflow/underflow. For N data parallel workers, each worker computes
747
+ # g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
748
+ # overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
749
+ pre_factor = 1
750
+ while factor % pre_factor == 0 and factor / pre_factor > pre_factor:
751
+ pre_factor *= 2
752
+ post_factor = factor / pre_factor
753
+ else:
754
+ # Prefer post-multiplying as it operates on less data and is thus faster
755
+ pre_factor, post_factor = None, factor
756
+
757
+ return pre_factor, post_factor, ReduceOp.SUM, ReduceOp.SUM
758
+
759
+
760
+ def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
761
+ if div_factor is not None and div_factor != 1:
762
+ tensor.div_(div_factor)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_common.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ import traceback
4
+ from dataclasses import dataclass
5
+ from enum import auto, Enum
6
+ from typing import Any, Optional
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+ import torch.nn as nn
11
+ from torch.distributed._composable.contract import _get_registry
12
+ from torch.distributed.tensor import DeviceMesh, DTensor
13
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
14
+
15
+
16
+ _compiled_autograd_enabled: bool = False
17
+
18
+
19
+ def detect_compiled_autograd():
20
+ if torch.compiler.is_compiling():
21
+ raise AssertionError(
22
+ "`detect_compiled_autograd()` is designed to be called in eager mode"
23
+ )
24
+ global _compiled_autograd_enabled
25
+ import torch._dynamo.compiled_autograd as ca
26
+
27
+ _compiled_autograd_enabled = (
28
+ ca.compiled_autograd_enabled
29
+ or ca.compiled_autograd_enabled_force_eager
30
+ or ca.in_compiled_autograd_region
31
+ )
32
+
33
+
34
+ def compiled_autograd_enabled():
35
+ global _compiled_autograd_enabled
36
+ return _compiled_autograd_enabled
37
+
38
+
39
+ @dataclass
40
+ class DataParallelMeshInfo:
41
+ mesh: DeviceMesh
42
+ shard_mesh_dim: Optional[int] = None
43
+ replicate_mesh_dim: Optional[int] = None
44
+
45
+ def __post_init__(self):
46
+ if self.shard_mesh_dim is None and self.replicate_mesh_dim is None:
47
+ raise AssertionError(
48
+ "At least one of shard_mesh_dim and replicate_mesh_dim must not be None"
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class FSDPMeshInfo(DataParallelMeshInfo):
54
+ def __post_init__(self):
55
+ super().__post_init__()
56
+ if self.shard_mesh_dim is None:
57
+ raise AssertionError("Expects non-None shard_mesh_dim")
58
+ self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim)
59
+ self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim)
60
+ self.shard_mesh_rank: int = self.shard_process_group.rank()
61
+
62
+
63
+ @dataclass
64
+ class DDPMeshInfo(DataParallelMeshInfo):
65
+ def __post_init__(self):
66
+ super().__post_init__()
67
+ if self.replicate_mesh_dim is None:
68
+ raise AssertionError("Expects non-None replicate_mesh_dim")
69
+ self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim)
70
+ self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim)
71
+ self.replicate_mesh_rank: int = self.replicate_process_group.rank()
72
+
73
+
74
+ @dataclass
75
+ class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo):
76
+ def __post_init__(self): # pylint:disable=useless-parent-delegation
77
+ # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo`
78
+ super().__post_init__()
79
+
80
+
81
+ class TrainingState(Enum):
82
+ """Describes the training state of one FSDP state / parameter group."""
83
+
84
+ # Transition to forward starting pre-forward until post-forward
85
+ FORWARD = auto()
86
+ # Transition to pre-backward when unsharding in backward
87
+ PRE_BACKWARD = auto()
88
+ # Transition to post-backward when resharding and reducing gradients
89
+ POST_BACKWARD = auto()
90
+ # Idle before/after forward or before pre-backward/after post-backward
91
+ IDLE = auto()
92
+
93
+
94
+ def _raise_assert_with_print(*args: Any, **kwargs: Any):
95
+ print(f"[Rank {dist.get_rank()}] ", end="")
96
+ print(*args, **kwargs)
97
+ traceback.print_stack()
98
+ raise AssertionError(*args, **kwargs)
99
+
100
+
101
+ def _is_composable_with_fsdp(module: nn.Module) -> bool:
102
+ registry = _get_registry(module)
103
+ if registry is None:
104
+ return True
105
+ # Registry keys by function name
106
+ return "replicate" not in registry
107
+
108
+
109
+ def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size:
110
+ padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor
111
+ return torch.Size([padded_dim0]) + tensor_size[1:]
112
+
113
+
114
+ def _chunk_with_empty(
115
+ tensor: torch.Tensor, num_chunks: int, dim: int
116
+ ) -> list[torch.Tensor]:
117
+ chunks = list(torch.chunk(tensor, num_chunks, dim=dim))
118
+ while len(chunks) < num_chunks:
119
+ chunks.append(chunks[0].new_empty(0))
120
+ return chunks
121
+
122
+
123
+ def _get_dim_chunked_size(
124
+ chunk: torch.Tensor, unchunked_size: torch.Size, dim: int
125
+ ) -> torch.Size:
126
+ if chunk.numel() > 0:
127
+ return chunk.size()
128
+ # For 0 numel, we need to preserve nonzero-sized dims for DTensor APIs
129
+ return unchunked_size[:dim] + torch.Size([0]) + unchunked_size[dim + 1 :]
130
+
131
+
132
+ def _from_local_no_grad(
133
+ local_tensor: torch.Tensor,
134
+ sharding_spec: DTensorSpec,
135
+ ) -> DTensor:
136
+ """
137
+ This method is similar to ``DTensor.from_local()`` except that in eager mode
138
+ it avoids some CPU overhead by avoiding default args and not being differentiable.
139
+ """
140
+
141
+ if not compiled_autograd_enabled():
142
+ # pyrefly: ignore [bad-argument-type]
143
+ return DTensor(
144
+ # Use the local tensor directly instead of constructing a new tensor
145
+ # variable, e.g. with `view_as()`, since this is not differentiable
146
+ # pyrefly: ignore [bad-argument-count]
147
+ local_tensor,
148
+ sharding_spec,
149
+ # pyrefly: ignore [unexpected-keyword]
150
+ requires_grad=local_tensor.requires_grad,
151
+ )
152
+ else:
153
+ return DTensor.from_local(
154
+ local_tensor,
155
+ sharding_spec.mesh,
156
+ sharding_spec.placements,
157
+ shape=sharding_spec.shape,
158
+ stride=sharding_spec.stride,
159
+ )
160
+
161
+
162
+ def _to_dtype_if_needed(
163
+ tensor: torch.Tensor, dtype: Optional[torch.dtype]
164
+ ) -> torch.Tensor:
165
+ if dtype is not None and tensor.dtype != dtype:
166
+ return tensor.to(dtype)
167
+ return tensor
168
+
169
+
170
+ def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor:
171
+ if (
172
+ not isinstance(x, torch.Tensor)
173
+ or not torch.is_floating_point(x)
174
+ or x.dtype == dtype
175
+ ):
176
+ return x
177
+ return x.to(dtype)
178
+
179
+
180
+ def is_bw() -> bool:
181
+ return torch._C._current_graph_task_id() != -1
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_init.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import logging
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ import torch.distributed as dist
7
+ import torch.nn as nn
8
+ from torch._logging import warning_once
9
+ from torch.distributed.device_mesh import _get_device_handle
10
+ from torch.distributed.tensor import DeviceMesh, DTensor, init_device_mesh
11
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
12
+
13
+ from ._fsdp_common import _is_composable_with_fsdp, FSDPMeshInfo, HSDPMeshInfo
14
+ from ._fsdp_state import _get_module_fsdp_state
15
+
16
+
17
+ logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
18
+
19
+
20
+ def _get_post_forward_mesh_info(
21
+ reshard_after_forward: Union[bool, int], mesh_info: FSDPMeshInfo
22
+ ) -> Optional[FSDPMeshInfo]:
23
+ shard_mesh_size = mesh_info.shard_mesh_size
24
+ if not isinstance(reshard_after_forward, (bool, int)):
25
+ raise ValueError(
26
+ "reshard_after_forward should be a bool or an int representing the "
27
+ f"group size to reshard to, not {reshard_after_forward}"
28
+ )
29
+ # NOTE: `isinstance(False, int)` returns `True`.
30
+ if not isinstance(reshard_after_forward, bool) and isinstance(
31
+ reshard_after_forward, int
32
+ ):
33
+ if (
34
+ reshard_after_forward < 1
35
+ or reshard_after_forward > shard_mesh_size
36
+ or shard_mesh_size % reshard_after_forward != 0
37
+ ):
38
+ raise ValueError(
39
+ "If passing reshard_after_forward as an int, it should be a "
40
+ f"factor of {shard_mesh_size}, not {reshard_after_forward}"
41
+ )
42
+ elif reshard_after_forward == 1:
43
+ msg = (
44
+ "reshard_after_forward=1 (int) means resharding parameters to world size 1, "
45
+ "instead of reshard_after_forward=True (bool)"
46
+ )
47
+ warning_once(logger, msg, stacklevel=2)
48
+ reshard_after_forward = False
49
+ elif reshard_after_forward == shard_mesh_size:
50
+ reshard_after_forward = True
51
+ post_forward_mesh_info = None
52
+ if reshard_after_forward is True:
53
+ post_forward_mesh_info = mesh_info
54
+ elif reshard_after_forward is not False: # int case
55
+ # For HSDP, we can flatten the two replicate dims into the 0th dim
56
+ post_forward_mesh_tensor = mesh_info.mesh.mesh.view(-1, reshard_after_forward)
57
+ post_forward_mesh = DeviceMesh(
58
+ mesh_info.mesh.device_type, post_forward_mesh_tensor
59
+ )
60
+ post_forward_mesh_info = HSDPMeshInfo(
61
+ post_forward_mesh, shard_mesh_dim=1, replicate_mesh_dim=0
62
+ )
63
+ return post_forward_mesh_info
64
+
65
+
66
+ def _init_default_fully_shard_mesh() -> DeviceMesh:
67
+ """Default to global CUDA mesh if possible else global CPU mesh."""
68
+ if not dist.distributed_c10d.is_initialized():
69
+ dist.distributed_c10d.init_process_group()
70
+ default_pg = dist.distributed_c10d._get_default_group()
71
+ device = torch._C._get_accelerator()
72
+ mesh = init_device_mesh(device.type, mesh_shape=(default_pg.size(),))
73
+ return mesh
74
+
75
+
76
+ def _get_device_from_mesh(mesh: DeviceMesh) -> torch.device:
77
+ if mesh.device_type == "cpu":
78
+ return torch.device("cpu")
79
+ device_handle = _get_device_handle(mesh.device_type)
80
+ return torch.device(mesh.device_type, device_handle.current_device())
81
+
82
+
83
+ def _ignore_module(
84
+ module: nn.Module,
85
+ ignored_params: set[nn.Parameter],
86
+ ignore_decision: dict[nn.Module, bool],
87
+ ) -> bool:
88
+ """
89
+ Decide if it is safe to ignore a module for applying fully_shard.
90
+ """
91
+ if module in ignore_decision:
92
+ return ignore_decision[module]
93
+
94
+ if len(list(module.buffers(recurse=False))) > 0:
95
+ # Cannot ignore a module with any buffer
96
+ ignore_decision[module] = False
97
+ return False
98
+
99
+ for _, param in module.named_parameters(recurse=False):
100
+ if param not in ignored_params:
101
+ # at least one param is not ignored. So this module shouldn't be.
102
+ ignore_decision[module] = False
103
+ return False
104
+
105
+ # Need to consider descendants of module
106
+ for child in list(module.children()):
107
+ ignore_child = _ignore_module(child, ignored_params, ignore_decision)
108
+ if not ignore_child:
109
+ # Cannot ignore module if one of its children is not ignored
110
+ ignore_decision[module] = False
111
+ return False
112
+
113
+ # Safe to ignore module
114
+ ignore_decision[module] = True
115
+ return True
116
+
117
+
118
+ def _adjust_managed_modules(
119
+ modules: list[nn.Module], ignored_params: set[nn.Parameter]
120
+ ) -> list[nn.Module]:
121
+ """
122
+ Adjust the given list of managed modules by removing those with all parameters ignored.
123
+ """
124
+ ignore_decision: dict[nn.Module, bool] = {}
125
+ new_modules = []
126
+ for module in modules:
127
+ ignored = _ignore_module(module, ignored_params, ignore_decision)
128
+ if not ignored:
129
+ new_modules.append(module)
130
+ return new_modules
131
+
132
+
133
+ def _get_managed_modules(
134
+ root_modules: tuple[nn.Module, ...],
135
+ ignored_params: Optional[set[nn.Parameter]] = None,
136
+ ) -> list[nn.Module]:
137
+ modules: list[nn.Module] = []
138
+ root_modules_set = set(root_modules)
139
+ # Track visisted modules to avoid visiting shared modules multiple times
140
+ visited_modules: set[nn.Module] = set()
141
+
142
+ def dfs(module: nn.Module) -> None:
143
+ """
144
+ Runs a DFS to collect managed modules, not recursing into modules with
145
+ a non-composable API or ``fully_shard`` already applied.
146
+ """
147
+ if not _is_composable_with_fsdp(module):
148
+ return
149
+ elif (
150
+ module not in root_modules_set
151
+ and _get_module_fsdp_state(module) is not None
152
+ ):
153
+ return # nested `fully_shard` module
154
+ visited_modules.add(module)
155
+ for submodule in module.children():
156
+ if submodule not in visited_modules:
157
+ dfs(submodule)
158
+ modules.append(module)
159
+
160
+ for root_module in root_modules:
161
+ dfs(root_module)
162
+
163
+ if ignored_params is None:
164
+ return modules
165
+
166
+ adjusted_modules = _adjust_managed_modules(modules, ignored_params)
167
+ return adjusted_modules
168
+
169
+
170
+ def _verify_managed_param(name: str, param: nn.Parameter) -> None:
171
+ """
172
+ Verify if the parameter is accepted by fully_shard. The only restriction now
173
+ is that the parameter cannot be a scalar tensor (param.numel == 0) since we
174
+ need at least one dim to shard.
175
+ """
176
+ if len(param.shape) == 0:
177
+ raise ValueError(
178
+ "fully_shard doesn't support scalar parameters. "
179
+ f"Change {name} to a 1D tensor with numel equal to 1."
180
+ )
181
+
182
+
183
+ def _get_managed_states(
184
+ modules: list[nn.Module], ignored_params: Optional[set[nn.Parameter]] = None
185
+ ) -> tuple[list[nn.Parameter], list[torch.Tensor]]:
186
+ params: list[nn.Parameter] = []
187
+ buffers: list[torch.Tensor] = []
188
+ # Track visited parameters/buffers to avoid visiting shared parameters and
189
+ # buffers multiple times
190
+ visited_params: set[nn.Parameter] = set()
191
+ visited_buffers: set[torch.Tensor] = set()
192
+ if ignored_params is None:
193
+ ignored_params = set()
194
+
195
+ for module in modules:
196
+ for name, param in module.named_parameters(recurse=False):
197
+ if param in ignored_params:
198
+ # do not include an ignored parameters
199
+ continue
200
+ if param not in visited_params:
201
+ _verify_managed_param(name, param)
202
+ params.append(param)
203
+ visited_params.add(param)
204
+ for buffer in module.buffers(recurse=False):
205
+ if buffer not in visited_buffers:
206
+ buffers.append(buffer)
207
+ visited_buffers.add(buffer)
208
+ return params, buffers
209
+
210
+
211
+ def _move_states_to_device(
212
+ params: list[nn.Parameter],
213
+ buffers: list[torch.Tensor],
214
+ device: torch.device,
215
+ ) -> None:
216
+ """
217
+ We have FSDP move states to device for simpler and faster initialization
218
+ since FSDP almost always uses CUDA for training. We move parameters/buffers
219
+ rather than modules since modules to support ignoring parameters/buffers in
220
+ the future.
221
+ """
222
+ # Follow the logic in `nn.Module._apply`
223
+ # pyrefly: ignore [bad-argument-type]
224
+ for tensor in itertools.chain(params, buffers):
225
+ if tensor.device == device or tensor.device.type == "meta":
226
+ # Keep meta-device tensors on meta device for deferred init
227
+ continue
228
+ if isinstance(tensor, DTensor):
229
+ if (dtensor_mesh_type := tensor.device_mesh.device_type) != device.type:
230
+ raise ValueError(
231
+ "Requires DTensor to have mesh of the same type as the FSDP mesh "
232
+ f"but got {dtensor_mesh_type} for DTensor and {device.type} for FSDP"
233
+ )
234
+ raise AssertionError(
235
+ f"Expects DTensor to be moved to {dtensor_mesh_type} but got {tensor.device}"
236
+ )
237
+ tensor_ = tensor
238
+ if is_traceable_wrapper_subclass(tensor_):
239
+ with torch.no_grad(): # avoid autograd increasing C++ refcount by 1
240
+ tensor_on_device = nn.Parameter(tensor.to(device))
241
+ torch.utils.swap_tensors(tensor, tensor_on_device)
242
+ else:
243
+ tensor.data = tensor.to(device)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_param.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ import itertools
4
+ from collections.abc import Callable, Sequence
5
+ from dataclasses import dataclass, field
6
+ from enum import auto, Enum
7
+ from typing import Any, cast, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch._prims_common import make_contiguous_strides_for
12
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
13
+ from torch.distributed.device_mesh import DeviceMesh
14
+ from torch.distributed.fsdp._fully_shard._fsdp_common import DDPMeshInfo
15
+ from torch.distributed.tensor import DTensor, Replicate, Shard
16
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
17
+ from torch.distributed.tensor.placement_types import _StridedShard, Placement
18
+
19
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
20
+ from ._fsdp_common import (
21
+ _chunk_with_empty,
22
+ _from_local_no_grad,
23
+ _get_dim_chunked_size,
24
+ _raise_assert_with_print,
25
+ _to_dtype_if_needed,
26
+ compiled_autograd_enabled,
27
+ FSDPMeshInfo,
28
+ HSDPMeshInfo,
29
+ )
30
+
31
+
32
+ """
33
+ [Note: FSDP tensors]
34
+ FSDP considers the following tensors:
35
+ - Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
36
+ on the module when applying FSDP
37
+ - Sharded parameter: sharding the original parameter on dim-0 (or a
38
+ user-specified dim) as a DTensor over the main mesh
39
+ - All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
40
+ derived from the sharded parameter
41
+ - All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
42
+ all-gathering the all-gather inputs
43
+ - Unsharded parameter: parameter used for forward/backward computation, derived
44
+ from the all-gather output; autograd leaf
45
+
46
+ We define these tensors to describe the general framework that can accommodate
47
+ extensions, where:
48
+ - all-gather-inputs = pre-all-gather-transform(sharded-parameter)
49
+ - unsharded-parameter = post-all-gather-transform(all-gather-outputs)
50
+
51
+ For the default ``torch.Tensor`` case, there is only one all-gather input, and
52
+ it shares the same underlying tensor data as the sharded parameter, meaning
53
+ that they can be thought of as the same tensors. The same applies for the
54
+ all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
55
+ these equivalences may no longer hold due to the pre/post-all-gather
56
+ transforms, and some may have multiple all-gather inputs/outputs (e.g.
57
+ quantized data and scales).
58
+
59
+ [Note: FSDP and autograd]
60
+ FSDP dynamically frees and allocates the unsharded parameter. Since autograd
61
+ can pack a reference to it or a view to save for backward, we use storage
62
+ resizing to implement the freeing/allocation since that preserves the aliasing.
63
+ This implies that we construct the unsharded parameter object once and write to
64
+ it in-place thereafter. For the default ``torch.Tensor` original parameter
65
+ case, the all-gather output and unsharded parameter share the same
66
+ data, so we use storage resizing on the all-gather output.
67
+ """
68
+
69
+ lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
70
+
71
+ lib.define("copy_(Tensor(a!) tensor, Tensor data) -> ()")
72
+
73
+
74
+ @torch.library.impl(lib, "copy_", "Meta")
75
+ @torch.library.impl(lib, "copy_", "CUDA")
76
+ @torch.library.impl(lib, "copy_", "XPU")
77
+ @torch.library.impl(lib, "copy_", "HPU")
78
+ @torch.library.impl(lib, "copy_", "CPU")
79
+ @torch.library.impl(lib, "copy_", "MTIA")
80
+ def copy_(tensor, data):
81
+ tensor.copy_(data)
82
+
83
+
84
+ """
85
+ [Note: Avoiding functionalization for fsdp.copy_ and inductor.resize_storage_bytes_]
86
+
87
+ Currently we don't functionalize `fsdp.copy_` op or `inductor.resize_storage_bytes_` op
88
+ (i.e. they show up as a mutation op in the middle of the AOT joint graph).
89
+
90
+ Reason:
91
+ Traceable FSDP2 compiled autograd BWD graph have the following traits:
92
+ (1) Two inputs of the graph were aliased to each other (one from hook closed-over tensors, one from FWD saved tensors).
93
+ (2) One of them is mutated (copy_ and resize_ to handle the all-gathered param).
94
+ (3) They are both subclasses.
95
+ The combination of these traits is not supported by AOTAutograd (it's difficult to reason about subclass aliasing).
96
+ So this doesn't work at all for Traceable FSDP2.
97
+
98
+ The compromise we use is to avoid functionalization for the FSDP2 copy_ and resize_ ops.
99
+ This avoids the problem above, because from AOTAutograd point-of-view there are no mutations
100
+ that functionalization needs to handle. (Although we need to be careful not to DCE those mutable ops.)
101
+
102
+ We can avoid this functionalization because:
103
+ (1) The nn.Parameter is never used before its .copy_() is called in eager code (i.e. no alias of it is created),
104
+ so it's safe to call .copy_() in the middle of the graph to update its content and start using the nn.Parameter downstream.
105
+ (2) We always re-allocate the buffer for nn.Parameter to store the AllGather output and to be used in downstream user ops.
106
+ So calling resize-to-0 in the middle of the graph to free nn.Parameter memory after use should always be okay
107
+ (since we always allocate anew next time we need it, we strictly don't need to keep the old tensor storage around anymore).
108
+
109
+ Q: Wouldn't the extra resize_ and copy_ ops hurt both memory usage and performance?
110
+ A: Yes it would. As an optimization, we have an Inductor post-grad FX pass to remove those resize_ and copy_ ops
111
+ for unsharded params that have this pattern: resize_(full) -> copy_ -> resize_(0).
112
+
113
+ TODO:
114
+ Now that we are maintaining the invariant of "no aliased + mutated graph inputs" in both the forward and backward,
115
+ it is now more feasible to functionalize all of the mutable FSDP ops. Some of the pros and cons are:
116
+
117
+ Cons (of functionalizing those ops):
118
+ (1) By not functionalizing them as we are today, we are making it more likely that they will run at the "correct" time
119
+ in the generated code. If we start to functionalize them, we will need to make sure that Inductor reinplaces them
120
+ in a way where it properly moves the mutations back to exactly where they should have run, or we risk suffering worse
121
+ peak memory than eager. (We probably already need to do something similar in Inductor's reinplacing for copy_:
122
+ https://github.com/pytorch/pytorch/issues/135305#issuecomment-2334888089)
123
+
124
+ Pros (of functionalizing):
125
+ (1) Better safety, we don't need to worry about the graph passes in inductor/partitioning handling input mutations
126
+ mid-graph quite as much (to be fair we've already done some amount of auditing, but we might have to do some more).
127
+ (2) Better perf: each mutation midway through the graph prevents Inductor from pattern matching across it.
128
+ But maybe there are few enough mutations induced by FSDP for this to matter.
129
+ """
130
+
131
+
132
+ @torch.library.impl(lib, "copy_", "Functionalize")
133
+ def copy__functionalize(tensor, data):
134
+ torch._sync(tensor)
135
+ torch._sync(data)
136
+ tensor_inner = torch._from_functional_tensor(tensor)
137
+ data_inner = torch._from_functional_tensor(data)
138
+ with torch._C._ExcludeDispatchKeyGuard(
139
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
140
+ ):
141
+ torch.ops.fsdp.copy_.default(tensor_inner, data_inner)
142
+
143
+
144
+ torch.fx.node.has_side_effect(torch.ops.fsdp.copy_.default)
145
+
146
+
147
+ class ShardedState(Enum):
148
+ """
149
+ - ``SHARDED``: The sharded parameter is registered to the module. It is the
150
+ only contributor to parameter memory.
151
+ - ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
152
+ smaller world size. Since this data should not be used for computation,
153
+ we do not register it to the module. Users should reshard the module
154
+ before any in-place modifications. Both it and the sharded parameter
155
+ contribute to parameter memory.
156
+ - ``UNSHARDED``: The unsharded parameter is registered to the module. Both
157
+ it and the sharded parameter contribute to parameter memory.
158
+ """
159
+
160
+ SHARDED = auto()
161
+ SHARDED_POST_FORWARD = auto()
162
+ UNSHARDED = auto()
163
+
164
+
165
+ @dataclass
166
+ class ParamModuleInfo:
167
+ """
168
+ For a parameter, this stores the module and the parameter name to be able
169
+ to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
170
+ the parameter via ``getattr(module, param_name)``. We additionally save
171
+ shared modules and shared parameter names to update them accordingly.
172
+ """
173
+
174
+ # Parameter names are unprefixed, e.g. "weight", not "lin.weight"
175
+ module: nn.Module
176
+ param_name: str
177
+ shared_modules: list[nn.Module] = field(default_factory=list)
178
+ shared_param_names: list[str] = field(default_factory=list)
179
+
180
+
181
+ @dataclass
182
+ class ExtensionsData:
183
+ # User-defined metadata passed from pre to post-all-gather
184
+ all_gather_metadata: Optional[Any] = None
185
+ # Save the all-gather input sizes to unflatten the all-gather outputs to ND
186
+ all_gather_input_sizes: Sequence[torch.Size] = () # ND
187
+
188
+ def clear(self):
189
+ self.all_gather_metadata = None
190
+ self.all_gather_input_sizes = ()
191
+
192
+
193
+ class FSDPParam:
194
+ """
195
+ This class manages a parameter with FSDP or FSDP variants applied,
196
+ implementing dim-0 per-parameter sharding.
197
+ """
198
+
199
+ orig_dtype: torch.dtype
200
+ param_dtype: Optional[torch.dtype]
201
+ reduce_dtype: Optional[torch.dtype]
202
+ _orig_size: torch.Size # ND
203
+ sharded_size: torch.Size # ND
204
+ contiguous_sharded_stride: tuple[int, ...]
205
+ padded_sharded_param_size: torch.Size # ND
206
+ sharded_post_forward_size: torch.Size # ND
207
+ contiguous_sharded_post_forward_stride: tuple[int, ...]
208
+ _sharded_param_data: torch.Tensor # 1D
209
+ sharded_param: nn.Parameter # ND
210
+ _sharded_post_forward_param_data: Optional[torch.Tensor] # 1D
211
+ _sharded_post_forward_param: Optional[nn.Parameter] # ND
212
+ _unsharded_param: nn.Parameter # ND
213
+ unsharded_accumulated_grad: Optional[torch.Tensor] # ND
214
+ _sharding_spec: DTensorSpec
215
+ # DTensor attributes (only defined for DTensor `param`):
216
+ _tp_spec: DTensorSpec
217
+ all_gather_outputs: list[torch.Tensor] # 1D
218
+ # All-gather extension attributes
219
+ _extensions_data: ExtensionsData
220
+ _unsharded_inner_tensors: list[torch.Tensor]
221
+
222
+ def __init__(
223
+ self,
224
+ param: nn.Parameter,
225
+ module_info: ParamModuleInfo,
226
+ mesh_info: FSDPMeshInfo,
227
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
228
+ device: torch.device,
229
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
230
+ mp_policy: MixedPrecisionPolicy,
231
+ offload_policy: OffloadPolicy,
232
+ ):
233
+ self._module_info: ParamModuleInfo = module_info
234
+ self.mesh_info = mesh_info
235
+ self.post_forward_mesh_info = post_forward_mesh_info
236
+ # pyrefly: ignore [read-only]
237
+ self.device = device
238
+ self.mp_policy = mp_policy
239
+ self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
240
+ self.pin_memory = (
241
+ self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
242
+ )
243
+ self.grad_offload_event: Optional[torch.Event] = None
244
+ self._init_sharded_param(param, device, shard_placement_fn)
245
+ if self.post_forward_mesh_info:
246
+ self._init_sharded_post_forward_param_metadata(param)
247
+ self._init_extensions()
248
+ self.all_gather_outputs: list[torch.Tensor] = []
249
+ self.unsharded_accumulated_grad = None
250
+ self._param_fqn: Optional[str] = None # prefixed from root module
251
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
252
+ # https://github.com/pytorch/pytorch/issues/113045
253
+ self._post_load_hook_handle = (
254
+ module_info.module.register_load_state_dict_post_hook(
255
+ lambda *args, **kwargs: self.reset_sharded_param()
256
+ )
257
+ )
258
+
259
+ @torch.no_grad()
260
+ def _init_sharded_param(
261
+ self,
262
+ param: nn.Parameter,
263
+ device: torch.device,
264
+ shard_placement_fn: Optional[Callable],
265
+ ):
266
+ if param.device != device and param.device.type != "meta":
267
+ raise AssertionError(
268
+ f"Expects the parameter to already be moved to device {device} but got {param.device}"
269
+ )
270
+ if not param.is_contiguous():
271
+ raise NotImplementedError(
272
+ f"FSDP does not support non-contiguous parameters yet: {param.shape=} {param.stride()=}"
273
+ )
274
+ fsdp_placement = shard_placement_fn(param) if shard_placement_fn else None
275
+ if fsdp_placement is None:
276
+ fsdp_placement = Shard(0)
277
+ elif fsdp_placement.dim < 0:
278
+ fsdp_placement = Shard(fsdp_placement.dim + param.ndim)
279
+ if not isinstance(fsdp_placement, Shard):
280
+ raise AssertionError(
281
+ f"Expected Shard, got {type(fsdp_placement)}: {fsdp_placement}"
282
+ )
283
+ self.fsdp_placement = fsdp_placement
284
+ shard_dim = fsdp_placement.dim
285
+ # TODO: Replace the sharded DTensor parameter construction logic with
286
+ # `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
287
+ # TODO: Simplify the following sharded parameter padding logic after
288
+ # https://github.com/pytorch/pytorch/issues/113045
289
+ self.is_dtensor = isinstance(param, DTensor)
290
+ if self.is_dtensor:
291
+ self._tp_spec = cast(DTensor, param)._spec
292
+ dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
293
+ if dp_mesh is None or tp_mesh is None:
294
+ raise AssertionError(
295
+ "FSDP requires the DP and model parallel TP/EP mesh to be not None but got: \n"
296
+ f"DP's mesh: {dp_mesh}\nTP/EP's mesh: {tp_mesh}"
297
+ )
298
+ self._spmd_mesh = DeviceMesh._concatenate([dp_mesh, tp_mesh])
299
+ if len(self._tp_spec.placements) > 2:
300
+ raise NotImplementedError(
301
+ f"FSDP only supports 1D TP/EP or 2D EP+TP, not {self._tp_spec.placements}"
302
+ )
303
+ split_factor = self._tp_spec.num_shards_map[shard_dim]
304
+ if not (2 <= self._spmd_mesh.ndim <= 4):
305
+ raise AssertionError(
306
+ "_spmd_mesh.ndim can only be 2 (FSDP+TP/EP), 3 (FSDP+EP+TP, HSDP+TP/EP), "
307
+ f"or 4 (HSDP+EP+TP) but got {self._spmd_mesh.ndim}."
308
+ )
309
+ self._spmd_placements: tuple[Placement, ...]
310
+ if isinstance(self.mesh_info, FSDPMeshInfo): # FSDP or HSDP
311
+ dp_shard_tp_placement = (
312
+ (
313
+ _StridedShard(shard_dim, split_factor=split_factor)
314
+ if split_factor > 1
315
+ else fsdp_placement
316
+ ),
317
+ *self._tp_spec.placements,
318
+ )
319
+ else: # DDP
320
+ dp_shard_tp_placement = (
321
+ (Replicate()),
322
+ *self._tp_spec.placements,
323
+ )
324
+ if isinstance(self.mesh_info, HSDPMeshInfo): # HSDP
325
+ if self.mesh_info.replicate_mesh_dim != 0:
326
+ raise AssertionError(
327
+ f"Expected replicate_mesh_dim to be 0, got {self.mesh_info.replicate_mesh_dim}"
328
+ )
329
+ self._spmd_placements = (Replicate(),) + dp_shard_tp_placement
330
+ else: # FSDP or DDP
331
+ self._spmd_placements = dp_shard_tp_placement
332
+
333
+ self._sharding_spec = DTensorSpec(
334
+ self._spmd_mesh,
335
+ self._spmd_placements,
336
+ tensor_meta=self._tp_spec.tensor_meta,
337
+ )
338
+ param_data = cast(DTensor, param)._local_tensor
339
+ else:
340
+ self._spmd_mesh = self.mesh_info.mesh
341
+ if isinstance(self.mesh_info, HSDPMeshInfo): # HSDP
342
+ self._spmd_placements = (Replicate(), fsdp_placement)
343
+ elif isinstance(self.mesh_info, FSDPMeshInfo): # FSDP
344
+ self._spmd_placements = (fsdp_placement,)
345
+ elif isinstance(self.mesh_info, DDPMeshInfo): # DDP
346
+ self._spmd_placements = (Replicate(),)
347
+ self._sharding_spec = DTensorSpec(
348
+ self._spmd_mesh,
349
+ self._spmd_placements,
350
+ tensor_meta=TensorMeta(param.size(), param.stride(), param.dtype),
351
+ )
352
+ param_data = param
353
+ if not param_data.is_contiguous():
354
+ raise AssertionError(
355
+ f"Expected contiguous tensor, got {param_data.shape=} {param_data.stride()=}"
356
+ )
357
+ shard_dim = fsdp_placement.dim
358
+ if shard_dim >= param_data.ndim:
359
+ raise AssertionError(
360
+ f"Shard dim {shard_dim} is invalid for {param_data.ndim}D tensor: {param.shape}"
361
+ )
362
+ self._orig_size = param_data.size()
363
+ self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
364
+ if isinstance(self.mesh_info, FSDPMeshInfo): # FSDP or HSDP
365
+ shard_rank = self.mesh_info.shard_mesh_rank
366
+ shard_world_size = self.mesh_info.shard_mesh_size
367
+ else: # DDP
368
+ shard_rank = 0
369
+ shard_world_size = 1
370
+
371
+ if shard_dim > 0 and param_data.size(shard_dim) % shard_world_size != 0:
372
+ # If sharding on nonzero dim, require even sharding for now because
373
+ # the uneven sharding (1) requires extra copies before/after FSDP
374
+ # collectives and (2) introduces extra complexity to handle padding
375
+ # and unpadding
376
+ raise NotImplementedError(
377
+ f"FSDP does not support uneven sharding on dim {shard_dim}: "
378
+ f"{param_data.size()} (world size: {shard_world_size})"
379
+ )
380
+ chunks = _chunk_with_empty(param_data, shard_world_size, dim=shard_dim)
381
+ sharded_param = chunks[shard_rank]
382
+ self.sharded_size = _get_dim_chunked_size(
383
+ sharded_param, param_data.size(), dim=shard_dim
384
+ )
385
+ self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
386
+ padded_sharded_size = chunks[0].size() # 0th always padded
387
+ self.padded_sharded_param_size = padded_sharded_size
388
+ # Pre-pad the sharded parameter to avoid padding before all-gather
389
+ padded_sharded_param = param_data.new_zeros(padded_sharded_size)
390
+ if sharded_param.numel() > 0:
391
+ padded_sharded_param.narrow(
392
+ dim=shard_dim, start=0, length=sharded_param.size(shard_dim)
393
+ ).copy_(sharded_param)
394
+ if self.offload_to_cpu and not padded_sharded_param.is_meta:
395
+ padded_sharded_param = padded_sharded_param.cpu()
396
+ if self.pin_memory:
397
+ padded_sharded_param = padded_sharded_param.pin_memory()
398
+ self._sharded_param_data = padded_sharded_param.view(-1)
399
+ length = sharded_param.size(shard_dim) if sharded_param.numel() > 0 else 0
400
+ sharded_param = padded_sharded_param.narrow(
401
+ dim=shard_dim, start=0, length=length
402
+ )
403
+ if not sharded_param.is_contiguous():
404
+ raise AssertionError(
405
+ f"Expected contiguous tensor with {self.fsdp_placement=}"
406
+ )
407
+ self.sharded_param = nn.Parameter(self.to_sharded_dtensor(sharded_param))
408
+ self.sharded_param.requires_grad_(param.requires_grad)
409
+ # Let `param_data` be freed normally when its ref count reaches 0 when
410
+ # the `fully_shard` call returns to allow provided parameters to alias
411
+ self._setattr_on_modules(self.sharded_param)
412
+ self.sharded_state = ShardedState.SHARDED
413
+
414
+ def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
415
+ mesh_info = self.post_forward_mesh_info
416
+ if mesh_info is None:
417
+ raise AssertionError("Expected post_forward_mesh_info to not be None")
418
+ param_data = param._local_tensor if isinstance(param, DTensor) else param
419
+ if isinstance(mesh_info, FSDPMeshInfo):
420
+ chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
421
+ self.sharded_post_forward_size = _get_dim_chunked_size(
422
+ chunks[mesh_info.shard_mesh_rank],
423
+ param_data.size(),
424
+ dim=self.fsdp_placement.dim,
425
+ )
426
+ else: # DDP
427
+ chunks = _chunk_with_empty(param_data, 1, dim=0)
428
+ self.sharded_post_forward_size = _get_dim_chunked_size(
429
+ chunks[0],
430
+ param_data.size(),
431
+ dim=self.fsdp_placement.dim,
432
+ )
433
+ self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
434
+ self.sharded_post_forward_size
435
+ )
436
+
437
+ def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
438
+ param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
439
+ self.orig_dtype = self.sharded_param.dtype
440
+ # Clamp `reduce_dtype` to `None` if no casting is required: since
441
+ # gradients are computed in `param_dtype`, if `reduce_dtype` matches,
442
+ # then we do not need extra casting
443
+ if reduce_dtype == param_dtype:
444
+ reduce_dtype = None
445
+ # Clamp `param_dtype` to `None` if no casting is required
446
+ if param_dtype == self.orig_dtype:
447
+ param_dtype = None
448
+ self.param_dtype = param_dtype
449
+ self.reduce_dtype = reduce_dtype
450
+ # None indicates that the mixed precision is not enabled
451
+
452
+ def _init_extensions(self) -> None:
453
+ inner_tensor = self._sharded_local_tensor
454
+ has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
455
+ has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
456
+ if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
457
+ raise AssertionError(
458
+ "Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
459
+ f"if using all-gather extensions: {inner_tensor}"
460
+ )
461
+ if has_fsdp_pre_all_gather:
462
+ self._extensions_data = ExtensionsData()
463
+ self._unsharded_inner_tensors: list[torch.Tensor] = []
464
+
465
+ def init_all_gather_outputs(
466
+ self,
467
+ all_gather_input_numels: list[int],
468
+ all_gather_input_dtypes: list[torch.dtype],
469
+ world_size: int,
470
+ device: torch.device,
471
+ force_recreate: bool = False,
472
+ ):
473
+ if not force_recreate and len(self.all_gather_outputs) > 0:
474
+ return # already initialized
475
+ self.all_gather_outputs = [
476
+ torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
477
+ for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
478
+ ]
479
+
480
+ def init_unsharded_param(self):
481
+ """
482
+ [Note: Invariants for torch.compile Traceable FSDP2]
483
+ 1. Under compile, we always re-populate the content of `self._unsharded_param`
484
+ per AllGather using the slow path.
485
+ 2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
486
+ This is to ensure the buffer creation is internal to the graph and
487
+ avoid `self.all_gather_outputs` being captured as a graph input.
488
+ 3. Under compile, at the end of `free_unsharded_param()`, we always clean up
489
+ `self.all_gather_outputs` and `self._unsharded_inner_tensors`,
490
+ to avoid them being captured as graph output.
491
+
492
+ With these invariants, only these tensors will be inputs to the graph:
493
+ - Sharded parameters
494
+ - Placeholders for the `self._unsharded_param` nn.Parameter
495
+ """
496
+ if not compiled_autograd_enabled() and hasattr(
497
+ self, "_unsharded_param"
498
+ ): # after the 1st all-gather
499
+ inner_tensor = self._sharded_local_tensor
500
+ if not hasattr(inner_tensor, "fsdp_post_all_gather"):
501
+ return # already initialized
502
+ for tensor in self._unsharded_inner_tensors:
503
+ alloc_storage(tensor)
504
+ all_gather_outputs = self._unflatten_all_gather_outputs()
505
+ inner_tensor.fsdp_post_all_gather(
506
+ all_gather_outputs,
507
+ self._extensions_data.all_gather_metadata,
508
+ self.param_dtype or self.orig_dtype,
509
+ out=self._unsharded_param,
510
+ )
511
+ self._extensions_data.clear()
512
+ return
513
+ inner_tensor = self._sharded_local_tensor
514
+ if not compiled_autograd_enabled() and hasattr(
515
+ inner_tensor, "fsdp_post_all_gather"
516
+ ):
517
+ all_gather_outputs = self._unflatten_all_gather_outputs()
518
+ (
519
+ unsharded_tensor,
520
+ self._unsharded_inner_tensors,
521
+ ) = inner_tensor.fsdp_post_all_gather(
522
+ all_gather_outputs,
523
+ self._extensions_data.all_gather_metadata,
524
+ self.param_dtype or self.orig_dtype,
525
+ )
526
+ self._extensions_data.clear()
527
+ else:
528
+ # For the default path (no post-all-gather), the all-gather output
529
+ # gives the unsharded parameter data directly
530
+ if len(self.all_gather_outputs) != 1:
531
+ raise AssertionError(
532
+ f"Expected 1 all_gather_output, got {len(self.all_gather_outputs)}"
533
+ )
534
+ unsharded_tensor = self.all_gather_outputs[0]
535
+ unsharded_param = torch.as_strided(
536
+ unsharded_tensor,
537
+ self._orig_size,
538
+ self._contiguous_orig_stride,
539
+ storage_offset=0,
540
+ )
541
+ if self.is_dtensor:
542
+ unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
543
+ if hasattr(self, "_unsharded_param"):
544
+ if not compiled_autograd_enabled():
545
+ raise AssertionError("Expected compiled_autograd to be enabled")
546
+ with (
547
+ torch.no_grad(),
548
+ torch.autograd._unsafe_preserve_version_counter(self._unsharded_param),
549
+ ):
550
+ # NOTE: Under compile, if an unsharded param goes through
551
+ # resize_(full) -> copy_ -> resize_(0) pattern, we will remove those
552
+ # resize_ and copy_ ops in a compiler graph pass
553
+ # `remove_fsdp2_unsharded_param_graph_input_usage` to recover performance.
554
+ self._unsharded_param.untyped_storage().resize_(
555
+ self._unsharded_param.numel() * self._unsharded_param.itemsize
556
+ )
557
+ torch.ops.fsdp.copy_(self._unsharded_param, unsharded_param)
558
+ else:
559
+ self._unsharded_param = nn.Parameter(
560
+ unsharded_param, requires_grad=self.sharded_param.requires_grad
561
+ )
562
+
563
+ def _unflatten_all_gather_outputs(self) -> tuple[torch.Tensor, ...]:
564
+ return tuple(
565
+ t.view(-1, *s[1:])
566
+ for t, s in zip(
567
+ self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
568
+ )
569
+ )
570
+
571
+ def to_sharded(self) -> None:
572
+ self._setattr_on_modules(self.sharded_param)
573
+ self.free_unsharded_param()
574
+ self.sharded_state = ShardedState.SHARDED
575
+
576
+ def to_sharded_post_forward(self) -> None:
577
+ if self.is_dtensor:
578
+ raise NotImplementedError(
579
+ "Resharding to smaller mesh with TP is not supported yet"
580
+ )
581
+ self._assert_in_states(ShardedState.UNSHARDED)
582
+ if self.post_forward_mesh_info is None:
583
+ raise AssertionError("Expected post_forward_mesh_info to not be None")
584
+ if len(self.all_gather_outputs) != 1:
585
+ raise AssertionError(
586
+ f"Expected 1 all_gather_output, got {len(self.all_gather_outputs)}"
587
+ )
588
+ shard_world_size = self.post_forward_mesh_info.shard_mesh_size
589
+ if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
590
+ _raise_assert_with_print(
591
+ f"All-gather output size ({numel}) must be divisible by the shard "
592
+ f"world size ({shard_world_size})"
593
+ )
594
+ shard_rank = self.post_forward_mesh_info.shard_mesh_rank
595
+ # pyrefly: ignore [unbound-name]
596
+ sharded_numel = numel // shard_world_size
597
+ self._sharded_post_forward_param_data = (
598
+ self.all_gather_outputs[0].narrow(
599
+ 0, sharded_numel * shard_rank, sharded_numel
600
+ )
601
+ ).clone() # clone to be able to free all-gather output
602
+ sharded_post_forward_tensor = torch.as_strided(
603
+ self._sharded_post_forward_param_data,
604
+ size=self.sharded_post_forward_size,
605
+ stride=self.contiguous_sharded_post_forward_stride,
606
+ storage_offset=0,
607
+ )
608
+ self._sharded_post_forward_param = nn.Parameter(
609
+ self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
610
+ )
611
+ self._setattr_on_modules(self._sharded_post_forward_param)
612
+ self.free_unsharded_param()
613
+ self.sharded_state = ShardedState.SHARDED_POST_FORWARD
614
+
615
+ def to_unsharded(self) -> None:
616
+ # Assume that the data has been allocated and all-gathered
617
+ set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
618
+ self._setattr_on_modules(self._unsharded_param)
619
+ if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
620
+ # The data is allocated in the default stream via the post-forward
621
+ # reshard and must be kept alive for the next all-gather copy-in.
622
+ # Since we call this method after the copy-out, the data's lifetime
623
+ # is ensured without further synchronization.
624
+ self._sharded_post_forward_param = None
625
+ self._sharded_post_forward_param_data = None # free
626
+ self.sharded_state = ShardedState.UNSHARDED
627
+
628
+ def _setattr_on_modules(self, param: nn.Parameter) -> None:
629
+ unsafe_setattr_param(
630
+ self._module_info.module, self._module_info.param_name, param
631
+ )
632
+ for shared_module, shared_param_name in zip(
633
+ self._module_info.shared_modules, self._module_info.shared_param_names
634
+ ):
635
+ unsafe_setattr_param(shared_module, shared_param_name, param)
636
+
637
+ def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
638
+ """
639
+ Converts a local tensor representing either the sharded parameter or
640
+ sharded gradient to DTensor.
641
+ """
642
+ if tensor.shape != self.sharded_size:
643
+ _raise_assert_with_print(
644
+ f"Expects size {self.sharded_size} but got {tensor.shape}"
645
+ )
646
+ return _from_local_no_grad(
647
+ tensor,
648
+ self._sharding_spec,
649
+ )
650
+
651
+ def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
652
+ if tensor.shape != self.sharded_post_forward_size:
653
+ _raise_assert_with_print(
654
+ f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
655
+ )
656
+ if not isinstance(self.post_forward_mesh_info, HSDPMeshInfo):
657
+ raise AssertionError(
658
+ f"Expected HSDPMeshInfo, got {type(self.post_forward_mesh_info)}"
659
+ )
660
+ # TODO: Prefer this DTensor to be read-only and generalize the
661
+ # placement once we support TP.
662
+ post_forward_sharding_spec = DTensorSpec(
663
+ self.post_forward_mesh_info.mesh,
664
+ (Replicate(), Shard(0)),
665
+ tensor_meta=self._sharding_spec.tensor_meta,
666
+ )
667
+ return _from_local_no_grad(tensor, post_forward_sharding_spec)
668
+
669
+ def to_accumulated_grad_if_needed(self) -> None:
670
+ # Access `_unsharded_param` to bypass the sharded state check since we
671
+ # prefer to reshard before upcasting the gradient to save memory
672
+ if (
673
+ self.reduce_dtype is None
674
+ or self._unsharded_param.grad is None
675
+ or self._unsharded_param.grad.dtype == self.reduce_dtype
676
+ ):
677
+ return
678
+ unsharded_grad = self._unsharded_param.grad
679
+ self._unsharded_param.grad = None
680
+ self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
681
+
682
+ def accumulate_unsharded_grad_if_needed(self) -> None:
683
+ if (
684
+ self.unsharded_accumulated_grad is not None
685
+ and self.unsharded_param.grad is not None
686
+ ):
687
+ self.unsharded_accumulated_grad += self.unsharded_param.grad
688
+ self.unsharded_param.grad = None
689
+
690
+ def alloc_all_gather_outputs(self) -> None:
691
+ for tensor in self.all_gather_outputs:
692
+ alloc_storage(tensor)
693
+
694
+ def free_unsharded_param(self) -> None:
695
+ if compiled_autograd_enabled():
696
+ """
697
+ Assumptions under compile:
698
+ - `self._unsharded_param` is NOT an alias of `self.all_gather_outputs`.
699
+ Instead, we resize `self._unsharded_param` storage size to full and then
700
+ explicitly *copy* the data from `self.all_gather_outputs` to `self._unsharded_param`
701
+ in `init_unsharded_param()`. (For full-graph FSDP2 case, we will then remove
702
+ the resize_ and copy_ ops in a compiler graph pass to recover performance.)
703
+ - `self.all_gather_outputs` and `self._unsharded_inner_tensors` are NOT
704
+ graph inputs. They are created within the graph and is guaranteed to be freed
705
+ by the end of the graph. They don't leak outside of the graph.
706
+ """
707
+ self._unsharded_param.untyped_storage().resize_(0)
708
+ self.all_gather_outputs = []
709
+ self._unsharded_inner_tensors = []
710
+ else:
711
+ for tensor in itertools.chain(
712
+ self.all_gather_outputs, self._unsharded_inner_tensors
713
+ ):
714
+ free_storage(tensor)
715
+
716
+ @property
717
+ def all_gather_inputs(self) -> list[torch.Tensor]: # 1D
718
+ self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
719
+ if self.sharded_state == ShardedState.SHARDED:
720
+ if not compiled_autograd_enabled() and hasattr(
721
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
722
+ ):
723
+ sharded_local_tensor = self._sharded_local_tensor
724
+ if self.offload_to_cpu:
725
+ sharded_local_tensor = sharded_local_tensor.to(
726
+ self.device, non_blocking=True
727
+ )
728
+ pre_all_gather_signature = inspect.signature(
729
+ # pyrefly: ignore [missing-attribute]
730
+ sharded_local_tensor.fsdp_pre_all_gather
731
+ )
732
+ num_fn_params = len(pre_all_gather_signature.parameters)
733
+ # Old signature only passes mesh; keep for BC for now
734
+ if num_fn_params not in (1, 5):
735
+ raise AssertionError(
736
+ f"Invalid fsdp_pre_all_gather: {pre_all_gather_signature}\n"
737
+ "Expects fsdp_pre_all_gather(self, mesh: DeviceMesh, "
738
+ "outer_size: torch.Size, outer_stride: tuple[int, ...], "
739
+ "module: nn.Module, mp_policy: MixedPrecisionPolicy)"
740
+ )
741
+ if num_fn_params == 1:
742
+ (
743
+ all_gather_inputs,
744
+ self._extensions_data.all_gather_metadata,
745
+ # pyrefly: ignore [missing-attribute]
746
+ ) = sharded_local_tensor.fsdp_pre_all_gather(
747
+ self.shard_mesh_from_root
748
+ )
749
+ else:
750
+ (
751
+ all_gather_inputs,
752
+ self._extensions_data.all_gather_metadata,
753
+ # pyrefly: ignore [missing-attribute]
754
+ ) = sharded_local_tensor.fsdp_pre_all_gather(
755
+ self.shard_mesh_from_root,
756
+ self._orig_size,
757
+ self._contiguous_orig_stride,
758
+ self._module_info.module,
759
+ self.mp_policy,
760
+ )
761
+ if (
762
+ sharded_local_tensor.size() != self.padded_sharded_param_size
763
+ and any(
764
+ all_gather_input.size() != self.padded_sharded_param_size
765
+ for all_gather_input in all_gather_inputs
766
+ )
767
+ ):
768
+ # NOTE: Since this error can only be raised on the
769
+ # ranks that have padding, this can manifest as a NCCL
770
+ # watchdog timeout, as the other ranks will not error.
771
+ raise AssertionError(
772
+ "When a parameter is unevenly sharded by FSDP "
773
+ f"(orig size={self._orig_size}, FSDP world size={self.mesh_info.mesh.size()}), "
774
+ "fsdp_pre_all_gather must return all-gather inputs with the padded sharded size "
775
+ f"{self.padded_sharded_param_size} but got {[t.size() for t in all_gather_inputs]}"
776
+ )
777
+ self._extensions_data.all_gather_input_sizes = [
778
+ t.size() for t in all_gather_inputs
779
+ ]
780
+ return [t.view(-1) for t in all_gather_inputs]
781
+ sharded_param_data = self._sharded_param_data
782
+ if self.offload_to_cpu:
783
+ sharded_param_data = sharded_param_data.to(
784
+ self.device, non_blocking=True
785
+ )
786
+ return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
787
+ elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
788
+ if not compiled_autograd_enabled() and hasattr(
789
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
790
+ ):
791
+ raise NotImplementedError
792
+ all_gather_input = _to_dtype_if_needed(
793
+ cast(torch.Tensor, self._sharded_post_forward_param_data),
794
+ self.param_dtype,
795
+ )
796
+ return [all_gather_input]
797
+ return [torch.empty(0)] # mypy
798
+
799
+ @property
800
+ def unsharded_param(self) -> nn.Parameter: # ND
801
+ return self._unsharded_param
802
+
803
+ @property
804
+ def unsharded_grad_data(self) -> torch.Tensor:
805
+ grad = self.unsharded_param.grad
806
+ if grad is None:
807
+ raise AssertionError("Expects unsharded_param.grad to not be None")
808
+ return self._get_grad_inner_tensor(grad)
809
+
810
+ @property
811
+ def unsharded_accumulated_grad_data(self) -> torch.Tensor:
812
+ grad = self.unsharded_accumulated_grad
813
+ if grad is None:
814
+ raise AssertionError("Expects unsharded_accumulated_grad to not be None")
815
+ return self._get_grad_inner_tensor(grad)
816
+
817
+ def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
818
+ if self.is_dtensor:
819
+ if isinstance(grad, AsyncCollectiveTensor):
820
+ grad = grad.wait()
821
+ if not isinstance(grad, DTensor):
822
+ raise AssertionError(f"Expected DTensor, got {type(grad)}")
823
+ placements = self._tp_spec.placements
824
+ if placements != grad.placements:
825
+ if len(self._tp_spec.placements) != len(grad.placements):
826
+ raise AssertionError(
827
+ f"Expected same placement length: {self._tp_spec=} {grad.placements=}"
828
+ )
829
+ grad = grad.redistribute(placements=placements)
830
+ grad = grad._local_tensor
831
+ return grad
832
+
833
+ @property
834
+ def _sharded_local_tensor(self) -> torch.Tensor:
835
+ return cast(DTensor, self.sharded_param)._local_tensor
836
+
837
+ @property
838
+ def shard_mesh(self):
839
+ mesh = self.mesh_info.mesh
840
+ if mesh.ndim == 1:
841
+ return mesh
842
+ elif mesh.ndim == 2:
843
+ if mesh.mesh_dim_names is None:
844
+ raise AssertionError("Expected mesh_dim_names to not be None")
845
+ return mesh[mesh.mesh_dim_names[-1]]
846
+ raise ValueError(f"Invalid mesh: {mesh}")
847
+
848
+ @property
849
+ def shard_mesh_from_root(self):
850
+ mesh = self.mesh_info.mesh
851
+
852
+ if mesh.ndim == 1:
853
+ return mesh
854
+ else:
855
+ if mesh.mesh_dim_names is None:
856
+ raise AssertionError("Expected mesh_dim_names to not be None")
857
+ shard_dim_name = mesh.mesh_dim_names[-1]
858
+ return mesh[shard_dim_name]
859
+
860
+ def _assert_in_states(self, *states: ShardedState) -> None:
861
+ if self.sharded_state not in states:
862
+ _raise_assert_with_print(
863
+ f"Expects to be in one of {states}, not {self.sharded_state}"
864
+ )
865
+
866
+ def reset_sharded_param(self):
867
+ # For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
868
+ # that change the sharded parameter tensor, we may need to re-pad the
869
+ # sharded local tensor and re-save the reference.
870
+ module_info = self._module_info
871
+ new_param = getattr(module_info.module, module_info.param_name)
872
+ if new_param is not self.sharded_param:
873
+ if torch.__future__.get_swap_module_params_on_conversion():
874
+ raise AssertionError(
875
+ f"Expects swap_tensors to preserve object but got {new_param} "
876
+ f"instead of {self.sharded_param}"
877
+ )
878
+ self.sharded_param = new_param
879
+ # pyrefly: ignore [missing-attribute]
880
+ local_tensor = new_param._local_tensor
881
+ if local_tensor.is_meta:
882
+ return
883
+ updated_local_tensor = False
884
+ # local_tensor can be padded twice
885
+ # 1st time in fully_shard(model)
886
+ # 2nd time in model(input) lazy_init
887
+ # 2nd time should be no-op if parameters remain unchanged
888
+ # 2nd time shouldn't be no-op if people call model.load_state_dict(...) before lazy_init
889
+ # this makes it possible for trainer to call `sd = model.state_dict()` before the training loop
890
+ # and use `sd` without calling .state_dict() per iteration
891
+ same_local_tensor = False
892
+ # TODO: need to support tensor subclass
893
+ if type(self._sharded_param_data) is torch.Tensor:
894
+ same_local_tensor = (
895
+ # when sharding param with shape (1, ...) over 2 ranks
896
+ # local_tensor on rank 1 can be size 0, data_ptr() can be 0
897
+ self._sharded_param_data.untyped_storage().data_ptr() > 0
898
+ and self._sharded_param_data.untyped_storage().data_ptr()
899
+ == local_tensor.untyped_storage().data_ptr()
900
+ )
901
+ padded_sharded_size = self.padded_sharded_param_size
902
+ shard_dim = self.fsdp_placement.dim
903
+ length = local_tensor.size(shard_dim) if local_tensor.numel() > 0 else 0
904
+ if local_tensor.size() != padded_sharded_size and not same_local_tensor:
905
+ if shard_dim != 0:
906
+ raise AssertionError(
907
+ f"Shard({shard_dim}) requires even sharding: {local_tensor.size()=}"
908
+ )
909
+ padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
910
+ padded_local_tensor.narrow(dim=shard_dim, start=0, length=length).copy_(
911
+ local_tensor
912
+ )
913
+ local_tensor = padded_local_tensor
914
+ updated_local_tensor = True
915
+ if self.pin_memory and not local_tensor.is_pinned():
916
+ local_tensor = local_tensor.cpu().pin_memory()
917
+ updated_local_tensor = True
918
+ if not same_local_tensor:
919
+ self._sharded_param_data = local_tensor.view(-1)
920
+ if not isinstance(self.sharded_param, DTensor):
921
+ raise AssertionError(f"Expected DTensor, got {type(self.sharded_param)}")
922
+ if updated_local_tensor:
923
+ # Only change the local tensor object if needed
924
+ self.sharded_param._local_tensor = local_tensor.narrow(
925
+ dim=shard_dim, start=0, length=length
926
+ )
927
+ if not self.sharded_param._local_tensor.is_contiguous():
928
+ raise AssertionError(
929
+ "Expected sharded_param._local_tensor to be contiguous"
930
+ )
931
+ self._sharding_spec = self.sharded_param._spec
932
+
933
+ def __repr__(self):
934
+ return f"FSDPParam(fqn={self._param_fqn}, orig_size={self._orig_size})"
935
+
936
+
937
+ def alloc_storage(tensor: torch.Tensor) -> None:
938
+ size = tensor.numel() * tensor.itemsize
939
+ if (storage := tensor.untyped_storage()).size() != size:
940
+ storage.resize_(size)
941
+
942
+
943
+ def free_storage(tensor: torch.Tensor) -> None:
944
+ if (storage := tensor.untyped_storage()).size() != 0:
945
+ storage.resize_(0)
946
+
947
+
948
+ # NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
949
+ # CPU overhead, if the module did not override it. For FSDP, we know we do not
950
+ # need those checks when transitioning between sharded/unsharded parameters.
951
+ def unsafe_setattr_param(
952
+ module: nn.Module, param_name: str, param: nn.Parameter
953
+ ) -> None:
954
+ if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
955
+ module._parameters[param_name] = param
956
+ else: # slow path
957
+ setattr(module, param_name, param)
958
+
959
+
960
+ def set_requires_grad_if_needed(
961
+ src_tensor: torch.Tensor, dst_tensor: torch.Tensor
962
+ ) -> None:
963
+ # Only call `requires_grad_` if needed to avoid the Python <> C++ context
964
+ # switch overhead
965
+ if src_tensor.requires_grad != dst_tensor.requires_grad:
966
+ dst_tensor.requires_grad_(src_tensor.requires_grad)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py ADDED
@@ -0,0 +1,901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ from collections.abc import Callable
5
+ from typing import Any, cast, NamedTuple, Optional
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.nn as nn
10
+ from torch.distributed.device_mesh import _get_device_handle
11
+ from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
12
+ from torch.distributed.tensor import Shard
13
+ from torch.profiler import record_function
14
+ from torch.utils._pytree import tree_flatten, tree_unflatten
15
+ from torch.utils.hooks import RemovableHandle
16
+
17
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
18
+ from ._fsdp_collectives import (
19
+ AllGather,
20
+ AllGatherResult,
21
+ DefaultAllGather,
22
+ DefaultReduceScatter,
23
+ foreach_all_gather,
24
+ foreach_all_gather_copy_out,
25
+ foreach_reduce,
26
+ ProcessGroupAllocAllGather,
27
+ ProcessGroupAllocReduceScatter,
28
+ ReduceScatter,
29
+ )
30
+ from ._fsdp_common import (
31
+ compiled_autograd_enabled,
32
+ DDPMeshInfo,
33
+ FSDPMeshInfo,
34
+ HSDPMeshInfo,
35
+ is_bw,
36
+ TrainingState,
37
+ )
38
+ from ._fsdp_param import alloc_storage, FSDPParam, ParamModuleInfo, ShardedState
39
+
40
+
41
+ logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
42
+
43
+ _ModuleToHandleDict = dict[nn.Module, RemovableHandle] # for state dict
44
+
45
+
46
+ """
47
+ [Note: Overlapping all-gather copy-in and all-gather]
48
+ For implicit forward prefetching, we want to overlap the next copy-in with the
49
+ current all-gather. We do so using a separate copy-in stream. However, since
50
+ we have the all-gather input as a view into the output, we must make sure to
51
+ copy into different memory from the current all-gather's output. Thus, we keep
52
+ a reference to the current all-gather's output and have the next FSDP parameter
53
+ group free it after its copy-in. Finally, we have the last FSDP state flush the
54
+ reference to avoid holding onto memory after forward.
55
+ """
56
+
57
+
58
+ class FSDPCommContext:
59
+ """This has the communication state shared across FSDP states/parameter groups."""
60
+
61
+ def lazy_init(self, device: torch.device):
62
+ self.device_handle = _get_device_handle(device.type)
63
+ # Setting the all-gather/reduce-scatter streams to be higher priority
64
+ # can help avoid some issues where their copies in/out are delayed and
65
+ # block computation (this is different from high-pri NCCL streams)
66
+ high_priority = -1
67
+ # All-gather state and copy-in stream allow overlapping the next
68
+ # copy-in with the current all-gather in forward; copy-in overlaps with
69
+ # reduce-scatter in backward without the separate copy-in stream
70
+ self.all_gather_copy_in_stream = self.device_handle.Stream(
71
+ priority=high_priority
72
+ )
73
+ # All-gather stream allows overlapping next all-gather with current
74
+ # forward compute
75
+ self.all_gather_stream = self.device_handle.Stream(priority=high_priority)
76
+ # Reduce-scatter stream gives separate execution "thread" for post-
77
+ # backward logic like pre/post-gradient division and reduce-scatter
78
+ self.reduce_scatter_stream = self.device_handle.Stream(priority=high_priority)
79
+ # Run the HSDP all-reduces concurrently with all-gather/reduce-scatter
80
+ # since collectives use different network resources and can overlap
81
+ # in the typical intra-node sharding / inter-node replication case
82
+ self.all_reduce_stream = self.device_handle.Stream()
83
+ # All-gather/reduce-scatter states keep references to collective
84
+ # tensors produced in one stream and used in another and accompanying
85
+ # CUDA events for synchronization
86
+ self.all_gather_state: Optional[AllGatherState] = None
87
+ self.reduce_scatter_state: Optional[ReduceScatterState] = None
88
+ # Post-forward order for explicit backward prefetching
89
+ self.post_forward_order: list[FSDPParamGroup] = [] # will cause ref cycles
90
+
91
+ def get_all_gather_streams(
92
+ self, async_op: bool, training_state: TrainingState
93
+ ) -> tuple[torch.Stream, torch.Stream]:
94
+ if not async_op and training_state in (
95
+ TrainingState.FORWARD,
96
+ TrainingState.PRE_BACKWARD,
97
+ ):
98
+ # Use separate streams for implicit prefetching
99
+ return self.all_gather_copy_in_stream, self.all_gather_stream
100
+ current_stream = self.device_handle.current_stream()
101
+ return current_stream, current_stream
102
+
103
+
104
+ # See [Note: Overlapping all-gather copy-in and all-gather]
105
+ class AllGatherState(NamedTuple):
106
+ all_gather_result: AllGatherResult
107
+ event: Optional[torch.Event] # all-gather copy-out
108
+
109
+
110
+ class ReduceScatterState(NamedTuple):
111
+ reduce_scatter_input: torch.Tensor
112
+ event: Optional[torch.Event] # reduce-scatter event
113
+
114
+
115
+ class AllReduceState(NamedTuple):
116
+ all_reduce_input: torch.Tensor
117
+ event: Optional[torch.Event] # all-reduce event
118
+
119
+
120
+ class FSDPParamGroup:
121
+ """This class represents a parameter group to communicate together."""
122
+
123
+ _orig_dtype: Optional[torch.dtype]
124
+ _reduce_dtype: Optional[torch.dtype]
125
+
126
+ def __init__(
127
+ self,
128
+ params: list[nn.Parameter],
129
+ modules: tuple[nn.Module, ...],
130
+ mesh_info: FSDPMeshInfo,
131
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
132
+ device: torch.device,
133
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
134
+ mp_policy: MixedPrecisionPolicy,
135
+ offload_policy: OffloadPolicy,
136
+ ):
137
+ self.modules = modules # permit ref cycle because 1:1 lifetime
138
+ param_module_infos = _get_param_module_infos(params, modules)
139
+
140
+ self.fsdp_params = [
141
+ FSDPParam(
142
+ param,
143
+ module_info,
144
+ mesh_info,
145
+ post_forward_mesh_info,
146
+ device,
147
+ shard_placement_fn,
148
+ mp_policy,
149
+ offload_policy,
150
+ )
151
+ for param, module_info in zip(params, param_module_infos)
152
+ ]
153
+ self.mesh_info = mesh_info
154
+ self.post_forward_mesh_info = post_forward_mesh_info
155
+ # pyrefly: ignore [read-only]
156
+ self.device = device
157
+ self.device_handle = _get_device_handle(device.type)
158
+ self.mp_policy = mp_policy
159
+ self.offload_policy = offload_policy
160
+ self._training_state = TrainingState.IDLE
161
+ # Group's sharded state always matches its parameters' sharded states
162
+ self._sharded_state = ShardedState.SHARDED
163
+ self._module_fqn: Optional[str] = None # prefixed from root module
164
+ # Only consider resetting sharded parameters once in lazy init since it
165
+ # can incur nontrivial overhead to reset them
166
+ self._reset_sharded_params: bool = False
167
+
168
+ # - Hook state
169
+ self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
170
+ self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
171
+ self._all_reduce_hook: Optional[Callable[[torch.Tensor], None]] = None
172
+ self._all_gather_comm: AllGather = DefaultAllGather()
173
+ self._all_gather_output = torch.empty(0, device=self.device)
174
+ self._reduce_scatter_comm: ReduceScatter = DefaultReduceScatter()
175
+ # Optional stream to run the user-defined all-reduce hook in
176
+ # Saved here and not in the comm. context because we allow the user to
177
+ # specify it, possibly at construction time before lazy init
178
+ self._all_reduce_hook_stream: Optional[torch.cuda.Stream] = None
179
+
180
+ # - Communication and communication/computation overlap
181
+ self.comm_ctx = FSDPCommContext()
182
+ # Group's indices in the shared post-forward order
183
+ self._post_forward_indices: list[int] = []
184
+ # Whether to reduce gradients at all (whether for FSDP or HSDP)
185
+ self.reduce_grads: bool = True
186
+ # Whether to all-reduce gradients for HSDP; only used if
187
+ # `self.reduce_grads` is true, in which case setting this to false
188
+ # means reduce-scatter but no all-reduce
189
+ self.all_reduce_grads: bool = True
190
+ # Whether to reshard parameters after backward (only useful for
191
+ # gradient accumulation)
192
+ self.reshard_after_backward: bool = True
193
+ # Optional custom factor for the gradient reduction op (e.g. to divide
194
+ # by a factor other than the world size)
195
+ self.gradient_divide_factor: Optional[float] = None
196
+ # Whether reduce-scatter and all-reduce should be issued using only
197
+ # summations, potentially with separate pre-/post-scaling.
198
+ self.force_sum_reduction_for_comms: bool = False
199
+ # `async_op` arg used for pre-forward/pre-backward unshard; can be
200
+ # overridden to only do explicit prefetching and avoid inter-stream
201
+ # fragmentation from using separate unshard streams
202
+ self.unshard_async_op: bool = False
203
+ # Whether to unshard in backward: can be overridden by the user if the
204
+ # parameters in this group are not needed for backward (e.g. embedding)
205
+ self.unshard_in_backward: bool = True
206
+
207
+ # - CUDA events for stream synchronization
208
+ # Holds the all-gather output buffer, sync objects, and metadata
209
+ self._all_gather_result: Optional[AllGatherResult] = None
210
+ # Holds the reduce-scatter/all-reduce view-out CUDA event that marks the end of
211
+ # the group's post-backward (e.g. reduce-scatter, all-reduce and div), which
212
+ # should be waited on at the end of backward
213
+ self._post_reduce_event: Optional[torch.Event] = None
214
+ # Holds the reshard-after-forward CUDA event when resharding to a
215
+ # different world size, which should be waited on in the next unshard
216
+ self._reshard_after_forward_event: Optional[torch.Event] = None
217
+
218
+ # Only for HSDP, if accumulating gradients without all-reduce, save the
219
+ # partial reduce output (only reduce-scattered but not all-reduced)
220
+ self._partial_reduce_output: Optional[torch.Tensor] = None
221
+ # Holds the all-reduce input and all-reduce event to keep it alive
222
+ # until the end of backward (critical when doing bf16 reduction with
223
+ # fp32 parameters since the all-reduce input is allocated in the RS
224
+ # stream and will have no refs to it after being upcast to fp32)
225
+ self._all_reduce_state: Optional[AllReduceState] = None
226
+
227
+ # Initialization #
228
+ def _init_mp_dtypes(self) -> None:
229
+ for fsdp_param in self.fsdp_params:
230
+ fsdp_param.init_dtype_attrs(self.mp_policy)
231
+ trainable_params: list[FSDPParam] = [
232
+ p for p in self.fsdp_params if p.sharded_param.requires_grad
233
+ ]
234
+ orig_dtypes = {p.orig_dtype for p in trainable_params}
235
+ reduce_dtypes = {p.reduce_dtype for p in trainable_params}
236
+ if len(trainable_params) > 0 and len(orig_dtypes) != 1:
237
+ # Models may have no grad params
238
+ raise AssertionError(
239
+ f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
240
+ )
241
+ self._orig_dtype = next(iter(orig_dtypes)) if trainable_params else None
242
+ if len(trainable_params) > 0 and len(reduce_dtypes) != 1:
243
+ # This can be relaxed if we issue one reduce-scatter per reduce
244
+ # dtype (but we would need a way for users to specify multiple
245
+ # reduce dtypes)
246
+ raise AssertionError(
247
+ f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
248
+ )
249
+ self._reduce_dtype = next(iter(reduce_dtypes)) if trainable_params else None
250
+
251
+ def lazy_init(self):
252
+ # Lazy init should be idempotent
253
+ # Users may change or register parameters after construction time.
254
+ # For example, DoRA (https://arxiv.org/abs/2402.09353) initializes linear magnitudes based on
255
+ # other parameters (e.g. loaded from the state dict).
256
+ if not hasattr(self.comm_ctx, "device_handle"):
257
+ self.comm_ctx.device_handle = _get_device_handle(self.device.type)
258
+ if self.is_sharded and not self._reset_sharded_params:
259
+ for fsdp_param in self.fsdp_params:
260
+ fsdp_param.reset_sharded_param()
261
+ fsdp_param._init_extensions() # allow monkey patch after init
262
+ self._reset_sharded_params = True
263
+ self._validate_no_meta_params()
264
+ self._validate_cpu_offload_params()
265
+ # Initialize mixed precision attributes lazily in case the user changes
266
+ # the parameter dtypes after construction time but before forward
267
+ self._init_mp_dtypes()
268
+ self._register_state_dict_hooks()
269
+
270
+ def set_allocate_memory_from_process_group(self, enable: bool) -> None:
271
+ """
272
+ Whether to (try to) use the ProcessGroup's allocate_tensor method for
273
+ the staging buffers for collective comms.
274
+ """
275
+ if not isinstance(
276
+ self._all_gather_comm, (DefaultAllGather | ProcessGroupAllocAllGather)
277
+ ):
278
+ raise AssertionError(
279
+ "cannot call set_allocate_memory_from_process_group() "
280
+ f"when all gather comm is custom: {self._all_gather_comm.__class__.__name__}"
281
+ )
282
+ self._all_gather_comm = (
283
+ ProcessGroupAllocAllGather(self._all_gather_process_group)
284
+ if enable
285
+ else DefaultAllGather()
286
+ )
287
+
288
+ if not isinstance(
289
+ self._reduce_scatter_comm,
290
+ (DefaultReduceScatter | ProcessGroupAllocReduceScatter),
291
+ ):
292
+ raise AssertionError(
293
+ "cannot call set_allocate_memory_from_process_group() "
294
+ f"when reduce scatter comm is custom: {self._reduce_scatter_comm.__class__.__name__}"
295
+ )
296
+ self._reduce_scatter_comm = (
297
+ ProcessGroupAllocReduceScatter(self._reduce_scatter_process_group)
298
+ if enable
299
+ else DefaultReduceScatter()
300
+ )
301
+
302
+ # Runtime #
303
+ def unshard(self, async_op: bool = False):
304
+ if self._all_gather_result is not None: # already called, pending wait
305
+ return
306
+ if self.is_unsharded:
307
+ return # no-op
308
+ if (
309
+ not self.unshard_in_backward
310
+ and self._training_state == TrainingState.PRE_BACKWARD
311
+ ):
312
+ return
313
+ if self._reshard_after_forward_event is not None:
314
+ # Resharded parameter data is allocated in the default stream and
315
+ # used in the all-gather streams
316
+ self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
317
+ self._reshard_after_forward_event = None
318
+
319
+ if isinstance(self.mesh_info, FSDPMeshInfo):
320
+ world_size = self._all_gather_process_group.size()
321
+ else:
322
+ world_size = 1
323
+ if world_size == 1:
324
+ # can't skip due to early return in wait_for_unshard if
325
+ # no self._all_gather_result
326
+ self._all_gather_result = AllGatherResult(
327
+ all_gather_output=self._all_gather_output,
328
+ all_gather_event=self.device_handle.Event().record(),
329
+ all_gather_work=None,
330
+ param_all_gather_input_dtypes=[],
331
+ param_all_gather_input_numels=[],
332
+ all_gather_input_split_sizes=[],
333
+ )
334
+
335
+ return
336
+
337
+ with record_function(self._with_fqn("FSDP::all_gather")):
338
+ self._all_gather_result = foreach_all_gather(
339
+ self.fsdp_params,
340
+ self._all_gather_process_group,
341
+ async_op,
342
+ *self.comm_ctx.get_all_gather_streams(async_op, self._training_state),
343
+ self.device,
344
+ self._all_gather_comm,
345
+ )
346
+
347
+ def wait_for_unshard(self):
348
+ """
349
+ 1. In forward with implicit prefetching, to overlap the current copy-out
350
+ with the next all-gather, we save a reference to the current all-gather
351
+ result to free after the next copy-out.
352
+ 2. Otherwise (explicit prefetching or in backward), we free the
353
+ all-gather result immediately after the current copy-out since we can
354
+ already overlap the current copy-out with the previous reduce-scatter.
355
+ """
356
+ if not self._all_gather_result:
357
+ return # no preceding unshard
358
+ async_op = self._all_gather_result.all_gather_work is not None
359
+ if self._training_state == TrainingState.FORWARD: # implicit prefetch
360
+ if prev_all_gather_state := self.comm_ctx.all_gather_state:
361
+ self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
362
+ self.comm_ctx.all_gather_state = None # free the all-gather result
363
+ if isinstance(self.mesh_info, FSDPMeshInfo):
364
+ world_size = self._all_gather_process_group.size()
365
+ else:
366
+ world_size = 1
367
+ if world_size == 1:
368
+ # directly initialize unsharded parameters from sharded parameters
369
+
370
+ for fsdp_param in self.fsdp_params:
371
+ # Use all_gather_inputs which already handles conversion to param_dtype
372
+ # This is consistent with the world_size > 1 path
373
+ all_gather_input = fsdp_param.all_gather_inputs[0]
374
+
375
+ # Make sure the all_gather_outputs has proper storage size before using it
376
+ # First ensure we have at least one tensor in all_gather_outputs
377
+ fsdp_param.init_all_gather_outputs(
378
+ [all_gather_input.numel()],
379
+ [all_gather_input.dtype],
380
+ world_size,
381
+ self.device,
382
+ force_recreate=False,
383
+ )
384
+
385
+ tensor = fsdp_param.all_gather_outputs[0]
386
+ alloc_storage(tensor)
387
+
388
+ # find alternative way to check if tensor.is_inference
389
+ with torch.autograd._unsafe_preserve_version_counter(tensor):
390
+ tensor.copy_(all_gather_input)
391
+
392
+ else:
393
+ with record_function(self._with_fqn("FSDP::all_gather_copy_out")):
394
+ foreach_all_gather_copy_out(
395
+ self._all_gather_result,
396
+ self.fsdp_params,
397
+ self._all_gather_process_group,
398
+ )
399
+
400
+ for fsdp_param in self.fsdp_params:
401
+ fsdp_param.init_unsharded_param()
402
+
403
+ self._to_unsharded()
404
+ all_gather_copy_out_event = self.device_handle.Event()
405
+ all_gather_copy_out_event.record()
406
+
407
+ if (
408
+ not async_op
409
+ and self._training_state == TrainingState.FORWARD
410
+ and world_size > 1
411
+ ):
412
+ # Defer free to allow for overlap of this copy-out with next
413
+ # all-gather collective
414
+ self.comm_ctx.all_gather_state = AllGatherState(
415
+ self._all_gather_result, all_gather_copy_out_event
416
+ )
417
+ else:
418
+ self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
419
+
420
+ self._all_gather_result = None # free unless saved in `all_gather_state`
421
+
422
+ def _wait_all_gather_streams_on_event(self, event: Optional[torch.Event]):
423
+ # Calling `unshard` before lazy init means streams are not initialized
424
+ if hasattr(self.comm_ctx, "all_gather_copy_in_stream") and event is not None:
425
+ self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
426
+ if hasattr(self.comm_ctx, "all_gather_stream") and event is not None:
427
+ self.comm_ctx.all_gather_stream.wait_event(event)
428
+
429
+ def reshard(self):
430
+ if self._training_state == TrainingState.FORWARD:
431
+ if not self._reshard_after_forward:
432
+ return
433
+ if self._use_post_forward_mesh:
434
+ self._to_sharded_post_forward()
435
+ self._reshard_after_forward_event = self.device_handle.Event()
436
+ if self._reshard_after_forward_event is not None:
437
+ self._reshard_after_forward_event.record()
438
+ return
439
+ self._to_sharded()
440
+
441
+ def pre_forward(
442
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
443
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
444
+ if not compiled_autograd_enabled():
445
+ logger.debug("%s", self._with_fqn("FSDP::pre_forward"))
446
+ with record_function(self._with_fqn("FSDP::pre_forward")):
447
+ self._training_state = TrainingState.FORWARD
448
+ self.unshard(self.unshard_async_op)
449
+ self.wait_for_unshard()
450
+ args, kwargs = self._register_post_backward_hook(args, kwargs)
451
+ return args, kwargs
452
+
453
+ def post_forward(self, module: nn.Module, input: Any, output: Any):
454
+ if not compiled_autograd_enabled():
455
+ logger.debug("%s", self._with_fqn("FSDP::post_forward"))
456
+ with record_function(self._with_fqn("FSDP::post_forward")):
457
+ if not compiled_autograd_enabled():
458
+ # for AC(fully_shard(model)), AC runs fsdp's _pre_forward
459
+ # it shouldn't change post_forward_order
460
+ if not is_bw():
461
+ self.reshard()
462
+ self._record_post_forward()
463
+ else:
464
+ self.reshard()
465
+ self._record_post_forward()
466
+ self._training_state = TrainingState.IDLE
467
+ return output
468
+
469
+ def _record_post_forward(self) -> None:
470
+ # Since a group has one pre-backward unshard for each forward call
471
+ # before the backward, we record each usage (with multiplicity)
472
+ post_forward_index = len(self.comm_ctx.post_forward_order)
473
+ self.comm_ctx.post_forward_order.append(self)
474
+ self._post_forward_indices.append(post_forward_index)
475
+
476
+ def pre_backward(self, default_prefetch: bool, *unused: Any):
477
+ if (
478
+ compiled_autograd_enabled()
479
+ and self._training_state == TrainingState.PRE_BACKWARD
480
+ ):
481
+ # Traceable FSDP2 cannot trigger the param group's `post_backward` immediately after param usage;
482
+ # instead it relies on this to trigger the previously unexecuted `post_backward`.
483
+ self.post_backward()
484
+ if self._training_state == TrainingState.PRE_BACKWARD:
485
+ return
486
+ if not compiled_autograd_enabled():
487
+ logger.debug("%s", self._with_fqn("FSDP::pre_backward"))
488
+ with record_function(self._with_fqn("FSDP::pre_backward")):
489
+ self._training_state = TrainingState.PRE_BACKWARD
490
+ self.unshard(self.unshard_async_op) # no-op if prefetched
491
+ self.wait_for_unshard()
492
+ if default_prefetch and not compiled_autograd_enabled():
493
+ self._backward_prefetch()
494
+
495
+ def post_backward(self, *unused: Any):
496
+ # This method should be idempotent and safe to call even when this
497
+ # FSDP parameter group was not used in backward (should be a no-op)
498
+ if not compiled_autograd_enabled():
499
+ logger.debug("%s", self._with_fqn("FSDP::post_backward"))
500
+ self._training_state = TrainingState.POST_BACKWARD
501
+ with record_function(self._with_fqn("FSDP::post_backward_accumulate")):
502
+ for fsdp_param in self.fsdp_params:
503
+ fsdp_param.accumulate_unsharded_grad_if_needed()
504
+ with record_function(self._with_fqn("FSDP::post_backward_reshard")):
505
+ if not self.reduce_grads:
506
+ if self.reshard_after_backward:
507
+ self.reshard()
508
+ for fsdp_param in self.fsdp_params:
509
+ fsdp_param.to_accumulated_grad_if_needed()
510
+ return
511
+ # Save the autograd-computed gradients before resharding to only
512
+ # access the unsharded parameters when their data is present
513
+ fsdp_params_with_grad: list[FSDPParam] = []
514
+ unsharded_grads: list[torch.Tensor] = []
515
+ for fsdp_param in self.fsdp_params:
516
+ if not hasattr(fsdp_param, "_unsharded_param"):
517
+ continue
518
+ # May have an accumulated gradient of the reduce dtype if the
519
+ # previous backward did not reduce-scatter
520
+ if fsdp_param.unsharded_accumulated_grad is not None:
521
+ fsdp_params_with_grad.append(fsdp_param)
522
+ unsharded_grads.append(fsdp_param.unsharded_accumulated_grad_data)
523
+ fsdp_param.unsharded_accumulated_grad = None
524
+ elif fsdp_param.unsharded_param.grad is not None:
525
+ fsdp_params_with_grad.append(fsdp_param)
526
+ unsharded_grads.append(fsdp_param.unsharded_grad_data)
527
+ fsdp_param.unsharded_param.grad = None
528
+ if self.reshard_after_backward:
529
+ self.reshard()
530
+ if len(fsdp_params_with_grad) == 0:
531
+ return
532
+ with record_function(self._with_fqn("FSDP::post_backward_reduce")):
533
+ if (
534
+ self.comm_ctx.reduce_scatter_state is not None
535
+ and self.comm_ctx.reduce_scatter_state.event is not None
536
+ ):
537
+ self.device_handle.current_stream().wait_event(
538
+ self.comm_ctx.reduce_scatter_state.event
539
+ )
540
+ self.comm_ctx.reduce_scatter_state = None
541
+ all_reduce_pg = (
542
+ self._all_reduce_process_group
543
+ if isinstance(self.mesh_info, DDPMeshInfo)
544
+ else None
545
+ )
546
+ all_reduce_stream: torch.cuda.Stream
547
+ if all_reduce_pg is None and self._all_reduce_hook_stream is not None:
548
+ # this means the native HSDP is not enabled,
549
+ # but user may want to have a custom HSDP setup
550
+ if self._all_reduce_hook is None:
551
+ raise AssertionError(
552
+ "all reduce hook stream is specified but hook itself is missing."
553
+ )
554
+ all_reduce_stream = self._all_reduce_hook_stream
555
+ else:
556
+ all_reduce_stream = self.comm_ctx.all_reduce_stream
557
+
558
+ self._wait_for_post_backward()
559
+ (
560
+ reduce_scatter_input,
561
+ reduce_scatter_event,
562
+ self._post_reduce_event,
563
+ all_reduce_input,
564
+ all_reduce_event,
565
+ self._partial_reduce_output,
566
+ ) = foreach_reduce(
567
+ fsdp_params_with_grad,
568
+ unsharded_grads,
569
+ (
570
+ self._reduce_scatter_process_group
571
+ if isinstance(self.mesh_info, FSDPMeshInfo)
572
+ else None # pyre-fixme[6]
573
+ ),
574
+ self.comm_ctx.reduce_scatter_stream,
575
+ self._reduce_scatter_comm,
576
+ self._orig_dtype,
577
+ self._reduce_dtype,
578
+ self.device,
579
+ self.gradient_divide_factor,
580
+ (
581
+ self._all_reduce_process_group
582
+ if isinstance(self.mesh_info, DDPMeshInfo)
583
+ else None
584
+ ),
585
+ all_reduce_stream,
586
+ self.all_reduce_grads,
587
+ self._partial_reduce_output,
588
+ self._all_reduce_hook,
589
+ self.force_sum_reduction_for_comms,
590
+ )
591
+ self.comm_ctx.reduce_scatter_state = ReduceScatterState(
592
+ reduce_scatter_input, reduce_scatter_event
593
+ )
594
+ if all_reduce_input is not None:
595
+ if self.device.type != "cpu":
596
+ if all_reduce_event is None:
597
+ raise AssertionError(
598
+ "Expected all_reduce_event to be set for non-CPU device"
599
+ )
600
+ self._all_reduce_state = AllReduceState(
601
+ all_reduce_input, all_reduce_event
602
+ )
603
+
604
+ def finalize_backward(self):
605
+ self._wait_for_post_backward()
606
+ for fsdp_param in self.fsdp_params:
607
+ if fsdp_param.grad_offload_event is not None:
608
+ fsdp_param.grad_offload_event.synchronize()
609
+ fsdp_param.grad_offload_event = None
610
+ if self._all_gather_result is not None:
611
+ # If there was a mistargeted unshard without a corresponding wait,
612
+ # then we wait here and clear the unshard
613
+ if (event := self._all_gather_result.all_gather_event) is not None:
614
+ torch.accelerator.current_stream().wait_event(event)
615
+ work = self._all_gather_result.all_gather_work
616
+ if isinstance(work, dist.distributed_c10d.Work):
617
+ work.wait()
618
+ self._all_gather_result = None
619
+ self._post_forward_indices.clear()
620
+
621
+ def _wait_for_post_backward(self):
622
+ if self._post_reduce_event is not None:
623
+ self.device_handle.current_stream().wait_event(self._post_reduce_event)
624
+ self._post_reduce_event = None
625
+ if (
626
+ self._all_reduce_state is not None
627
+ and self._all_reduce_state.event is not None
628
+ ):
629
+ self.device_handle.current_stream().wait_event(self._all_reduce_state.event)
630
+ self._all_reduce_state = None
631
+
632
+ def _backward_prefetch(self) -> None:
633
+ if self._training_state == TrainingState.PRE_BACKWARD:
634
+ if not self._post_forward_indices:
635
+ # Can be cleared if running multiple `backward`s
636
+ return
637
+ curr_index = self._post_forward_indices.pop()
638
+ if (target_index := curr_index - 1) < 0:
639
+ return
640
+ # Prefetch naively using the reverse post-forward order, which may
641
+ # have mistargeted prefetches if not all modules used in forward
642
+ # are used in this backward
643
+ # pyrefly: ignore [unbound-name]
644
+ target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
645
+ self._prefetch_unshard(target_fsdp_param_group, "backward")
646
+
647
+ @staticmethod
648
+ def _prefetch_unshard(
649
+ target_fsdp_param_group: "FSDPParamGroup", pass_type: str
650
+ ) -> None:
651
+ if pass_type == "backward":
652
+ training_state = TrainingState.PRE_BACKWARD
653
+ elif pass_type == "forward":
654
+ training_state = TrainingState.FORWARD
655
+ else:
656
+ raise ValueError(f"Unknown pass type: {pass_type}")
657
+ target_fqn = target_fsdp_param_group._module_fqn
658
+ with (
659
+ record_function(f"FSDP::{pass_type}_prefetch for {target_fqn}"),
660
+ target_fsdp_param_group.use_training_state(training_state),
661
+ ):
662
+ async_op = target_fsdp_param_group.unshard_async_op
663
+ target_fsdp_param_group.unshard(async_op)
664
+
665
+ # Utilities #
666
+ def _to_sharded(self):
667
+ if not self.is_sharded:
668
+ for fsdp_param in self.fsdp_params:
669
+ fsdp_param.to_sharded()
670
+ self._sharded_state = ShardedState.SHARDED
671
+
672
+ def _to_sharded_post_forward(self):
673
+ if not self.is_sharded_post_forward:
674
+ for fsdp_param in self.fsdp_params:
675
+ fsdp_param.to_sharded_post_forward()
676
+ self._sharded_state = ShardedState.SHARDED_POST_FORWARD
677
+
678
+ def _to_unsharded(self):
679
+ if not self.is_unsharded:
680
+ for fsdp_param in self.fsdp_params:
681
+ fsdp_param.to_unsharded()
682
+ self._sharded_state = ShardedState.UNSHARDED
683
+
684
+ @property
685
+ def is_sharded(self) -> bool:
686
+ return self._sharded_state == ShardedState.SHARDED
687
+
688
+ @property
689
+ def is_sharded_post_forward(self) -> bool:
690
+ return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
691
+
692
+ @property
693
+ def is_unsharded(self) -> bool:
694
+ return self._sharded_state == ShardedState.UNSHARDED
695
+
696
+ @contextlib.contextmanager
697
+ def use_training_state(self, training_state: TrainingState):
698
+ old_training_state = self._training_state
699
+ self._training_state = training_state
700
+ try:
701
+ yield
702
+ finally:
703
+ self._training_state = old_training_state
704
+
705
+ # Hook Registration #
706
+ def _register_post_backward_hook(
707
+ self, args: tuple[Any, ...], kwargs: dict[str, Any]
708
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
709
+ # Traceable FSDP2 relies on `root_post_backward_callback` to call each
710
+ # `FSDPParamGroup.post_backward`
711
+ if (not torch._dynamo.config.skip_fsdp_hooks) or compiled_autograd_enabled():
712
+ return args, kwargs
713
+ if not torch.is_grad_enabled():
714
+ return args, kwargs
715
+ args_list, args_spec = tree_flatten(args)
716
+ kwargs_list, kwargs_spec = tree_flatten(kwargs)
717
+ args_kwargs_list = list(args_list) + list(kwargs_list)
718
+ inp_tensor_indices: list[int] = []
719
+ inp_tensors: list[torch.Tensor] = []
720
+ for i, obj in enumerate(args_kwargs_list):
721
+ if torch.is_tensor(obj) and obj.requires_grad:
722
+ inp_tensor_indices.append(i)
723
+ inp_tensors.append(obj)
724
+ if len(inp_tensors) == 0:
725
+ return args, kwargs # no tensors that require gradients
726
+ inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
727
+ for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
728
+ args_kwargs_list[inp_tensor_idx] = inp_tensor
729
+ args_list = args_kwargs_list[: len(args_list)]
730
+ kwargs_list = args_kwargs_list[len(args_list) :]
731
+ args = tree_unflatten(args_list, args_spec)
732
+ kwargs = tree_unflatten(kwargs_list, kwargs_spec)
733
+ return args, kwargs
734
+
735
+ def _register_state_dict_hooks(self) -> None:
736
+ num_pre_save_hooks = len(self._module_to_pre_save_state_dict_hook_handle)
737
+ num_pre_load_hooks = len(self._module_to_pre_load_state_dict_hook_handle)
738
+ if num_pre_save_hooks != num_pre_load_hooks:
739
+ raise AssertionError(
740
+ f"Pre-save: {num_pre_save_hooks} pre-load: {num_pre_load_hooks}"
741
+ )
742
+ if num_pre_save_hooks > 0:
743
+ return # already registered
744
+ modules_with_fsdp_params: set[nn.Module] = {
745
+ fsdp_param._module_info.module for fsdp_param in self.fsdp_params
746
+ }
747
+
748
+ def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
749
+ self._to_sharded()
750
+
751
+ for module in modules_with_fsdp_params:
752
+ self._module_to_pre_save_state_dict_hook_handle[module] = (
753
+ module.register_state_dict_pre_hook(to_sharded_hook)
754
+ )
755
+ self._module_to_pre_load_state_dict_hook_handle[module] = (
756
+ module._register_load_state_dict_pre_hook(to_sharded_hook)
757
+ )
758
+
759
+ # Properties #
760
+ @property
761
+ def _reshard_after_forward(self) -> bool:
762
+ return self.post_forward_mesh_info is not None
763
+
764
+ @property
765
+ def _use_post_forward_mesh(self) -> bool:
766
+ return (
767
+ self._reshard_after_forward
768
+ and self.mesh_info != self.post_forward_mesh_info
769
+ )
770
+
771
+ @property
772
+ def _is_hsdp(self) -> bool:
773
+ return isinstance(self.mesh_info, HSDPMeshInfo)
774
+
775
+ @property
776
+ def _all_gather_process_group(self) -> dist.ProcessGroup:
777
+ mesh_info = (
778
+ cast(FSDPMeshInfo, self.post_forward_mesh_info)
779
+ if self.is_sharded_post_forward
780
+ else self.mesh_info
781
+ )
782
+ if not isinstance(mesh_info, FSDPMeshInfo):
783
+ raise AssertionError(
784
+ f"Expected mesh_info to be FSDPMeshInfo, got {type(mesh_info)}"
785
+ )
786
+ return mesh_info.shard_process_group
787
+
788
+ @property
789
+ def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
790
+ if not isinstance(self.mesh_info, FSDPMeshInfo):
791
+ raise AssertionError(
792
+ f"Expected mesh_info to be FSDPMeshInfo, got {type(self.mesh_info)}"
793
+ )
794
+ return self.mesh_info.shard_process_group
795
+
796
+ @property
797
+ def _all_reduce_process_group(self) -> dist.ProcessGroup:
798
+ if not isinstance(self.mesh_info, DDPMeshInfo):
799
+ raise AssertionError(
800
+ f"Expected mesh_info to be DDPMeshInfo or HSDPMeshInfo, got {type(self.mesh_info)}"
801
+ )
802
+ return self.mesh_info.replicate_process_group
803
+
804
+ def _with_fqn(self, label: str) -> str:
805
+ if self._module_fqn:
806
+ return f"{label} ({self._module_fqn})"
807
+ return label
808
+
809
+ def __repr__(self):
810
+ return f"FSDPParamGroup(fqn={self._module_fqn})"
811
+
812
+ def _validate_no_meta_params(self):
813
+ param_names_on_meta = [
814
+ fsdp_param._param_fqn
815
+ for fsdp_param in self.fsdp_params
816
+ if fsdp_param.sharded_param.device.type == "meta"
817
+ ]
818
+ if param_names_on_meta:
819
+ raise RuntimeError(
820
+ "FSDP parameters should be materialized from meta device before training, "
821
+ f"but the following were still on meta device: {param_names_on_meta}\n"
822
+ "For example, call module.to_empty(device) to materialize to device and "
823
+ "call module.reset_parameters() on each module to initialize values."
824
+ )
825
+
826
+ def _validate_cpu_offload_params(self):
827
+ if not isinstance(self.offload_policy, CPUOffloadPolicy):
828
+ return
829
+ fsdp_params_not_on_cpu = [
830
+ fsdp_param
831
+ for fsdp_param in self.fsdp_params
832
+ if fsdp_param.sharded_param.device.type != "cpu"
833
+ ]
834
+ if fsdp_params_not_on_cpu:
835
+ raise RuntimeError(
836
+ "FSDP parameters should be materialized on CPU when enabling CPU offloading. "
837
+ 'For example, load a CPU state dict or call module.to_empty(device="cpu"). '
838
+ "Found following parameters on non-CPU device: "
839
+ f"{[(fsdp_param._param_fqn, fsdp_param.sharded_param.device) for fsdp_param in fsdp_params_not_on_cpu]}\n"
840
+ )
841
+
842
+
843
+ def _get_param_module_infos(
844
+ params: list[nn.Parameter], modules: tuple[nn.Module, ...]
845
+ ) -> list[ParamModuleInfo]:
846
+ """
847
+ Shared parameter: lin1.weight = lin2.weight
848
+ Shared module: mlp.lin1 = mlp.lin2
849
+ We do not remove duplicates when traversing both modules and parameters to
850
+ find shared modules' parameters and shared parameters within a module.
851
+ """
852
+ params_set = set(params)
853
+ param_to_module_info: dict[nn.Parameter, ParamModuleInfo] = {}
854
+ for module in modules:
855
+ for _, submodule in module.named_modules(remove_duplicate=False):
856
+ for param_name, param in _named_parameters_with_duplicates(
857
+ submodule, recurse=False
858
+ ):
859
+ if param in params_set:
860
+ if param not in param_to_module_info:
861
+ param_to_module_info[param] = ParamModuleInfo(
862
+ submodule, param_name
863
+ )
864
+ else:
865
+ param_to_module_info[param].shared_modules.append(submodule)
866
+ param_to_module_info[param].shared_param_names.append(
867
+ param_name
868
+ )
869
+ if len(param_to_module_info) != len(params):
870
+ raise AssertionError(f"Some parameters are not in the module tree of {modules}")
871
+ return [param_to_module_info[param] for param in params]
872
+
873
+
874
+ class RegisterPostBackwardFunction(torch.autograd.Function):
875
+ @staticmethod
876
+ def _assert_not_tracing_fsdp():
877
+ if compiled_autograd_enabled():
878
+ # TODO: Find a way to print the offending FSDP2 module.
879
+ msg = """\
880
+ When Traceable FSDP2 is enabled, we should not be calling into `RegisterPostBackwardFunction`.
881
+ Instead, we rely on the param group's next `pre_backward` hook to trigger its previously unexecuted
882
+ `post_backward`, and we rely on FSDPState's `root_post_backward_callback` to trigger the resharding
883
+ of any leftover unsharded param groups.
884
+ If you are here, it means the forward part of this FSDP2 instance is not compiled, and you must also
885
+ compile the forward part if you want to use Traceable FSDP2."""
886
+ torch._dynamo.comptime.comptime.print(msg)
887
+ raise RuntimeError(msg)
888
+
889
+ @staticmethod
890
+ # pyrefly: ignore [bad-override]
891
+ def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
892
+ # All tensors in `inputs` should require gradient
893
+ RegisterPostBackwardFunction._assert_not_tracing_fsdp()
894
+ ctx.param_group = param_group
895
+ return inputs
896
+
897
+ @staticmethod
898
+ def backward(ctx, *grads: torch.Tensor):
899
+ RegisterPostBackwardFunction._assert_not_tracing_fsdp()
900
+ ctx.param_group.post_backward()
901
+ return (None,) + grads
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fsdp_state.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import functools
4
+ import logging
5
+ from collections.abc import Callable, Sequence
6
+ from typing import Any, Optional, TYPE_CHECKING
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch._logging import warning_once
11
+ from torch.autograd import Variable
12
+ from torch.autograd.graph import _MultiHandle
13
+ from torch.distributed._composable_state import (
14
+ _get_module_state,
15
+ _insert_module_state,
16
+ _State,
17
+ )
18
+ from torch.distributed.device_mesh import _get_device_handle
19
+ from torch.distributed.utils import _apply_to_tensors, _to_kwargs
20
+ from torch.utils._pytree import tree_flatten
21
+
22
+ from ._fsdp_api import MixedPrecisionPolicy
23
+ from ._fsdp_common import (
24
+ _cast_fp_tensor,
25
+ compiled_autograd_enabled,
26
+ detect_compiled_autograd,
27
+ TrainingState,
28
+ )
29
+ from ._fsdp_param_group import FSDPCommContext, FSDPParamGroup
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from ._fsdp_param import FSDPParam
34
+
35
+
36
+ logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
37
+
38
+
39
+ class FSDPStateContext:
40
+ """This has state shared across FSDP states."""
41
+
42
+ def __init__(self) -> None:
43
+ # All FSDP states in the root state's module tree
44
+ self.all_states: list[FSDPState] = []
45
+ # Iteration's forward root runs the once-per-forward logic; this root
46
+ # may not be the overall root set by lazy initialization in cases where
47
+ # only a submodule runs forward (e.g. encoder-only for eval)
48
+ self.iter_forward_root: Optional[FSDPState] = None
49
+ # Final callback should only be queued once per backward
50
+ self.post_backward_final_callback_queued: bool = False
51
+ # Whether to finalize backward in this backward's final callback
52
+ self.is_last_backward: bool = True
53
+ # Optional user-provided event recorded after optimizer for the
54
+ # all-gather streams to wait on in the root pre-forward
55
+ self.post_optim_event: Optional[torch.Event] = None
56
+
57
+
58
+ def disable_if_config_true(func):
59
+ @functools.wraps(func)
60
+ def fsdp_hook_wrapper(*args, **kwargs):
61
+ if torch._dynamo.config.skip_fsdp_hooks:
62
+ return torch._dynamo.disable(
63
+ func,
64
+ recursive=True,
65
+ reason="skipping FSDP hooks since torch._dynamo.config.skip_fsdp_hooks is set",
66
+ )(*args, **kwargs)
67
+ else:
68
+ return func(*args, **kwargs)
69
+
70
+ return fsdp_hook_wrapper
71
+
72
+
73
+ class FSDPState(_State):
74
+ def __init__(self) -> None:
75
+ super().__init__()
76
+ self._fsdp_param_group: Optional[FSDPParamGroup] = None
77
+ self._is_root: Optional[bool] = None # root set during lazy init
78
+ self._state_ctx = FSDPStateContext()
79
+ self._comm_ctx = FSDPCommContext()
80
+ self._training_state: TrainingState = TrainingState.IDLE
81
+ self._states_to_forward_prefetch: list[FSDPState] = []
82
+ self._states_to_backward_prefetch: list[FSDPState] = []
83
+ self._modules_to_run_forward: set[nn.Module] = set()
84
+ # ``False`` when user set reshard_after_forward
85
+ # through ``fully_shard`` or ``set_reshard_after_forward``
86
+ self._auto_reshard_after_forward: Optional[bool] = True
87
+
88
+ # Define a separate init since `__init__` is called in the contract
89
+ def init(
90
+ self,
91
+ modules: tuple[nn.Module, ...],
92
+ device: torch.device,
93
+ mp_policy: MixedPrecisionPolicy,
94
+ auto_reshard_after_forward: bool,
95
+ ) -> None:
96
+ for module in modules:
97
+ _insert_module_state(module, self)
98
+ self._modules = modules
99
+ # pyrefly: ignore [read-only]
100
+ self._device = device
101
+ self._device_handle = _get_device_handle(device.type)
102
+ self._mp_policy = mp_policy
103
+ self._auto_reshard_after_forward = auto_reshard_after_forward
104
+ if len(modules) == 1:
105
+ self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
106
+ self._pre_forward, prepend=True, with_kwargs=True
107
+ )
108
+ self._post_forward_hook_handle = modules[0].register_forward_hook(
109
+ self._post_forward, prepend=False
110
+ )
111
+ else:
112
+ hook_handle = _register_group_forward_hooks(
113
+ modules,
114
+ self._pre_forward,
115
+ self._post_forward,
116
+ self._modules_to_run_forward,
117
+ )
118
+ self._pre_forward_hook_handle = hook_handle
119
+ self._post_forward_hook_handle = hook_handle
120
+
121
+ def _root_pre_forward(
122
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
123
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
124
+ self._lazy_init()
125
+ if self._state_ctx.iter_forward_root is not None:
126
+ return args, kwargs
127
+ if not compiled_autograd_enabled():
128
+ logger.debug("FSDP::root_pre_forward")
129
+ self._state_ctx.iter_forward_root = self
130
+ with torch.profiler.record_function("FSDP::root_pre_forward"):
131
+ # Wait for optimizer before implicitly prefetched all-gathers
132
+ if (event := self._state_ctx.post_optim_event) is not None:
133
+ self._comm_ctx.all_gather_copy_in_stream.wait_event(event)
134
+ self._comm_ctx.all_gather_stream.wait_event(event)
135
+ self._state_ctx.post_optim_event = None
136
+ else:
137
+ current_stream = self._device_handle.current_stream()
138
+ self._comm_ctx.all_gather_copy_in_stream.wait_stream(current_stream)
139
+ self._comm_ctx.all_gather_stream.wait_stream(current_stream)
140
+ if self._device.type in [
141
+ "cuda",
142
+ "hpu",
143
+ "xpu",
144
+ "mtia",
145
+ torch._C._get_privateuse1_backend_name(),
146
+ ]:
147
+ with torch.profiler.record_function("FSDP::inputs_to_device"):
148
+ args_tuple, kwargs_tuple = _to_kwargs(
149
+ args, kwargs, self._device, False
150
+ ) # same as DDP
151
+ args, kwargs = args_tuple[0], kwargs_tuple[0]
152
+ return args, kwargs
153
+
154
+ def _lazy_init(self) -> None:
155
+ """
156
+ Lazy initialization represents when all modules' parallelisms have
157
+ finalized (e.g. FSDP has been applied to all desired modules). This
158
+ means that we can determine which state is the root, and we do so by
159
+ the 1st state to run forward.
160
+ """
161
+ if self._is_root is not None:
162
+ return # no-op: already initialized
163
+ self._is_root = True
164
+ if len(self._modules) > 1:
165
+ raise RuntimeError(
166
+ f"FSDP requires a single root module but got {self._modules}"
167
+ )
168
+ detect_compiled_autograd()
169
+ root_module = self._modules[0]
170
+ visited_states: set[FSDPState] = set()
171
+ for module_name, module in root_module.named_modules():
172
+ if (state := _get_module_fsdp_state(module)) is None:
173
+ continue
174
+ if module is not root_module:
175
+ if state not in visited_states and state._is_root is not None:
176
+ raise RuntimeError(
177
+ "FSDP state has already been lazily initialized for "
178
+ f"{module_name}\nFSDP requires running forward through "
179
+ "the root module first"
180
+ )
181
+ state._is_root = False
182
+ self._state_ctx.all_states.append(state)
183
+ visited_states.add(state)
184
+ if self._fsdp_param_group and self._auto_reshard_after_forward:
185
+ # For the root, do not reshard after forward since for training,
186
+ # the parameters would be freed and all-gathered immediately
187
+ self._fsdp_param_group.post_forward_mesh_info = None
188
+ self._init_fqns()
189
+ self._init_shared_state()
190
+ # Run parameter group lazy inits after initializing FQNs for improved
191
+ # error messages
192
+ for state in self._state_ctx.all_states:
193
+ if state._fsdp_param_group:
194
+ state._fsdp_param_group.lazy_init()
195
+
196
+ def _init_shared_state(self) -> None:
197
+ self._comm_ctx.lazy_init(self._device)
198
+ for state in self._state_ctx.all_states:
199
+ state._state_ctx = self._state_ctx
200
+ state._comm_ctx = self._comm_ctx
201
+ if fsdp_param_group := state._fsdp_param_group:
202
+ fsdp_param_group.comm_ctx = self._comm_ctx
203
+
204
+ def _init_fqns(self) -> None:
205
+ """Sets module and parameter FQN attributes for debugging."""
206
+ if not self._is_root:
207
+ raise AssertionError("Expected _is_root to be True")
208
+ root_module = self._modules[0]
209
+ param_to_fsdp_param: dict[nn.Parameter, FSDPParam] = {}
210
+ module_to_fsdp_param_group: dict[nn.Module, FSDPParamGroup] = {}
211
+ for state in self._state_ctx.all_states:
212
+ if fsdp_param_group := state._fsdp_param_group:
213
+ for fsdp_param in fsdp_param_group.fsdp_params:
214
+ param_to_fsdp_param[fsdp_param.sharded_param] = fsdp_param
215
+ for module in fsdp_param_group.modules:
216
+ module_to_fsdp_param_group[module] = fsdp_param_group
217
+ for param_name, param in root_module.named_parameters():
218
+ if param in param_to_fsdp_param:
219
+ param_to_fsdp_param[param]._param_fqn = param_name
220
+ for module_name, module in root_module.named_modules():
221
+ if module in module_to_fsdp_param_group:
222
+ module_fqn = module_to_fsdp_param_group[module]._module_fqn
223
+ if module_fqn is None:
224
+ module_to_fsdp_param_group[module]._module_fqn = module_name
225
+ else:
226
+ if not isinstance(module_fqn, str):
227
+ raise AssertionError(
228
+ f"Expected module_fqn to be str, got {type(module_fqn)}: {module_fqn}"
229
+ )
230
+ module_fqn += f", {module_name}"
231
+ module_to_fsdp_param_group[module]._module_fqn = module_fqn
232
+
233
+ @disable_if_config_true
234
+ def _pre_forward(
235
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
236
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
237
+ # When composing with module-hook-based activation checkpointing, the
238
+ # pre-backward hook is responsible for the unshard
239
+ if self._training_state == TrainingState.PRE_BACKWARD:
240
+ return args, kwargs
241
+ self._training_state = TrainingState.FORWARD
242
+ args, kwargs = self._root_pre_forward(module, args, kwargs)
243
+ if self._mp_policy.cast_forward_inputs and self._mp_policy.param_dtype:
244
+ with torch.profiler.record_function("FSDP::cast_forward_inputs"):
245
+ cast_fn = functools.partial(
246
+ _cast_fp_tensor, self._mp_policy.param_dtype
247
+ )
248
+ args, kwargs = (
249
+ _apply_to_tensors(cast_fn, args),
250
+ _apply_to_tensors(cast_fn, kwargs),
251
+ )
252
+ if self._fsdp_param_group:
253
+ args, kwargs = self._fsdp_param_group.pre_forward(module, args, kwargs)
254
+ for fsdp_state in self._states_to_forward_prefetch:
255
+ if (target_param_group := fsdp_state._fsdp_param_group) is not None:
256
+ FSDPParamGroup._prefetch_unshard(target_param_group, "forward")
257
+ return args, kwargs
258
+
259
+ @disable_if_config_true
260
+ def _post_forward(self, module: nn.Module, input: Any, output: Any) -> Any:
261
+ # When composing with module-hook-based activation checkpointing, the
262
+ # post-backward hook is responsible for the reshard
263
+ if self._training_state == TrainingState.PRE_BACKWARD:
264
+ return output
265
+ if self._fsdp_param_group:
266
+ output = self._fsdp_param_group.post_forward(module, input, output)
267
+ output = self._register_pre_backward_hook(output)
268
+ self._training_state = TrainingState.IDLE
269
+ if self._state_ctx.iter_forward_root is self:
270
+ if all_gather_state := self._comm_ctx.all_gather_state:
271
+ # Free the last all-gather result if needed; refer to
272
+ # [Note: Overlapping all-gather copy-in and all-gather]
273
+ self._comm_ctx.all_gather_copy_in_stream.wait_event(
274
+ all_gather_state.event
275
+ )
276
+ self._comm_ctx.all_gather_stream.wait_event(all_gather_state.event)
277
+ self._comm_ctx.all_gather_state = None # free the all-gather result
278
+ self._state_ctx.iter_forward_root = None
279
+ if self._mp_policy.output_dtype is not None:
280
+ with torch.profiler.record_function("FSDP::cast_forward_outputs"):
281
+ output = _apply_to_tensors(
282
+ functools.partial(_cast_fp_tensor, self._mp_policy.output_dtype),
283
+ output,
284
+ )
285
+ return output
286
+
287
+ def _pre_backward(self, grad: torch.Tensor) -> torch.Tensor:
288
+ self._training_state = TrainingState.PRE_BACKWARD
289
+ self._register_root_post_backward_final_callback()
290
+ if self._fsdp_param_group:
291
+ default_prefetch = len(self._states_to_backward_prefetch) == 0
292
+ self._fsdp_param_group.pre_backward(default_prefetch)
293
+ for fsdp_state in self._states_to_backward_prefetch:
294
+ if (target_param_group := fsdp_state._fsdp_param_group) is not None:
295
+ FSDPParamGroup._prefetch_unshard(target_param_group, "backward")
296
+ return grad
297
+
298
+ def _root_post_backward_final_callback(self) -> None:
299
+ if not compiled_autograd_enabled():
300
+ logger.debug("FSDP::root_post_backward")
301
+ with torch.profiler.record_function("FSDP::root_post_backward_callback"):
302
+ for state in self._state_ctx.all_states:
303
+ fsdp_param_group = state._fsdp_param_group
304
+ if (
305
+ fsdp_param_group
306
+ and fsdp_param_group._training_state != TrainingState.POST_BACKWARD
307
+ ):
308
+ # Run post-backward in case forward inputs did not require
309
+ # gradient so the autograd backward did not run
310
+ fsdp_param_group.post_backward()
311
+ state._training_state = TrainingState.IDLE
312
+ if fsdp_param_group:
313
+ fsdp_param_group._training_state = TrainingState.IDLE
314
+ if self._state_ctx.is_last_backward:
315
+ state._finalize_backward()
316
+ if self._state_ctx.is_last_backward:
317
+ self._comm_ctx.post_forward_order.clear()
318
+ if self._comm_ctx.reduce_scatter_state is not None:
319
+ self._device_handle.current_stream().wait_event(
320
+ self._comm_ctx.reduce_scatter_state.event
321
+ )
322
+ self._comm_ctx.reduce_scatter_state = None
323
+ self._state_ctx.post_backward_final_callback_queued = False
324
+
325
+ def _finalize_backward(self) -> None:
326
+ if self._modules_to_run_forward:
327
+ msg = (
328
+ f"{len(self._modules_to_run_forward)} of the {len(self._modules)} "
329
+ f"modules passed to fully_shard did not run forward before backward, "
330
+ "which is error-prone since FSDP post-forward/pre-backward logic "
331
+ "will not run for these modules. We recommend passing only modules "
332
+ "that run forward together. Modules that did not run forward: "
333
+ f"{list(self._modules_to_run_forward)}"
334
+ )
335
+ warning_once(logger, msg, stacklevel=2)
336
+ # Clear since we want the next forward to run
337
+ self._modules_to_run_forward.clear()
338
+ if self._fsdp_param_group:
339
+ self._fsdp_param_group.finalize_backward()
340
+
341
+ def _register_pre_backward_hook(self, output: Any) -> Any:
342
+ if not torch.is_grad_enabled():
343
+ return output
344
+ flat_outputs, _ = tree_flatten(output)
345
+ for t in flat_outputs:
346
+ if torch.is_tensor(t) and t.requires_grad:
347
+ t.register_hook(self._pre_backward)
348
+ return output
349
+
350
+ def _register_root_post_backward_final_callback(self):
351
+ if self._state_ctx.post_backward_final_callback_queued:
352
+ return
353
+ self._state_ctx.post_backward_final_callback_queued = True
354
+ Variable._execution_engine.queue_callback(
355
+ self._root_post_backward_final_callback
356
+ )
357
+
358
+
359
+ def _get_module_fsdp_state(module: nn.Module) -> Optional[FSDPState]:
360
+ state = _get_module_state(module)
361
+ if isinstance(state, FSDPState):
362
+ return state
363
+ return None
364
+
365
+
366
+ def _register_group_forward_hooks(
367
+ modules: Sequence[nn.Module],
368
+ pre_hook: Callable,
369
+ post_hook: Callable,
370
+ modules_to_run: set[nn.Module],
371
+ ):
372
+ """
373
+ Registers group forward pre and post-hooks. The pre-hook runs upon the
374
+ first module pre-forward, and the post-hook runs upon the last. If at least
375
+ one module does not run forward, then the post-hook does not run.
376
+ """
377
+ modules_set = set(modules)
378
+
379
+ @disable_if_config_true
380
+ @functools.wraps(pre_hook)
381
+ def wrapped_pre_hook(*args: Any, **kwargs: Any):
382
+ if len(modules_to_run) == 0: # first to run
383
+ modules_to_run.update(modules_set)
384
+ return pre_hook(*args, **kwargs)
385
+
386
+ @disable_if_config_true
387
+ def get_wrapped_post_hook(module: nn.Module):
388
+ @functools.wraps(post_hook)
389
+ def wrapped_post_hook(*args: Any, **kwargs: Any):
390
+ modules_to_run.discard(module)
391
+ if len(modules_to_run) == 0:
392
+ return post_hook(*args, **kwargs)
393
+
394
+ return wrapped_post_hook
395
+
396
+ pre_handles = [
397
+ module.register_forward_pre_hook(
398
+ wrapped_pre_hook, prepend=True, with_kwargs=True
399
+ )
400
+ for module in modules
401
+ ]
402
+ post_handles = [
403
+ module.register_forward_hook(
404
+ get_wrapped_post_hook(module), prepend=False, always_call=True
405
+ )
406
+ for module in modules
407
+ ]
408
+ return _MultiHandle(tuple(pre_handles + post_handles))
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_fully_shard/_fully_shard.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+
4
+ from __future__ import annotations
5
+
6
+ import functools
7
+ from contextlib import contextmanager
8
+ from typing import Any, cast, NoReturn, Optional, overload, TYPE_CHECKING, Union
9
+ from typing_extensions import deprecated
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from torch.distributed._composable import contract
14
+ from torch.distributed.utils import _get_root_modules
15
+
16
+ from ._fsdp_api import AllGather, MixedPrecisionPolicy, OffloadPolicy, ReduceScatter
17
+ from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo
18
+ from ._fsdp_init import (
19
+ _get_device_from_mesh,
20
+ _get_managed_modules,
21
+ _get_managed_states,
22
+ _get_post_forward_mesh_info,
23
+ _init_default_fully_shard_mesh,
24
+ _move_states_to_device,
25
+ )
26
+ from ._fsdp_param_group import FSDPParamGroup
27
+ from ._fsdp_state import _get_module_fsdp_state, FSDPState
28
+
29
+
30
+ if TYPE_CHECKING:
31
+ from collections.abc import Callable, Iterable, Iterator
32
+
33
+ from torch.distributed.tensor import DeviceMesh, Shard
34
+
35
+ __all__ = [
36
+ "fully_shard",
37
+ "FSDPModule",
38
+ "UnshardHandle",
39
+ "register_fsdp_forward_method",
40
+ "get_cls_to_fsdp_cls",
41
+ "disable_fsdp_module_new_init",
42
+ "share_comm_ctx",
43
+ ]
44
+
45
+
46
+ cls_to_fsdp_cls: dict[type, type] = {}
47
+
48
+
49
+ def get_cls_to_fsdp_cls() -> dict[type, type]:
50
+ return cls_to_fsdp_cls
51
+
52
+
53
+ @overload
54
+ # pyrefly: ignore [inconsistent-overload]
55
+ def fully_shard(
56
+ module: nn.Module,
57
+ *,
58
+ mesh: Optional[DeviceMesh] = ...,
59
+ reshard_after_forward: Union[bool, int] = ...,
60
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
61
+ mp_policy: MixedPrecisionPolicy = ...,
62
+ offload_policy: OffloadPolicy = ...,
63
+ ignored_params: Optional[set[nn.Parameter]] = ...,
64
+ ) -> FSDPModule: ...
65
+
66
+
67
+ @overload
68
+ # pyrefly: ignore [inconsistent-overload]
69
+ def fully_shard(
70
+ module: list[nn.Module],
71
+ *,
72
+ mesh: Optional[DeviceMesh] = ...,
73
+ reshard_after_forward: Union[bool, int] = ...,
74
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
75
+ mp_policy: MixedPrecisionPolicy = ...,
76
+ offload_policy: OffloadPolicy = ...,
77
+ ignored_params: Optional[set[nn.Parameter]] = ...,
78
+ ) -> list[FSDPModule]: ...
79
+
80
+
81
+ # The decorator adds a state object to `module` that can be accessed via
82
+ # `fully_shard.state(module)`. The state object and module are 1:1.
83
+ # [1] Python runtime decorator does not play well with static type checking
84
+ # so suppressing some type checks to support type overloads
85
+ # such that caller can still get correct return types based on input type
86
+ @contract(state_cls=FSDPState) # type: ignore[misc] # see [1]
87
+ def fully_shard(
88
+ module,
89
+ *,
90
+ mesh: Optional[DeviceMesh] = None,
91
+ reshard_after_forward: Optional[Union[bool, int]] = None,
92
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = None,
93
+ mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
94
+ offload_policy: OffloadPolicy = OffloadPolicy(),
95
+ ignored_params: Optional[set[nn.Parameter]] = None,
96
+ ):
97
+ """
98
+ Apply fully sharded data parallelism (FSDP) to ``module``, where FSDP
99
+ shards module parameters, gradients, and optimizer states across data
100
+ parallel workers to save memory at the cost of communication.
101
+
102
+ At initialization, FSDP shards the module's parameters across the data
103
+ parallel workers given by ``mesh``. Before forward, FSDP all-gathers the
104
+ sharded parameters across the data-parallel workers to get the unsharded
105
+ parameters for forward computation. If ``reshard_after_forward`` is
106
+ ``True``, then FSDP frees the unsharded parameters after forward and
107
+ re-all-gathers them in backward before gradient computation. After gradient
108
+ computation, FSDP frees the unsharded parameters and reduce-scatters the
109
+ unsharded gradients across data-parallel workers.
110
+
111
+ This implementation represents the sharded parameters as :class:`DTensor` s
112
+ sharded on dim-0, while the unsharded parameters will be like the original
113
+ parameters on ``module`` (e.g. :class:`torch.Tensor` if originally
114
+ :class:`torch.Tensor`). A module
115
+ `forward pre-hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_pre_hook>`_
116
+ on ``module`` all-gathers the parameters, and a module
117
+ `forward hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook>`_
118
+ on ``module`` frees them (if needed). Similar backward hooks all-gather
119
+ parameters and later free parameters and reduce-scatter gradients.
120
+
121
+ Since grouping multiple tensors together for one collective is critical for
122
+ communication efficiency, this implementation makes this grouping first
123
+ class. Calling :meth:`fully_shard` on ``module`` constructs one group that
124
+ includes the parameters in ``module.parameters()`` except those already
125
+ assigned to a group from an earlier call on a submodule. This means that
126
+ :meth:`fully_shard` should be called bottom-up on your model. Each group's
127
+ parameters are all-gathered in one collective, and its gradients are
128
+ reduce-scattered in one collective. Partitioning the model into multiple
129
+ groups ("layer by layer") allows for peak memory savings and communication/computation
130
+ overlap. Users generally should *not* call :meth:`fully_shard` only on the
131
+ topmost root module.
132
+
133
+ Args:
134
+ module (Union[nn.Module, List[nn.Module]): The module or modules to
135
+ shard with FSDP and group together for communication.
136
+ mesh (Optional[DeviceMesh]): This data parallel mesh defines the
137
+ sharding and device. If 1D, then parameters are fully sharded
138
+ across the 1D mesh (FSDP) with ``(Shard(0),)`` placement. If 2D,
139
+ then parameters are sharded across the 1st dim and replicated
140
+ across the 0th dim (HSDP) with ``(Replicate(), Shard(0))``
141
+ placement. The mesh's device type gives the device type used for
142
+ communication; if a CUDA or CUDA-like device type, then we use the
143
+ current device.
144
+ reshard_after_forward (Optional[Union[bool, int]]): This controls the parameter
145
+ behavior after forward and can trade off memory and communication:
146
+
147
+ - If ``True``, then this reshards parameters after forward and
148
+ re-all-gathers in backward.
149
+ - If ``False``, then this keeps the unsharded parameters in memory
150
+ after forward and avoids the all-gather in backward. For best performance,
151
+ we usually set ``False`` for the root module, because the root module
152
+ is typically required immediately when the backward pass begins.
153
+ - If ``None``, it is set to ``True`` for non-root modules and ``False``
154
+ for root modules.
155
+ - If an ``int``, then this represents the world size to reshard to
156
+ after forward. It should be a non-trivial divisor of the ``mesh``
157
+ shard dim size (i.e. excluding 1 and the dim size itself). A
158
+ choice may be the intra-node size (e.g. ``torch.cuda.device_count()``).
159
+ This allows the all-gather in backward to be over a smaller world
160
+ size at the cost of higher memory usage than setting to ``True``.
161
+ - After forward, the parameters registered to the module depend on
162
+ to this: The registered parameters are the sharded parameters if
163
+ ``True``; unsharded parameters if ``False``; and the parameters
164
+ resharded to the smaller mesh otherwise. To modify the parameters
165
+ between forward and backward, the registered parameters must be
166
+ the sharded parameters. For ``False`` or an ``int``, this can be
167
+ done by manually resharding via :meth:`reshard`.
168
+ shard_placement_fn (Optional[Callable[[nn.Parameter], Optional[Shard]]]):
169
+ This callable can be used to override the sharding placement for a
170
+ parameter to shard a parameter on a dimension other than dim-0. If
171
+ this callable returns a :class:`Shard` placement (not ``None``),
172
+ then FSDP will shard according to that placement (e.g. ``Shard(1)``).
173
+ If sharding on a nonzero dim, we currently require even sharding,
174
+ i.e. the tensor dim size on that dim must be divisible by the FSDP
175
+ shard mesh size.
176
+ mp_policy (MixedPrecisionPolicy): This controls the mixed precision
177
+ policy, which offers parameter/reduction mixed precision for this
178
+ module. See :class:`MixedPrecisionPolicy` for details.
179
+ offload_policy (OffloadPolicy): This controls the offloading policy,
180
+ which offers parameter/gradient/optimizer state offloading. See
181
+ :class:`OffloadPolicy` and its subclasses for details.
182
+ ignored_params: Optional(Set[nn.Parameter]): The set of parameters to be
183
+ ignored by FSDP. They will not be sharded, nor moved to the device
184
+ during init, nor have their gradients reduced in backward.
185
+
186
+ Returns:
187
+ FSDPModule: The module with FSDP applied (in-place).
188
+ """
189
+ torch._C._log_api_usage_once("torch.distributed.fsdp.fully_shard")
190
+ if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
191
+ raise ValueError(
192
+ f"fully_shard does not support containers that do not implement forward: {module}"
193
+ )
194
+ mesh = mesh or _init_default_fully_shard_mesh()
195
+ if mesh.ndim not in (1, 2):
196
+ raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}")
197
+ elif mesh.ndim == 1:
198
+ mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0)
199
+ else:
200
+ if mesh.mesh_dim_names is None:
201
+ raise AssertionError(
202
+ "Please init the 2D mesh for HSDP with mesh_dim_names specified"
203
+ )
204
+ mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0)
205
+ device = _get_device_from_mesh(mesh)
206
+ auto_reshard_after_forward = reshard_after_forward is None
207
+ # If the user does not provide ``reshard_after_forward``, we set it to True.
208
+ # During lazy_init, we identify which module is the root and override its value to False
209
+ post_forward_mesh_info = _get_post_forward_mesh_info(
210
+ reshard_after_forward if not auto_reshard_after_forward else True, # type: ignore[arg-type]
211
+ mesh_info,
212
+ )
213
+
214
+ arg_module = module
215
+ modules = (
216
+ (module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
217
+ )
218
+ state = fully_shard.state(modules[0]) # type: ignore[attr-defined] # see [1]
219
+ state.init(modules, device, mp_policy, auto_reshard_after_forward)
220
+
221
+ managed_modules = _get_managed_modules(modules, ignored_params)
222
+ params, buffers = _get_managed_states(managed_modules, ignored_params)
223
+
224
+ _move_states_to_device(params, buffers, device)
225
+ if params:
226
+ state._fsdp_param_group = FSDPParamGroup(
227
+ params,
228
+ modules,
229
+ mesh_info,
230
+ post_forward_mesh_info,
231
+ device,
232
+ shard_placement_fn,
233
+ mp_policy,
234
+ offload_policy,
235
+ )
236
+
237
+ # For Dynamo
238
+ for managed_module in managed_modules:
239
+ managed_module._is_fsdp_managed_module = True # type: ignore[assignment]
240
+ managed_module._fsdp_use_orig_params = True # type: ignore[assignment]
241
+
242
+ # Place FSDP leftmost for highest priority in the method resolution order
243
+ for module in modules:
244
+ cls = module.__class__
245
+ new_cls = cls_to_fsdp_cls.get(cls)
246
+ if not new_cls:
247
+ dct = {"__deepcopy__": _unimplemented_deepcopy}
248
+ new_cls = type(f"FSDP{cls.__name__}", (FSDPModule, cls), dct)
249
+ cls_to_fsdp_cls[cls] = new_cls
250
+ module.__class__ = new_cls
251
+ return arg_module
252
+
253
+
254
+ def _unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
255
+ raise AssertionError(
256
+ "FSDP does not support deepcopy. Please use state dict for serialization."
257
+ )
258
+
259
+
260
+ _enable_fsdp_module_new_init: bool = True
261
+
262
+
263
+ @contextmanager
264
+ def disable_fsdp_module_new_init() -> Iterator[None]:
265
+ global _enable_fsdp_module_new_init
266
+ prev, _enable_fsdp_module_new_init = _enable_fsdp_module_new_init, False
267
+ try:
268
+ yield
269
+ finally:
270
+ _enable_fsdp_module_new_init = prev
271
+
272
+
273
+ class FSDPModule:
274
+ def __new__(cls, *args, **kwargs):
275
+ """
276
+ Override ``__new__`` to remove the FSDP class and directly construct
277
+ the original class for cases like indexing into a container module.
278
+ """
279
+ # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
280
+ # and index 1 is the `FSDPModule` class itself
281
+ orig_cls = cls.__mro__[2]
282
+ self = orig_cls.__new__(orig_cls, *args, **kwargs)
283
+ if _enable_fsdp_module_new_init:
284
+ self.__init__(*args, **kwargs)
285
+ return self
286
+
287
+ def reshard(self) -> None:
288
+ """
289
+ Reshards the module's parameters, freeing the unsharded parameters if
290
+ they are allocated and registering the sharded parameters to the
291
+ module. This method is *not* recursive.
292
+ """
293
+ state = self._get_fsdp_state()
294
+ if fsdp_param_group := state._fsdp_param_group:
295
+ fsdp_param_group.reshard()
296
+
297
+ def unshard(self, async_op: bool = False) -> Optional[UnshardHandle]:
298
+ """
299
+ Unshards the module's parameters by allocating memory and all-gathering
300
+ the parameters. This method is *not* recursive. The unshard follows the
301
+ :class:`MixedPrecisionPolicy`, so it will all-gather following
302
+ ``param_dtype`` if set.
303
+
304
+ Args:
305
+ async_op (bool): If ``True``, then returns a :class:`UnshardHandle`
306
+ that has a :meth:`wait` method to wait on the unshard op. If
307
+ ``False``, then returns ``None`` and waits on the handle inside
308
+ this function.
309
+
310
+ .. note:: If ``async_op=True``, then FSDP will wait on the pending
311
+ unshard in the module's pre-forward for the user. The user only
312
+ needs to call :meth:`wait` explicitly if the wait should happen
313
+ before pre-forward.
314
+ """
315
+ state = self._get_fsdp_state()
316
+ fsdp_param_group = state._fsdp_param_group
317
+ if fsdp_param_group is not None:
318
+ fsdp_param_group.lazy_init()
319
+ fsdp_param_group.unshard(async_op=async_op)
320
+ handle = _UnshardHandleImpl(fsdp_param_group)
321
+ if async_op:
322
+ return handle
323
+ handle.wait()
324
+ return None
325
+
326
+ def set_is_last_backward(self, is_last_backward: bool) -> None:
327
+ """
328
+ Sets whether the next backward is the last one. On the last backward,
329
+ FSDP waits on pending gradient reduction and clears internal data
330
+ data structures for backward prefetching. This can be useful for
331
+ microbatching.
332
+ """
333
+ state = self._get_fsdp_state()
334
+ state._state_ctx.is_last_backward = is_last_backward
335
+
336
+ def set_requires_gradient_sync(
337
+ self, requires_gradient_sync: bool, *, recurse: bool = True
338
+ ) -> None:
339
+ """
340
+ Sets if the module should sync gradients. This can be used to implement
341
+ gradient accumulation *without communication*. For HSDP, this controls
342
+ both reduce-scatter and all-reduce together. This is the equivalence of
343
+ `no_sync` in FSDP1.
344
+
345
+ Args:
346
+ requires_gradient_sync (bool): Whether to reduce gradients for the
347
+ module's parameters.
348
+ recurse (bool): Whether to set for all FSDP submodules or just the
349
+ passed-in module.
350
+ """
351
+ self_module = cast(nn.Module, self)
352
+ modules = list(self_module.modules()) if recurse else [self_module]
353
+ for module in modules:
354
+ if isinstance(module, FSDPModule):
355
+ state = module._get_fsdp_state()
356
+ if fsdp_param_group := state._fsdp_param_group:
357
+ fsdp_param_group.reduce_grads = requires_gradient_sync
358
+ fsdp_param_group.all_reduce_grads = requires_gradient_sync
359
+
360
+ def set_requires_all_reduce(
361
+ self, requires_all_reduce: bool, *, recurse: bool = True
362
+ ) -> None:
363
+ """
364
+ Sets if the module should all-reduce gradients. This can be used to
365
+ implement gradient accumulation with only reduce-scatter but not
366
+ all-reduce for HSDP.
367
+ """
368
+ self_module = cast(nn.Module, self)
369
+ modules = list(self_module.modules()) if recurse else [self_module]
370
+ for module in modules:
371
+ if isinstance(module, FSDPModule):
372
+ state = module._get_fsdp_state()
373
+ if fsdp_param_group := state._fsdp_param_group:
374
+ fsdp_param_group.all_reduce_grads = requires_all_reduce
375
+
376
+ def set_reshard_after_forward(
377
+ self, reshard_after_forward: bool, recurse: bool = True
378
+ ) -> None:
379
+ """
380
+ Sets if the module should reshard parameters after forward. This can be
381
+ used to change the ``reshard_after_forward`` FSDP arg at runtime. For
382
+ example, this can be used to set the FSDP root module's value to
383
+ ``True`` (since it is otherwise specially set to ``False``), or it can
384
+ set an FSDP module's value to ``False`` for running evals and set back
385
+ to ``True`` for training.
386
+
387
+ Args:
388
+ reshard_after_forward (bool): Whether to reshard parameters after
389
+ forward.
390
+ recurse (bool): Whether to set for all FSDP submodules or just the
391
+ passed-in module.
392
+ """
393
+ if not isinstance(reshard_after_forward, bool):
394
+ raise ValueError(
395
+ f"reshard_after_forward should be a bool, got {type(reshard_after_forward)}"
396
+ )
397
+ self_module = cast(nn.Module, self)
398
+ modules = list(self_module.modules()) if recurse else [self_module]
399
+ for module in modules:
400
+ if isinstance(module, FSDPModule):
401
+ state = module._get_fsdp_state()
402
+ state._auto_reshard_after_forward = False
403
+ if fsdp_param_group := state._fsdp_param_group:
404
+ fsdp_param_group.post_forward_mesh_info = (
405
+ _get_post_forward_mesh_info(
406
+ reshard_after_forward, fsdp_param_group.mesh_info
407
+ )
408
+ )
409
+
410
+ def set_reshard_after_backward(
411
+ self, reshard_after_backward: bool, *, recurse: bool = True
412
+ ) -> None:
413
+ """
414
+ Sets if the module should reshard parameters after backward. This can
415
+ be used during gradient accumulation to trade off higher memory for
416
+ reduced communication since the unsharded parameters do not need to be
417
+ re-all-gathered before the next forward.
418
+
419
+ Args:
420
+ reshard_after_backward (bool): Whether to reshard parameters after
421
+ backward.
422
+ recurse (bool): Whether to set for all FSDP submodules or just the
423
+ passed-in module.
424
+ """
425
+ self_module = cast(nn.Module, self)
426
+ modules = list(self_module.modules()) if recurse else [self_module]
427
+ for module in modules:
428
+ if isinstance(module, FSDPModule):
429
+ state = module._get_fsdp_state()
430
+ if fsdp_param_group := state._fsdp_param_group:
431
+ fsdp_param_group.reshard_after_backward = reshard_after_backward
432
+
433
+ def set_modules_to_forward_prefetch(self, modules: list[FSDPModule]) -> None:
434
+ """
435
+ Sets the FSDP modules for which this FSDP module should explicitly
436
+ prefetch all-gathers in forward. The prefetching runs after this
437
+ module's all-gather copy-out.
438
+
439
+ Passing a singleton list containing the next FSDP module gives the same
440
+ all-gather overlap behavior as the default overlap behavior, except the
441
+ prefetched all-gather is issued earlier from the CPU. Passing a list
442
+ with at least length two is required for more aggressive overlap and
443
+ will use more reserved memory.
444
+
445
+ Args:
446
+ modules (List[FSDPModule]): FSDP modules to prefetch.
447
+ """
448
+ _assert_all_fsdp_modules(modules)
449
+ self._get_fsdp_state()._states_to_forward_prefetch = [
450
+ module._get_fsdp_state() for module in modules
451
+ ]
452
+
453
+ def set_modules_to_backward_prefetch(self, modules: list[FSDPModule]) -> None:
454
+ """
455
+ Sets the FSDP modules for which this FSDP module should explicitly
456
+ prefetch all-gathers in backward. This overrides the default backward
457
+ pretching implementation that prefetches the next FSDP module based on
458
+ the reverse post-forward order.
459
+
460
+ Passing a singleton list containing the previous FSDP module gives the
461
+ same all-gather overlap behavior as the default overlap behavior.
462
+ Passing a list with at least length two is required for more aggressive
463
+ overlap and will use more reserved memory.
464
+
465
+ Args:
466
+ modules (List[FSDPModule]): FSDP modules to prefetch.
467
+ """
468
+ _assert_all_fsdp_modules(modules)
469
+ self._get_fsdp_state()._states_to_backward_prefetch = [
470
+ module._get_fsdp_state() for module in modules
471
+ ]
472
+
473
+ def set_custom_all_gather(self, comm: AllGather) -> None:
474
+ """
475
+ Overrides the default ``all_gather`` communication behavior,
476
+ to have better control over the communication and memory usage.
477
+ See `Comm` and `ReduceScatter` for details.
478
+
479
+ Args:
480
+ comm (AllGather): Custom all-gather communication.
481
+ """
482
+ state = self._get_fsdp_state()
483
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
484
+ fsdp_param_group._all_gather_comm = comm
485
+
486
+ def set_custom_reduce_scatter(self, comm: ReduceScatter) -> None:
487
+ """
488
+ Overrides the default ``reduce_scatter`` communication behavior,
489
+ to have better control over the communication and memory usage.
490
+ See `Comm` and `ReduceScatter` for details.
491
+
492
+ Args:
493
+ comm (ReduceScatter): Custom reduce_scatter communication.
494
+ """
495
+ state = self._get_fsdp_state()
496
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
497
+ fsdp_param_group._reduce_scatter_comm = comm
498
+
499
+ def set_all_reduce_hook(
500
+ self,
501
+ hook: Callable[[torch.Tensor], None],
502
+ *,
503
+ stream: Optional[torch.cuda.Stream] = None,
504
+ ):
505
+ """
506
+ Args:
507
+ hook (Callable[[torch.Tensor], None]): User-defined all-reduce hook
508
+ with expected signature ``hook(reduce_output: torch.Tensor) -> None``
509
+ where ``reduce_output`` is the reduce-scatter output if only
510
+ using FSDP or the all-reduce output if using native HSDP.
511
+ stream (Optional[torch.cuda.Stream]): Stream to run the all-reduce
512
+ hook in. This should only be set if not using native HSDP. If
513
+ using native HSDP, the hook will run in the internally defined
514
+ all-reduce stream used by the native HSDP all-reduce.
515
+ """
516
+ state = self._get_fsdp_state()
517
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
518
+ fsdp_param_group._all_reduce_hook = hook
519
+ if stream is not None:
520
+ if fsdp_param_group._is_hsdp:
521
+ raise ValueError("stream cannot be set when using native HSDP")
522
+ fsdp_param_group._all_reduce_hook_stream = stream
523
+
524
+ def set_post_optim_event(self, event: torch.Event) -> None:
525
+ """
526
+ Sets a post-optimizer-step event for the root FSDP module to wait the
527
+ all-gather streams on.
528
+
529
+ By default, the root FSDP module waits the all-gather streams on the
530
+ current stream to ensure that the optimizer step has finished before
531
+ all-gathering. However, this may introduce false dependencies if
532
+ there is unrelated computation after the optimizer step. This API
533
+ allows the user to provide their own event to wait on. After the root
534
+ waits on the event, the event is discarded, so this API should be
535
+ called with a new event each iteration.
536
+
537
+ Args:
538
+ event (torch.Event): Event recorded after the optimizer step
539
+ to wait all-gather streams on.
540
+ """
541
+ self._get_fsdp_state()._state_ctx.post_optim_event = event
542
+
543
+ @deprecated("Use `set_gradient_divide_factor` instead")
544
+ def set_reduce_scatter_divide_factor(self, factor: float) -> None:
545
+ """Use :py:meth:`set_gradient_divide_factor` instead"""
546
+ self.set_gradient_divide_factor(factor)
547
+
548
+ def set_gradient_divide_factor(self, factor: float) -> None:
549
+ """
550
+ Sets a custom divide factor for the gradient reduction. This might use
551
+ a custom reduce op using NCCL's PreMulSum, which allows multiplying by
552
+ the factor before reduction.
553
+
554
+ Args:
555
+ factor (float): Custom divide factor.
556
+ """
557
+ state = self._get_fsdp_state()
558
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
559
+ fsdp_param_group.gradient_divide_factor = factor
560
+
561
+ def set_force_sum_reduction_for_comms(self, enable: bool) -> None:
562
+ """
563
+ Sets whether to require the low-level collective communication
564
+ primitives to exclusively use "sum"-type reductions, even if it comes
565
+ at the cost of separate additional pre- or post-scaling operations.
566
+ This is needed for example because NCCL currently supports zero-copy
567
+ transfers only for this kind of collectives.
568
+
569
+ NB: for MTIA devices, this is always implicitly enabled.
570
+
571
+ NB: if `set_all_reduce_hook` is used under FSDP setup, the caller needs
572
+ to ensure the custom all-reduce across FSDP units follow this strategy
573
+ as well, as FSDP can no longer automatically handle that.
574
+
575
+ Args:
576
+ enable (bool): Whether to only ever use ReduceOp.SUM for comms.
577
+ """
578
+ state = self._get_fsdp_state()
579
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
580
+ fsdp_param_group.force_sum_reduction_for_comms = enable
581
+
582
+ def set_unshard_in_backward(self, unshard_in_backward: bool) -> None:
583
+ """
584
+ Sets whether the FSDP module's parameters need to be unsharded in
585
+ backward. This can be used in expert cases when the user knows that all
586
+ parameters in this FSDP module's parameter group are not needed for
587
+ backward computation (e.g. embedding).
588
+ """
589
+ state = self._get_fsdp_state()
590
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
591
+ fsdp_param_group.unshard_in_backward = unshard_in_backward
592
+
593
+ def set_allocate_memory_from_process_group_for_comm(self, enable: bool) -> None:
594
+ """
595
+ Sets whether the temporary staging buffers used to send and receive data
596
+ over collective communications should be allocated using the custom
597
+ optimized allocator provided by the ProcessGroup itself (if any). This
598
+ might allow the ProcessGroup to be more efficient. For example, when
599
+ using NCCL, this enables it to leverage zero-copy transfers over SHARP
600
+ (for NVLink and/or InfiniBand).
601
+
602
+ This cannot be used together with :meth:`set_custom_all_gather` or
603
+ :meth:`set_custom_reduce_scatter` as those APIs allow for
604
+ finer-grained control over each communication, and this method cannot
605
+ determine their staging buffer allocation strategy.
606
+
607
+ Args:
608
+ enable (bool): Whether to turn on ProcessGroup allocation.
609
+ """
610
+ state = self._get_fsdp_state()
611
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
612
+ fsdp_param_group.set_allocate_memory_from_process_group(enable)
613
+
614
+ def _set_unshard_async_op(self, async_op: bool):
615
+ """
616
+ Sets whether to use ``async_op=True`` or ``False`` for the pre-forward
617
+ and pre-backward unshard op. This defaults to ``False`` but can be set
618
+ to ``True`` with this method.
619
+
620
+ Setting this to ``True`` allows the all-gather allocations to happen in
621
+ the default stream, avoiding inter-stream memory fragmentation.
622
+ However, you must use explicit prefetching (e.g. via :meth:`unshard`)
623
+ in forward to still get overlap, and the pre-all-gather ops like dtype
624
+ casting and copy-in will not overlap with compute.
625
+ """
626
+ self_module = cast(nn.Module, self)
627
+ for module in self_module.modules():
628
+ if isinstance(module, FSDPModule):
629
+ state = module._get_fsdp_state()
630
+ if fsdp_param_group := state._fsdp_param_group:
631
+ fsdp_param_group.unshard_async_op = async_op
632
+
633
+ def _get_fsdp_state(self) -> FSDPState:
634
+ if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None:
635
+ raise AssertionError(f"No FSDP state found on {self}")
636
+ return state
637
+
638
+ def _apply(self, *args: Any, **kwargs: Any) -> Any:
639
+ # Reshard to ensure that sharded parameters are registered
640
+ self.reshard()
641
+ ret = super()._apply(*args, **kwargs) # type: ignore[misc]
642
+ state = self._get_fsdp_state()
643
+ if not (fsdp_param_group := state._fsdp_param_group):
644
+ return ret
645
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
646
+ # https://github.com/pytorch/pytorch/issues/113045
647
+ with torch.no_grad():
648
+ for fsdp_param in fsdp_param_group.fsdp_params:
649
+ fsdp_param.reset_sharded_param()
650
+ return ret
651
+
652
+
653
+ class UnshardHandle:
654
+ """
655
+ A handle to wait on a :meth:`FSDPModule.unshard` op.
656
+ """
657
+
658
+ def wait(self) -> None:
659
+ """
660
+ Waits on the unshard op. This ensures that the current stream can use
661
+ the unsharded parameters, which are now registered to the module.
662
+ """
663
+ return
664
+
665
+
666
+ class _UnshardHandleImpl(UnshardHandle):
667
+ def __init__(self, fsdp_param_group: Optional[FSDPParamGroup]):
668
+ self._fsdp_param_group = fsdp_param_group
669
+
670
+ def wait(self):
671
+ if self._fsdp_param_group is not None:
672
+ self._fsdp_param_group.wait_for_unshard()
673
+ # Avoid keeping a reference
674
+ self._fsdp_param_group = None
675
+
676
+
677
+ def register_fsdp_forward_method(module: nn.Module, method_name: str) -> None:
678
+ """
679
+ Registers a method on ``module`` to be considered a forward method for
680
+ FSDP.
681
+
682
+ FSDP all-gathers parameters pre-forward and optionally frees parameters
683
+ post-forward (depending on ``reshard_after_forward``). FSDP only knows to
684
+ do this for :meth:`nn.Module.forward` by default. This function patches a
685
+ user-specified method to run the pre/post-forward hooks before/after the
686
+ method, respectively. If ``module`` is not an :class:`FSDPModule`, then
687
+ this is a no-op.
688
+
689
+ Args:
690
+ module (nn.Module): Module to register the forward method on.
691
+ method_name (str): Name of the forward method.
692
+ """
693
+ if not isinstance(module, FSDPModule):
694
+ # Make no-op to allow including both when using/not using FSDP
695
+ return
696
+ if not hasattr(module, method_name):
697
+ raise ValueError(f"{type(module)} does not have a method {method_name}")
698
+ orig_method = getattr(module, method_name)
699
+
700
+ @functools.wraps(orig_method)
701
+ def wrapped_method(self, *args, **kwargs):
702
+ fsdp_state = self._get_fsdp_state()
703
+ args, kwargs = fsdp_state._pre_forward(self, args, kwargs)
704
+ out = orig_method(*args, **kwargs)
705
+ return fsdp_state._post_forward(self, args, out)
706
+
707
+ # Use `__get__` to make `wrapped_method` an instance method
708
+ setattr(
709
+ module,
710
+ method_name,
711
+ wrapped_method.__get__(module, type(module)), # type:ignore[attr-defined]
712
+ )
713
+
714
+
715
+ def share_comm_ctx(modules: list[FSDPModule]) -> None:
716
+ """
717
+ Share cuda streams for multiple FSDPModules
718
+
719
+ Example usage:
720
+ from torch.distributed.fsdp import share_comm_ctx
721
+ share_comm_ctx([fsdp_model_1, fsdp_model_2, ...])
722
+
723
+ For Pipeline Parallelism (PP), each model chunk is a FSDP root. We want
724
+ to share cuda streams for all-gather, reduce-scatter, and all-reduce.
725
+ This avoids allocating inter-stream memory framgmentation
726
+
727
+ Args:
728
+ modules (List[FSDPModule]): modules to share cuda streams
729
+ """
730
+ if len(modules) == 0:
731
+ return
732
+ for module in modules:
733
+ if not isinstance(module, FSDPModule):
734
+ raise ValueError(f"Expects list of FSDPModules but got {module}")
735
+ fsdp_states = [module._get_fsdp_state() for module in modules]
736
+ comm_ctx = fsdp_states[0]._comm_ctx
737
+ for fsdp_state in fsdp_states[1:]:
738
+ fsdp_state._comm_ctx = comm_ctx
739
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
740
+ fsdp_param_group.comm_ctx = comm_ctx
741
+
742
+
743
+ def _assert_all_fsdp_modules(modules: Iterable[Any]) -> None:
744
+ for module in modules:
745
+ if not isinstance(module, FSDPModule):
746
+ raise ValueError(f"Expects FSDPModule but got {type(module)}: {module}")
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_init_utils.py ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import itertools
4
+ import os
5
+ import warnings
6
+ from collections.abc import Callable, Generator, Iterable, Iterator
7
+ from typing import Any, no_type_check, Optional, TYPE_CHECKING, Union
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.fsdp._exec_order_utils as exec_order_utils
12
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
13
+ import torch.distributed.fsdp.fully_sharded_data_parallel as fsdp_file
14
+ import torch.nn as nn
15
+ from torch.distributed.algorithms._comm_hooks import default_hooks
16
+ from torch.distributed.device_mesh import DeviceMesh
17
+ from torch.distributed.distributed_c10d import _get_default_group
18
+ from torch.distributed.fsdp._common_utils import (
19
+ _FSDPDeviceHandle,
20
+ _FSDPState,
21
+ _get_module_fsdp_state,
22
+ _is_fsdp_flattened,
23
+ _named_parameters_with_duplicates,
24
+ clean_tensor_name,
25
+ TrainingState,
26
+ )
27
+ from torch.distributed.fsdp._flat_param import (
28
+ _FSDP_USE_FULL_PREC_IN_EVAL,
29
+ FlatParameter,
30
+ FlatParamHandle,
31
+ HandleShardingStrategy,
32
+ )
33
+ from torch.distributed.fsdp._limiter_utils import _FreeEventQueue
34
+ from torch.distributed.fsdp.api import (
35
+ BackwardPrefetch,
36
+ CPUOffload,
37
+ FullOptimStateDictConfig,
38
+ FullStateDictConfig,
39
+ MixedPrecision,
40
+ ShardingStrategy,
41
+ StateDictConfig,
42
+ StateDictType,
43
+ )
44
+ from torch.distributed.fsdp.wrap import _Policy
45
+ from torch.distributed.tensor.parallel.fsdp import DTensorExtensions
46
+ from torch.distributed.utils import _sync_params_and_buffers
47
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
48
+
49
+
50
+ if TYPE_CHECKING:
51
+ from torch.utils.hooks import RemovableHandle
52
+
53
+ _TORCHDISTX_AVAIL = True
54
+ try:
55
+ from torchdistx import deferred_init, fake # type: ignore[import]
56
+ except ImportError:
57
+ _TORCHDISTX_AVAIL = False
58
+
59
+ PARAM_BROADCAST_BUCKET_SIZE = 250 * 1024 * 1024
60
+ FSDP_SYNCED = "_fsdp_synced"
61
+ # Specification of process groups for hybrid sharding strategies.
62
+ HybridShardProcessGroupType = tuple[dist.ProcessGroup, dist.ProcessGroup]
63
+ # Overall specification of process group.
64
+ ProcessGroupType = Optional[Union[dist.ProcessGroup, HybridShardProcessGroupType]]
65
+
66
+
67
+ # TODO (awgu): Refactor this later
68
+ SHARDING_STRATEGY_MAP = {
69
+ ShardingStrategy.NO_SHARD: HandleShardingStrategy.NO_SHARD,
70
+ ShardingStrategy.FULL_SHARD: HandleShardingStrategy.FULL_SHARD,
71
+ ShardingStrategy.SHARD_GRAD_OP: HandleShardingStrategy.SHARD_GRAD_OP,
72
+ ShardingStrategy.HYBRID_SHARD: HandleShardingStrategy.HYBRID_SHARD,
73
+ ShardingStrategy._HYBRID_SHARD_ZERO2: HandleShardingStrategy._HYBRID_SHARD_ZERO2,
74
+ }
75
+ HYBRID_SHARDING_STRATEGIES = [
76
+ ShardingStrategy.HYBRID_SHARD,
77
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
78
+ ]
79
+ NO_RESHARD_AFTER_FORWARD_STRATEGIES = (
80
+ ShardingStrategy.SHARD_GRAD_OP,
81
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
82
+ )
83
+
84
+
85
+ # NOTE: Since non-self attributes cannot be type annotated, several attributes
86
+ # on `state` are defined first as local variables before being assigned.
87
+
88
+
89
+ @no_type_check
90
+ def _init_process_group_state(
91
+ state: _FSDPState,
92
+ process_group: ProcessGroupType,
93
+ sharding_strategy: ShardingStrategy,
94
+ policy: Optional[_Policy],
95
+ device_mesh: Optional[DeviceMesh] = None,
96
+ ) -> _FSDPState:
97
+ if process_group is not None and device_mesh is not None:
98
+ raise ValueError(
99
+ "Cannot pass both process_group and device_mesh at the "
100
+ "same time. Please just pass only one of them."
101
+ )
102
+ is_hybrid_strategy = sharding_strategy in HYBRID_SHARDING_STRATEGIES
103
+ if is_hybrid_strategy:
104
+ if process_group is None and policy is None and device_mesh is None:
105
+ # Raise an error here, since this is manual wrapping with no process group
106
+ # passed in, there is no way to ensure all wrapped FSDP instances use the same
107
+ # process groups.
108
+ raise ValueError(
109
+ f"Manual wrapping with {sharding_strategy} "
110
+ "requires explicit specification of process group or device_mesh."
111
+ )
112
+ else:
113
+ state = _init_process_group_state_for_hybrid_shard(
114
+ state, process_group, device_mesh
115
+ )
116
+ else:
117
+ if device_mesh:
118
+ state._device_mesh = device_mesh
119
+ state.process_group = device_mesh.get_group(mesh_dim=0)
120
+ else:
121
+ state.process_group = (
122
+ process_group if process_group is not None else _get_default_group()
123
+ )
124
+
125
+ state.rank = state.process_group.rank()
126
+ state.world_size = state.process_group.size()
127
+ data_parallel_world_size = state.world_size
128
+ if is_hybrid_strategy:
129
+ data_parallel_world_size *= state._inter_node_pg.size()
130
+ state._gradient_predivide_factor = (
131
+ default_hooks.DefaultState._get_gradient_predivide_factor(
132
+ data_parallel_world_size
133
+ )
134
+ )
135
+ state._gradient_postdivide_factor = (
136
+ data_parallel_world_size / state._gradient_predivide_factor
137
+ )
138
+ return state
139
+
140
+
141
+ @no_type_check
142
+ def _init_process_group_state_for_hybrid_shard(
143
+ state: _FSDPState,
144
+ process_group: ProcessGroupType,
145
+ device_mesh: DeviceMesh,
146
+ ) -> _FSDPState:
147
+ if device_mesh:
148
+ if _is_valid_hybrid_shard_device_mesh(device_mesh):
149
+ state._device_mesh = device_mesh
150
+ # We currently only allow _inter_node_pg to be the outermost dimension, and the
151
+ # process_group(intra_node) to be the innermost dimension.
152
+ state._inter_node_pg = device_mesh.get_group(mesh_dim=0)
153
+ state.process_group = device_mesh.get_group(mesh_dim=1)
154
+ else:
155
+ raise ValueError(
156
+ f"Expected device_mesh to have ndim=2 but got {device_mesh.ndim}"
157
+ )
158
+ elif process_group is None:
159
+ default_group = _get_default_group()
160
+ intra_node_group, inter_node_group = _init_intra_and_inter_node_groups(
161
+ default_group, state._device_handle.device_count()
162
+ )
163
+ # we shard across intra-node
164
+ state.process_group = intra_node_group
165
+ # save _inter_node_pg to allreduce across.
166
+ state._inter_node_pg = inter_node_group
167
+ else:
168
+ # Check type and assign state.process_group and state._inter_node_pg.
169
+ if _is_valid_hybrid_shard_pg_type(process_group):
170
+ # Assuming that user passed in as intra node group and inter node group
171
+ # as documented.
172
+ state.process_group, state._inter_node_pg = process_group
173
+ else:
174
+ raise ValueError(
175
+ "Expected process_group to be passed in as either None or "
176
+ f"Tuple[dist.ProcessGroup, dist.ProcessGroup] but got {type(process_group)}"
177
+ )
178
+ # Create state for allreduce
179
+ state._inter_node_state = _get_default_comm_hook_state(
180
+ process_group=state._inter_node_pg,
181
+ )
182
+ return state
183
+
184
+
185
+ @no_type_check
186
+ def _is_valid_hybrid_shard_pg_type(process_group: Any) -> bool:
187
+ return (
188
+ isinstance(process_group, tuple)
189
+ and len(process_group) == 2
190
+ and all(isinstance(pg, dist.ProcessGroup) for pg in process_group)
191
+ )
192
+
193
+
194
+ @no_type_check
195
+ def _is_valid_hybrid_shard_device_mesh(device_mesh: DeviceMesh) -> bool:
196
+ return isinstance(device_mesh, DeviceMesh) and device_mesh.ndim == 2
197
+
198
+
199
+ @no_type_check
200
+ def _init_intra_node_process_group(num_devices_per_node: int) -> dist.ProcessGroup:
201
+ """
202
+ Return a process group across the current node.
203
+
204
+ For example, given each row is a distinct node:
205
+ 0 1 2 3 4 5 6 7
206
+ 8 9 10 11 12 13 14 15
207
+ This API would return an intra-node subgroup across
208
+ [0, 1, ..., 7] or [8, 9, ..., 15] depending on the process's rank.
209
+ For example, rank 3 would get [0, 1, ..., 7].
210
+ """
211
+ intra_node_subgroup, _ = dist.new_subgroups(num_devices_per_node)
212
+ return intra_node_subgroup
213
+
214
+
215
+ @no_type_check
216
+ def _init_inter_node_process_group(
217
+ global_process_group: dist.ProcessGroup,
218
+ num_devices_per_node: int,
219
+ ) -> dist.ProcessGroup:
220
+ """
221
+ Return an inter-node process group where each contained rank has the same local rank.
222
+
223
+ For example, given each row is a distinct node:
224
+ 0 1 2 3 4 5 6 7
225
+ 8 9 10 11 12 13 14 15
226
+ This API would return inter-node process group [0, 8], [1, 9], [2, 10], and so forth
227
+ depending on the process's rank. For example, rank 1 would get [1, 9], rank 5
228
+ would get [5, 13].
229
+ """
230
+ # the inter-node pg that is returned
231
+ inter_node_pg = None
232
+ sharding_backend = dist.get_backend(global_process_group)
233
+ world_size = dist.get_world_size(global_process_group)
234
+ # Assuming fully homogeneous setup
235
+ num_nodes = world_size // num_devices_per_node
236
+ my_local_rank = dist.get_rank(global_process_group) % num_devices_per_node
237
+ for local_rank in range(num_devices_per_node):
238
+ ranks_for_inter_group = [
239
+ local_rank + (i * num_devices_per_node) for i in range(num_nodes)
240
+ ]
241
+ # every rank always needs to call dist.new_group
242
+ grp = dist.new_group(ranks=ranks_for_inter_group, backend=sharding_backend)
243
+ if local_rank == my_local_rank:
244
+ inter_node_pg = grp
245
+
246
+ if inter_node_pg is None:
247
+ raise AssertionError(
248
+ f"{my_local_rank} expected to assign inter-node pg, but did not"
249
+ )
250
+ return inter_node_pg
251
+
252
+
253
+ def _init_intra_and_inter_node_groups(
254
+ global_process_group: dist.ProcessGroup,
255
+ num_devices_per_node: int,
256
+ ) -> tuple[dist.ProcessGroup, dist.ProcessGroup]:
257
+ """
258
+ Initialize intra and inter-node process groups and return the ones corresponding to this process's rank.
259
+
260
+ This function can be used to initialize process groups for ``HYBRID_SHARD`` or
261
+ ``_HYBRID_SHARD_ZERO2`` in FSDP.
262
+ This function assumes each node has an equal number of CUDA-enabled devices.
263
+ Returns:
264
+ Tuple[dist.ProcessGroup, dist.ProcessGroup]: Intra and inter-node process group.
265
+ """
266
+ return (
267
+ _init_intra_node_process_group(num_devices_per_node),
268
+ _init_inter_node_process_group(global_process_group, num_devices_per_node),
269
+ )
270
+
271
+
272
+ @no_type_check
273
+ def _init_ignored_module_states(
274
+ state: _FSDPState,
275
+ module: nn.Module,
276
+ ignored_modules: Optional[Iterable[torch.nn.Module]],
277
+ ignored_states: Union[
278
+ Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
279
+ ] = None,
280
+ ) -> _FSDPState:
281
+ if ignored_modules is not None and ignored_states is not None:
282
+ raise ValueError(
283
+ "Cannot pass both ignored_modules and ignored_states at the "
284
+ "same time. Please just pass ignored_states."
285
+ )
286
+ ignored_parameters = None
287
+ passed_as_ignored_states = ignored_states is not None
288
+ if passed_as_ignored_states:
289
+ ignored_states_list = list(ignored_states)
290
+ _check_ignored_states(ignored_states_list, True)
291
+ else:
292
+ ignored_states_list = []
293
+ _check_ignored_states(
294
+ list(ignored_modules) if ignored_modules is not None else [], False
295
+ )
296
+ if len(ignored_states_list) > 0:
297
+ if isinstance(ignored_states_list[0], nn.Parameter):
298
+ ignored_parameters = ignored_states_list
299
+ else:
300
+ ignored_modules = ignored_states_list
301
+ state._ignored_modules = _get_ignored_modules(module, ignored_modules)
302
+ state._ignored_params = _get_ignored_params(
303
+ module,
304
+ state._ignored_modules,
305
+ ignored_parameters,
306
+ )
307
+ state._ignored_buffer_names = _get_ignored_buffer_names(
308
+ module,
309
+ state._ignored_modules,
310
+ )
311
+ # TODO: FSDP's contract for buffers is not well-defined. They are
312
+ # implicitly ignored for most functionality since they are not sharded;
313
+ # however, FSDP still imposes some semantics on buffers (e.g. buffer mixed
314
+ # precision). We should formalize this contract and decide if we need to
315
+ # compute and store `_ignored_buffers`.
316
+ return state
317
+
318
+
319
+ def _check_ignored_states(
320
+ ignored_states: list[Any], passed_as_ignored_states: bool
321
+ ) -> None:
322
+ """
323
+ Check that the ignored states are uniformly parameters or uniformly modules.
324
+
325
+ We may remove this check in the future if we permit mixing.
326
+ """
327
+ if len(ignored_states) == 0:
328
+ return
329
+ if passed_as_ignored_states:
330
+ all_params = all(isinstance(state, nn.Parameter) for state in ignored_states)
331
+ all_modules = all(isinstance(state, nn.Module) for state in ignored_states)
332
+ if not all_params and not all_modules:
333
+ # Sort for consistent ordering for unit test regex matching
334
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
335
+ raise ValueError(
336
+ "ignored_states expects all nn.Parameter or all nn.Module list "
337
+ f"elements but got types {sorted_types}"
338
+ )
339
+ else:
340
+ if not all(isinstance(state, nn.Module) for state in ignored_states):
341
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
342
+ raise ValueError(
343
+ "ignored_modules expects nn.Module list elements but got "
344
+ f"types {sorted_types}"
345
+ )
346
+
347
+
348
+ @no_type_check
349
+ def _init_device_handle(
350
+ state: _FSDPState,
351
+ module: nn.Module,
352
+ ignored_params: set[nn.Parameter],
353
+ device_id: Optional[Union[int, torch.device]],
354
+ ) -> _FSDPState:
355
+ """
356
+ Determine device handle used for initializing FSDP.
357
+
358
+ If a device is specified by ``device_id``,
359
+ then returns device handle corresponds to that device type. Otherwise, If the
360
+ module is already on a non-CPU device, then the device type is that non-CPU device type.
361
+ If the module is on CPU or meta, then the device type is the current accelerator device.
362
+ See the :ref:`Accelerators<accelerators>` for details.
363
+
364
+
365
+ This method will be called once ignored parameters was determined, as the device handle maybe needed
366
+ for other initialization.
367
+ """
368
+ determined_device = None
369
+ if device_id is not None:
370
+ determined_device = (
371
+ device_id
372
+ if isinstance(device_id, torch.device)
373
+ else torch.device(device_id)
374
+ )
375
+ if determined_device is None:
376
+ for param in _get_orig_params(module, ignored_params):
377
+ if param.device.type in {"cpu", "meta"}:
378
+ continue
379
+ if determined_device is None:
380
+ determined_device = param.device
381
+ else:
382
+ if param.device.type != determined_device.type:
383
+ raise RuntimeError(
384
+ f"FSDP does not support modules with different device types "
385
+ f"but got params on {determined_device.type} and {param.device.type}"
386
+ )
387
+ determined_device = determined_device or torch._C._get_accelerator()
388
+ if determined_device.type == "cpu":
389
+ raise RuntimeError(
390
+ "FSDP needs a non-CPU accelerator device, but no accelerator device is detected."
391
+ )
392
+
393
+ state._device_handle = _FSDPDeviceHandle.from_device(determined_device)
394
+ return state
395
+
396
+
397
+ @no_type_check
398
+ def _init_buffer_state(
399
+ state: _FSDPState,
400
+ module: nn.Module,
401
+ ) -> _FSDPState:
402
+ state._buffer_names = _get_buffer_names(module)
403
+ # Save a mapping from clean fully-qualified buffer name (starting from
404
+ # `module`) to its original dtype for restoring that dtype during model
405
+ # checkpointing when buffer mixed precision is enabled. The names should
406
+ # be clean since the casting happens in a `summon_full_params()` context.
407
+ _buffer_name_to_orig_dtype: dict[str, torch.dtype] = {}
408
+ for buffer_name, buffer in module.named_buffers():
409
+ buffer_name = clean_tensor_name(buffer_name)
410
+ _buffer_name_to_orig_dtype[buffer_name] = buffer.dtype
411
+ state._buffer_name_to_orig_dtype = _buffer_name_to_orig_dtype
412
+ return state
413
+
414
+
415
+ @no_type_check
416
+ def _init_core_state(
417
+ state: _FSDPState,
418
+ sharding_strategy: Optional[ShardingStrategy],
419
+ mixed_precision: Optional[MixedPrecision],
420
+ cpu_offload: Optional[CPUOffload],
421
+ limit_all_gathers: bool,
422
+ use_orig_params: bool,
423
+ backward_prefetch_limit: int,
424
+ forward_prefetch_limit: int,
425
+ ) -> _FSDPState:
426
+ # We clamp the strategy to `NO_SHARD` for world size of 1 since they are
427
+ # currently functionally equivalent. This may change if/when we integrate
428
+ # FSDP with MoE.
429
+ if state.world_size == 1:
430
+ if sharding_strategy != ShardingStrategy.NO_SHARD:
431
+ warnings.warn(
432
+ "FSDP is switching to use `NO_SHARD` instead of "
433
+ f"{sharding_strategy or ShardingStrategy.FULL_SHARD} since "
434
+ "the world size is 1.",
435
+ stacklevel=2,
436
+ )
437
+ sharding_strategy = ShardingStrategy.NO_SHARD
438
+ elif sharding_strategy == ShardingStrategy.NO_SHARD:
439
+ warnings.warn(
440
+ "The `NO_SHARD` sharding strategy is deprecated. If having issues, "
441
+ "please use `DistributedDataParallel` instead.",
442
+ FutureWarning,
443
+ # Level 1 is here, level 2 is from `FullyShardedDataParallel`, and
444
+ # level 3 is from the true caller
445
+ stacklevel=3,
446
+ )
447
+ state.sharding_strategy = sharding_strategy or ShardingStrategy.FULL_SHARD
448
+ state.mixed_precision = mixed_precision or MixedPrecision()
449
+ if mixed_precision is not None:
450
+ torch._C._log_api_usage_once(
451
+ f"torch.distributed.fsdp.mixed_precision.{str(state.mixed_precision)}"
452
+ )
453
+ state._use_full_prec_in_eval = (
454
+ os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1"
455
+ )
456
+ state.cpu_offload = cpu_offload or CPUOffload()
457
+ state.limit_all_gathers = limit_all_gathers
458
+ state._use_orig_params = use_orig_params
459
+ state.training_state = TrainingState.IDLE
460
+ state._is_root = None
461
+ state._free_event_queue = _FreeEventQueue()
462
+ state._debug_level = dist.get_debug_level()
463
+ state._exec_order_data = exec_order_utils._ExecOrderData(
464
+ state._debug_level,
465
+ backward_prefetch_limit,
466
+ forward_prefetch_limit,
467
+ )
468
+ state._unshard_event = None
469
+ # Mapping from fully sharded module to the handles it is responsible to
470
+ # unshard and reshard (see [Note: Fully Sharded Module])
471
+ _fully_sharded_module_to_handle: dict[nn.Module, FlatParamHandle] = {}
472
+ state._fully_sharded_module_to_handle = _fully_sharded_module_to_handle
473
+ # Invariant: `state.params` contains exactly the `FlatParameter`s of the
474
+ # handles in `state._handle`
475
+ _handle: Optional[FlatParamHandle] = None
476
+ state._handle = _handle
477
+ params: list[FlatParameter] = []
478
+ state.params = params
479
+ return state
480
+
481
+
482
+ @no_type_check
483
+ def _init_runtime_state(
484
+ state: _FSDPState,
485
+ ) -> _FSDPState:
486
+ _root_pre_forward_handles: list[RemovableHandle] = []
487
+ state._root_pre_forward_handles = _root_pre_forward_handles
488
+ _pre_forward_handles: list[RemovableHandle] = []
489
+ state._pre_forward_handles = _pre_forward_handles
490
+ _post_forward_handles: list[RemovableHandle] = []
491
+ state._post_forward_handles = _post_forward_handles
492
+ state._sync_gradients = True
493
+ state._comm_hook = None
494
+ state._comm_hook_state = None
495
+ # Used to prevent running the pre-backward hook multiple times
496
+ return state
497
+
498
+
499
+ @no_type_check
500
+ def _init_prefetching_state(
501
+ state: _FSDPState,
502
+ backward_prefetch: BackwardPrefetch,
503
+ forward_prefetch: bool,
504
+ ) -> _FSDPState:
505
+ state.backward_prefetch = backward_prefetch
506
+ state.forward_prefetch = forward_prefetch
507
+ # The data structures use tuples of handles to generalize over the case
508
+ # where a module's forward involves multiple handles.
509
+ return state
510
+
511
+
512
+ @no_type_check
513
+ # pyrefly: ignore [bad-function-definition]
514
+ def _init_extension(state: _FSDPState, device_mesh: DeviceMesh = None) -> _FSDPState:
515
+ # TODO: we need to add additional check once we support FSDP + PiPPy.
516
+ # This check is currently sufficient, since we only support FSDP + TP.
517
+ root_mesh = device_mesh._get_root_mesh() if device_mesh is not None else None
518
+ # if a root mesh is not the same as device_mesh,
519
+ # meaning the device_mesh is sliced out from the root mesh.
520
+ if device_mesh and root_mesh != state._device_mesh:
521
+ state._fsdp_extension = DTensorExtensions(state._device_handle)
522
+ else:
523
+ # We need to explicitly set _fsdp_extension to None.
524
+ # Otherwise, we will run into an infinite recursion when getting the attribute.
525
+ state._fsdp_extension = None
526
+ return state
527
+
528
+
529
+ @no_type_check
530
+ def _init_state_dict_state(state: _FSDPState) -> _FSDPState:
531
+ state._state_dict_type = StateDictType.FULL_STATE_DICT
532
+ state_dict_config: StateDictConfig = FullStateDictConfig()
533
+ state._optim_state_dict_config = FullOptimStateDictConfig()
534
+ state._state_dict_config = state_dict_config
535
+ unshard_params_ctx: dict[nn.Module, Generator] = {}
536
+ state._unshard_params_ctx = unshard_params_ctx
537
+
538
+ return state
539
+
540
+
541
+ def _verify_managed_params(module: nn.Module, params: list[nn.Parameter]) -> None:
542
+ """
543
+ Verify if the parameters are accepted by FSDP. The only restriction now
544
+ is that the parameter cannot be a scalar tensor (param.shape == []).
545
+ """
546
+ for param in params:
547
+ if len(param.shape) == 0:
548
+ param_name = ""
549
+ for name, param_ in module.named_parameters():
550
+ if param is param_:
551
+ param_name = name
552
+ break
553
+ if not param_name:
554
+ raise AssertionError("Expected param_name to be set")
555
+ raise ValueError(
556
+ "FSDP doesn't support scalar parameters. "
557
+ f"Change {param_name} to a 1D tensor with numel equal to 1."
558
+ )
559
+
560
+
561
+ @no_type_check
562
+ def _init_param_handle_from_module(
563
+ state: _FSDPState,
564
+ fully_sharded_module: nn.Module,
565
+ device_id: Optional[Union[int, torch.device]],
566
+ param_init_fn: Optional[Callable[[nn.Module], None]],
567
+ sync_module_states: bool,
568
+ ) -> _FSDPState:
569
+ """Initialize a ``FlatParamHandle`` from a module ``fully_sharded_module``."""
570
+ _check_single_device_module(fully_sharded_module, state._ignored_params, device_id)
571
+ device_from_device_id = _get_device_from_device_id(
572
+ device_id, state.rank, state._device_handle
573
+ )
574
+ is_meta_module, is_torchdistX_deferred_init = _need_to_materialize_module(
575
+ fully_sharded_module, state._ignored_params, state._ignored_modules
576
+ )
577
+ # Materialize the module if needed
578
+ if (is_meta_module or is_torchdistX_deferred_init) and param_init_fn is not None:
579
+ _materialize_with_param_init_fn(
580
+ fully_sharded_module, param_init_fn, state._ignored_modules
581
+ )
582
+ elif is_meta_module:
583
+ _materialize_meta_module(
584
+ fully_sharded_module,
585
+ device_id,
586
+ state._ignored_modules,
587
+ state._device_handle,
588
+ )
589
+ elif is_torchdistX_deferred_init:
590
+ deferred_init.materialize_module(
591
+ fully_sharded_module,
592
+ check_fn=lambda submodule: _get_module_fsdp_state(submodule) is None
593
+ and submodule not in state._ignored_modules,
594
+ )
595
+
596
+ ignored_buffers = {
597
+ buffer
598
+ for ignored_module in state._ignored_modules
599
+ for buffer in ignored_module.buffers()
600
+ }
601
+
602
+ _move_module_to_device(
603
+ fully_sharded_module,
604
+ state._ignored_params,
605
+ ignored_buffers,
606
+ device_from_device_id,
607
+ )
608
+ state.compute_device = _get_compute_device(
609
+ fully_sharded_module,
610
+ state._ignored_params,
611
+ device_from_device_id,
612
+ state.rank,
613
+ state._device_handle,
614
+ )
615
+
616
+ managed_params = list(_get_orig_params(fully_sharded_module, state._ignored_params))
617
+ _verify_managed_params(fully_sharded_module, managed_params)
618
+ if sync_module_states:
619
+ _sync_module_params_and_buffers(
620
+ fully_sharded_module, managed_params, state.process_group
621
+ )
622
+ if state.sharding_strategy in HYBRID_SHARDING_STRATEGIES:
623
+ _sync_module_params_and_buffers(
624
+ fully_sharded_module, managed_params, state._inter_node_pg
625
+ )
626
+ _init_param_handle_from_params(state, managed_params, fully_sharded_module)
627
+ return state
628
+
629
+
630
+ @no_type_check
631
+ def _init_param_handle_from_params(
632
+ state: _FSDPState,
633
+ params: list[nn.Parameter],
634
+ fully_sharded_module: nn.Module,
635
+ ):
636
+ if len(params) == 0:
637
+ return
638
+ handle = FlatParamHandle(
639
+ params,
640
+ fully_sharded_module,
641
+ state.compute_device,
642
+ SHARDING_STRATEGY_MAP[state.sharding_strategy],
643
+ state.cpu_offload.offload_params,
644
+ state.mixed_precision.param_dtype,
645
+ state.mixed_precision.reduce_dtype,
646
+ state.mixed_precision.keep_low_precision_grads,
647
+ state.process_group,
648
+ state._use_orig_params,
649
+ fsdp_extension=state._fsdp_extension,
650
+ )
651
+ handle.shard()
652
+ if state._handle:
653
+ raise AssertionError("Expected state._handle to be None")
654
+ state.params.append(handle.flat_param)
655
+ state._handle = handle
656
+ state._fully_sharded_module_to_handle[handle._fully_sharded_module] = handle
657
+ cpu_device = torch.device("cpu")
658
+ if state.cpu_offload.offload_params and handle.flat_param.device != cpu_device:
659
+ handle.flat_param_to(cpu_device)
660
+
661
+
662
+ def _get_ignored_modules(
663
+ root_module: nn.Module,
664
+ _ignored_modules: Optional[Iterable[torch.nn.Module]],
665
+ ) -> set[nn.Module]:
666
+ """
667
+ Check that ``_ignored_modules`` is an iterable of ``nn.Module`` s without any FSDP instances.
668
+
669
+ Return the modules contained in their module
670
+ subtrees as a :class:`set`. Nested FSDP instances are excluded, but their
671
+ already-computed ignored modules are included.
672
+
673
+ ``_ignored_modules`` represents the argument passed by the user to FSDP.
674
+ """
675
+ msg_prefix = "`ignored_modules` should be an iterable of `torch.nn.Module`s "
676
+ try:
677
+ ignored_root_modules = (
678
+ set(_ignored_modules) if _ignored_modules is not None else set()
679
+ )
680
+ except TypeError as e:
681
+ raise TypeError(msg_prefix + f"but got {type(_ignored_modules)}") from e
682
+ for module in ignored_root_modules:
683
+ if not isinstance(module, torch.nn.Module):
684
+ raise TypeError(msg_prefix + f"but got an iterable with {type(module)}")
685
+ if _get_module_fsdp_state(module):
686
+ # TODO: We may relax this by taking the FSDP instance's wrapped
687
+ # module to provide more flexibility to the user.
688
+ raise ValueError("`ignored_modules` should not include FSDP modules")
689
+ # Treat modules that cannot compose with `fully_shard` as ignored modules,
690
+ # meaning that their subtrees are ignored
691
+ for module in root_module.modules():
692
+ if not traversal_utils._composable(module):
693
+ ignored_root_modules.add(module)
694
+ # NOTE: Even if `ignored_root_modules` is empty, do not return early so
695
+ # that this FSDP instance can get any ignored modules from its children.
696
+
697
+ # Include child modules and exclude nested FSDP modules themselves
698
+ ignored_modules = {
699
+ child
700
+ for module in ignored_root_modules
701
+ for child in module.modules()
702
+ if not isinstance(child, fsdp_file.FullyShardedDataParallel)
703
+ }
704
+ if root_module in ignored_modules:
705
+ warnings.warn(
706
+ "Trying to ignore the top-level module passed into the FSDP "
707
+ "constructor itself will result in all parameters being "
708
+ f"ignored and is not well-supported: {module}",
709
+ stacklevel=2,
710
+ )
711
+ # Include nested FSDP modules' ignored modules
712
+ for submodule in root_module.modules():
713
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
714
+ if optional_fsdp_state is not None:
715
+ if not hasattr(optional_fsdp_state, "_ignored_modules"):
716
+ raise AssertionError(
717
+ "Expected optional_fsdp_state to have _ignored_modules attribute"
718
+ )
719
+ ignored_modules.update(optional_fsdp_state._ignored_modules)
720
+ return ignored_modules
721
+
722
+
723
+ def _get_ignored_params(
724
+ root_module: torch.nn.Module,
725
+ ignored_modules: set[torch.nn.Module],
726
+ ignored_parameters: Optional[Iterable[torch.nn.Parameter]] = None,
727
+ ) -> set[torch.nn.Parameter]:
728
+ """
729
+ Return the parameters of the modules in ``ignored_modules`` and the parameters in ``ignored_parameters``.
730
+
731
+ :class:`FlatParameter` s are excluded from the result.
732
+ """
733
+ all_ignored_params: set[torch.nn.Parameter] = set()
734
+
735
+ params_in_ignored_modules = {
736
+ p for m in ignored_modules for p in m.parameters() if not _is_fsdp_flattened(p)
737
+ }
738
+
739
+ all_ignored_params.update(params_in_ignored_modules)
740
+
741
+ if ignored_parameters is not None:
742
+ params_in_ignored_parameters = {
743
+ p for p in ignored_parameters if not _is_fsdp_flattened(p)
744
+ }
745
+ all_ignored_params.update(params_in_ignored_parameters)
746
+
747
+ # Always include nested FSDP modules' ignored parameters
748
+ for submodule in root_module.modules():
749
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
750
+ if optional_fsdp_state is not None:
751
+ if not hasattr(optional_fsdp_state, "_ignored_params"):
752
+ raise AssertionError(
753
+ "Expected optional_fsdp_state to have _ignored_params attribute"
754
+ )
755
+ all_ignored_params.update(optional_fsdp_state._ignored_params)
756
+
757
+ return all_ignored_params
758
+
759
+
760
+ def _get_ignored_buffer_names(
761
+ root_module: torch.nn.Module,
762
+ ignored_modules: set[torch.nn.Module],
763
+ ) -> set[str]:
764
+ """Return the cleaned buffer FQNs in ``ignored_modules``."""
765
+ all_ignored_buffer_names: set[str] = set()
766
+
767
+ buffers_in_ignored_modules = {
768
+ buffer for m in ignored_modules for buffer in m.buffers()
769
+ }
770
+
771
+ all_ignored_buffer_names.update(
772
+ {
773
+ clean_tensor_name(buffer_name)
774
+ for buffer_name, buffer in root_module.named_buffers()
775
+ if buffer in buffers_in_ignored_modules
776
+ }
777
+ )
778
+
779
+ # Always include nested FSDP modules' ignored buffer names
780
+ for submodule in root_module.modules():
781
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
782
+ if optional_fsdp_state is not None:
783
+ if not hasattr(optional_fsdp_state, "_ignored_buffer_names"):
784
+ raise AssertionError(
785
+ "Expected optional_fsdp_state to have _ignored_buffer_names attribute"
786
+ )
787
+ all_ignored_buffer_names.update(optional_fsdp_state._ignored_buffer_names)
788
+
789
+ return all_ignored_buffer_names
790
+
791
+
792
+ def _get_buffer_names(root_module: nn.Module) -> set[str]:
793
+ """Return the fully prefixed names of all buffers in the module hierarchy rooted at ``root_module`` as a class:`set`."""
794
+ return {
795
+ clean_tensor_name(buffer_name) for buffer_name, _ in root_module.named_buffers()
796
+ }
797
+
798
+
799
+ def _check_single_device_module(
800
+ module: nn.Module,
801
+ ignored_params: set[nn.Parameter],
802
+ device_id: Optional[Union[int, torch.device]],
803
+ ) -> None:
804
+ """
805
+ Raise an error if ``module`` has original parameters on multiple devices, ignoring the parameters in ``ignored_params``.
806
+
807
+ Thus, after this method, the
808
+ module must be either fully on the CPU or fully on a non-CPU device.
809
+ """
810
+ devices = {param.device for param in _get_orig_params(module, ignored_params)}
811
+ # We allow module to be partially on CPU and partially on GPU if device_id is not
812
+ # None, since the device_id arg will result in the CPU portion being moved to
813
+ # GPU. This is useful in cases where part of the module may be parallelized
814
+ # by another algorithm and may already be on GPU. We'd like to enforce device_id
815
+ # to not be None, otherwise we'd flatten parameters in a mixed module which is
816
+ # not supported.
817
+ if len(devices) == 2 and torch.device("cpu") in devices:
818
+ if device_id is None:
819
+ raise RuntimeError(
820
+ "To support a module with both CPU and GPU params, "
821
+ "please pass in device_id argument."
822
+ )
823
+ elif len(devices) > 1:
824
+ raise RuntimeError(
825
+ f"FSDP only supports single device modules but got params on {devices}"
826
+ )
827
+
828
+
829
+ def _get_device_from_device_id(
830
+ device_id: Optional[Union[int, torch.device]],
831
+ rank: int,
832
+ device_handle: _FSDPDeviceHandle,
833
+ ) -> Optional[torch.device]:
834
+ """
835
+ Return a ``torch.device`` for the specified ``device_id``.
836
+
837
+ Processes ``device_id`` and returns either the corresponding device or
838
+ ``None`` if ``device_id`` is ``None``.
839
+ """
840
+ if device_id is None:
841
+ return None
842
+ device = (
843
+ device_id if isinstance(device_id, torch.device) else torch.device(device_id)
844
+ )
845
+ if device.type != "cpu" and device.index is None:
846
+ warnings.warn(
847
+ f"FSDP got the argument `device_id` {device_id} on rank "
848
+ f"{rank}, which does not have an explicit index. "
849
+ f"FSDP will use the current device {device_handle.current_device()}. "
850
+ f"If this is incorrect, please explicitly call `torch.{device.type}.set_device()` "
851
+ "before FSDP initialization or pass in the explicit device "
852
+ "index as the `device_id` argument.",
853
+ stacklevel=2,
854
+ )
855
+ device = torch.device(device_handle.current_device())
856
+ return device
857
+
858
+
859
+ def _need_to_materialize_module(
860
+ module: nn.Module,
861
+ ignored_params: set[nn.Parameter],
862
+ ignored_modules: set[nn.Module],
863
+ ) -> tuple[bool, bool]:
864
+ """
865
+ Return if ``module`` has parameters on meta device and if ``module`` is using torchdistX deferred initialization.
866
+
867
+ At most of the returned bools can
868
+ be ``True``. If either is ``True``, then ``module`` needs to be
869
+ materialized.
870
+ """
871
+ managed_params = list(_get_orig_params(module, ignored_params))
872
+ is_meta_module = any(param.is_meta for param in managed_params)
873
+ # TODO: We need to establish a contract for FSDP and buffers. For now, we
874
+ # skip checking for meta buffers from ignored modules. We should consider
875
+ # refactoring the initialization holistically to avoid so many traversals.
876
+ for submodule in module.modules():
877
+ if submodule in ignored_modules:
878
+ continue
879
+ for buf in submodule.buffers(recurse=False):
880
+ is_meta_module |= buf.is_meta
881
+ is_torchdistX_deferred_init = (
882
+ not is_meta_module
883
+ and _TORCHDISTX_AVAIL
884
+ and any(fake.is_fake(param) for param in managed_params)
885
+ )
886
+ return is_meta_module, is_torchdistX_deferred_init
887
+
888
+
889
+ def _materialize_with_param_init_fn(
890
+ root_module: nn.Module,
891
+ param_init_fn: Callable[[nn.Module], None],
892
+ ignored_modules: set[nn.Module],
893
+ ) -> None:
894
+ if not callable(param_init_fn):
895
+ raise ValueError(
896
+ f"Expected {param_init_fn} to be callable but got {type(param_init_fn)}"
897
+ )
898
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
899
+ for module in modules_to_materialize:
900
+ param_init_fn(module)
901
+
902
+
903
+ def _materialize_meta_module(
904
+ root_module: nn.Module,
905
+ device_from_device_id: Optional[torch.device],
906
+ ignored_modules: set[nn.Module],
907
+ device_handle: _FSDPDeviceHandle,
908
+ ):
909
+ # Run default meta device initialization
910
+ materialization_device = device_from_device_id or torch.device(
911
+ device_handle.current_device()
912
+ )
913
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
914
+ module = None
915
+ try:
916
+ # Assume that each module's `reset_parameters()` only initializes its
917
+ # own parameters and not those of its children
918
+ with torch.no_grad():
919
+ for module in modules_to_materialize:
920
+ # As a contract to the user, only call `reset_parameters()` if
921
+ # the module has directly managed parameters/buffers
922
+ module_state_iter = itertools.chain(
923
+ module.parameters(recurse=False),
924
+ # pyrefly: ignore [bad-argument-type]
925
+ module.buffers(recurse=False),
926
+ )
927
+ has_module_states = len(list(module_state_iter)) > 0
928
+ if has_module_states:
929
+ module.to_empty(device=materialization_device, recurse=False)
930
+ module.reset_parameters() # type: ignore[operator]
931
+ except BaseException as e:
932
+ warnings.warn(
933
+ "Unable to call `reset_parameters()` for module on meta "
934
+ f"device with error {str(e)}. Please ensure that your module of"
935
+ f"type {type(module)} implements a `reset_parameters()` method.",
936
+ stacklevel=2, # type: ignore[possibly-undefined]
937
+ )
938
+ raise e
939
+
940
+
941
+ def _get_modules_to_materialize(
942
+ root_module: nn.Module, ignored_modules: set[nn.Module]
943
+ ) -> list[nn.Module]:
944
+ # Run BFS to collect the modules to materialize via `reset_parameters()`,
945
+ # stopping at any module with FSDP already applied or at ignored modules.
946
+ modules_to_materialize: list[nn.Module] = []
947
+ queue = collections.deque([root_module])
948
+ visited_modules: set[nn.Module] = {root_module}
949
+ while queue:
950
+ module = queue.popleft()
951
+ modules_to_materialize.append(module)
952
+ for child_module in module.children():
953
+ if (
954
+ child_module not in visited_modules
955
+ and _get_module_fsdp_state(child_module) is None
956
+ and child_module not in ignored_modules
957
+ ):
958
+ visited_modules.add(child_module)
959
+ queue.append(child_module)
960
+ return modules_to_materialize
961
+
962
+
963
+ def _move_module_to_device(
964
+ module: nn.Module,
965
+ ignored_params: set[nn.Parameter],
966
+ ignored_buffers: set[torch.Tensor],
967
+ device_from_device_id: Optional[torch.device],
968
+ ) -> None:
969
+ """
970
+ Move ``module`` depending on ``device_from_device_id`` and its current device.
971
+
972
+ This includes moving ignored modules' parameters.
973
+
974
+ - If ``device_from_device_id`` is not ``None``, then this moves
975
+ ``module`` to the device.
976
+ - If ``device_from_device_id`` is ``None``, then this does not move
977
+ ``module`` but warns the user if it is on CPU.
978
+
979
+ Precondition: ``_check_single_device_module()``.
980
+ """
981
+ cpu_device = torch.device("cpu")
982
+ if device_from_device_id is not None:
983
+ # BFS from `module` without traversing any nested FSDP instances to
984
+ # collect the parameters/buffers that have not yet been managed
985
+ queue: collections.deque[nn.Module] = collections.deque()
986
+ queue.append(module)
987
+ params: list[nn.Parameter] = []
988
+ buffers: list[torch.Tensor] = []
989
+ while queue:
990
+ curr_module = queue.popleft()
991
+ # NOTE: We include a check to only move parameters/buffers that are
992
+ # on CPU device. If they are on a CUDA device different from the
993
+ # one specified by `device_id`, then this does NOT move them. This
994
+ # is so that we can raise an error in `_get_compute_device()`.
995
+ params.extend(
996
+ param
997
+ for param in curr_module.parameters(recurse=False)
998
+ if param.device == cpu_device
999
+ )
1000
+ buffers.extend(
1001
+ buffer
1002
+ for buffer in curr_module.buffers(recurse=False)
1003
+ if buffer.device == cpu_device
1004
+ )
1005
+ for submodule in curr_module.children():
1006
+ if not isinstance(submodule, fsdp_file.FullyShardedDataParallel):
1007
+ queue.append(submodule)
1008
+ params_to_move = [p for p in params if p not in ignored_params]
1009
+ bufs_to_move = [p for p in buffers if p not in ignored_buffers]
1010
+ _move_states_to_device(params_to_move, bufs_to_move, device_from_device_id)
1011
+ return
1012
+ param = next(_get_orig_params(module, ignored_params), None)
1013
+ if param is not None and param.device == cpu_device:
1014
+ _warn_cpu_init()
1015
+
1016
+
1017
+ def _move_states_to_device(
1018
+ params: list[nn.Parameter],
1019
+ buffers: list[torch.Tensor],
1020
+ device_from_device_id: Optional[torch.device],
1021
+ ) -> None:
1022
+ """
1023
+ Move states to the specified device.
1024
+
1025
+ Precondition: ``_check_single_device_module()`` and module's parameters and
1026
+ buffers have been materialized if needed.
1027
+ """
1028
+ if len(params) == 0 and len(buffers) == 0:
1029
+ return
1030
+ if len(params) > 0:
1031
+ current_device = params[0].device
1032
+ elif len(buffers) > 0:
1033
+ current_device = buffers[0].device
1034
+ cpu_device = torch.device("cpu")
1035
+ if device_from_device_id is not None:
1036
+ # Move the parameters and buffers like the `.data` code path in
1037
+ # `nn.Module._apply()`, which underlies `nn.Module.to()`
1038
+ for param in params:
1039
+ with torch.no_grad():
1040
+ param.data = param.to(device_from_device_id)
1041
+ if param.grad is not None:
1042
+ param.grad.data = param.grad.to(device_from_device_id)
1043
+ for buffer in buffers:
1044
+ buffer.data = buffer.to(device_from_device_id)
1045
+ elif current_device == cpu_device: # type: ignore[possibly-undefined]
1046
+ _warn_cpu_init()
1047
+
1048
+
1049
+ def _warn_cpu_init():
1050
+ warnings.warn(
1051
+ "The passed-in `module` is on CPU and will thus have FSDP's sharding "
1052
+ "initialization run on CPU, which may be slower than on GPU. We "
1053
+ "recommend passing in the `device_id` argument for FSDP to move "
1054
+ "`module` to GPU for the sharding initialization. `module` must also "
1055
+ "be on GPU device to work with the `sync_module_states=True` flag "
1056
+ "since that requires GPU communication.",
1057
+ stacklevel=2,
1058
+ )
1059
+
1060
+
1061
+ def _get_compute_device(
1062
+ module: nn.Module,
1063
+ ignored_params: set[nn.Parameter],
1064
+ device_from_device_id: Optional[torch.device],
1065
+ rank: int,
1066
+ device_handle: _FSDPDeviceHandle,
1067
+ ) -> torch.device:
1068
+ """
1069
+ Determine and return this FSDP instance's compute device.
1070
+
1071
+ If the module is already on a non-CPU device, then the compute device is that non-CPU
1072
+ device. If the module is on CPU, then the compute device is the current
1073
+ device.
1074
+
1075
+ Since this method should be called after materializing the module, any
1076
+ non-CPU device should not be meta device. For now, the compute device is
1077
+ always a CUDA or CUDA-like device with its explicit index.
1078
+
1079
+ Precondition: ``_check_single_device_module()`` and
1080
+ ``_move_module_to_device()``.
1081
+ """
1082
+ param = next(_get_orig_params(module, ignored_params), None)
1083
+ if param is not None and param.device.type != "cpu":
1084
+ compute_device = param.device # Determined by model param placement
1085
+ else:
1086
+ compute_device = torch.device(device_handle.current_device())
1087
+ if device_from_device_id is not None and compute_device != device_from_device_id:
1088
+ raise ValueError(
1089
+ f"Inconsistent compute device and `device_id` on rank {rank}: "
1090
+ f"{compute_device} vs {device_from_device_id}"
1091
+ )
1092
+ return compute_device
1093
+
1094
+
1095
+ # TODO: See how to deprecate!
1096
+ def _sync_module_params_and_buffers(
1097
+ module: nn.Module,
1098
+ params: list[nn.Parameter],
1099
+ process_group: dist.ProcessGroup,
1100
+ ) -> None:
1101
+ """
1102
+ Synchronize module states (i.e. parameters ``params`` and all not-yet-synced buffers) by broadcasting from rank 0 to all ranks.
1103
+
1104
+ Precondition: ``sync_module_states == True`` and ``self.process_group`` has
1105
+ been set.
1106
+ """
1107
+ module_states: list[torch.Tensor] = []
1108
+ for buffer in module.buffers():
1109
+ # Avoid re-synchronizing buffers in case of nested wrapping
1110
+ if not getattr(buffer, FSDP_SYNCED, False):
1111
+ setattr(buffer, FSDP_SYNCED, True)
1112
+ detached_buffer = buffer.detach()
1113
+ if is_traceable_wrapper_subclass(detached_buffer):
1114
+ # NOTE: Here we assume no nested subclasses, at most one level of subclass
1115
+ # in both model's buffers and params
1116
+ attrs, _ = detached_buffer.__tensor_flatten__() # type: ignore[attr-defined]
1117
+ inner_buffers = [getattr(detached_buffer, attr) for attr in attrs]
1118
+ module_states.extend(inner_buffers)
1119
+ else:
1120
+ module_states.append(detached_buffer)
1121
+
1122
+ for param in params:
1123
+ detached_param = param.detach()
1124
+ if is_traceable_wrapper_subclass(detached_param):
1125
+ attrs, _ = detached_param.__tensor_flatten__() # type: ignore[attr-defined]
1126
+ inner_params = [getattr(detached_param, attr) for attr in attrs]
1127
+ module_states.extend(inner_params)
1128
+ else:
1129
+ module_states.append(detached_param)
1130
+
1131
+ _check_module_states_for_sync_module_states(module_states)
1132
+ _sync_params_and_buffers(
1133
+ process_group,
1134
+ module_states,
1135
+ PARAM_BROADCAST_BUCKET_SIZE,
1136
+ src=0,
1137
+ )
1138
+
1139
+
1140
+ def _check_module_states_for_sync_module_states(
1141
+ module_states: list[torch.Tensor],
1142
+ ) -> None:
1143
+ if module_states and any(
1144
+ tensor.device == torch.device("cpu") for tensor in module_states
1145
+ ):
1146
+ raise ValueError(
1147
+ "The module has CPU parameters or buffers when `sync_module_states=True`, "
1148
+ "which requires them to be on GPU. Please specify the `device_id` argument "
1149
+ "or move the module to GPU before passing it to FSDP."
1150
+ )
1151
+
1152
+
1153
+ def _get_orig_params(
1154
+ module: nn.Module,
1155
+ ignored_params: set[nn.Parameter],
1156
+ ) -> Iterator[nn.Parameter]:
1157
+ """
1158
+ Return an iterator over the original parameters in ``module``.
1159
+
1160
+ The iterator does not return
1161
+ the parameters in ``ignored_params``, any ``FlatParameter`` s (which may be
1162
+ present due to nested FSDP wrapping), or any original parameters already
1163
+ flattened (only relevant when ``use_orig_params=True``).
1164
+ """
1165
+ param_gen = module.parameters()
1166
+ try:
1167
+ while True:
1168
+ param = next(param_gen)
1169
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1170
+ yield param
1171
+ except StopIteration:
1172
+ pass
1173
+
1174
+
1175
+ def _check_orig_params_flattened(
1176
+ fsdp_module,
1177
+ ignored_params: set[nn.Parameter],
1178
+ ) -> None:
1179
+ """
1180
+ Check that original parameters in ``fsdp_module`` have been flattened.
1181
+
1182
+ The flattened parameters are made
1183
+ invisible to ``named_parameters()`` for the module hierarchy rooted at
1184
+ ``fsdp_module``. This should be called as a sanity check after flattening
1185
+ the wrapped module's parameters.
1186
+ """
1187
+ for param_name, param in _named_parameters_with_duplicates(fsdp_module):
1188
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1189
+ raise RuntimeError(
1190
+ f"Found an unflattened parameter: {param_name}; "
1191
+ f"{param.size()} {param.__class__}"
1192
+ )
1193
+
1194
+
1195
+ def _get_default_comm_hook(sharding_strategy: ShardingStrategy):
1196
+ return (
1197
+ default_hooks.allreduce_hook
1198
+ if sharding_strategy == ShardingStrategy.NO_SHARD
1199
+ else default_hooks.reduce_scatter_hook
1200
+ )
1201
+
1202
+
1203
+ def _get_default_comm_hook_state(
1204
+ process_group: dist.ProcessGroup,
1205
+ ) -> default_hooks.DefaultState:
1206
+ return default_hooks.DefaultState(process_group=process_group)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_limiter_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+
7
+ class _FreeEventQueue:
8
+ """
9
+ This tracks all pending frees corresponding to inflight all-gathers. The
10
+ queueing pattern is iterative enqueues with a single dequeue per iteration
11
+ once the limit ``_max_num_inflight_all_gathers`` is reached.
12
+ """
13
+
14
+ def __init__(self) -> None:
15
+ self._queue: collections.deque[torch.Event] = collections.deque()
16
+ self._max_num_inflight_all_gathers = 2 # empirically chosen
17
+
18
+ def enqueue(self, free_event: torch.Event) -> None:
19
+ """Enqueues a free event."""
20
+ self._queue.append(free_event)
21
+
22
+ def dequeue_if_needed(self) -> Optional[torch.Event]:
23
+ """Dequeues a single event if the limit is reached."""
24
+ if len(self._queue) >= self._max_num_inflight_all_gathers:
25
+ return self._dequeue()
26
+ return None
27
+
28
+ def _dequeue(self) -> Optional[torch.Event]:
29
+ """Dequeues a free event if possible."""
30
+ if self._queue:
31
+ event = self._queue.popleft()
32
+ return event
33
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_optim_utils.py ADDED
@@ -0,0 +1,2139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import functools
4
+ import logging
5
+ import warnings
6
+ from collections.abc import Iterable, Iterator, Sequence
7
+ from contextlib import ExitStack
8
+ from dataclasses import dataclass, field
9
+ from itertools import chain
10
+ from typing import Any, cast, NamedTuple, no_type_check, Optional, TYPE_CHECKING, Union
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
15
+ import torch.nn as nn
16
+ from torch.distributed._state_dict_utils import _gather_state_dict
17
+ from torch.distributed.distributed_c10d import _get_pg_default_device
18
+ from torch.distributed.fsdp._common_utils import (
19
+ _apply_to_modules,
20
+ _FSDPState,
21
+ _get_module_fsdp_state_if_fully_sharded_module,
22
+ _get_param_to_fqns,
23
+ _module_handle,
24
+ _named_parameters_with_duplicates,
25
+ clean_tensor_name,
26
+ )
27
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
28
+ from torch.distributed.fsdp._flat_param import FlatParameter, FlatParamHandle
29
+ from torch.distributed.fsdp._fsdp_extensions import (
30
+ _ext_chunk_dtensor,
31
+ _ext_chunk_tensor,
32
+ )
33
+ from torch.distributed.fsdp._runtime_utils import (
34
+ _lazy_init,
35
+ _reset_flat_param_grad_info_if_needed,
36
+ )
37
+ from torch.distributed.fsdp.api import (
38
+ ShardingStrategy,
39
+ StateDictSettings,
40
+ StateDictType,
41
+ )
42
+ from torch.distributed.tensor import DTensor, Replicate
43
+ from torch.utils._pytree import tree_map_only
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
48
+
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ @dataclass
54
+ class FSDPParamInfo:
55
+ state: _FSDPState
56
+ handle: FlatParamHandle
57
+ param_indices: dict[str, int]
58
+ param_requires_grad: list[bool]
59
+
60
+
61
+ def sorted_items(dictionary: dict[str, Any]) -> Iterator[tuple[str, Any]]:
62
+ keys = sorted(dictionary.keys())
63
+ for k in keys:
64
+ yield k, dictionary[k]
65
+
66
+
67
+ @dataclass
68
+ class _ConsolidatedOptimState:
69
+ """
70
+ This holds the consolidated optimizer state on the target rank. Positive-
71
+ dimension tensor state is communicated across ranks, while zero-dimension
72
+ tensor state and non-tensor state is taken directly from the target rank.
73
+
74
+ PyTorch version 1.12 moved to using zero-dimension tensors for scalar
75
+ values, but user implemented optimizers may still use float (i.e. a
76
+ non-tensor). Thus, we support both and handle them identically.
77
+
78
+ Attributes:
79
+ tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
80
+ tensor state name to the unsharded flat tensor representing the
81
+ state.
82
+ zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
83
+ dimension tensor state name to its value.
84
+ non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
85
+ name to its value.
86
+ """
87
+
88
+ tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
89
+ zero_dim_tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
90
+ non_tensor_state: dict[str, Any] = field(default_factory=dict)
91
+
92
+
93
+ class _PosDimTensorInfo(NamedTuple):
94
+ """
95
+ Metadata for positive-dimension tensors used internally for
96
+ :meth:`scatter_full_optim_state_dict`.
97
+
98
+ Attributes:
99
+ shape (torch.Size): Sharded tensor shape (which is equal to the
100
+ unsharded tensor shape if the tensor is optimizer state for a
101
+ non-FSDP parameter and is hence not sharded).
102
+ dtype (torch.dtype): Data type of the tensor.
103
+ """
104
+
105
+ shape: torch.Size
106
+ dtype: torch.dtype
107
+
108
+
109
+ class _OptimStateKey(NamedTuple):
110
+ """
111
+ This represents an optimizer state key that may be used commonly across
112
+ ranks. It is based on the unflattened parameter names rather than parameter
113
+ IDs to make it independent of each rank's own optimizer construction.
114
+ """
115
+
116
+ unflat_param_names: tuple[str, ...]
117
+ is_fsdp_managed: bool
118
+
119
+
120
+ def _unflatten_optim_state(
121
+ fsdp_param_info: FSDPParamInfo,
122
+ flat_param_state: dict[str, Any],
123
+ to_save: bool,
124
+ shard_state: bool,
125
+ cpu_offload: bool,
126
+ ) -> list[dict[str, Any]]:
127
+ """
128
+ Unflattens the optimizer state, consisting of the "state" part and the
129
+ "param_groups" part. Unflattening the "state" part involves consolidating
130
+ the state on the target rank and remapping from flattened to unflattened
131
+ parameter IDs, and the "param_groups" part only involves remapping from
132
+ flattened to unflattened parameter IDs.
133
+
134
+ Args:
135
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
136
+ mapping from FQN to original parameter index.
137
+ flat_param_state (Dict[str, Any]): Entry for the flat parameter in the
138
+ "state" part of the optimizer state dict.
139
+ to_save (bool): Whether to save the state on this rank.
140
+
141
+ Returns:
142
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
143
+ "state" part of the optimizer state dict corresponding to the
144
+ unflattened parameters comprising the flat parameter if on the target
145
+ rank or an empty :class:`list` otherwise. The final optimizer state
146
+ dict will need to map these entries using the proper unflattened
147
+ parameter IDs.
148
+ """
149
+ if shard_state and not to_save:
150
+ raise AssertionError("If ``shard_state`` is True, ``to_save`` has to be True.")
151
+ consolidated_state = _communicate_optim_state(
152
+ fsdp_param_info,
153
+ flat_param_state,
154
+ )
155
+ if to_save:
156
+ unflat_param_state = _unflatten_communicated_optim_state(
157
+ fsdp_param_info,
158
+ consolidated_state,
159
+ shard_state,
160
+ )
161
+ for optim_state in unflat_param_state:
162
+ # We can't use .items() below cuz we'd run into a concurrent modification error
163
+ if cpu_offload:
164
+ for key in list(optim_state.keys()):
165
+ state = optim_state[key]
166
+ if not isinstance(state, torch.Tensor):
167
+ continue
168
+ optim_state[key] = state.cpu()
169
+ return unflat_param_state
170
+ else:
171
+ return []
172
+
173
+
174
+ def _is_zero_dim_tensor(x: Any) -> bool:
175
+ return torch.is_tensor(x) and x.dim() == 0
176
+
177
+
178
+ def _communicate_optim_state(
179
+ fsdp_param_info: FSDPParamInfo,
180
+ flat_param_state: dict[str, Any],
181
+ ) -> _ConsolidatedOptimState:
182
+ """
183
+ Communicates the optimizer state for a flat parameter across ranks. All
184
+ ranks will hold the entire non-sharded optimizer state on GPU.
185
+
186
+ If ``N`` is the number of tensor optimizer states in the optimizer state
187
+ dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
188
+ otherwise (where the plus 1 comes from all-gathering the padding per rank).
189
+
190
+ Args:
191
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
192
+ mapping from FQN to original parameter index.
193
+ flat_param_state (Dict[str, Any]): The entry in the "state" part of the
194
+ optimizer state dict corresponding to the flat parameter.
195
+
196
+ Returns:
197
+ ConsolidatedOptimState: Consolidated optimizer state for the target
198
+ flat parameter.
199
+ """
200
+ fsdp_state = fsdp_param_info.state
201
+ flat_param = fsdp_param_info.handle.flat_param
202
+ state = _ConsolidatedOptimState()
203
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
204
+ state.tensor_state,
205
+ state.zero_dim_tensor_state,
206
+ state.non_tensor_state,
207
+ )
208
+
209
+ for state_name, value in sorted_items(flat_param_state):
210
+ # Positive-dimension tensor state: communicate across ranks
211
+ if torch.is_tensor(value) and value.dim() > 0:
212
+ # If the parameter is not sharded, then neither is the
213
+ # positive-dimension tensor state, so no need to communicate it --
214
+ # we take the target rank's value
215
+ if (
216
+ fsdp_state.world_size == 1
217
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
218
+ ):
219
+ tensor_state[state_name] = value
220
+ continue
221
+ if fsdp_state.compute_device is None:
222
+ raise AssertionError("compute_device has not been initialized")
223
+ if value.device.type != fsdp_state.compute_device.type:
224
+ value = value.to(fsdp_state.compute_device)
225
+ # Assume that positive-dimension tensor optimizer state
226
+ # has the same shape as the sharded flat parameter
227
+ buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined]
228
+ tensor_buffer = value.new_zeros(*buffer_size)
229
+ dist.all_gather_into_tensor(
230
+ tensor_buffer, value, group=fsdp_state.process_group
231
+ )
232
+ fsdp_state._device_handle.synchronize()
233
+ unpadded_numel = cast(
234
+ nn.Parameter, flat_param._unpadded_unsharded_size
235
+ ).numel()
236
+ tensor_state[state_name] = tensor_buffer[:unpadded_numel]
237
+ # Zero-dimension tensor state and non-tensor state: take this rank's
238
+ # value directly
239
+ else:
240
+ if _is_zero_dim_tensor(value):
241
+ zero_dim_tensor_state[state_name] = value.detach().clone()
242
+ else:
243
+ non_tensor_state[state_name] = value
244
+ return state
245
+
246
+
247
+ def _unflatten_communicated_optim_state(
248
+ fsdp_param_info: FSDPParamInfo,
249
+ state: _ConsolidatedOptimState,
250
+ shard_state: bool,
251
+ ) -> list[dict[str, Any]]:
252
+ """
253
+ Unflattens the communicated optimizer state (given by ``tensor_state``,
254
+ ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flat
255
+ parameter. This should only be called on the target rank.
256
+
257
+ Args:
258
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
259
+ mapping from FQN to original parameter index.
260
+ state (_ConsolidatedOptimState): Consolidated optimizer state.
261
+
262
+ Returns:
263
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
264
+ "state" part of the optimizer state dict corresponding to the
265
+ unflattened parameters comprising the flat parameter. The final
266
+ optimizer state dict will need to map these entries using the proper
267
+ unflattened parameter IDs.
268
+ """
269
+ fsdp_state = fsdp_param_info.state
270
+ handle = fsdp_param_info.handle
271
+ flat_param = handle.flat_param
272
+ unflat_param_state: list[dict[str, Any]] = []
273
+ flat_param_views: dict[str, Iterator] = {}
274
+ num_unflat_params = flat_param._num_params
275
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
276
+ state.tensor_state,
277
+ state.zero_dim_tensor_state,
278
+ state.non_tensor_state,
279
+ )
280
+
281
+ for _ in range(num_unflat_params):
282
+ unflat_state_param = {}
283
+ # Add positive-dimension tensor state: unflatten with views
284
+ for state_name, flat_tensor in sorted_items(tensor_state):
285
+ views_generated = state_name in flat_param_views
286
+ if not views_generated:
287
+ views = handle._get_unflat_views(flat_tensor)
288
+ flat_param_views[state_name] = views
289
+ else:
290
+ views = flat_param_views[state_name]
291
+ optim_state: Union[torch.Tensor, ShardedTensor, DTensor] = next(views)
292
+ if shard_state:
293
+ osd_config = fsdp_state._optim_state_dict_config
294
+ if getattr(osd_config, "_use_dtensor", False):
295
+ if fsdp_state._device_mesh is None:
296
+ raise AssertionError(
297
+ f"Expected _device_mesh to be not None, got {fsdp_state._device_mesh}"
298
+ )
299
+ optim_state = _ext_chunk_dtensor(
300
+ optim_state,
301
+ fsdp_state.rank,
302
+ fsdp_state._device_mesh,
303
+ fsdp_state._fsdp_extension,
304
+ )
305
+ else:
306
+ if fsdp_state.process_group is None:
307
+ raise AssertionError(
308
+ f"Expected process_group to be not None, got {fsdp_state.process_group}"
309
+ )
310
+ optim_state = _ext_chunk_tensor(
311
+ optim_state,
312
+ fsdp_state.rank,
313
+ fsdp_state.world_size,
314
+ fsdp_state._device_handle.device_count(),
315
+ fsdp_state.process_group,
316
+ fsdp_state._fsdp_extension,
317
+ )
318
+ unflat_state_param[state_name] = optim_state
319
+
320
+ # Add zero-dimension tensor state: take the target rank's value
321
+ unflat_state_param.update(sorted_items(zero_dim_tensor_state))
322
+ # Add non-tensor state: take the target rank's value
323
+ unflat_state_param.update(sorted_items(non_tensor_state))
324
+ unflat_param_state.append(unflat_state_param)
325
+ return unflat_param_state
326
+
327
+
328
+ def _broadcast_processed_state(
329
+ fsdp_state: _FSDPState,
330
+ optim_state: dict[str, Any],
331
+ group: Optional[dist.ProcessGroup],
332
+ ) -> dict[str, Any]:
333
+ objects: list[Any] = [None]
334
+ if dist.get_rank(group) == 0:
335
+ objects[0] = tree_map_only(
336
+ torch.Tensor,
337
+ lambda v: v.cpu() if v.dim() == 0 else _PosDimTensorInfo(v.shape, v.dtype), # type: ignore[union-attr]
338
+ optim_state,
339
+ )
340
+ dist.broadcast_object_list(objects, src=0, group=group)
341
+ if dist.get_rank(group) == 0:
342
+ return optim_state
343
+ else:
344
+ return objects[0]
345
+
346
+
347
+ def _broadcast_state(
348
+ fsdp_state: _FSDPState, state: Any, group: Optional[dist.ProcessGroup]
349
+ ) -> Any:
350
+ if dist.get_rank(group) == 0:
351
+ if not isinstance(state, torch.Tensor) or state.dim() == 0:
352
+ return state
353
+ tensor = state.to(fsdp_state.compute_device)
354
+ else:
355
+ if isinstance(state, torch.Tensor):
356
+ if state.dim() != 0:
357
+ raise AssertionError(
358
+ "For non-zero ranks, a tensor state should have zero dimension, "
359
+ f"but got the state with shape {state.shape}."
360
+ )
361
+ return state
362
+ elif not isinstance(state, _PosDimTensorInfo):
363
+ return state
364
+ tensor = torch.zeros(
365
+ state.shape, dtype=state.dtype, device=fsdp_state.compute_device
366
+ )
367
+ dist.broadcast(tensor, src=0, group=group)
368
+ return tensor
369
+
370
+
371
+ def _shard_orig_param_state(
372
+ fsdp_param_info: FSDPParamInfo,
373
+ fqn: str,
374
+ optim_state: dict[str, Any],
375
+ ) -> dict[str, Any]:
376
+ """
377
+ Shard the optimizer state for the original parameter with the name ``fqn``.
378
+ This API should only be used when ``use_orig_params`` is True.
379
+ """
380
+ if not optim_state:
381
+ return {}
382
+ fsdp_state = fsdp_param_info.state
383
+ flat_param = fsdp_param_info.handle.flat_param
384
+ param_idx = fsdp_param_info.param_indices[fqn]
385
+ shard_param_info = flat_param._shard_param_infos[param_idx] # type: ignore[attr-defined]
386
+ optim_state = _gather_state_dict(
387
+ optim_state, pg=fsdp_state.process_group, device=fsdp_state.compute_device
388
+ )
389
+ if not shard_param_info.in_shard:
390
+ return {}
391
+ # Flatten and shard the state.
392
+ new_optim_state: dict[str, Any] = {}
393
+ intra_param_start_idx = shard_param_info.intra_param_start_idx
394
+ intra_param_end_idx = shard_param_info.intra_param_end_idx
395
+ for state_name, value in optim_state.items():
396
+ if (
397
+ torch.is_tensor(value)
398
+ and value.dim() > 0
399
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
400
+ ):
401
+ value = value.flatten()[
402
+ intra_param_start_idx : intra_param_end_idx # type: ignore[operator]
403
+ + 1
404
+ ].clone()
405
+ new_optim_state[state_name] = value
406
+ return new_optim_state
407
+
408
+
409
+ def _flatten_optim_state_dict(
410
+ optim_state_dict: dict[str, Any],
411
+ model: nn.Module,
412
+ use_orig_params: bool = False,
413
+ optim: Optional[torch.optim.Optimizer] = None,
414
+ rank0_only: bool = False,
415
+ group: Optional[dist.ProcessGroup] = None,
416
+ ) -> dict[str, Any]:
417
+ """
418
+ Flattens the full optimizer state dict, still keying by unflattened parameter
419
+ names.
420
+
421
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
422
+ parameters but some of these parameters may be empty due to the sharding.
423
+ For a regular optim.Optimizer, states for those empty parameters will
424
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
425
+ will be raised on a rank even if it does not have all the states -- it is
426
+ valid and FSDP know how to aggregate them. However, FSDP has to ignore
427
+ handling those parameters that are not managed by FSDP and do not exist on
428
+ the local rank -- it is managed by other parallelism and FSDP does not
429
+ know ho to handle/aggregate them.
430
+
431
+ Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
432
+ flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
433
+ all the states even if the corresponding parameters are empty. To this end,
434
+ ``optim`` will be used to get the initial state of the empty parameters.
435
+ ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
436
+ NamedOptimizer.
437
+
438
+ Returns:
439
+ Dict[str, Any]: The flattened optimizer state dict.
440
+ """
441
+ SimpleProfiler.reset()
442
+
443
+ unflat_osd = optim_state_dict
444
+ if "state" not in unflat_osd and not rank0_only:
445
+ raise ValueError(
446
+ '`optim_state_dict` must have the keys "state"'
447
+ "to be a valid optimizer state dict"
448
+ )
449
+ param_to_fqns = _get_param_to_fqns(model)
450
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
451
+ fsdp_state = next(iter(fqn_to_fsdp_param_info.values())).state
452
+
453
+ # Broadcast unflat_osd without non-scalar tensor if rank0_only is True.
454
+ if rank0_only:
455
+ unflat_osd = _broadcast_processed_state(fsdp_state, unflat_osd, group=group)
456
+
457
+ # Construct the "state" part
458
+ flat_osd_state: dict[Union[_OptimStateKey, str], Any] = {}
459
+ unflat_osd_state = unflat_osd["state"]
460
+ all_state_keys = set(unflat_osd_state.keys())
461
+
462
+ for param, fqns in param_to_fqns.items():
463
+ fqn = fqns[0]
464
+ if fqn not in unflat_osd_state:
465
+ continue
466
+ all_state_keys.difference_update(fqns)
467
+
468
+ if rank0_only:
469
+ for fqn in fqns:
470
+ if not unflat_osd_state[fqn]:
471
+ continue
472
+ for state_name in unflat_osd_state[fqn]:
473
+ unflat_osd_state[fqn][state_name] = _broadcast_state(
474
+ fsdp_state, unflat_osd_state[fqn][state_name], group=group
475
+ )
476
+ fqn = fqns[0]
477
+ if fqn in fqn_to_fsdp_param_info:
478
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
479
+ if use_orig_params:
480
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
481
+ flat_state = _shard_orig_param_state(
482
+ fsdp_param_info,
483
+ fqn,
484
+ unflat_osd_state[fqn],
485
+ )
486
+ else:
487
+ flat_state = _flatten_optim_state(
488
+ fsdp_param_info,
489
+ unflat_osd_state,
490
+ fqns,
491
+ )
492
+ key = _OptimStateKey(tuple(fqns), True)
493
+ # Only include non-empty states since as expected by
494
+ # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
495
+ # or NamedOptimizer.
496
+ if flat_state:
497
+ flat_osd_state[key] = flat_state
498
+ elif use_orig_params:
499
+ if len(fqns) != 1:
500
+ raise AssertionError(
501
+ f"use_orig_params is True but there are multiple FQNs, {fqns}."
502
+ )
503
+ if optim is not None: # NamedOptimizer or KeyedOptimizer case.
504
+ state = optim.state.get(param, None) # type: ignore[call-overload]
505
+ if state is not None:
506
+ flat_osd_state[key] = copy.deepcopy(state)
507
+ else:
508
+ warnings.warn(
509
+ f"optim_state[{key}] is not on rank{fsdp_state.rank}.",
510
+ stacklevel=2,
511
+ )
512
+
513
+ else:
514
+ raise RuntimeError(
515
+ f"The state of {key} is empty. This should happen when "
516
+ "use_orig_params=True."
517
+ )
518
+ else: # do not flatten non-FSDP parameters' states
519
+ if len(fqns) != 1:
520
+ raise AssertionError(f"Expected len(fqns) == 1, got {len(fqns)}")
521
+ key = _OptimStateKey(tuple(fqns), False)
522
+ flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
523
+
524
+ if rank0_only:
525
+ for fqn in fqns:
526
+ if not unflat_osd_state[fqn]:
527
+ continue
528
+ for state_name, param_state in list(unflat_osd_state[fqn].items()):
529
+ if fsdp_state.rank > 0:
530
+ # Deference the tensor so that PyTorch can collect the memory.
531
+ del unflat_osd_state[fqn][state_name]
532
+ else:
533
+ # Move the tensor in the original osd back to CPU to make the
534
+ # original osd unaffected.
535
+ unflat_osd_state[fqn][state_name] = param_state.cpu()
536
+
537
+ # Handle user-defined state, states that are not associated with parameters.
538
+ for key in all_state_keys:
539
+ user_state = unflat_osd_state[key]
540
+ if isinstance(user_state, torch.Tensor) and rank0_only and use_orig_params:
541
+ user_state = _broadcast_state(fsdp_state, user_state, group=group)
542
+ flat_osd_state[key] = copy.copy(user_state)
543
+
544
+ SimpleProfiler.dump_and_reset("FSDP _flatten_optim_state_dict() profiling: ")
545
+ # Construct the "param_groups" part -- copy as is since it will be
546
+ # rekeyed later according to the target rank's optimizer
547
+ # Only copy param_groups if it exists in unflat_osd
548
+ if "param_groups" in unflat_osd:
549
+ flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
550
+ return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
551
+ else:
552
+ return {"state": flat_osd_state}
553
+
554
+
555
+ def _flatten_optim_state(
556
+ fsdp_param_info: FSDPParamInfo,
557
+ unflat_osd_state: dict[str, dict[str, Any]],
558
+ unflat_param_names: list[str],
559
+ ) -> dict[str, Any]:
560
+ """
561
+ Flattens the optimizer state in ``full_optim_state_dict`` for a single
562
+ flat parameter in ``fsdp_param_info`` corresponding to the unflattened
563
+ parameter names in ``unflat_param_names``.
564
+
565
+ Args:
566
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
567
+ mapping from FQN to original parameter index.
568
+ unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
569
+ optimizer state dict corresponding to the unflattened parameters.
570
+ unflat_param_names (List[str]): A :class:`list` of unflattened
571
+ parameter names corresponding to the flat parameter ``flat_param``.
572
+
573
+ Returns:
574
+ Dict[str, Any]: A :class:`dict` mapping state names to their values for
575
+ a particular flat parameter. The sharded optimizer state dict's "state"
576
+ part will map a key to this returned value.
577
+ """
578
+ fsdp_state = fsdp_param_info.state
579
+ handle = fsdp_param_info.handle
580
+ flat_param = handle.flat_param
581
+ num_unflat_params = len(unflat_param_names)
582
+ if num_unflat_params <= 0:
583
+ raise AssertionError(
584
+ "Expects at least one unflattened parameter corresponding to the flat parameter"
585
+ )
586
+ unflat_param_shapes = flat_param._shapes
587
+ num_unflat_param_shapes = len(unflat_param_shapes)
588
+ if num_unflat_params != num_unflat_param_shapes:
589
+ raise AssertionError(
590
+ f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
591
+ )
592
+
593
+ # Check if these unflattened parameters have any optimizer state
594
+ has_state = [
595
+ bool(unflat_param_name in unflat_osd_state)
596
+ for unflat_param_name in unflat_param_names
597
+ ]
598
+ # If none of the unflattened parameters comprising this flat parameter have
599
+ # any state, then we do not want an entry in the optimizer state dict
600
+ if not any(has_state):
601
+ return {} # no need to flatten any state
602
+ # There may still be some unflattened parameters with state and some
603
+ # without
604
+ unflat_param_states = [
605
+ _gather_state_dict(
606
+ unflat_osd_state[unflat_param_name],
607
+ pg=fsdp_state.process_group,
608
+ device=fsdp_state.compute_device,
609
+ )
610
+ if unflat_param_name in unflat_osd_state
611
+ else None
612
+ for unflat_param_name in unflat_param_names
613
+ ]
614
+ # Check that the unflattened parameters have the same state names
615
+ state_names = None
616
+ # pyrefly: ignore [bad-assignment]
617
+ for unflat_param_state in unflat_param_states:
618
+ if unflat_param_state is None:
619
+ continue
620
+ if state_names is None:
621
+ state_names = set(unflat_param_state.keys())
622
+ else:
623
+ if state_names != set(unflat_param_state.keys()):
624
+ raise ValueError(
625
+ "Differing optimizer state names for the unflattened "
626
+ f"parameters: {unflat_param_names}"
627
+ )
628
+ if state_names is None:
629
+ raise AssertionError(f"Expected state_names to be not None, got {state_names}")
630
+
631
+ # Flatten the state
632
+ flat_state: dict[str, Optional[torch.Tensor]] = {}
633
+ for state_name in state_names:
634
+ state_values = [
635
+ unflat_param_state[state_name] if unflat_param_state is not None else None
636
+ for unflat_param_state in unflat_param_states
637
+ ]
638
+ non_none_state_values = [v for v in state_values if v is not None]
639
+ # If all ranks have None, this is a None value
640
+ if not non_none_state_values:
641
+ flat_state[state_name] = None
642
+ continue
643
+ are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
644
+ for v in non_none_state_values:
645
+ are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
646
+ are_zero_dim_tensors &= _is_zero_dim_tensor(v)
647
+ are_non_tensors &= not torch.is_tensor(v)
648
+ types = {type(v) for v in non_none_state_values}
649
+ if len(types) != 1 or not (
650
+ are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
651
+ ):
652
+ raise ValueError(
653
+ f"Differing optimizer state types for state {state_name}, "
654
+ f"values {non_none_state_values}, and unflattened parameter "
655
+ f"names {unflat_param_names}"
656
+ )
657
+ if are_pos_dim_tensors:
658
+ flat_tensor = _flatten_tensor_optim_state(
659
+ state_name,
660
+ state_values, # type: ignore[arg-type]
661
+ unflat_param_names,
662
+ unflat_param_shapes,
663
+ handle,
664
+ )
665
+ # Shard the flattened tensor immediately to minimize max memory
666
+ # usage
667
+ if (
668
+ fsdp_state.world_size != 1
669
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
670
+ ):
671
+ sharded_flat_tensor, _ = FlatParamHandle._get_shard(
672
+ flat_tensor,
673
+ fsdp_state.rank,
674
+ fsdp_state.world_size,
675
+ )
676
+ else:
677
+ sharded_flat_tensor = flat_tensor
678
+ flat_state[state_name] = sharded_flat_tensor
679
+ elif are_zero_dim_tensors:
680
+ flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
681
+ state_name,
682
+ state_values, # type: ignore[arg-type]
683
+ unflat_param_names,
684
+ )
685
+ else:
686
+ if not are_non_tensors:
687
+ raise AssertionError(
688
+ f"Expected are_non_tensors to be True, got {are_non_tensors}"
689
+ )
690
+ flat_state[state_name] = _flatten_non_tensor_optim_state(
691
+ state_name,
692
+ state_values,
693
+ unflat_param_names,
694
+ )
695
+
696
+ return flat_state
697
+
698
+
699
+ def _flatten_tensor_optim_state(
700
+ state_name: str,
701
+ pos_dim_tensors: list[torch.Tensor],
702
+ unflat_param_names: list[str],
703
+ unflat_param_shapes: Sequence[torch.Size],
704
+ handle: FlatParamHandle,
705
+ ) -> torch.Tensor:
706
+ """
707
+ Flattens the positive-dimension tensor optimizer state given by the values
708
+ ``tensors`` for the state ``state_name`` for a single flat parameter
709
+ from ``handle`` corresponding to the unflattened parameter names
710
+ ``unflat_param_names`` and unflatted parameter shapes
711
+ ``unflat_param_shapes``. This flattens each unflattened parameter's tensor
712
+ state into one tensor.
713
+
714
+ NOTE: We use zero tensors for any unflattened parameters without state
715
+ since some value is required to fill those entries. This assumes that the
716
+ zero tensor is mathematically equivalent to having no state, which is true
717
+ for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
718
+ optimizers.
719
+
720
+ Args:
721
+ state_name (str): Optimizer state name.
722
+ pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
723
+ optimizer state values for the unflattened parameters corresponding
724
+ to the single flat parameter.
725
+ unflat_param_names (List[str]): A :class:`list` of unflattened
726
+ parameter names corresponding to the single flat parameter.
727
+ unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
728
+ corresponding to the single flat parameter.
729
+ handle (FlatParamHandle): The flat parameter's handle.
730
+
731
+ Returns:
732
+ torch.Tensor: A flat tensor containing the optimizer state
733
+ corresponding to ``state_name`` constructed by concatenating the
734
+ unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
735
+ tensors for any unflattened parameters without the state).
736
+ """
737
+ flat_param = handle.flat_param
738
+ non_none_tensors = [t for t in pos_dim_tensors if t is not None]
739
+ # Check that all are tensors with the same dtype
740
+ dtypes = {t.dtype for t in non_none_tensors}
741
+ if len(dtypes) != 1:
742
+ raise ValueError(
743
+ "All unflattened parameters comprising a single flat "
744
+ "parameter must have positive-dimension tensor state with the "
745
+ f"same dtype but got dtypes {dtypes} for state {state_name} and "
746
+ f"unflattened parameter names {unflat_param_names}"
747
+ )
748
+ dtype = next(iter(dtypes))
749
+ # Check that each tensor state matches its parameter's shape
750
+ for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes):
751
+ if tensor is None and len(shape) == 0:
752
+ raise ValueError("Flattening a zero-dimension parameter is not supported")
753
+ elif tensor is not None and tensor.shape != shape:
754
+ raise ValueError(
755
+ "Tensor optimizer state does not have same shape as its "
756
+ f"parameter: {tensor.shape} {shape}"
757
+ )
758
+ # Flatten the tensor states: we do not need to add any right-hand-side
759
+ # padding since the flat optimizer state tensor is sharded via
760
+ # `_get_shard()`, which pads the shard as needed (just like for the flat
761
+ # parameter)
762
+ cpu_device = torch.device("cpu")
763
+ tensors_to_flatten = [
764
+ torch.flatten(state_value.to(cpu_device))
765
+ if state_value is not None
766
+ else torch.flatten(
767
+ torch.zeros(
768
+ size=shape,
769
+ dtype=dtype,
770
+ device=cpu_device,
771
+ )
772
+ )
773
+ for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes)
774
+ ]
775
+ flat_tensor = handle.flatten_tensors(tensors_to_flatten, handle._aligned_numel)
776
+ flat_param_shape = flat_param._unpadded_unsharded_size # type: ignore[attr-defined]
777
+ if flat_tensor.shape != flat_param_shape:
778
+ raise AssertionError(
779
+ f"tensor optim state: {flat_tensor.shape} flat parameter: {flat_param_shape}"
780
+ )
781
+ return flat_tensor
782
+
783
+
784
+ def _flatten_zero_dim_tensor_optim_state(
785
+ state_name: str,
786
+ zero_dim_tensors: list[torch.Tensor],
787
+ unflat_param_names: list[str],
788
+ ) -> torch.Tensor:
789
+ """
790
+ Flattens the zero-dimension tensor optimizer state given by the values
791
+ ``zero_dim_tensors`` for the state ``state_name`` for a single flat
792
+ parameter corresponding to the unflattened parameter names
793
+ ``unflat_param_names`` by enforcing that all tensors are the same and using
794
+ that common value.
795
+
796
+ NOTE: The requirement that the tensors are the same across all unflattened
797
+ parameters comprising the flat parameter is needed to maintain the
798
+ invariant that FSDP performs the same computation as its non-sharded
799
+ equivalent. This means that none of the unflattened parameters can be
800
+ missing this state since imposing a value may differ from having no value.
801
+ For example, for Adam's "step", no value means maximum bias correction,
802
+ while having some positive value means less bias correction.
803
+
804
+ Args:
805
+ state_name (str): Optimizer state name.
806
+ zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
807
+ for the unflattened parameters corresponding to the single
808
+ flat parameter.
809
+ unflat_param_names (List[str]): A :class:`list` of unflattened
810
+ parameter names corresponding to the single flat parameter.
811
+
812
+ Returns:
813
+ torch.Tensor: A zero-dimensional tensor giving the value of the state
814
+ ``state_name`` for all unflattened parameters corresponding to the
815
+ names ``unflat_param_names``.
816
+ """
817
+ non_none_tensors = [t for t in zero_dim_tensors if t is not None]
818
+ # Enforce that all have the same value and dtype
819
+ values_set = {t.item() if t is not None else None for t in zero_dim_tensors}
820
+ dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors}
821
+ if (
822
+ len(non_none_tensors) != len(zero_dim_tensors)
823
+ or len(values_set) != 1
824
+ or len(dtypes) != 1
825
+ ):
826
+ raise ValueError(
827
+ "All unflattened parameters comprising a single flat "
828
+ "parameter must have scalar state with the same value and dtype "
829
+ f"but got values {values_set} and dtypes {dtypes} for state "
830
+ f"{state_name} and unflattened parameter names "
831
+ f"{unflat_param_names}"
832
+ )
833
+ value = next(iter(values_set))
834
+ dtype = next(iter(dtypes))
835
+ return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
836
+
837
+
838
+ def _flatten_non_tensor_optim_state(
839
+ state_name: str,
840
+ non_tensors: list[Any],
841
+ unflat_param_names: list[str],
842
+ ) -> Any:
843
+ """
844
+ Flattens the non-tensor optimizer state given by the values ``non_tensors``
845
+ for the state ``state_name`` for a single flat parameter corresponding
846
+ to the unflattened parameter names ``unflat_param_names`` by enforcing that
847
+ all values are the same and using that common value.
848
+
849
+ See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
850
+
851
+ Args:
852
+ state_name (str): Optimizer state name.
853
+ non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
854
+ parameters corresponding to the single flat parameter.
855
+ unflat_param_names (List[str]): A :class:`list` of unflattened
856
+ parameter names corresponding to the single flat parameter.
857
+
858
+ Returns:
859
+ Any: A non-tensor giving the value of the state ``state_name`` for all
860
+ unflattened parameters corresponding to the names
861
+ ``unflat_param_names``.
862
+ """
863
+ non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
864
+ # Enforce that all have the same value (same type already checked)
865
+ non_tensor_set = set(non_tensors)
866
+ if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1:
867
+ raise ValueError(
868
+ "All unflattened parameters comprising a single flat "
869
+ "parameter must have scalar state with the same value and dtype "
870
+ f"but got values {non_tensor_set} for state {state_name} and "
871
+ f"unflattened parameter names {unflat_param_names}"
872
+ )
873
+ non_tensor = next(iter(non_tensor_set))
874
+ return non_tensor
875
+
876
+
877
+ def _rekey_sharded_optim_state_dict(
878
+ sharded_osd: dict[str, Any],
879
+ model: nn.Module,
880
+ optim: torch.optim.Optimizer,
881
+ optim_input: Optional[
882
+ Union[
883
+ list[dict[str, Any]],
884
+ Iterable[nn.Parameter],
885
+ ]
886
+ ],
887
+ using_optim_input: bool,
888
+ is_named_optimizer: bool = False,
889
+ ) -> dict[str, Any]:
890
+ """
891
+ Rekeys the optimizer state dict from unflattened parameter names to flat
892
+ parameter IDs according to the calling rank's ``optim``, which may be
893
+ different across ranks. In particular, the unflattened parameter names are
894
+ represented as :class:`_OptimStateKey` s.
895
+ """
896
+ param_to_fqns = _get_param_to_fqns(model)
897
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
898
+ param_to_param_key: dict[nn.Parameter, Union[int, str]] = cast(
899
+ dict[nn.Parameter, Union[int, str]],
900
+ (
901
+ _get_param_to_param_id_from_optim_input(model, optim_input)
902
+ if using_optim_input
903
+ else _get_param_to_param_key(
904
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
905
+ )
906
+ ),
907
+ )
908
+ # All parameter keys in `param_to_param_key` should be in
909
+ # `param_to_fqns` -- strict inequality follows when not all parameters are
910
+ # passed to the optimizer
911
+ if len(param_to_param_key) > len(param_to_fqns):
912
+ raise AssertionError(
913
+ f"Expected len(param_to_param_key) <= len(param_to_fqns), got {len(param_to_param_key)} > {len(param_to_fqns)}"
914
+ )
915
+
916
+ unflat_param_names_to_flat_param_key: dict[
917
+ tuple[str, ...], Union[int, str]
918
+ ] = {} # for "state"
919
+ unflat_param_name_to_flat_param_key: dict[
920
+ str, Union[int, str]
921
+ ] = {} # for "param_groups"
922
+ for param, unflat_param_names in param_to_fqns.items():
923
+ if param not in param_to_param_key:
924
+ # This parameter was not passed to the optimizer
925
+ continue
926
+ flat_param_key = param_to_param_key[param]
927
+ unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
928
+ for unflat_param_name in unflat_param_names:
929
+ unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
930
+
931
+ sharded_osd_state = sharded_osd["state"]
932
+ rekeyed_osd_state: dict[Union[str, int], Any] = {}
933
+ for key, param_state in sharded_osd_state.items():
934
+ if isinstance(key, str):
935
+ rekeyed_osd_state[key] = param_state
936
+ continue
937
+ flat_param_key = unflat_param_names_to_flat_param_key.get(
938
+ key.unflat_param_names, key.unflat_param_names
939
+ )
940
+ # pyrefly: ignore [unsupported-operation]
941
+ rekeyed_osd_state[flat_param_key] = param_state
942
+
943
+ # Only process param_groups if it exists in sharded_osd
944
+ if "param_groups" in sharded_osd:
945
+ rekeyed_osd_param_groups: list[dict[str, Any]] = []
946
+ for unflat_param_group in sharded_osd["param_groups"]:
947
+ flat_param_group = copy.deepcopy(unflat_param_group)
948
+ flat_param_keys = sorted(
949
+ {
950
+ unflat_param_name_to_flat_param_key[unflat_param_name]
951
+ for unflat_param_name in unflat_param_group["params"]
952
+ }
953
+ )
954
+ flat_param_group["params"] = flat_param_keys
955
+ rekeyed_osd_param_groups.append(flat_param_group)
956
+ return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
957
+ else:
958
+ return {"state": rekeyed_osd_state}
959
+
960
+
961
+ def _get_param_id_to_param_from_optim_input(
962
+ model: nn.Module,
963
+ optim_input: Optional[
964
+ Union[
965
+ list[dict[str, Any]],
966
+ Iterable[nn.Parameter],
967
+ ]
968
+ ] = None,
969
+ ) -> dict[int, nn.Parameter]:
970
+ """
971
+ Constructs a mapping from parameter IDs to parameters. This may be used
972
+ both for models with ``FlatParameter`` s and without.
973
+
974
+ NOTE: This method is only preserved for backward compatibility. The method
975
+ :meth:`_get_param_key_to_param` is the preferred code path that does not
976
+ rely on ``optim_input``.
977
+
978
+ NOTE: We critically assume that, whether the optimizer input is a list of
979
+ parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
980
+ enumerates the parameter IDs in order. In other words, for a parameter list
981
+ input, the parameter IDs should be in that list order, and for a parameter
982
+ groups input, the parameter IDs should be in order within each parameter
983
+ group and in order across parameter groups.
984
+
985
+ Args:
986
+ model (nn.Module): Model whose parameters are passed into the
987
+ optimizer.
988
+ optim_input (Optional[Union[List[Dict[str, Any]],
989
+ Iterable[nn.Parameter]]]): Input passed into the optimizer
990
+ representing either a :class:`list` of parameter groups or an
991
+ iterable of parameters; if ``None``, then this method assumes the
992
+ input was ``model.parameters()``. (Default: ``None``)
993
+
994
+ Returns:
995
+ List[nn.Parameter]: Mapping from parameter IDs to parameters,
996
+ where the parameter ID is implicitly the index in the :class:`list`.
997
+ """
998
+ # Assume the standard case of passing `model.parameters()` to the optimizer
999
+ # if `optim_input` is not specified
1000
+ if optim_input is None:
1001
+ return dict(enumerate(model.parameters()))
1002
+ try:
1003
+ # pyrefly: ignore [no-matching-overload]
1004
+ # pyrefly: ignore [redundant-cast]
1005
+ params = cast(list[nn.Parameter], list(optim_input))
1006
+ except TypeError as e:
1007
+ raise TypeError(
1008
+ "Optimizer input should be an iterable of Tensors or dicts, "
1009
+ f"but got {optim_input}"
1010
+ ) from e
1011
+ if len(params) == 0:
1012
+ raise ValueError("Optimizer input should not be empty")
1013
+
1014
+ # Check if the optimizer input represents tensors or parameter groups
1015
+ all_tensors = True
1016
+ all_dicts = True
1017
+ for param in params:
1018
+ all_tensors &= isinstance(param, torch.Tensor)
1019
+ all_dicts &= isinstance(param, dict)
1020
+ if not all_tensors and not all_dicts:
1021
+ raise TypeError("Optimizer input should be an iterable of Tensors or dicts")
1022
+ if all_tensors:
1023
+ return dict(enumerate(params))
1024
+ if not all_dicts:
1025
+ raise AssertionError(f"Expected all_dicts to be True, got {all_dicts}")
1026
+ param_id_to_param: list[nn.Parameter] = []
1027
+ for param_group in params:
1028
+ has_params_key = "params" in param_group # type: ignore[operator]
1029
+ if not has_params_key:
1030
+ raise AssertionError(
1031
+ 'A parameter group should map "params" to a list of the parameters in the group'
1032
+ )
1033
+ # Implicitly map `flat_param_id` (current length of the list) to
1034
+ # `param`
1035
+ param_id_to_param.extend(param_group["params"]) # type: ignore[index]
1036
+ return dict(enumerate(param_id_to_param))
1037
+
1038
+
1039
+ def _get_flat_param_to_fqn(model: torch.nn.Module) -> dict[FlatParameter, str]:
1040
+ """
1041
+ Constructs a mapping from ``FlatParameter`` to a cleaned (devoid of prefixes
1042
+ from wrappers) fully qualified name (FQN). Note that this FQN is "non-canonical"
1043
+ because ``FlatParameter`` s do not come from the original module but are
1044
+ registered only after FSDP has been applied. This function returns the FSDP-given
1045
+ name for the ``FlatParameter`` (usually module._flat_param) as opposed to the
1046
+ canonical FQNs returned for ``FlatParameter`` s in ``_common_utils._get_param_to_fqns(...)``).
1047
+
1048
+ Consequently, this function will only return a non-empty mapping if FSDP was
1049
+ applied with ``use_orig_params=False`` as, otherwise, the original parameters
1050
+ are used within the module and there would be no ``FlatParameter`` s in the module.
1051
+
1052
+ """
1053
+
1054
+ def module_fn(module, prefix, tree_level, flat_param_to_fqn):
1055
+ for param_name, param in _named_parameters_with_duplicates(
1056
+ module, recurse=False
1057
+ ):
1058
+ if not isinstance(param, FlatParameter):
1059
+ continue
1060
+ fqn = clean_tensor_name(prefix + param_name)
1061
+ flat_param_to_fqn[param] = fqn
1062
+
1063
+ def return_fn(flat_param_to_fqn):
1064
+ return flat_param_to_fqn
1065
+
1066
+ flat_param_to_fqn_ret: dict[FlatParameter, str] = {}
1067
+ return _apply_to_modules(
1068
+ model,
1069
+ module_fn,
1070
+ return_fn,
1071
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
1072
+ flat_param_to_fqn_ret,
1073
+ )
1074
+
1075
+
1076
+ def _get_param_key_to_param(
1077
+ optim: torch.optim.Optimizer,
1078
+ model: Optional[nn.Module] = None,
1079
+ is_named_optimizer: bool = False,
1080
+ param_to_fqns: Optional[dict[nn.Parameter, list[str]]] = None,
1081
+ flat_param_to_fqn: Optional[dict[FlatParameter, str]] = None,
1082
+ ) -> dict[Union[int, str], nn.Parameter]:
1083
+ """
1084
+ Constructs a mapping from parameter keys to parameters. For the regular
1085
+ optimizers, the keys are parameter IDs. For NamedOptimizer, the keys
1086
+ are FQNs. This API may be used both for models with ``FlatParameter`` s and
1087
+ without.
1088
+ """
1089
+ clean_fqn_to_curr_fqn: dict[str, str] = {}
1090
+ if is_named_optimizer:
1091
+ if param_to_fqns is None or flat_param_to_fqn is None:
1092
+ raise AssertionError(
1093
+ "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None."
1094
+ )
1095
+ if model is None:
1096
+ raise AssertionError(f"Expected model to be not None, got {model}")
1097
+ for key, _ in _named_parameters_with_duplicates(model):
1098
+ clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key
1099
+
1100
+ param_key_to_param: dict[Union[str, int], nn.Parameter] = {}
1101
+ pid = 0
1102
+ for param_group in optim.param_groups:
1103
+ if is_named_optimizer:
1104
+ for param in param_group["params"]:
1105
+ if flat_param_to_fqn is None:
1106
+ raise AssertionError(
1107
+ f"Expected flat_param_to_fqn to be not None, got {flat_param_to_fqn}"
1108
+ )
1109
+ if param in flat_param_to_fqn:
1110
+ # FlatParameter case
1111
+ key = flat_param_to_fqn[param]
1112
+ else:
1113
+ if param_to_fqns is None:
1114
+ raise AssertionError(
1115
+ f"Expected param_to_fqns to be not None, got {param_to_fqns}"
1116
+ )
1117
+ # use_orig_params case
1118
+ if len(param_to_fqns[param]) != 1:
1119
+ raise AssertionError(
1120
+ f"Expected len(param_to_fqns[param]) == 1, got {len(param_to_fqns[param])}"
1121
+ )
1122
+ key = param_to_fqns[param][0]
1123
+ try:
1124
+ key = clean_fqn_to_curr_fqn[key]
1125
+ except KeyError as e:
1126
+ raise KeyError(
1127
+ f"Can't find {key} from {list(clean_fqn_to_curr_fqn.keys())}."
1128
+ ) from e
1129
+ param_key_to_param[key] = param
1130
+ else:
1131
+ for param in param_group["params"]:
1132
+ param_key_to_param[pid] = param
1133
+ pid += 1
1134
+
1135
+ return param_key_to_param
1136
+
1137
+
1138
+ def _get_param_to_param_key(
1139
+ optim: torch.optim.Optimizer,
1140
+ model: Optional[nn.Module] = None,
1141
+ is_named_optimizer: bool = False,
1142
+ param_to_fqns: Optional[dict[nn.Parameter, list[str]]] = None,
1143
+ flat_param_to_fqn: Optional[dict[FlatParameter, str]] = None,
1144
+ ) -> dict[nn.Parameter, Union[int, str]]:
1145
+ """
1146
+ Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API
1147
+ only supports the case where `optim` is a regular optimizer, not NamedOptimizer.
1148
+ So the parameter keys will be parameter ids.
1149
+ """
1150
+ param_id_to_param = _get_param_key_to_param(
1151
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1152
+ )
1153
+ return {param: param_id for param_id, param in param_id_to_param.items()}
1154
+
1155
+
1156
+ def _get_param_to_param_id_from_optim_input(
1157
+ model: nn.Module,
1158
+ optim_input: Optional[
1159
+ Union[
1160
+ list[dict[str, Any]],
1161
+ Iterable[nn.Parameter],
1162
+ ]
1163
+ ] = None,
1164
+ ) -> dict[nn.Parameter, int]:
1165
+ """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`."""
1166
+ param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input)
1167
+ return {param: param_id for param_id, param in param_id_to_param.items()}
1168
+
1169
+
1170
+ def _check_missing_keys_on_rank(
1171
+ r0_optim_state_keys: list[_OptimStateKey],
1172
+ optim_state_key_to_param_key: dict[_OptimStateKey, Union[str, int]],
1173
+ param_key_to_param: dict[Union[str, int], nn.Parameter],
1174
+ group: Optional[dist.ProcessGroup],
1175
+ ) -> None:
1176
+ # Ensure that all ranks have at least the optimizer states needed by
1177
+ # rank 0's optimizer
1178
+ missing_keys: list[_OptimStateKey] = []
1179
+ for r0_optim_state_key in r0_optim_state_keys:
1180
+ if r0_optim_state_key not in optim_state_key_to_param_key:
1181
+ # A parameter from rank 0's optimizer does not exist for this
1182
+ # rank's optimizer
1183
+ missing_keys.append(r0_optim_state_key)
1184
+ continue
1185
+ param_key = optim_state_key_to_param_key[r0_optim_state_key]
1186
+ if isinstance(param_key, int):
1187
+ if not (param_key >= 0 and param_key < len(param_key_to_param)):
1188
+ raise AssertionError("Check the `param_key_to_param` construction")
1189
+ # We cannot use FSDPState.compute_device as this API is a global view.
1190
+ device = _get_pg_default_device(group)
1191
+ num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device)
1192
+ dist.all_reduce(num_missing, group=group)
1193
+ if num_missing.item() > 0:
1194
+ obj_list = [None for _ in range(dist.get_world_size(group))]
1195
+ dist.all_gather_object(obj_list, missing_keys, group=group)
1196
+ error_msg = (
1197
+ "FSDP currently requires each rank to have at least the "
1198
+ "optimizer states needed by rank 0's optimizer but some ranks "
1199
+ "are missing some of those states"
1200
+ )
1201
+ for rank, keys in enumerate(obj_list):
1202
+ keys = cast(list[_OptimStateKey], keys)
1203
+ if len(keys) > 0:
1204
+ error_msg += (
1205
+ f"\nRank {rank} is missing states for the parameters: "
1206
+ f"{[key.unflat_param_names for key in keys]}"
1207
+ )
1208
+ raise RuntimeError(error_msg)
1209
+
1210
+
1211
+ def _map_param_key_to_optim_keys(
1212
+ optim_state_dict: dict[str, Any],
1213
+ group: Optional[dist.ProcessGroup],
1214
+ param_key_to_param: dict[Union[int, str], nn.Parameter],
1215
+ param_to_fqns: dict[nn.Parameter, list[str]],
1216
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1217
+ merge_keys: bool = False,
1218
+ ) -> tuple[list[_OptimStateKey], dict[_OptimStateKey, Union[int, str]]]:
1219
+ """
1220
+ Construct the local mapping between the ``_OptimStateKey`` and parameter keys
1221
+ and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0
1222
+ must contain all the ``_OptimStateKey``, an exception will be raised otherwise.
1223
+ Note that ``merge_keys`` should equal to ``use_orig_params``.
1224
+ """
1225
+ rank = dist.get_rank(group)
1226
+ optim_state_key_to_param_key: dict[_OptimStateKey, Union[int, str]] = {} # local
1227
+ all_optim_state_keys: list[_OptimStateKey] = []
1228
+
1229
+ for param_key, param in param_key_to_param.items():
1230
+ # Do not include parameters without state to avoid empty mappings
1231
+ # just like in normal `torch.optim.Optimizer.state_dict()`
1232
+ if param_key not in optim_state_dict["state"]:
1233
+ continue
1234
+ fqns = param_to_fqns[param]
1235
+ is_fsdp_managed = isinstance(param, FlatParameter)
1236
+ if is_fsdp_managed:
1237
+ if fqns[0] not in fqn_to_fsdp_param_info:
1238
+ raise AssertionError(
1239
+ f"Expected {fqns[0]} to be in fqn_to_fsdp_param_info, got keys: {list(fqn_to_fsdp_param_info.keys())}"
1240
+ )
1241
+ is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info
1242
+ optim_state_key = _OptimStateKey(
1243
+ unflat_param_names=tuple(fqns),
1244
+ is_fsdp_managed=is_fsdp_managed,
1245
+ )
1246
+ if rank == 0 or merge_keys:
1247
+ all_optim_state_keys.append(optim_state_key)
1248
+ optim_state_key_to_param_key[optim_state_key] = param_key
1249
+
1250
+ if merge_keys:
1251
+ all_keys: list[list[_OptimStateKey]] = [
1252
+ [] for _ in range(dist.get_world_size(group))
1253
+ ]
1254
+ dist.all_gather_object(all_keys, all_optim_state_keys, group=group)
1255
+ merge_all_optim_state_keys = [*chain.from_iterable(all_keys)]
1256
+ all_optim_state_keys = sorted(set(merge_all_optim_state_keys))
1257
+ else:
1258
+ key_obj_list: list[Optional[list[_OptimStateKey]]] = (
1259
+ [all_optim_state_keys] if rank == 0 else [None]
1260
+ )
1261
+ dist.broadcast_object_list(key_obj_list, src=0, group=group)
1262
+ if key_obj_list[0] is None:
1263
+ raise AssertionError(
1264
+ f"Expected key_obj_list[0] to be not None, got {key_obj_list[0]}"
1265
+ )
1266
+ all_optim_state_keys = key_obj_list[0]
1267
+ _check_missing_keys_on_rank(
1268
+ all_optim_state_keys,
1269
+ optim_state_key_to_param_key,
1270
+ param_key_to_param,
1271
+ group,
1272
+ )
1273
+
1274
+ return all_optim_state_keys, optim_state_key_to_param_key
1275
+
1276
+
1277
+ def _unflatten_param_groups(
1278
+ state_dict: dict[str, Any],
1279
+ param_key_to_param: dict[Union[int, str], nn.Parameter],
1280
+ param_to_fqns: dict[nn.Parameter, list[str]],
1281
+ ) -> list[dict[str, Any]]:
1282
+ param_groups: list[dict[str, Any]] = []
1283
+ for flat_param_group in state_dict["param_groups"]:
1284
+ unflat_param_group = copy.deepcopy(flat_param_group)
1285
+ param_group_params = [
1286
+ param_key_to_param[flat_param_key]
1287
+ for flat_param_key in flat_param_group["params"]
1288
+ ]
1289
+ nested_unflat_param_names = [
1290
+ param_to_fqns[param] for param in param_group_params
1291
+ ]
1292
+ unflat_param_group["params"] = [
1293
+ *chain.from_iterable(nested_unflat_param_names)
1294
+ ] # flatten the list of lists
1295
+ param_groups.append(unflat_param_group)
1296
+ return param_groups
1297
+
1298
+
1299
+ def _is_named_optimizer(optim_state_dict: dict[str, Any]) -> bool:
1300
+ """
1301
+ Returns whether the state_dict is from a NamedOptimizer.
1302
+ This function checks that the keys in the state_dict['state'] are strings
1303
+ (which usually are FQNs) versus integers (which usually refer to param_ids
1304
+ from a vanilla torch.optim.Optimizer).
1305
+ """
1306
+ state = optim_state_dict.get("state")
1307
+ if not state:
1308
+ # If we cannot find a state, assume it is not NamedOptimizer as
1309
+ # NamedOptimizer has eager initialization.
1310
+ return False
1311
+ try:
1312
+ key = next(iter(state.keys()))
1313
+ except Exception as e:
1314
+ raise Exception(optim_state_dict) from e # noqa: TRY002
1315
+ return isinstance(key, str)
1316
+
1317
+
1318
+ @dataclass
1319
+ class StateInfo:
1320
+ # The key of these dictionaries are the state name, e.g., `exp_avg`.
1321
+ tensors: dict[str, _PosDimTensorInfo]
1322
+ scalar_tensors: dict[str, torch.Tensor]
1323
+ non_tensors: dict[str, Any]
1324
+
1325
+
1326
+ def _allgather_state_info(
1327
+ fsdp_state: _FSDPState,
1328
+ input_states: dict[str, Any],
1329
+ ) -> list[dict[str, StateInfo]]:
1330
+ """
1331
+ Given the ``input_states``, allgather StateInfo for each state. The function
1332
+ uses all_gather_object to gather StateInfo so no GPU tensors are sent.
1333
+ """
1334
+
1335
+ processed_state_dict: dict[str, StateInfo] = {}
1336
+ gathered_state_info: list[dict[str, StateInfo]] = [
1337
+ {} for _ in range(fsdp_state.world_size)
1338
+ ]
1339
+
1340
+ for fqn, optim_state in input_states.items():
1341
+ # Allgather the scalar tensor state, non-tensor states and tensors metadata.
1342
+ processed_state = StateInfo({}, {}, {})
1343
+ for state_name, value in sorted_items(optim_state):
1344
+ if torch.is_tensor(value):
1345
+ if value.dim() == 0:
1346
+ # Ensure that `step` is on CPU.
1347
+ processed_state.scalar_tensors[state_name] = value.cpu()
1348
+ else:
1349
+ processed_state.tensors[state_name] = _PosDimTensorInfo(
1350
+ value.shape, value.dtype
1351
+ )
1352
+ else:
1353
+ processed_state.non_tensors[state_name] = value
1354
+ processed_state_dict[fqn] = processed_state
1355
+ dist.all_gather_object(
1356
+ gathered_state_info,
1357
+ processed_state_dict,
1358
+ group=fsdp_state.process_group,
1359
+ )
1360
+ return gathered_state_info
1361
+
1362
+
1363
+ def _convert_all_state_info(
1364
+ fsdp_param_info: FSDPParamInfo,
1365
+ gathered_state_info: list[dict[str, StateInfo]],
1366
+ input_states: dict[str, Any],
1367
+ output_states: dict[str, dict[str, Any]],
1368
+ ) -> tuple[Optional[torch.dtype], dict[str, list[Optional[torch.Tensor]]]]:
1369
+ """
1370
+ Given the ``gathered_state_info`` and ``input_states``, the API converted
1371
+ the StateInfo into the original state if the state is not a non-scalar
1372
+ tensor. For a multi-dimensional tensor, the local state will be stored in
1373
+ ``state_buffer`` in a correct order for later allgather purpose.
1374
+ """
1375
+
1376
+ state_buffers: dict[str, list[Optional[torch.Tensor]]] = {}
1377
+
1378
+ for fqn, gathered_state in output_states.items():
1379
+ state_info = [s[fqn] for s in gathered_state_info]
1380
+ all_tensor_states = sorted({n for state in state_info for n in state.tensors})
1381
+ empty_ranks: set[int] = set()
1382
+ dtype: Optional[torch.dtype] = None
1383
+ # First check all the non-scalar states and get the information of
1384
+ # states on each rank.
1385
+ for state_name in all_tensor_states:
1386
+ numels = []
1387
+ _empty_ranks: set[int] = set()
1388
+ for rank, object_state in enumerate(state_info):
1389
+ numels.append(0)
1390
+ info = object_state.tensors.get(state_name, None)
1391
+ if info is not None:
1392
+ numels[-1] = info.shape.numel()
1393
+ if not dtype:
1394
+ dtype = info.dtype
1395
+ else:
1396
+ if dtype != info.dtype:
1397
+ raise AssertionError(
1398
+ f"Expected dtype == info.dtype, got {dtype} != {info.dtype}"
1399
+ )
1400
+ if numels[-1] == 0:
1401
+ _empty_ranks.add(rank)
1402
+
1403
+ if not (not empty_ranks or empty_ranks == _empty_ranks):
1404
+ raise AssertionError(
1405
+ f"Expected empty_ranks to be empty or equal to _empty_ranks, got {empty_ranks} vs {_empty_ranks}"
1406
+ )
1407
+ empty_ranks = _empty_ranks
1408
+ if state_name not in state_buffers:
1409
+ state_buffers[state_name] = [
1410
+ None for _ in fsdp_param_info.param_indices
1411
+ ]
1412
+ local_state = input_states[fqn].get(state_name, None)
1413
+ # N.B. We need to move the state to compute_device. The reason is
1414
+ # not yet clear and we need to figure out why the state may be on a
1415
+ # different device.
1416
+ if local_state is not None:
1417
+ local_state = local_state.to(fsdp_param_info.state.compute_device)
1418
+ state_buffers[state_name][fsdp_param_info.param_indices[fqn]] = local_state
1419
+
1420
+ # Restoring the scalar and non-tensor states. If the corresponding
1421
+ # non-scalar states do not exist on the rank, we also skip the scalar
1422
+ # non-tensor states on that rank.
1423
+ for rank, object_state in enumerate(state_info):
1424
+ if rank in empty_ranks:
1425
+ continue
1426
+ for name, non_tensor_value in object_state.non_tensors.items():
1427
+ curr_non_tensor_value = gathered_state.get(name, None)
1428
+ if not (
1429
+ curr_non_tensor_value is None
1430
+ or curr_non_tensor_value == non_tensor_value
1431
+ ):
1432
+ raise AssertionError(
1433
+ f"Rank {rank} has different values for {name}: {non_tensor_value}."
1434
+ + f" Other ranks: {curr_non_tensor_value}"
1435
+ )
1436
+ gathered_state[name] = non_tensor_value
1437
+
1438
+ for name, scalar_tensor_value in object_state.scalar_tensors.items():
1439
+ curr_scalar_tensor_value = gathered_state.get(name, None)
1440
+ if not (
1441
+ curr_scalar_tensor_value is None
1442
+ or torch.equal(scalar_tensor_value, curr_scalar_tensor_value)
1443
+ ):
1444
+ raise AssertionError(
1445
+ f"Rank {rank} has different values for {name}: {scalar_tensor_value}."
1446
+ + f" Other ranks: {curr_scalar_tensor_value}"
1447
+ )
1448
+ gathered_state[name] = scalar_tensor_value
1449
+
1450
+ return dtype, state_buffers # type: ignore[possibly-undefined]
1451
+
1452
+
1453
+ def _unflatten_orig_param_states(
1454
+ fsdp_param_info: FSDPParamInfo,
1455
+ output_states: dict[str, dict[str, Any]],
1456
+ state_name: str,
1457
+ shard_state: bool,
1458
+ to_save: bool,
1459
+ cpu_offload: bool,
1460
+ ) -> None:
1461
+ """
1462
+ Given a output state dict, ``output_states``, which the keys are FQNs to the
1463
+ original parameters (not FlatParameters nor parameter ID), and the values
1464
+ are gathered states, unflatten the states to the original dimensions.
1465
+
1466
+ This function performs the unflattening process in-place.
1467
+ """
1468
+ if not to_save:
1469
+ return
1470
+ flat_param = fsdp_param_info.handle.flat_param
1471
+ fsdp_state = fsdp_param_info.state
1472
+ for fqn, gathered_state in output_states.items():
1473
+ value = gathered_state[state_name]
1474
+ param_idx = fsdp_param_info.param_indices[fqn]
1475
+
1476
+ # TODO: This solution is not general and only apply to PTD TP solution.
1477
+ if isinstance(value, DTensor):
1478
+ placement = value.placements[0]
1479
+ # If gathered state is a DTensor and its TP placement is not Replicate(), we need to
1480
+ # gather the tensor on its TP dimension before chunking them into DTensor again.
1481
+ if placement != Replicate():
1482
+ placement_dim = placement.dim # type: ignore[attr-defined]
1483
+ value.redistribute(placements=(Replicate(),))
1484
+ reshape_size = list(flat_param._shapes[param_idx])
1485
+ reshape_size[placement_dim] *= value.device_mesh.size(0)
1486
+ reshape_size = torch.Size(reshape_size)
1487
+ value = value.reshape(reshape_size)
1488
+ # If gathered state is a replicate DTensor, we directly reshape it.
1489
+ else:
1490
+ value = value.reshape(flat_param._shapes[param_idx])
1491
+ else:
1492
+ # If gathered state is a tensor, we directly reshape it into unflatten state.
1493
+ value = value.reshape(flat_param._shapes[param_idx])
1494
+
1495
+ if shard_state:
1496
+ osd_config = fsdp_state._optim_state_dict_config
1497
+ if getattr(osd_config, "_use_dtensor", False):
1498
+ if fsdp_state._device_mesh is None:
1499
+ raise AssertionError(
1500
+ f"Expected _device_mesh to be not None, got {fsdp_state._device_mesh}"
1501
+ )
1502
+ value = _ext_chunk_dtensor(
1503
+ value,
1504
+ fsdp_state.rank,
1505
+ fsdp_state._device_mesh,
1506
+ fsdp_state._fsdp_extension,
1507
+ )
1508
+ else:
1509
+ if fsdp_state.process_group is None:
1510
+ raise AssertionError(
1511
+ f"Expected process_group to be not None, got {fsdp_state.process_group}"
1512
+ )
1513
+ value = _ext_chunk_tensor(
1514
+ value,
1515
+ fsdp_state.rank,
1516
+ fsdp_state.world_size,
1517
+ fsdp_state._device_handle.device_count(),
1518
+ fsdp_state.process_group,
1519
+ fsdp_state._fsdp_extension,
1520
+ )
1521
+ elif not cpu_offload:
1522
+ with SimpleProfiler.profile("clone"):
1523
+ value = value.detach().clone()
1524
+
1525
+ if cpu_offload:
1526
+ with SimpleProfiler.profile(SimpleProfiler.Type.D2H):
1527
+ value = value.cpu()
1528
+ gathered_state[state_name] = value
1529
+
1530
+
1531
+ def _allgather_orig_param_states(
1532
+ fsdp_param_info: FSDPParamInfo,
1533
+ gathered_state_info: list[dict[str, StateInfo]],
1534
+ input_states: dict[str, Any],
1535
+ shard_state: bool,
1536
+ to_save: bool,
1537
+ cpu_offload: bool,
1538
+ ) -> dict[str, dict[str, Any]]:
1539
+ """
1540
+ Given the ``gathered_state_info`` and ``input_states``, the API allgathers
1541
+ all tensor states and restore non-tensor states from ``gathered_state_info``.
1542
+ """
1543
+ fsdp_state = fsdp_param_info.state
1544
+ if fsdp_state.rank == 0 and dist.get_debug_level() == dist.DebugLevel.DETAIL:
1545
+ logger.info(
1546
+ "Memory Summary before calling to _allgather_orig_param_states %s",
1547
+ fsdp_state._device_handle.memory_summary(),
1548
+ )
1549
+
1550
+ output_states: dict[str, dict[str, Any]] = {fqn: {} for fqn in input_states}
1551
+
1552
+ dtype, state_buffers = _convert_all_state_info(
1553
+ fsdp_param_info, gathered_state_info, input_states, output_states
1554
+ )
1555
+
1556
+ if len(state_buffers) == 0:
1557
+ return output_states
1558
+
1559
+ has_state_params: list[bool] = [
1560
+ fqn in output_states for fqn, idx in fsdp_param_info.param_indices.items()
1561
+ ]
1562
+
1563
+ # Loop through the ``state_buffers`` and construct the flattened, concatenated,
1564
+ # sharded states. The size of the constructed state will be the same size as
1565
+ # flat_param (also sharded).
1566
+ # Then we perform an allgather_into_tensor to get the full flat_param state.
1567
+ # The full flat_param state is the result of concatenation of multiple states
1568
+ # the order of of flat_param._fqns.
1569
+ # The final step is to split the flat_param state into original param states
1570
+ # and return the result.
1571
+ flat_param = fsdp_param_info.handle.flat_param
1572
+ empty_func = functools.partial(
1573
+ torch.empty, dtype=dtype, device=fsdp_state.compute_device
1574
+ )
1575
+ gathered_tensor = empty_func(flat_param._padded_unsharded_size)
1576
+ # Synchronize can be slow but this will be easier for us to debug.
1577
+ fsdp_state._device_handle.synchronize()
1578
+ for state_name, buffers in state_buffers.items():
1579
+ local_buffers: list[torch.Tensor] = []
1580
+ begin = fsdp_state.rank * flat_param._sharded_size.numel()
1581
+ # End is inclusive.
1582
+ end = begin + flat_param._sharded_size.numel() - 1
1583
+ # param_idx corresponds to the parameter index in the FlatParameter.
1584
+ mem_offset, param_idx = 0, 0
1585
+ for numel, is_padding in zip(
1586
+ flat_param._numels_with_padding, flat_param._is_padding_mask
1587
+ ):
1588
+ frozen_and_no_state = not is_padding and (
1589
+ not fsdp_param_info.param_requires_grad[param_idx]
1590
+ and not has_state_params[param_idx]
1591
+ )
1592
+
1593
+ if is_padding or frozen_and_no_state:
1594
+ # This memory range is a padding or the param is frozen and does
1595
+ # not require gradient. For the later case, we treat it as a
1596
+ # padding and add empty values to the local_buffers.
1597
+
1598
+ padding_begin, padding_end = mem_offset, mem_offset + numel - 1
1599
+ if padding_begin <= begin <= padding_end:
1600
+ # The range is an align padding before the first parameter in
1601
+ # the shard. The shard includes parts of this align padding.
1602
+ padding_len = (
1603
+ padding_end - begin + 1
1604
+ if end >= padding_end
1605
+ else end - begin + 1
1606
+ )
1607
+ elif padding_begin <= end <= padding_end:
1608
+ # The range is an align padding after the last parameter in
1609
+ # the shard. The shard includes parts of this align padding.
1610
+ padding_len = (
1611
+ end - padding_begin + 1
1612
+ if begin <= padding_begin
1613
+ else end - begin + 1
1614
+ )
1615
+ elif begin < padding_begin <= padding_end < end:
1616
+ # The range is an align padding that is completely in the
1617
+ # shard.
1618
+ padding_len = numel
1619
+ else:
1620
+ padding_len = 0
1621
+ if padding_len:
1622
+ local_buffers.append(empty_func(padding_len))
1623
+
1624
+ if not is_padding:
1625
+ # This memory range is a parameter in FlatParameter. So there
1626
+ # should be an corresponding state in the optimizer unless the
1627
+ # parameter is frozen, which we treat it as a padding above.
1628
+
1629
+ # We need to check if this rank owns the buffer. If this is None:
1630
+ # 1.) the rank does not own any part of the original parameter.
1631
+ # As a result, there is no corresponding optimizer state on
1632
+ # the rank as well.
1633
+ # 2.) the parameter is frozen AND no optimizer state for the
1634
+ # parameter. If a parameter is frozen, there can still be
1635
+ # optimizer state if the parameter is not frozen in the
1636
+ # previous steps.
1637
+ if buffers[param_idx] is not None:
1638
+ local_buffers.append(cast(torch.Tensor, buffers[param_idx]))
1639
+ param_idx += 1
1640
+
1641
+ mem_offset += numel
1642
+
1643
+ shard_numel_padded = flat_param._sharded_size.numel() - (
1644
+ sum(t.numel() for t in local_buffers)
1645
+ )
1646
+
1647
+ if flat_param._shard_numel_padded != shard_numel_padded:
1648
+ raise AssertionError(
1649
+ "Manually calculated _sharded_numel_padded is incorrect. "
1650
+ f"_shard_numel_padded={flat_param._shard_numel_padded}, "
1651
+ f"shard_numel_padded={shard_numel_padded}, "
1652
+ f"_sharded_size.numel={flat_param._sharded_size.numel()}, "
1653
+ f"_numels_with_padding={flat_param._numels_with_padding}, "
1654
+ f"begin={begin}, end={end},"
1655
+ )
1656
+ if shard_numel_padded > 0:
1657
+ # Add right-handed padding.
1658
+ local_buffers.append(empty_func(shard_numel_padded))
1659
+ local_shard = torch.cat(local_buffers)
1660
+ if local_shard.numel() * fsdp_state.world_size != gathered_tensor.numel():
1661
+ raise AssertionError(
1662
+ "The size of local shard times the world size should equal to the "
1663
+ "gathered tensor size. The inconsistency may be from a bug of "
1664
+ "FlatParameter's metadata or the reconstruction logic in optimizer "
1665
+ "state dict."
1666
+ )
1667
+ fsdp_state._device_handle.synchronize()
1668
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
1669
+ dist.all_gather_into_tensor(
1670
+ gathered_tensor, local_shard, group=fsdp_state.process_group
1671
+ )
1672
+ # Synchronize can be slow but this will be easier for us to debug.
1673
+ fsdp_state._device_handle.synchronize()
1674
+
1675
+ unpadded_tensor = gathered_tensor[: flat_param._unpadded_unsharded_size.numel()]
1676
+ flat_param_handle = fsdp_param_info.handle
1677
+ orig_states = flat_param_handle._get_unflat_views_aligned(unpadded_tensor)
1678
+ if len(orig_states) != len(fsdp_param_info.param_indices):
1679
+ raise AssertionError(
1680
+ "The number of parameters from FlatParameter is not consistent to "
1681
+ "the number of states used by optimizer state dict reconstruction "
1682
+ "logic."
1683
+ )
1684
+ for fqn, idx in fsdp_param_info.param_indices.items():
1685
+ if fsdp_param_info.param_requires_grad[idx] or fqn in output_states:
1686
+ output_states[fqn][state_name] = orig_states[idx]
1687
+
1688
+ _unflatten_orig_param_states(
1689
+ fsdp_param_info,
1690
+ output_states,
1691
+ state_name,
1692
+ shard_state,
1693
+ to_save,
1694
+ cpu_offload,
1695
+ )
1696
+
1697
+ del gathered_tensor
1698
+ return output_states
1699
+
1700
+
1701
+ def _gather_all_orig_param_state(
1702
+ fsdp_param_info: FSDPParamInfo,
1703
+ input_states: dict[str, Any],
1704
+ shard_state: bool,
1705
+ to_save: bool,
1706
+ cpu_offload: bool,
1707
+ ) -> dict[str, Any]:
1708
+ """
1709
+ Given a optimizer state dict, ``input_states``, which the keys are FQNs to the
1710
+ original parameters (not FlatParameters nor parameter ID), gather all the
1711
+ states and unflatten them to the original dimensions. Note that all the
1712
+ params referred by the ``input_states`` must be managed by FSDP.
1713
+ """
1714
+ fsdp_state = fsdp_param_info.state
1715
+ if (
1716
+ fsdp_state.world_size == 1
1717
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
1718
+ ):
1719
+ return input_states if to_save else {}
1720
+
1721
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
1722
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER_OBJ):
1723
+ gathered_state_info = _allgather_state_info(fsdp_state, input_states)
1724
+ output_states = _allgather_orig_param_states(
1725
+ fsdp_param_info,
1726
+ gathered_state_info,
1727
+ input_states,
1728
+ shard_state,
1729
+ to_save,
1730
+ cpu_offload,
1731
+ )
1732
+ if to_save:
1733
+ for key, idx in fsdp_param_info.param_indices.items():
1734
+ if key in output_states:
1735
+ continue
1736
+ if not fsdp_param_info.param_requires_grad[idx]:
1737
+ continue
1738
+
1739
+ raise RuntimeError(
1740
+ f"{key} is not in the output state. "
1741
+ "The FSDPParamInfo has the param keys "
1742
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1743
+ "the output_states has the param keys "
1744
+ f"{sorted(output_states.keys())}."
1745
+ )
1746
+ return output_states
1747
+ else:
1748
+ return {}
1749
+
1750
+
1751
+ def _convert_state_with_orig_params(
1752
+ all_optim_state_keys: list[_OptimStateKey],
1753
+ optim_state_key_to_param_key: dict[_OptimStateKey, Union[int, str]],
1754
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1755
+ optim_state_dict: dict[Union[str, int], Any],
1756
+ to_save: bool,
1757
+ shard_state: bool,
1758
+ cpu_offload: bool = True,
1759
+ ) -> dict[str, Any]:
1760
+ fsdp_osd_state: dict[str, Any] = {}
1761
+ # This variable is used to deduplicate the FSDPParamInfo as one FSDPParamInfo
1762
+ # usually corresponds to multiple parameters. We could not use FSDPParamInfo
1763
+ # as the key because FSDPParamInfo is not hashable. As a result, we fall back
1764
+ # to `id(FSDPParamInfo)`, which the type is an integer.
1765
+ all_states: dict[int, dict[str, Any]] = {}
1766
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1767
+ # across ranks
1768
+ for optim_state_key in all_optim_state_keys:
1769
+ param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
1770
+ optim_state_key
1771
+ )
1772
+
1773
+ if param_key is None and not optim_state_key.is_fsdp_managed:
1774
+ continue
1775
+
1776
+ if optim_state_key.is_fsdp_managed:
1777
+ fqn = optim_state_key.unflat_param_names[0]
1778
+ fsdp_param_info = fqn_to_fsdp_param_info.get(fqn)
1779
+ if fsdp_param_info is None:
1780
+ # This can happen if the not all FSDP instances have all the
1781
+ # parameters. This can happen with FSDP + some MPMD style
1782
+ # parallelism.
1783
+
1784
+ # TODO: it is unclear if we need to do the same check with
1785
+ # non-FSDP managed keys.
1786
+ continue
1787
+ state = {} if param_key is None else optim_state_dict[param_key]
1788
+ if id(fsdp_param_info) not in all_states:
1789
+ all_states[id(fsdp_param_info)] = {}
1790
+ all_states[id(fsdp_param_info)][fqn] = state
1791
+
1792
+ elif to_save:
1793
+ if len(optim_state_key.unflat_param_names) != 1:
1794
+ raise AssertionError(
1795
+ f"Expected len(optim_state_key.unflat_param_names) == 1, got {len(optim_state_key.unflat_param_names)}"
1796
+ )
1797
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1798
+ with SimpleProfiler.profile("none_fsdp_managed_copy"):
1799
+ param_key = cast(Union[str, int], param_key)
1800
+ fsdp_osd_state[unflat_param_name] = copy.copy(
1801
+ optim_state_dict[param_key]
1802
+ )
1803
+ if cpu_offload:
1804
+ for state_name, value in sorted_items(
1805
+ fsdp_osd_state[unflat_param_name]
1806
+ ):
1807
+ if not torch.is_tensor(value):
1808
+ continue
1809
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1810
+
1811
+ # Instead of gathering the state of each parameter individually, we perform
1812
+ # the gathering all at once to speed up the process.
1813
+ for _all_states in all_states.values():
1814
+ fqn = next(iter(_all_states.keys()))
1815
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1816
+ if len(fsdp_param_info.param_requires_grad) <= 0:
1817
+ raise AssertionError(
1818
+ "With use_orig_params, FSDPParamInfo should have requires_grad "
1819
+ "information. However, the length is zero."
1820
+ )
1821
+ for key, idx in fsdp_param_info.param_indices.items():
1822
+ if key in _all_states:
1823
+ continue
1824
+ if not fsdp_param_info.param_requires_grad[idx]:
1825
+ continue
1826
+ raise RuntimeError(
1827
+ f"{key} is not in the optimizer state. "
1828
+ "The FSDPParamInfo has the param keys "
1829
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1830
+ "the optimizer has the param keys "
1831
+ f"{sorted(_all_states.keys())}."
1832
+ )
1833
+ fsdp_osd_state.update(
1834
+ _gather_all_orig_param_state(
1835
+ fsdp_param_info,
1836
+ _all_states,
1837
+ shard_state,
1838
+ to_save,
1839
+ cpu_offload,
1840
+ )
1841
+ )
1842
+
1843
+ return fsdp_osd_state
1844
+
1845
+
1846
+ def _convert_state_with_flat_params(
1847
+ all_optim_state_keys: list[_OptimStateKey],
1848
+ optim_state_key_to_param_key: dict[_OptimStateKey, Union[int, str]],
1849
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1850
+ optim_state_dict: dict[Union[str, int], Any],
1851
+ to_save: bool,
1852
+ shard_state: bool,
1853
+ cpu_offload: bool = True,
1854
+ ) -> dict[str, Any]:
1855
+ fsdp_osd_state: dict[str, Any] = {}
1856
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1857
+ # across ranks
1858
+ for optim_state_key in all_optim_state_keys:
1859
+ param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
1860
+ optim_state_key
1861
+ )
1862
+
1863
+ if param_key is None:
1864
+ raise AssertionError(
1865
+ "If use_orig_params is False, we must be able to find the "
1866
+ f"corresponding param id. {optim_state_key} {param_key}"
1867
+ )
1868
+
1869
+ if optim_state_key.is_fsdp_managed:
1870
+ # If there are multiple unflat_param_names (not use_orig_params),
1871
+ # they share the same FSDPParamInfo. So the first unflat_param_name
1872
+ # is sufficient to fetch the FSDPParamInfo.
1873
+ fqn = optim_state_key.unflat_param_names[0]
1874
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1875
+ unflat_state = _unflatten_optim_state(
1876
+ fsdp_param_info,
1877
+ optim_state_dict[param_key],
1878
+ to_save,
1879
+ shard_state,
1880
+ cpu_offload,
1881
+ )
1882
+ if to_save:
1883
+ if len(unflat_state) != len(optim_state_key.unflat_param_names):
1884
+ raise AssertionError(
1885
+ f"Expected len(unflat_state) == len(optim_state_key.unflat_param_names), "
1886
+ f"got {len(unflat_state)} != {len(optim_state_key.unflat_param_names)}"
1887
+ )
1888
+ fsdp_osd_state.update(
1889
+ zip(
1890
+ optim_state_key.unflat_param_names,
1891
+ unflat_state,
1892
+ )
1893
+ )
1894
+ elif to_save:
1895
+ if len(optim_state_key.unflat_param_names) != 1:
1896
+ raise AssertionError(
1897
+ f"Expected len(optim_state_key.unflat_param_names) == 1, got {len(optim_state_key.unflat_param_names)}"
1898
+ )
1899
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1900
+ fsdp_osd_state[unflat_param_name] = copy.copy(optim_state_dict[param_key])
1901
+ if cpu_offload:
1902
+ for state_name, value in sorted_items(
1903
+ fsdp_osd_state[unflat_param_name]
1904
+ ):
1905
+ if not torch.is_tensor(value):
1906
+ continue
1907
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1908
+
1909
+ return fsdp_osd_state
1910
+
1911
+
1912
+ @torch.no_grad()
1913
+ def _optim_state_dict(
1914
+ model: nn.Module,
1915
+ optim: torch.optim.Optimizer,
1916
+ optim_state_dict: dict[str, Any],
1917
+ optim_input: Optional[
1918
+ Union[
1919
+ list[dict[str, Any]],
1920
+ Iterable[nn.Parameter],
1921
+ ]
1922
+ ],
1923
+ rank0_only: bool,
1924
+ shard_state: bool,
1925
+ group: Optional[dist.ProcessGroup],
1926
+ using_optim_input: bool,
1927
+ use_orig_params: bool = False,
1928
+ cpu_offload: bool = True,
1929
+ ) -> dict[str, Any]:
1930
+ """
1931
+ Consolidates the optimizer state and returns it as a :class:`dict`
1932
+ following the convention of :meth:`torch.optim.Optimizer.state_dict`,
1933
+ i.e. with keys ``"state"`` and ``"param_groups"``.
1934
+ The flat parameters in ``FSDP`` modules contained in ``model`` are mapped
1935
+ back to their unflattened parameters.
1936
+
1937
+ Parameter keys are not well-defined. For a regular optimizer, the optimizer
1938
+ state_dict contains a mapping from parameter IDs to parameter states.
1939
+ Parameter IDs are the order of parameters in ``optim.param_groups()`` across
1940
+ all the groups. This API also allows user to pass ``optim_input`` for the
1941
+ mapping between parameters and parameter IDs. Using ``optim_input`` is being
1942
+ deprecated.
1943
+
1944
+ If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not
1945
+ contain parameter IDs mapping but a mapping from parameter FQNs to parameter
1946
+ states. This API finds the mapping from FQNs to parameters if the optimizer
1947
+ is a ``NamedOptimizer``.
1948
+
1949
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
1950
+ parameters but some of these parameters may be empty due to the sharding.
1951
+ For a regular optim.Optimizer, states for those empty parameters will
1952
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
1953
+ will be raised on a rank even if it does not have all the states -- it is
1954
+ valid and FSDP knows how to aggregate them. However, FSDP has to ignore
1955
+ handling those parameters that are not managed by FSDP and do not exist on
1956
+ the local rank -- those are managed by other parallelisms and FSDP does not
1957
+ know how to handle/aggregate them.
1958
+
1959
+ Args:
1960
+ model (nn.Module): Root module (which may or may not be a
1961
+ :class:`FullyShardedDataParallel` instance) whose parameters
1962
+ were passed into the optimizer ``optim``.
1963
+ optim (torch.optim.Optimizer): Optimizer for ``model`` 's
1964
+ parameters.
1965
+ rank0_only (bool): If ``True``, saves the populated :class:`dict`
1966
+ only on rank 0; if ``False``, saves it on all ranks. (Default:
1967
+ ``True``)
1968
+ shard_state (bool): If ``True``, shard and distribute all
1969
+ non-zero-dimension states.
1970
+
1971
+ Returns:
1972
+ Dict[str, Any]: A :class:`dict` containing the optimizer state for
1973
+ ``model`` 's original unflattened parameters and including keys
1974
+ "state" and "param_groups" following the convention of
1975
+ :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
1976
+ then nonzero ranks return an empty :class:`dict`.
1977
+ """
1978
+ SimpleProfiler.reset()
1979
+ cm = ExitStack()
1980
+ cm.enter_context(SimpleProfiler.profile(SimpleProfiler.Type.ALL))
1981
+ _reset_flat_param_grad_info_if_needed(traversal_utils._get_fsdp_handles(model))
1982
+ to_save = not rank0_only or dist.get_rank(group) == 0 or shard_state
1983
+
1984
+ with SimpleProfiler.profile("preprocessing"):
1985
+ param_to_fqns = _get_param_to_fqns(model)
1986
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
1987
+ is_named_optimizer = _is_named_optimizer(optim_state_dict)
1988
+
1989
+ param_key_to_param = cast(
1990
+ dict[Union[int, str], nn.Parameter],
1991
+ (
1992
+ _get_param_id_to_param_from_optim_input(model, optim_input)
1993
+ if using_optim_input
1994
+ else _get_param_key_to_param(
1995
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1996
+ )
1997
+ ),
1998
+ )
1999
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
2000
+
2001
+ with SimpleProfiler.profile("preprocessing_with_comm"):
2002
+ (
2003
+ all_optim_state_keys,
2004
+ optim_state_key_to_param_key,
2005
+ ) = _map_param_key_to_optim_keys(
2006
+ optim_state_dict,
2007
+ group,
2008
+ param_key_to_param,
2009
+ param_to_fqns,
2010
+ fqn_to_fsdp_param_info,
2011
+ merge_keys=use_orig_params,
2012
+ )
2013
+
2014
+ with SimpleProfiler.profile("state_converting"):
2015
+ convert_fn = (
2016
+ _convert_state_with_orig_params
2017
+ if use_orig_params
2018
+ else _convert_state_with_flat_params
2019
+ )
2020
+ fsdp_osd_state = convert_fn(
2021
+ all_optim_state_keys,
2022
+ optim_state_key_to_param_key,
2023
+ fqn_to_fsdp_param_info,
2024
+ optim_state_dict["state"],
2025
+ to_save,
2026
+ shard_state,
2027
+ cpu_offload,
2028
+ )
2029
+
2030
+ # At this point, communication is complete and ranks can return early if nothing
2031
+ # will be saved on that rank.
2032
+ if not to_save:
2033
+ return {}
2034
+
2035
+ fsdp_osd: dict[str, Any] = {"state": fsdp_osd_state}
2036
+
2037
+ flat_param_fqns = set(flat_param_to_fqn.values())
2038
+ for key, value in optim_state_dict["state"].items():
2039
+ if key in fsdp_osd_state:
2040
+ continue
2041
+ if key in flat_param_fqns:
2042
+ continue
2043
+ if key in param_key_to_param:
2044
+ continue
2045
+ # This key is not recognized by FSDP. It may be a user-defined state
2046
+ # or some parameters state that FSDP is unable to map from
2047
+ # ``optim.param_groups``.
2048
+ warnings.warn(
2049
+ f"Found a optim state, {key}, that FSDP cannot process. FSDP "
2050
+ "will directly copy everything to the returned state_dict. In "
2051
+ "most cases, this is a user-defined state that is not "
2052
+ "associated with any particular parameter. Another possible "
2053
+ "case is this state is managed by TorchRec. Otherwise, there may "
2054
+ " be a mismatched assumption of optim_state_dict of this mode.",
2055
+ stacklevel=2,
2056
+ )
2057
+ fsdp_osd_state[key] = value
2058
+
2059
+ if "param_groups" in optim_state_dict:
2060
+ fsdp_osd["param_groups"] = _unflatten_param_groups(
2061
+ optim_state_dict, param_key_to_param, param_to_fqns
2062
+ )
2063
+
2064
+ cm.close()
2065
+ SimpleProfiler.dump_and_reset("FSDP _optim_state_dict() profiling: ")
2066
+
2067
+ return fsdp_osd
2068
+
2069
+
2070
+ def _get_fqn_to_fsdp_param_info(model: nn.Module) -> dict[str, FSDPParamInfo]:
2071
+ """
2072
+ Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo``
2073
+ if the param is managed by FSDP. Shared parameters, or original parameters that
2074
+ are shared across multiple nn.Modules, are required to belong to one and only
2075
+ one FSDP instance and thus correspond to one ``FlatParameter``. Within the one
2076
+ ``FlatParameter``, ``FlatParameter._fqns`` only stores the first FQN of a shared
2077
+ parameter. Thus, the keys in the mapping are guaranteed to map to unique parameters.
2078
+ """
2079
+
2080
+ def module_fn(module, prefix, tree_level, fqn_to_param_info):
2081
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
2082
+ if fsdp_state is None:
2083
+ return
2084
+ _lazy_init(fsdp_state, module)
2085
+ handle = _module_handle(fsdp_state, module)
2086
+ if not handle:
2087
+ return
2088
+ flat_param = handle.flat_param
2089
+ fsdp_param_info = FSDPParamInfo(fsdp_state, handle, {}, [])
2090
+ # NOTE: `idx` indexes into the data structures *without* padding
2091
+ # elements
2092
+ for idx, local_fqn in enumerate(flat_param._fqns):
2093
+ fqn = clean_tensor_name(prefix + local_fqn)
2094
+ if fqn in fqn_to_param_info:
2095
+ if fqn_to_param_info[fqn].handle.flat_param is not flat_param:
2096
+ raise AssertionError(
2097
+ f"Expected fqn_to_param_info[fqn].handle.flat_param is flat_param for {fqn}"
2098
+ )
2099
+ fqn_to_param_info[fqn] = fsdp_param_info
2100
+ fsdp_param_info.param_indices[fqn] = idx
2101
+ if flat_param._params is not None:
2102
+ fsdp_param_info.param_requires_grad.append(
2103
+ flat_param._params[idx].requires_grad
2104
+ )
2105
+
2106
+ def return_fn(fqn_to_param_info):
2107
+ return fqn_to_param_info
2108
+
2109
+ fqn_to_param_info: dict[str, FSDPParamInfo] = {}
2110
+ # FlatParameter._fqns stores the local fqn, starting from the root of the
2111
+ # FSDP. Using _apply_to_modules() with model (may not be the FSDP root
2112
+ # module) allows us to construct the global fqn.
2113
+ return _apply_to_modules(
2114
+ model,
2115
+ module_fn,
2116
+ return_fn,
2117
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
2118
+ fqn_to_param_info,
2119
+ )
2120
+
2121
+
2122
+ @no_type_check
2123
+ def _set_optim_use_dtensor(
2124
+ fsdp_state: _FSDPState,
2125
+ state_dict_settings: StateDictSettings,
2126
+ ) -> None:
2127
+ # If device_mesh is passed in when initializing FSDP, we automatically turn the
2128
+ # _use_dtensor flag to be true for ShardedOptimStateDictConfig() if state_dict_type
2129
+ # has to be set to SHARDED_STATE_DICT.
2130
+ if getattr(fsdp_state, "_device_mesh", None):
2131
+ state_dict_type = state_dict_settings.state_dict_type
2132
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
2133
+ raise RuntimeError(
2134
+ "Found state_dict_type LOCAL_STATE_DICT.",
2135
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
2136
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
2137
+ )
2138
+ else:
2139
+ state_dict_settings.optim_state_dict_config._use_dtensor = True
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_runtime_utils.py ADDED
@@ -0,0 +1,1654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import logging
4
+ from collections.abc import Callable
5
+ from enum import auto, Enum
6
+ from typing import Any, no_type_check, Optional
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from torch.autograd import Variable
14
+ from torch.autograd.graph import register_multi_grad_hook
15
+ from torch.distributed.algorithms._comm_hooks import LOW_PRECISION_HOOKS
16
+ from torch.distributed.fsdp._common_utils import (
17
+ _assert_in_training_states,
18
+ _FSDPState,
19
+ _get_module_fsdp_state,
20
+ _is_composable,
21
+ _log_post_backward_hook,
22
+ _no_dispatch_record_stream,
23
+ clean_tensor_name,
24
+ TrainingState,
25
+ )
26
+ from torch.distributed.fsdp._flat_param import (
27
+ FlatParameter,
28
+ FlatParamHandle,
29
+ HandleShardingStrategy,
30
+ HandleTrainingState,
31
+ RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES,
32
+ )
33
+ from torch.distributed.fsdp._init_utils import HYBRID_SHARDING_STRATEGIES
34
+ from torch.distributed.fsdp.api import BackwardPrefetch
35
+ from torch.distributed.utils import (
36
+ _apply_to_tensors,
37
+ _cast_forward_inputs,
38
+ _p_assert,
39
+ _to_kwargs,
40
+ )
41
+ from torch.utils import _pytree as pytree
42
+
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # Do not include "process_group" to enable hybrid shard and MoE cases
47
+ HOMOGENEOUS_ATTR_NAMES = (
48
+ "_use_orig_params",
49
+ "limit_all_gathers",
50
+ "_use_full_prec_in_eval",
51
+ )
52
+
53
+
54
+ class _PrefetchMode(Enum):
55
+ BACKWARD = auto()
56
+ FORWARD = auto()
57
+
58
+
59
+ def _get_fsdp_root_states_with_modules(
60
+ module: nn.Module,
61
+ ) -> tuple[list[_FSDPState], list[nn.Module]]:
62
+ """
63
+ Returns a tuple containing:
64
+ 1. A list of the root ``_FSDPState`` instances in the module tree rooted at
65
+ ``module`` without any duplicates and following the ``module.modules()``
66
+ traversal order (which is assumed to be depth-first).
67
+ 2. A corresponding list of the root modules owning the states in the first
68
+ list.
69
+
70
+ This is similar to :func:`_get_fsdp_states_with_modules` except that we
71
+ must call :func:`_is_fsdp_root` to force a lazy initialization to determine
72
+ the FSDP root in case lazy initialization has not yet happened.
73
+ """
74
+ fsdp_root_states: list[_FSDPState] = []
75
+ fsdp_root_modules: list[nn.Module] = []
76
+ visited_fsdp_states: set[_FSDPState] = set()
77
+ # NOTE: This function assumes that `module.modules()` proceeds top-down.
78
+ for submodule in module.modules():
79
+ optional_state = _get_module_fsdp_state(submodule)
80
+ if (
81
+ optional_state is not None
82
+ and optional_state not in visited_fsdp_states
83
+ and _is_fsdp_root(optional_state, submodule)
84
+ ):
85
+ visited_fsdp_states.add(optional_state)
86
+ fsdp_root_states.append(optional_state)
87
+ fsdp_root_modules.append(submodule)
88
+ return fsdp_root_states, fsdp_root_modules
89
+
90
+
91
+ def _get_fsdp_root_states(module: nn.Module) -> list[_FSDPState]:
92
+ """See :func:`_get_fsdp_root_states_with_modules`."""
93
+ fsdp_root_states, _ = _get_fsdp_root_states_with_modules(module)
94
+ return fsdp_root_states
95
+
96
+
97
+ def _is_fsdp_root(state: _FSDPState, module: nn.Module) -> bool:
98
+ """
99
+ Returns if ``state`` corresponds to that of an FSDP root.
100
+
101
+ For the wrapper code path, ``state`` and ``module`` should be the same. For
102
+ the non-wrapper code path, ``state`` should be ``module`` 's state.
103
+ """
104
+ # Force a lazy initialization to determine the FSDP root
105
+ _lazy_init(state, module)
106
+ if state._is_root is None:
107
+ raise AssertionError("Expected _is_root to be set after lazy init")
108
+ return state._is_root
109
+
110
+
111
+ @no_type_check
112
+ def _lazy_init(
113
+ state: _FSDPState,
114
+ root_module: nn.Module,
115
+ ) -> _FSDPState:
116
+ """
117
+ Performs initialization lazily, typically right before the first forward
118
+ pass. The laziness is needed to ensure that the parameter device/dtype and
119
+ the FSDP hierarchy have finalized. This method's actual logic only runs on
120
+ the root FSDP instance, which performs initialization for all non-root FSDP
121
+ instances to avoid partial initialization.
122
+
123
+ For the non-composable code path, ``state`` and ``root_module`` should be
124
+ the same, namely the FSDP instance itself.
125
+ """
126
+ if state._is_root is not None:
127
+ return # no-op: already lazily initialized
128
+ if not state._device_handle.is_available():
129
+ # Allow the FSDP constructor to run even without CUDA but check this
130
+ # once we start real execution
131
+ raise RuntimeError("FSDP does not support CPU only execution")
132
+ # The following logic is only run on the root FSDP instance since it will
133
+ # set `_is_root=False` for the non-root instances
134
+ state._is_root = True
135
+ _assert_in_training_states(state, [TrainingState.IDLE])
136
+ _check_flat_params_on_expected_device(state, root_module)
137
+ state._all_fsdp_states = traversal_utils._get_fsdp_states(root_module)
138
+ _init_streams(state)
139
+ buffers, buffer_dtypes = _get_buffers_and_dtypes_for_computation(state, root_module)
140
+ _cast_buffers_to_dtype_and_device(buffers, buffer_dtypes, state.compute_device)
141
+ state._exec_order_data.init(state, root_module, state.process_group)
142
+ _share_state_and_init_handle_attrs(state, root_module)
143
+ return state
144
+
145
+
146
+ def _check_flat_params_on_expected_device(state: _FSDPState, module: nn.Module):
147
+ """
148
+ Checks that all ``FlatParameter``s in ``module`` 's tree managed by
149
+ ``state`` are on the expected device for *lazy initialization*.
150
+ """
151
+ cpu_device = torch.device("cpu")
152
+ for handle in traversal_utils._get_fsdp_handles(module):
153
+ if (
154
+ not handle._offload_params
155
+ and handle.flat_param.device != state.compute_device
156
+ ):
157
+ raise RuntimeError(
158
+ "An FSDP-managed module unexpectedly has parameters on "
159
+ f"{handle.flat_param.device}. Make sure to move the module to "
160
+ f"{state.compute_device} before training."
161
+ )
162
+ elif handle._offload_params and handle.flat_param.device != cpu_device:
163
+ raise RuntimeError(
164
+ "An FSDP-managed module with parameter CPU offloading enabled "
165
+ f"has parameters on {handle.flat_param.device}. Make sure to "
166
+ f"not move the module from CPU when offloading parameters."
167
+ )
168
+
169
+
170
+ @no_type_check
171
+ def _share_state_and_init_handle_attrs(
172
+ root_state: _FSDPState,
173
+ root_module: nn.Module,
174
+ ) -> None:
175
+ """
176
+ Shares data structure state from the ``root_state`` to all FSDP states in
177
+ ``root_module`` 's module tree, and initializes handle attributes. These
178
+ are done together to require a single loop over the states.
179
+ """
180
+ handle = root_state._handle
181
+ if handle:
182
+ handle.init_flat_param_attributes()
183
+ attr_name_to_values: dict[str, set[Any]] = {}
184
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
185
+ attr_name_to_values[attr_name] = set()
186
+ root_state._all_handles = root_state._exec_order_data.all_handles # share reference
187
+ # Update _has_optim_in_backward for each handle.
188
+ for handle in root_state._all_handles:
189
+ flat_param = handle.flat_param
190
+ if hasattr(flat_param, "_in_backward_optimizers"):
191
+ raise RuntimeError(
192
+ "FSDP optimizer in backward only supported with use_orig_params=True!"
193
+ )
194
+ handle._has_optim_in_backward = flat_param._params is not None and any(
195
+ hasattr(param, "_in_backward_optimizers") for param in flat_param._params
196
+ )
197
+ if handle._has_optim_in_backward:
198
+ torch._C._log_api_usage_once("fsdp.optimizer_in_backward")
199
+ for fsdp_state in root_state._all_fsdp_states:
200
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
201
+ _p_assert(
202
+ hasattr(fsdp_state, attr_name),
203
+ f"FSDP state missing attribute {attr_name}",
204
+ )
205
+ attr_name_to_values[attr_name].add(getattr(fsdp_state, attr_name))
206
+ if fsdp_state is root_state:
207
+ continue
208
+ # Relax the assert for non-root FSDP instances in case the nested
209
+ # initialized module is wrapped again in FSDP later (e.g. after
210
+ # training to run inference)
211
+ _p_assert(
212
+ fsdp_state._is_root is None or not fsdp_state._is_root,
213
+ "Non-root FSDP instance's `_is_root` should not have been "
214
+ "set yet or should have been set to `False`",
215
+ )
216
+ fsdp_state._is_root = False
217
+ fsdp_state._unshard_stream = root_state._unshard_stream
218
+ fsdp_state._post_backward_stream = root_state._post_backward_stream
219
+ fsdp_state._pre_unshard_stream = root_state._pre_unshard_stream
220
+ fsdp_state._all_reduce_stream = root_state._all_reduce_stream
221
+ fsdp_state._default_stream = root_state._default_stream
222
+ fsdp_state._exec_order_data = root_state._exec_order_data
223
+ fsdp_state._free_event_queue = root_state._free_event_queue
224
+ if fsdp_state._fsdp_extension is not None:
225
+ fsdp_state._fsdp_extension.compute_stream = root_state._default_stream
226
+ handle = fsdp_state._handle
227
+ if handle:
228
+ handle.init_flat_param_attributes()
229
+ for attr_name, attr_values in attr_name_to_values.items():
230
+ if len(attr_values) != 1:
231
+ raise ValueError(
232
+ f"Expects one homogeneous value for {attr_name} but got {attr_values}"
233
+ )
234
+
235
+
236
+ @no_type_check
237
+ def _init_streams(
238
+ state: _FSDPState,
239
+ ) -> None:
240
+ """
241
+ Initializes CUDA streams for overlapping communication, computation, and
242
+ data transfers. The streams should be shared across FSDP instances.
243
+ """
244
+ if not state._is_root:
245
+ raise AssertionError("Expected state to be root")
246
+ if not state._device_handle.is_available():
247
+ raise AssertionError("Expected device handle to be available")
248
+ uses_hybrid_sharding = any(
249
+ fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES
250
+ for fsdp_state in state._all_fsdp_states
251
+ )
252
+ # Prioritize all-gathers/reduce-scatters over async all-reduce for HSDP and
253
+ # preserve the default priority of 0 otherwise
254
+ high_priority = -1 if state.limit_all_gathers and uses_hybrid_sharding else 0
255
+ # Default stream for computation
256
+ state._default_stream = state._device_handle.current_stream()
257
+ if state._fsdp_extension is not None:
258
+ # set the compute stream to the FSDP extension
259
+ state._fsdp_extension.compute_stream = state._default_stream
260
+
261
+ # Stream for unshard logic, including allocating the all-gather destination
262
+ # tensors and the all-gathers themselves
263
+ state._unshard_stream = state._device_handle.Stream(priority=high_priority)
264
+ # Stream for overlapping gradient reduction with the backward pass gradient
265
+ # computation
266
+ state._post_backward_stream = state._device_handle.Stream(priority=high_priority)
267
+ # Stream for pre-unshard logic, namely allocations and writes for CPU
268
+ # offloading (H2D copy) and mixed precision (low precision cast)
269
+ state._pre_unshard_stream = state._device_handle.Stream(priority=high_priority)
270
+ # Stream to run HSDP's all-reduce as async (if using HSDP)
271
+ state._all_reduce_stream = (
272
+ state._device_handle.Stream() if uses_hybrid_sharding else state._default_stream
273
+ )
274
+
275
+
276
+ @no_type_check
277
+ def _unshard(
278
+ state: _FSDPState,
279
+ handle: FlatParamHandle,
280
+ unshard_stream: torch.Stream,
281
+ pre_unshard_stream: torch.Stream,
282
+ ) -> None:
283
+ """
284
+ Unshards the handles in ``handles``. If the handles are in
285
+ :meth:`summon_full_params` and are using mixed precision, then they are
286
+ forced to full precision.
287
+
288
+ Postcondition: handle's ``FlatParameter`` 's data is the padded
289
+ unsharded flat parameter on the compute device.
290
+ """
291
+ if not handle:
292
+ return
293
+ with state._device_handle.stream(pre_unshard_stream):
294
+ ran_pre_unshard = handle.pre_unshard()
295
+ if ran_pre_unshard:
296
+ unshard_stream.wait_stream(pre_unshard_stream)
297
+ if state.limit_all_gathers:
298
+ event = state._free_event_queue.dequeue_if_needed()
299
+ if event:
300
+ with torch.profiler.record_function(
301
+ "FullyShardedDataParallel.rate_limiter"
302
+ ):
303
+ event.synchronize()
304
+ with state._device_handle.stream(unshard_stream):
305
+ handle.unshard()
306
+ handle.post_unshard()
307
+
308
+
309
+ @no_type_check
310
+ def _reshard(
311
+ state: _FSDPState,
312
+ handle: FlatParamHandle,
313
+ free_unsharded_flat_param: bool,
314
+ ):
315
+ """
316
+ Reshards the handle. ``free_unsharded_flat_param`` indicates whether to
317
+ free the handle's padded unsharded flat parameter.
318
+ """
319
+ handle.reshard(free_unsharded_flat_param)
320
+ if state.limit_all_gathers and free_unsharded_flat_param:
321
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
322
+ # We don't run a even queue for freeing under torch compile atm
323
+ # But maybe we need to? TODO(voz): Look into this
324
+ free_event = state._device_handle.Event()
325
+ free_event.record()
326
+ state._free_event_queue.enqueue(free_event)
327
+ handle.post_reshard()
328
+ # Flat parameter freed or not, we always have to "unshard" the parameter
329
+ # upon next access to get its shape correct.
330
+ handle._prefetched = False
331
+
332
+
333
+ def _unshard_grads(
334
+ handle: Optional[FlatParamHandle],
335
+ ) -> None:
336
+ if handle:
337
+ handle.unshard_grad()
338
+
339
+
340
+ def _reshard_grads(
341
+ handle: Optional[FlatParamHandle],
342
+ ) -> None:
343
+ if handle:
344
+ handle.reshard_grad()
345
+
346
+
347
+ @no_type_check
348
+ def _pre_forward(
349
+ state: _FSDPState,
350
+ handle: Optional[FlatParamHandle],
351
+ unshard_fn: Callable,
352
+ module: nn.Module,
353
+ args: tuple[Any, ...],
354
+ kwargs: dict[str, Any],
355
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
356
+ """
357
+ Runs the pre-forward logic. This includes an opportunity to unshard
358
+ currently sharded parameters such as those for the current forward and
359
+ registering post-backward hooks for these current parameters. This function
360
+ also converts forward ``args`` and ``kwargs`` to the given precision.
361
+
362
+ Args:
363
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
364
+ the current forward.
365
+ unshard_fn (Optional[Callable]): A callable to unshard any currently
366
+ sharded parameters or ``None`` to not do any unsharding.
367
+ module (nn.Module): Module whose forward this method runs right before;
368
+ expected by the hook signature.
369
+ args (Tuple[Any, ...]): Module forward ``args``.
370
+ kwargs (Dict[str, Any]): Module forward ``kwargs``.
371
+ """
372
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_forward"):
373
+ # For `fully_shard` + `checkpoint`, skip pre-forward logic in the
374
+ # recomputed forward
375
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
376
+ # For both checkpoint implementations, we do not need to re-cast
377
+ # inputs here since they will be checkpointed in the low precision
378
+ # either by AC or normally by autograd as long as the AC region is
379
+ # nested within FSDP
380
+ return args, kwargs
381
+ state.training_state = TrainingState.FORWARD_BACKWARD
382
+ state._exec_order_data.record_pre_forward(handle, module.training)
383
+ if handle:
384
+ handle._training_state = HandleTrainingState.FORWARD
385
+ if unshard_fn is not None:
386
+ unshard_fn(state, handle)
387
+ # Register post-backward hooks to reshard the parameters and reduce-scatter
388
+ # their gradients. They must be re-registered every forward pass in case
389
+ # the `grad_fn` is mutated.
390
+ _register_post_backward_hook(state, handle)
391
+ # We have to reallocate the _cpu_grad if optimizer overlap
392
+ # set the grad to None in the backward pass.
393
+ if handle and handle._offload_params and handle.flat_param._cpu_grad is None:
394
+ handle.flat_param._cpu_grad = torch.zeros_like(
395
+ handle.flat_param._local_shard, device=torch.device("cpu")
396
+ ).pin_memory()
397
+
398
+ should_cast_forward_inputs = (
399
+ state._handle and not state._handle._force_full_precision
400
+ )
401
+
402
+ if should_cast_forward_inputs and state.mixed_precision.cast_forward_inputs:
403
+ # Recursively convert args and kwargs to specified precision.
404
+ input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
405
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
406
+ _register_post_backward_reshard_only_hook(state, handle, args, kwargs)
407
+ return args, kwargs
408
+
409
+
410
+ @no_type_check
411
+ def _pre_forward_unshard(
412
+ state: _FSDPState,
413
+ handle: Optional[FlatParamHandle],
414
+ ) -> None:
415
+ """Unshards parameters in the pre-forward."""
416
+ if not handle:
417
+ return
418
+ # If the handles have been prefetched, then there is no need to call
419
+ # `_unshard()` again
420
+ if not handle._prefetched:
421
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
422
+ handle._needs_pre_forward_unshard = False
423
+ # Don't wait during trace
424
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
425
+ current_stream = state._device_handle.current_stream()
426
+ if state._unshard_event is not None:
427
+ current_stream.wait_event(state._unshard_event)
428
+ state._unshard_event = None
429
+ else:
430
+ current_stream.wait_stream(state._unshard_stream)
431
+ with torch.profiler.record_function(
432
+ "FullyShardedDataParallel._pre_forward_prefetch"
433
+ ):
434
+ _prefetch_handle(state, handle, _PrefetchMode.FORWARD)
435
+
436
+
437
+ @no_type_check
438
+ def _post_forward(
439
+ state: _FSDPState,
440
+ handle: Optional[FlatParamHandle],
441
+ reshard_fn: Callable,
442
+ module: nn.Module,
443
+ input: Any,
444
+ output: Any,
445
+ ) -> Any:
446
+ """
447
+ Runs the post-forward logic. This includes an opportunity to reshard
448
+ currently unsharded parameters such as those used in the current forward
449
+ and registering pre-backward hooks on the forward outputs.
450
+
451
+ Args:
452
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
453
+ the current forward.
454
+ reshard_fn (Optional[Callable]): A callable to reshard any currently
455
+ unsharded parameters (e.g. from the current forward) or ``None`` to
456
+ not do any resharding.
457
+ module (nn.Module): Module whose forward just ran, which should be a
458
+ fully sharded module (see [Note: Fully Sharded Module]); expected
459
+ by the hook signature.
460
+ input (Any): Unused; expected by the hook signature.
461
+ output (Any): Forward pass output; pre-backward hooks are registered on
462
+ the tensors that require gradients in this output.
463
+
464
+ Postcondition: Each ``FlatParameter`` 's data points to the sharded flat
465
+ parameter.
466
+ """
467
+ with torch.profiler.record_function("FullyShardedDataParallel._post_forward"):
468
+ # For `fully_shard` + `checkpoint`, skip post-forward logic in the
469
+ # recomputed forward
470
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
471
+ return output
472
+
473
+ state._exec_order_data.record_post_forward(handle)
474
+ if reshard_fn is not None:
475
+ reshard_fn(state, handle)
476
+ # Register pre-backward hooks to unshard the flat parameters for the
477
+ # gradient computation (if needed)
478
+ output = _register_pre_backward_hooks(state, module, output, handle)
479
+ state.training_state = TrainingState.IDLE
480
+ if handle:
481
+ handle._training_state = HandleTrainingState.IDLE
482
+ return output
483
+
484
+
485
+ @no_type_check
486
+ def _post_forward_reshard(
487
+ state: _FSDPState,
488
+ handle: FlatParamHandle,
489
+ ) -> None:
490
+ """Reshards parameters in the post-forward."""
491
+ if not handle:
492
+ return
493
+ # Do not free the root's parameters in the post-forward for `FULL_SHARD`
494
+ # with the intention that they are immediately used for backward
495
+ # computation (though this may not be true)
496
+ free_unsharded_flat_param = (
497
+ not state._is_root
498
+ and handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
499
+ )
500
+ _reshard(state, handle, free_unsharded_flat_param)
501
+
502
+
503
+ @no_type_check
504
+ def _root_pre_forward(
505
+ state: _FSDPState,
506
+ module: nn.Module,
507
+ args,
508
+ kwargs,
509
+ ) -> None:
510
+ """
511
+ Runs pre-forward logic specific to the root FSDP instance, which should run
512
+ before any individual module's pre-forward. This starts with an attempt at
513
+ lazy initialization (which only runs non-vacuously once). Otherwise, if
514
+ this is called on a non-root FSDP instance, then it returns directly.
515
+
516
+ Args:
517
+ module (nn.Module): Module for which this logic tries to run. It may or
518
+ may not be the root. If not, then this method does not do anything.
519
+ """
520
+ with torch.profiler.record_function("FullyShardedDataParallel._root_pre_forward"):
521
+ _lazy_init(state, module)
522
+ _p_assert(state._is_root is not None, "Expects a root FSDP to have been set")
523
+ if not state._is_root:
524
+ # Always cast forward inputs in the root of this local FSDP unit for mixed
525
+ # precision, as this is where mixed precision could be configured.
526
+ # This is more useful for auto wrapping that is recommended in composable path.
527
+ # For manual wrapping, cast forward inputs on each local FSDP unit root will
528
+ # increase some overhead, so not turned on for model wrapper path right now where
529
+ # manual wrapping is more broadly used.
530
+ if _is_composable(state):
531
+ return _root_cast_forward_input(state, module, args, kwargs)
532
+ return args, kwargs
533
+
534
+ # We cast buffers back to full precision if we're forcing full precision. Disjointly, we check if buffers
535
+ # are in full precision and if we should cast them back to lower precision, which happens when
536
+ # exiting eval() mode.
537
+ handle = state._handle
538
+ if handle:
539
+ should_cast_buffers_to_full_prec = handle._force_full_precision
540
+ else:
541
+ # If the root has no handle (no managed parameters), then we fall
542
+ # back to checking if any child wants to force full precision as a
543
+ # workaround
544
+ handles = traversal_utils._get_fsdp_handles(module)
545
+ should_cast_buffers_to_full_prec = any(
546
+ handle._force_full_precision for handle in handles
547
+ )
548
+
549
+ if should_cast_buffers_to_full_prec:
550
+ _cast_buffers_to_dtype_and_device(
551
+ buffers=dict(module.named_buffers()).values(),
552
+ buffer_dtypes=list(state._buffer_name_to_orig_dtype.values()),
553
+ device=state.compute_device,
554
+ )
555
+ # This flag is only set when we cast buffers to full precision, to avoid the
556
+ # CPU overhead that can stem from retrieving all buffers and their types in the
557
+ # following else branch.
558
+ state._needs_buffer_dtype_restore_check = True
559
+ elif getattr(state, "_needs_buffer_dtype_restore_check", False):
560
+ # Check if buffers are in full precision and we need to cast them
561
+ # back down.
562
+ (
563
+ buffers,
564
+ buffer_dtypes_for_computation,
565
+ ) = _get_buffers_and_dtypes_for_computation(state, module)
566
+ if len(buffers) > 0 and len(buffer_dtypes_for_computation) > 0:
567
+ if any(
568
+ buffer.dtype != buffer_dtype_for_computation
569
+ for buffer, buffer_dtype_for_computation in zip(
570
+ buffers, buffer_dtypes_for_computation
571
+ )
572
+ ):
573
+ # Assume we have to cast everything if there is one mismatch
574
+ _cast_buffers_to_dtype_and_device(
575
+ buffers, buffer_dtypes_for_computation, state.compute_device
576
+ )
577
+ # We don't have to check this again until we cast buffers to full precision again.
578
+ state._needs_buffer_dtype_restore_check = False
579
+
580
+ if state.forward_prefetch:
581
+ handles = [
582
+ fsdp_state._handle
583
+ for fsdp_state in state._all_fsdp_states
584
+ if fsdp_state._handle
585
+ ]
586
+ for handle in handles:
587
+ handle._needs_pre_forward_unshard = True
588
+ handle._prefetched = False
589
+ _wait_for_computation_stream(
590
+ state._device_handle.current_stream(),
591
+ state._unshard_stream,
592
+ state._pre_unshard_stream,
593
+ )
594
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
595
+
596
+ # Prepares the forward inputs by moving them to ``compute_device``
597
+ # TODO: Do not use the side stream for tensor copies for now; investigate
598
+ # the perf with/without it.
599
+ with torch.profiler.record_function("FullyShardedDataParallel._to_kwargs"):
600
+ args_tuple, kwargs_tuple = _to_kwargs(
601
+ args, kwargs, state.compute_device, False
602
+ )
603
+ args = args_tuple[0] if args_tuple else tuple()
604
+ kwargs = kwargs_tuple[0] if kwargs_tuple else {}
605
+
606
+ return _root_cast_forward_input(state, module, args, kwargs)
607
+
608
+
609
+ @no_type_check
610
+ def _root_cast_forward_input(
611
+ state: _FSDPState, module: torch.nn.Module, args, kwargs
612
+ ) -> tuple[Any, Any]:
613
+ if state._handle:
614
+ force_full_precision = not state._handle._force_full_precision
615
+ else:
616
+ force_full_precision = True
617
+
618
+ should_cast_forward_inputs = (
619
+ (module.training or not state._use_full_prec_in_eval) and force_full_precision
620
+ ) and state.mixed_precision.cast_root_forward_inputs
621
+
622
+ if should_cast_forward_inputs:
623
+ input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
624
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
625
+
626
+ return args, kwargs
627
+
628
+
629
+ @no_type_check
630
+ def _pre_backward_hook(
631
+ state: _FSDPState,
632
+ module: nn.Module,
633
+ handle: FlatParamHandle,
634
+ grad,
635
+ *unused: Any,
636
+ ) -> Any:
637
+ """
638
+ Prepares ``_handle`` 's ``FlatParameter`` s for gradient computation.
639
+
640
+ Args:
641
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
642
+ Module]).
643
+ """
644
+ # Only run the pre-backward hook once per group of handles involved in the
645
+ # same module forward computation
646
+ if (
647
+ handle
648
+ and hasattr(handle, "_ran_pre_backward_hook")
649
+ and handle._ran_pre_backward_hook
650
+ ):
651
+ return grad
652
+
653
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_backward_hook"):
654
+ # Queue the post-backward callback once for the root FSDP instance to
655
+ # attach it to the outermost backward graph task so that it is called
656
+ # after all backward calls complete
657
+ if state._is_root and not state._post_backward_callback_queued:
658
+ _register_post_backward_final_callback(state, module)
659
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
660
+ elif handle:
661
+ allowed_states = [TrainingState.IDLE]
662
+ if _is_composable(state):
663
+ allowed_states.append(TrainingState.FORWARD_BACKWARD)
664
+ _assert_in_training_states(state, allowed_states)
665
+ state.training_state = TrainingState.FORWARD_BACKWARD
666
+ # Queueing the post-backward callback is the only logic that is not
667
+ # per-handle in the pre-backward hook, so we can return early here if
668
+ # there are no handles.
669
+ if not handle:
670
+ return grad
671
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
672
+
673
+ if handle._needs_pre_backward_unshard:
674
+ # If the handles have been prefetched, then there is no need to
675
+ # call `_unshard()` again
676
+ if not handle._prefetched:
677
+ _unshard(
678
+ state,
679
+ handle,
680
+ state._unshard_stream,
681
+ state._pre_unshard_stream,
682
+ )
683
+ # Don't wait during trace
684
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
685
+ state._device_handle.current_stream().wait_stream(state._unshard_stream)
686
+
687
+ # Set this to `False` to ensure that a mistargeted prefetch does not
688
+ # actually unshard these handles
689
+ handle._needs_pre_backward_unshard = False
690
+ with torch.profiler.record_function(
691
+ "FullyShardedDataParallel._pre_backward_prefetch"
692
+ ):
693
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
694
+ handle.prepare_gradient_for_backward()
695
+ handle._ran_pre_backward_hook = True
696
+ return grad
697
+
698
+
699
+ @no_type_check
700
+ @torch.no_grad()
701
+ def _post_backward_hook(
702
+ state: _FSDPState,
703
+ handle: FlatParamHandle,
704
+ flat_param,
705
+ *unused: Any,
706
+ ):
707
+ """
708
+ Reduce-scatters the gradient of ``handle`` 's ``FlatParameter``.
709
+
710
+ Precondition: The ``FlatParameter`` 's ``.grad`` attribute contains the
711
+ unsharded gradient for the local batch.
712
+
713
+ Postcondition:
714
+ - If using ``NO_SHARD``, then the ``.grad`` attribute is the reduced
715
+ unsharded gradient.
716
+ - Otherwise, the ``_saved_grad_shard`` attribute is the reduced sharded
717
+ gradient (accumulating with any existing gradient).
718
+ """
719
+ _log_post_backward_hook(state, handle, logger)
720
+ flat_param = handle.flat_param
721
+ flat_param._post_backward_called = True
722
+ with torch.autograd.profiler.record_function(
723
+ "FullyShardedDataParallel._post_backward_hook"
724
+ ):
725
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
726
+ # For multiple applications of reentrant AC across submodules sharing
727
+ # the same `FlatParameter`, the post-backward hook may run multiple
728
+ # times in one backward, in which case we permit the state to already
729
+ # be in `BACKWARD_POST`.
730
+ _p_assert(
731
+ handle._training_state
732
+ in (HandleTrainingState.BACKWARD_PRE, HandleTrainingState.BACKWARD_POST),
733
+ f"Expects `BACKWARD_PRE` or `BACKWARD_POST` state but got {handle._training_state}",
734
+ )
735
+ handle._training_state = HandleTrainingState.BACKWARD_POST
736
+
737
+ if flat_param.grad is None:
738
+ return
739
+ if flat_param.grad.requires_grad:
740
+ raise RuntimeError("FSDP does not support gradients of gradients")
741
+
742
+ _post_backward_reshard(state, handle)
743
+ if not state._sync_gradients:
744
+ if handle._use_orig_params:
745
+ handle._use_unsharded_grad_views()
746
+ return
747
+
748
+ # Wait for all ops in the current stream (e.g. gradient computation) to
749
+ # finish before reduce-scattering the gradient
750
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
751
+ state._post_backward_stream.wait_stream(
752
+ state._device_handle.current_stream()
753
+ )
754
+
755
+ with state._device_handle.stream(state._post_backward_stream):
756
+ autograd_computed_grad = flat_param.grad.data
757
+ if (
758
+ not _low_precision_hook_enabled(state)
759
+ and flat_param.grad.dtype != handle._reduce_dtype
760
+ # If we are forcing full precision but communicating grads
761
+ # (i.e. model.eval() + full precision in eval was configured), don't downcast gradient.
762
+ and not handle._force_full_precision
763
+ ):
764
+ flat_param.grad.data = flat_param.grad.to(handle._reduce_dtype)
765
+ if handle.uses_sharded_strategy:
766
+ _reduce_grad(state, handle)
767
+ else:
768
+ _reduce_grad_no_shard(state, handle)
769
+ # Since the unsharded gradient is produced in the computation
770
+ # stream and consumed in the post-backward stream, inform the
771
+ # caching allocator (before it goes out of scope)
772
+ _no_dispatch_record_stream(
773
+ autograd_computed_grad, state._post_backward_stream
774
+ )
775
+
776
+
777
+ def _post_backward_reshard_only_hook(
778
+ state: _FSDPState,
779
+ handle: FlatParamHandle,
780
+ *unused: Any,
781
+ ) -> None:
782
+ with torch.profiler.record_function(
783
+ "FullyShardedDataParallel._post_backward_hook_reshard_only"
784
+ ):
785
+ # `_pre_backward_hook` may not get executed
786
+ # if forward output does not require grad
787
+ # overwrite IDLE state for post-backward prefetching
788
+ state.training_state = TrainingState.FORWARD_BACKWARD
789
+ handle._training_state = HandleTrainingState.BACKWARD_POST
790
+ _post_backward_reshard(state, handle)
791
+
792
+
793
+ def _post_backward_reshard(
794
+ state: _FSDPState,
795
+ handle: FlatParamHandle,
796
+ *unused: Any,
797
+ ) -> None:
798
+ free_unsharded_flat_param = _should_free_in_backward(state, handle)
799
+ _reshard(state, handle, free_unsharded_flat_param)
800
+
801
+ # TODO: Post-backward prefetching does not support the multiple handles
802
+ # per module case since the post-backward hook runs per handle, not per
803
+ # group of handles.
804
+ with torch.profiler.record_function(
805
+ "FullyShardedDataParallel._post_backward_prefetch"
806
+ ):
807
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
808
+
809
+
810
+ @no_type_check
811
+ def _should_free_in_backward(
812
+ state: _FSDPState,
813
+ handle: FlatParamHandle,
814
+ ) -> bool:
815
+ """
816
+ Returns whether FSDP should free the unsharded flat parameter in the
817
+ post-backward or not.
818
+ """
819
+ if not handle.uses_sharded_strategy:
820
+ return False
821
+ # If not syncing gradients, then we do not free for strategies that do not
822
+ # reshard after forward as a *heuristic* to tradeoff higher memory for
823
+ # higher throughput.
824
+ return (
825
+ state._sync_gradients
826
+ or handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
827
+ )
828
+
829
+
830
+ @no_type_check
831
+ def _reduce_grad(state: _FSDPState, handle: FlatParamHandle) -> None:
832
+ """
833
+ For sharded strategies, this runs gradient reduction, sharded gradient
834
+ accumulation if needed, and the post-reduction callback.
835
+ """
836
+ flat_param = handle.flat_param
837
+ uses_hybrid_sharded_strategy = handle._sharding_strategy in (
838
+ HandleShardingStrategy.HYBRID_SHARD,
839
+ HandleShardingStrategy._HYBRID_SHARD_ZERO2,
840
+ )
841
+ # We clear `.grad` to permit multiple backwards. This avoids a race where
842
+ # the second backward pass computation precedes ahead of the first backward
843
+ # pass reduction, which is possible since the reduction is issued in a
844
+ # separate stream and is async and would result in reducing the wrong
845
+ # gradient.
846
+ unsharded_grad = flat_param.grad.data
847
+ flat_param.grad = None
848
+ padded_unsharded_grad, new_sharded_grad = _get_reduce_scatter_tensors(
849
+ state, unsharded_grad
850
+ )
851
+ if state._comm_hook is None: # default path
852
+ _div_if_needed(padded_unsharded_grad, state._gradient_predivide_factor)
853
+ pg = (
854
+ handle._fake_process_group
855
+ if handle._use_fake_reduce
856
+ else state.process_group
857
+ )
858
+ dist.reduce_scatter_tensor(
859
+ new_sharded_grad,
860
+ padded_unsharded_grad,
861
+ group=pg,
862
+ )
863
+ if uses_hybrid_sharded_strategy:
864
+ # Don't wait during trace
865
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
866
+ state._all_reduce_stream.wait_stream(state._post_backward_stream)
867
+ with state._device_handle.stream(state._all_reduce_stream):
868
+ # Since the new sharded gradient is produced in the post-
869
+ # backward stream and consumed in the all-reduce stream,
870
+ # inform the caching allocator
871
+ _no_dispatch_record_stream(new_sharded_grad, state._all_reduce_stream)
872
+ dist.all_reduce(new_sharded_grad, group=state._inter_node_pg)
873
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
874
+ grad_to_offload = _accumulate_sharded_grad(
875
+ state, handle, new_sharded_grad
876
+ )
877
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
878
+ return
879
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
880
+ else:
881
+ state._comm_hook(
882
+ state._comm_hook_state, padded_unsharded_grad, new_sharded_grad
883
+ )
884
+ # NOTE: HSDP variants do not support communication hook.
885
+ grad_to_offload = _accumulate_sharded_grad(state, handle, new_sharded_grad)
886
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
887
+
888
+
889
+ @no_type_check
890
+ def _get_reduce_scatter_tensors(
891
+ state: _FSDPState, unsharded_grad: torch.Tensor
892
+ ) -> tuple[torch.Tensor, torch.Tensor]:
893
+ """
894
+ Returns the input and output tensors to reduce-scatter, respectively.
895
+ """
896
+ chunks = list(unsharded_grad.chunk(state.world_size))
897
+ numel_to_pad = state.world_size * chunks[0].numel() - unsharded_grad.numel()
898
+ padded_unsharded_grad = (
899
+ F.pad(unsharded_grad, [0, numel_to_pad]) if numel_to_pad > 0 else unsharded_grad
900
+ )
901
+ new_sharded_grad = torch.empty_like(chunks[0]) # padded
902
+ return padded_unsharded_grad, new_sharded_grad
903
+
904
+
905
+ @no_type_check
906
+ def _accumulate_sharded_grad(
907
+ state: _FSDPState,
908
+ handle: FlatParamHandle,
909
+ sharded_grad: torch.Tensor,
910
+ ) -> torch.Tensor:
911
+ """
912
+ Accumulates the reduce-scattered sharded gradient with any existing sharded
913
+ gradient if needed, returning the gradient to offload (if CPU offloading is
914
+ enabled).
915
+ """
916
+ flat_param = handle.flat_param
917
+ _cast_grad_to_param_dtype(state, sharded_grad, flat_param)
918
+ # Save the sharded gradient in `_saved_grad_shard` to support gradient
919
+ # accumulation -- for multiple backwards, the gradient reductions may
920
+ # happen in arbitrary order
921
+ accumulate_grad = hasattr(flat_param, "_saved_grad_shard")
922
+ if accumulate_grad:
923
+ _check_grad_to_accumulate(sharded_grad, flat_param._saved_grad_shard)
924
+ flat_param._saved_grad_shard += sharded_grad
925
+ else:
926
+ flat_param._saved_grad_shard = sharded_grad
927
+ grad_to_offload = flat_param._saved_grad_shard
928
+ return grad_to_offload
929
+
930
+
931
+ @no_type_check
932
+ def _reduce_grad_no_shard(state: _FSDPState, handle: FlatParamHandle) -> None:
933
+ """
934
+ For no-shard, this runs gradient reduction (which directly covers any
935
+ gradient accumulation implicitly) and the post-reduction callback.
936
+ """
937
+ flat_param = handle.flat_param
938
+ if state._comm_hook is None: # default path
939
+ _div_if_needed(flat_param.grad, state._gradient_predivide_factor)
940
+ dist.all_reduce(flat_param.grad, group=state.process_group)
941
+ _div_if_needed(flat_param.grad, state._gradient_postdivide_factor)
942
+ else:
943
+ state._comm_hook(state._comm_hook_state, flat_param.grad)
944
+ # For `NO_SHARD`, we can keep the low precision gradients by simply
945
+ # omitting the cast altogether
946
+ if not handle._keep_low_precision_grads:
947
+ _cast_grad_to_param_dtype(state, flat_param.grad, flat_param)
948
+ grad_to_offload = flat_param.grad.data
949
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
950
+
951
+
952
+ @no_type_check
953
+ def _post_reduce_grad_callback(
954
+ state: _FSDPState,
955
+ handle: FlatParamHandle,
956
+ # Additional arguments needed for the callback logic
957
+ grad_to_offload: torch.Tensor,
958
+ ):
959
+ """
960
+ This callback captures any logic to run after the gradient reduction
961
+ finishes. Currently, this offloads the gradient to CPU if CPU offloading is
962
+ enabled and uses sharded gradient views if ``use_orig_params=True``.
963
+ """
964
+ _offload_grad(state, handle, grad_to_offload)
965
+ _post_backward_use_sharded_grad_views(handle)
966
+
967
+
968
+ @no_type_check
969
+ def _offload_grad(
970
+ state: _FSDPState,
971
+ handle: FlatParamHandle,
972
+ grad_to_offload: torch.Tensor,
973
+ ):
974
+ if not handle._offload_params:
975
+ return
976
+ # Offload the gradient to CPU to ensure parameters and gradients are on the
977
+ # same device as required by the optimizer
978
+ # TODO: Investigate why `NO_SHARD` breaks correctness when using
979
+ # `non_blocking=True` here.
980
+ # TODO (rohan-varma): When CPU offload and optimizer overlap,
981
+ # non_blocking=True won't work since the copy may have not finished before
982
+ # the optimizer step executes on CPU. If we want to use non-blocking=True
983
+ # here, we'll have to synchronize before using result on CPU.
984
+ non_blocking = handle.uses_sharded_strategy and not handle._has_optim_in_backward
985
+ handle.flat_param._cpu_grad.copy_(
986
+ grad_to_offload.detach(), non_blocking=non_blocking
987
+ ) # synchronized in the post-backward callback
988
+ # Since the gradient being offloaded may have been produced in the
989
+ # computation stream and is being consumed here in the post-backward
990
+ # stream, inform the caching allocator
991
+ _no_dispatch_record_stream(grad_to_offload.data, state._post_backward_stream)
992
+
993
+
994
+ @no_type_check
995
+ def _post_backward_use_sharded_grad_views(handle: FlatParamHandle):
996
+ if not handle._use_orig_params:
997
+ return
998
+ # Since the handle's `FlatParameter` completed its gradient computation, we
999
+ # should reset the gradient noneness mask
1000
+ handle._reset_is_grad_none()
1001
+ # Delay using sharded gradient views until after the reduce-scatter instead
1002
+ # of immediately after resharding
1003
+ handle._use_sharded_grad_views()
1004
+ if handle._has_optim_in_backward:
1005
+ handle.prepare_gradient_for_optim()
1006
+ for orig_param in handle.flat_param._params:
1007
+ # Check for `None` gradient to filter parameters not in the rank
1008
+ if orig_param.grad is not None and hasattr(
1009
+ orig_param, "_in_backward_optimizers"
1010
+ ):
1011
+ # TODO (rohan-varma): For CPU offload, this unfortunately
1012
+ # operates on CPU because the parameters and gradients have
1013
+ # already been offloaded. We should run this on GPU after
1014
+ # refactoring.
1015
+ for optim in orig_param._in_backward_optimizers:
1016
+ optim.step()
1017
+
1018
+ optim.zero_grad(set_to_none=True)
1019
+ handle._reset_flat_param_grad_info_if_needed()
1020
+ if handle._offload_params:
1021
+ handle.flat_param._cpu_grad = None
1022
+
1023
+
1024
+ def _div_if_needed(tensor: torch.Tensor, div_factor: float) -> None:
1025
+ if div_factor > 1:
1026
+ tensor.div_(div_factor)
1027
+
1028
+
1029
+ @no_type_check
1030
+ def _cast_grad_to_param_dtype(
1031
+ state: _FSDPState,
1032
+ sharded_grad: torch.Tensor,
1033
+ param: FlatParameter,
1034
+ ):
1035
+ """
1036
+ Casts ``sharded_grad`` back to the full parameter dtype so that the
1037
+ optimizer step runs with that dtype. This performs an actual cast if
1038
+ 1. parameters were in reduced precision during the forward since then
1039
+ gradients would be in that reduced precision, or
1040
+ 2. parameters were not in reduced precision but gradients were in
1041
+ reduced precision for communication.
1042
+ However, if a low precision communication hook is registered, then this
1043
+ dtype cast happens in the hook instead.
1044
+ """
1045
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
1046
+ if not _low_precision_hook_enabled(state) and sharded_grad.dtype != param.dtype:
1047
+ low_prec_grad_data = sharded_grad.data
1048
+ sharded_grad.data = sharded_grad.data.to(dtype=param.dtype)
1049
+ # Since for `NO_SHARD`, the gradient is produced in the computation
1050
+ # stream and consumed here in the post-backward stream, inform the
1051
+ # caching allocator; for the sharded strategies, the gradient is
1052
+ # produced in the post-backward stream, so this `record_stream()`
1053
+ # should be a no-op
1054
+ _no_dispatch_record_stream(
1055
+ low_prec_grad_data, state._device_handle.current_stream()
1056
+ )
1057
+
1058
+
1059
+ def _check_grad_to_accumulate(
1060
+ new_sharded_grad: torch.Tensor,
1061
+ accumulated_grad: torch.Tensor,
1062
+ ) -> None:
1063
+ _p_assert(
1064
+ accumulated_grad.shape == new_sharded_grad.shape,
1065
+ "Shape mismatch when accumulating gradients: "
1066
+ f"existing gradient shape={accumulated_grad.shape} "
1067
+ f"new gradient shape={new_sharded_grad.shape}",
1068
+ )
1069
+ _p_assert(
1070
+ accumulated_grad.device == new_sharded_grad.device,
1071
+ "Device mismatch when accumulating gradients: "
1072
+ f"existing gradient device={accumulated_grad.device} "
1073
+ f"new gradient device={new_sharded_grad.device}",
1074
+ )
1075
+
1076
+
1077
+ @no_type_check
1078
+ def _low_precision_hook_enabled(state: _FSDPState) -> bool:
1079
+ return state._comm_hook in LOW_PRECISION_HOOKS
1080
+
1081
+
1082
+ @no_type_check
1083
+ @torch.no_grad()
1084
+ def _post_backward_final_callback(
1085
+ state: _FSDPState,
1086
+ module: nn.Module,
1087
+ ):
1088
+ """
1089
+ This waits for the post-backward to finish and performs some final cleanup.
1090
+ This runs at the end of the entire backward pass and should only be called
1091
+ on the root FSDP instance.
1092
+ """
1093
+ _p_assert(
1094
+ state._is_root,
1095
+ "The post-backward callback should only be called on the root FSDP instance",
1096
+ )
1097
+ root_state = state
1098
+
1099
+ if root_state._sync_gradients:
1100
+ current_stream = state._device_handle.current_stream()
1101
+ # TODO (rohan-varma): this also waits for the overlapped optimizer step to finish
1102
+ # since it currently runs in the post-backward stream. That can be
1103
+ # pushed to the next forward if run in a different stream
1104
+ current_stream.wait_stream(root_state._post_backward_stream)
1105
+ if root_state._all_reduce_stream is not current_stream: # uses HSDP
1106
+ current_stream.wait_stream(root_state._all_reduce_stream)
1107
+ if root_state.cpu_offload.offload_params:
1108
+ # Wait for non-blocking GPU -> CPU sharded gradient copies from the
1109
+ # post-backward hooks to finish explicitly since CPU gradients do
1110
+ # not automatically synchronize with the GPU
1111
+ state._device_handle.current_stream().synchronize()
1112
+ root_state._exec_order_data.next_iter()
1113
+
1114
+ for fsdp_state in state._all_fsdp_states:
1115
+ _catch_all_reshard(fsdp_state)
1116
+ _finalize_params(fsdp_state)
1117
+ fsdp_state.training_state = TrainingState.IDLE
1118
+ handle = fsdp_state._handle
1119
+ if handle:
1120
+ handle._ran_pre_backward_hook = False
1121
+ handle._needs_pre_backward_unshard = False
1122
+ handle._post_forward_index = None
1123
+ handle._training_state = HandleTrainingState.IDLE
1124
+ handle._prefetched = False
1125
+ # Reset for cases like one forward and multiple backwards
1126
+ root_state._post_backward_callback_queued = False
1127
+
1128
+
1129
+ @no_type_check
1130
+ def _catch_all_reshard(
1131
+ state: _FSDPState,
1132
+ ) -> None:
1133
+ """
1134
+ Reshards the parameters that may not have been resharded in the
1135
+ post-backward hook. This can happen when a module's output is used in the
1136
+ forward pass, meaning that its pre-backward hook runs (unsharding the
1137
+ parameter), but the post-backward hook does not run because the output was
1138
+ not jused in the loss computation corresponding to this backward pass.
1139
+ """
1140
+ # Wrap with a try-except to provide a more informative traceback if an
1141
+ # error is raised
1142
+ try:
1143
+ if state._handle:
1144
+ # TODO: This already-resharded check is brittle:
1145
+ # https://github.com/pytorch/pytorch/issues/83956
1146
+ already_resharded = (
1147
+ state._handle.flat_param.data_ptr()
1148
+ == state._handle.flat_param._local_shard.data_ptr()
1149
+ # If FSDP skipped using sharded views, then the flat parameter
1150
+ # still points to the sharded data, so we need to reshard to
1151
+ # use sharded views
1152
+ and not state._handle._skipped_use_sharded_views
1153
+ )
1154
+ if already_resharded:
1155
+ return
1156
+ free_unsharded_flat_param = _should_free_in_backward(state, state._handle)
1157
+ _reshard(state, state._handle, free_unsharded_flat_param)
1158
+ except Exception as e:
1159
+ _p_assert(
1160
+ False,
1161
+ f"Got exception in the catch-all reshard for {state}: {str(e)}",
1162
+ raise_assertion_error=False,
1163
+ )
1164
+ raise e
1165
+
1166
+
1167
+ @no_type_check
1168
+ def _finalize_params(
1169
+ state: _FSDPState,
1170
+ ) -> None:
1171
+ """Finalizes the parameters before the next iteration."""
1172
+ handle = state._handle
1173
+ if not handle:
1174
+ return
1175
+ flat_param = handle.flat_param
1176
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1177
+ if hasattr(flat_param, "_post_backward_hook_handle"):
1178
+ pbhs_handle = flat_param._post_backward_hook_handle
1179
+ pbhs_handle.remove()
1180
+ del flat_param._post_backward_hook_handle
1181
+ else:
1182
+ if hasattr(flat_param, "_post_backward_hook_state"):
1183
+ post_backward_hook_state_len = len(flat_param._post_backward_hook_state)
1184
+ expected_post_backward_hook_state_len = int(flat_param.requires_grad) + 1
1185
+ _p_assert(
1186
+ post_backward_hook_state_len == expected_post_backward_hook_state_len,
1187
+ f"Invalid: ``_post_backward_hook_state``: {flat_param._post_backward_hook_state}",
1188
+ )
1189
+ flat_param._post_backward_hook_state[-1].remove()
1190
+ delattr(flat_param, "_post_backward_hook_state")
1191
+ if flat_param.requires_grad:
1192
+ if not state._sync_gradients:
1193
+ # Preserve the gradient accumulation state if not synchronizing
1194
+ # gradients: `.grad` remains the unsharded gradient from prior
1195
+ # `no_sync()` iterations, and `_saved_grad_shard` remains the
1196
+ # sharded gradient from the last synchronized iteration
1197
+ return
1198
+ if not handle._has_optim_in_backward:
1199
+ handle.prepare_gradient_for_optim()
1200
+ _p_assert(
1201
+ hasattr(flat_param, "_post_backward_called"),
1202
+ "Expects `_post_backward_called` to be set on the `FlatParameter`",
1203
+ )
1204
+ flat_param._post_backward_called = False
1205
+
1206
+
1207
+ @no_type_check
1208
+ def _prefetch_handle(
1209
+ state: _FSDPState,
1210
+ current_handle: Optional[FlatParamHandle],
1211
+ prefetch_mode: _PrefetchMode,
1212
+ ) -> None:
1213
+ """
1214
+ Prefetches the next handles if needed (without synchronization). An empty
1215
+ handles key cannot prefetch.
1216
+ """
1217
+ if not current_handle:
1218
+ return
1219
+ handle = _get_handle_to_prefetch(state, current_handle)
1220
+ if not handle:
1221
+ return
1222
+ # Temporarily emulate the training state while calling `_unshard` to
1223
+ # ensure the correct `as_params` for `_use_unsharded_views()`
1224
+ prev_training_state = handle._training_state
1225
+ if prefetch_mode == _PrefetchMode.BACKWARD:
1226
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
1227
+ elif prefetch_mode == _PrefetchMode.FORWARD:
1228
+ handle._training_state = HandleTrainingState.FORWARD
1229
+ else:
1230
+ raise ValueError(f"Invalid prefetch mode on rank {state.rank}: {prefetch_mode}")
1231
+ # Prefetch the next set of handles without synchronizing to allow
1232
+ # the sync to happen as late as possible to maximize overlap
1233
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
1234
+ handle._training_state = prev_training_state
1235
+ handle._prefetched = True
1236
+
1237
+
1238
+ @no_type_check
1239
+ def _get_handle_to_prefetch(
1240
+ state: _FSDPState,
1241
+ current_handle: FlatParamHandle,
1242
+ ) -> FlatParamHandle:
1243
+ """
1244
+ Returns a :class:`list` of the handles keys to prefetch for the next
1245
+ module(s), where ``current_handle`` represents the current module.
1246
+
1247
+ "Prefetching" refers to running the unshard logic early (without
1248
+ synchronization), and the "next" modules depend on the recorded execution
1249
+ order and the current training state.
1250
+ """
1251
+ training_state = _get_training_state(current_handle)
1252
+ valid_training_states = (
1253
+ HandleTrainingState.BACKWARD_PRE,
1254
+ HandleTrainingState.BACKWARD_POST,
1255
+ HandleTrainingState.FORWARD,
1256
+ )
1257
+ _p_assert(
1258
+ training_state in valid_training_states,
1259
+ f"Prefetching is only supported in {valid_training_states} but "
1260
+ f"currently in {training_state}",
1261
+ )
1262
+ eod = state._exec_order_data
1263
+ target_handle: Optional[FlatParamHandle] = None
1264
+ if (
1265
+ training_state == HandleTrainingState.BACKWARD_PRE
1266
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_PRE
1267
+ ) or (
1268
+ training_state == HandleTrainingState.BACKWARD_POST
1269
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_POST
1270
+ ):
1271
+ target_handle_candidate = eod.get_handle_to_backward_prefetch(current_handle)
1272
+ if (
1273
+ target_handle_candidate
1274
+ and target_handle_candidate._needs_pre_backward_unshard
1275
+ and not target_handle_candidate._prefetched
1276
+ ):
1277
+ target_handle = target_handle_candidate
1278
+ else:
1279
+ target_handle = None
1280
+ elif training_state == HandleTrainingState.FORWARD and state.forward_prefetch:
1281
+ target_handle_candidate = eod.get_handle_to_forward_prefetch(current_handle)
1282
+ if (
1283
+ target_handle_candidate
1284
+ and target_handle_candidate._needs_pre_forward_unshard
1285
+ and not target_handle_candidate._prefetched
1286
+ ):
1287
+ target_handle = target_handle_candidate
1288
+ else:
1289
+ target_handle = None
1290
+
1291
+ return target_handle
1292
+
1293
+
1294
+ def _get_training_state(
1295
+ handle: FlatParamHandle,
1296
+ ) -> HandleTrainingState:
1297
+ """Returns the training state of the handles in ``handle``."""
1298
+ _p_assert(handle, "Expects a non-empty handle")
1299
+ return handle._training_state
1300
+
1301
+
1302
+ @no_type_check
1303
+ def _register_pre_forward_hook(
1304
+ state: _FSDPState,
1305
+ module: nn.Module,
1306
+ ) -> None:
1307
+ """
1308
+ Registers a pre-forward hook on ``module``.
1309
+ """
1310
+ for forward_handle in state._pre_forward_handles:
1311
+ forward_handle.remove()
1312
+ state._pre_forward_handles.clear()
1313
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1314
+ hook = functools.partial(
1315
+ _pre_forward, state, module_param_handle, _pre_forward_unshard
1316
+ )
1317
+ state._pre_forward_handles.append(
1318
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1319
+ )
1320
+
1321
+
1322
+ @no_type_check
1323
+ def _register_post_forward_hook(
1324
+ state: _FSDPState,
1325
+ module: nn.Module,
1326
+ ) -> None:
1327
+ """
1328
+ Registers a post-forward hook on ``module``. Even if the module has no
1329
+ handles, we should register the hook since it will register the module's
1330
+ pre-backward hook.
1331
+ """
1332
+ for forward_handle in state._post_forward_handles:
1333
+ forward_handle.remove()
1334
+ state._post_forward_handles.clear()
1335
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1336
+ hook = functools.partial(
1337
+ _post_forward,
1338
+ state,
1339
+ module_param_handle,
1340
+ _post_forward_reshard,
1341
+ )
1342
+ state._post_forward_handles.append(module.register_forward_hook(hook))
1343
+
1344
+
1345
+ @no_type_check
1346
+ def _register_root_pre_forward_hook(
1347
+ state: _FSDPState,
1348
+ module: nn.Module,
1349
+ ):
1350
+ """
1351
+ Registers root pre-forward hook on ``module``, which should be the local
1352
+ FSDP root.
1353
+
1354
+ NOTE: For the current composable FSDP design, we have each application of
1355
+ ``fully_shard()`` to a module to indicate that that module is the local
1356
+ FSDP root. We may remove this assumption in the future, in which case we
1357
+ will need to register this root pre-forward hook on any candidate module
1358
+ that may be the local FSDP root.
1359
+ """
1360
+ for forward_handle in state._root_pre_forward_handles:
1361
+ forward_handle.remove()
1362
+ state._root_pre_forward_handles.clear()
1363
+ hook = functools.partial(_root_pre_forward, state)
1364
+ state._root_pre_forward_handles.append(
1365
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1366
+ )
1367
+
1368
+
1369
+ @no_type_check
1370
+ def _register_pre_backward_hooks(
1371
+ state: _FSDPState,
1372
+ module: nn.Module,
1373
+ outputs: Any,
1374
+ handle: FlatParamHandle,
1375
+ ) -> None:
1376
+ """
1377
+ Registers pre-backward hooks on the tensors that require gradients in the
1378
+ forward pass outputs ``outputs``, which were computed using the
1379
+ ``FlatParameter`` s of ``handles``.
1380
+
1381
+ Args:
1382
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
1383
+ Module]).
1384
+
1385
+ Returns:
1386
+ Forward pass outputs with pre-backward hooks registered to tensors that
1387
+ require gradients.
1388
+ """
1389
+ # If there is no gradient computation, then there is no need for
1390
+ # pre-backward logic
1391
+ if not torch.is_grad_enabled():
1392
+ return outputs
1393
+ if state._is_root:
1394
+ state._post_backward_callback_queued = False # only defined on the root
1395
+
1396
+ if handle:
1397
+ handle._needs_pre_backward_unshard = False
1398
+ # Since these handles' `FlatParameter`s participated in a forward, we
1399
+ # conservatively assume that they will be used in the backward
1400
+ handle._ran_pre_backward_hook = False
1401
+
1402
+ def _register_hook(t: torch.Tensor) -> torch.Tensor:
1403
+ if t.requires_grad:
1404
+ t.register_hook(
1405
+ torch.utils.hooks.unserializable_hook(
1406
+ functools.partial(_pre_backward_hook, state, module, handle)
1407
+ )
1408
+ )
1409
+ if handle:
1410
+ handle._needs_pre_backward_unshard = True
1411
+ return t
1412
+
1413
+ return _apply_to_tensors(_register_hook, outputs)
1414
+
1415
+
1416
+ def _register_post_backward_hook(
1417
+ state: _FSDPState,
1418
+ handle: Optional[FlatParamHandle],
1419
+ ) -> None:
1420
+ """
1421
+ Registers post-backward hooks on the ``FlatParameter`` s'
1422
+ ``AccumulateGrad`` objects to reshard and to reduce-scatter gradients.
1423
+
1424
+ The ``AccumulateGrad`` object represents the last function that finalizes
1425
+ the ``FlatParameter`` 's gradient, so it only runs after its entire
1426
+ gradient computation has finished.
1427
+
1428
+ We register the post-backward hook only once in the *first* forward that a
1429
+ ``FlatParameter`` participates in. This relies on the ``AccumulateGrad``
1430
+ object being preserved through multiple forwards.
1431
+
1432
+ NOTE: We follow this heuristic to prefer the *first* forward to target the
1433
+ parameter mixed precision case, where there are *separate*
1434
+ ``AccumulateGrad`` objects across the different forwards. (Without
1435
+ parameter mixed precision, the ``AccumulateGrad`` objects are the same.) If
1436
+ we instead prefer the *last* forward, then the hook runs early.
1437
+ """
1438
+ # If there is no gradient computation, then there is no need for
1439
+ # post-backward logic
1440
+ if not torch.is_grad_enabled():
1441
+ return
1442
+ if not handle:
1443
+ return
1444
+ flat_param = handle.flat_param
1445
+
1446
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1447
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1448
+ if already_registered or not flat_param.requires_grad:
1449
+ return
1450
+ hook = functools.partial(_post_backward_hook, state, handle)
1451
+ hook_handle = flat_param.register_post_accumulate_grad_hook(hook)
1452
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined]
1453
+ else:
1454
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1455
+ if already_registered or not flat_param.requires_grad:
1456
+ return
1457
+ # Get the `AccumulateGrad` object
1458
+ temp_flat_param = flat_param.expand_as(flat_param)
1459
+ _p_assert(
1460
+ temp_flat_param.grad_fn is not None,
1461
+ "The `grad_fn` is needed to access the `AccumulateGrad` and "
1462
+ "register the post-backward hook",
1463
+ )
1464
+ acc_grad = temp_flat_param.grad_fn.next_functions[0][0] # type: ignore[union-attr]
1465
+ if acc_grad is None:
1466
+ raise AssertionError("Expected acc_grad to be set")
1467
+ hook_handle = acc_grad.register_hook(
1468
+ functools.partial(_post_backward_hook, state, handle)
1469
+ )
1470
+ flat_param._post_backward_hook_state = (acc_grad, hook_handle) # type: ignore[attr-defined]
1471
+
1472
+
1473
+ def _register_post_backward_reshard_only_hook(
1474
+ state: _FSDPState,
1475
+ handle: Optional[FlatParamHandle],
1476
+ args: tuple[Any, ...],
1477
+ kwargs: dict[str, Any],
1478
+ ) -> None:
1479
+ """
1480
+ Registers post-backward hooks to reshard flat parameters that do not
1481
+ require gradient. We register these using multi-post-grad hooks on the
1482
+ input activations to ensure that all gradients that may depend on the
1483
+ parameters have been computed before resharding.
1484
+ """
1485
+ # If there is no gradient computation, then there is no need for
1486
+ # post-backward logic
1487
+ if not torch.is_grad_enabled():
1488
+ return
1489
+ # Construct `inp_tensors` lazily to avoid CPU overhead in typical case
1490
+ # where each flat parameter requires gradient
1491
+ inp_tensors: Optional[list[torch.Tensor]] = None
1492
+ if not handle:
1493
+ return
1494
+ flat_param = handle.flat_param
1495
+
1496
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1497
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1498
+ else:
1499
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1500
+
1501
+ if already_registered or flat_param.requires_grad:
1502
+ return
1503
+ if inp_tensors is None:
1504
+ args_flat = pytree.arg_tree_leaves(*args, **kwargs)
1505
+ inp_tensors = [
1506
+ obj for obj in args_flat if torch.is_tensor(obj) and obj.requires_grad
1507
+ ]
1508
+ if inp_tensors is None:
1509
+ raise AssertionError("Expected inp_tensors to be set")
1510
+ hook_handle = register_multi_grad_hook(
1511
+ inp_tensors, functools.partial(_post_backward_reshard_only_hook, state, handle)
1512
+ )
1513
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1514
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined, assignment]
1515
+ else:
1516
+ flat_param._post_backward_hook_state = (hook_handle,) # type: ignore[attr-defined, assignment]
1517
+
1518
+
1519
+ @no_type_check
1520
+ def _register_post_backward_final_callback(
1521
+ state: _FSDPState, module: nn.Module
1522
+ ) -> None:
1523
+ """
1524
+ Registers the post-backward final callback that runs at the end of the
1525
+ backward pass. This should be called from the root FSDP instance at the
1526
+ beginning of the pre-backward.
1527
+ """
1528
+ _p_assert(
1529
+ state._is_root,
1530
+ "Only the root FSDP instance should register the post-backward callback",
1531
+ )
1532
+ if state._post_backward_callback_queued:
1533
+ return
1534
+ _assert_in_training_states(state, [TrainingState.IDLE])
1535
+ # Trace does not need this callback
1536
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
1537
+ state._post_backward_callback_queued = True
1538
+ Variable._execution_engine.queue_callback(
1539
+ functools.partial(_post_backward_final_callback, state, module)
1540
+ )
1541
+
1542
+
1543
+ def _wait_for_computation_stream(
1544
+ computation_stream: torch.Stream,
1545
+ unshard_stream: torch.Stream,
1546
+ pre_unshard_stream: torch.Stream,
1547
+ ):
1548
+ """
1549
+ Has the unshard and pre-unshard streams wait for the computation stream.
1550
+ For example, this should be called in the FSDP root's pre-forward to
1551
+ respect optimizer step computation.
1552
+ """
1553
+ # Tracing does not need to wait
1554
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1555
+ return
1556
+ unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1557
+ # Having the pre-all-gather stream wait for the current stream even if we
1558
+ # do not leverage the pre-all-gather stream is tolerable since this only
1559
+ # runs once per iteration
1560
+ pre_unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1561
+
1562
+
1563
+ def _reset_flat_param_grad_info_if_needed(
1564
+ handles: list[FlatParamHandle],
1565
+ ):
1566
+ """
1567
+ Clears the original parameters' gradients if needed. This method's CPU
1568
+ overhead is minimal, so we may call it throughout FSDP methods, which serve
1569
+ as callsites to free the gradient memory earlier.
1570
+ """
1571
+ if not isinstance(handles, list):
1572
+ handles = [handles]
1573
+ for handle in handles:
1574
+ if handle._use_orig_params:
1575
+ handle._reset_flat_param_grad_info_if_needed()
1576
+
1577
+
1578
+ @no_type_check
1579
+ def _get_buffers_and_dtypes_for_computation(
1580
+ state: _FSDPState,
1581
+ root_module: nn.Module,
1582
+ ) -> tuple[list[torch.Tensor], list[Optional[torch.dtype]]]:
1583
+ """
1584
+ Returns all buffers in the module tree rooted at ``root_module`` and a
1585
+ corresponding list of the buffer dtypes for computation. Each buffer dtype
1586
+ is either ``None`` if buffer mixed precision is not enabled or the buffer
1587
+ low precision dtype otherwise.
1588
+ """
1589
+ _p_assert(state._is_root, "Expects the root to cast buffers")
1590
+ buffers: list[torch.Tensor] = []
1591
+ buffer_dtypes: list[Optional[torch.dtype]] = []
1592
+ visited_buffers: set[torch.Tensor] = set()
1593
+ # Traverse the FSDP states bottom-up so that we prefer the owning FSDP
1594
+ # instance's mixed precision setting for each buffer
1595
+ fsdp_states, fsdp_modules = traversal_utils._get_fsdp_states_with_modules(
1596
+ root_module
1597
+ )
1598
+ for fsdp_state, fsdp_module in zip(reversed(fsdp_states), reversed(fsdp_modules)):
1599
+ for buffer_name, buffer in fsdp_module.named_buffers():
1600
+ if buffer in visited_buffers:
1601
+ continue
1602
+ visited_buffers.add(buffer)
1603
+ if clean_tensor_name(buffer_name) in fsdp_state._ignored_buffer_names:
1604
+ continue
1605
+ buffers.append(buffer)
1606
+ buffer_dtypes.append(fsdp_state.mixed_precision.buffer_dtype)
1607
+ if len(buffers) != len(buffer_dtypes):
1608
+ raise AssertionError(
1609
+ f"Expected buffers and buffer_dtypes to have the same length, got {len(buffers)} and {len(buffer_dtypes)}"
1610
+ )
1611
+ return buffers, buffer_dtypes
1612
+
1613
+
1614
+ @no_type_check
1615
+ def _get_orig_buffer_dtypes(
1616
+ state: _FSDPState,
1617
+ buffer_names: list[str],
1618
+ ) -> list[torch.dtype]:
1619
+ """
1620
+ Returns the original buffer types of the given buffer names.
1621
+ """
1622
+ buffer_dtypes: list[torch.dtype] = []
1623
+ for buffer_name in buffer_names:
1624
+ _p_assert(
1625
+ buffer_name in state._buffer_name_to_orig_dtype,
1626
+ f"{buffer_name} is missing from pre-computed dict on rank "
1627
+ f"{state.rank}, which only has keys "
1628
+ f"{state._buffer_name_to_orig_dtype.keys()}",
1629
+ )
1630
+ buffer_dtypes.append(state._buffer_name_to_orig_dtype[buffer_name])
1631
+ return buffer_dtypes
1632
+
1633
+
1634
+ def _cast_buffers_to_dtype_and_device(
1635
+ buffers: list[torch.Tensor],
1636
+ buffer_dtypes: list[Optional[torch.dtype]],
1637
+ device: torch.device,
1638
+ ) -> None:
1639
+ """
1640
+ Casts ``buffers`` to the dtypes given by ``buffer_dtypes`` and moves them
1641
+ to ``device``. If an element in ``buffer_dtypes`` is ``None``, then the
1642
+ corresponding buffer is only moved to ``device``.
1643
+ """
1644
+ _p_assert(
1645
+ buffer_dtypes is None or len(buffers) == len(buffer_dtypes),
1646
+ f"Expects `buffers` and `buffer_dtypes` to have the same length if "
1647
+ f"`buffer_dtypes` is specified but got {len(buffers)} and "
1648
+ f"{len(buffer_dtypes)}",
1649
+ )
1650
+ for buffer, buffer_dtype in zip(buffers, buffer_dtypes):
1651
+ if not torch.is_floating_point(buffer) or buffer_dtype is None:
1652
+ buffer.data = buffer.to(device=device)
1653
+ else:
1654
+ buffer.data = buffer.to(device=device, dtype=buffer_dtype)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_shard_utils.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import itertools
4
+ import math
5
+ from typing import Optional
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from torch._utils import _get_device_module
10
+ from torch.distributed import distributed_c10d
11
+ from torch.distributed._shard.sharded_tensor import (
12
+ Shard,
13
+ ShardedTensor,
14
+ ShardedTensorMetadata,
15
+ TensorProperties,
16
+ )
17
+ from torch.distributed._shard.sharding_spec import ShardMetadata
18
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
19
+
20
+
21
+ def _get_remote_device_str(rank, device_type, num_devices_per_node):
22
+ if device_type.lower() == "cpu":
23
+ return f"rank:{rank}/{device_type}"
24
+ elif device_type.lower() == "hpu":
25
+ return f"rank:{rank}/{device_type}:{_get_device_module(device_type).current_device()}"
26
+ else:
27
+ return f"rank:{rank}/{device_type}:{rank % num_devices_per_node}"
28
+
29
+
30
+ def _create_chunk_sharded_tensor(
31
+ tensor: torch.Tensor,
32
+ rank: int,
33
+ world_size: int,
34
+ num_devices_per_node: int,
35
+ pg: dist.ProcessGroup,
36
+ device: Optional[torch.device] = None,
37
+ ) -> ShardedTensor:
38
+ """
39
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
40
+ corresponding chunk as the local shard to create a ShardedTensor.
41
+ """
42
+ chunks = tensor.chunk(world_size, dim=0)
43
+ if len(chunks) > rank:
44
+ local_shard = chunks[rank].clone()
45
+ offsets = [0 for _ in tensor.size()]
46
+ offsets[0] = math.ceil(tensor.size()[0] / world_size) * rank
47
+ local_shards = [Shard.from_tensor_and_offsets(local_shard, offsets, rank)]
48
+ else:
49
+ local_shards = []
50
+
51
+ # Create a ShardedTensor without invoking communication.
52
+ chunk_sizes = [list(chunk.size()) for chunk in chunks]
53
+ dim0_offsets = [0] + list(
54
+ itertools.accumulate([chunk_size[0] for chunk_size in chunk_sizes])
55
+ )[:-1]
56
+ offsets = [0] * (len(chunk_sizes[0]) - 1)
57
+ chunk_offsets = [[d0] + offsets for d0 in dim0_offsets]
58
+ device_type = (
59
+ distributed_c10d._get_pg_default_device(pg).type
60
+ if device is None
61
+ else device.type
62
+ )
63
+ placements = [
64
+ _get_remote_device_str(
65
+ dist.get_global_rank(pg, r),
66
+ device_type,
67
+ num_devices_per_node,
68
+ )
69
+ for r in range(len(chunk_sizes))
70
+ ]
71
+ if len(chunk_sizes) != len(chunk_offsets) or len(chunk_sizes) != len(placements):
72
+ raise AssertionError(
73
+ f"Expected chunk_sizes, chunk_offsets, and placements to have the same length, "
74
+ f"got {len(chunk_sizes)}, {len(chunk_offsets)}, {len(placements)}"
75
+ )
76
+ shard_metadata = [
77
+ ShardMetadata(offset, size, placement)
78
+ for offset, size, placement in zip(chunk_offsets, chunk_sizes, placements)
79
+ ]
80
+ sharded_tensor_metadata = ShardedTensorMetadata(
81
+ shards_metadata=shard_metadata,
82
+ size=tensor.size(),
83
+ tensor_properties=TensorProperties(
84
+ dtype=tensor.dtype,
85
+ layout=tensor.layout,
86
+ requires_grad=False,
87
+ memory_format=torch.contiguous_format,
88
+ pin_memory=tensor.is_pinned(),
89
+ ),
90
+ )
91
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
92
+ local_shards, sharded_tensor_metadata=sharded_tensor_metadata, process_group=pg
93
+ )
94
+
95
+
96
+ def _create_chunk_dtensor(
97
+ tensor: torch.Tensor,
98
+ rank: int,
99
+ device_mesh: DeviceMesh,
100
+ ) -> DTensor:
101
+ """
102
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
103
+ corresponding chunk as the local tensor to create a DTensor.
104
+ """
105
+ # We need to explicitly call .detach() to return a new tensor detached from the current graph.
106
+ tensor = tensor.detach().clone()
107
+
108
+ # FSDP placements: [Shard(0)]
109
+ # HSDP placements: [Replicate(), Shard(0)]
110
+ replicate_placements = [Replicate() for _ in range(device_mesh.ndim)]
111
+ shard_placements = [Replicate() for _ in range(device_mesh.ndim)]
112
+ shard_placements[-1] = DShard(0) # type: ignore[call-overload]
113
+
114
+ return DTensor.from_local(
115
+ tensor, device_mesh, replicate_placements, run_check=False
116
+ ).redistribute(
117
+ placements=shard_placements,
118
+ )
119
+
120
+
121
+ def _all_gather_dtensor(
122
+ tensor: DTensor,
123
+ root_mesh: Optional[DeviceMesh],
124
+ ) -> torch.Tensor:
125
+ """
126
+ All gather a DTensor in its sharded dimension and return the local tensor.
127
+ """
128
+ if root_mesh != tensor.device_mesh:
129
+ raise AssertionError("The device mesh of a tensor should be a root mesh.")
130
+
131
+ placements = list(copy.deepcopy(tensor.placements))
132
+ # FSDP placements: [Shard(0)] -> [Replicate()]
133
+ # HSDP placements: [Replicate(), Shard(0)] -> [Replicate(), Replicate()]
134
+ placements[-1] = Replicate()
135
+ tensor = tensor.redistribute(
136
+ device_mesh=tensor.device_mesh,
137
+ placements=placements,
138
+ )
139
+
140
+ return tensor.to_local()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_state_dict_utils.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ import math
5
+ import warnings
6
+ from collections.abc import Callable, Generator, Iterator
7
+ from typing import Any, cast, no_type_check
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.algorithms._checkpoint.checkpoint_wrapper as checkpoint_wrapper
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from torch.distributed._shard.sharded_tensor import (
15
+ init_from_local_shards,
16
+ Shard,
17
+ ShardedTensor,
18
+ )
19
+ from torch.distributed.fsdp._common_utils import (
20
+ _FSDPState,
21
+ _get_module_fsdp_state_if_fully_sharded_module,
22
+ _has_fsdp_params,
23
+ _is_composable,
24
+ _module_handle,
25
+ clean_tensor_name,
26
+ FSDP_PREFIX,
27
+ FSDP_WRAPPED_MODULE,
28
+ )
29
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
30
+ from torch.distributed.fsdp._runtime_utils import (
31
+ _cast_buffers_to_dtype_and_device,
32
+ _get_orig_buffer_dtypes,
33
+ _lazy_init,
34
+ _reset_flat_param_grad_info_if_needed,
35
+ )
36
+ from torch.distributed.fsdp.api import (
37
+ FullStateDictConfig,
38
+ ShardingStrategy,
39
+ StateDictType,
40
+ )
41
+ from torch.distributed.tensor import DTensor
42
+ from torch.distributed.utils import _replace_by_prefix
43
+
44
+ from ._fsdp_extensions import (
45
+ _ext_all_gather_dtensor,
46
+ _ext_chunk_dtensor,
47
+ _ext_chunk_tensor,
48
+ _ext_post_unflatten_transform,
49
+ _ext_pre_load_state_dict_transform,
50
+ )
51
+ from ._unshard_param_utils import _unshard_fsdp_state_params, FLAT_PARAM
52
+
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ def _should_unshard_params(fsdp_state: _FSDPState) -> bool:
58
+ return not (
59
+ fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
60
+ and (_is_composable(fsdp_state) or fsdp_state._use_orig_params)
61
+ )
62
+
63
+
64
+ def _convert_to_wrapped_module_name(module_name: str) -> str:
65
+ module_name = module_name.replace(f"{FSDP_PREFIX}", "")
66
+ module_name = module_name.replace(f"{FSDP_WRAPPED_MODULE}", "")
67
+ if module_name:
68
+ module_name = f"{module_name}."
69
+ # `CheckpointWrapper` adds a prefix that has to be removed as well.
70
+ module_name = module_name.replace(checkpoint_wrapper._CHECKPOINT_PREFIX, "")
71
+ return module_name
72
+
73
+
74
+ def _param_name_infos(
75
+ module: nn.Module, fsdp_state: _FSDPState
76
+ ) -> Iterator[tuple[str, str, str]]:
77
+ if not _has_fsdp_params(fsdp_state, module):
78
+ return
79
+ for param_name, module_name in _module_handle(
80
+ fsdp_state, module
81
+ ).param_module_names():
82
+ module_name = _convert_to_wrapped_module_name(module_name)
83
+ fqn = f"{module_name}{param_name}"
84
+ yield fqn, param_name, module_name
85
+
86
+
87
+ def _shared_param_name_infos(
88
+ module: nn.Module, fsdp_state
89
+ ) -> Iterator[tuple[str, str, str]]:
90
+ for param_name, module_name in _module_handle(
91
+ fsdp_state, module
92
+ ).shared_param_module_names():
93
+ module_name = _convert_to_wrapped_module_name(module_name)
94
+ fqn = f"{module_name}{param_name}"
95
+ yield fqn, param_name, module_name
96
+
97
+
98
+ @no_type_check
99
+ def _enter_unshard_params_ctx(
100
+ module: nn.Module,
101
+ fsdp_state: _FSDPState,
102
+ writeback: bool = False,
103
+ rank0_only: bool = False,
104
+ offload_to_cpu: bool = False,
105
+ with_grads: bool = False,
106
+ ) -> None:
107
+ """
108
+ state_dict hooks cannot use the pure context call as the checkpoint flow
109
+ requires to enter the context in the pre-hook but leave the context in the
110
+ post-hook. This API enters the context of ``_unshard_fsdp_state_params``.
111
+ """
112
+ if module in fsdp_state._unshard_params_ctx:
113
+ raise AssertionError(
114
+ "Entering the ``_unshard_fsdp_state_params`` context but _unshard_params_ctx[module] "
115
+ "is not None."
116
+ )
117
+ fsdp_state._unshard_params_ctx[module] = _unshard_fsdp_state_params(
118
+ module,
119
+ fsdp_state,
120
+ writeback=writeback,
121
+ rank0_only=rank0_only,
122
+ offload_to_cpu=offload_to_cpu,
123
+ with_grads=with_grads,
124
+ )
125
+ fsdp_state._unshard_params_ctx[module].__enter__()
126
+
127
+
128
+ @no_type_check
129
+ def _exit_unshard_params_ctx(module: nn.Module, fsdp_state: _FSDPState) -> None:
130
+ """A helper function to exit ``_unshard_fsdp_state_params`` context."""
131
+ fsdp_state._unshard_params_ctx[module].__exit__(None, None, None)
132
+ fsdp_state._unshard_params_ctx.pop(module)
133
+
134
+
135
+ def _common_pre_state_dict_hook(
136
+ module: nn.Module,
137
+ fsdp_state: _FSDPState,
138
+ ) -> None:
139
+ """Performs the pre-state_dict tasks shared by all state_dict types."""
140
+ if fsdp_state._device_handle.is_available():
141
+ fsdp_state._device_handle.synchronize()
142
+ # TODO: need to check if this is always correct for composable FSDP.
143
+ _lazy_init(fsdp_state, module)
144
+ if fsdp_state._is_root:
145
+ _reset_flat_param_grad_info_if_needed(fsdp_state._all_handles)
146
+
147
+
148
+ def _common_unshard_pre_state_dict_hook(
149
+ module: nn.Module,
150
+ fsdp_state: _FSDPState,
151
+ offload_to_cpu: bool,
152
+ rank0_only: bool,
153
+ ) -> None:
154
+ """
155
+ Performs the pre-state_dict tasks shared by all state_dict types that require
156
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this hook.
157
+ """
158
+ # For composable `fully_shard`, it does not need to unshard parameters for `NO_SHARD` cases.
159
+ if not _should_unshard_params(fsdp_state):
160
+ return
161
+ _enter_unshard_params_ctx(
162
+ module,
163
+ fsdp_state,
164
+ writeback=False,
165
+ offload_to_cpu=offload_to_cpu,
166
+ rank0_only=rank0_only,
167
+ )
168
+
169
+
170
+ @no_type_check
171
+ def _common_unshard_post_state_dict_hook(
172
+ module: nn.Module,
173
+ fsdp_state: _FSDPState,
174
+ state_dict: dict[str, Any],
175
+ prefix: str,
176
+ param_hook: Callable,
177
+ ) -> dict[str, Any]:
178
+ """
179
+ The post-state_dict flow that shared by all state_dict types that require
180
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this
181
+ hook.
182
+ """
183
+ _replace_by_prefix(state_dict, prefix + f"{FSDP_PREFIX}", prefix)
184
+ # Return early for trivial cases
185
+ if not state_dict or not _has_fsdp_params(fsdp_state, module):
186
+ if _should_unshard_params(fsdp_state):
187
+ _exit_unshard_params_ctx(module, fsdp_state)
188
+ return state_dict
189
+
190
+ # If a rank does not have unsharded parameters(when `rank0_only=True`
191
+ # and `rank != 0`), then the rank only needed to participate in the
192
+ # all-gather and does not need to save the # state dict. We simply check
193
+ # rank0_only to ensure this issue.
194
+ rank0_only = (
195
+ fsdp_state._state_dict_type == StateDictType.FULL_STATE_DICT
196
+ and cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only
197
+ )
198
+ # no_fsdp_return means the state_dict returned by this rank should contain
199
+ # only non-FSDP controlled parameters and buffers.
200
+ no_fsdp_return = rank0_only and fsdp_state.rank != 0
201
+ if no_fsdp_return and not fsdp_state._use_orig_params:
202
+ for clean_key in fsdp_state._buffer_names:
203
+ # This is a hack to support activation checkpoint.
204
+ clean_key = clean_key.replace(
205
+ f"{checkpoint_wrapper._CHECKPOINT_PREFIX}.", ""
206
+ )
207
+ state_dict.pop(f"{prefix}{clean_key}", None)
208
+ # Non-zero ranks have flat_param key when rank0_only=True, because rank0_only=True is
209
+ # passed in to unshard context, but nonzero ranks reshard early, causing this flat_param
210
+ # to appear in state_dict.
211
+ state_dict.pop(f"{prefix}{FLAT_PARAM}")
212
+ _exit_unshard_params_ctx(module, fsdp_state)
213
+ return state_dict
214
+
215
+ # Loop only the parameters saved in this instance's wrapped module to
216
+ # avoid processing buffers.
217
+ for fqn, param_name, module_name in _param_name_infos(module, fsdp_state):
218
+ fqn = f"{prefix}{fqn}"
219
+ if no_fsdp_return:
220
+ state_dict.pop(fqn)
221
+ continue
222
+ if fqn not in state_dict:
223
+ raise AssertionError(
224
+ f"FSDP assumes {fqn} is in the state_dict but the state_dict only "
225
+ f"has {state_dict.keys()}. "
226
+ f"prefix={prefix}, module_name={module_name}, "
227
+ f"param_name={param_name} rank={fsdp_state.rank}."
228
+ )
229
+
230
+ param_hook(state_dict, prefix, fqn)
231
+
232
+ if _should_unshard_params(fsdp_state):
233
+ _exit_unshard_params_ctx(module, fsdp_state)
234
+
235
+ cpu_device = torch.device("cpu")
236
+ buffer_clean_fqns = []
237
+ buffers = []
238
+ for clean_key in fsdp_state._buffer_names:
239
+ # This is a hack to support activation checkpoint.
240
+ clean_key = clean_tensor_name(clean_key)
241
+ fqn = f"{prefix}{clean_key}"
242
+ if fqn not in state_dict:
243
+ # A buffer can be registered as non-persistent.
244
+ continue
245
+ if no_fsdp_return:
246
+ state_dict.pop(fqn)
247
+ else:
248
+ buffer = state_dict[fqn]
249
+ if (
250
+ fsdp_state._state_dict_config.offload_to_cpu
251
+ and buffer.device != cpu_device
252
+ ):
253
+ state_dict[fqn] = buffer.to(cpu_device)
254
+ # skip upcasting for ignored buffers
255
+ if clean_key not in fsdp_state._ignored_buffer_names:
256
+ buffer_clean_fqns.append(clean_key)
257
+ buffers.append(state_dict[fqn])
258
+
259
+ if buffers:
260
+ mixed_precision_enabled_for_buffers = (
261
+ fsdp_state._mixed_precision_enabled_for_buffers()
262
+ if not _is_composable(fsdp_state)
263
+ else (fsdp_state.mixed_precision.buffer_dtype is not None)
264
+ )
265
+ if mixed_precision_enabled_for_buffers:
266
+ buffer_dtypes = _get_orig_buffer_dtypes(fsdp_state, buffer_clean_fqns)
267
+ _cast_buffers_to_dtype_and_device(
268
+ buffers, buffer_dtypes, fsdp_state.compute_device
269
+ )
270
+ for buffer, clean_fqn in zip(buffers, buffer_clean_fqns):
271
+ fqn = f"{prefix}{clean_fqn}"
272
+ logger.info("FSDP is casting the dtype of %s to %s", fqn, buffer.dtype)
273
+ state_dict[fqn] = buffer.clone()
274
+ return state_dict
275
+
276
+
277
+ @no_type_check
278
+ def _full_pre_state_dict_hook(
279
+ fsdp_state: _FSDPState,
280
+ module: nn.Module,
281
+ *args,
282
+ **kwargs,
283
+ ) -> None:
284
+ """
285
+ Hook that runs before model.state_dict() is called. pre-state_dict hook is
286
+ not actually supported by ``nn.Module``. As a result, this API is called
287
+ from ``_full_post_state_dict_hook()`` to simulate the case. Once pre-state_dict
288
+ is supported in ``nn.Module``, this hook will be registered as a hook in
289
+ ``nn.Module``.
290
+ """
291
+ if getattr(fsdp_state, "_device_mesh", False):
292
+ fsdp_state._device_mesh._get_root_mesh()
293
+
294
+ _common_pre_state_dict_hook(module, fsdp_state)
295
+ _common_unshard_pre_state_dict_hook(
296
+ module,
297
+ fsdp_state,
298
+ offload_to_cpu=fsdp_state._state_dict_config.offload_to_cpu,
299
+ rank0_only=cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only,
300
+ )
301
+
302
+
303
+ @no_type_check
304
+ def _full_post_state_dict_hook(
305
+ module: nn.Module,
306
+ fsdp_state: _FSDPState,
307
+ state_dict: dict[str, Any],
308
+ prefix: str,
309
+ ) -> dict[str, Any]:
310
+ """
311
+ Hook that runs after model.state_dict() is called before returning result to
312
+ user. For FSDP, we may have to clone the tensors in state_dict as params go
313
+ back to sharded version after _unshard_fsdp_state_params ends, and also remove
314
+ the ``FSDP_WRAPPED_MODULE`` prefix.
315
+ """
316
+
317
+ def param_hook(
318
+ state_dict: dict[str, Any],
319
+ prefix: str,
320
+ fqn: str,
321
+ ) -> None:
322
+ clean_key = fqn
323
+ clean_prefix = clean_tensor_name(prefix)
324
+ # Strip prefix out of key if needed as buffer names and param names
325
+ # do not have prefix considered as they are not computed in `state_dict`
326
+ # call.
327
+ clean_key = clean_key.removeprefix(clean_prefix)
328
+
329
+ # Clone parameters before exiting the `_unshard_fsdp_state_params()` context.
330
+ if not getattr(state_dict[fqn], "_has_been_cloned", False):
331
+ try:
332
+ state_dict[fqn] = state_dict[fqn].detach().clone()
333
+ state_dict[fqn]._has_been_cloned = True # type: ignore[attr-defined]
334
+ except BaseException as e: # noqa: B036
335
+ warnings.warn(
336
+ f"Failed to clone() tensor with name {fqn} on rank {fsdp_state.rank}. "
337
+ "This may mean that this state_dict entry could point to invalid "
338
+ "memory regions after returning from state_dict() call if this "
339
+ "parameter is managed by FSDP. Please check clone "
340
+ f"implementation of {fqn}. Error: {str(e)}",
341
+ stacklevel=2,
342
+ )
343
+
344
+ return _common_unshard_post_state_dict_hook(
345
+ module, fsdp_state, state_dict, prefix, param_hook
346
+ )
347
+
348
+
349
+ def _full_pre_load_state_dict_hook(
350
+ module: nn.Module,
351
+ fsdp_state: _FSDPState,
352
+ state_dict: dict[str, Any],
353
+ prefix: str,
354
+ ) -> None:
355
+ _lazy_init(fsdp_state, module)
356
+ if _should_unshard_params(fsdp_state):
357
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
358
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
359
+ # Add FSDP_PREFIX only for wrapper-based FSDP.
360
+ if not _is_composable(fsdp_state):
361
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
362
+
363
+
364
+ def _full_post_load_state_dict_hook(
365
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
366
+ ) -> None:
367
+ if _should_unshard_params(fsdp_state):
368
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
369
+ _exit_unshard_params_ctx(module, fsdp_state)
370
+
371
+
372
+ def _local_pre_state_dict_hook(
373
+ fsdp_state: _FSDPState,
374
+ module: nn.Module,
375
+ *args,
376
+ **kwargs,
377
+ ) -> None:
378
+ """
379
+ Hook that runs before model.state_dict() is called. Right now, pre-state_dict
380
+ hook is not supported by the PyTorch core. So this API is called from
381
+ `_local_post_state_dict_hook()` to simulate the case.
382
+ """
383
+ if (
384
+ _has_fsdp_params(fsdp_state, module)
385
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
386
+ ):
387
+ raise RuntimeError(
388
+ "``local_state_dict`` can only be used when parameters are flatten "
389
+ "and sharded."
390
+ )
391
+ _common_pre_state_dict_hook(module, fsdp_state)
392
+
393
+
394
+ @no_type_check
395
+ def _local_post_state_dict_hook(
396
+ module: nn.Module,
397
+ fsdp_state: _FSDPState,
398
+ state_dict: dict[str, Any],
399
+ prefix: str,
400
+ ) -> dict[str, Any]:
401
+ """
402
+ This hook create a ShardedTensor from the local flat_param and replace
403
+ the state_dict[f"{prefix}{FLAT_PARAM}] with the ShardedTensor. No copy
404
+ will happen. The underlying storage is the same.
405
+ """
406
+
407
+ _replace_by_prefix(state_dict, f"{prefix}{FSDP_PREFIX}", prefix)
408
+ if not _has_fsdp_params(fsdp_state, module):
409
+ return state_dict
410
+
411
+ # state_dict[f"{prefix}{FLAT_PARAM}"] exists and has the same tensor
412
+ # value as the flat_param but it is a pure Tensor because
413
+ # nn.Module.state_dict() will detach the parameter. Therefore, we need
414
+ # to get flat_param to get the metadata.
415
+ if not _module_handle(fsdp_state, module):
416
+ raise AssertionError("Should have returned early")
417
+ flat_param = _module_handle(fsdp_state, module).flat_param
418
+ # Constructs a ShardedTensor from the flat_param "without" padding.
419
+ # Removing the padding allows users to change the number of ranks
420
+ # when loading the local_state_dict.
421
+ full_numel = flat_param._unpadded_unsharded_size.numel() # type: ignore[attr-defined]
422
+ shard_offset = flat_param.numel() * fsdp_state.rank
423
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
424
+ if valid_data_size > 0:
425
+ # If FlatParameter is returned, FlatParameter._local_shard cause a
426
+ # pickling issue (can be torch.save but not torch.load). Since there
427
+ # is no benefit for state_dict to return the actual FlatParameter class,
428
+ # a view (which is a tensor) of the FlatParameter will be returned.
429
+ flat_param = flat_param[:valid_data_size].view(valid_data_size)
430
+ local_shards = [
431
+ Shard.from_tensor_and_offsets(flat_param, [shard_offset], fsdp_state.rank)
432
+ ]
433
+ else:
434
+ local_shards = []
435
+ sharded_tensor = init_from_local_shards(
436
+ local_shards, full_numel, process_group=fsdp_state.process_group
437
+ ) # type: ignore[assignment]
438
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
439
+ if fsdp_state._state_dict_config.offload_to_cpu:
440
+ sharded_tensor = sharded_tensor.cpu()
441
+ state_dict[f"{prefix}{FLAT_PARAM}"] = sharded_tensor
442
+ return state_dict
443
+
444
+
445
+ def _local_post_load_state_dict_hook(
446
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
447
+ ) -> None:
448
+ pass
449
+
450
+
451
+ def _local_pre_load_state_dict_hook(
452
+ module: nn.Module,
453
+ fsdp_state: _FSDPState,
454
+ state_dict: dict[str, Any],
455
+ prefix: str,
456
+ ) -> None:
457
+ """
458
+ This hook finds the local flat_param for this FSDP module from the
459
+ state_dict. The flat_param should be a ShardedTensor. This hook converts
460
+ the ShardedTensor to a tensor. No copy happen unless padding is required.
461
+ """
462
+ _lazy_init(fsdp_state, module)
463
+ _replace_by_prefix(state_dict, prefix, f"{prefix}{FSDP_PREFIX}")
464
+ fqn = f"{prefix}{FSDP_PREFIX}{FLAT_PARAM}"
465
+ if fqn not in state_dict:
466
+ if _has_fsdp_params(fsdp_state, module):
467
+ raise AssertionError(
468
+ "No `FlatParameter` in `state_dict` for this FSDP instance "
469
+ "but it has parameters"
470
+ )
471
+ return
472
+ load_tensor = state_dict[fqn]
473
+ if not isinstance(load_tensor, ShardedTensor):
474
+ raise AssertionError("Tensors in local_state_dict should be ShardedTensor.")
475
+
476
+ # Convert the ShardedTensor to a Tensor.
477
+ flat_param = _module_handle(fsdp_state, module).flat_param
478
+ if flat_param is None:
479
+ raise AssertionError("Expected flat_param to be set")
480
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
481
+ shards = load_tensor.local_shards()
482
+ if valid_data_size > 0:
483
+ if not len(shards):
484
+ raise AssertionError(
485
+ "load_local_state_dict assume one shard per ShardedTensor."
486
+ )
487
+ load_tensor = shards[0].tensor
488
+
489
+ # Get the metadata of the flat_param to decide whether to pad the loaded
490
+ # tensor.
491
+ if flat_param._shard_numel_padded > 0:
492
+ if load_tensor.numel() >= flat_param.numel():
493
+ raise AssertionError(
494
+ f"Local shard size = {flat_param.numel()} and the tensor in "
495
+ f"the state_dict is {load_tensor.numel()}."
496
+ )
497
+ load_tensor = F.pad(load_tensor, [0, flat_param._shard_numel_padded])
498
+ else:
499
+ load_tensor = flat_param
500
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
501
+ state_dict[fqn] = load_tensor
502
+
503
+
504
+ def _sharded_pre_state_dict_hook(
505
+ fsdp_state: _FSDPState,
506
+ module: nn.Module,
507
+ *args,
508
+ **kwargs,
509
+ ) -> None:
510
+ """
511
+ Hook that runs before model.state_dict() is called. Check
512
+ ``_full_pre_load_state_dict_hook`` for the detail.
513
+ """
514
+ if (
515
+ _has_fsdp_params(fsdp_state, module)
516
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
517
+ ):
518
+ raise RuntimeError(
519
+ "``sharded_state_dict`` can only be used when parameters are flatten "
520
+ "and sharded."
521
+ )
522
+ _common_pre_state_dict_hook(module, fsdp_state)
523
+ # Setting offload_to_cpu here does not work even if offload_to_cpu is True.
524
+ # We have to create ShardedTensor first then move it to CPU.
525
+ _common_unshard_pre_state_dict_hook(
526
+ module,
527
+ fsdp_state,
528
+ offload_to_cpu=False,
529
+ rank0_only=False,
530
+ )
531
+
532
+
533
+ @no_type_check
534
+ def _sharded_post_state_dict_hook(
535
+ module: nn.Module,
536
+ fsdp_state: _FSDPState,
537
+ state_dict: dict[str, Any],
538
+ prefix: str,
539
+ ) -> dict[str, Any]:
540
+ """
541
+ The hook replaces the unflattened, unsharded parameter in the state_dict
542
+ with a unflattened, sharded parameter (a ShardedTensor).
543
+ """
544
+
545
+ def param_hook(state_dict: dict[str, Any], prefix: str, fqn: str):
546
+ param = state_dict[fqn]
547
+ if not fsdp_state._state_dict_config._use_dtensor:
548
+ sharded_tensor = _ext_chunk_tensor(
549
+ tensor=param,
550
+ rank=fsdp_state.rank,
551
+ world_size=fsdp_state.world_size,
552
+ num_devices_per_node=fsdp_state._device_handle.device_count(),
553
+ pg=fsdp_state.process_group,
554
+ fsdp_extension=fsdp_state._fsdp_extension,
555
+ )
556
+ else:
557
+ sharded_tensor = _ext_chunk_dtensor(
558
+ tensor=param,
559
+ rank=fsdp_state.rank,
560
+ device_mesh=fsdp_state._device_mesh,
561
+ fsdp_extension=fsdp_state._fsdp_extension,
562
+ )
563
+ if fsdp_state._state_dict_config.offload_to_cpu:
564
+ sharded_tensor = sharded_tensor.cpu()
565
+ state_dict[fqn] = sharded_tensor
566
+
567
+ return _common_unshard_post_state_dict_hook(
568
+ module, fsdp_state, state_dict, prefix, param_hook
569
+ )
570
+
571
+
572
+ @no_type_check
573
+ def _sharded_post_load_state_dict_hook(
574
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
575
+ ) -> None:
576
+ if _has_fsdp_params(fsdp_state, module):
577
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
578
+ _exit_unshard_params_ctx(module, fsdp_state)
579
+
580
+
581
+ @no_type_check
582
+ def _sharded_pre_load_state_dict_hook(
583
+ module: nn.Module,
584
+ fsdp_state: _FSDPState,
585
+ state_dict: dict[str, Any],
586
+ prefix: str,
587
+ ) -> None:
588
+ """
589
+ The hook combines the unflattened, sharded parameters (ShardedTensor) to
590
+ a new FlatParameter and shards the new FlatParameter to the local chunk.
591
+ """
592
+ _lazy_init(fsdp_state, module)
593
+ if not _is_composable(fsdp_state):
594
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
595
+ if not _has_fsdp_params(fsdp_state, module):
596
+ return
597
+
598
+ handle = _module_handle(fsdp_state, module)
599
+ if not handle.uses_sharded_strategy:
600
+ raise RuntimeError(
601
+ "load_sharded_state_dict can only be called when parameters "
602
+ "are flattened and sharded."
603
+ )
604
+ fqn_to_param_ext = dict(
605
+ zip(handle.flat_param._fqns, handle.flat_param._param_extensions)
606
+ )
607
+
608
+ for fqn, _, _ in _param_name_infos(module, fsdp_state):
609
+ if not _is_composable(fsdp_state):
610
+ fqn_from_global_root = f"{prefix}{FSDP_PREFIX}{fqn}"
611
+ else:
612
+ fqn_from_global_root = f"{prefix}{fqn}"
613
+ try:
614
+ param = state_dict.pop(fqn_from_global_root)
615
+ except KeyError:
616
+ logger.warning(
617
+ f"Did not find param with FQN {fqn_from_global_root}, skipping it. " # noqa: G004
618
+ "The weight will not be filled if you expect it to be."
619
+ )
620
+ continue # TODO: Improve unittesting for state_dict finetuning
621
+ # cases: https://github.com/pytorch/pytorch/issues/109134
622
+
623
+ if not fsdp_state._state_dict_config._use_dtensor:
624
+ # All-gather the param (ShardedTensor)
625
+ param, shards = _ext_pre_load_state_dict_transform(
626
+ param, fsdp_state._fsdp_extension
627
+ )
628
+
629
+ if len(shards) >= 2:
630
+ raise AssertionError(
631
+ "Expects 0 or 1 shard per rank "
632
+ f"but got {len(shards)} shards on rank {fsdp_state.rank}."
633
+ )
634
+ param_numel = param.size().numel()
635
+ dim_0_size = param.size()[0]
636
+ chunk_size = (
637
+ math.ceil(dim_0_size / fsdp_state.world_size)
638
+ * param_numel
639
+ // dim_0_size
640
+ )
641
+ if len(shards) == 1:
642
+ local_tensor = shards[0].tensor.flatten()
643
+ with SimpleProfiler.profile(SimpleProfiler.Type.H2D):
644
+ local_tensor = local_tensor.to(fsdp_state.compute_device)
645
+ num_padding = chunk_size - local_tensor.numel()
646
+ if num_padding > 0:
647
+ local_tensor = F.pad(local_tensor, [0, num_padding])
648
+ else:
649
+ local_tensor = torch.zeros(
650
+ chunk_size, dtype=param.dtype, device=fsdp_state.compute_device
651
+ )
652
+ tensor = torch.empty(
653
+ chunk_size * fsdp_state.world_size,
654
+ dtype=local_tensor.dtype,
655
+ device=fsdp_state.compute_device,
656
+ )
657
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
658
+ dist.all_gather_into_tensor(
659
+ tensor, local_tensor, group=fsdp_state.process_group
660
+ )
661
+ tensor = tensor.narrow(0, 0, param_numel).reshape(param.size())
662
+ state_dict[fqn_from_global_root] = tensor
663
+ else:
664
+ if param.device != fsdp_state._device_mesh.device_type:
665
+ param = param.to(fsdp_state._device_mesh.device_type)
666
+
667
+ root_mesh = fsdp_state._device_mesh._get_root_mesh()
668
+ local_tensor = _ext_all_gather_dtensor(
669
+ param, root_mesh, fsdp_state._fsdp_extension
670
+ )
671
+
672
+ if fqn_to_param_ext.get(fqn) is not None:
673
+ ext = fqn_to_param_ext[fqn]
674
+ local_tensor = _ext_post_unflatten_transform(
675
+ local_tensor, ext, fsdp_state._fsdp_extension
676
+ )
677
+ state_dict[fqn_from_global_root] = local_tensor
678
+
679
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
680
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
681
+
682
+
683
+ @contextlib.contextmanager
684
+ def _replace_with_full_state_dict_type(fsdp_state: _FSDPState) -> Generator:
685
+ old_state_dict_config = fsdp_state._state_dict_config
686
+ old_state_dict_type = fsdp_state._state_dict_type
687
+ fsdp_state._state_dict_config = FullStateDictConfig()
688
+ fsdp_state._state_dict_type = StateDictType.FULL_STATE_DICT
689
+ yield
690
+ fsdp_state._state_dict_config = old_state_dict_config
691
+ fsdp_state._state_dict_type = old_state_dict_type
692
+
693
+
694
+ @no_type_check
695
+ @torch.no_grad()
696
+ def _post_state_dict_hook(
697
+ module: nn.Module,
698
+ state_dict: dict[str, Any],
699
+ prefix: str,
700
+ *args: Any,
701
+ ) -> dict[str, Any]:
702
+ """
703
+ _post_state_dict_hook() is called after the state_dict() of this
704
+ FSDP module is executed. ``fsdp_state._state_dict_type`` is used to decide
705
+ what postprocessing will be done.
706
+ """
707
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
708
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
709
+ context = _replace_with_full_state_dict_type(fsdp_state)
710
+ warnings.warn(
711
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will "
712
+ "be returned.",
713
+ stacklevel=2,
714
+ )
715
+ else:
716
+ context = contextlib.nullcontext()
717
+
718
+ with context:
719
+ _post_state_dict_hook_fn = {
720
+ StateDictType.FULL_STATE_DICT: _full_post_state_dict_hook,
721
+ StateDictType.LOCAL_STATE_DICT: _local_post_state_dict_hook,
722
+ StateDictType.SHARDED_STATE_DICT: _sharded_post_state_dict_hook,
723
+ }
724
+ processed_state_dict = _post_state_dict_hook_fn[fsdp_state._state_dict_type](
725
+ module, fsdp_state, state_dict, prefix
726
+ )
727
+
728
+ if fsdp_state._is_root:
729
+ logger.info("FSDP finished processing state_dict(), prefix=%s", prefix)
730
+ for key, tensor in sorted(processed_state_dict.items()):
731
+ if key.startswith(prefix) and isinstance(tensor, torch.Tensor):
732
+ local_shape = tensor.shape
733
+ device = None
734
+ if isinstance(tensor, ShardedTensor):
735
+ local_shape = None
736
+ shards = tensor.local_shards()
737
+ if shards:
738
+ local_shape = shards[0].tensor.shape
739
+ device = shards[0].tensor.device
740
+ elif isinstance(tensor, DTensor):
741
+ local_shape = tensor.to_local().shape
742
+ device = tensor.device
743
+ else:
744
+ device = tensor.device
745
+ logger.info(
746
+ "FQN=%s: type=%s, shape=%s, local_shape=%s, dtype=%s, device=%s",
747
+ key,
748
+ type(tensor),
749
+ tensor.shape,
750
+ local_shape,
751
+ tensor.dtype,
752
+ device,
753
+ )
754
+
755
+ return processed_state_dict
756
+
757
+
758
+ @no_type_check
759
+ @torch.no_grad()
760
+ def _pre_state_dict_hook(
761
+ module: nn.Module,
762
+ *args,
763
+ **kwargs,
764
+ ) -> None:
765
+ """
766
+ This is called before the core state dict saving logic of ``module``.
767
+ ``fsdp_state._state_dict_type`` is used to decide what postprocessing will
768
+ be done.
769
+ """
770
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
771
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
772
+ context = _replace_with_full_state_dict_type(fsdp_state)
773
+ warnings.warn(
774
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will "
775
+ "be returned.",
776
+ stacklevel=2,
777
+ )
778
+ else:
779
+ _set_use_dtensor(fsdp_state)
780
+ context = contextlib.nullcontext()
781
+
782
+ with context:
783
+ _pre_state_dict_hook_fn = {
784
+ StateDictType.FULL_STATE_DICT: _full_pre_state_dict_hook,
785
+ StateDictType.LOCAL_STATE_DICT: _local_pre_state_dict_hook,
786
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_state_dict_hook,
787
+ }
788
+ _pre_state_dict_hook_fn[fsdp_state._state_dict_type](
789
+ fsdp_state,
790
+ module,
791
+ *args,
792
+ **kwargs,
793
+ )
794
+
795
+
796
+ @no_type_check
797
+ def _set_use_dtensor(fsdp_state: _FSDPState) -> None:
798
+ # If device_mesh is passed in when initializing FSDP, we automatically turn the
799
+ # _use_dtensor flag to be true for ShardedStateDictConfig().
800
+ if getattr(fsdp_state, "_device_mesh", None):
801
+ state_dict_type = fsdp_state._state_dict_type
802
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
803
+ raise RuntimeError(
804
+ "Found state_dict_type LOCAL_STATE_DICT",
805
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
806
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
807
+ )
808
+ else:
809
+ fsdp_state._state_dict_config._use_dtensor = True
810
+
811
+
812
+ @no_type_check
813
+ @torch.no_grad()
814
+ def _pre_load_state_dict_hook(
815
+ module: nn.Module,
816
+ state_dict: dict[str, Any],
817
+ prefix: str,
818
+ *args: Any,
819
+ ) -> None:
820
+ """
821
+ This is called before ``module._load_from_state_dict()``.
822
+ ``fsdp_state._state_dict_type`` is used to decide what preprocessing will
823
+ be done.
824
+ """
825
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
826
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
827
+ context = _replace_with_full_state_dict_type(fsdp_state)
828
+ warnings.warn(
829
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
830
+ "be returned.",
831
+ stacklevel=2,
832
+ )
833
+ else:
834
+ _set_use_dtensor(fsdp_state)
835
+ context = contextlib.nullcontext()
836
+
837
+ _lazy_init(fsdp_state, module)
838
+ if fsdp_state._is_root:
839
+ SimpleProfiler.reset()
840
+
841
+ with context:
842
+ _pre_load_state_dict_hook_fn = {
843
+ StateDictType.FULL_STATE_DICT: _full_pre_load_state_dict_hook,
844
+ StateDictType.LOCAL_STATE_DICT: _local_pre_load_state_dict_hook,
845
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_load_state_dict_hook,
846
+ }
847
+ # Code that is common for all state_dict impls
848
+ if fsdp_state._device_handle.is_available():
849
+ fsdp_state._device_handle.synchronize()
850
+ # Dispatch into state_dict specific implementation of pre-hook.
851
+ _pre_load_state_dict_hook_fn[fsdp_state._state_dict_type](
852
+ module, fsdp_state, state_dict, prefix
853
+ )
854
+
855
+
856
+ @no_type_check
857
+ @torch.no_grad()
858
+ def _post_load_state_dict_hook(
859
+ module: nn.Module,
860
+ incompatible_keys: tuple[list[str], list[str]],
861
+ *args: Any,
862
+ ) -> None:
863
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
864
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
865
+ context = _replace_with_full_state_dict_type(fsdp_state)
866
+ warnings.warn(
867
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
868
+ "be returned.",
869
+ stacklevel=2,
870
+ )
871
+ else:
872
+ context = contextlib.nullcontext()
873
+
874
+ with context:
875
+ _post_load_state_dict_hook_fn = {
876
+ StateDictType.FULL_STATE_DICT: _full_post_load_state_dict_hook,
877
+ StateDictType.LOCAL_STATE_DICT: _local_post_load_state_dict_hook,
878
+ StateDictType.SHARDED_STATE_DICT: _sharded_post_load_state_dict_hook,
879
+ }
880
+ # Code that is common for all state_dict impls
881
+ # Dispatch into state_dict type specific implementation of post-hook for
882
+ # loading state_dict.
883
+ _post_load_state_dict_hook_fn[fsdp_state._state_dict_type](module, fsdp_state)
884
+
885
+ # When reporting incompatible keys, trim FSDP prefixes.
886
+ missing_keys = incompatible_keys[0]
887
+ unexpected_keys = incompatible_keys[1]
888
+ for i in range(len(missing_keys)):
889
+ missing_keys[i] = clean_tensor_name(missing_keys[i])
890
+
891
+ for i in range(len(unexpected_keys)):
892
+ unexpected_keys[i] = clean_tensor_name(unexpected_keys[i])
893
+
894
+ if fsdp_state._is_root:
895
+ SimpleProfiler.dump_and_reset("FSDP model load_state_dict profiling: ")
896
+
897
+
898
+ def _register_all_state_dict_hooks(state: _FSDPState):
899
+ """
900
+ Registers pre-save, post-save, pre-load, and post-load state dict hooks.
901
+ """
902
+ for hook_registration_fn_str, hook, hook_registration_fn_kwargs in (
903
+ ("register_state_dict_pre_hook", _pre_state_dict_hook, {}),
904
+ ("_register_state_dict_hook", _post_state_dict_hook, {}),
905
+ (
906
+ "_register_load_state_dict_pre_hook",
907
+ _pre_load_state_dict_hook,
908
+ {"with_module": True},
909
+ ),
910
+ ("register_load_state_dict_post_hook", _post_load_state_dict_hook, {}),
911
+ ):
912
+ _register_state_dict_hooks_base(
913
+ state, hook_registration_fn_str, hook, hook_registration_fn_kwargs
914
+ )
915
+
916
+
917
+ @no_type_check
918
+ def _register_state_dict_hooks_base(
919
+ state: _FSDPState,
920
+ hook_registration_fn_name: str,
921
+ hook: Callable,
922
+ hook_registration_fn_kwargs: dict[str, Any],
923
+ ) -> None:
924
+ """Registers ``hook`` using ``hook_registration_fn``."""
925
+ if not _is_composable(state):
926
+ getattr(state, hook_registration_fn_name)(hook, **hook_registration_fn_kwargs)
927
+ else:
928
+ handle = state._handle
929
+ if handle:
930
+ getattr(handle._fully_sharded_module, hook_registration_fn_name)(
931
+ hook, **hook_registration_fn_kwargs
932
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_trace_utils.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections.abc import Callable
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, NamedTuple, Optional
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+
12
+ @dataclass
13
+ class TracingConfig:
14
+ """
15
+ This represents a symbolic tracing configuration.
16
+
17
+ Args:
18
+ tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
19
+ use for symbolic tracing. The default value is the native
20
+ :class:`torch.fx.Tracer` constructed with default arguments.
21
+ However, the user may want to pass a different value such as the
22
+ ``HFTracer`` for models in the HuggingFace Transformers_ library.
23
+ .. _Transformers: https://huggingface.co/docs/transformers/index
24
+ concrete_args (Optional[Dict[str, Any]]): Concrete arguments that
25
+ should not be treated as ``torch.fx.Proxy`` when tracing the
26
+ module ``forward()``. Passing ``concrete_args`` allows partially
27
+ specializing the forward, e.g. to remove control flow or data
28
+ structures. This ``concrete_args`` here is the same argument used
29
+ in :meth:`~torch.fx.Tracer.trace`.
30
+ """
31
+
32
+ tracer: torch.fx.Tracer = field(default_factory=torch.fx.Tracer)
33
+ concrete_args: Optional[dict[str, Any]] = None
34
+
35
+
36
+ class _ParamUsageInfo(NamedTuple):
37
+ """
38
+ This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
39
+ execution information. The ``dict`` maps modules to a list of these
40
+ ``_ParamUsageInfo`` instances, where each instance represents a group of
41
+ parameters used together.
42
+
43
+ Specifically, for each module key in the ``dict``, each instance of this
44
+ class represents either:
45
+ (1) the module and some sublist of its ``named_parameters()`` used
46
+ together in execution (see ``_patched_create_proxy()``), or
47
+ (2) a submodule and all of ``submodule.named_parameters()`` (see
48
+ ``_patched_call_module()``).
49
+
50
+ Type (1) corresponds to directly using parameters in ops without calling
51
+ ``forward()``, and type (2) corresponds to calling ``forward()``. The
52
+ mapped-to lists in the ``dict`` follow the execution order.
53
+ """
54
+
55
+ module: nn.Module
56
+ named_params: list[tuple[str, nn.Parameter]]
57
+
58
+
59
+ class _ExecutionInfo:
60
+ """
61
+ This represents the execution order information from the forward pass.
62
+
63
+ Attributes:
64
+ curr_module (nn.Module): Current module being traced.
65
+ module_forward_order (List[nn.Module]): The modules in (pre-)forward
66
+ order, i.e. the order in which their ``forward()`` methods are
67
+ called. Each call to a module's ``forward()`` corresponds to one
68
+ element in the list.
69
+ module_to_param_usage_infos (Dict[nn.Module, List[_ParamUsageInfo]]):
70
+ Maps a module to a list of module execution infos. See
71
+ :class:`_ParamUsageInfo` for details.
72
+ param_forward_order (List[nn.Parameter]): The parameters in forward
73
+ execution order, where only a parameter's first participation is
74
+ included.
75
+ visited_params (Set[nn.Parameter]): The parameters visited so far
76
+ during the trace. This is only used during tracing for fast
77
+ membership check. Invariant: The parameters in
78
+ ``param_forward_order`` are exactly those in ``visited_params``.
79
+ """
80
+
81
+ def __init__(self, root_module: nn.Module) -> None:
82
+ self.curr_module: nn.Module = root_module
83
+ self.module_forward_order: list[nn.Module] = [root_module]
84
+ self.module_to_param_usage_infos: dict[nn.Module, list[_ParamUsageInfo]] = {
85
+ root_module: []
86
+ }
87
+ self.param_forward_order: list[nn.Parameter] = []
88
+ self.visited_params: set[nn.Parameter] = set()
89
+
90
+
91
+ class _ExecOrderTracer:
92
+ def __init__(self) -> None:
93
+ self.exec_info: Optional[_ExecutionInfo] = None
94
+
95
+ @contextmanager
96
+ def patch_tracer(self, tracer: torch.fx.Tracer, root_module: nn.Module):
97
+ self.exec_info = _ExecutionInfo(root_module)
98
+ orig_call_module = tracer.call_module
99
+ orig_create_proxy = tracer.create_proxy
100
+ tracer.call_module = functools.partial( # type: ignore[method-assign]
101
+ self._patched_call_module, orig_call_module, self.exec_info
102
+ )
103
+ fqn_to_param = dict(root_module.named_parameters())
104
+ tracer.create_proxy = functools.partial( # type: ignore[method-assign]
105
+ self._patched_create_proxy,
106
+ orig_create_proxy,
107
+ self.exec_info,
108
+ fqn_to_param,
109
+ )
110
+ try:
111
+ yield
112
+ finally:
113
+ tracer.call_module = orig_call_module # type: ignore[method-assign]
114
+ tracer.create_proxy = orig_create_proxy # type: ignore[method-assign]
115
+
116
+ def _patched_call_module(
117
+ self,
118
+ call_module: Callable,
119
+ exec_info: _ExecutionInfo,
120
+ # Below are the expected arguments to `call_module()`
121
+ module: nn.Module,
122
+ forward: Callable,
123
+ args: tuple[Any, ...],
124
+ kwargs: dict[str, Any],
125
+ ) -> Any:
126
+ """
127
+ Overrides ``call_module`` to save execution information to
128
+ ``exec_info``. Note that ``call_module`` is called during symbolic
129
+ tracing for each non-root module.
130
+
131
+ Args:
132
+ call_module (Callable): Original ``call_module`` to override.
133
+ exec_info (_ExecutionInfo): Used to record execution information.
134
+ module (nn.Module): Module corresponding to this ``call_module``.
135
+ forward (Callable): ``forward()`` method of ``module`` to be called
136
+ for this ``call_module``.
137
+ args (Tuple[Any, ...]): Positional arguments for ``forward``.
138
+ kwargs (Dict[str, Any]): Keyword arguments for ``forward``.
139
+
140
+ Returns:
141
+ Same return value as ``call_module``.
142
+ """
143
+ exec_info.module_forward_order.append(module)
144
+ named_params = list(module.named_parameters())
145
+ curr_module = exec_info.curr_module
146
+ if named_params:
147
+ if curr_module not in exec_info.module_to_param_usage_infos:
148
+ raise AssertionError(
149
+ "The current module should have already been processed by a patched `call_module`"
150
+ )
151
+ exec_info.module_to_param_usage_infos[exec_info.curr_module].append(
152
+ _ParamUsageInfo(module, named_params)
153
+ )
154
+ prev_curr_module = curr_module
155
+ exec_info.curr_module = module
156
+ exec_info.module_to_param_usage_infos[module] = []
157
+ output = call_module(module, forward, args, kwargs)
158
+ exec_info.curr_module = prev_curr_module
159
+ return output
160
+
161
+ def _patched_create_proxy(
162
+ self,
163
+ create_proxy: Callable,
164
+ exec_info: _ExecutionInfo,
165
+ fqn_to_param: dict[str, nn.Parameter],
166
+ # Below are the expected arguments to `create_proxy()`
167
+ kind: str,
168
+ target: torch.fx.node.Target,
169
+ args: tuple[Any, ...],
170
+ kwargs: dict[str, Any],
171
+ name: Optional[str] = None,
172
+ type_expr: Optional[Any] = None,
173
+ proxy_factory_fn: Optional[Callable[[torch.fx.Node], torch.fx.Proxy]] = None,
174
+ ) -> torch.fx.Proxy:
175
+ """
176
+ Overrides ``create_proxy`` to save execution information to
177
+ ``exec_info``. Note that ``create_proxy`` is called during symbolic
178
+ tracing for each leaf function/method/module.
179
+
180
+ Args:
181
+ create_proxy (Callable): Original ``create_proxy`` to override.
182
+ exec_info (_ExecutionInfo): Used to record execution information.
183
+ fqn_to_param (Dict[str, nn.Parameter]): ``dict`` version of the
184
+ root module's ``named_parameters()`` with FQN as key and
185
+ parameter as value.
186
+ kind (str): Kind of the target method ('call_function',
187
+ 'call_method', 'get_attr', 'call_module', 'placeholder', or
188
+ 'output'). See :class:`torch.fx.Graph` for details. This is
189
+ passed to ``create_proxy``.
190
+ target (torch.fx.node.Target): Contains the string name of the
191
+ function/method/module. This is passed to ``create_proxy``.
192
+ args (Tuple[Any, ...]): Positional arguments for the function/
193
+ method/module. This is passed to ``create_proxy``.
194
+ kwargs (Dict[str, Any]): Keyword arguments for the function/method/
195
+ module. This is passed to ``create_proxy``
196
+ name (Optional[str]): An optional string name for the ``Node``
197
+ created in ``create_proxy``. This is passed to
198
+ ``create_proxy``.
199
+ type_expr (Optional[Any]): An optional type annotation representing
200
+ the Python type that the output of the node has. This is passed
201
+ to ``create_proxy``.
202
+ proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
203
+ An alternative proxy constructor used in ``create_proxy``. This
204
+ is passed to ``create_proxy``.
205
+
206
+ Returns:
207
+ torch.fx.Proxy: Created ``Node`` wrapped in a ``Proxy`` object.
208
+ """
209
+ proxy = create_proxy(
210
+ kind, target, args, kwargs, name, type_expr, proxy_factory_fn
211
+ )
212
+ curr_module = exec_info.curr_module
213
+ if kind in ("call_function", "call_method"):
214
+ if args is not None:
215
+ named_params: list[tuple[str, nn.Parameter]] = []
216
+ for arg in args:
217
+ if (
218
+ isinstance(arg, torch.fx.Proxy)
219
+ and arg.node.target in fqn_to_param
220
+ ):
221
+ param = fqn_to_param[arg.node.target] # type: ignore[index]
222
+ named_params.append((arg.node.target, param)) # type: ignore[arg-type]
223
+ if param not in exec_info.visited_params:
224
+ exec_info.visited_params.add(param)
225
+ exec_info.param_forward_order.append(param)
226
+ if named_params:
227
+ exec_info.module_to_param_usage_infos[curr_module].append(
228
+ _ParamUsageInfo(curr_module, named_params)
229
+ )
230
+ elif kind == "call_module":
231
+ named_params = list(curr_module.named_parameters())
232
+ if named_params:
233
+ exec_info.module_to_param_usage_infos[curr_module].append(
234
+ _ParamUsageInfo(curr_module, named_params)
235
+ )
236
+ for _, param in named_params:
237
+ if param not in exec_info.visited_params:
238
+ exec_info.visited_params.add(param)
239
+ exec_info.param_forward_order.append(param)
240
+ return proxy
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_traversal_utils.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE: This file must be imported like
3
+ ``import torch.distributed.fsdp._traversal_utils`` and not like
4
+ ``from torch.distributed.fsdp._traversal_utils import ...`` to avoid circular
5
+ imports. For brevity, we may import the file as ``traversal_utils``.
6
+ """
7
+
8
+ import collections
9
+
10
+ import torch.nn as nn
11
+ from torch.distributed._composable.contract import _get_registry
12
+ from torch.distributed.fsdp._common_utils import _FSDPState, _get_module_fsdp_state
13
+
14
+
15
+ """
16
+ [Note: FSDP State Traversal]
17
+ For the wrapper code path, ``_FSDPState`` is the ``FullyShardedDataParallel``
18
+ module wrapping a fully sharded module, and for the non-wrapper code path,
19
+ ``_FSDPState`` is an object that gets embedded on a fully sharded module.
20
+ See [Note: Fully Sharded Module] for the definition.
21
+
22
+ There are three common traversal idioms: Given a root module,
23
+ - ``_get_fsdp_states()`` returns all ``_FSDPState`` s in the tree.
24
+ - ``get_fsdp_root_states()`` returns all local root ``_FSDPState`` s in the
25
+ tree (i.e. those with ``_is_root == True``).
26
+ - ``_get_fsdp_handles()``returns all ``FlatParamHandle`` s in the tree.
27
+
28
+ All of these methods must take in the root module (i.e. an ``nn.Module``) and
29
+ not a general ``_FSDPState`` because ``_FSDPState`` does not support a graph
30
+ traversal, whereas ``nn.Module`` has ``nn.Module.modules()`` for traversal.
31
+ """
32
+
33
+
34
+ def _composable(module: nn.Module) -> bool:
35
+ """
36
+ Returns if ``module`` can compose with ``fully_shard``.
37
+ """
38
+ # TODO: Add any other composable APIs that are mutually exclusive.
39
+ registry = _get_registry(module)
40
+ if registry is None:
41
+ return True
42
+ return "replicate" not in registry
43
+
44
+
45
+ # TODO (awgu): We may be able to remove this function if we retired the
46
+ # `use_orig_params=False` code path since so far we only need the module for
47
+ # `FlatParameter` registration, which is not needed for `use_orig_params=True`.
48
+ def _get_fsdp_states_with_modules(
49
+ module: nn.Module,
50
+ ) -> tuple[list[_FSDPState], list[nn.Module]]:
51
+ """
52
+ Returns a tuple containing:
53
+ 1. A list of the ``_FSDPState`` instances in the module tree rooted at
54
+ ``module`` without any duplicates and following the ``module.modules()``
55
+ traversal order (which is assumed to be depth-first).
56
+ 2. A corresponding list of the modules owning the states in the first list.
57
+
58
+ For the wrapper code path, both returned lists are the same, each
59
+ containing all ``FullyShardedDataParallel`` instances. For the composable
60
+ code path, this returns a list of all composable state instances and a list
61
+ of the corresponding fully sharded modules. See [Note: Fully Sharded
62
+ Module].
63
+
64
+ NOTE: The traversal does not proceed into any module annotated by an
65
+ incompatible API (e.g. ``replicate``).
66
+ """
67
+ fsdp_states: list[_FSDPState] = []
68
+ fsdp_modules: list[nn.Module] = []
69
+ # Track the visited FSDP states since multiple modules may share the same
70
+ # one and we want to return a de-duplicated list
71
+ visited_fsdp_states: set[_FSDPState] = set()
72
+ # Track the visited modules in case of shared modules, which implies the
73
+ # module graph is no longer a tree
74
+ visited_modules: set[nn.Module] = set()
75
+
76
+ # Perform depth-first search from `module` to ensure that we do not
77
+ # traverse into an incompatible API's subtree (use DFS instead of BFS to
78
+ # match `.modules()` order)
79
+ deque: collections.deque[nn.Module] = collections.deque([module])
80
+ while deque:
81
+ submodule = deque.popleft()
82
+ visited_modules.add(submodule)
83
+ if not _composable(submodule):
84
+ continue
85
+ for child_module in reversed(list(submodule.children())):
86
+ if child_module not in visited_modules:
87
+ deque.appendleft(child_module)
88
+ optional_state = _get_module_fsdp_state(submodule)
89
+ if optional_state is not None and optional_state not in visited_fsdp_states:
90
+ visited_fsdp_states.add(optional_state)
91
+ fsdp_states.append(optional_state)
92
+ fsdp_modules.append(submodule)
93
+ return fsdp_states, fsdp_modules
94
+
95
+
96
+ def _get_fsdp_states(module: nn.Module) -> list[_FSDPState]:
97
+ """See :func:`_get_fsdp_states_with_modules`."""
98
+ fsdp_states, _ = _get_fsdp_states_with_modules(module)
99
+ return fsdp_states
100
+
101
+
102
+ def _get_fsdp_handles(module: nn.Module) -> list:
103
+ """
104
+ Returns all ``FlatParamHandle`` s in the module tree rooted at ``module``
105
+ following the rules in :func:`_get_fsdp_state`.
106
+ """
107
+ handles = [
108
+ fsdp_state._handle
109
+ for fsdp_state in _get_fsdp_states(module)
110
+ if fsdp_state._handle is not None
111
+ ]
112
+ return handles
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/fsdp/_unshard_param_utils.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import warnings
4
+ from collections.abc import Generator
5
+ from typing import cast
6
+
7
+ import torch
8
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
9
+ import torch.nn as nn
10
+ from torch.distributed.fsdp._common_utils import (
11
+ _FSDPState,
12
+ _get_module_fsdp_state,
13
+ _has_fsdp_params,
14
+ _module_handle,
15
+ HandleTrainingState,
16
+ TrainingState,
17
+ )
18
+ from torch.distributed.fsdp._runtime_utils import (
19
+ _lazy_init,
20
+ _reset_flat_param_grad_info_if_needed,
21
+ _reshard,
22
+ _reshard_grads,
23
+ _unshard,
24
+ _unshard_grads,
25
+ )
26
+ from torch.distributed.utils import _p_assert
27
+
28
+ from ._flat_param import FlatParamHandle
29
+
30
+
31
+ FLAT_PARAM = "_flat_param"
32
+
33
+
34
+ @torch.no_grad()
35
+ def _writeback_to_local_shard(
36
+ handle: FlatParamHandle,
37
+ writeback_grad: bool,
38
+ ):
39
+ """
40
+ For the handle, writes back the this rank's shard of the unsharded
41
+ flattened parameter to the sharded flattened parameter. If
42
+ ``writeback_grad=True``, then writes back to the sharded gradient as
43
+ well.
44
+
45
+ Precondition: The handle's ``FlatParameter`` 's data points to the
46
+ padded unsharded flattened parameter.
47
+ """
48
+
49
+ def _get_shard(flat_param_or_grad: torch.Tensor) -> torch.Tensor:
50
+ if handle.uses_sharded_strategy:
51
+ # For sharded strategies, get the *unpadded* shard instead of
52
+ # the *padded* shard to persist user changes to the padding
53
+ # (though FSDP does not explicitly support this)
54
+ shard, _ = FlatParamHandle._get_unpadded_shard(
55
+ flat_param_or_grad,
56
+ handle.rank,
57
+ handle.world_size,
58
+ )
59
+ return shard
60
+ # For `NO_SHARD`, the `flat_param` or its gradient may be modified,
61
+ # so we write it back directly
62
+ return flat_param_or_grad
63
+
64
+ param_shard = _get_shard(handle.flat_param)
65
+ handle.flat_param._local_shard[: param_shard.numel()].copy_(param_shard) # type: ignore[attr-defined]
66
+ if writeback_grad:
67
+ existing_grad = handle.sharded_grad
68
+ if existing_grad is not None:
69
+ if handle.flat_param.grad is None:
70
+ raise AssertionError("Expected handle.flat_param.grad to not be None")
71
+ grad_shard = _get_shard(handle.flat_param.grad)
72
+ existing_grad[: grad_shard.numel()].copy_(grad_shard)
73
+
74
+
75
+ def _deregister_flat_param(state: _FSDPState, module: nn.Module) -> None:
76
+ """
77
+ De-registers the flattened parameter from the wrapped module, hiding it
78
+ from ``nn.Module`` methods.
79
+
80
+ We do not use ``del`` because we want ``FLAT_PARAM`` to always be an
81
+ attribute but dynamically change whether it is visible to ``nn.Module``
82
+ methods.
83
+ """
84
+ if _has_fsdp_params(state, module):
85
+ # TODO: figure out the case for the composable APIs.
86
+ cast(nn.Module, module.module)._parameters.pop(FLAT_PARAM, None)
87
+
88
+
89
+ def _register_flat_param(state: _FSDPState, module: nn.Module) -> None:
90
+ """
91
+ Registers the flattened parameter to the wrapped module, making it
92
+ visible to ``nn.Module`` methods.
93
+
94
+ We do not use :meth:`nn.Module.register_parameter` because we want
95
+ ``FLAT_PARAM`` to always be an attribute but dynamically change whether
96
+ it is visible to ``nn.Module`` methods.
97
+ """
98
+ handle = _module_handle(state, module)
99
+ if _has_fsdp_params(state, module):
100
+ # TODO: figure out the case for the composable APIs.
101
+ cast(nn.Module, module.module)._parameters[FLAT_PARAM] = handle.flat_param
102
+
103
+
104
+ @contextlib.contextmanager
105
+ def _unflatten_as_params(state: _FSDPState, module: nn.Module) -> Generator:
106
+ """
107
+ Assumes that the flattened parameter is unsharded. When in the context,
108
+ de-registers the flattened parameter and unflattens the original
109
+ parameters as ``nn.Parameter`` views into the flattened parameter.
110
+ After the context, re-registers the flattened parameter and restores
111
+ the original parameters as ``Tensor`` views into the flattened
112
+ parameter.
113
+ """
114
+ handle = _module_handle(state, module)
115
+ if not handle:
116
+ yield
117
+ else:
118
+ _deregister_flat_param(state, module)
119
+ try:
120
+ with handle.unflatten_as_params():
121
+ yield
122
+ finally:
123
+ if not handle._use_orig_params:
124
+ _register_flat_param(state, module)
125
+
126
+
127
+ def _validate_unshard_params_args(
128
+ state: _FSDPState,
129
+ writeback: bool,
130
+ rank0_only: bool,
131
+ offload_to_cpu: bool,
132
+ with_grads: bool,
133
+ ) -> None:
134
+ if with_grads and (offload_to_cpu or not state._use_orig_params):
135
+ raise NotImplementedError(
136
+ f"with_grads={with_grads}, "
137
+ f"use_orig_params={state._use_orig_params}, "
138
+ f"offload_to_cpu={offload_to_cpu} "
139
+ f"is not supported yet"
140
+ )
141
+ if offload_to_cpu and state._handle and (not state._handle.uses_sharded_strategy):
142
+ raise NotImplementedError(
143
+ "offload_to_cpu=True and NO_SHARD is not supported yet"
144
+ )
145
+ if writeback and rank0_only:
146
+ # TODO: Rank 0 can broadcast the `FlatParameter` to allow all ranks to
147
+ # persist the changes.
148
+ raise NotImplementedError(
149
+ "writeback=True and rank0_only=True is not supported yet"
150
+ )
151
+ if offload_to_cpu and not rank0_only:
152
+ warnings.warn(
153
+ "offload_to_cpu=True and rank0_only=False may result in the"
154
+ "unsharded parameters being redundantly copied to CPU memory for "
155
+ "GPUs sharing the same CPU memory, which risks CPU OOM. We "
156
+ "recommend using offload_to_cpu=True with rank0_only=True.",
157
+ stacklevel=2,
158
+ )
159
+
160
+
161
+ @contextlib.contextmanager
162
+ def _unshard_fsdp_state_params(
163
+ module: nn.Module,
164
+ state: _FSDPState,
165
+ writeback: bool,
166
+ rank0_only: bool,
167
+ offload_to_cpu: bool,
168
+ with_grads: bool,
169
+ ):
170
+ """
171
+ This unshards the parameters for a single FSDP state ``state`` that
172
+ corresponds to ``module``.
173
+ """
174
+ _validate_unshard_params_args(
175
+ state, writeback, rank0_only, offload_to_cpu, with_grads
176
+ )
177
+ state._device_handle.synchronize()
178
+ # If handles are shared by other module(s), the handle may be already unsharded.
179
+ maybe_handle = _module_handle(state, module)
180
+ handle = None
181
+ if (
182
+ maybe_handle
183
+ and maybe_handle._training_state != HandleTrainingState.SUMMON_FULL_PARAMS
184
+ ):
185
+ handle = maybe_handle
186
+ if not handle:
187
+ yield
188
+ return
189
+
190
+ if handle._training_state != HandleTrainingState.IDLE:
191
+ raise AssertionError(
192
+ f"Expects the handle training to be IDLE but got {handle._training_state}"
193
+ )
194
+
195
+ handle._training_state = HandleTrainingState.SUMMON_FULL_PARAMS
196
+
197
+ _reset_flat_param_grad_info_if_needed(handle)
198
+ free_unsharded_flat_param = handle.needs_unshard()
199
+ # No need to call `wait_stream()` since we unshard in the computation
200
+ # stream directly
201
+ computation_stream = state._device_handle.current_stream()
202
+ _unshard(state, handle, computation_stream, computation_stream)
203
+ if with_grads:
204
+ _unshard_grads(handle)
205
+
206
+ if rank0_only and state.rank != 0:
207
+ # Free the unsharded flattened parameter early
208
+ _reshard(state, handle, free_unsharded_flat_param)
209
+ if with_grads:
210
+ _reshard_grads(handle)
211
+ try:
212
+ yield
213
+ finally:
214
+ handle._training_state = HandleTrainingState.IDLE
215
+ else:
216
+ # Unflatten the unsharded flattened parameters
217
+ with contextlib.ExitStack() as stack:
218
+ # Invariant: rank == 0 or !rank0_only
219
+ if offload_to_cpu and handle.uses_sharded_strategy:
220
+ stack.enter_context(handle.to_cpu())
221
+ # NOTE: Since PyTorch enforces that a parameter and its
222
+ # gradients need to match metadata (e.g. device), we must
223
+ # move gradients to CPU *after* we move parameters.
224
+ # NOTE: This assumes 1 `FlatParameter`
225
+ if not state._use_orig_params:
226
+ stack.enter_context(_unflatten_as_params(state, module))
227
+ try:
228
+ yield
229
+ finally:
230
+ stack.close()
231
+ if writeback:
232
+ _writeback_to_local_shard(handle, with_grads)
233
+ _reshard(state, handle, free_unsharded_flat_param)
234
+ if with_grads:
235
+ _reshard_grads(handle)
236
+ handle._training_state = HandleTrainingState.IDLE
237
+
238
+
239
+ @contextlib.contextmanager
240
+ def _unshard_params_for_summon(
241
+ module: nn.Module,
242
+ state: _FSDPState,
243
+ writeback: bool,
244
+ rank0_only: bool,
245
+ offload_to_cpu: bool,
246
+ with_grads: bool,
247
+ ):
248
+ _validate_unshard_params_args(
249
+ state, writeback, rank0_only, offload_to_cpu, with_grads
250
+ )
251
+ _lazy_init(state, module)
252
+ if state.training_state == TrainingState.FORWARD_BACKWARD:
253
+ raise AssertionError(
254
+ "Cannot manually unshard parameters during forward/backward"
255
+ )
256
+ elif state.training_state == TrainingState.SUMMON_FULL_PARAMS:
257
+ raise AssertionError(
258
+ "Cannot manually unshard parameters when already unsharding parameters"
259
+ )
260
+ with _unshard_fsdp_state_params(
261
+ module=module,
262
+ state=state,
263
+ writeback=writeback,
264
+ rank0_only=rank0_only,
265
+ offload_to_cpu=offload_to_cpu,
266
+ with_grads=with_grads,
267
+ ):
268
+ try:
269
+ state.training_state = TrainingState.SUMMON_FULL_PARAMS
270
+ yield
271
+ finally:
272
+ state.training_state = TrainingState.IDLE
273
+
274
+
275
+ @contextlib.contextmanager
276
+ def _unshard_params(
277
+ module: nn.Module,
278
+ recurse: bool,
279
+ writeback: bool,
280
+ rank0_only: bool,
281
+ offload_to_cpu: bool,
282
+ with_grads: bool,
283
+ ):
284
+ """
285
+ This unshards FSDP-managed parameters for all modules with FSDP applied in
286
+ the module tree rooted at ``module``.
287
+ """
288
+ if not recurse:
289
+ optional_state = _get_module_fsdp_state(module)
290
+ if optional_state is None:
291
+ with contextlib.nullcontext():
292
+ yield
293
+ return
294
+ states_and_modules = ([optional_state], [module])
295
+ else:
296
+ states_and_modules = traversal_utils._get_fsdp_states_with_modules(module)
297
+ with contextlib.ExitStack() as stack:
298
+ for state, module in zip(*states_and_modules):
299
+ stack.enter_context(
300
+ _unshard_params_for_summon(
301
+ module=module,
302
+ state=state,
303
+ writeback=writeback,
304
+ rank0_only=rank0_only,
305
+ offload_to_cpu=offload_to_cpu,
306
+ with_grads=with_grads,
307
+ )
308
+ )
309
+ yield
310
+
311
+
312
+ def _deregister_orig_params(state: _FSDPState, module: nn.Module) -> None:
313
+ """
314
+ Deregisters the original parameters; registers the ``FlatParameter``.
315
+ """
316
+ handle = _module_handle(state, module)
317
+ if not handle:
318
+ return
319
+ _p_assert(
320
+ handle._use_orig_params,
321
+ f"Inconsistent `_use_orig_params` -- FSDP: {state._use_orig_params} "
322
+ f"handle: {handle._use_orig_params}",
323
+ )
324
+ handle._deregister_orig_params()
325
+ _register_flat_param(state, module)
326
+
327
+
328
+ def _register_orig_params(state: _FSDPState, module: nn.Module) -> None:
329
+ """
330
+ Deregisters the ``FlatParameter``; registers the original parameters.
331
+ """
332
+ handle = _module_handle(state, module)
333
+ if not handle:
334
+ return
335
+ _deregister_flat_param(state, module)
336
+ if handle.is_sharded(handle.flat_param):
337
+ handle._use_sharded_views()
338
+ handle._use_sharded_grad_views()
339
+ else:
340
+ handle._use_unsharded_views(as_params=True)