Commit ·
e8976ac
1
Parent(s): 6ab602e
Upload folder using huggingface_hub (part 19)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +5 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.py +54 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.py +283 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.py +24 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py +442 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.py +128 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.py +9 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.py +62 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.py +10 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.py +57 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py +92 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.py +184 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.py +14 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.py +69 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.py +226 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.py +66 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pyc +3 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pyc +3 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.py +546 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.py +157 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.py +43 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.py +364 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.py +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.py +179 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__init__.py +18 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_api.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_collectives.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_common.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_init.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param_group.cpython-311.pyc +0 -0
- pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_state.cpython-311.pyc +0 -0
.gitattributes
CHANGED
|
@@ -892,3 +892,8 @@ pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/autograd/__pycache
|
|
| 892 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 893 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -text
|
| 894 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 892 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 893 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -text
|
| 894 |
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 895 |
+
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 896 |
+
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 897 |
+
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/fx/__pycache__/graph.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 898 |
+
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/fx/experimental/__pycache__/proxy_tensor.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 899 |
+
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
pace_revision_1/.venv-pace/lib/python3.11/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
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Optional
|
| 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: Optional[threading.Thread] = 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: Optional[TimerClient] = 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(
|
| 251 |
+
after: float, scope: Optional[str] = None, client: Optional[TimerClient] = None
|
| 252 |
+
):
|
| 253 |
+
"""
|
| 254 |
+
Acquires a countdown timer that expires in ``after`` seconds from now,
|
| 255 |
+
unless the code-block that it wraps is finished within the timeframe.
|
| 256 |
+
When the timer expires, this worker is eligible to be reaped. The
|
| 257 |
+
exact meaning of "reaped" depends on the client implementation. In
|
| 258 |
+
most cases, reaping means to terminate the worker process.
|
| 259 |
+
Note that the worker is NOT guaranteed to be reaped at exactly
|
| 260 |
+
``time.now() + after``, but rather the worker is "eligible" for being
|
| 261 |
+
reaped and the ``TimerServer`` that the client talks to will ultimately
|
| 262 |
+
make the decision when and how to reap the workers with expired timers.
|
| 263 |
+
|
| 264 |
+
Usage::
|
| 265 |
+
|
| 266 |
+
torch.distributed.elastic.timer.configure(LocalTimerClient())
|
| 267 |
+
with expires(after=10):
|
| 268 |
+
torch.distributed.all_reduce(...)
|
| 269 |
+
"""
|
| 270 |
+
if client is None:
|
| 271 |
+
if _timer_client is None:
|
| 272 |
+
raise RuntimeError("Configure timer client before using countdown timers.")
|
| 273 |
+
client = _timer_client
|
| 274 |
+
if scope is None:
|
| 275 |
+
# grab the caller file + lineno
|
| 276 |
+
caller = getframeinfo(stack()[1][0])
|
| 277 |
+
scope = f"{caller.filename}#{caller.lineno}"
|
| 278 |
+
expiration = time.time() + after
|
| 279 |
+
client.acquire(scope, expiration)
|
| 280 |
+
try:
|
| 281 |
+
yield
|
| 282 |
+
finally:
|
| 283 |
+
client.release(scope)
|
pace_revision_1/.venv-pace/lib/python3.11/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)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 typing import Callable, Optional, TypeVar
|
| 17 |
+
from typing_extensions import ParamSpec
|
| 18 |
+
|
| 19 |
+
from torch.distributed.elastic.timer.api import TimerClient, TimerRequest
|
| 20 |
+
from torch.distributed.elastic.timer.debug_info_logging import (
|
| 21 |
+
log_debug_info_for_expired_timers,
|
| 22 |
+
)
|
| 23 |
+
from torch.distributed.elastic.utils.logging import get_logger
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_P = ParamSpec("_P")
|
| 27 |
+
_R = TypeVar("_R")
|
| 28 |
+
|
| 29 |
+
__all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"]
|
| 30 |
+
|
| 31 |
+
logger = get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _retry(max_retries: int, sleep_time: float) -> Callable:
|
| 35 |
+
"""
|
| 36 |
+
A simple retry wrapper.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
max_retries: int, the maximum number of retries.
|
| 40 |
+
sleep_time: float, the time to sleep between retries.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def wrapper(func: Callable[_P, _R]) -> Callable[_P, _R]:
|
| 44 |
+
def wrapper(*args: _P.args, **kwargs: _P.kwargs):
|
| 45 |
+
for i in range(max_retries):
|
| 46 |
+
try:
|
| 47 |
+
return func(*args, **kwargs)
|
| 48 |
+
except Exception:
|
| 49 |
+
logger.exception("Error running %s. Retrying...", func.__name__)
|
| 50 |
+
if i < max_retries - 1:
|
| 51 |
+
time.sleep(sleep_time)
|
| 52 |
+
else:
|
| 53 |
+
raise
|
| 54 |
+
|
| 55 |
+
return wrapper
|
| 56 |
+
|
| 57 |
+
return wrapper
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class FileTimerRequest(TimerRequest):
|
| 61 |
+
"""
|
| 62 |
+
Data object representing a countdown timer acquisition and release
|
| 63 |
+
that is used between the ``FileTimerClient`` and ``FileTimerServer``.
|
| 64 |
+
A negative ``expiration_time`` should be interpreted as a "release"
|
| 65 |
+
request.
|
| 66 |
+
``signal`` is the signal to reap the worker process from the server
|
| 67 |
+
process.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
__slots__ = ["version", "worker_pid", "scope_id", "expiration_time", "signal"]
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0
|
| 74 |
+
) -> None:
|
| 75 |
+
self.version = 1
|
| 76 |
+
self.worker_pid = worker_pid
|
| 77 |
+
self.scope_id = scope_id
|
| 78 |
+
self.expiration_time = expiration_time
|
| 79 |
+
self.signal = signal
|
| 80 |
+
|
| 81 |
+
def __eq__(self, other) -> bool:
|
| 82 |
+
if isinstance(other, FileTimerRequest):
|
| 83 |
+
return (
|
| 84 |
+
self.version == other.version
|
| 85 |
+
and self.worker_pid == other.worker_pid
|
| 86 |
+
and self.scope_id == other.scope_id
|
| 87 |
+
and self.expiration_time == other.expiration_time
|
| 88 |
+
and self.signal == other.signal
|
| 89 |
+
)
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
def to_json(self) -> str:
|
| 93 |
+
return json.dumps(
|
| 94 |
+
{
|
| 95 |
+
"version": self.version,
|
| 96 |
+
"pid": self.worker_pid,
|
| 97 |
+
"scope_id": self.scope_id,
|
| 98 |
+
"expiration_time": self.expiration_time,
|
| 99 |
+
"signal": self.signal,
|
| 100 |
+
},
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FileTimerClient(TimerClient):
|
| 105 |
+
"""
|
| 106 |
+
Client side of ``FileTimerServer``. This client is meant to be used
|
| 107 |
+
on the same host that the ``FileTimerServer`` is running on and uses
|
| 108 |
+
pid to uniquely identify a worker.
|
| 109 |
+
This client uses a named_pipe to send timer requests to the
|
| 110 |
+
``FileTimerServer``. This client is a producer while the
|
| 111 |
+
``FileTimerServer`` is a consumer. Multiple clients can work with
|
| 112 |
+
the same ``FileTimerServer``.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
|
| 116 |
+
file_path: str, the path of a FIFO special file. ``FileTimerServer``
|
| 117 |
+
must have created it by calling os.mkfifo().
|
| 118 |
+
|
| 119 |
+
signal: signal, the signal to use to kill the process. Using a
|
| 120 |
+
negative or zero signal will not kill the process.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
def __init__(
|
| 124 |
+
self,
|
| 125 |
+
file_path: str,
|
| 126 |
+
signal=(signal.SIGKILL if sys.platform != "win32" else signal.CTRL_C_EVENT), # type: ignore[attr-defined]
|
| 127 |
+
) -> None:
|
| 128 |
+
super().__init__()
|
| 129 |
+
self._file_path = file_path
|
| 130 |
+
self.signal = signal
|
| 131 |
+
|
| 132 |
+
@_retry(max_retries=10, sleep_time=0.1)
|
| 133 |
+
def _open_non_blocking(self) -> Optional[io.TextIOWrapper]:
|
| 134 |
+
# The server may have crashed or may haven't started yet.
|
| 135 |
+
# In such case, calling open() in blocking model blocks the client.
|
| 136 |
+
# To avoid such issue, open it in non-blocking mode, and an OSError will
|
| 137 |
+
# be raised if the server is not there.
|
| 138 |
+
fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK)
|
| 139 |
+
return os.fdopen(fd, "wt")
|
| 140 |
+
|
| 141 |
+
def _send_request(self, request: FileTimerRequest) -> None:
|
| 142 |
+
try:
|
| 143 |
+
file = self._open_non_blocking()
|
| 144 |
+
except Exception as e:
|
| 145 |
+
raise BrokenPipeError(
|
| 146 |
+
"Could not send the FileTimerRequest because FileTimerServer is not available."
|
| 147 |
+
) from e
|
| 148 |
+
with file:
|
| 149 |
+
json_request = request.to_json()
|
| 150 |
+
# Write request with no greater than select.PIPE_BUF is guarantee to be atomic.
|
| 151 |
+
if len(json_request) > select.PIPE_BUF:
|
| 152 |
+
raise RuntimeError(
|
| 153 |
+
f"FileTimerRequest larger than {select.PIPE_BUF} bytes "
|
| 154 |
+
f"is not supported: {json_request}"
|
| 155 |
+
)
|
| 156 |
+
file.write(json_request + "\n")
|
| 157 |
+
|
| 158 |
+
def acquire(self, scope_id: str, expiration_time: float) -> None:
|
| 159 |
+
self._send_request(
|
| 160 |
+
request=FileTimerRequest(
|
| 161 |
+
worker_pid=os.getpid(),
|
| 162 |
+
scope_id=scope_id,
|
| 163 |
+
expiration_time=expiration_time,
|
| 164 |
+
signal=self.signal,
|
| 165 |
+
),
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def release(self, scope_id: str) -> None:
|
| 169 |
+
self._send_request(
|
| 170 |
+
request=FileTimerRequest(
|
| 171 |
+
worker_pid=os.getpid(), scope_id=scope_id, expiration_time=-1, signal=0
|
| 172 |
+
),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class FileTimerServer:
|
| 177 |
+
"""
|
| 178 |
+
Server that works with ``FileTimerClient``. Clients are expected to be
|
| 179 |
+
running on the same host as the process that is running this server.
|
| 180 |
+
Each host in the job is expected to start its own timer server locally
|
| 181 |
+
and each server instance manages timers for local workers (running on
|
| 182 |
+
processes on the same host).
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
|
| 186 |
+
file_path: str, the path of a FIFO special file to be created.
|
| 187 |
+
|
| 188 |
+
max_interval: float, max interval in seconds for each watchdog loop.
|
| 189 |
+
|
| 190 |
+
daemon: bool, running the watchdog thread in daemon mode or not.
|
| 191 |
+
A daemon thread will not block a process to stop.
|
| 192 |
+
log_event: Callable[[Dict[str, str]], None], an optional callback for
|
| 193 |
+
logging the events in JSON format.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
file_path: str,
|
| 199 |
+
run_id: str,
|
| 200 |
+
max_interval: float = 10,
|
| 201 |
+
daemon: bool = True,
|
| 202 |
+
log_event: Optional[Callable[[str, Optional[FileTimerRequest]], None]] = None,
|
| 203 |
+
) -> None:
|
| 204 |
+
self._file_path = file_path
|
| 205 |
+
self._run_id = run_id
|
| 206 |
+
self._max_interval = max_interval
|
| 207 |
+
self._daemon = daemon
|
| 208 |
+
self._timers: dict[tuple[int, str], FileTimerRequest] = {}
|
| 209 |
+
self._stop_signaled = False
|
| 210 |
+
self._watchdog_thread: Optional[threading.Thread] = None
|
| 211 |
+
|
| 212 |
+
self._is_client_started = False
|
| 213 |
+
if os.path.exists(self._file_path):
|
| 214 |
+
os.remove(self._file_path)
|
| 215 |
+
os.mkfifo(self._file_path)
|
| 216 |
+
# For test only. Count the number of requests received.
|
| 217 |
+
self._request_count = 0
|
| 218 |
+
# For test only. Process all requests and stop the server.
|
| 219 |
+
self._run_once = False
|
| 220 |
+
self._log_event = (
|
| 221 |
+
log_event if log_event is not None else lambda name, request: None
|
| 222 |
+
)
|
| 223 |
+
self._last_progress_time = int(time.time())
|
| 224 |
+
|
| 225 |
+
def start(self) -> None:
|
| 226 |
+
logger.info(
|
| 227 |
+
"Starting %s... max_interval=%s, daemon=%s, file_path=%s",
|
| 228 |
+
type(self).__name__,
|
| 229 |
+
self._max_interval,
|
| 230 |
+
self._daemon,
|
| 231 |
+
self._file_path,
|
| 232 |
+
)
|
| 233 |
+
self._watchdog_thread = threading.Thread(
|
| 234 |
+
target=self._watchdog_loop, daemon=self._daemon
|
| 235 |
+
)
|
| 236 |
+
logger.info("Starting watchdog thread...")
|
| 237 |
+
self._watchdog_thread.start()
|
| 238 |
+
self._log_event("watchdog started", None)
|
| 239 |
+
|
| 240 |
+
def stop(self) -> None:
|
| 241 |
+
logger.info("Stopping %s", type(self).__name__)
|
| 242 |
+
self._stop_signaled = True
|
| 243 |
+
if self._watchdog_thread:
|
| 244 |
+
logger.info("Stopping watchdog thread...")
|
| 245 |
+
self._watchdog_thread.join(self._max_interval)
|
| 246 |
+
self._watchdog_thread = None
|
| 247 |
+
else:
|
| 248 |
+
logger.info("No watchdog thread running, doing nothing")
|
| 249 |
+
if os.path.exists(self._file_path):
|
| 250 |
+
os.remove(self._file_path)
|
| 251 |
+
self._log_event("watchdog stopped", None)
|
| 252 |
+
|
| 253 |
+
def run_once(self) -> None:
|
| 254 |
+
self._run_once = True
|
| 255 |
+
if self._watchdog_thread:
|
| 256 |
+
logger.info("Stopping watchdog thread...")
|
| 257 |
+
self._watchdog_thread.join()
|
| 258 |
+
self._watchdog_thread = None
|
| 259 |
+
else:
|
| 260 |
+
logger.info("No watchdog thread running, doing nothing")
|
| 261 |
+
if os.path.exists(self._file_path):
|
| 262 |
+
os.remove(self._file_path)
|
| 263 |
+
|
| 264 |
+
@staticmethod
|
| 265 |
+
def is_process_running(pid: int):
|
| 266 |
+
"""
|
| 267 |
+
function to check process is running or not
|
| 268 |
+
"""
|
| 269 |
+
try:
|
| 270 |
+
# Check if the process exists and we can send signals to it
|
| 271 |
+
os.kill(pid, 0)
|
| 272 |
+
return True
|
| 273 |
+
except OSError:
|
| 274 |
+
return False
|
| 275 |
+
|
| 276 |
+
def _watchdog_loop(self) -> None:
|
| 277 |
+
# Open the pipe in blocking mode blocks the server thread.
|
| 278 |
+
# This is fine for the following reasons:
|
| 279 |
+
# 1. No client case usually does not happen.
|
| 280 |
+
# 2. We are running the watchdog loop in a separate daemon
|
| 281 |
+
# thread, which will not block the process to stop.
|
| 282 |
+
try:
|
| 283 |
+
fd = open(self._file_path)
|
| 284 |
+
except Exception:
|
| 285 |
+
logger.exception("Could not open the FileTimerServer pipe")
|
| 286 |
+
raise
|
| 287 |
+
|
| 288 |
+
with fd:
|
| 289 |
+
self._is_client_started = True
|
| 290 |
+
while not self._stop_signaled:
|
| 291 |
+
try:
|
| 292 |
+
run_once = self._run_once
|
| 293 |
+
self._run_watchdog(fd)
|
| 294 |
+
if run_once:
|
| 295 |
+
break
|
| 296 |
+
self._last_progress_time = int(time.time())
|
| 297 |
+
except Exception:
|
| 298 |
+
logger.exception("Error running watchdog")
|
| 299 |
+
|
| 300 |
+
def _run_watchdog(self, fd: io.TextIOWrapper) -> None:
|
| 301 |
+
timer_requests = self._get_requests(fd, self._max_interval)
|
| 302 |
+
self.register_timers(timer_requests)
|
| 303 |
+
now = time.time()
|
| 304 |
+
reaped_worker_pids = set()
|
| 305 |
+
kill_process = False
|
| 306 |
+
reap_signal = 0
|
| 307 |
+
|
| 308 |
+
all_expired_timers = self.get_expired_timers(now)
|
| 309 |
+
log_debug_info_for_expired_timers(
|
| 310 |
+
self._run_id,
|
| 311 |
+
{
|
| 312 |
+
pid: [expired_timer.to_json() for expired_timer in expired_timers]
|
| 313 |
+
for pid, expired_timers in all_expired_timers.items()
|
| 314 |
+
},
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
for worker_pid, expired_timers in all_expired_timers.items():
|
| 318 |
+
logger.info(
|
| 319 |
+
"Reaping worker_pid=[%s]. Expired timers: %s",
|
| 320 |
+
worker_pid,
|
| 321 |
+
self._get_scopes(expired_timers),
|
| 322 |
+
)
|
| 323 |
+
reaped_worker_pids.add(worker_pid)
|
| 324 |
+
# In case we have multiple expired timers, we find the first timer
|
| 325 |
+
# with a valid signal (>0) in the expiration time order.
|
| 326 |
+
expired_timers.sort(key=lambda timer: timer.expiration_time)
|
| 327 |
+
signal = 0
|
| 328 |
+
expired_timer = None
|
| 329 |
+
for timer in expired_timers:
|
| 330 |
+
self._log_event("timer expired", timer)
|
| 331 |
+
if timer.signal > 0:
|
| 332 |
+
signal = timer.signal
|
| 333 |
+
expired_timer = timer
|
| 334 |
+
break
|
| 335 |
+
if signal <= 0:
|
| 336 |
+
logger.info(
|
| 337 |
+
"No signal specified with worker=[%s]. Do not reap it.", worker_pid
|
| 338 |
+
)
|
| 339 |
+
continue
|
| 340 |
+
if self._reap_worker(worker_pid, signal):
|
| 341 |
+
logger.info(
|
| 342 |
+
"Successfully reaped worker=[%s] with signal=%s", worker_pid, signal
|
| 343 |
+
)
|
| 344 |
+
self._log_event("kill worker process", expired_timer)
|
| 345 |
+
kill_process = True
|
| 346 |
+
reap_signal = signal
|
| 347 |
+
else:
|
| 348 |
+
logger.error(
|
| 349 |
+
"Error reaping worker=[%s]. Will retry on next watchdog.",
|
| 350 |
+
worker_pid,
|
| 351 |
+
)
|
| 352 |
+
if kill_process and reap_signal > 0:
|
| 353 |
+
logger.info(
|
| 354 |
+
"Terminating the server process=[%s] because of expired timers",
|
| 355 |
+
os.getpid(),
|
| 356 |
+
)
|
| 357 |
+
self._reap_worker(os.getpid(), reap_signal)
|
| 358 |
+
|
| 359 |
+
self.clear_timers(reaped_worker_pids)
|
| 360 |
+
|
| 361 |
+
def _get_scopes(self, timer_requests: list[FileTimerRequest]) -> list[str]:
|
| 362 |
+
return [r.scope_id for r in timer_requests]
|
| 363 |
+
|
| 364 |
+
def _get_requests(
|
| 365 |
+
self, fd: io.TextIOWrapper, max_interval: float
|
| 366 |
+
) -> list[FileTimerRequest]:
|
| 367 |
+
start = time.time()
|
| 368 |
+
requests = []
|
| 369 |
+
while not self._stop_signaled or self._run_once:
|
| 370 |
+
# For named pipe, readline() is blocking when at least one writer opens.
|
| 371 |
+
# It returns only when flush() is called at the writer side.
|
| 372 |
+
# Note that flush() is automatically called inside close().
|
| 373 |
+
# After the last writer closes, readline() is not blocking.
|
| 374 |
+
# It will return an empty string when it's at end-of-file.
|
| 375 |
+
# Since the client side always opens the pipe, writes a message and closes
|
| 376 |
+
# the pipe immediately, the readline() call below is not blocking for long.
|
| 377 |
+
json_request = fd.readline()
|
| 378 |
+
if len(json_request) == 0:
|
| 379 |
+
if self._run_once:
|
| 380 |
+
break
|
| 381 |
+
time.sleep(min(max_interval, 1))
|
| 382 |
+
else:
|
| 383 |
+
request = json.loads(json_request)
|
| 384 |
+
pid = request["pid"]
|
| 385 |
+
scope_id = request["scope_id"]
|
| 386 |
+
expiration_time = request["expiration_time"]
|
| 387 |
+
signal = request["signal"]
|
| 388 |
+
requests.append(
|
| 389 |
+
FileTimerRequest(
|
| 390 |
+
worker_pid=pid,
|
| 391 |
+
scope_id=scope_id,
|
| 392 |
+
expiration_time=expiration_time,
|
| 393 |
+
signal=signal,
|
| 394 |
+
)
|
| 395 |
+
)
|
| 396 |
+
now = time.time()
|
| 397 |
+
if now - start > max_interval:
|
| 398 |
+
break
|
| 399 |
+
return requests
|
| 400 |
+
|
| 401 |
+
def register_timers(self, timer_requests: list[FileTimerRequest]) -> None:
|
| 402 |
+
for request in timer_requests:
|
| 403 |
+
pid = request.worker_pid
|
| 404 |
+
scope_id = request.scope_id
|
| 405 |
+
expiration_time = request.expiration_time
|
| 406 |
+
self._request_count += 1
|
| 407 |
+
|
| 408 |
+
key = (pid, scope_id)
|
| 409 |
+
# negative expiration is a proxy for a release call
|
| 410 |
+
if expiration_time < 0:
|
| 411 |
+
if key in self._timers:
|
| 412 |
+
del self._timers[key]
|
| 413 |
+
else:
|
| 414 |
+
self._timers[key] = request
|
| 415 |
+
|
| 416 |
+
def clear_timers(self, worker_pids: set[int]) -> None:
|
| 417 |
+
for pid, scope_id in list(self._timers.keys()):
|
| 418 |
+
if pid in worker_pids or not FileTimerServer.is_process_running(pid):
|
| 419 |
+
del self._timers[(pid, scope_id)]
|
| 420 |
+
|
| 421 |
+
def get_expired_timers(self, deadline: float) -> dict[int, list[FileTimerRequest]]:
|
| 422 |
+
# pid -> [timer_requests...]
|
| 423 |
+
expired_timers: dict[int, list[FileTimerRequest]] = {}
|
| 424 |
+
for request in self._timers.values():
|
| 425 |
+
if request.expiration_time <= deadline:
|
| 426 |
+
expired_scopes = expired_timers.setdefault(request.worker_pid, [])
|
| 427 |
+
expired_scopes.append(request)
|
| 428 |
+
return expired_timers
|
| 429 |
+
|
| 430 |
+
def _reap_worker(self, worker_pid: int, signal: int) -> bool:
|
| 431 |
+
try:
|
| 432 |
+
os.kill(worker_pid, signal)
|
| 433 |
+
return True
|
| 434 |
+
except ProcessLookupError:
|
| 435 |
+
logger.info("Process with pid=%s does not exist. Skipping", worker_pid)
|
| 436 |
+
return True
|
| 437 |
+
except Exception:
|
| 438 |
+
logger.exception("Error terminating pid=%s", worker_pid)
|
| 439 |
+
return False
|
| 440 |
+
|
| 441 |
+
def get_last_progress_time(self) -> int:
|
| 442 |
+
return self._last_progress_time if self._is_client_started else int(time.time())
|
pace_revision_1/.venv-pace/lib/python3.11/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(0, 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
|
pace_revision_1/.venv-pace/lib/python3.11/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
|
pace_revision_1/.venv-pace/lib/python3.11/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
|
pace_revision_1/.venv-pace/lib/python3.11/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
|
pace_revision_1/.venv-pace/lib/python3.11/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 Iterator
|
| 4 |
+
from typing import Callable, 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
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Optional, 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: Optional[int] = None,
|
| 48 |
+
rank: Optional[int] = 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 |
+
sized_dataset = cast(Sized, dataset)
|
| 57 |
+
|
| 58 |
+
if start_index >= len(sized_dataset):
|
| 59 |
+
raise ValueError(
|
| 60 |
+
f"Start index {start_index} should be less than dataset size {len(sized_dataset)}"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
self.start_index = start_index
|
| 64 |
+
sized_dataset = cast(Sized, self.dataset)
|
| 65 |
+
self.num_samples = int(
|
| 66 |
+
math.ceil(float(len(sized_dataset) - self.start_index) / self.num_replicas)
|
| 67 |
+
)
|
| 68 |
+
self.total_size = self.num_samples * self.num_replicas
|
| 69 |
+
|
| 70 |
+
def __iter__(self) -> Iterator[T]:
|
| 71 |
+
# deterministically shuffle based on epoch
|
| 72 |
+
g = torch.Generator()
|
| 73 |
+
g.manual_seed(self.epoch)
|
| 74 |
+
sized_dataset = cast(Sized, self.dataset)
|
| 75 |
+
indices = (
|
| 76 |
+
torch.randperm(len(sized_dataset) - self.start_index, generator=g)
|
| 77 |
+
.add(self.start_index)
|
| 78 |
+
.tolist()
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# add extra samples to make it evenly divisible
|
| 82 |
+
indices += indices[: (self.total_size - len(indices))]
|
| 83 |
+
assert len(indices) == self.total_size
|
| 84 |
+
|
| 85 |
+
# subsample
|
| 86 |
+
indices = indices[self.rank : self.total_size : self.num_replicas]
|
| 87 |
+
assert len(indices) == self.num_samples
|
| 88 |
+
|
| 89 |
+
return iter(indices)
|
| 90 |
+
|
| 91 |
+
def __len__(self) -> int:
|
| 92 |
+
return self.num_samples
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
# 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 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
import torch.distributed as dist
|
| 16 |
+
from torch.distributed.elastic.utils.logging import get_logger
|
| 17 |
+
from torch.distributed.elastic.utils.store import barrier
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = ["create_c10d_store", "get_free_port", "get_socket_with_port"]
|
| 21 |
+
|
| 22 |
+
logger = get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
_ADDRESS_IN_USE = "Address already in use"
|
| 25 |
+
_SOCKET_TIMEOUT = "Socket Timeout"
|
| 26 |
+
|
| 27 |
+
_TCP_STORE_INIT = "_tcp_store/num_members"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def create_c10d_store(
|
| 31 |
+
is_server: bool,
|
| 32 |
+
server_addr: str,
|
| 33 |
+
server_port: int = -1,
|
| 34 |
+
world_size: int = 1,
|
| 35 |
+
timeout: float = (60 * 10), # 10 min
|
| 36 |
+
wait_for_workers: bool = True,
|
| 37 |
+
retries=3,
|
| 38 |
+
use_libuv: Optional[bool] = None,
|
| 39 |
+
):
|
| 40 |
+
if use_libuv is not None:
|
| 41 |
+
logger.warning(
|
| 42 |
+
"argument use_libuv is deprecated and ignored. Set USE_LIBUV environment "
|
| 43 |
+
'variable to "0" to disable libuv, or "1" to enable it. If the env var '
|
| 44 |
+
"is not set, libuv will be used by default."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# check os.environ for use_libuv
|
| 48 |
+
use_libuv = os.environ.get("USE_LIBUV", "1") == "1" # libuv is the default option
|
| 49 |
+
|
| 50 |
+
if server_port == -1 and world_size > 1:
|
| 51 |
+
raise ValueError(
|
| 52 |
+
f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if server_port != -1:
|
| 56 |
+
logger.info("sever_port: %s, specified, ignoring retries", server_port)
|
| 57 |
+
|
| 58 |
+
# only retry when server_port is NOT static
|
| 59 |
+
attempt = retries if server_port == -1 else 1
|
| 60 |
+
while True:
|
| 61 |
+
if server_port != -1:
|
| 62 |
+
port = server_port
|
| 63 |
+
else:
|
| 64 |
+
port = get_free_port()
|
| 65 |
+
|
| 66 |
+
logger.info(
|
| 67 |
+
"Creating c10d store on %s:%s\n"
|
| 68 |
+
" world_size : %s\n"
|
| 69 |
+
" is_server : %s\n"
|
| 70 |
+
" timeout(sec): %s\n"
|
| 71 |
+
" use_libuv : %s\n",
|
| 72 |
+
server_addr,
|
| 73 |
+
port,
|
| 74 |
+
world_size,
|
| 75 |
+
is_server,
|
| 76 |
+
timeout,
|
| 77 |
+
use_libuv,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
store = dist.TCPStore(
|
| 82 |
+
host_name=server_addr,
|
| 83 |
+
port=port,
|
| 84 |
+
world_size=world_size,
|
| 85 |
+
is_master=is_server,
|
| 86 |
+
timeout=datetime.timedelta(seconds=timeout),
|
| 87 |
+
wait_for_workers=wait_for_workers,
|
| 88 |
+
use_libuv=use_libuv,
|
| 89 |
+
)
|
| 90 |
+
# skips full rank check when we don't have to wait for all workers
|
| 91 |
+
if wait_for_workers:
|
| 92 |
+
_check_full_rank(store, world_size, timeout=timeout)
|
| 93 |
+
logger.info("Successfully created c10d store")
|
| 94 |
+
return store
|
| 95 |
+
except RuntimeError as e:
|
| 96 |
+
# this is brittle, but the underlying exception type is not properly pybinded
|
| 97 |
+
# so we parse the error msg for now, interestingly this is how torch itself
|
| 98 |
+
# detects timeouts and port conflicts in their own unittests
|
| 99 |
+
# see - caffe2/torch/testing/_internal/common_utils.py
|
| 100 |
+
# TODO properly map the exceptions in pybind (c10d/init.cpp)
|
| 101 |
+
if str(e) == _ADDRESS_IN_USE: # this will only happen on the server
|
| 102 |
+
if attempt < retries:
|
| 103 |
+
logger.warning(
|
| 104 |
+
"port: %s already in use, attempt: [%s/%s]",
|
| 105 |
+
port,
|
| 106 |
+
attempt,
|
| 107 |
+
retries,
|
| 108 |
+
)
|
| 109 |
+
attempt += 1
|
| 110 |
+
else:
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
f"on {server_addr}, port: {port} already in use"
|
| 113 |
+
) from e
|
| 114 |
+
else:
|
| 115 |
+
raise
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _check_full_rank(store, world_size, timeout):
|
| 119 |
+
try:
|
| 120 |
+
barrier(store, world_size, key_prefix=_TCP_STORE_INIT, barrier_timeout=timeout)
|
| 121 |
+
except RuntimeError as e:
|
| 122 |
+
if str(e) == _SOCKET_TIMEOUT:
|
| 123 |
+
raise TimeoutError(
|
| 124 |
+
f"timed out waiting for all {world_size} members to join"
|
| 125 |
+
) from e
|
| 126 |
+
else:
|
| 127 |
+
raise
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_free_port():
|
| 131 |
+
"""
|
| 132 |
+
Returns an unused port on localhost.
|
| 133 |
+
|
| 134 |
+
This function finds an unused port on localhost by opening to socket to bind
|
| 135 |
+
to a port and then closing it.
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
int: an unused port on localhost
|
| 139 |
+
|
| 140 |
+
Example:
|
| 141 |
+
>>> # xdoctest: +SKIP("Nondeterministic")
|
| 142 |
+
>>> get_free_port()
|
| 143 |
+
63976
|
| 144 |
+
|
| 145 |
+
.. note::
|
| 146 |
+
The port returned by :func:`get_free_port` is not reserved and may be
|
| 147 |
+
taken by another process after this function returns.
|
| 148 |
+
"""
|
| 149 |
+
sock = get_socket_with_port()
|
| 150 |
+
with closing(sock):
|
| 151 |
+
return sock.getsockname()[1]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_socket_with_port() -> socket.socket:
|
| 155 |
+
"""
|
| 156 |
+
Returns a free port on localhost that is "reserved" by binding a temporary
|
| 157 |
+
socket on it. Close the socket before passing the port to the entity
|
| 158 |
+
that requires it. Usage example
|
| 159 |
+
|
| 160 |
+
::
|
| 161 |
+
|
| 162 |
+
sock = _get_socket_with_port()
|
| 163 |
+
with closing(sock):
|
| 164 |
+
port = sock.getsockname()[1]
|
| 165 |
+
sock.close()
|
| 166 |
+
# there is still a race-condition that some other process
|
| 167 |
+
# may grab this port before func() runs
|
| 168 |
+
func(port)
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
addrs = socket.getaddrinfo(
|
| 172 |
+
host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
|
| 173 |
+
)
|
| 174 |
+
for addr in addrs:
|
| 175 |
+
family, type, proto, _, _ = addr
|
| 176 |
+
s = socket.socket(family, type, proto)
|
| 177 |
+
try:
|
| 178 |
+
s.bind(("localhost", 0))
|
| 179 |
+
s.listen(0)
|
| 180 |
+
return s
|
| 181 |
+
except OSError as e:
|
| 182 |
+
s.close()
|
| 183 |
+
logger.warning("Socket creation attempt failed.", exc_info=e)
|
| 184 |
+
raise RuntimeError("Failed to create a socket")
|
pace_revision_1/.venv-pace/lib/python3.11/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"
|
pace_revision_1/.venv-pace/lib/python3.11/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 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
from torch.distributed.elastic.utils.log_level import get_log_level
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
| 19 |
+
"""
|
| 20 |
+
Util function to set up a simple logger that writes
|
| 21 |
+
into stderr. The loglevel is fetched from the LOGLEVEL
|
| 22 |
+
env. variable or WARNING as default. The function will use the
|
| 23 |
+
module name of the caller if no name is provided.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
name: Name of the logger. If no name provided, the name will
|
| 27 |
+
be derived from the call stack.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
# Derive the name of the caller, if none provided
|
| 31 |
+
# Use depth=2 since this function takes up one level in the call stack
|
| 32 |
+
return _setup_logger(name or _derive_module_name(depth=2))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _setup_logger(name: Optional[str] = None) -> logging.Logger:
|
| 36 |
+
logger = logging.getLogger(name)
|
| 37 |
+
logger.setLevel(os.environ.get("LOGLEVEL", get_log_level()))
|
| 38 |
+
return logger
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _derive_module_name(depth: int = 1) -> Optional[str]:
|
| 42 |
+
"""
|
| 43 |
+
Derives the name of the caller module from the stack frames.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
depth: The position of the frame in the stack.
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
stack = inspect.stack()
|
| 50 |
+
assert depth < len(stack)
|
| 51 |
+
# FrameInfo is just a named tuple: (frame, filename, lineno, function, code_context, index)
|
| 52 |
+
frame_info = stack[depth]
|
| 53 |
+
|
| 54 |
+
module = inspect.getmodule(frame_info[0])
|
| 55 |
+
if module:
|
| 56 |
+
module_name = module.__name__
|
| 57 |
+
else:
|
| 58 |
+
# inspect.getmodule(frame_info[0]) does NOT work (returns None) in
|
| 59 |
+
# binaries built with @mode/opt
|
| 60 |
+
# return the filename (minus the .py extension) as modulename
|
| 61 |
+
filename = frame_info[1]
|
| 62 |
+
module_name = os.path.splitext(os.path.basename(filename))[0]
|
| 63 |
+
return module_name
|
| 64 |
+
except Exception as e:
|
| 65 |
+
warnings.warn(
|
| 66 |
+
f"Error deriving logger module name, using <None>. Exception: {e}",
|
| 67 |
+
RuntimeWarning,
|
| 68 |
+
)
|
| 69 |
+
return None
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/tor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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Iterable
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from datetime import timedelta
|
| 13 |
+
from typing import Callable, Optional
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
DistStoreError = torch._C._DistStoreError
|
| 19 |
+
|
| 20 |
+
_NUM_MEMBERS = "/num_members"
|
| 21 |
+
_LAST_MEMBER_CHECKIN = "/last_member"
|
| 22 |
+
_TRACE = "/TRACE"
|
| 23 |
+
_TRACING_GATE = "/TRACING_GATE"
|
| 24 |
+
_MAX_TRACE_MISSING_RANKS = 16
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
__all__ = ["store_timeout", "get_all", "synchronize", "barrier"]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@contextmanager
|
| 31 |
+
def store_timeout(store, timeout: float):
|
| 32 |
+
"""
|
| 33 |
+
This sets the timeout and then restores the old timeout when the context
|
| 34 |
+
manager exits.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
store: the store to set the timeout on
|
| 38 |
+
timeout: the timeout to set
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
old_timeout = store.timeout
|
| 42 |
+
store.set_timeout(timedelta(seconds=timeout))
|
| 43 |
+
yield
|
| 44 |
+
store.set_timeout(old_timeout)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_all(store, rank: int, prefix: str, world_size: int):
|
| 48 |
+
r"""
|
| 49 |
+
Given a store and a prefix, the method goes through the array of keys
|
| 50 |
+
of the following format: ``{prefix}{idx}``, where idx is in a range
|
| 51 |
+
from 0 to size, and tries to retrieve the data.
|
| 52 |
+
|
| 53 |
+
The Rank0 process waits at the end to make sure all other processes
|
| 54 |
+
finished the procedure before exiting.
|
| 55 |
+
|
| 56 |
+
Usage
|
| 57 |
+
|
| 58 |
+
::
|
| 59 |
+
|
| 60 |
+
values = get_all(store, "torchelastic/data", 3)
|
| 61 |
+
value1 = values[0] # retrieves the data for key torchelastic/data0
|
| 62 |
+
value2 = values[1] # retrieves the data for key torchelastic/data1
|
| 63 |
+
value3 = values[2] # retrieves the data for key torchelastic/data2
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
data_arr = store.multi_get([f"{prefix}{idx}" for idx in range(world_size)])
|
| 67 |
+
|
| 68 |
+
barrier_key = _barrier_nonblocking(
|
| 69 |
+
store=store,
|
| 70 |
+
world_size=world_size,
|
| 71 |
+
key_prefix=f"{prefix}/finished",
|
| 72 |
+
)
|
| 73 |
+
if rank == 0:
|
| 74 |
+
# Rank0 runs the TCPStore daemon, as a result it needs to exit last.
|
| 75 |
+
# Otherwise, the barrier may timeout if rank0 process finished the work
|
| 76 |
+
# before other processes finished `get_all` method
|
| 77 |
+
store.wait([barrier_key])
|
| 78 |
+
|
| 79 |
+
return data_arr
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def synchronize(
|
| 83 |
+
store,
|
| 84 |
+
data: bytes,
|
| 85 |
+
rank: int,
|
| 86 |
+
world_size: int,
|
| 87 |
+
key_prefix: str,
|
| 88 |
+
timeout: float = 300,
|
| 89 |
+
) -> list[bytes]:
|
| 90 |
+
"""
|
| 91 |
+
Synchronizes ``world_size`` agents between each other using the underlying c10d store.
|
| 92 |
+
The ``data`` will be available on each of the agents.
|
| 93 |
+
|
| 94 |
+
Note: The data on the path is not deleted, as a result there can be stale data if
|
| 95 |
+
you use the same key_prefix twice.
|
| 96 |
+
|
| 97 |
+
Time complexity: O(N) per worker, O(N^2) globally.
|
| 98 |
+
"""
|
| 99 |
+
with store_timeout(store, timeout):
|
| 100 |
+
store.set(f"{key_prefix}{rank}", data)
|
| 101 |
+
agent_data = get_all(store, rank, key_prefix, world_size)
|
| 102 |
+
return agent_data
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _try_detecting_missing_ranks(
|
| 106 |
+
store,
|
| 107 |
+
world_size: int,
|
| 108 |
+
key_prefix: str,
|
| 109 |
+
rank: int,
|
| 110 |
+
rank_decoder: Callable[[int], str],
|
| 111 |
+
trace_timeout: float,
|
| 112 |
+
) -> Optional[Iterable[str]]:
|
| 113 |
+
store.set(f"{key_prefix}{rank}{_TRACE}", "<val_ignored>")
|
| 114 |
+
|
| 115 |
+
def _find_missing_ranks():
|
| 116 |
+
missing_rank_info = set()
|
| 117 |
+
ranks_missing = 0
|
| 118 |
+
for i in range(1, world_size):
|
| 119 |
+
# reduce noise, assuming in general 8 ranks per node
|
| 120 |
+
# It is valuable to know that 1 or >1 nodes have timed-out.
|
| 121 |
+
if ranks_missing >= _MAX_TRACE_MISSING_RANKS:
|
| 122 |
+
break
|
| 123 |
+
try:
|
| 124 |
+
if ranks_missing == 0:
|
| 125 |
+
store.wait(
|
| 126 |
+
[f"{key_prefix}{i}{_TRACE}"], timedelta(seconds=trace_timeout)
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
# use a shortest timeout, some ranks have failed to check-in
|
| 130 |
+
store.wait([f"{key_prefix}{i}{_TRACE}"], timedelta(milliseconds=1))
|
| 131 |
+
except DistStoreError:
|
| 132 |
+
ranks_missing += 1
|
| 133 |
+
missing_rank_info.add(rank_decoder(i))
|
| 134 |
+
return missing_rank_info
|
| 135 |
+
|
| 136 |
+
def _checkin():
|
| 137 |
+
try:
|
| 138 |
+
store.wait([f"{key_prefix}{_TRACING_GATE}"])
|
| 139 |
+
return [f"[<check rank 0 ({rank_decoder(0)}) for missing rank info>]"]
|
| 140 |
+
except DistStoreError:
|
| 141 |
+
# in case rank0 is the source of the timeout, original exception will be raised
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
if rank == 0:
|
| 145 |
+
missing_rank_info = _find_missing_ranks()
|
| 146 |
+
store.set(f"{key_prefix}{_TRACING_GATE}", "<val_ignored>")
|
| 147 |
+
return missing_rank_info
|
| 148 |
+
else:
|
| 149 |
+
return _checkin()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _barrier_nonblocking(store, world_size: int, key_prefix: str) -> str:
|
| 153 |
+
"""
|
| 154 |
+
Does all the non-blocking operations for a barrier and returns the final key
|
| 155 |
+
that can be waited on.
|
| 156 |
+
"""
|
| 157 |
+
num_members_key = key_prefix + _NUM_MEMBERS
|
| 158 |
+
last_member_key = key_prefix + _LAST_MEMBER_CHECKIN
|
| 159 |
+
|
| 160 |
+
idx = store.add(num_members_key, 1)
|
| 161 |
+
if idx == world_size:
|
| 162 |
+
store.set(last_member_key, "<val_ignored>")
|
| 163 |
+
|
| 164 |
+
return last_member_key
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def barrier(
|
| 168 |
+
store,
|
| 169 |
+
world_size: int,
|
| 170 |
+
key_prefix: str,
|
| 171 |
+
barrier_timeout: float = 300,
|
| 172 |
+
rank: Optional[int] = None,
|
| 173 |
+
rank_tracing_decoder: Optional[Callable[[int], str]] = None,
|
| 174 |
+
trace_timeout: float = 10,
|
| 175 |
+
) -> None:
|
| 176 |
+
"""
|
| 177 |
+
A global lock between agents. This will pause all workers until at least
|
| 178 |
+
``world_size`` workers respond.
|
| 179 |
+
|
| 180 |
+
This uses a fast incrementing index to assign waiting ranks and a success
|
| 181 |
+
flag set by the last worker.
|
| 182 |
+
|
| 183 |
+
Time complexity: O(1) per worker, O(N) globally.
|
| 184 |
+
|
| 185 |
+
Optionally, passing rank will enable tracing of missing ranks on timeouts.
|
| 186 |
+
`rank_tracing_decoder` lambda arg can be used to convert rank data
|
| 187 |
+
into a more meaningful information at an app level (e.g. hostname).
|
| 188 |
+
|
| 189 |
+
Note: Since the data is not removed from the store, the barrier can be used
|
| 190 |
+
once per unique ``key_prefix``.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
if rank is None:
|
| 194 |
+
assert rank_tracing_decoder is None, "Tracing requires rank information"
|
| 195 |
+
|
| 196 |
+
with store_timeout(store, barrier_timeout):
|
| 197 |
+
last_member_key = _barrier_nonblocking(
|
| 198 |
+
store=store, world_size=world_size, key_prefix=key_prefix
|
| 199 |
+
)
|
| 200 |
+
try:
|
| 201 |
+
store.wait([last_member_key])
|
| 202 |
+
except DistStoreError as e:
|
| 203 |
+
if rank is None:
|
| 204 |
+
raise e
|
| 205 |
+
else:
|
| 206 |
+
missing_ranks = _try_detecting_missing_ranks(
|
| 207 |
+
store,
|
| 208 |
+
world_size,
|
| 209 |
+
key_prefix,
|
| 210 |
+
rank,
|
| 211 |
+
rank_tracing_decoder or (lambda x: str(x)),
|
| 212 |
+
trace_timeout,
|
| 213 |
+
)
|
| 214 |
+
if missing_ranks is not None:
|
| 215 |
+
raise DistStoreError(
|
| 216 |
+
"Timed out waiting on barrier on "
|
| 217 |
+
"rank {}, for key prefix: {} (world_size={}, missing_ranks={}, timeout={})".format(
|
| 218 |
+
rank,
|
| 219 |
+
key_prefix,
|
| 220 |
+
world_size,
|
| 221 |
+
f"[{', '.join(missing_ranks)}]",
|
| 222 |
+
barrier_timeout,
|
| 223 |
+
)
|
| 224 |
+
) from None
|
| 225 |
+
else:
|
| 226 |
+
raise e
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
UnshardHandle,
|
| 10 |
+
)
|
| 11 |
+
from .fully_sharded_data_parallel import (
|
| 12 |
+
BackwardPrefetch,
|
| 13 |
+
CPUOffload,
|
| 14 |
+
FullOptimStateDictConfig,
|
| 15 |
+
FullStateDictConfig,
|
| 16 |
+
FullyShardedDataParallel,
|
| 17 |
+
LocalOptimStateDictConfig,
|
| 18 |
+
LocalStateDictConfig,
|
| 19 |
+
MixedPrecision,
|
| 20 |
+
OptimStateDictConfig,
|
| 21 |
+
OptimStateKeyType,
|
| 22 |
+
ShardedOptimStateDictConfig,
|
| 23 |
+
ShardedStateDictConfig,
|
| 24 |
+
ShardingStrategy,
|
| 25 |
+
StateDictConfig,
|
| 26 |
+
StateDictSettings,
|
| 27 |
+
StateDictType,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = [
|
| 32 |
+
# FSDP1
|
| 33 |
+
"BackwardPrefetch",
|
| 34 |
+
"CPUOffload",
|
| 35 |
+
"FullOptimStateDictConfig",
|
| 36 |
+
"FullStateDictConfig",
|
| 37 |
+
"FullyShardedDataParallel",
|
| 38 |
+
"LocalOptimStateDictConfig",
|
| 39 |
+
"LocalStateDictConfig",
|
| 40 |
+
"MixedPrecision",
|
| 41 |
+
"OptimStateDictConfig",
|
| 42 |
+
"OptimStateKeyType",
|
| 43 |
+
"ShardedOptimStateDictConfig",
|
| 44 |
+
"ShardedStateDictConfig",
|
| 45 |
+
"ShardingStrategy",
|
| 46 |
+
"StateDictConfig",
|
| 47 |
+
"StateDictSettings",
|
| 48 |
+
"StateDictType",
|
| 49 |
+
# FSDP2
|
| 50 |
+
"CPUOffloadPolicy",
|
| 51 |
+
"FSDPModule",
|
| 52 |
+
"fully_shard",
|
| 53 |
+
"MixedPrecisionPolicy",
|
| 54 |
+
"OffloadPolicy",
|
| 55 |
+
"register_fsdp_forward_method",
|
| 56 |
+
"UnshardHandle",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# Set namespace for exposed private names
|
| 60 |
+
CPUOffloadPolicy.__module__ = "torch.distributed.fsdp"
|
| 61 |
+
FSDPModule.__module__ = "torch.distributed.fsdp"
|
| 62 |
+
fully_shard.__module__ = "torch.distributed.fsdp"
|
| 63 |
+
MixedPrecisionPolicy.__module__ = "torch.distributed.fsdp"
|
| 64 |
+
OffloadPolicy.__module__ = "torch.distributed.fsdp"
|
| 65 |
+
register_fsdp_forward_method.__module__ = "torch.distributed.fsdp"
|
| 66 |
+
UnshardHandle.__module__ = "torch.distributed.fsdp"
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pyc
ADDED
|
Binary file (25.4 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pyc
ADDED
|
Binary file (8.54 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pyc
ADDED
|
Binary file (1.02 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pyc
ADDED
|
Binary file (15.9 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:66bf006c46374b6e50a305862d2144ca16d76f636f5b33f7f2bf3f4dff4b1971
|
| 3 |
+
size 120052
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pyc
ADDED
|
Binary file (7.05 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pyc
ADDED
|
Binary file (53.5 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pyc
ADDED
|
Binary file (2.19 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pyc
ADDED
|
Binary file (91.2 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pyc
ADDED
|
Binary file (69.2 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pyc
ADDED
|
Binary file (8.07 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pyc
ADDED
|
Binary file (39.1 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pyc
ADDED
|
Binary file (4.16 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pyc
ADDED
|
Binary file (22.2 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dec5da21d48e1ac508b6d023007524d8485fe227d43a5230d4dde0c24286311f
|
| 3 |
+
size 106898
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pyc
ADDED
|
Binary file (26.1 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Generator, Iterable
|
| 11 |
+
from enum import auto, Enum
|
| 12 |
+
from functools import partial
|
| 13 |
+
from itertools import chain
|
| 14 |
+
from typing import Any, Callable, 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 |
+
self.__device = device
|
| 69 |
+
except AttributeError as exc:
|
| 70 |
+
raise AttributeError(
|
| 71 |
+
f"Device '{device}' does not have a corresponding backend registered as 'torch.{device.type}'."
|
| 72 |
+
) from exc
|
| 73 |
+
else:
|
| 74 |
+
self.__backend = backend
|
| 75 |
+
|
| 76 |
+
@classmethod
|
| 77 |
+
def from_device(cls, device: torch.device) -> "_FSDPDeviceHandle":
|
| 78 |
+
"""
|
| 79 |
+
Return a device handle corresponding to the device, and through this handle,
|
| 80 |
+
operations with the same semantics as CUDA can be performed on the device.
|
| 81 |
+
Just return torch.cuda if the device is cuda to make attribute-access faster.
|
| 82 |
+
Custom backend must first register a module with the same name with {device.type} on torch.
|
| 83 |
+
"""
|
| 84 |
+
if device.type == "cuda":
|
| 85 |
+
return cast(_FSDPDeviceHandle, torch.cuda)
|
| 86 |
+
elif device.type == "mtia":
|
| 87 |
+
return cast(_FSDPDeviceHandle, torch.mtia)
|
| 88 |
+
return cls(device)
|
| 89 |
+
|
| 90 |
+
def __getattr__(self, name: str, /) -> Any:
|
| 91 |
+
try:
|
| 92 |
+
return getattr(self.__backend, name)
|
| 93 |
+
except AttributeError as exc:
|
| 94 |
+
raise AttributeError(
|
| 95 |
+
f"Custom backend '{self.__device.type}' not implement 'torch.{self.__device.type}.{name}'"
|
| 96 |
+
) from exc
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class _UninitializedDeviceHandle(_FSDPDeviceHandle):
|
| 100 |
+
def __init__(self) -> None:
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
def __getattribute__(self, name: str, /) -> Any:
|
| 104 |
+
raise RuntimeError("Trying to use an uninitialized device handle.")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class _FSDPState(_State):
|
| 108 |
+
def __init__(self) -> None:
|
| 109 |
+
# TODO: Move all the attributes to this class to enable typing for
|
| 110 |
+
# FSDP/fully_shard.
|
| 111 |
+
self._ignored_modules: set[nn.Module] = set()
|
| 112 |
+
self._ignored_params: set[nn.Parameter] = set()
|
| 113 |
+
# Buffer names are cleaned (without wrapper prefixes)
|
| 114 |
+
self._ignored_buffer_names: set[str] = set()
|
| 115 |
+
self.process_group: Optional[dist.ProcessGroup] = None
|
| 116 |
+
self.rank: int = -1
|
| 117 |
+
self.world_size: int = -1
|
| 118 |
+
self._device_mesh: Optional[DeviceMesh] = None
|
| 119 |
+
self.sharding_strategy = ShardingStrategy.FULL_SHARD
|
| 120 |
+
self._use_orig_params: bool = False
|
| 121 |
+
self.training_state = TrainingState.IDLE
|
| 122 |
+
self._unshard_params_ctx: dict[nn.Module, Generator] = {}
|
| 123 |
+
self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT
|
| 124 |
+
self._state_dict_config: StateDictConfig = FullStateDictConfig()
|
| 125 |
+
self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig()
|
| 126 |
+
self._is_root: Optional[bool] = None
|
| 127 |
+
self._handle: Optional[flat_param_file.FlatParamHandle] = None
|
| 128 |
+
self._fully_sharded_module_to_handle: dict[
|
| 129 |
+
nn.Module, Optional[flat_param_file.FlatParamHandle]
|
| 130 |
+
] = {}
|
| 131 |
+
self.compute_device: Optional[torch.device] = None
|
| 132 |
+
self._gradient_predivide_factor: int = 0
|
| 133 |
+
self._gradient_postdivide_factor: int = 0
|
| 134 |
+
self._comm_hook: Optional[Callable] = None
|
| 135 |
+
self._comm_hook_state: Optional[Any] = None
|
| 136 |
+
self._unshard_event: Optional[torch.Event] = None
|
| 137 |
+
# Abstract device handle for fsdp compute device. For now,
|
| 138 |
+
# the compute device must implement cuda semantics used by fsdp
|
| 139 |
+
self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle()
|
| 140 |
+
# All following attributes should only be used for root states:
|
| 141 |
+
# Save these static lists to avoid the repeated tree traversals
|
| 142 |
+
self._all_fsdp_states: list[_FSDPState] = []
|
| 143 |
+
self._all_handles: list[flat_param_file.FlatParamHandle] = []
|
| 144 |
+
self._fsdp_extension: Optional[FSDPExtensions] = None
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]:
|
| 148 |
+
state = _get_module_state(module)
|
| 149 |
+
if state is None or not isinstance(state, _FSDPState):
|
| 150 |
+
return None
|
| 151 |
+
return state
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _get_module_fsdp_state_if_fully_sharded_module(
|
| 155 |
+
module: nn.Module,
|
| 156 |
+
) -> Optional[_FSDPState]:
|
| 157 |
+
state = _get_module_fsdp_state(module)
|
| 158 |
+
if state is None:
|
| 159 |
+
return None
|
| 160 |
+
if state == module: # FullyShardedDataParallel module case.
|
| 161 |
+
return state
|
| 162 |
+
if module in state._fully_sharded_module_to_handle: # fully_shard case.
|
| 163 |
+
return state
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class TrainingState(Enum):
|
| 168 |
+
"""
|
| 169 |
+
An enum that indicates the state of a ``FullyShardedDataParallel` instance.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
IDLE = auto()
|
| 173 |
+
FORWARD_BACKWARD = auto()
|
| 174 |
+
SUMMON_FULL_PARAMS = auto()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class HandleTrainingState(Enum):
|
| 178 |
+
"""
|
| 179 |
+
An enum that indicates the state of a ``FlatParamHandle`.
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
IDLE = auto()
|
| 183 |
+
FORWARD = auto()
|
| 184 |
+
BACKWARD_PRE = auto()
|
| 185 |
+
BACKWARD_POST = auto()
|
| 186 |
+
SUMMON_FULL_PARAMS = auto()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _is_composable(state: _FSDPState):
|
| 190 |
+
# TODO: This is a temporary hack for differentiate between code paths.
|
| 191 |
+
return not isinstance(state, nn.Module)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@no_type_check
|
| 195 |
+
def _module_handle(state: _FSDPState, module: nn.Module) -> Optional["FlatParamHandle"]:
|
| 196 |
+
"""
|
| 197 |
+
Returns the ``FlatParamHandle`` s corresponding to ``module``. This is
|
| 198 |
+
the handle that contains some parameter in ``module``.
|
| 199 |
+
"""
|
| 200 |
+
if _is_composable(state):
|
| 201 |
+
# A valid FSDP state may have no managed parameters and hence no
|
| 202 |
+
# handles, meaning no entry in `_fully_sharded_module_to_handles`
|
| 203 |
+
if state._handle is None:
|
| 204 |
+
return None
|
| 205 |
+
assert module in state._fully_sharded_module_to_handle, (
|
| 206 |
+
f"Expects a fully sharded module but got {module} on rank {state.rank}"
|
| 207 |
+
)
|
| 208 |
+
return state._fully_sharded_module_to_handle[module]
|
| 209 |
+
else:
|
| 210 |
+
# NOTE: This assumes `module` is a `FullyShardedDataParallel` instance.
|
| 211 |
+
return module._handle
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@no_type_check
|
| 215 |
+
def _has_fsdp_params(state: _FSDPState, module: nn.Module) -> bool:
|
| 216 |
+
"""Returns if ``module`` has parameters managed by FSDP."""
|
| 217 |
+
return _module_handle(state, module) is not None
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _get_sharding_strategy(handle):
|
| 221 |
+
"""
|
| 222 |
+
Returns the sharding strategy of the handle.
|
| 223 |
+
"""
|
| 224 |
+
return handle._sharding_strategy if handle else None
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def clean_tensor_name(tensor_name: str) -> str:
|
| 228 |
+
"""
|
| 229 |
+
Cleans the parameter or buffer name by removing any module wrapper
|
| 230 |
+
prefixes.
|
| 231 |
+
"""
|
| 232 |
+
tensor_name = tensor_name.replace(FSDP_PREFIX, "")
|
| 233 |
+
# TODO: Explicitly replacing the checkpoint wrapper prefix is not ideal as
|
| 234 |
+
# it couples `CheckpointWrapper` and FSDP and also does not scale for more
|
| 235 |
+
# module wrappers.
|
| 236 |
+
tensor_name = tensor_name.replace(_CHECKPOINT_PREFIX, "")
|
| 237 |
+
return tensor_name
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _set_fsdp_flattened(tensor: torch.Tensor) -> None:
|
| 241 |
+
"""
|
| 242 |
+
Sets an attribute on ``tensor`` to mark it as flattened by FSDP. This is to
|
| 243 |
+
avoid re-flattening it during nested construction.
|
| 244 |
+
"""
|
| 245 |
+
setattr(tensor, FSDP_FLATTENED, True)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _is_fsdp_flattened(tensor: torch.Tensor) -> bool:
|
| 249 |
+
"""Returns if ``tensor`` has been marked as flattened by FSDP."""
|
| 250 |
+
return getattr(tensor, FSDP_FLATTENED, False)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _named_parameters_with_duplicates(
|
| 254 |
+
module: nn.Module, **kwargs: Any
|
| 255 |
+
) -> list[tuple[str, nn.Parameter]]:
|
| 256 |
+
"""
|
| 257 |
+
This API is required as some modules overwrite `named_parameters()` but do not support
|
| 258 |
+
`remove_duplicate`.
|
| 259 |
+
"""
|
| 260 |
+
assert "remove_duplicate" not in kwargs, (
|
| 261 |
+
"_named_parameters_with_duplicates cannot be used with `remove_duplicate` argument."
|
| 262 |
+
)
|
| 263 |
+
kwargs["remove_duplicate"] = False
|
| 264 |
+
try:
|
| 265 |
+
ret = list(module.named_parameters(**kwargs))
|
| 266 |
+
except AssertionError:
|
| 267 |
+
kwargs.pop("remove_duplicate")
|
| 268 |
+
ret = list(module.named_parameters(**kwargs))
|
| 269 |
+
return ret
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _get_param_to_fqns(
|
| 273 |
+
model: torch.nn.Module,
|
| 274 |
+
dedup_shared_params: bool = True,
|
| 275 |
+
) -> dict[nn.Parameter, list[str]]:
|
| 276 |
+
"""
|
| 277 |
+
Constructs a mapping from parameter to a list of its \"canonical\" FQNs. Here,
|
| 278 |
+
we use canonical to mean the fully-qualified name assigned to the parameter
|
| 279 |
+
based on its position in the original nn.Module hierarchy before any wrapper
|
| 280 |
+
or parallelism has been applied to it. This is in contrast to FQNs that may be
|
| 281 |
+
generated after parallelisms or wrappers have been applied to the model.
|
| 282 |
+
|
| 283 |
+
Each normal parameter maps to a singleton list containing its FQN, while each
|
| 284 |
+
``FlatParameter`` maps to a list of its original parameter FQNs, which may
|
| 285 |
+
have length greater than one. All FQNs are prefixed starting from ``model``.
|
| 286 |
+
|
| 287 |
+
In the case where FSDP was applied with ``use_orig_params=True``, there should be no
|
| 288 |
+
``FlatParameter`` s registered to the model's modules and this mapping will only
|
| 289 |
+
contain mappings from ``nn.Parameter`` s to singleton FQN lists.
|
| 290 |
+
|
| 291 |
+
It is only in the case where FSDP was applied with ``use_orig_params=False`` where
|
| 292 |
+
a ``FlatParameter`` will be registered in place of the original parameters and there
|
| 293 |
+
will be mappings from each ``FlatParameter`` to lists of FQNs corresponding to the
|
| 294 |
+
original parameters.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
model (torch.nn.Module): Root module (which may or may not be a
|
| 298 |
+
:class:`FullyShardedDataParallel` instance).
|
| 299 |
+
dedup_shared_params (bool): For shared parameters, if ``True``, only
|
| 300 |
+
includes the FQNs corresponding to the first encounter of the
|
| 301 |
+
shared parameter in the module traversal; if ``False``, then
|
| 302 |
+
includes the FQNs across all encounters. (Default: ``True``)
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
def module_fn(module, prefix, tree_level, param_to_fqns):
|
| 306 |
+
for param_name, param in _named_parameters_with_duplicates(
|
| 307 |
+
module, recurse=False
|
| 308 |
+
):
|
| 309 |
+
local_fqns = (
|
| 310 |
+
param._fqns
|
| 311 |
+
if isinstance(param, flat_param_file.FlatParameter)
|
| 312 |
+
else [param_name]
|
| 313 |
+
) # prefixed from `module`
|
| 314 |
+
global_fqns = [
|
| 315 |
+
clean_tensor_name(prefix + name) for name in local_fqns
|
| 316 |
+
] # prefixed from the top level `model` (i.e. including `prefix`)
|
| 317 |
+
is_shared_param = param in param_to_fqns
|
| 318 |
+
if not is_shared_param:
|
| 319 |
+
param_to_fqns[param] = global_fqns
|
| 320 |
+
else:
|
| 321 |
+
if isinstance(param, flat_param_file.FlatParameter):
|
| 322 |
+
# DMP overwrites `named_parameters` and skip (advance to
|
| 323 |
+
# the next child module) the wrapped_module (e.g.,
|
| 324 |
+
# _dmp_wrapped_module and _fsdp_wrapped_module). When a user
|
| 325 |
+
# calls `named_child` to traverse the module recursively and
|
| 326 |
+
# calls `named_parameters` with `recurse=False`, parameters
|
| 327 |
+
# will be traversed more than once.
|
| 328 |
+
# This hack is specified designed for DMP + FSDP. We
|
| 329 |
+
# overwrite the flat_parameters traversal result to only obtain
|
| 330 |
+
# the last one, which happens to be the correct one.
|
| 331 |
+
#
|
| 332 |
+
# TODO: Remove this hack once DMP + FSDP is not supported.
|
| 333 |
+
warnings.warn(
|
| 334 |
+
"FlatParameter is being traversed more than once. "
|
| 335 |
+
"This case should only happen when using "
|
| 336 |
+
"DistributedModelParallel with FullyShardedDataParallel."
|
| 337 |
+
)
|
| 338 |
+
param_to_fqns[param] = global_fqns
|
| 339 |
+
elif not dedup_shared_params:
|
| 340 |
+
param_to_fqns[param].extend(global_fqns)
|
| 341 |
+
|
| 342 |
+
def return_fn(param_to_fqns):
|
| 343 |
+
return param_to_fqns
|
| 344 |
+
|
| 345 |
+
param_to_unflat_param_names: dict[torch.nn.Parameter, list[str]] = {}
|
| 346 |
+
return _apply_to_modules(
|
| 347 |
+
model,
|
| 348 |
+
module_fn,
|
| 349 |
+
return_fn,
|
| 350 |
+
[key for key, _ in _named_parameters_with_duplicates(model)],
|
| 351 |
+
param_to_unflat_param_names,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
@no_type_check
|
| 356 |
+
def _log_post_backward_hook(
|
| 357 |
+
state: _FSDPState, handle: "FlatParamHandle", logger: logging.Logger
|
| 358 |
+
) -> None:
|
| 359 |
+
# Under TORCH_DISTRIBUTED_DEBUG=INFO, log the module names this hook fires for.
|
| 360 |
+
# Below logging of module names this post-bwd hook fires for can help debug certain
|
| 361 |
+
# cases where hooks don't fire, such as under certain activation checkpoint configs.
|
| 362 |
+
if state._use_orig_params and handle._debug_level == dist.DebugLevel.INFO:
|
| 363 |
+
param_fqns = _get_handle_fqns_from_root(state, handle)
|
| 364 |
+
logger.warning("FSDP firing post-backward hooks for parameters %s", param_fqns)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@no_type_check
|
| 368 |
+
def _get_handle_fqns_from_root(
|
| 369 |
+
state: _FSDPState, handle: "FlatParamHandle"
|
| 370 |
+
) -> Optional[list[str]]:
|
| 371 |
+
if handle is None:
|
| 372 |
+
return None
|
| 373 |
+
param_to_fqn = state._exec_order_data.param_to_fqn
|
| 374 |
+
handle_params = handle.flat_param._params # only populated for use_orig_params
|
| 375 |
+
param_fqns = [*chain.from_iterable(param_to_fqn[p] for p in handle_params)]
|
| 376 |
+
return param_fqns
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _apply_to_modules(
|
| 380 |
+
root_module: torch.nn.Module,
|
| 381 |
+
module_fn: Callable,
|
| 382 |
+
return_fn: Callable,
|
| 383 |
+
filter_fqns: Optional[list[str]] = None,
|
| 384 |
+
*args,
|
| 385 |
+
**kwargs,
|
| 386 |
+
):
|
| 387 |
+
"""
|
| 388 |
+
Performs a pre-order traversal of the modules in the hierarchy rooted at
|
| 389 |
+
``root_module``, applying ``module_fn`` at each module and finally
|
| 390 |
+
returning a value using ``return_fn``. The traversal constructs the full
|
| 391 |
+
module prefix name (e.g. "module.submodule." just like in model state dict)
|
| 392 |
+
and makes that available to ``module_fn``.
|
| 393 |
+
|
| 394 |
+
``filter_fqns`` is used because some module may have its own prefix similar
|
| 395 |
+
to ``FullyShardedDataParallel`` and the ``named_parameters()`` is overwritten
|
| 396 |
+
to remove the prefix.
|
| 397 |
+
"""
|
| 398 |
+
|
| 399 |
+
def f(module: torch.nn.Module, prefix: str, tree_level: int, *args, **kwargs):
|
| 400 |
+
# Call the module function before recursing over children (pre-order)
|
| 401 |
+
module_fn(module, prefix, tree_level, *args, **kwargs)
|
| 402 |
+
for submodule_name, submodule in module.named_children():
|
| 403 |
+
if submodule is None:
|
| 404 |
+
continue
|
| 405 |
+
new_prefix = prefix + submodule_name + "."
|
| 406 |
+
new_tree_level = tree_level + 1
|
| 407 |
+
if filter_fqns is not None:
|
| 408 |
+
for fqn in filter_fqns:
|
| 409 |
+
if fqn.startswith(new_prefix):
|
| 410 |
+
break
|
| 411 |
+
else:
|
| 412 |
+
# DMP's named_parameter() will mess up the traversal with
|
| 413 |
+
# ``named_children`` + `named_parameter(recurse=False)``.
|
| 414 |
+
# This hack is a must to make the traversal work.
|
| 415 |
+
# TODO: Remove this hack once DMP + FSDP is not supported.
|
| 416 |
+
# It turns out that recursive wrapping may trigger this as
|
| 417 |
+
# well.
|
| 418 |
+
if (
|
| 419 |
+
submodule_name == "_fsdp_wrapped_module"
|
| 420 |
+
or submodule_name == "_dmp_wrapped_module"
|
| 421 |
+
):
|
| 422 |
+
new_prefix = prefix
|
| 423 |
+
elif submodule_name == "module":
|
| 424 |
+
new_prefix = prefix
|
| 425 |
+
f(submodule, new_prefix, new_tree_level, *args, **kwargs)
|
| 426 |
+
|
| 427 |
+
f(root_module, "", 0, *args, **kwargs)
|
| 428 |
+
return return_fn(*args, **kwargs)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
@no_type_check
|
| 432 |
+
def _assert_in_training_states(
|
| 433 |
+
state: _FSDPState,
|
| 434 |
+
training_states: list[TrainingState],
|
| 435 |
+
) -> None:
|
| 436 |
+
"""Asserts that FSDP is in the states ``_training_states``."""
|
| 437 |
+
# Raise a `ValueError` instead of using `assert` to ensure that these
|
| 438 |
+
# logical assertions run even if `assert`s are disabled
|
| 439 |
+
if state.training_state not in training_states:
|
| 440 |
+
msg = (
|
| 441 |
+
f"expected to be in states {training_states} but current state is "
|
| 442 |
+
f"{state.training_state}"
|
| 443 |
+
)
|
| 444 |
+
# Print the error on rank 0 in case this is called in the backward pass
|
| 445 |
+
if state.rank == 0:
|
| 446 |
+
if isinstance(state, nn.Module):
|
| 447 |
+
print(f"Asserting FSDP instance is: {state}")
|
| 448 |
+
print(f"ERROR: {msg}")
|
| 449 |
+
traceback.print_stack()
|
| 450 |
+
raise ValueError(msg)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def _get_root_modules(modules: set[nn.Module]) -> set[nn.Module]:
|
| 454 |
+
"""
|
| 455 |
+
Returns:
|
| 456 |
+
Set[nn.Module]: The subset of ``modules`` that are root modules (i.e.
|
| 457 |
+
parent-less) with respect to the modules in the set itself. In other
|
| 458 |
+
words, these are the modules in ``modules`` that are not the child of
|
| 459 |
+
any other module in ``modules``.
|
| 460 |
+
"""
|
| 461 |
+
root_modules: set[nn.Module] = set()
|
| 462 |
+
module_to_submodules = {module: set(module.modules()) for module in modules}
|
| 463 |
+
for candidate_module in modules:
|
| 464 |
+
is_root_module = True
|
| 465 |
+
for module, submodules in module_to_submodules.items():
|
| 466 |
+
is_child_module = (
|
| 467 |
+
candidate_module is not module and candidate_module in submodules
|
| 468 |
+
)
|
| 469 |
+
if is_child_module:
|
| 470 |
+
is_root_module = False
|
| 471 |
+
break
|
| 472 |
+
if is_root_module:
|
| 473 |
+
root_modules.add(candidate_module)
|
| 474 |
+
return root_modules
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _override_module_mixed_precision(
|
| 478 |
+
root: torch.nn.Module,
|
| 479 |
+
module_classes_to_override: Iterable[type[nn.Module]],
|
| 480 |
+
wrap_override_dict: dict[str, Any] = {"mixed_precision": None}, # noqa: B006
|
| 481 |
+
) -> set[type[nn.Module]]:
|
| 482 |
+
module_classes_to_override = tuple(set(module_classes_to_override))
|
| 483 |
+
# Return a set of the actually overridden module classes
|
| 484 |
+
overridden_module_classes: set[type[nn.Module]] = set()
|
| 485 |
+
for mod in root.modules():
|
| 486 |
+
if isinstance(mod, module_classes_to_override):
|
| 487 |
+
overridden_module_classes.add(type(mod))
|
| 488 |
+
mod._wrap_overrides = wrap_override_dict # type: ignore[assignment]
|
| 489 |
+
# TODO: We need to run this mixed precision ignored module in fp32,
|
| 490 |
+
# but ensure subsequent modules, that may possibly be running with
|
| 491 |
+
# mixed precision, still receive the appropriate precision inputs
|
| 492 |
+
# without user having to adjust mixed precision config too much.
|
| 493 |
+
# As a result, we attach pre and post forward hooks to up / down
|
| 494 |
+
# cast. We should revisit this design.
|
| 495 |
+
|
| 496 |
+
def cast_fn(
|
| 497 |
+
dtype: torch.dtype, module: nn.Module, x: torch.Tensor
|
| 498 |
+
) -> torch.Tensor:
|
| 499 |
+
if not torch.is_floating_point(x) or x.dtype == dtype:
|
| 500 |
+
return x
|
| 501 |
+
_MODULE_TO_INP_DTYPE[module] = x.dtype
|
| 502 |
+
return x.to(dtype)
|
| 503 |
+
|
| 504 |
+
def forward_pre_hook(module, args):
|
| 505 |
+
return _apply_to_tensors(partial(cast_fn, torch.float32, module), args)
|
| 506 |
+
|
| 507 |
+
def forward_post_hook(module, args, output):
|
| 508 |
+
# NOTE: If the forward did not have any floating-point tensors,
|
| 509 |
+
# then the dtype will not be set for this module, and we do not
|
| 510 |
+
# upcast the dtype.
|
| 511 |
+
if module in _MODULE_TO_INP_DTYPE:
|
| 512 |
+
old_dtype = _MODULE_TO_INP_DTYPE[module]
|
| 513 |
+
return _apply_to_tensors(
|
| 514 |
+
partial(cast_fn, old_dtype, module), output
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
# We intentionally append both of these hooks so that they run after
|
| 518 |
+
# all other hooks.
|
| 519 |
+
mod.register_forward_pre_hook(forward_pre_hook, prepend=False)
|
| 520 |
+
mod.register_forward_hook(forward_post_hook, prepend=False)
|
| 521 |
+
return overridden_module_classes
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _no_dispatch_record_stream(tensor: torch.Tensor, stream: torch.Stream) -> None:
|
| 525 |
+
# FIXME record_stream doesn't work with non-cuda/mtia/xpu tensors
|
| 526 |
+
if tensor.device.type not in [
|
| 527 |
+
"cuda",
|
| 528 |
+
"mtia",
|
| 529 |
+
"xpu",
|
| 530 |
+
torch._C._get_privateuse1_backend_name(),
|
| 531 |
+
]:
|
| 532 |
+
return
|
| 533 |
+
|
| 534 |
+
if torch.distributed._functional_collectives.is_torchdynamo_compiling():
|
| 535 |
+
return
|
| 536 |
+
# from @ezyang:
|
| 537 |
+
# The no_dispatch was added in https://github.com/pytorch/pytorch/pull/88014 cc @fegin
|
| 538 |
+
# Looking over the PR, it looks like this is because we don't actually support Stream arguments
|
| 539 |
+
# in torch dispatch, so it just chokes.
|
| 540 |
+
# If Dynamo is able to answer "are there any torch dispatch modes" active (it should answer False),
|
| 541 |
+
# a better version of this would just be to check if there are any modes before disabling dispatch.
|
| 542 |
+
# TODO(voz): Extend a dynamo util to answer the above, unify the codepaths here.
|
| 543 |
+
tensor.record_stream(stream)
|
| 544 |
+
else:
|
| 545 |
+
with no_dispatch():
|
| 546 |
+
tensor.record_stream(stream)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
assert profile_type not in cls.profiling, (
|
| 43 |
+
f"{profile_type} is already being profiled. "
|
| 44 |
+
"SimpleProfiler does not support profiling multiple instances at "
|
| 45 |
+
"the same time. "
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
cls.profiling.add(profile_type)
|
| 49 |
+
begin = time.monotonic()
|
| 50 |
+
try:
|
| 51 |
+
yield
|
| 52 |
+
finally:
|
| 53 |
+
end = time.monotonic()
|
| 54 |
+
cls.results[profile_type] += end - begin
|
| 55 |
+
cls.profiling.remove(profile_type)
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
def dump_and_reset(cls, msg: str) -> None:
|
| 59 |
+
# This cannot be combined with DETAIL distributed log
|
| 60 |
+
# as the profiling will be very incorrect.
|
| 61 |
+
if dist.get_rank() == 0 and dist.get_debug_level() == dist.DebugLevel.INFO:
|
| 62 |
+
logger.info("%s %s", msg, cls.results)
|
| 63 |
+
cls.reset()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _get_sharded_module_tree_with_module_name_to_fqns(
|
| 67 |
+
model: torch.nn.Module,
|
| 68 |
+
) -> tuple[str, dict[str, list[str]]]:
|
| 69 |
+
"""
|
| 70 |
+
It is used for composable fully_shard() code path, it returns
|
| 71 |
+
1. sharded module tree info: each line represents a submodule name that contains the
|
| 72 |
+
submodule's FQN and its submodule class name, if the submodule is sharded by `fully_shard`,
|
| 73 |
+
the submodule name will add a postfix with ' FULLY SHARDED'. Each increased tree
|
| 74 |
+
level adds 4 spaces before the printed name. A printed sharded module tree info for a toy model
|
| 75 |
+
is like this:
|
| 76 |
+
[CompositeModel] FULLY SHARDED
|
| 77 |
+
l1[Linear]
|
| 78 |
+
u1[UnitModule] FULLY SHARDED
|
| 79 |
+
u1.l1[Linear]
|
| 80 |
+
u1.seq[Sequential]
|
| 81 |
+
u1.seq.0[ReLU]
|
| 82 |
+
u1.seq.1[Linear]
|
| 83 |
+
u1.seq.2[ReLU]
|
| 84 |
+
u1.l2[Linear]
|
| 85 |
+
u2[UnitModule] FULLY SHARDED
|
| 86 |
+
u2.l1[Linear]
|
| 87 |
+
u2.seq[Sequential]
|
| 88 |
+
u2.seq.0[ReLU]
|
| 89 |
+
u2.seq.1[Linear]
|
| 90 |
+
u2.seq.2[ReLU]
|
| 91 |
+
u2.l2[Linear]
|
| 92 |
+
l2[Linear]
|
| 93 |
+
2. a dict mapping from the concated module FQN and class name to a list of its managed
|
| 94 |
+
original parameters' FQNs. An example of the dict for the above toy sharded model is like this:
|
| 95 |
+
{'[CompositeModel]': ['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'],
|
| 96 |
+
'u1[UnitModule]': ['u1.l1.weight', 'u1.l1.bias', 'u1.seq.1.weight', 'u1.seq.1.bias', 'u1.l2.weight', 'u1.l2.bias'],
|
| 97 |
+
'u2[UnitModule]': ['u2.l1.weight', 'u2.l1.bias', 'u2.seq.1.weight', 'u2.seq.1.bias', 'u2.l2.weight', 'u2.l2.bias']
|
| 98 |
+
}
|
| 99 |
+
All FQNs are prefixed starting from ``model``.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
model (torch.nn.Module): Root module (which may or may not be passed to
|
| 103 |
+
composable `fully_shard()`).
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def module_fn(
|
| 107 |
+
module, prefix, tree_level, sharded_tree_info, sharded_module_name_to_fqns
|
| 108 |
+
):
|
| 109 |
+
num_spaces = tree_level * 4
|
| 110 |
+
trimed_prefix = (
|
| 111 |
+
prefix[:-1] if (len(prefix) > 0 and prefix[-1] == ".") else prefix
|
| 112 |
+
)
|
| 113 |
+
prefixed_module_name = trimed_prefix + "[" + module.__class__.__name__ + "]"
|
| 114 |
+
printed_prefixed_module_name = " " * num_spaces + prefixed_module_name
|
| 115 |
+
|
| 116 |
+
state = _get_module_fsdp_state(module)
|
| 117 |
+
if state is None:
|
| 118 |
+
sharded_tree_info[0] += printed_prefixed_module_name + "\n"
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
handle = state._fully_sharded_module_to_handle.get(module, None)
|
| 122 |
+
|
| 123 |
+
if handle:
|
| 124 |
+
sharded_tree_info[0] += (
|
| 125 |
+
printed_prefixed_module_name + " FULLY SHARDED" + "\n"
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
sharded_tree_info[0] += printed_prefixed_module_name + "\n"
|
| 129 |
+
|
| 130 |
+
if handle:
|
| 131 |
+
param = handle.flat_param
|
| 132 |
+
assert isinstance(param, flat_param_file.FlatParameter)
|
| 133 |
+
global_fqns = [
|
| 134 |
+
clean_tensor_name(prefix + name) for name in param._fqns
|
| 135 |
+
] # prefixed from the top level `model` (i.e. including `prefix`)
|
| 136 |
+
|
| 137 |
+
if prefixed_module_name in sharded_module_name_to_fqns:
|
| 138 |
+
sharded_module_name_to_fqns[prefixed_module_name].extend(global_fqns)
|
| 139 |
+
else:
|
| 140 |
+
sharded_module_name_to_fqns[prefixed_module_name] = global_fqns
|
| 141 |
+
|
| 142 |
+
def return_fn(sharded_tree_info, sharded_module_name_to_fqns):
|
| 143 |
+
return sharded_tree_info[0], sharded_module_name_to_fqns
|
| 144 |
+
|
| 145 |
+
# Use List to mutate its value in place while running the recursive functions
|
| 146 |
+
sharded_tree_info: list[str] = [
|
| 147 |
+
"",
|
| 148 |
+
]
|
| 149 |
+
sharded_module_name_to_fqns: dict[str, list[str]] = {}
|
| 150 |
+
return _apply_to_modules(
|
| 151 |
+
model,
|
| 152 |
+
module_fn,
|
| 153 |
+
return_fn,
|
| 154 |
+
[key for key, _ in model.named_parameters()],
|
| 155 |
+
sharded_tree_info,
|
| 156 |
+
sharded_module_name_to_fqns,
|
| 157 |
+
)
|
pace_revision_1/.venv-pace/lib/python3.11/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]
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
assert self.world_size is not None # mypy
|
| 218 |
+
if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
|
| 219 |
+
# TODO(voz): Don't graph break on this - dynamo hates the n1 != n2
|
| 220 |
+
# tensor comparison control flow.
|
| 221 |
+
# https://github.com/pytorch/pytorch/issues/107055
|
| 222 |
+
for (r1, n1), (r2, n2) in itertools.combinations(
|
| 223 |
+
(
|
| 224 |
+
(rank, world_num_valid_indices[rank])
|
| 225 |
+
for rank in range(self.world_size)
|
| 226 |
+
),
|
| 227 |
+
2,
|
| 228 |
+
):
|
| 229 |
+
if n1 != n2:
|
| 230 |
+
raise RuntimeError(
|
| 231 |
+
f"{msg_prefix} rank {r1} is all-gathering {n1} parameters "
|
| 232 |
+
f"while rank {r2} is all-gathering {n2} parameters"
|
| 233 |
+
)
|
| 234 |
+
world_indices = torch.zeros( # type: ignore[call-overload]
|
| 235 |
+
self.world_size * num_valid_indices, **tensor_kwargs
|
| 236 |
+
)
|
| 237 |
+
local_indices = torch.tensor(optional_local_indices, **tensor_kwargs) # type: ignore[arg-type]
|
| 238 |
+
dist.all_gather_into_tensor(
|
| 239 |
+
world_indices, local_indices, group=self.process_group
|
| 240 |
+
)
|
| 241 |
+
# Copy entire tensor from D2H once to avoid per element D2H copies
|
| 242 |
+
world_indices = world_indices.cpu()
|
| 243 |
+
# Check that all ranks plan to all-gather the same index parameters
|
| 244 |
+
if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
|
| 245 |
+
# TODO(voz): Don't graph break on this - dynamo hates the i1 != i2
|
| 246 |
+
# tensor comparison control flow.
|
| 247 |
+
# https://github.com/pytorch/pytorch/issues/107055
|
| 248 |
+
for (r1, i1), (r2, i2) in itertools.combinations(
|
| 249 |
+
(
|
| 250 |
+
(
|
| 251 |
+
rank,
|
| 252 |
+
world_indices[
|
| 253 |
+
rank * num_valid_indices : (rank + 1)
|
| 254 |
+
* num_valid_indices
|
| 255 |
+
],
|
| 256 |
+
)
|
| 257 |
+
for rank in range(self.world_size)
|
| 258 |
+
),
|
| 259 |
+
2,
|
| 260 |
+
):
|
| 261 |
+
if i1 != i2:
|
| 262 |
+
r1_param_names = self._get_names_from_handle_indices(i1)
|
| 263 |
+
r2_param_names = self._get_names_from_handle_indices(i2)
|
| 264 |
+
raise RuntimeError(
|
| 265 |
+
f"{msg_prefix} rank {r1} is all-gathering parameters "
|
| 266 |
+
f"for {r1_param_names} while rank {r2} is all-gathering "
|
| 267 |
+
f"parameters for {r2_param_names}"
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
# Only issue warnings on the first deviating iteration and stop
|
| 271 |
+
# checking thereafter to avoid flooding the console
|
| 272 |
+
if self.warn_status == _ExecOrderWarnStatus.WARNED:
|
| 273 |
+
return
|
| 274 |
+
msg_prefix = None # non-`None` means we should warn
|
| 275 |
+
if self.current_order_index >= len(self.handles_pre_forward_order):
|
| 276 |
+
# This iteration sees extra all-gather(s) compared to the first
|
| 277 |
+
msg_prefix = (
|
| 278 |
+
"Expected to not all-gather any more parameters in the "
|
| 279 |
+
"forward but trying to all-gather parameters for "
|
| 280 |
+
)
|
| 281 |
+
else:
|
| 282 |
+
expected_handle = self.handles_pre_forward_order[
|
| 283 |
+
self.current_order_index
|
| 284 |
+
]
|
| 285 |
+
if expected_handle != handle:
|
| 286 |
+
expected_param_names = self._get_names_from_handles(expected_handle)
|
| 287 |
+
msg_prefix = (
|
| 288 |
+
f"Expected to all-gather for {expected_param_names} "
|
| 289 |
+
"but trying to all-gather parameters for "
|
| 290 |
+
)
|
| 291 |
+
if msg_prefix is not None:
|
| 292 |
+
param_names = self._get_names_from_handles(handle)
|
| 293 |
+
msg_suffix = (
|
| 294 |
+
f"{param_names}"
|
| 295 |
+
if param_names
|
| 296 |
+
else "a newly-added parameter since construction time"
|
| 297 |
+
)
|
| 298 |
+
warnings.warn(
|
| 299 |
+
"Forward order differs from that of the first iteration "
|
| 300 |
+
f"on rank {self.rank}. Collectives are unchecked and may "
|
| 301 |
+
f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}"
|
| 302 |
+
)
|
| 303 |
+
self.warn_status = _ExecOrderWarnStatus.WARNING
|
| 304 |
+
self.current_order_index += 1
|
| 305 |
+
|
| 306 |
+
def _get_handle_indices(
|
| 307 |
+
self,
|
| 308 |
+
handle: FlatParamHandle,
|
| 309 |
+
) -> tuple[Optional[int], ...]:
|
| 310 |
+
"""
|
| 311 |
+
Returns the handle indices (i.e. indices into ``self.all_handles``)
|
| 312 |
+
corresponding to the handles in ``handle``. An entry in the
|
| 313 |
+
returned tuple is ``None`` if the handle is invalid.
|
| 314 |
+
"""
|
| 315 |
+
indices: list[Optional[int]] = []
|
| 316 |
+
if handle:
|
| 317 |
+
indices.append(handle._handle_index)
|
| 318 |
+
return tuple(indices)
|
| 319 |
+
|
| 320 |
+
def _get_names_from_handle_indices(
|
| 321 |
+
self,
|
| 322 |
+
handle_indices: tuple[int, ...],
|
| 323 |
+
) -> list[list[str]]:
|
| 324 |
+
"""
|
| 325 |
+
Returns a list of FQNs for each handle in ``handle_indices``. If a
|
| 326 |
+
handle index is invalid, then its FQNs are omitted from the returned
|
| 327 |
+
list.
|
| 328 |
+
"""
|
| 329 |
+
fqns: list[list[str]] = []
|
| 330 |
+
for index in handle_indices:
|
| 331 |
+
if index is None or index < 0 or index >= len(self.all_handles):
|
| 332 |
+
continue
|
| 333 |
+
handle = self.all_handles[index]
|
| 334 |
+
flat_param = handle.flat_param
|
| 335 |
+
fqns.append(self.param_to_fqn[flat_param])
|
| 336 |
+
return fqns
|
| 337 |
+
|
| 338 |
+
def _get_names_from_handles(
|
| 339 |
+
self,
|
| 340 |
+
handle: FlatParamHandle,
|
| 341 |
+
) -> list[list[str]]:
|
| 342 |
+
"""
|
| 343 |
+
Returns a list of FQNs for each handle in ``handles_key``. If a handle
|
| 344 |
+
is invalid, then its FQNs are omitted from the returned list.
|
| 345 |
+
"""
|
| 346 |
+
fqns: list[list[str]] = []
|
| 347 |
+
if handle:
|
| 348 |
+
flat_param = handle.flat_param
|
| 349 |
+
if flat_param in self.param_to_fqn:
|
| 350 |
+
fqns.append(self.param_to_fqn[flat_param])
|
| 351 |
+
return fqns
|
| 352 |
+
|
| 353 |
+
def next_iter(self):
|
| 354 |
+
"""
|
| 355 |
+
Advances the internal data structures per iteration. This should be
|
| 356 |
+
called in the post-backward callback since that marks the true end of
|
| 357 |
+
an iteration.
|
| 358 |
+
"""
|
| 359 |
+
self._iter += 1
|
| 360 |
+
self.handles_post_forward_order.clear()
|
| 361 |
+
if self._checking_order:
|
| 362 |
+
self.current_order_index = 0
|
| 363 |
+
if self.warn_status == _ExecOrderWarnStatus.WARNING:
|
| 364 |
+
self.warn_status = _ExecOrderWarnStatus.WARNED
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsd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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
assert type(tensor) is ShardedTensor
|
| 165 |
+
shards = tensor.local_shards()
|
| 166 |
+
return (tensor, shards)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _ext_all_gather_dtensor(
|
| 170 |
+
tensor: DTensor,
|
| 171 |
+
parent_mesh: Optional[DeviceMesh],
|
| 172 |
+
fsdp_extension: Optional[FSDPExtensions] = None,
|
| 173 |
+
) -> torch.Tensor:
|
| 174 |
+
all_gather_dtensor_fn = (
|
| 175 |
+
fsdp_extension.all_gather_dtensor
|
| 176 |
+
if fsdp_extension is not None
|
| 177 |
+
else _all_gather_dtensor
|
| 178 |
+
)
|
| 179 |
+
return all_gather_dtensor_fn(tensor, parent_mesh)
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
|
| 2 |
+
from ._fully_shard import (
|
| 3 |
+
FSDPModule,
|
| 4 |
+
fully_shard,
|
| 5 |
+
register_fsdp_forward_method,
|
| 6 |
+
UnshardHandle,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"CPUOffloadPolicy",
|
| 12 |
+
"FSDPModule",
|
| 13 |
+
"fully_shard",
|
| 14 |
+
"MixedPrecisionPolicy",
|
| 15 |
+
"OffloadPolicy",
|
| 16 |
+
"register_fsdp_forward_method",
|
| 17 |
+
"UnshardHandle",
|
| 18 |
+
]
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (608 Bytes). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_api.cpython-311.pyc
ADDED
|
Binary file (7.95 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_collectives.cpython-311.pyc
ADDED
|
Binary file (35.4 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_common.cpython-311.pyc
ADDED
|
Binary file (9.62 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_init.cpython-311.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param.cpython-311.pyc
ADDED
|
Binary file (43.4 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param_group.cpython-311.pyc
ADDED
|
Binary file (43.8 kB). View file
|
|
|
pace_revision_1/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_state.cpython-311.pyc
ADDED
|
Binary file (22.5 kB). View file
|
|
|