Commit ·
25485a0
1
Parent(s): eb8af13
Upload folder using huggingface_hub (part 19)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+5
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.pyAdded+54
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.pyAdded+283
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.pyAdded+24
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.pyAdded+442
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.pyAdded+128
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.pyAdded+9
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.pyAdded+62
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.pyAdded+10
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.pyAdded+57
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.pyAdded+92
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.pyAdded+184
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.pyAdded+14
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.pyAdded+69
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.pyAdded+226
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.pyAdded+66
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pycAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pycAdded+3
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.pyAdded+546
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.pyAdded+157
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.pyAdded+43
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.pyAdded+364
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.pyAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.pyAdded+179
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__init__.pyAdded+18
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/__init__.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_api.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_collectives.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_common.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_init.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param_group.cpython-311.pycAdded
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_state.cpython-311.pycAdded
1274 unmodified lines1275127612771274 unmodified linespace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text1274 unmodified lines127512761277127812791280128112821274 unmodified linespace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/fx/__pycache__/graph.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/fx/experimental/__pycache__/proxy_tensor.cpython-311.pyc filter=lfs diff=lfs merge=lfs -textpace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Expiration timers are set up on the same process as the agent andused from your script to deal with stuck workers. When you go intoa code-block that has the potential to get stuck you can acquirean expiration timer, which instructs the timer server to kill theprocess if it does not release the timer by the self-imposed expirationdeadline.
Usage::
import torchelastic.timer as timer import torchelastic.agent.server as agent
def main(): start_method = "spawn" message_queue = mp.get_context(start_method).Queue() server = timer.LocalTimerServer(message, max_interval=0.01) server.start() # non-blocking
spec = WorkerSpec( fn=trainer_func, args=(message_queue,), ...<OTHER_PARAMS...>) agent = agent.LocalElasticAgent(spec, start_method) agent.run()
def trainer_func(message_queue): timer.configure(timer.LocalTimerClient(message_queue)) with timer.expires(after=60): # 60 second expiry # do some work
In the example above if ``trainer_func`` takes more than 60 seconds tocomplete, then the worker process is killed and the agent retries the worker group."""
from .api import ( # noqa: F401 configure, expires, TimerClient, TimerRequest, TimerServer,)from .file_based_local_timer import ( # noqa: F401 FileTimerClient, FileTimerRequest, FileTimerServer,)from .local_timer import LocalTimerClient, LocalTimerServer # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# mypy: allow-untyped-defs# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.import abcimport loggingimport threadingimport timefrom contextlib import contextmanagerfrom inspect import getframeinfo, stackfrom typing import Any, Optional
__all__ = [ "TimerRequest", "TimerClient", "RequestQueue", "TimerServer", "configure", "expires",]
logger = logging.getLogger(__name__)
class TimerRequest: """ Data object representing a countdown timer acquisition and release that is used between the ``TimerClient`` and ``TimerServer``. A negative ``expiration_time`` should be interpreted as a "release" request.
.. note:: the type of ``worker_id`` is implementation specific. It is whatever the TimerServer and TimerClient implementations have on to uniquely identify a worker. """
__slots__ = ["worker_id", "scope_id", "expiration_time"]
def __init__(self, worker_id: Any, scope_id: str, expiration_time: float): self.worker_id = worker_id self.scope_id = scope_id self.expiration_time = expiration_time
def __eq__(self, other): if isinstance(other, TimerRequest): return ( self.worker_id == other.worker_id and self.scope_id == other.scope_id and self.expiration_time == other.expiration_time ) return False
class TimerClient(abc.ABC): """ Client library to acquire and release countdown timers by communicating with the TimerServer. """
@abc.abstractmethod def acquire(self, scope_id: str, expiration_time: float) -> None: """ Acquires a timer for the worker that holds this client object given the scope_id and expiration_time. Typically registers the timer with the TimerServer. """
@abc.abstractmethod def release(self, scope_id: str): """ Releases the timer for the ``scope_id`` on the worker this client represents. After this method is called, the countdown timer on the scope is no longer in effect. """
class RequestQueue(abc.ABC): """ Consumer queue holding timer acquisition/release requests """
@abc.abstractmethod def size(self) -> int: """ Returns the size of the queue at the time this method is called. Note that by the time ``get`` is called the size of the queue may have increased. The size of the queue should not decrease until the ``get`` method is called. That is, the following assertion should hold:
size = q.size() res = q.get(size, timeout=0) assert size == len(res)
-- or --
size = q.size() res = q.get(size * 2, timeout=1) assert size <= len(res) <= size * 2 """
@abc.abstractmethod def get(self, size: int, timeout: float) -> list[TimerRequest]: """ Gets up to ``size`` number of timer requests in a blocking fashion (no more than ``timeout`` seconds). """
class TimerServer(abc.ABC): """ Entity that monitors active timers and expires them in a timely fashion. This server is responsible for reaping workers that have expired timers. """
def __init__( self, request_queue: RequestQueue, max_interval: float, daemon: bool = True ): """ :param request_queue: Consumer ``RequestQueue`` :param max_interval: max time (in seconds) to wait for an item in the request_queue :param daemon: whether to run the watchdog thread as a daemon """ super().__init__() self._request_queue = request_queue self._max_interval = max_interval self._daemon = daemon self._watchdog_thread: Optional[threading.Thread] = None self._stop_signaled = False
@abc.abstractmethod def register_timers(self, timer_requests: list[TimerRequest]) -> None: """ Processes the incoming timer requests and registers them with the server. The timer request can either be a acquire-timer or release-timer request. Timer requests with a negative expiration_time should be interpreted as a release-timer request. """
@abc.abstractmethod def clear_timers(self, worker_ids: set[Any]) -> None: """ Clears all timers for the given ``worker_ids``. """
@abc.abstractmethod def get_expired_timers(self, deadline: float) -> dict[str, list[TimerRequest]]: """ Returns all expired timers for each worker_id. An expired timer is a timer for which the expiration_time is less than or equal to the provided deadline. """
@abc.abstractmethod def _reap_worker(self, worker_id: Any) -> bool: """ Reaps the given worker. Returns True if the worker has been successfully reaped, False otherwise. If any uncaught exception is thrown from this method, the worker is considered reaped and all associated timers will be removed. """
def _reap_worker_no_throw(self, worker_id: Any) -> bool: """ Wraps ``_reap_worker(worker_id)``, if an uncaught exception is thrown, then it considers the worker as reaped. """ try: return self._reap_worker(worker_id) except Exception: logger.exception( "Uncaught exception thrown from _reap_worker(), " "check that the implementation correctly catches exceptions", ) return True
def _watchdog_loop(self): while not self._stop_signaled: try: self._run_watchdog() except Exception: logger.exception("Error running watchdog")
def _run_watchdog(self): batch_size = max(1, self._request_queue.size()) timer_requests = self._request_queue.get(batch_size, self._max_interval) self.register_timers(timer_requests) now = time.time() reaped_worker_ids = set() for worker_id, expired_timers in self.get_expired_timers(now).items(): logger.info( "Reaping worker_id=[%s]. Expired timers: %s", worker_id, self._get_scopes(expired_timers), ) if self._reap_worker_no_throw(worker_id): logger.info("Successfully reaped worker=[%s]", worker_id) reaped_worker_ids.add(worker_id) else: logger.error( "Error reaping worker=[%s]. Will retry on next watchdog.", worker_id ) self.clear_timers(reaped_worker_ids)
def _get_scopes(self, timer_requests): return [r.scope_id for r in timer_requests]
def start(self) -> None: logger.info( "Starting %s... max_interval=%s, daemon=%s", type(self).__name__, self._max_interval, self._daemon, ) self._watchdog_thread = threading.Thread( target=self._watchdog_loop, daemon=self._daemon ) logger.info("Starting watchdog thread...") self._watchdog_thread.start()
def stop(self) -> None: logger.info("Stopping %s", type(self).__name__) self._stop_signaled = True if self._watchdog_thread: logger.info("Stopping watchdog thread...") self._watchdog_thread.join(self._max_interval) self._watchdog_thread = None else: logger.info("No watchdog thread running, doing nothing")
_timer_client: Optional[TimerClient] = None
def configure(timer_client: TimerClient): """ Configures a timer client. Must be called before using ``expires``. """ global _timer_client _timer_client = timer_client logger.info("Timer client configured to: %s", type(_timer_client).__name__)
@contextmanagerdef expires( after: float, scope: Optional[str] = None, client: Optional[TimerClient] = None): """ Acquires a countdown timer that expires in ``after`` seconds from now, unless the code-block that it wraps is finished within the timeframe. When the timer expires, this worker is eligible to be reaped. The exact meaning of "reaped" depends on the client implementation. In most cases, reaping means to terminate the worker process. Note that the worker is NOT guaranteed to be reaped at exactly ``time.now() + after``, but rather the worker is "eligible" for being reaped and the ``TimerServer`` that the client talks to will ultimately make the decision when and how to reap the workers with expired timers.
Usage::
torch.distributed.elastic.timer.configure(LocalTimerClient()) with expires(after=10): torch.distributed.all_reduce(...) """ if client is None: if _timer_client is None: raise RuntimeError("Configure timer client before using countdown timers.") client = _timer_client if scope is None: # grab the caller file + lineno caller = getframeinfo(stack()[1][0]) scope = f"{caller.filename}#{caller.lineno}" expiration = time.time() + after client.acquire(scope, expiration) try: yield finally: client.release(scope)123456789101112131415161718192021222324#!/usr/bin/env python3# mypy: allow-untyped-defs
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
from torch.distributed.elastic.utils.logging import get_logger
logger = get_logger(__name__)
__all__ = ["log_debug_info_for_expired_timers"]
def log_debug_info_for_expired_timers( run_id: str, expired_timers: dict[int, list[str]],): if expired_timers: logger.info("Timers expired for run:[%s] [%s].", run_id, expired_timers)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442# mypy: allow-untyped-defs# Copyright (c) Meta Platforms, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
import ioimport jsonimport osimport selectimport signalimport sysimport threadingimport timefrom typing import Callable, Optional, TypeVarfrom typing_extensions import ParamSpec
from torch.distributed.elastic.timer.api import TimerClient, TimerRequestfrom torch.distributed.elastic.timer.debug_info_logging import ( log_debug_info_for_expired_timers,)from torch.distributed.elastic.utils.logging import get_logger
_P = ParamSpec("_P")_R = TypeVar("_R")
__all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"]
logger = get_logger(__name__)
def _retry(max_retries: int, sleep_time: float) -> Callable: """ A simple retry wrapper.
Args: max_retries: int, the maximum number of retries. sleep_time: float, the time to sleep between retries. """
def wrapper(func: Callable[_P, _R]) -> Callable[_P, _R]: def wrapper(*args: _P.args, **kwargs: _P.kwargs): for i in range(max_retries): try: return func(*args, **kwargs) except Exception: logger.exception("Error running %s. Retrying...", func.__name__) if i < max_retries - 1: time.sleep(sleep_time) else: raise
return wrapper
return wrapper
class FileTimerRequest(TimerRequest): """ Data object representing a countdown timer acquisition and release that is used between the ``FileTimerClient`` and ``FileTimerServer``. A negative ``expiration_time`` should be interpreted as a "release" request. ``signal`` is the signal to reap the worker process from the server process. """
__slots__ = ["version", "worker_pid", "scope_id", "expiration_time", "signal"]
def __init__( self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0 ) -> None: self.version = 1 self.worker_pid = worker_pid self.scope_id = scope_id self.expiration_time = expiration_time self.signal = signal
def __eq__(self, other) -> bool: if isinstance(other, FileTimerRequest): return ( self.version == other.version and self.worker_pid == other.worker_pid and self.scope_id == other.scope_id and self.expiration_time == other.expiration_time and self.signal == other.signal ) return False
def to_json(self) -> str: return json.dumps( { "version": self.version, "pid": self.worker_pid, "scope_id": self.scope_id, "expiration_time": self.expiration_time, "signal": self.signal, }, )
class FileTimerClient(TimerClient): """ Client side of ``FileTimerServer``. This client is meant to be used on the same host that the ``FileTimerServer`` is running on and uses pid to uniquely identify a worker. This client uses a named_pipe to send timer requests to the ``FileTimerServer``. This client is a producer while the ``FileTimerServer`` is a consumer. Multiple clients can work with the same ``FileTimerServer``.
Args:
file_path: str, the path of a FIFO special file. ``FileTimerServer`` must have created it by calling os.mkfifo().
signal: signal, the signal to use to kill the process. Using a negative or zero signal will not kill the process. """
def __init__( self, file_path: str, signal=(signal.SIGKILL if sys.platform != "win32" else signal.CTRL_C_EVENT), # type: ignore[attr-defined] ) -> None: super().__init__() self._file_path = file_path self.signal = signal
@_retry(max_retries=10, sleep_time=0.1) def _open_non_blocking(self) -> Optional[io.TextIOWrapper]: # The server may have crashed or may haven't started yet. # In such case, calling open() in blocking model blocks the client. # To avoid such issue, open it in non-blocking mode, and an OSError will # be raised if the server is not there. fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK) return os.fdopen(fd, "wt")
def _send_request(self, request: FileTimerRequest) -> None: try: file = self._open_non_blocking() except Exception as e: raise BrokenPipeError( "Could not send the FileTimerRequest because FileTimerServer is not available." ) from e with file: json_request = request.to_json() # Write request with no greater than select.PIPE_BUF is guarantee to be atomic. if len(json_request) > select.PIPE_BUF: raise RuntimeError( f"FileTimerRequest larger than {select.PIPE_BUF} bytes " f"is not supported: {json_request}" ) file.write(json_request + "\n")
def acquire(self, scope_id: str, expiration_time: float) -> None: self._send_request( request=FileTimerRequest( worker_pid=os.getpid(), scope_id=scope_id, expiration_time=expiration_time, signal=self.signal, ), )
def release(self, scope_id: str) -> None: self._send_request( request=FileTimerRequest( worker_pid=os.getpid(), scope_id=scope_id, expiration_time=-1, signal=0 ), )
class FileTimerServer: """ Server that works with ``FileTimerClient``. Clients are expected to be running on the same host as the process that is running this server. Each host in the job is expected to start its own timer server locally and each server instance manages timers for local workers (running on processes on the same host).
Args:
file_path: str, the path of a FIFO special file to be created.
max_interval: float, max interval in seconds for each watchdog loop.
daemon: bool, running the watchdog thread in daemon mode or not. A daemon thread will not block a process to stop. log_event: Callable[[Dict[str, str]], None], an optional callback for logging the events in JSON format. """
def __init__( self, file_path: str, run_id: str, max_interval: float = 10, daemon: bool = True, log_event: Optional[Callable[[str, Optional[FileTimerRequest]], None]] = None, ) -> None: self._file_path = file_path self._run_id = run_id self._max_interval = max_interval self._daemon = daemon self._timers: dict[tuple[int, str], FileTimerRequest] = {} self._stop_signaled = False self._watchdog_thread: Optional[threading.Thread] = None
self._is_client_started = False if os.path.exists(self._file_path): os.remove(self._file_path) os.mkfifo(self._file_path) # For test only. Count the number of requests received. self._request_count = 0 # For test only. Process all requests and stop the server. self._run_once = False self._log_event = ( log_event if log_event is not None else lambda name, request: None ) self._last_progress_time = int(time.time())
def start(self) -> None: logger.info( "Starting %s... max_interval=%s, daemon=%s, file_path=%s", type(self).__name__, self._max_interval, self._daemon, self._file_path, ) self._watchdog_thread = threading.Thread( target=self._watchdog_loop, daemon=self._daemon ) logger.info("Starting watchdog thread...") self._watchdog_thread.start() self._log_event("watchdog started", None)
def stop(self) -> None: logger.info("Stopping %s", type(self).__name__) self._stop_signaled = True if self._watchdog_thread: logger.info("Stopping watchdog thread...") self._watchdog_thread.join(self._max_interval) self._watchdog_thread = None else: logger.info("No watchdog thread running, doing nothing") if os.path.exists(self._file_path): os.remove(self._file_path) self._log_event("watchdog stopped", None)
def run_once(self) -> None: self._run_once = True if self._watchdog_thread: logger.info("Stopping watchdog thread...") self._watchdog_thread.join() self._watchdog_thread = None else: logger.info("No watchdog thread running, doing nothing") if os.path.exists(self._file_path): os.remove(self._file_path)
@staticmethod def is_process_running(pid: int): """ function to check process is running or not """ try: # Check if the process exists and we can send signals to it os.kill(pid, 0) return True except OSError: return False
def _watchdog_loop(self) -> None: # Open the pipe in blocking mode blocks the server thread. # This is fine for the following reasons: # 1. No client case usually does not happen. # 2. We are running the watchdog loop in a separate daemon # thread, which will not block the process to stop. try: fd = open(self._file_path) except Exception: logger.exception("Could not open the FileTimerServer pipe") raise
with fd: self._is_client_started = True while not self._stop_signaled: try: run_once = self._run_once self._run_watchdog(fd) if run_once: break self._last_progress_time = int(time.time()) except Exception: logger.exception("Error running watchdog")
def _run_watchdog(self, fd: io.TextIOWrapper) -> None: timer_requests = self._get_requests(fd, self._max_interval) self.register_timers(timer_requests) now = time.time() reaped_worker_pids = set() kill_process = False reap_signal = 0
all_expired_timers = self.get_expired_timers(now) log_debug_info_for_expired_timers( self._run_id, { pid: [expired_timer.to_json() for expired_timer in expired_timers] for pid, expired_timers in all_expired_timers.items() }, )
for worker_pid, expired_timers in all_expired_timers.items(): logger.info( "Reaping worker_pid=[%s]. Expired timers: %s", worker_pid, self._get_scopes(expired_timers), ) reaped_worker_pids.add(worker_pid) # In case we have multiple expired timers, we find the first timer # with a valid signal (>0) in the expiration time order. expired_timers.sort(key=lambda timer: timer.expiration_time) signal = 0 expired_timer = None for timer in expired_timers: self._log_event("timer expired", timer) if timer.signal > 0: signal = timer.signal expired_timer = timer break if signal <= 0: logger.info( "No signal specified with worker=[%s]. Do not reap it.", worker_pid ) continue if self._reap_worker(worker_pid, signal): logger.info( "Successfully reaped worker=[%s] with signal=%s", worker_pid, signal ) self._log_event("kill worker process", expired_timer) kill_process = True reap_signal = signal else: logger.error( "Error reaping worker=[%s]. Will retry on next watchdog.", worker_pid, ) if kill_process and reap_signal > 0: logger.info( "Terminating the server process=[%s] because of expired timers", os.getpid(), ) self._reap_worker(os.getpid(), reap_signal)
self.clear_timers(reaped_worker_pids)
def _get_scopes(self, timer_requests: list[FileTimerRequest]) -> list[str]: return [r.scope_id for r in timer_requests]
def _get_requests( self, fd: io.TextIOWrapper, max_interval: float ) -> list[FileTimerRequest]: start = time.time() requests = [] while not self._stop_signaled or self._run_once: # For named pipe, readline() is blocking when at least one writer opens. # It returns only when flush() is called at the writer side. # Note that flush() is automatically called inside close(). # After the last writer closes, readline() is not blocking. # It will return an empty string when it's at end-of-file. # Since the client side always opens the pipe, writes a message and closes # the pipe immediately, the readline() call below is not blocking for long. json_request = fd.readline() if len(json_request) == 0: if self._run_once: break time.sleep(min(max_interval, 1)) else: request = json.loads(json_request) pid = request["pid"] scope_id = request["scope_id"] expiration_time = request["expiration_time"] signal = request["signal"] requests.append( FileTimerRequest( worker_pid=pid, scope_id=scope_id, expiration_time=expiration_time, signal=signal, ) ) now = time.time() if now - start > max_interval: break return requests
def register_timers(self, timer_requests: list[FileTimerRequest]) -> None: for request in timer_requests: pid = request.worker_pid scope_id = request.scope_id expiration_time = request.expiration_time self._request_count += 1
key = (pid, scope_id) # negative expiration is a proxy for a release call if expiration_time < 0: if key in self._timers: del self._timers[key] else: self._timers[key] = request
def clear_timers(self, worker_pids: set[int]) -> None: for pid, scope_id in list(self._timers.keys()): if pid in worker_pids or not FileTimerServer.is_process_running(pid): del self._timers[(pid, scope_id)]
def get_expired_timers(self, deadline: float) -> dict[int, list[FileTimerRequest]]: # pid -> [timer_requests...] expired_timers: dict[int, list[FileTimerRequest]] = {} for request in self._timers.values(): if request.expiration_time <= deadline: expired_scopes = expired_timers.setdefault(request.worker_pid, []) expired_scopes.append(request) return expired_timers
def _reap_worker(self, worker_pid: int, signal: int) -> bool: try: os.kill(worker_pid, signal) return True except ProcessLookupError: logger.info("Process with pid=%s does not exist. Skipping", worker_pid) return True except Exception: logger.exception("Error terminating pid=%s", worker_pid) return False
def get_last_progress_time(self) -> int: return self._last_progress_time if self._is_client_started else int(time.time())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# mypy: allow-untyped-defs# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.import loggingimport multiprocessing as mpimport osimport signalimport timefrom queue import Emptyfrom typing import Any
from .api import RequestQueue, TimerClient, TimerRequest, TimerServer
__all__ = ["LocalTimerClient", "MultiprocessingRequestQueue", "LocalTimerServer"]
logger = logging.getLogger(__name__)
class LocalTimerClient(TimerClient): """ Client side of ``LocalTimerServer``. This client is meant to be used on the same host that the ``LocalTimerServer`` is running on and uses pid to uniquely identify a worker. This is particularly useful in situations where one spawns a subprocess (trainer) per GPU on a host with multiple GPU devices. """
def __init__(self, mp_queue): super().__init__() self._mp_queue = mp_queue
def acquire(self, scope_id, expiration_time): pid = os.getpid() acquire_request = TimerRequest(pid, scope_id, expiration_time) self._mp_queue.put(acquire_request)
def release(self, scope_id): pid = os.getpid() release_request = TimerRequest(pid, scope_id, -1) self._mp_queue.put(release_request)
class MultiprocessingRequestQueue(RequestQueue): """ A ``RequestQueue`` backed by python ``multiprocessing.Queue`` """
def __init__(self, mp_queue: mp.Queue): super().__init__() self._mp_queue = mp_queue
def size(self) -> int: return self._mp_queue.qsize()
def get(self, size, timeout: float) -> list[TimerRequest]: requests = [] wait = timeout for _ in range(0, size): start = time.time()
try: r = self._mp_queue.get(block=True, timeout=wait) except Empty: break
requests.append(r) wait = wait - (time.time() - start) if wait <= 0: break
return requests
class LocalTimerServer(TimerServer): """ Server that works with ``LocalTimerClient``. Clients are expected to be subprocesses to the parent process that is running this server. Each host in the job is expected to start its own timer server locally and each server instance manages timers for local workers (running on processes on the same host). """
def __init__( self, mp_queue: mp.Queue, max_interval: float = 60, daemon: bool = True ): super().__init__(MultiprocessingRequestQueue(mp_queue), max_interval, daemon) self._timers: dict[tuple[Any, str], TimerRequest] = {}
def register_timers(self, timer_requests: list[TimerRequest]) -> None: for request in timer_requests: pid = request.worker_id scope_id = request.scope_id expiration_time = request.expiration_time
# negative expiration is a proxy for a release call if expiration_time < 0: self._timers.pop((pid, scope_id), None) else: self._timers[(pid, scope_id)] = request
def clear_timers(self, worker_ids: set[int]) -> None: for pid, scope_id in list(self._timers.keys()): if pid in worker_ids: self._timers.pop((pid, scope_id))
def get_expired_timers(self, deadline: float) -> dict[Any, list[TimerRequest]]: # pid -> [timer_requests...] expired_timers: dict[Any, list[TimerRequest]] = {} for request in self._timers.values(): if request.expiration_time <= deadline: expired_scopes = expired_timers.setdefault(request.worker_id, []) expired_scopes.append(request) return expired_timers
def _reap_worker(self, worker_id: int) -> bool: try: os.kill(worker_id, signal.SIGKILL) return True except ProcessLookupError: logger.info("Process with pid=%s does not exist. Skipping", worker_id) return True except Exception: logger.exception("Error terminating pid=%s", worker_id) return False123456789#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
from .api import get_env_variable_or_raise, get_socket_with_port, macros # noqa: F4011234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
import osimport socketfrom string import Templatefrom typing import Any
def get_env_variable_or_raise(env_name: str) -> str: r""" Tries to retrieve environment variable. Raises ``ValueError`` if no environment variable found.
Args: env_name (str): Name of the env variable """ value = os.environ.get(env_name, None) if value is None: msg = f"Environment variable {env_name} expected, but not set" raise ValueError(msg) return value
def get_socket_with_port() -> socket.socket: addrs = socket.getaddrinfo( host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM ) for addr in addrs: family, type, proto, _, _ = addr s = socket.socket(family, type, proto) try: s.bind(("localhost", 0)) s.listen(0) return s except OSError: s.close() raise RuntimeError("Failed to create a socket")
class macros: """ Defines simple macros for caffe2.distributed.launch cmd args substitution """
local_rank = "${local_rank}"
@staticmethod def substitute(args: list[Any], local_rank: str) -> list[str]: args_sub = [] for arg in args: if isinstance(arg, str): sub = Template(arg).safe_substitute(local_rank=local_rank) args_sub.append(sub) else: args_sub.append(arg) return args_sub12345678910#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
from .cycling_iterator import CyclingIterator # noqa: F401from .elastic_distributed_sampler import ElasticDistributedSampler # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657#!/usr/bin/env python3
from collections.abc import Iteratorfrom typing import Callable, TypeVarfrom typing_extensions import Self
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
_T = TypeVar("_T")
__all__ = ["CyclingIterator"]
class CyclingIterator(Iterator[_T]): """ An iterator decorator that cycles through the underlying iterator "n" times. Useful to "unroll" the dataset across multiple training epochs.
The generator function is called as ``generator_fn(epoch)`` to obtain the underlying iterator, where ``epoch`` is a number less than or equal to ``n`` representing the ``k``th cycle
For example if ``generator_fn`` always returns ``[1,2,3]`` then ``CyclingIterator(n=2, generator_fn)`` will iterate through ``[1,2,3,1,2,3]`` """
def __init__( self, n: int, generator_fn: Callable[[int], Iterator[_T]], start_epoch: int = 0, ): self._n = n self._epoch = start_epoch self._generator_fn = generator_fn self._iter = generator_fn(self._epoch)
def __iter__(self) -> Self: return self
def __next__(self) -> _T: try: return next(self._iter) except StopIteration as eod: # eod == end of data if self._epoch < self._n - 1: self._epoch += 1 self._iter = self._generator_fn(self._epoch) return self.__next__() else: raise eod1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
import mathfrom collections.abc import Iterator, Sizedfrom typing import cast, Optional, TypeVar
import torchfrom torch.utils.data import Datasetfrom torch.utils.data.distributed import DistributedSampler
T = TypeVar("T")
__all__ = ["ElasticDistributedSampler"]
class ElasticDistributedSampler(DistributedSampler[T]): """ Sampler that restricts data loading to a subset of the dataset for elastic training.
It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the original dataset that is exclusive to it.
.. note:: Dataset is assumed to be of constant size.
Args: dataset: Dataset used for sampling. num_replicas (optional): Number of processes participating in distributed training. rank (optional): Rank of the current process within num_replicas. start_index (optional): Which index of the dataset to start sampling from """
def __init__( self, dataset: Dataset[T], num_replicas: Optional[int] = None, rank: Optional[int] = None, start_index: int = 0, ): super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank) if not isinstance(dataset, Sized): raise TypeError("Dataset must be an instance of collections.abc.Sized")
# Cast to Sized for mypy sized_dataset = cast(Sized, dataset)
if start_index >= len(sized_dataset): raise ValueError( f"Start index {start_index} should be less than dataset size {len(sized_dataset)}" )
self.start_index = start_index sized_dataset = cast(Sized, self.dataset) self.num_samples = int( math.ceil(float(len(sized_dataset) - self.start_index) / self.num_replicas) ) self.total_size = self.num_samples * self.num_replicas
def __iter__(self) -> Iterator[T]: # deterministically shuffle based on epoch g = torch.Generator() g.manual_seed(self.epoch) sized_dataset = cast(Sized, self.dataset) indices = ( torch.randperm(len(sized_dataset) - self.start_index, generator=g) .add(self.start_index) .tolist() )
# add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] assert len(indices) == self.total_size
# subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples
return iter(indices)
def __len__(self) -> int: return self.num_samples123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184#!/usr/bin/env python3# mypy: allow-untyped-defs
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.import datetimeimport osimport socketfrom contextlib import closingfrom typing import Optional
import torch.distributed as distfrom torch.distributed.elastic.utils.logging import get_loggerfrom torch.distributed.elastic.utils.store import barrier
__all__ = ["create_c10d_store", "get_free_port", "get_socket_with_port"]
logger = get_logger(__name__)
_ADDRESS_IN_USE = "Address already in use"_SOCKET_TIMEOUT = "Socket Timeout"
_TCP_STORE_INIT = "_tcp_store/num_members"
def create_c10d_store( is_server: bool, server_addr: str, server_port: int = -1, world_size: int = 1, timeout: float = (60 * 10), # 10 min wait_for_workers: bool = True, retries=3, use_libuv: Optional[bool] = None,): if use_libuv is not None: logger.warning( "argument use_libuv is deprecated and ignored. Set USE_LIBUV environment " 'variable to "0" to disable libuv, or "1" to enable it. If the env var ' "is not set, libuv will be used by default." )
# check os.environ for use_libuv use_libuv = os.environ.get("USE_LIBUV", "1") == "1" # libuv is the default option
if server_port == -1 and world_size > 1: raise ValueError( f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}" )
if server_port != -1: logger.info("sever_port: %s, specified, ignoring retries", server_port)
# only retry when server_port is NOT static attempt = retries if server_port == -1 else 1 while True: if server_port != -1: port = server_port else: port = get_free_port()
logger.info( "Creating c10d store on %s:%s\n" " world_size : %s\n" " is_server : %s\n" " timeout(sec): %s\n" " use_libuv : %s\n", server_addr, port, world_size, is_server, timeout, use_libuv, )
try: store = dist.TCPStore( host_name=server_addr, port=port, world_size=world_size, is_master=is_server, timeout=datetime.timedelta(seconds=timeout), wait_for_workers=wait_for_workers, use_libuv=use_libuv, ) # skips full rank check when we don't have to wait for all workers if wait_for_workers: _check_full_rank(store, world_size, timeout=timeout) logger.info("Successfully created c10d store") return store except RuntimeError as e: # this is brittle, but the underlying exception type is not properly pybinded # so we parse the error msg for now, interestingly this is how torch itself # detects timeouts and port conflicts in their own unittests # see - caffe2/torch/testing/_internal/common_utils.py # TODO properly map the exceptions in pybind (c10d/init.cpp) if str(e) == _ADDRESS_IN_USE: # this will only happen on the server if attempt < retries: logger.warning( "port: %s already in use, attempt: [%s/%s]", port, attempt, retries, ) attempt += 1 else: raise RuntimeError( f"on {server_addr}, port: {port} already in use" ) from e else: raise
def _check_full_rank(store, world_size, timeout): try: barrier(store, world_size, key_prefix=_TCP_STORE_INIT, barrier_timeout=timeout) except RuntimeError as e: if str(e) == _SOCKET_TIMEOUT: raise TimeoutError( f"timed out waiting for all {world_size} members to join" ) from e else: raise
def get_free_port(): """ Returns an unused port on localhost.
This function finds an unused port on localhost by opening to socket to bind to a port and then closing it.
Returns: int: an unused port on localhost
Example: >>> # xdoctest: +SKIP("Nondeterministic") >>> get_free_port() 63976
.. note:: The port returned by :func:`get_free_port` is not reserved and may be taken by another process after this function returns. """ sock = get_socket_with_port() with closing(sock): return sock.getsockname()[1]
def get_socket_with_port() -> socket.socket: """ Returns a free port on localhost that is "reserved" by binding a temporary socket on it. Close the socket before passing the port to the entity that requires it. Usage example
::
sock = _get_socket_with_port() with closing(sock): port = sock.getsockname()[1] sock.close() # there is still a race-condition that some other process # may grab this port before func() runs func(port) """
addrs = socket.getaddrinfo( host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM ) for addr in addrs: family, type, proto, _, _ = addr s = socket.socket(family, type, proto) try: s.bind(("localhost", 0)) s.listen(0) return s except OSError as e: s.close() logger.warning("Socket creation attempt failed.", exc_info=e) raise RuntimeError("Failed to create a socket")1234567891011121314#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
def get_log_level() -> str: """ Return default log level for pytorch. """ return "WARNING"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
import inspectimport loggingimport osimport warningsfrom typing import Optional
from torch.distributed.elastic.utils.log_level import get_log_level
def get_logger(name: Optional[str] = None) -> logging.Logger: """ Util function to set up a simple logger that writes into stderr. The loglevel is fetched from the LOGLEVEL env. variable or WARNING as default. The function will use the module name of the caller if no name is provided.
Args: name: Name of the logger. If no name provided, the name will be derived from the call stack. """
# Derive the name of the caller, if none provided # Use depth=2 since this function takes up one level in the call stack return _setup_logger(name or _derive_module_name(depth=2))
def _setup_logger(name: Optional[str] = None) -> logging.Logger: logger = logging.getLogger(name) logger.setLevel(os.environ.get("LOGLEVEL", get_log_level())) return logger
def _derive_module_name(depth: int = 1) -> Optional[str]: """ Derives the name of the caller module from the stack frames.
Args: depth: The position of the frame in the stack. """ try: stack = inspect.stack() assert depth < len(stack) # FrameInfo is just a named tuple: (frame, filename, lineno, function, code_context, index) frame_info = stack[depth]
module = inspect.getmodule(frame_info[0]) if module: module_name = module.__name__ else: # inspect.getmodule(frame_info[0]) does NOT work (returns None) in # binaries built with @mode/opt # return the filename (minus the .py extension) as modulename filename = frame_info[1] module_name = os.path.splitext(os.path.basename(filename))[0] return module_name except Exception as e: warnings.warn( f"Error deriving logger module name, using <None>. Exception: {e}", RuntimeWarning, ) return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226#!/usr/bin/env python3# mypy: allow-untyped-defs
# Copyright (c) Facebook, Inc. and its affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
from collections.abc import Iterablefrom contextlib import contextmanagerfrom datetime import timedeltafrom typing import Callable, Optional
import torch
DistStoreError = torch._C._DistStoreError
_NUM_MEMBERS = "/num_members"_LAST_MEMBER_CHECKIN = "/last_member"_TRACE = "/TRACE"_TRACING_GATE = "/TRACING_GATE"_MAX_TRACE_MISSING_RANKS = 16
__all__ = ["store_timeout", "get_all", "synchronize", "barrier"]
@contextmanagerdef store_timeout(store, timeout: float): """ This sets the timeout and then restores the old timeout when the context manager exits.
Args: store: the store to set the timeout on timeout: the timeout to set """
old_timeout = store.timeout store.set_timeout(timedelta(seconds=timeout)) yield store.set_timeout(old_timeout)
def get_all(store, rank: int, prefix: str, world_size: int): r""" Given a store and a prefix, the method goes through the array of keys of the following format: ``{prefix}{idx}``, where idx is in a range from 0 to size, and tries to retrieve the data.
The Rank0 process waits at the end to make sure all other processes finished the procedure before exiting.
Usage
::
values = get_all(store, "torchelastic/data", 3) value1 = values[0] # retrieves the data for key torchelastic/data0 value2 = values[1] # retrieves the data for key torchelastic/data1 value3 = values[2] # retrieves the data for key torchelastic/data2
""" data_arr = store.multi_get([f"{prefix}{idx}" for idx in range(world_size)])
barrier_key = _barrier_nonblocking( store=store, world_size=world_size, key_prefix=f"{prefix}/finished", ) if rank == 0: # Rank0 runs the TCPStore daemon, as a result it needs to exit last. # Otherwise, the barrier may timeout if rank0 process finished the work # before other processes finished `get_all` method store.wait([barrier_key])
return data_arr
def synchronize( store, data: bytes, rank: int, world_size: int, key_prefix: str, timeout: float = 300,) -> list[bytes]: """ Synchronizes ``world_size`` agents between each other using the underlying c10d store. The ``data`` will be available on each of the agents.
Note: The data on the path is not deleted, as a result there can be stale data if you use the same key_prefix twice.
Time complexity: O(N) per worker, O(N^2) globally. """ with store_timeout(store, timeout): store.set(f"{key_prefix}{rank}", data) agent_data = get_all(store, rank, key_prefix, world_size) return agent_data
def _try_detecting_missing_ranks( store, world_size: int, key_prefix: str, rank: int, rank_decoder: Callable[[int], str], trace_timeout: float,) -> Optional[Iterable[str]]: store.set(f"{key_prefix}{rank}{_TRACE}", "<val_ignored>")
def _find_missing_ranks(): missing_rank_info = set() ranks_missing = 0 for i in range(1, world_size): # reduce noise, assuming in general 8 ranks per node # It is valuable to know that 1 or >1 nodes have timed-out. if ranks_missing >= _MAX_TRACE_MISSING_RANKS: break try: if ranks_missing == 0: store.wait( [f"{key_prefix}{i}{_TRACE}"], timedelta(seconds=trace_timeout) ) else: # use a shortest timeout, some ranks have failed to check-in store.wait([f"{key_prefix}{i}{_TRACE}"], timedelta(milliseconds=1)) except DistStoreError: ranks_missing += 1 missing_rank_info.add(rank_decoder(i)) return missing_rank_info
def _checkin(): try: store.wait([f"{key_prefix}{_TRACING_GATE}"]) return [f"[<check rank 0 ({rank_decoder(0)}) for missing rank info>]"] except DistStoreError: # in case rank0 is the source of the timeout, original exception will be raised return None
if rank == 0: missing_rank_info = _find_missing_ranks() store.set(f"{key_prefix}{_TRACING_GATE}", "<val_ignored>") return missing_rank_info else: return _checkin()
def _barrier_nonblocking(store, world_size: int, key_prefix: str) -> str: """ Does all the non-blocking operations for a barrier and returns the final key that can be waited on. """ num_members_key = key_prefix + _NUM_MEMBERS last_member_key = key_prefix + _LAST_MEMBER_CHECKIN
idx = store.add(num_members_key, 1) if idx == world_size: store.set(last_member_key, "<val_ignored>")
return last_member_key
def barrier( store, world_size: int, key_prefix: str, barrier_timeout: float = 300, rank: Optional[int] = None, rank_tracing_decoder: Optional[Callable[[int], str]] = None, trace_timeout: float = 10,) -> None: """ A global lock between agents. This will pause all workers until at least ``world_size`` workers respond.
This uses a fast incrementing index to assign waiting ranks and a success flag set by the last worker.
Time complexity: O(1) per worker, O(N) globally.
Optionally, passing rank will enable tracing of missing ranks on timeouts. `rank_tracing_decoder` lambda arg can be used to convert rank data into a more meaningful information at an app level (e.g. hostname).
Note: Since the data is not removed from the store, the barrier can be used once per unique ``key_prefix``. """
if rank is None: assert rank_tracing_decoder is None, "Tracing requires rank information"
with store_timeout(store, barrier_timeout): last_member_key = _barrier_nonblocking( store=store, world_size=world_size, key_prefix=key_prefix ) try: store.wait([last_member_key]) except DistStoreError as e: if rank is None: raise e else: missing_ranks = _try_detecting_missing_ranks( store, world_size, key_prefix, rank, rank_tracing_decoder or (lambda x: str(x)), trace_timeout, ) if missing_ranks is not None: raise DistStoreError( "Timed out waiting on barrier on " "rank {}, for key prefix: {} (world_size={}, missing_ranks={}, timeout={})".format( rank, key_prefix, world_size, f"[{', '.join(missing_ranks)}]", barrier_timeout, ) ) from None else: raise e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566from ._flat_param import FlatParameter as FlatParameterfrom ._fully_shard import ( CPUOffloadPolicy, FSDPModule, fully_shard, MixedPrecisionPolicy, OffloadPolicy, register_fsdp_forward_method, UnshardHandle,)from .fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullOptimStateDictConfig, FullStateDictConfig, FullyShardedDataParallel, LocalOptimStateDictConfig, LocalStateDictConfig, MixedPrecision, OptimStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictConfig, StateDictSettings, StateDictType,)
__all__ = [ # FSDP1 "BackwardPrefetch", "CPUOffload", "FullOptimStateDictConfig", "FullStateDictConfig", "FullyShardedDataParallel", "LocalOptimStateDictConfig", "LocalStateDictConfig", "MixedPrecision", "OptimStateDictConfig", "OptimStateKeyType", "ShardedOptimStateDictConfig", "ShardedStateDictConfig", "ShardingStrategy", "StateDictConfig", "StateDictSettings", "StateDictType", # FSDP2 "CPUOffloadPolicy", "FSDPModule", "fully_shard", "MixedPrecisionPolicy", "OffloadPolicy", "register_fsdp_forward_method", "UnshardHandle",]
# Set namespace for exposed private namesCPUOffloadPolicy.__module__ = "torch.distributed.fsdp"FSDPModule.__module__ = "torch.distributed.fsdp"fully_shard.__module__ = "torch.distributed.fsdp"MixedPrecisionPolicy.__module__ = "torch.distributed.fsdp"OffloadPolicy.__module__ = "torch.distributed.fsdp"register_fsdp_forward_method.__module__ = "torch.distributed.fsdp"UnshardHandle.__module__ = "torch.distributed.fsdp"123version https://git-lfs.github.com/spec/v1oid sha256:66bf006c46374b6e50a305862d2144ca16d76f636f5b33f7f2bf3f4dff4b1971size 120052123version https://git-lfs.github.com/spec/v1oid sha256:dec5da21d48e1ac508b6d023007524d8485fe227d43a5230d4dde0c24286311fsize 106898123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546# mypy: allow-untyped-defs"""This file includes private common utilities for FSDP."""
import loggingimport tracebackimport warningsimport weakreffrom collections.abc import Generator, Iterablefrom enum import auto, Enumfrom functools import partialfrom itertools import chainfrom typing import Any, Callable, cast, no_type_check, Optional, TYPE_CHECKING
import torchimport torch.distributed as distimport torch.distributed.fsdp._flat_param as flat_param_fileimport torch.nn as nnfrom torch.distributed._composable_state import _get_module_state, _Statefrom torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_PREFIX,)from torch.distributed.utils import _apply_to_tensorsfrom torch.utils._mode_utils import no_dispatch
from .api import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateDictConfig, ShardingStrategy, StateDictConfig, StateDictType,)
if TYPE_CHECKING: from torch.distributed.device_mesh import DeviceMesh from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
from ._flat_param import FlatParamHandle
FSDP_WRAPPED_MODULE = "_fsdp_wrapped_module"FSDP_PREFIX = FSDP_WRAPPED_MODULE + "."FSDP_FLATTENED = "_fsdp_flattened"
# Save a global mapping from module to its input tensor dtype to be populated# during the forward pre-hook and consumed in the forward post-hook when# overriding a module's mixed precision# NOTE: We currently take the last input tensor's dtype in the case of multiple# floating-point input tensors, which may be incorrect. However, since there is# not a 1:1 correspondence between input and output tensors, we must use *some*# heuristic like this to predict the desired output dtype._MODULE_TO_INP_DTYPE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
class _FSDPDeviceHandle: """ This is a simple abstraction for FSDP computing devices, which enables custom backends that implement CUDA-like semantics to be integrated with FSDP. """
def __init__(self, device: torch.device, backend: Any = None): if backend is None: try: self.__backend = getattr(torch, device.type) self.__device = device except AttributeError as exc: raise AttributeError( f"Device '{device}' does not have a corresponding backend registered as 'torch.{device.type}'." ) from exc else: self.__backend = backend
@classmethod def from_device(cls, device: torch.device) -> "_FSDPDeviceHandle": """ Return a device handle corresponding to the device, and through this handle, operations with the same semantics as CUDA can be performed on the device. Just return torch.cuda if the device is cuda to make attribute-access faster. Custom backend must first register a module with the same name with {device.type} on torch. """ if device.type == "cuda": return cast(_FSDPDeviceHandle, torch.cuda) elif device.type == "mtia": return cast(_FSDPDeviceHandle, torch.mtia) return cls(device)
def __getattr__(self, name: str, /) -> Any: try: return getattr(self.__backend, name) except AttributeError as exc: raise AttributeError( f"Custom backend '{self.__device.type}' not implement 'torch.{self.__device.type}.{name}'" ) from exc
class _UninitializedDeviceHandle(_FSDPDeviceHandle): def __init__(self) -> None: pass
def __getattribute__(self, name: str, /) -> Any: raise RuntimeError("Trying to use an uninitialized device handle.")
class _FSDPState(_State): def __init__(self) -> None: # TODO: Move all the attributes to this class to enable typing for # FSDP/fully_shard. self._ignored_modules: set[nn.Module] = set() self._ignored_params: set[nn.Parameter] = set() # Buffer names are cleaned (without wrapper prefixes) self._ignored_buffer_names: set[str] = set() self.process_group: Optional[dist.ProcessGroup] = None self.rank: int = -1 self.world_size: int = -1 self._device_mesh: Optional[DeviceMesh] = None self.sharding_strategy = ShardingStrategy.FULL_SHARD self._use_orig_params: bool = False self.training_state = TrainingState.IDLE self._unshard_params_ctx: dict[nn.Module, Generator] = {} self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT self._state_dict_config: StateDictConfig = FullStateDictConfig() self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig() self._is_root: Optional[bool] = None self._handle: Optional[flat_param_file.FlatParamHandle] = None self._fully_sharded_module_to_handle: dict[ nn.Module, Optional[flat_param_file.FlatParamHandle] ] = {} self.compute_device: Optional[torch.device] = None self._gradient_predivide_factor: int = 0 self._gradient_postdivide_factor: int = 0 self._comm_hook: Optional[Callable] = None self._comm_hook_state: Optional[Any] = None self._unshard_event: Optional[torch.Event] = None # Abstract device handle for fsdp compute device. For now, # the compute device must implement cuda semantics used by fsdp self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle() # All following attributes should only be used for root states: # Save these static lists to avoid the repeated tree traversals self._all_fsdp_states: list[_FSDPState] = [] self._all_handles: list[flat_param_file.FlatParamHandle] = [] self._fsdp_extension: Optional[FSDPExtensions] = None
def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]: state = _get_module_state(module) if state is None or not isinstance(state, _FSDPState): return None return state
def _get_module_fsdp_state_if_fully_sharded_module( module: nn.Module,) -> Optional[_FSDPState]: state = _get_module_fsdp_state(module) if state is None: return None if state == module: # FullyShardedDataParallel module case. return state if module in state._fully_sharded_module_to_handle: # fully_shard case. return state return None
class TrainingState(Enum): """ An enum that indicates the state of a ``FullyShardedDataParallel` instance. """
IDLE = auto() FORWARD_BACKWARD = auto() SUMMON_FULL_PARAMS = auto()
class HandleTrainingState(Enum): """ An enum that indicates the state of a ``FlatParamHandle`. """
IDLE = auto() FORWARD = auto() BACKWARD_PRE = auto() BACKWARD_POST = auto() SUMMON_FULL_PARAMS = auto()
def _is_composable(state: _FSDPState): # TODO: This is a temporary hack for differentiate between code paths. return not isinstance(state, nn.Module)
@no_type_checkdef _module_handle(state: _FSDPState, module: nn.Module) -> Optional["FlatParamHandle"]: """ Returns the ``FlatParamHandle`` s corresponding to ``module``. This is the handle that contains some parameter in ``module``. """ if _is_composable(state): # A valid FSDP state may have no managed parameters and hence no # handles, meaning no entry in `_fully_sharded_module_to_handles` if state._handle is None: return None assert module in state._fully_sharded_module_to_handle, ( f"Expects a fully sharded module but got {module} on rank {state.rank}" ) return state._fully_sharded_module_to_handle[module] else: # NOTE: This assumes `module` is a `FullyShardedDataParallel` instance. return module._handle
@no_type_checkdef _has_fsdp_params(state: _FSDPState, module: nn.Module) -> bool: """Returns if ``module`` has parameters managed by FSDP.""" return _module_handle(state, module) is not None
def _get_sharding_strategy(handle): """ Returns the sharding strategy of the handle. """ return handle._sharding_strategy if handle else None
def clean_tensor_name(tensor_name: str) -> str: """ Cleans the parameter or buffer name by removing any module wrapper prefixes. """ tensor_name = tensor_name.replace(FSDP_PREFIX, "") # TODO: Explicitly replacing the checkpoint wrapper prefix is not ideal as # it couples `CheckpointWrapper` and FSDP and also does not scale for more # module wrappers. tensor_name = tensor_name.replace(_CHECKPOINT_PREFIX, "") return tensor_name
def _set_fsdp_flattened(tensor: torch.Tensor) -> None: """ Sets an attribute on ``tensor`` to mark it as flattened by FSDP. This is to avoid re-flattening it during nested construction. """ setattr(tensor, FSDP_FLATTENED, True)
def _is_fsdp_flattened(tensor: torch.Tensor) -> bool: """Returns if ``tensor`` has been marked as flattened by FSDP.""" return getattr(tensor, FSDP_FLATTENED, False)
def _named_parameters_with_duplicates( module: nn.Module, **kwargs: Any) -> list[tuple[str, nn.Parameter]]: """ This API is required as some modules overwrite `named_parameters()` but do not support `remove_duplicate`. """ assert "remove_duplicate" not in kwargs, ( "_named_parameters_with_duplicates cannot be used with `remove_duplicate` argument." ) kwargs["remove_duplicate"] = False try: ret = list(module.named_parameters(**kwargs)) except AssertionError: kwargs.pop("remove_duplicate") ret = list(module.named_parameters(**kwargs)) return ret
def _get_param_to_fqns( model: torch.nn.Module, dedup_shared_params: bool = True,) -> dict[nn.Parameter, list[str]]: """ Constructs a mapping from parameter to a list of its \"canonical\" FQNs. Here, we use canonical to mean the fully-qualified name assigned to the parameter based on its position in the original nn.Module hierarchy before any wrapper or parallelism has been applied to it. This is in contrast to FQNs that may be generated after parallelisms or wrappers have been applied to the model.
Each normal parameter maps to a singleton list containing its FQN, while each ``FlatParameter`` maps to a list of its original parameter FQNs, which may have length greater than one. All FQNs are prefixed starting from ``model``.
In the case where FSDP was applied with ``use_orig_params=True``, there should be no ``FlatParameter`` s registered to the model's modules and this mapping will only contain mappings from ``nn.Parameter`` s to singleton FQN lists.
It is only in the case where FSDP was applied with ``use_orig_params=False`` where a ``FlatParameter`` will be registered in place of the original parameters and there will be mappings from each ``FlatParameter`` to lists of FQNs corresponding to the original parameters.
Args: model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance). dedup_shared_params (bool): For shared parameters, if ``True``, only includes the FQNs corresponding to the first encounter of the shared parameter in the module traversal; if ``False``, then includes the FQNs across all encounters. (Default: ``True``) """
def module_fn(module, prefix, tree_level, param_to_fqns): for param_name, param in _named_parameters_with_duplicates( module, recurse=False ): local_fqns = ( param._fqns if isinstance(param, flat_param_file.FlatParameter) else [param_name] ) # prefixed from `module` global_fqns = [ clean_tensor_name(prefix + name) for name in local_fqns ] # prefixed from the top level `model` (i.e. including `prefix`) is_shared_param = param in param_to_fqns if not is_shared_param: param_to_fqns[param] = global_fqns else: if isinstance(param, flat_param_file.FlatParameter): # DMP overwrites `named_parameters` and skip (advance to # the next child module) the wrapped_module (e.g., # _dmp_wrapped_module and _fsdp_wrapped_module). When a user # calls `named_child` to traverse the module recursively and # calls `named_parameters` with `recurse=False`, parameters # will be traversed more than once. # This hack is specified designed for DMP + FSDP. We # overwrite the flat_parameters traversal result to only obtain # the last one, which happens to be the correct one. # # TODO: Remove this hack once DMP + FSDP is not supported. warnings.warn( "FlatParameter is being traversed more than once. " "This case should only happen when using " "DistributedModelParallel with FullyShardedDataParallel." ) param_to_fqns[param] = global_fqns elif not dedup_shared_params: param_to_fqns[param].extend(global_fqns)
def return_fn(param_to_fqns): return param_to_fqns
param_to_unflat_param_names: dict[torch.nn.Parameter, list[str]] = {} return _apply_to_modules( model, module_fn, return_fn, [key for key, _ in _named_parameters_with_duplicates(model)], param_to_unflat_param_names, )
@no_type_checkdef _log_post_backward_hook( state: _FSDPState, handle: "FlatParamHandle", logger: logging.Logger) -> None: # Under TORCH_DISTRIBUTED_DEBUG=INFO, log the module names this hook fires for. # Below logging of module names this post-bwd hook fires for can help debug certain # cases where hooks don't fire, such as under certain activation checkpoint configs. if state._use_orig_params and handle._debug_level == dist.DebugLevel.INFO: param_fqns = _get_handle_fqns_from_root(state, handle) logger.warning("FSDP firing post-backward hooks for parameters %s", param_fqns)
@no_type_checkdef _get_handle_fqns_from_root( state: _FSDPState, handle: "FlatParamHandle") -> Optional[list[str]]: if handle is None: return None param_to_fqn = state._exec_order_data.param_to_fqn handle_params = handle.flat_param._params # only populated for use_orig_params param_fqns = [*chain.from_iterable(param_to_fqn[p] for p in handle_params)] return param_fqns
def _apply_to_modules( root_module: torch.nn.Module, module_fn: Callable, return_fn: Callable, filter_fqns: Optional[list[str]] = None, *args, **kwargs,): """ Performs a pre-order traversal of the modules in the hierarchy rooted at ``root_module``, applying ``module_fn`` at each module and finally returning a value using ``return_fn``. The traversal constructs the full module prefix name (e.g. "module.submodule." just like in model state dict) and makes that available to ``module_fn``.
``filter_fqns`` is used because some module may have its own prefix similar to ``FullyShardedDataParallel`` and the ``named_parameters()`` is overwritten to remove the prefix. """
def f(module: torch.nn.Module, prefix: str, tree_level: int, *args, **kwargs): # Call the module function before recursing over children (pre-order) module_fn(module, prefix, tree_level, *args, **kwargs) for submodule_name, submodule in module.named_children(): if submodule is None: continue new_prefix = prefix + submodule_name + "." new_tree_level = tree_level + 1 if filter_fqns is not None: for fqn in filter_fqns: if fqn.startswith(new_prefix): break else: # DMP's named_parameter() will mess up the traversal with # ``named_children`` + `named_parameter(recurse=False)``. # This hack is a must to make the traversal work. # TODO: Remove this hack once DMP + FSDP is not supported. # It turns out that recursive wrapping may trigger this as # well. if ( submodule_name == "_fsdp_wrapped_module" or submodule_name == "_dmp_wrapped_module" ): new_prefix = prefix elif submodule_name == "module": new_prefix = prefix f(submodule, new_prefix, new_tree_level, *args, **kwargs)
f(root_module, "", 0, *args, **kwargs) return return_fn(*args, **kwargs)
@no_type_checkdef _assert_in_training_states( state: _FSDPState, training_states: list[TrainingState],) -> None: """Asserts that FSDP is in the states ``_training_states``.""" # Raise a `ValueError` instead of using `assert` to ensure that these # logical assertions run even if `assert`s are disabled if state.training_state not in training_states: msg = ( f"expected to be in states {training_states} but current state is " f"{state.training_state}" ) # Print the error on rank 0 in case this is called in the backward pass if state.rank == 0: if isinstance(state, nn.Module): print(f"Asserting FSDP instance is: {state}") print(f"ERROR: {msg}") traceback.print_stack() raise ValueError(msg)
def _get_root_modules(modules: set[nn.Module]) -> set[nn.Module]: """ Returns: Set[nn.Module]: The subset of ``modules`` that are root modules (i.e. parent-less) with respect to the modules in the set itself. In other words, these are the modules in ``modules`` that are not the child of any other module in ``modules``. """ root_modules: set[nn.Module] = set() module_to_submodules = {module: set(module.modules()) for module in modules} for candidate_module in modules: is_root_module = True for module, submodules in module_to_submodules.items(): is_child_module = ( candidate_module is not module and candidate_module in submodules ) if is_child_module: is_root_module = False break if is_root_module: root_modules.add(candidate_module) return root_modules
def _override_module_mixed_precision( root: torch.nn.Module, module_classes_to_override: Iterable[type[nn.Module]], wrap_override_dict: dict[str, Any] = {"mixed_precision": None}, # noqa: B006) -> set[type[nn.Module]]: module_classes_to_override = tuple(set(module_classes_to_override)) # Return a set of the actually overridden module classes overridden_module_classes: set[type[nn.Module]] = set() for mod in root.modules(): if isinstance(mod, module_classes_to_override): overridden_module_classes.add(type(mod)) mod._wrap_overrides = wrap_override_dict # type: ignore[assignment] # TODO: We need to run this mixed precision ignored module in fp32, # but ensure subsequent modules, that may possibly be running with # mixed precision, still receive the appropriate precision inputs # without user having to adjust mixed precision config too much. # As a result, we attach pre and post forward hooks to up / down # cast. We should revisit this design.
def cast_fn( dtype: torch.dtype, module: nn.Module, x: torch.Tensor ) -> torch.Tensor: if not torch.is_floating_point(x) or x.dtype == dtype: return x _MODULE_TO_INP_DTYPE[module] = x.dtype return x.to(dtype)
def forward_pre_hook(module, args): return _apply_to_tensors(partial(cast_fn, torch.float32, module), args)
def forward_post_hook(module, args, output): # NOTE: If the forward did not have any floating-point tensors, # then the dtype will not be set for this module, and we do not # upcast the dtype. if module in _MODULE_TO_INP_DTYPE: old_dtype = _MODULE_TO_INP_DTYPE[module] return _apply_to_tensors( partial(cast_fn, old_dtype, module), output )
# We intentionally append both of these hooks so that they run after # all other hooks. mod.register_forward_pre_hook(forward_pre_hook, prepend=False) mod.register_forward_hook(forward_post_hook, prepend=False) return overridden_module_classes
def _no_dispatch_record_stream(tensor: torch.Tensor, stream: torch.Stream) -> None: # FIXME record_stream doesn't work with non-cuda/mtia/xpu tensors if tensor.device.type not in [ "cuda", "mtia", "xpu", torch._C._get_privateuse1_backend_name(), ]: return
if torch.distributed._functional_collectives.is_torchdynamo_compiling(): return # from @ezyang: # The no_dispatch was added in https://github.com/pytorch/pytorch/pull/88014 cc @fegin # Looking over the PR, it looks like this is because we don't actually support Stream arguments # in torch dispatch, so it just chokes. # If Dynamo is able to answer "are there any torch dispatch modes" active (it should answer False), # a better version of this would just be to check if there are any modes before disabling dispatch. # TODO(voz): Extend a dynamo util to answer the above, unify the codepaths here. tensor.record_stream(stream) else: with no_dispatch(): tensor.record_stream(stream)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# mypy: allow-untyped-defsimport loggingimport timefrom collections import defaultdictfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom enum import Enum
import torchimport torch.distributed as distimport torch.distributed.fsdp._flat_param as flat_param_filefrom torch.distributed.fsdp._common_utils import ( _apply_to_modules, _get_module_fsdp_state, clean_tensor_name,)
logger = logging.getLogger(__name__)
class SimpleProfiler: class Type(str, Enum): ALL = "all" ALLGATHER = "all_gather" ALLGATHER_OBJ = "all_gather_object" RESHARDING = "resharding" H2D = "H2D" D2H = "D2H"
results: dict[str, float] = defaultdict(float) profiling: set[str] = set()
@classmethod def reset(cls) -> None: cls.results.clear() cls.profiling.clear()
@classmethod @contextmanager def profile(cls, profile_type: str) -> Iterator[None]: assert profile_type not in cls.profiling, ( f"{profile_type} is already being profiled. " "SimpleProfiler does not support profiling multiple instances at " "the same time. " )
cls.profiling.add(profile_type) begin = time.monotonic() try: yield finally: end = time.monotonic() cls.results[profile_type] += end - begin cls.profiling.remove(profile_type)
@classmethod def dump_and_reset(cls, msg: str) -> None: # This cannot be combined with DETAIL distributed log # as the profiling will be very incorrect. if dist.get_rank() == 0 and dist.get_debug_level() == dist.DebugLevel.INFO: logger.info("%s %s", msg, cls.results) cls.reset()
def _get_sharded_module_tree_with_module_name_to_fqns( model: torch.nn.Module,) -> tuple[str, dict[str, list[str]]]: """ It is used for composable fully_shard() code path, it returns 1. sharded module tree info: each line represents a submodule name that contains the submodule's FQN and its submodule class name, if the submodule is sharded by `fully_shard`, the submodule name will add a postfix with ' FULLY SHARDED'. Each increased tree level adds 4 spaces before the printed name. A printed sharded module tree info for a toy model is like this: [CompositeModel] FULLY SHARDED l1[Linear] u1[UnitModule] FULLY SHARDED u1.l1[Linear] u1.seq[Sequential] u1.seq.0[ReLU] u1.seq.1[Linear] u1.seq.2[ReLU] u1.l2[Linear] u2[UnitModule] FULLY SHARDED u2.l1[Linear] u2.seq[Sequential] u2.seq.0[ReLU] u2.seq.1[Linear] u2.seq.2[ReLU] u2.l2[Linear] l2[Linear] 2. a dict mapping from the concated module FQN and class name to a list of its managed original parameters' FQNs. An example of the dict for the above toy sharded model is like this: {'[CompositeModel]': ['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'], 'u1[UnitModule]': ['u1.l1.weight', 'u1.l1.bias', 'u1.seq.1.weight', 'u1.seq.1.bias', 'u1.l2.weight', 'u1.l2.bias'], 'u2[UnitModule]': ['u2.l1.weight', 'u2.l1.bias', 'u2.seq.1.weight', 'u2.seq.1.bias', 'u2.l2.weight', 'u2.l2.bias'] } All FQNs are prefixed starting from ``model``.
Args: model (torch.nn.Module): Root module (which may or may not be passed to composable `fully_shard()`). """
def module_fn( module, prefix, tree_level, sharded_tree_info, sharded_module_name_to_fqns ): num_spaces = tree_level * 4 trimed_prefix = ( prefix[:-1] if (len(prefix) > 0 and prefix[-1] == ".") else prefix ) prefixed_module_name = trimed_prefix + "[" + module.__class__.__name__ + "]" printed_prefixed_module_name = " " * num_spaces + prefixed_module_name
state = _get_module_fsdp_state(module) if state is None: sharded_tree_info[0] += printed_prefixed_module_name + "\n" return
handle = state._fully_sharded_module_to_handle.get(module, None)
if handle: sharded_tree_info[0] += ( printed_prefixed_module_name + " FULLY SHARDED" + "\n" ) else: sharded_tree_info[0] += printed_prefixed_module_name + "\n"
if handle: param = handle.flat_param assert isinstance(param, flat_param_file.FlatParameter) global_fqns = [ clean_tensor_name(prefix + name) for name in param._fqns ] # prefixed from the top level `model` (i.e. including `prefix`)
if prefixed_module_name in sharded_module_name_to_fqns: sharded_module_name_to_fqns[prefixed_module_name].extend(global_fqns) else: sharded_module_name_to_fqns[prefixed_module_name] = global_fqns
def return_fn(sharded_tree_info, sharded_module_name_to_fqns): return sharded_tree_info[0], sharded_module_name_to_fqns
# Use List to mutate its value in place while running the recursive functions sharded_tree_info: list[str] = [ "", ] sharded_module_name_to_fqns: dict[str, list[str]] = {} return _apply_to_modules( model, module_fn, return_fn, [key for key, _ in model.named_parameters()], sharded_tree_info, sharded_module_name_to_fqns, )12345678910111213141516171819202122232425262728293031323334353637383940414243import torch.nn as nn
def _annotate_modules_for_dynamo( module: nn.Module, ignored_modules: set[nn.Module], use_orig_params: bool,) -> None: """ Annotates the submodules in ``module`` 's tree, except those in ``ignored_modules``, indicating that the submodules are FSDP-managed and saving the ``use_orig_params`` setting passed to the FSDP constructor. """ for submodule in module.modules(): if submodule not in ignored_modules: """[note: Dynamo treats FSDP wrapped modules as UnspecializedNNModule]
Dynamo doesn't get to see this instance (FullyShardedDataParallel) during tracing, since it skips tracing all the torch.distributed.fsdp code. - Why? Running the FSDP code eagerly avoids lots of issues trying to trace complex hooks, and also gets us graph-breaks on FSDP module boundaries which we want anyway for comm ops. - However, we _also_ want dynamo to treat the wrapped module inside FSDP 'unspecially' (*), and we need a way to indicate to dynamo which modules are wrapped by FSDP.
(*) UnspecializedNNModules in dynamo are traced-through without any assumptions, and with thorough guards. NNModules otherwise are 'specialized', meaning there is less overhead due to assuming their code is well-behaved.
One particular issue with specialized NNModules for FSDP is that the views created for orig_params are captured into the compiled graph on the first iteration, and while they are always going to point to the correct flatparameter and give correct results, their order of creation influences the order of backward execution, preventing overlap of comm and computation during backward. We need to _use_ the new parameter views created on each forward iteration, in order for backward to interleave hooks with compute per layer. UnspecializedNNModule lets us achieve this by capturing the module code more 'functionally' and passing parameters in as inputs each time. """ submodule._is_fsdp_managed_module = True # type: ignore[assignment]
# Dynamo only supports FSDP with use_orig_params=True. # This is hacky, but I could not think of another way to add an assertion to dynamo # for this, since Dynamo skips all the FSDP code frames and thus can't inspect the # FSDP module directly submodule._fsdp_use_orig_params = use_orig_params # type: ignore[assignment]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364# mypy: allow-untyped-defsimport itertoolsimport warningsfrom enum import auto, Enumfrom typing import Optional, Union
import torchimport torch.distributed as distimport torch.distributed.fsdp._traversal_utils as traversal_utilsimport torch.nn as nnfrom torch.distributed.fsdp._common_utils import _FSDPState, _get_param_to_fqnsfrom torch.distributed.fsdp._flat_param import FlatParamHandle
class _ExecOrderWarnStatus(Enum): """Used internally for execution order validation."""
NONE = auto() # no deviation yet WARNING = auto() # deviated this iteration; currently issuing warnings WARNED = auto() # deviated in a previous iteration
class _ExecOrderData: """ This contains the data structures to track the execution order. We track the pre-forward order on the *first* iteration for forward prefetching (which thus assumes static graph) and the post-forward order on *every* iteration for backward prefetching (which thus does not assume static graph but may be provide an incorrect order). """
def __init__( self, debug_level: dist.DebugLevel, backward_prefetch_limit: int, forward_prefetch_limit: int, ) -> None: # Tracks the (static) pre-forward order for execution order validation # and forward prefetching self.handles_pre_forward_order: list[FlatParamHandle] = [] # Tracks the post-forward order for pre-backward prefetching self.handles_post_forward_order: list[Optional[FlatParamHandle]] = [] self._iter = 0
# Gives the max number of backward/forward prefetched all-gathers by a # single module self._backward_prefetch_limit = backward_prefetch_limit self._forward_prefetch_limit = forward_prefetch_limit
# Data structures for execution order validation self._checking_order: bool = debug_level == dist.DebugLevel.DETAIL self.process_group: Optional[dist.ProcessGroup] = None self.world_size: Optional[int] = None self.all_handles: list[FlatParamHandle] = [] # Names are prefixed from the root module self.param_to_fqn: dict[nn.Parameter, list[str]] = {} # Current index in the pre-forward execution order self.current_order_index = 0 self.warn_status = _ExecOrderWarnStatus.NONE
def init( self, state: _FSDPState, root_module: nn.Module, process_group: dist.ProcessGroup, ) -> None: """ Initializes the data structures needed for checking the forward order. This should be called after a root FSDP instance has been set during lazy initialization. """ self.process_group = process_group self.rank = process_group.rank() self.world_size = process_group.size() # Fix an order over the handles, which should be the same across ranks for handle in traversal_utils._get_fsdp_handles(root_module): index = len(self.all_handles) self.all_handles.append(handle) handle._handle_index = index self.param_to_fqn = _get_param_to_fqns(root_module) # TODO (awgu): We can broadcast the metadata of rank 0's `all_handles` # to check that all ranks have the same handles in the same order. # https://github.com/pytorch/pytorch/issues/79620
@property def is_first_iter(self) -> bool: return self._iter == 0
def get_handle_to_backward_prefetch( self, current_handle: FlatParamHandle, ) -> Optional[FlatParamHandle]: """ Returns a :class:`list` of the handles keys of the handles to backward prefetch given the current handles key. If there are no valid handles keys to prefetch, then this returns an empty :class:`list`. """ current_index = current_handle._post_forward_index if current_index is None: return None target_index = current_index - 1 target_handle: Optional[FlatParamHandle] = None for _ in range(self._backward_prefetch_limit): if target_index < 0: break target_handle = self.handles_post_forward_order[target_index] target_index -= 1 return target_handle
def get_handle_to_forward_prefetch( self, current_handle: FlatParamHandle, ) -> Optional[FlatParamHandle]: """ Returns a :class:`list` of the handles keys of the handles to forward prefetch given the current handles key. If there are no valid handles keys to prefetch, then this returns an empty :class:`list`. """ current_index = current_handle._pre_forward_order_index if current_index is None: return None target_index = current_index + 1 target_handle: Optional[FlatParamHandle] = None for _ in range(self._forward_prefetch_limit): if target_index >= len(self.handles_pre_forward_order): break target_handle = self.handles_pre_forward_order[target_index] target_index += 1 return target_handle
def record_post_forward(self, handle: Optional[FlatParamHandle]) -> None: """ Records ``handles`` in the post-forward order, where ``handles`` should be a group of handles used in the same module's forward. If ``handles`` is empty, then it is omitted.
Unlike :meth:`record_pre_forward`, this records the order *every* iteration with the expectation that the recorded order is reset in :meth:`next_iter`. """ if not handle: return # Only record the first usage of a handles key if handle._post_forward_index: self.handles_post_forward_order.append(handle) return index = len(self.handles_post_forward_order) handle._post_forward_index = index self.handles_post_forward_order.append(handle)
def record_pre_forward( self, handle: Optional[FlatParamHandle], is_training: bool ) -> None: """ Records ``handles`` in the pre-forward order, where ``handles`` should be a group of handles used in the same module's forward. If ``handles`` is empty, then it is omitted.
On the first iteration, this checks the execution order across ranks. See :meth:`_check_order` for details. """ if not handle: return self._check_order(handle, is_training) # Fix the order after the first iteration and only record the first # usage of a handles key if not self.is_first_iter or handle._pre_forward_order_index is not None: return index = len(self.handles_pre_forward_order) handle._pre_forward_order_index = index self.handles_pre_forward_order.append(handle)
def _check_order(self, handle: FlatParamHandle, is_training: bool) -> None: """ Checks the forward execution order as long as ``is_training`` is ``True`` since checking in eval mode is not supported. This only checks if the distributed debug level is DETAIL.
- On the first iteration, this uses all-gathers to check that all ranks are all-gathering the same handles and hence ``FlatParameter`` s, raising an error if not. - On subsequent iterations, this checks that each rank is locally consistent with its own forward order from the first iteration, issuing a warning if not. This issues a warning on the first deviating iteration and stops warning thereafter. """ # Do not check order in eval mode since the post-backward callback does # not run so it cannot be used to mark the end of an iteration if not is_training or not self._checking_order: return if self.is_first_iter: msg_prefix = "Forward order differs across ranks:" optional_local_indices: tuple[Optional[int], ...] = ( self._get_handle_indices(handle) ) device = handle.device # guaranteed to be non-CPU num_valid_indices = sum( (index is not None) for index in optional_local_indices ) tensor_kwargs: dict[str, Union[torch.dtype, torch.device]] = { "dtype": torch.int32, "device": device, } world_num_valid_indices = torch.zeros(self.world_size, **tensor_kwargs) # type: ignore[arg-type, call-overload] local_num_valid_indices = torch.tensor([num_valid_indices], **tensor_kwargs) # type: ignore[arg-type, call-overload] dist.all_gather_into_tensor( world_num_valid_indices, local_num_valid_indices, group=self.process_group, ) # Copy entire tensor from D2H once to avoid per element D2H copies world_num_valid_indices = world_num_valid_indices.cpu() # Check that all ranks plan to all-gather the same number of # parameters # TODO (awgu): Since every module has at most one handle in the # current implementation, this should never raise the error. assert self.world_size is not None # mypy if not torch.distributed._functional_collectives.is_torchdynamo_compiling(): # TODO(voz): Don't graph break on this - dynamo hates the n1 != n2 # tensor comparison control flow. # https://github.com/pytorch/pytorch/issues/107055 for (r1, n1), (r2, n2) in itertools.combinations( ( (rank, world_num_valid_indices[rank]) for rank in range(self.world_size) ), 2, ): if n1 != n2: raise RuntimeError( f"{msg_prefix} rank {r1} is all-gathering {n1} parameters " f"while rank {r2} is all-gathering {n2} parameters" ) world_indices = torch.zeros( # type: ignore[call-overload] self.world_size * num_valid_indices, **tensor_kwargs ) local_indices = torch.tensor(optional_local_indices, **tensor_kwargs) # type: ignore[arg-type] dist.all_gather_into_tensor( world_indices, local_indices, group=self.process_group ) # Copy entire tensor from D2H once to avoid per element D2H copies world_indices = world_indices.cpu() # Check that all ranks plan to all-gather the same index parameters if not torch.distributed._functional_collectives.is_torchdynamo_compiling(): # TODO(voz): Don't graph break on this - dynamo hates the i1 != i2 # tensor comparison control flow. # https://github.com/pytorch/pytorch/issues/107055 for (r1, i1), (r2, i2) in itertools.combinations( ( ( rank, world_indices[ rank * num_valid_indices : (rank + 1) * num_valid_indices ], ) for rank in range(self.world_size) ), 2, ): if i1 != i2: r1_param_names = self._get_names_from_handle_indices(i1) r2_param_names = self._get_names_from_handle_indices(i2) raise RuntimeError( f"{msg_prefix} rank {r1} is all-gathering parameters " f"for {r1_param_names} while rank {r2} is all-gathering " f"parameters for {r2_param_names}" ) else: # Only issue warnings on the first deviating iteration and stop # checking thereafter to avoid flooding the console if self.warn_status == _ExecOrderWarnStatus.WARNED: return msg_prefix = None # non-`None` means we should warn if self.current_order_index >= len(self.handles_pre_forward_order): # This iteration sees extra all-gather(s) compared to the first msg_prefix = ( "Expected to not all-gather any more parameters in the " "forward but trying to all-gather parameters for " ) else: expected_handle = self.handles_pre_forward_order[ self.current_order_index ] if expected_handle != handle: expected_param_names = self._get_names_from_handles(expected_handle) msg_prefix = ( f"Expected to all-gather for {expected_param_names} " "but trying to all-gather parameters for " ) if msg_prefix is not None: param_names = self._get_names_from_handles(handle) msg_suffix = ( f"{param_names}" if param_names else "a newly-added parameter since construction time" ) warnings.warn( "Forward order differs from that of the first iteration " f"on rank {self.rank}. Collectives are unchecked and may " f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}" ) self.warn_status = _ExecOrderWarnStatus.WARNING self.current_order_index += 1
def _get_handle_indices( self, handle: FlatParamHandle, ) -> tuple[Optional[int], ...]: """ Returns the handle indices (i.e. indices into ``self.all_handles``) corresponding to the handles in ``handle``. An entry in the returned tuple is ``None`` if the handle is invalid. """ indices: list[Optional[int]] = [] if handle: indices.append(handle._handle_index) return tuple(indices)
def _get_names_from_handle_indices( self, handle_indices: tuple[int, ...], ) -> list[list[str]]: """ Returns a list of FQNs for each handle in ``handle_indices``. If a handle index is invalid, then its FQNs are omitted from the returned list. """ fqns: list[list[str]] = [] for index in handle_indices: if index is None or index < 0 or index >= len(self.all_handles): continue handle = self.all_handles[index] flat_param = handle.flat_param fqns.append(self.param_to_fqn[flat_param]) return fqns
def _get_names_from_handles( self, handle: FlatParamHandle, ) -> list[list[str]]: """ Returns a list of FQNs for each handle in ``handles_key``. If a handle is invalid, then its FQNs are omitted from the returned list. """ fqns: list[list[str]] = [] if handle: flat_param = handle.flat_param if flat_param in self.param_to_fqn: fqns.append(self.param_to_fqn[flat_param]) return fqns
def next_iter(self): """ Advances the internal data structures per iteration. This should be called in the post-backward callback since that marks the true end of an iteration. """ self._iter += 1 self.handles_post_forward_order.clear() if self._checking_order: self.current_order_index = 0 if self.warn_status == _ExecOrderWarnStatus.WARNING: self.warn_status = _ExecOrderWarnStatus.WARNED123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179from abc import ABC, abstractmethodfrom typing import Any, Optional
import torchimport torch.distributed as distfrom torch.distributed._shard.sharded_tensor.api import ShardedTensorfrom torch.distributed._shard.sharded_tensor.shard import Shardfrom torch.distributed.fsdp._shard_utils import ( _all_gather_dtensor, _create_chunk_dtensor, _create_chunk_sharded_tensor,)from torch.distributed.tensor import DeviceMesh, DTensor
class FSDPExtensions(ABC): """ This enables some customizable hooks to enable composability with tensor parallelism. To activate these hooks, use :func:`_set_fsdp_extensions` to set a custom :class:`FSDPExtensions` that implements the hooks. """
@abstractmethod def pre_flatten_transform( self, tensor: torch.Tensor, ) -> tuple[torch.Tensor, Optional[Any]]: """E.g. converting ``DistributedTensor`` to local tensor.""" ...
@abstractmethod def post_unflatten_transform( self, tensor: torch.Tensor, param_extension: Any, ) -> torch.Tensor: """E.g. converting local tensor to ``DistributedTensor``.""" ...
@abstractmethod def chunk_tensor( self, tensor: torch.Tensor, rank: int, world_size: int, num_devices_per_node: int, pg: dist.ProcessGroup, device: Optional[torch.device] = None, ) -> torch.Tensor: """Shards a tensor to chunks and returns the local chunk.""" ...
@abstractmethod def chunk_dtensor( self, tensor: torch.Tensor, rank: int, device_mesh: DeviceMesh, ) -> torch.Tensor: """Shards a tensor/DTensor to DTensor and returns the local DTensor.""" ...
@abstractmethod def pre_load_state_dict_transform( self, tensor: torch.Tensor, ) -> tuple[torch.Tensor, list[Shard]]: """ This is to be called before loading a *sharded* model state dict and should return the tensor and list of shards from which to load data. """ ...
@abstractmethod def all_gather_dtensor( self, tensor: DTensor, parent_mesh: Optional[DeviceMesh], ) -> torch.Tensor: """ This is to be called before loading a *sharded* DTensor state dict. This gathers tensor in FSDP dimension and returns local tensor of TP DTensor. """ ...
_extensions: Optional[FSDPExtensions] = None
def _set_fsdp_extensions(flattener: FSDPExtensions) -> None: global _extensions _extensions = flattener
def _ext_pre_flatten_transform( tensor: torch.Tensor, fsdp_extension: Optional[FSDPExtensions] = None,) -> tuple[torch.Tensor, Optional[Any]]: if fsdp_extension is not None: new_tensor, param_extension = fsdp_extension.pre_flatten_transform(tensor) if param_extension is not None: return new_tensor, param_extension return tensor, None
def _ext_post_unflatten_transform( tensor: torch.Tensor, param_extension: Any, fsdp_extension: Optional[FSDPExtensions] = None,) -> torch.Tensor: if fsdp_extension is not None and param_extension is not None: return fsdp_extension.post_unflatten_transform(tensor, param_extension) return tensor
def _ext_chunk_tensor( tensor: torch.Tensor, rank: int, world_size: int, num_devices_per_node: int, pg: dist.ProcessGroup, fsdp_extension: Optional[FSDPExtensions] = None,) -> torch.Tensor: chunk_tensor_fn = ( fsdp_extension.chunk_tensor if fsdp_extension is not None else _create_chunk_sharded_tensor ) return chunk_tensor_fn( tensor, rank, world_size, num_devices_per_node, pg, )
def _ext_chunk_dtensor( tensor: torch.Tensor, rank: int, device_mesh: DeviceMesh, fsdp_extension: Optional[FSDPExtensions] = None,) -> torch.Tensor: chunk_dtensor_fn = ( fsdp_extension.chunk_dtensor if fsdp_extension is not None else _create_chunk_dtensor ) return chunk_dtensor_fn( tensor, rank, device_mesh, )
def _ext_pre_load_state_dict_transform( tensor: torch.Tensor, fsdp_extension: Optional[FSDPExtensions] = None,) -> tuple[torch.Tensor, list[Shard]]: if fsdp_extension is not None: return fsdp_extension.pre_load_state_dict_transform(tensor)
assert type(tensor) is ShardedTensor shards = tensor.local_shards() return (tensor, shards)
def _ext_all_gather_dtensor( tensor: DTensor, parent_mesh: Optional[DeviceMesh], fsdp_extension: Optional[FSDPExtensions] = None,) -> torch.Tensor: all_gather_dtensor_fn = ( fsdp_extension.all_gather_dtensor if fsdp_extension is not None else _all_gather_dtensor ) return all_gather_dtensor_fn(tensor, parent_mesh)123456789101112131415161718from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicyfrom ._fully_shard import ( FSDPModule, fully_shard, register_fsdp_forward_method, UnshardHandle,)
__all__ = [ "CPUOffloadPolicy", "FSDPModule", "fully_shard", "MixedPrecisionPolicy", "OffloadPolicy", "register_fsdp_forward_method", "UnshardHandle",].gitattributes+5
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/__init__.pyAdded+54
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/api.pyAdded+283
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/debug_info_logging.pyAdded+24
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/file_based_local_timer.pyAdded+442
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/timer/local_timer.pyAdded+128
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/__init__.pyAdded+9
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/api.pyAdded+62
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/__init__.pyAdded+10
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/cycling_iterator.pyAdded+57
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/data/elastic_distributed_sampler.pyAdded+92
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/distributed.pyAdded+184
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/log_level.pyAdded+14
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/logging.pyAdded+69
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/elastic/utils/store.pyAdded+226
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__init__.pyAdded+66
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/__init__.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_common_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_debug_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-311.pycAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_init_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_optim_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_shard_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/api.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-311.pycAdded+3
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/__pycache__/wrap.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_common_utils.pyAdded+546
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_debug_utils.pyAdded+157
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_dynamo_utils.pyAdded+43
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_exec_order_utils.pyAdded+364
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_flat_param.pyAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fsdp_extensions.pyAdded+179
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__init__.pyAdded+18
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/__init__.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_api.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_collectives.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_common.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_init.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param_group.cpython-311.pycAdded
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_state.cpython-311.pycAdded