Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_composable_state.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/argparse_util.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/constants.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/device_mesh.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/launch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/remote_device.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/rendezvous.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/run.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/registry.py +71 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__init__.py +54 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/api.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/local_timer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/api.py +283 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/debug_info_logging.py +25 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py +393 -0
- vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/local_timer.py +128 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/__init__.py +67 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_api.py +1231 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__init__.py +10 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_common_rules.py +288 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_conv_ops.py +110 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py +181 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_experimental_ops.py +28 -0
- vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_math_ops.py +1058 -0
.gitattributes
CHANGED
|
@@ -1828,3 +1828,5 @@ parrot/lib/python3.10/site-packages/scipy/optimize/_trlib/_trlib.cpython-310-x86
|
|
| 1828 |
videollama2/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1829 |
vllm/lib/python3.10/site-packages/cupy/_core/_routines_sorting.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1830 |
vllm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1828 |
videollama2/lib/python3.10/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1829 |
vllm/lib/python3.10/site-packages/cupy/_core/_routines_sorting.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1830 |
vllm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1831 |
+
vllm/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1832 |
+
vllm/lib/python3.10/site-packages/torch/testing/_internal/__pycache__/common_methods_invocations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (4.42 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-310.pyc
ADDED
|
Binary file (1.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_composable_state.cpython-310.pyc
ADDED
|
Binary file (1.31 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-310.pyc
ADDED
|
Binary file (30.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-310.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-310.pyc
ADDED
|
Binary file (20 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/argparse_util.cpython-310.pyc
ADDED
|
Binary file (3.93 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-310.pyc
ADDED
|
Binary file (3.17 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/constants.cpython-310.pyc
ADDED
|
Binary file (540 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/device_mesh.cpython-310.pyc
ADDED
|
Binary file (28.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/launch.cpython-310.pyc
ADDED
|
Binary file (7.82 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-310.pyc
ADDED
|
Binary file (385 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/remote_device.cpython-310.pyc
ADDED
|
Binary file (3.78 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/rendezvous.cpython-310.pyc
ADDED
|
Binary file (8.77 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/run.cpython-310.pyc
ADDED
|
Binary file (29.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/events/__pycache__/api.cpython-310.pyc
ADDED
|
Binary file (3.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/rendezvous/registry.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from .api import (
|
| 8 |
+
rendezvous_handler_registry as handler_registry,
|
| 9 |
+
RendezvousHandler,
|
| 10 |
+
RendezvousParameters,
|
| 11 |
+
)
|
| 12 |
+
from .dynamic_rendezvous import create_handler
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
__all__ = ["get_rendezvous_handler"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _create_static_handler(params: RendezvousParameters) -> RendezvousHandler:
|
| 19 |
+
from . import static_tcp_rendezvous
|
| 20 |
+
|
| 21 |
+
return static_tcp_rendezvous.create_rdzv_handler(params)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _create_etcd_handler(params: RendezvousParameters) -> RendezvousHandler:
|
| 25 |
+
from . import etcd_rendezvous
|
| 26 |
+
|
| 27 |
+
return etcd_rendezvous.create_rdzv_handler(params)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _create_etcd_v2_handler(params: RendezvousParameters) -> RendezvousHandler:
|
| 31 |
+
from .etcd_rendezvous_backend import create_backend
|
| 32 |
+
|
| 33 |
+
backend, store = create_backend(params)
|
| 34 |
+
|
| 35 |
+
return create_handler(store, backend, params)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _create_c10d_handler(params: RendezvousParameters) -> RendezvousHandler:
|
| 39 |
+
from .c10d_rendezvous_backend import create_backend
|
| 40 |
+
|
| 41 |
+
backend, store = create_backend(params)
|
| 42 |
+
|
| 43 |
+
return create_handler(store, backend, params)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _register_default_handlers() -> None:
|
| 47 |
+
handler_registry.register("etcd", _create_etcd_handler)
|
| 48 |
+
handler_registry.register("etcd-v2", _create_etcd_v2_handler)
|
| 49 |
+
handler_registry.register("c10d", _create_c10d_handler)
|
| 50 |
+
handler_registry.register("static", _create_static_handler)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_rendezvous_handler(params: RendezvousParameters) -> RendezvousHandler:
|
| 54 |
+
"""
|
| 55 |
+
Obtain a reference to a :py:class`RendezvousHandler`.
|
| 56 |
+
|
| 57 |
+
Custom rendezvous handlers can be registered by
|
| 58 |
+
|
| 59 |
+
::
|
| 60 |
+
|
| 61 |
+
from torch.distributed.elastic.rendezvous import rendezvous_handler_registry
|
| 62 |
+
from torch.distributed.elastic.rendezvous.registry import get_rendezvous_handler
|
| 63 |
+
|
| 64 |
+
def create_my_rdzv(params: RendezvousParameters):
|
| 65 |
+
return MyCustomRdzv(params)
|
| 66 |
+
|
| 67 |
+
rendezvous_handler_registry.register("my_rdzv_backend_name", create_my_rdzv)
|
| 68 |
+
|
| 69 |
+
my_rdzv_handler = get_rendezvous_handler("my_rdzv_backend_name", RendezvousParameters)
|
| 70 |
+
"""
|
| 71 |
+
return handler_registry.create_handler(params)
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__init__.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Expiration timers are set up on the same process as the agent and
|
| 9 |
+
used from your script to deal with stuck workers. When you go into
|
| 10 |
+
a code-block that has the potential to get stuck you can acquire
|
| 11 |
+
an expiration timer, which instructs the timer server to kill the
|
| 12 |
+
process if it does not release the timer by the self-imposed expiration
|
| 13 |
+
deadline.
|
| 14 |
+
|
| 15 |
+
Usage::
|
| 16 |
+
|
| 17 |
+
import torchelastic.timer as timer
|
| 18 |
+
import torchelastic.agent.server as agent
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
start_method = "spawn"
|
| 22 |
+
message_queue = mp.get_context(start_method).Queue()
|
| 23 |
+
server = timer.LocalTimerServer(message, max_interval=0.01)
|
| 24 |
+
server.start() # non-blocking
|
| 25 |
+
|
| 26 |
+
spec = WorkerSpec(
|
| 27 |
+
fn=trainer_func,
|
| 28 |
+
args=(message_queue,),
|
| 29 |
+
...<OTHER_PARAMS...>)
|
| 30 |
+
agent = agent.LocalElasticAgent(spec, start_method)
|
| 31 |
+
agent.run()
|
| 32 |
+
|
| 33 |
+
def trainer_func(message_queue):
|
| 34 |
+
timer.configure(timer.LocalTimerClient(message_queue))
|
| 35 |
+
with timer.expires(after=60): # 60 second expiry
|
| 36 |
+
# do some work
|
| 37 |
+
|
| 38 |
+
In the example above if ``trainer_func`` takes more than 60 seconds to
|
| 39 |
+
complete, then the worker process is killed and the agent retries the worker group.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from .api import ( # noqa: F401
|
| 43 |
+
configure,
|
| 44 |
+
expires,
|
| 45 |
+
TimerClient,
|
| 46 |
+
TimerRequest,
|
| 47 |
+
TimerServer,
|
| 48 |
+
)
|
| 49 |
+
from .file_based_local_timer import ( # noqa: F401
|
| 50 |
+
FileTimerClient,
|
| 51 |
+
FileTimerRequest,
|
| 52 |
+
FileTimerServer,
|
| 53 |
+
)
|
| 54 |
+
from .local_timer import LocalTimerClient, LocalTimerServer # noqa: F401
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/api.cpython-310.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-310.pyc
ADDED
|
Binary file (11.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/__pycache__/local_timer.cpython-310.pyc
ADDED
|
Binary file (4.83 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/api.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
# All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# This source code is licensed under the BSD-style license found in the
|
| 6 |
+
# LICENSE file in the root directory of this source tree.
|
| 7 |
+
import abc
|
| 8 |
+
import logging
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from inspect import getframeinfo, stack
|
| 13 |
+
from typing import Any, Dict, List, Optional, Set
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"TimerRequest",
|
| 18 |
+
"TimerClient",
|
| 19 |
+
"RequestQueue",
|
| 20 |
+
"TimerServer",
|
| 21 |
+
"configure",
|
| 22 |
+
"expires",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TimerRequest:
|
| 29 |
+
"""
|
| 30 |
+
Data object representing a countdown timer acquisition and release
|
| 31 |
+
that is used between the ``TimerClient`` and ``TimerServer``.
|
| 32 |
+
A negative ``expiration_time`` should be interpreted as a "release"
|
| 33 |
+
request.
|
| 34 |
+
|
| 35 |
+
.. note:: the type of ``worker_id`` is implementation specific.
|
| 36 |
+
It is whatever the TimerServer and TimerClient implementations
|
| 37 |
+
have on to uniquely identify a worker.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
__slots__ = ["worker_id", "scope_id", "expiration_time"]
|
| 41 |
+
|
| 42 |
+
def __init__(self, worker_id: Any, scope_id: str, expiration_time: float):
|
| 43 |
+
self.worker_id = worker_id
|
| 44 |
+
self.scope_id = scope_id
|
| 45 |
+
self.expiration_time = expiration_time
|
| 46 |
+
|
| 47 |
+
def __eq__(self, other):
|
| 48 |
+
if isinstance(other, TimerRequest):
|
| 49 |
+
return (
|
| 50 |
+
self.worker_id == other.worker_id
|
| 51 |
+
and self.scope_id == other.scope_id
|
| 52 |
+
and self.expiration_time == other.expiration_time
|
| 53 |
+
)
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class TimerClient(abc.ABC):
|
| 58 |
+
"""
|
| 59 |
+
Client library to acquire and release countdown timers by communicating
|
| 60 |
+
with the TimerServer.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
@abc.abstractmethod
|
| 64 |
+
def acquire(self, scope_id: str, expiration_time: float) -> None:
|
| 65 |
+
"""
|
| 66 |
+
Acquires a timer for the worker that holds this client object
|
| 67 |
+
given the scope_id and expiration_time. Typically registers
|
| 68 |
+
the timer with the TimerServer.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
@abc.abstractmethod
|
| 72 |
+
def release(self, scope_id: str):
|
| 73 |
+
"""
|
| 74 |
+
Releases the timer for the ``scope_id`` on the worker this
|
| 75 |
+
client represents. After this method is
|
| 76 |
+
called, the countdown timer on the scope is no longer in effect.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class RequestQueue(abc.ABC):
|
| 81 |
+
"""
|
| 82 |
+
Consumer queue holding timer acquisition/release requests
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
@abc.abstractmethod
|
| 86 |
+
def size(self) -> int:
|
| 87 |
+
"""
|
| 88 |
+
Returns the size of the queue at the time this method is called.
|
| 89 |
+
Note that by the time ``get`` is called the size of the queue
|
| 90 |
+
may have increased. The size of the queue should not decrease
|
| 91 |
+
until the ``get`` method is called. That is, the following assertion
|
| 92 |
+
should hold:
|
| 93 |
+
|
| 94 |
+
size = q.size()
|
| 95 |
+
res = q.get(size, timeout=0)
|
| 96 |
+
assert size == len(res)
|
| 97 |
+
|
| 98 |
+
-- or --
|
| 99 |
+
|
| 100 |
+
size = q.size()
|
| 101 |
+
res = q.get(size * 2, timeout=1)
|
| 102 |
+
assert size <= len(res) <= size * 2
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
@abc.abstractmethod
|
| 106 |
+
def get(self, size: int, timeout: float) -> List[TimerRequest]:
|
| 107 |
+
"""
|
| 108 |
+
Gets up to ``size`` number of timer requests in a blocking fashion
|
| 109 |
+
(no more than ``timeout`` seconds).
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class TimerServer(abc.ABC):
|
| 114 |
+
"""
|
| 115 |
+
Entity that monitors active timers and expires them
|
| 116 |
+
in a timely fashion. This server is responsible for
|
| 117 |
+
reaping workers that have expired timers.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
def __init__(
|
| 121 |
+
self, request_queue: RequestQueue, max_interval: float, daemon: bool = True
|
| 122 |
+
):
|
| 123 |
+
"""
|
| 124 |
+
:param request_queue: Consumer ``RequestQueue``
|
| 125 |
+
:param max_interval: max time (in seconds) to wait
|
| 126 |
+
for an item in the request_queue
|
| 127 |
+
:param daemon: whether to run the watchdog thread as a daemon
|
| 128 |
+
"""
|
| 129 |
+
super().__init__()
|
| 130 |
+
self._request_queue = request_queue
|
| 131 |
+
self._max_interval = max_interval
|
| 132 |
+
self._daemon = daemon
|
| 133 |
+
self._watchdog_thread: Optional[threading.Thread] = None
|
| 134 |
+
self._stop_signaled = False
|
| 135 |
+
|
| 136 |
+
@abc.abstractmethod
|
| 137 |
+
def register_timers(self, timer_requests: List[TimerRequest]) -> None:
|
| 138 |
+
"""
|
| 139 |
+
Processes the incoming timer requests and registers them with the server.
|
| 140 |
+
The timer request can either be a acquire-timer or release-timer request.
|
| 141 |
+
Timer requests with a negative expiration_time should be interpreted
|
| 142 |
+
as a release-timer request.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
@abc.abstractmethod
|
| 146 |
+
def clear_timers(self, worker_ids: Set[Any]) -> None:
|
| 147 |
+
"""
|
| 148 |
+
Clears all timers for the given ``worker_ids``.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
@abc.abstractmethod
|
| 152 |
+
def get_expired_timers(self, deadline: float) -> Dict[str, List[TimerRequest]]:
|
| 153 |
+
"""
|
| 154 |
+
Returns all expired timers for each worker_id. An expired timer
|
| 155 |
+
is a timer for which the expiration_time is less than or equal to
|
| 156 |
+
the provided deadline.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
@abc.abstractmethod
|
| 160 |
+
def _reap_worker(self, worker_id: Any) -> bool:
|
| 161 |
+
"""
|
| 162 |
+
Reaps the given worker. Returns True if the worker has been
|
| 163 |
+
successfully reaped, False otherwise. If any uncaught exception
|
| 164 |
+
is thrown from this method, the worker is considered reaped
|
| 165 |
+
and all associated timers will be removed.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def _reap_worker_no_throw(self, worker_id: Any) -> bool:
|
| 169 |
+
"""
|
| 170 |
+
Wraps ``_reap_worker(worker_id)``, if an uncaught exception is
|
| 171 |
+
thrown, then it considers the worker as reaped.
|
| 172 |
+
"""
|
| 173 |
+
try:
|
| 174 |
+
return self._reap_worker(worker_id)
|
| 175 |
+
except Exception:
|
| 176 |
+
logger.exception(
|
| 177 |
+
"Uncaught exception thrown from _reap_worker(), "
|
| 178 |
+
"check that the implementation correctly catches exceptions",
|
| 179 |
+
)
|
| 180 |
+
return True
|
| 181 |
+
|
| 182 |
+
def _watchdog_loop(self):
|
| 183 |
+
while not self._stop_signaled:
|
| 184 |
+
try:
|
| 185 |
+
self._run_watchdog()
|
| 186 |
+
except Exception:
|
| 187 |
+
logger.exception("Error running watchdog")
|
| 188 |
+
|
| 189 |
+
def _run_watchdog(self):
|
| 190 |
+
batch_size = max(1, self._request_queue.size())
|
| 191 |
+
timer_requests = self._request_queue.get(batch_size, self._max_interval)
|
| 192 |
+
self.register_timers(timer_requests)
|
| 193 |
+
now = time.time()
|
| 194 |
+
reaped_worker_ids = set()
|
| 195 |
+
for worker_id, expired_timers in self.get_expired_timers(now).items():
|
| 196 |
+
logger.info(
|
| 197 |
+
"Reaping worker_id=[%s]." " Expired timers: %s",
|
| 198 |
+
worker_id,
|
| 199 |
+
self._get_scopes(expired_timers),
|
| 200 |
+
)
|
| 201 |
+
if self._reap_worker_no_throw(worker_id):
|
| 202 |
+
logger.info("Successfully reaped worker=[%s]", worker_id)
|
| 203 |
+
reaped_worker_ids.add(worker_id)
|
| 204 |
+
else:
|
| 205 |
+
logger.error(
|
| 206 |
+
"Error reaping worker=[%s]. Will retry on next watchdog.", worker_id
|
| 207 |
+
)
|
| 208 |
+
self.clear_timers(reaped_worker_ids)
|
| 209 |
+
|
| 210 |
+
def _get_scopes(self, timer_requests):
|
| 211 |
+
return [r.scope_id for r in timer_requests]
|
| 212 |
+
|
| 213 |
+
def start(self) -> None:
|
| 214 |
+
logger.info(
|
| 215 |
+
"Starting %s..." " max_interval=%s," " daemon=%s",
|
| 216 |
+
type(self).__name__,
|
| 217 |
+
self._max_interval,
|
| 218 |
+
self._daemon,
|
| 219 |
+
)
|
| 220 |
+
self._watchdog_thread = threading.Thread(
|
| 221 |
+
target=self._watchdog_loop, daemon=self._daemon
|
| 222 |
+
)
|
| 223 |
+
logger.info("Starting watchdog thread...")
|
| 224 |
+
self._watchdog_thread.start()
|
| 225 |
+
|
| 226 |
+
def stop(self) -> None:
|
| 227 |
+
logger.info("Stopping %s", type(self).__name__)
|
| 228 |
+
self._stop_signaled = True
|
| 229 |
+
if self._watchdog_thread:
|
| 230 |
+
logger.info("Stopping watchdog thread...")
|
| 231 |
+
self._watchdog_thread.join(self._max_interval)
|
| 232 |
+
self._watchdog_thread = None
|
| 233 |
+
else:
|
| 234 |
+
logger.info("No watchdog thread running, doing nothing")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
_timer_client: Optional[TimerClient] = None
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def configure(timer_client: TimerClient):
|
| 241 |
+
"""
|
| 242 |
+
Configures a timer client. Must be called before using ``expires``.
|
| 243 |
+
"""
|
| 244 |
+
global _timer_client
|
| 245 |
+
_timer_client = timer_client
|
| 246 |
+
logger.info("Timer client configured to: %s", type(_timer_client).__name__)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@contextmanager
|
| 250 |
+
def expires(
|
| 251 |
+
after: float, scope: Optional[str] = None, client: Optional[TimerClient] = None
|
| 252 |
+
):
|
| 253 |
+
"""
|
| 254 |
+
Acquires a countdown timer that expires in ``after`` seconds from now,
|
| 255 |
+
unless the code-block that it wraps is finished within the timeframe.
|
| 256 |
+
When the timer expires, this worker is eligible to be reaped. The
|
| 257 |
+
exact meaning of "reaped" depends on the client implementation. In
|
| 258 |
+
most cases, reaping means to terminate the worker process.
|
| 259 |
+
Note that the worker is NOT guaranteed to be reaped at exactly
|
| 260 |
+
``time.now() + after``, but rather the worker is "eligible" for being
|
| 261 |
+
reaped and the ``TimerServer`` that the client talks to will ultimately
|
| 262 |
+
make the decision when and how to reap the workers with expired timers.
|
| 263 |
+
|
| 264 |
+
Usage::
|
| 265 |
+
|
| 266 |
+
torch.distributed.elastic.timer.configure(LocalTimerClient())
|
| 267 |
+
with expires(after=10):
|
| 268 |
+
torch.distributed.all_reduce(...)
|
| 269 |
+
"""
|
| 270 |
+
if client is None:
|
| 271 |
+
if _timer_client is None:
|
| 272 |
+
raise RuntimeError("Configure timer client before using countdown timers.")
|
| 273 |
+
client = _timer_client
|
| 274 |
+
if scope is None:
|
| 275 |
+
# grab the caller file + lineno
|
| 276 |
+
caller = getframeinfo(stack()[1][0])
|
| 277 |
+
scope = f"{caller.filename}#{caller.lineno}"
|
| 278 |
+
expiration = time.time() + after
|
| 279 |
+
client.acquire(scope, expiration)
|
| 280 |
+
try:
|
| 281 |
+
yield
|
| 282 |
+
finally:
|
| 283 |
+
client.release(scope)
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/debug_info_logging.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
|
| 4 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 5 |
+
# All rights reserved.
|
| 6 |
+
#
|
| 7 |
+
# This source code is licensed under the BSD-style license found in the
|
| 8 |
+
# LICENSE file in the root directory of this source tree.
|
| 9 |
+
|
| 10 |
+
from typing import Dict, List
|
| 11 |
+
|
| 12 |
+
from torch.distributed.elastic.utils.logging import get_logger
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
logger = get_logger(__name__)
|
| 16 |
+
|
| 17 |
+
__all__ = ["log_debug_info_for_expired_timers"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def log_debug_info_for_expired_timers(
|
| 21 |
+
run_id: str,
|
| 22 |
+
expired_timers: Dict[int, List[str]],
|
| 23 |
+
):
|
| 24 |
+
if expired_timers:
|
| 25 |
+
logger.info("Timers expired for run:[%s] [%s].", run_id, expired_timers)
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/file_based_local_timer.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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5 |
+
# This source code is licensed under the BSD-style license found in the
|
| 6 |
+
# LICENSE file in the root directory of this source tree.
|
| 7 |
+
|
| 8 |
+
import io
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import select
|
| 12 |
+
import signal
|
| 13 |
+
import sys
|
| 14 |
+
import threading
|
| 15 |
+
import time
|
| 16 |
+
from typing import Callable, Dict, List, Optional, Set, Tuple
|
| 17 |
+
|
| 18 |
+
from torch.distributed.elastic.timer.api import TimerClient, TimerRequest
|
| 19 |
+
from torch.distributed.elastic.timer.debug_info_logging import (
|
| 20 |
+
log_debug_info_for_expired_timers,
|
| 21 |
+
)
|
| 22 |
+
from torch.distributed.elastic.utils.logging import get_logger
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
__all__ = ["FileTimerClient", "FileTimerRequest", "FileTimerServer"]
|
| 26 |
+
|
| 27 |
+
logger = get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class FileTimerRequest(TimerRequest):
|
| 31 |
+
"""
|
| 32 |
+
Data object representing a countdown timer acquisition and release
|
| 33 |
+
that is used between the ``FileTimerClient`` and ``FileTimerServer``.
|
| 34 |
+
A negative ``expiration_time`` should be interpreted as a "release"
|
| 35 |
+
request.
|
| 36 |
+
``signal`` is the signal to reap the worker process from the server
|
| 37 |
+
process.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
__slots__ = ["version", "worker_pid", "scope_id", "expiration_time", "signal"]
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self, worker_pid: int, scope_id: str, expiration_time: float, signal: int = 0
|
| 44 |
+
) -> None:
|
| 45 |
+
self.version = 1
|
| 46 |
+
self.worker_pid = worker_pid
|
| 47 |
+
self.scope_id = scope_id
|
| 48 |
+
self.expiration_time = expiration_time
|
| 49 |
+
self.signal = signal
|
| 50 |
+
|
| 51 |
+
def __eq__(self, other) -> bool:
|
| 52 |
+
if isinstance(other, FileTimerRequest):
|
| 53 |
+
return (
|
| 54 |
+
self.version == other.version
|
| 55 |
+
and self.worker_pid == other.worker_pid
|
| 56 |
+
and self.scope_id == other.scope_id
|
| 57 |
+
and self.expiration_time == other.expiration_time
|
| 58 |
+
and self.signal == other.signal
|
| 59 |
+
)
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
def to_json(self) -> str:
|
| 63 |
+
return json.dumps(
|
| 64 |
+
{
|
| 65 |
+
"version": self.version,
|
| 66 |
+
"pid": self.worker_pid,
|
| 67 |
+
"scope_id": self.scope_id,
|
| 68 |
+
"expiration_time": self.expiration_time,
|
| 69 |
+
"signal": self.signal,
|
| 70 |
+
},
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class FileTimerClient(TimerClient):
|
| 75 |
+
"""
|
| 76 |
+
Client side of ``FileTimerServer``. This client is meant to be used
|
| 77 |
+
on the same host that the ``FileTimerServer`` is running on and uses
|
| 78 |
+
pid to uniquely identify a worker.
|
| 79 |
+
This client uses a named_pipe to send timer requests to the
|
| 80 |
+
``FileTimerServer``. This client is a producer while the
|
| 81 |
+
``FileTimerServer`` is a consumer. Multiple clients can work with
|
| 82 |
+
the same ``FileTimerServer``.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
|
| 86 |
+
file_path: str, the path of a FIFO special file. ``FileTimerServer``
|
| 87 |
+
must have created it by calling os.mkfifo().
|
| 88 |
+
|
| 89 |
+
signal: signal, the signal to use to kill the process. Using a
|
| 90 |
+
negative or zero signal will not kill the process.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
file_path: str,
|
| 96 |
+
signal=(signal.SIGKILL if sys.platform != "win32" else signal.CTRL_C_EVENT), # type: ignore[attr-defined]
|
| 97 |
+
) -> None:
|
| 98 |
+
super().__init__()
|
| 99 |
+
self._file_path = file_path
|
| 100 |
+
self.signal = signal
|
| 101 |
+
|
| 102 |
+
def _open_non_blocking(self) -> Optional[io.TextIOWrapper]:
|
| 103 |
+
try:
|
| 104 |
+
fd = os.open(self._file_path, os.O_WRONLY | os.O_NONBLOCK)
|
| 105 |
+
return os.fdopen(fd, "wt")
|
| 106 |
+
except Exception:
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
def _send_request(self, request: FileTimerRequest) -> None:
|
| 110 |
+
# The server may have crashed or may haven't started yet.
|
| 111 |
+
# In such case, calling open() in blocking model blocks the client.
|
| 112 |
+
# To avoid such issue, open it in non-blocking mode, and an OSError will
|
| 113 |
+
# be raised if the server is not there.
|
| 114 |
+
file = self._open_non_blocking()
|
| 115 |
+
if file is None:
|
| 116 |
+
raise BrokenPipeError(
|
| 117 |
+
"Could not send the FileTimerRequest because FileTimerServer is not available."
|
| 118 |
+
)
|
| 119 |
+
with file:
|
| 120 |
+
json_request = request.to_json()
|
| 121 |
+
# Write request with no greater than select.PIPE_BUF is guarantee to be atomic.
|
| 122 |
+
if len(json_request) > select.PIPE_BUF:
|
| 123 |
+
raise RuntimeError(
|
| 124 |
+
f"FileTimerRequest larger than {select.PIPE_BUF} bytes "
|
| 125 |
+
f"is not supported: {json_request}"
|
| 126 |
+
)
|
| 127 |
+
file.write(json_request + "\n")
|
| 128 |
+
|
| 129 |
+
def acquire(self, scope_id: str, expiration_time: float) -> None:
|
| 130 |
+
self._send_request(
|
| 131 |
+
request=FileTimerRequest(
|
| 132 |
+
worker_pid=os.getpid(),
|
| 133 |
+
scope_id=scope_id,
|
| 134 |
+
expiration_time=expiration_time,
|
| 135 |
+
signal=self.signal,
|
| 136 |
+
),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def release(self, scope_id: str) -> None:
|
| 140 |
+
self._send_request(
|
| 141 |
+
request=FileTimerRequest(
|
| 142 |
+
worker_pid=os.getpid(), scope_id=scope_id, expiration_time=-1, signal=0
|
| 143 |
+
),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class FileTimerServer:
|
| 148 |
+
"""
|
| 149 |
+
Server that works with ``FileTimerClient``. Clients are expected to be
|
| 150 |
+
running on the same host as the process that is running this server.
|
| 151 |
+
Each host in the job is expected to start its own timer server locally
|
| 152 |
+
and each server instance manages timers for local workers (running on
|
| 153 |
+
processes on the same host).
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
|
| 157 |
+
file_path: str, the path of a FIFO special file to be created.
|
| 158 |
+
|
| 159 |
+
max_interval: float, max interval in seconds for each watchdog loop.
|
| 160 |
+
|
| 161 |
+
daemon: bool, running the watchdog thread in daemon mode or not.
|
| 162 |
+
A daemon thread will not block a process to stop.
|
| 163 |
+
log_event: Callable[[Dict[str, str]], None], an optional callback for
|
| 164 |
+
logging the events in JSON format.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
file_path: str,
|
| 170 |
+
run_id: str,
|
| 171 |
+
max_interval: float = 10,
|
| 172 |
+
daemon: bool = True,
|
| 173 |
+
log_event: Optional[Callable[[str, Optional[FileTimerRequest]], None]] = None,
|
| 174 |
+
) -> None:
|
| 175 |
+
self._file_path = file_path
|
| 176 |
+
self._run_id = run_id
|
| 177 |
+
self._max_interval = max_interval
|
| 178 |
+
self._daemon = daemon
|
| 179 |
+
self._timers: Dict[Tuple[int, str], FileTimerRequest] = {}
|
| 180 |
+
self._stop_signaled = False
|
| 181 |
+
self._watchdog_thread: Optional[threading.Thread] = None
|
| 182 |
+
if os.path.exists(self._file_path):
|
| 183 |
+
os.remove(self._file_path)
|
| 184 |
+
os.mkfifo(self._file_path)
|
| 185 |
+
# For test only. Count the number of requests received.
|
| 186 |
+
self._request_count = 0
|
| 187 |
+
# For test only. Process all requests and stop the server.
|
| 188 |
+
self._run_once = False
|
| 189 |
+
self._log_event = (
|
| 190 |
+
log_event if log_event is not None else lambda name, request: None
|
| 191 |
+
)
|
| 192 |
+
self._last_progress_time = int(time.time())
|
| 193 |
+
|
| 194 |
+
def start(self) -> None:
|
| 195 |
+
logger.info(
|
| 196 |
+
"Starting %s... max_interval=%s, daemon=%s, file_path=%s",
|
| 197 |
+
type(self).__name__,
|
| 198 |
+
self._max_interval,
|
| 199 |
+
self._daemon,
|
| 200 |
+
self._file_path,
|
| 201 |
+
)
|
| 202 |
+
self._watchdog_thread = threading.Thread(
|
| 203 |
+
target=self._watchdog_loop, daemon=self._daemon
|
| 204 |
+
)
|
| 205 |
+
logger.info("Starting watchdog thread...")
|
| 206 |
+
self._watchdog_thread.start()
|
| 207 |
+
self._log_event("watchdog started", None)
|
| 208 |
+
|
| 209 |
+
def stop(self) -> None:
|
| 210 |
+
logger.info("Stopping %s", type(self).__name__)
|
| 211 |
+
self._stop_signaled = True
|
| 212 |
+
if self._watchdog_thread:
|
| 213 |
+
logger.info("Stopping watchdog thread...")
|
| 214 |
+
self._watchdog_thread.join(self._max_interval)
|
| 215 |
+
self._watchdog_thread = None
|
| 216 |
+
else:
|
| 217 |
+
logger.info("No watchdog thread running, doing nothing")
|
| 218 |
+
if os.path.exists(self._file_path):
|
| 219 |
+
os.remove(self._file_path)
|
| 220 |
+
self._log_event("watchdog stopped", None)
|
| 221 |
+
|
| 222 |
+
def run_once(self) -> None:
|
| 223 |
+
self._run_once = True
|
| 224 |
+
if self._watchdog_thread:
|
| 225 |
+
logger.info("Stopping watchdog thread...")
|
| 226 |
+
self._watchdog_thread.join()
|
| 227 |
+
self._watchdog_thread = None
|
| 228 |
+
else:
|
| 229 |
+
logger.info("No watchdog thread running, doing nothing")
|
| 230 |
+
if os.path.exists(self._file_path):
|
| 231 |
+
os.remove(self._file_path)
|
| 232 |
+
|
| 233 |
+
@staticmethod
|
| 234 |
+
def is_process_running(pid: int):
|
| 235 |
+
"""
|
| 236 |
+
function to check process is running or not
|
| 237 |
+
"""
|
| 238 |
+
try:
|
| 239 |
+
# Check if the process exists and we can send signals to it
|
| 240 |
+
os.kill(pid, 0)
|
| 241 |
+
return True
|
| 242 |
+
except OSError:
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
def _watchdog_loop(self) -> None:
|
| 246 |
+
# Open the pipe in blocking mode blocks the server thread.
|
| 247 |
+
# This is fine for the following reasons:
|
| 248 |
+
# 1. No client case usually does not happen.
|
| 249 |
+
# 2. We are running the watchdog loop in a separate daemon
|
| 250 |
+
# thread, which will not block the process to stop.
|
| 251 |
+
with open(self._file_path) as fd:
|
| 252 |
+
while not self._stop_signaled:
|
| 253 |
+
try:
|
| 254 |
+
run_once = self._run_once
|
| 255 |
+
self._run_watchdog(fd)
|
| 256 |
+
if run_once:
|
| 257 |
+
break
|
| 258 |
+
self._last_progress_time = int(time.time())
|
| 259 |
+
except Exception:
|
| 260 |
+
logger.exception("Error running watchdog")
|
| 261 |
+
|
| 262 |
+
def _run_watchdog(self, fd: io.TextIOWrapper) -> None:
|
| 263 |
+
timer_requests = self._get_requests(fd, self._max_interval)
|
| 264 |
+
self.register_timers(timer_requests)
|
| 265 |
+
now = time.time()
|
| 266 |
+
reaped_worker_pids = set()
|
| 267 |
+
|
| 268 |
+
all_expired_timers = self.get_expired_timers(now)
|
| 269 |
+
log_debug_info_for_expired_timers(
|
| 270 |
+
self._run_id,
|
| 271 |
+
{
|
| 272 |
+
pid: self._get_scopes(expired_timers)
|
| 273 |
+
for pid, expired_timers in all_expired_timers.items()
|
| 274 |
+
},
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
for worker_pid, expired_timers in all_expired_timers.items():
|
| 278 |
+
logger.info(
|
| 279 |
+
"Reaping worker_pid=[%s]. Expired timers: %s",
|
| 280 |
+
worker_pid,
|
| 281 |
+
self._get_scopes(expired_timers),
|
| 282 |
+
)
|
| 283 |
+
reaped_worker_pids.add(worker_pid)
|
| 284 |
+
# In case we have multiple expired timers, we find the first timer
|
| 285 |
+
# with a valid signal (>0) in the expiration time order.
|
| 286 |
+
expired_timers.sort(key=lambda timer: timer.expiration_time)
|
| 287 |
+
signal = 0
|
| 288 |
+
expired_timer = None
|
| 289 |
+
for timer in expired_timers:
|
| 290 |
+
self._log_event("timer expired", timer)
|
| 291 |
+
if timer.signal > 0:
|
| 292 |
+
signal = timer.signal
|
| 293 |
+
expired_timer = timer
|
| 294 |
+
break
|
| 295 |
+
if signal <= 0:
|
| 296 |
+
logger.info(
|
| 297 |
+
"No signal specified with worker=[%s]. Do not reap it.", worker_pid
|
| 298 |
+
)
|
| 299 |
+
continue
|
| 300 |
+
if self._reap_worker(worker_pid, signal):
|
| 301 |
+
logger.info(
|
| 302 |
+
"Successfully reaped worker=[%s] with signal=%s", worker_pid, signal
|
| 303 |
+
)
|
| 304 |
+
self._log_event("kill worker process", expired_timer)
|
| 305 |
+
else:
|
| 306 |
+
logger.error(
|
| 307 |
+
"Error reaping worker=[%s]. Will retry on next watchdog.",
|
| 308 |
+
worker_pid,
|
| 309 |
+
)
|
| 310 |
+
self.clear_timers(reaped_worker_pids)
|
| 311 |
+
|
| 312 |
+
def _get_scopes(self, timer_requests: List[FileTimerRequest]) -> List[str]:
|
| 313 |
+
return [r.scope_id for r in timer_requests]
|
| 314 |
+
|
| 315 |
+
def _get_requests(
|
| 316 |
+
self, fd: io.TextIOWrapper, max_interval: float
|
| 317 |
+
) -> List[FileTimerRequest]:
|
| 318 |
+
start = time.time()
|
| 319 |
+
requests = []
|
| 320 |
+
while not self._stop_signaled or self._run_once:
|
| 321 |
+
# For named pipe, readline() is blocking when at least one writer opens.
|
| 322 |
+
# It returns only when flush() is called at the writer side.
|
| 323 |
+
# Note that flush() is automatically called inside close().
|
| 324 |
+
# After the last writer closes, readline() is not blocking.
|
| 325 |
+
# It will return an empty string when it's at end-of-file.
|
| 326 |
+
# Since the client side always opens the pipe, writes a message and closes
|
| 327 |
+
# the pipe immediately, the readline() call below is not blocking for long.
|
| 328 |
+
json_request = fd.readline()
|
| 329 |
+
if len(json_request) == 0:
|
| 330 |
+
if self._run_once:
|
| 331 |
+
break
|
| 332 |
+
time.sleep(min(max_interval, 1))
|
| 333 |
+
else:
|
| 334 |
+
request = json.loads(json_request)
|
| 335 |
+
pid = request["pid"]
|
| 336 |
+
scope_id = request["scope_id"]
|
| 337 |
+
expiration_time = request["expiration_time"]
|
| 338 |
+
signal = request["signal"]
|
| 339 |
+
requests.append(
|
| 340 |
+
FileTimerRequest(
|
| 341 |
+
worker_pid=pid,
|
| 342 |
+
scope_id=scope_id,
|
| 343 |
+
expiration_time=expiration_time,
|
| 344 |
+
signal=signal,
|
| 345 |
+
)
|
| 346 |
+
)
|
| 347 |
+
now = time.time()
|
| 348 |
+
if now - start > max_interval:
|
| 349 |
+
break
|
| 350 |
+
return requests
|
| 351 |
+
|
| 352 |
+
def register_timers(self, timer_requests: List[FileTimerRequest]) -> None:
|
| 353 |
+
for request in timer_requests:
|
| 354 |
+
pid = request.worker_pid
|
| 355 |
+
scope_id = request.scope_id
|
| 356 |
+
expiration_time = request.expiration_time
|
| 357 |
+
self._request_count += 1
|
| 358 |
+
|
| 359 |
+
key = (pid, scope_id)
|
| 360 |
+
# negative expiration is a proxy for a release call
|
| 361 |
+
if expiration_time < 0:
|
| 362 |
+
if key in self._timers:
|
| 363 |
+
del self._timers[key]
|
| 364 |
+
else:
|
| 365 |
+
self._timers[key] = request
|
| 366 |
+
|
| 367 |
+
def clear_timers(self, worker_pids: Set[int]) -> None:
|
| 368 |
+
for pid, scope_id in list(self._timers.keys()):
|
| 369 |
+
if pid in worker_pids or not FileTimerServer.is_process_running(pid):
|
| 370 |
+
del self._timers[(pid, scope_id)]
|
| 371 |
+
|
| 372 |
+
def get_expired_timers(self, deadline: float) -> Dict[int, List[FileTimerRequest]]:
|
| 373 |
+
# pid -> [timer_requests...]
|
| 374 |
+
expired_timers: Dict[int, List[FileTimerRequest]] = {}
|
| 375 |
+
for request in self._timers.values():
|
| 376 |
+
if request.expiration_time <= deadline:
|
| 377 |
+
expired_scopes = expired_timers.setdefault(request.worker_pid, [])
|
| 378 |
+
expired_scopes.append(request)
|
| 379 |
+
return expired_timers
|
| 380 |
+
|
| 381 |
+
def _reap_worker(self, worker_pid: int, signal: int) -> bool:
|
| 382 |
+
try:
|
| 383 |
+
os.kill(worker_pid, signal)
|
| 384 |
+
return True
|
| 385 |
+
except ProcessLookupError:
|
| 386 |
+
logger.info("Process with pid=%s does not exist. Skipping", worker_pid)
|
| 387 |
+
return True
|
| 388 |
+
except Exception:
|
| 389 |
+
logger.exception("Error terminating pid=%s", worker_pid)
|
| 390 |
+
return False
|
| 391 |
+
|
| 392 |
+
def get_last_progress_time(self) -> int:
|
| 393 |
+
return self._last_progress_time
|
vllm/lib/python3.10/site-packages/torch/distributed/elastic/timer/local_timer.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
# All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# This source code is licensed under the BSD-style license found in the
|
| 6 |
+
# LICENSE file in the root directory of this source tree.
|
| 7 |
+
import logging
|
| 8 |
+
import multiprocessing as mp
|
| 9 |
+
import os
|
| 10 |
+
import signal
|
| 11 |
+
import time
|
| 12 |
+
from queue import Empty
|
| 13 |
+
from typing import Any, Dict, List, Set, Tuple
|
| 14 |
+
|
| 15 |
+
from .api import RequestQueue, TimerClient, TimerRequest, TimerServer
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["LocalTimerClient", "MultiprocessingRequestQueue", "LocalTimerServer"]
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class LocalTimerClient(TimerClient):
|
| 24 |
+
"""
|
| 25 |
+
Client side of ``LocalTimerServer``. This client is meant to be used
|
| 26 |
+
on the same host that the ``LocalTimerServer`` is running on and uses
|
| 27 |
+
pid to uniquely identify a worker. This is particularly useful in situations
|
| 28 |
+
where one spawns a subprocess (trainer) per GPU on a host with multiple
|
| 29 |
+
GPU devices.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, mp_queue):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self._mp_queue = mp_queue
|
| 35 |
+
|
| 36 |
+
def acquire(self, scope_id, expiration_time):
|
| 37 |
+
pid = os.getpid()
|
| 38 |
+
acquire_request = TimerRequest(pid, scope_id, expiration_time)
|
| 39 |
+
self._mp_queue.put(acquire_request)
|
| 40 |
+
|
| 41 |
+
def release(self, scope_id):
|
| 42 |
+
pid = os.getpid()
|
| 43 |
+
release_request = TimerRequest(pid, scope_id, -1)
|
| 44 |
+
self._mp_queue.put(release_request)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class MultiprocessingRequestQueue(RequestQueue):
|
| 48 |
+
"""
|
| 49 |
+
A ``RequestQueue`` backed by python ``multiprocessing.Queue``
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, mp_queue: mp.Queue):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self._mp_queue = mp_queue
|
| 55 |
+
|
| 56 |
+
def size(self) -> int:
|
| 57 |
+
return self._mp_queue.qsize()
|
| 58 |
+
|
| 59 |
+
def get(self, size, timeout: float) -> List[TimerRequest]:
|
| 60 |
+
requests = []
|
| 61 |
+
wait = timeout
|
| 62 |
+
for _ in range(0, size):
|
| 63 |
+
start = time.time()
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
r = self._mp_queue.get(block=True, timeout=wait)
|
| 67 |
+
except Empty:
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
requests.append(r)
|
| 71 |
+
wait = wait - (time.time() - start)
|
| 72 |
+
if wait <= 0:
|
| 73 |
+
break
|
| 74 |
+
|
| 75 |
+
return requests
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class LocalTimerServer(TimerServer):
|
| 79 |
+
"""
|
| 80 |
+
Server that works with ``LocalTimerClient``. Clients are expected to be
|
| 81 |
+
subprocesses to the parent process that is running this server. Each host
|
| 82 |
+
in the job is expected to start its own timer server locally and each
|
| 83 |
+
server instance manages timers for local workers (running on processes
|
| 84 |
+
on the same host).
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self, mp_queue: mp.Queue, max_interval: float = 60, daemon: bool = True
|
| 89 |
+
):
|
| 90 |
+
super().__init__(MultiprocessingRequestQueue(mp_queue), max_interval, daemon)
|
| 91 |
+
self._timers: Dict[Tuple[Any, str], TimerRequest] = {}
|
| 92 |
+
|
| 93 |
+
def register_timers(self, timer_requests: List[TimerRequest]) -> None:
|
| 94 |
+
for request in timer_requests:
|
| 95 |
+
pid = request.worker_id
|
| 96 |
+
scope_id = request.scope_id
|
| 97 |
+
expiration_time = request.expiration_time
|
| 98 |
+
|
| 99 |
+
# negative expiration is a proxy for a release call
|
| 100 |
+
if expiration_time < 0:
|
| 101 |
+
self._timers.pop((pid, scope_id), None)
|
| 102 |
+
else:
|
| 103 |
+
self._timers[(pid, scope_id)] = request
|
| 104 |
+
|
| 105 |
+
def clear_timers(self, worker_ids: Set[int]) -> None:
|
| 106 |
+
for pid, scope_id in list(self._timers.keys()):
|
| 107 |
+
if pid in worker_ids:
|
| 108 |
+
self._timers.pop((pid, scope_id))
|
| 109 |
+
|
| 110 |
+
def get_expired_timers(self, deadline: float) -> Dict[Any, List[TimerRequest]]:
|
| 111 |
+
# pid -> [timer_requests...]
|
| 112 |
+
expired_timers: Dict[Any, List[TimerRequest]] = {}
|
| 113 |
+
for request in self._timers.values():
|
| 114 |
+
if request.expiration_time <= deadline:
|
| 115 |
+
expired_scopes = expired_timers.setdefault(request.worker_id, [])
|
| 116 |
+
expired_scopes.append(request)
|
| 117 |
+
return expired_timers
|
| 118 |
+
|
| 119 |
+
def _reap_worker(self, worker_id: int) -> bool:
|
| 120 |
+
try:
|
| 121 |
+
os.kill(worker_id, signal.SIGKILL)
|
| 122 |
+
return True
|
| 123 |
+
except ProcessLookupError:
|
| 124 |
+
logger.info("Process with pid=%s does not exist. Skipping", worker_id)
|
| 125 |
+
return True
|
| 126 |
+
except Exception:
|
| 127 |
+
logger.exception("Error terminating pid=%s", worker_id)
|
| 128 |
+
return False
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed.tensor._ops # force import all built-in dtensor ops
|
| 5 |
+
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh # noqa: F401
|
| 6 |
+
from torch.distributed.tensor._api import (
|
| 7 |
+
distribute_module,
|
| 8 |
+
distribute_tensor,
|
| 9 |
+
DTensor,
|
| 10 |
+
empty,
|
| 11 |
+
full,
|
| 12 |
+
ones,
|
| 13 |
+
rand,
|
| 14 |
+
randn,
|
| 15 |
+
zeros,
|
| 16 |
+
)
|
| 17 |
+
from torch.distributed.tensor.placement_types import (
|
| 18 |
+
Partial,
|
| 19 |
+
Placement,
|
| 20 |
+
Replicate,
|
| 21 |
+
Shard,
|
| 22 |
+
)
|
| 23 |
+
from torch.optim.optimizer import (
|
| 24 |
+
_foreach_supported_types as _optim_foreach_supported_types,
|
| 25 |
+
)
|
| 26 |
+
from torch.utils._foreach_utils import (
|
| 27 |
+
_foreach_supported_types as _util_foreach_supported_types,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# All public APIs from dtensor package
|
| 32 |
+
__all__ = [
|
| 33 |
+
"DTensor",
|
| 34 |
+
"distribute_tensor",
|
| 35 |
+
"distribute_module",
|
| 36 |
+
"Shard",
|
| 37 |
+
"Replicate",
|
| 38 |
+
"Partial",
|
| 39 |
+
"Placement",
|
| 40 |
+
"ones",
|
| 41 |
+
"empty",
|
| 42 |
+
"full",
|
| 43 |
+
"rand",
|
| 44 |
+
"randn",
|
| 45 |
+
"zeros",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Append DTensor to the list of supported types for foreach implementation for optimizer
|
| 50 |
+
# and clip_grad_norm_ so that we will try to use foreach over the for-loop implementation on CUDA.
|
| 51 |
+
if DTensor not in _optim_foreach_supported_types:
|
| 52 |
+
_optim_foreach_supported_types.append(DTensor)
|
| 53 |
+
|
| 54 |
+
if DTensor not in _util_foreach_supported_types:
|
| 55 |
+
_util_foreach_supported_types.append(DTensor)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Set namespace for exposed private names
|
| 59 |
+
DTensor.__module__ = "torch.distributed.tensor"
|
| 60 |
+
distribute_tensor.__module__ = "torch.distributed.tensor"
|
| 61 |
+
distribute_module.__module__ = "torch.distributed.tensor"
|
| 62 |
+
ones.__module__ = "torch.distributed.tensor"
|
| 63 |
+
empty.__module__ = "torch.distributed.tensor"
|
| 64 |
+
full.__module__ = "torch.distributed.tensor"
|
| 65 |
+
rand.__module__ = "torch.distributed.tensor"
|
| 66 |
+
randn.__module__ = "torch.distributed.tensor"
|
| 67 |
+
zeros.__module__ = "torch.distributed.tensor"
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-310.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_api.py
ADDED
|
@@ -0,0 +1,1231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 4 |
+
import inspect
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Any, Callable, cast, Optional, Sequence, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed.tensor._dispatch as op_dispatch
|
| 10 |
+
import torch.distributed.tensor._random as random
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
|
| 13 |
+
from torch.distributed.tensor._collective_utils import check_tensor_meta, mesh_broadcast
|
| 14 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
|
| 15 |
+
from torch.distributed.tensor._random import (
|
| 16 |
+
is_rng_supported_mesh,
|
| 17 |
+
OffsetBasedRNGTracker,
|
| 18 |
+
)
|
| 19 |
+
from torch.distributed.tensor._redistribute import (
|
| 20 |
+
Redistribute,
|
| 21 |
+
redistribute_local_tensor,
|
| 22 |
+
)
|
| 23 |
+
from torch.distributed.tensor._utils import (
|
| 24 |
+
compute_global_tensor_info,
|
| 25 |
+
compute_local_shape,
|
| 26 |
+
normalize_to_torch_size,
|
| 27 |
+
)
|
| 28 |
+
from torch.distributed.tensor.placement_types import (
|
| 29 |
+
Partial,
|
| 30 |
+
Placement,
|
| 31 |
+
Replicate,
|
| 32 |
+
Shard,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
"DTensor",
|
| 38 |
+
"distribute_tensor",
|
| 39 |
+
"distribute_module",
|
| 40 |
+
"ones",
|
| 41 |
+
"empty",
|
| 42 |
+
"full",
|
| 43 |
+
"rand",
|
| 44 |
+
"randn",
|
| 45 |
+
"zeros",
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
aten = torch.ops.aten
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# NOTE [Autograd interaction between torch.Tensor]
|
| 52 |
+
#
|
| 53 |
+
# The autograd functions defined below are being used by the public
|
| 54 |
+
# facing APIs (i.e. from_local, to_local) to ensure DTensor to work
|
| 55 |
+
# together with torch.Tensor within the autograd engine. This
|
| 56 |
+
# allows DTensor to only exist on part of the module hierarchy.
|
| 57 |
+
#
|
| 58 |
+
# As an example, we have the a module that consists of submodules
|
| 59 |
+
# A, B, and C, the execution flow would be like:
|
| 60 |
+
# input(torch.Tensor) -> Module A -> Module B -> Module C -> output (torch.Tensor)
|
| 61 |
+
#
|
| 62 |
+
# Suppose I only want to make Module B be a sharded module with
|
| 63 |
+
# DTensor params, the following forward/backward should work:
|
| 64 |
+
#
|
| 65 |
+
# input(torch.Tensor) -> Module A
|
| 66 |
+
# -> DTensor input (from_local) -> Sharded Module B -> DTensor output
|
| 67 |
+
# -> torch.Tensor output (to_local) -> Module C
|
| 68 |
+
#
|
| 69 |
+
# So from_local/to_local must be Autograd functions.
|
| 70 |
+
#
|
| 71 |
+
class _ToTorchTensor(torch.autograd.Function):
|
| 72 |
+
@staticmethod
|
| 73 |
+
def forward( # type: ignore[override]
|
| 74 |
+
ctx,
|
| 75 |
+
input: "DTensor",
|
| 76 |
+
grad_placements: Optional[Sequence[Placement]],
|
| 77 |
+
):
|
| 78 |
+
ctx.dtensor_spec = input._spec
|
| 79 |
+
ctx.grad_placements = grad_placements
|
| 80 |
+
local_tensor = input._local_tensor
|
| 81 |
+
|
| 82 |
+
# We need to return a fresh Tensor object there as autograd metadata
|
| 83 |
+
# will be inplaced into it. So we don't want to pollute the Tensor
|
| 84 |
+
# object stored in the _local_tensor of this DTensor.
|
| 85 |
+
return local_tensor.view_as(local_tensor)
|
| 86 |
+
|
| 87 |
+
@staticmethod
|
| 88 |
+
def backward(ctx, grad_output: torch.Tensor): # type: ignore[override]
|
| 89 |
+
dtensor_spec = ctx.dtensor_spec
|
| 90 |
+
mesh = dtensor_spec.mesh
|
| 91 |
+
grad_placements = ctx.grad_placements
|
| 92 |
+
dtensor_meta = dtensor_spec.tensor_meta
|
| 93 |
+
|
| 94 |
+
_, tensor_stride = compute_global_tensor_info(
|
| 95 |
+
grad_output, mesh, dtensor_spec.placements
|
| 96 |
+
)
|
| 97 |
+
tensor_stride = tuple(tensor_stride)
|
| 98 |
+
grad_placements = grad_placements or dtensor_spec.placements
|
| 99 |
+
grad_spec = DTensorSpec(
|
| 100 |
+
mesh,
|
| 101 |
+
grad_placements,
|
| 102 |
+
tensor_meta=TensorMeta(
|
| 103 |
+
shape=dtensor_meta.shape,
|
| 104 |
+
stride=tensor_stride,
|
| 105 |
+
dtype=dtensor_meta.dtype,
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
return (
|
| 110 |
+
DTensor(
|
| 111 |
+
grad_output,
|
| 112 |
+
grad_spec,
|
| 113 |
+
requires_grad=grad_output.requires_grad,
|
| 114 |
+
),
|
| 115 |
+
None,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class _FromTorchTensor(torch.autograd.Function):
|
| 120 |
+
@staticmethod
|
| 121 |
+
def forward( # type: ignore[override]
|
| 122 |
+
ctx, # pyre-ignore[2]: Parameter must be annotated.
|
| 123 |
+
input: torch.Tensor,
|
| 124 |
+
device_mesh: DeviceMesh,
|
| 125 |
+
placements: Tuple[Placement, ...],
|
| 126 |
+
run_check: bool,
|
| 127 |
+
shape: Optional[torch.Size] = None,
|
| 128 |
+
stride: Optional[Tuple[int, ...]] = None,
|
| 129 |
+
) -> "DTensor":
|
| 130 |
+
ctx.previous_placement = placements
|
| 131 |
+
ctx.previous_device_mesh = device_mesh
|
| 132 |
+
|
| 133 |
+
if shape and stride:
|
| 134 |
+
tensor_shape, tensor_stride = shape, stride
|
| 135 |
+
elif not shape and not stride:
|
| 136 |
+
# if it's not by default run_check, we assume user is certain that each
|
| 137 |
+
# rank has the same tensor shape, and we just use that to calculate the
|
| 138 |
+
# global shape
|
| 139 |
+
global_shape, global_stride = compute_global_tensor_info(
|
| 140 |
+
input, device_mesh, placements
|
| 141 |
+
)
|
| 142 |
+
tensor_shape, tensor_stride = torch.Size(global_shape), tuple(global_stride)
|
| 143 |
+
else:
|
| 144 |
+
raise RuntimeError(
|
| 145 |
+
f"Found shape:{shape}, stride:{stride}.",
|
| 146 |
+
"Please pass both shape and stride at the same time.",
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
if device_mesh.get_coordinate() is None:
|
| 150 |
+
# if the global rank is not participating in the device mesh, we
|
| 151 |
+
# simply set the local tensor to an empty tensor
|
| 152 |
+
input = input.new_empty(0, requires_grad=input.requires_grad)
|
| 153 |
+
elif run_check:
|
| 154 |
+
# TODO: support uneven sharding when global shape/stride not passed, by
|
| 155 |
+
# building the global TensorMeta during check_tensor_meta
|
| 156 |
+
check_shape_stride = not shape and not stride
|
| 157 |
+
check_tensor_meta(input, check_shape_stride=check_shape_stride)
|
| 158 |
+
# TODO: See if we need to make this run_check logic
|
| 159 |
+
# have a corresponding backward.
|
| 160 |
+
for idx, placement in enumerate(placements):
|
| 161 |
+
if placement.is_replicate():
|
| 162 |
+
# broadcast rank 0 tensor to all ranks
|
| 163 |
+
# only broadcast if run_check is True
|
| 164 |
+
input = input.contiguous()
|
| 165 |
+
mesh_broadcast(input, device_mesh, mesh_dim=idx)
|
| 166 |
+
|
| 167 |
+
dist_spec = DTensorSpec(
|
| 168 |
+
device_mesh,
|
| 169 |
+
placements,
|
| 170 |
+
tensor_meta=TensorMeta(
|
| 171 |
+
tensor_shape,
|
| 172 |
+
tensor_stride,
|
| 173 |
+
input.dtype,
|
| 174 |
+
),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# We want a fresh Tensor object that shares memory with the input tensor
|
| 178 |
+
dist_tensor = DTensor(
|
| 179 |
+
input.view_as(input),
|
| 180 |
+
dist_spec,
|
| 181 |
+
# requires_grad of the dist tensor depends on if input
|
| 182 |
+
# requires_grad or not
|
| 183 |
+
requires_grad=input.requires_grad,
|
| 184 |
+
)
|
| 185 |
+
return dist_tensor
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def backward(ctx, grad_output: "DTensor"): # type: ignore[override]
|
| 189 |
+
previous_placement = ctx.previous_placement
|
| 190 |
+
previous_device_mesh = ctx.previous_device_mesh
|
| 191 |
+
|
| 192 |
+
# reshard to the placement when creating DistributedTensor
|
| 193 |
+
# so that the gradient layout matches, and we could return
|
| 194 |
+
# local gradients directly
|
| 195 |
+
if grad_output.placements != previous_placement:
|
| 196 |
+
current_spec = grad_output._spec
|
| 197 |
+
target_spec = DTensorSpec(
|
| 198 |
+
previous_device_mesh,
|
| 199 |
+
previous_placement,
|
| 200 |
+
tensor_meta=grad_output._spec.tensor_meta,
|
| 201 |
+
)
|
| 202 |
+
local_tensor = grad_output._local_tensor
|
| 203 |
+
output = redistribute_local_tensor(
|
| 204 |
+
local_tensor, current_spec, target_spec, is_backward=True
|
| 205 |
+
)
|
| 206 |
+
# TODO: return the redistributed local tensor directly without
|
| 207 |
+
# differentiable backward. see if this make sense for all cases.
|
| 208 |
+
return output, None, None, None, None, None
|
| 209 |
+
|
| 210 |
+
# TODO: backward is also differentiable now, add a test
|
| 211 |
+
# to test higher level gradients.
|
| 212 |
+
return grad_output.to_local(), None, None, None, None, None
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class DTensor(torch.Tensor):
|
| 216 |
+
"""
|
| 217 |
+
``DTensor`` (Distributed Tensor) is a subclass of ``torch.Tensor`` that provides single-device like
|
| 218 |
+
abstraction to program with multi-device ``torch.Tensor``. It describes the distributed tensor sharding
|
| 219 |
+
layout (DTensor Layout) through the :class:`DeviceMesh` and following types of :class:`Placement`:
|
| 220 |
+
|
| 221 |
+
* :class:`Shard`: Tensor sharded on the tensor dimension ``dim`` on the devices of the ``DeviceMesh`` dimension
|
| 222 |
+
* :class:`Replicate`: Tensor replicated on the devices of the ``DeviceMesh`` dimension
|
| 223 |
+
* :class:`Partial`: Tensor is pending reduction on the devices of the ``DeviceMesh`` dimension
|
| 224 |
+
|
| 225 |
+
When calling PyTorch operators, ``DTensor`` overrides the PyTorch operators to perform sharded computation and issue
|
| 226 |
+
communications whenever necessary. Along with the operator computation, ``DTensor`` will transform or propagate the
|
| 227 |
+
placements (DTensor Layout) properly (based on the operator semantic itself) and generate new ``DTensor`` outputs.
|
| 228 |
+
|
| 229 |
+
To ensure numerical correctness of the ``DTensor`` sharded computation when calling PyTorch operators, ``DTensor``
|
| 230 |
+
requires every Tensor argument of the operator be DTensor.
|
| 231 |
+
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
_local_tensor: torch.Tensor
|
| 235 |
+
_spec: DTensorSpec
|
| 236 |
+
__slots__ = ["_local_tensor", "_spec"]
|
| 237 |
+
|
| 238 |
+
# _op_dispatcher instance as a class attribute to handle runtime dispatching logic
|
| 239 |
+
_op_dispatcher: op_dispatch.OpDispatcher = op_dispatch.OpDispatcher()
|
| 240 |
+
|
| 241 |
+
@staticmethod
|
| 242 |
+
@torch._disable_dynamo
|
| 243 |
+
def __new__(
|
| 244 |
+
cls,
|
| 245 |
+
local_tensor: torch.Tensor,
|
| 246 |
+
spec: DTensorSpec,
|
| 247 |
+
*,
|
| 248 |
+
requires_grad: bool,
|
| 249 |
+
) -> "DTensor":
|
| 250 |
+
"""
|
| 251 |
+
Construct a DTensor from a local tensor, device mesh, and placement and
|
| 252 |
+
other tensor properties (i.e. shape, requires_grad, strides, etc).
|
| 253 |
+
|
| 254 |
+
.. note:: This is not a public API and it's only supposed to be used by the
|
| 255 |
+
operator implementations and internals. If you want to construct a
|
| 256 |
+
DTensor from a local tensor, consider using ``DTensor.from_local``, if
|
| 257 |
+
you want to construct a DTensor from a "global" tensor (where you
|
| 258 |
+
already have tensor initialized and want to shard this tensor),
|
| 259 |
+
consider using ``distribute_tensor``.
|
| 260 |
+
"""
|
| 261 |
+
if local_tensor.requires_grad and not requires_grad:
|
| 262 |
+
warnings.warn(
|
| 263 |
+
"To construct DTensor from torch.Tensor, it's recommended to "
|
| 264 |
+
"use local_tensor.detach() and make requires_grad consistent."
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# new method instruct wrapper tensor from local_tensor and add
|
| 268 |
+
# placement spec, it does not do actual distribution
|
| 269 |
+
assert spec.tensor_meta is not None, "TensorMeta should not be None!"
|
| 270 |
+
r = torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined]
|
| 271 |
+
cls,
|
| 272 |
+
spec.tensor_meta.shape,
|
| 273 |
+
strides=spec.tensor_meta.stride,
|
| 274 |
+
dtype=local_tensor.dtype,
|
| 275 |
+
device=local_tensor.device,
|
| 276 |
+
layout=local_tensor.layout,
|
| 277 |
+
requires_grad=requires_grad,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
r._spec = spec
|
| 281 |
+
r._local_tensor = local_tensor
|
| 282 |
+
return r
|
| 283 |
+
|
| 284 |
+
# pyre-fixme[14]: `__repr__` overrides method defined in `DTensor` inconsistently.
|
| 285 |
+
# pyre-fixme[3]: Return type must be annotated.
|
| 286 |
+
def __repr__(self):
|
| 287 |
+
# TODO: consider all_gather the local tensors for better debugging
|
| 288 |
+
return f"DTensor(local_tensor={self._local_tensor}, device_mesh={self._spec.mesh}, placements={self._spec.placements})"
|
| 289 |
+
|
| 290 |
+
def __tensor_flatten__(self):
|
| 291 |
+
"""
|
| 292 |
+
protocol to inform how to flatten a DTensor to local tensor
|
| 293 |
+
for PT2 tracing
|
| 294 |
+
"""
|
| 295 |
+
return ["_local_tensor"], (self._spec, self.requires_grad)
|
| 296 |
+
|
| 297 |
+
@staticmethod
|
| 298 |
+
def __tensor_unflatten__(inner_tensors, flatten_spec, outer_size, outer_stride):
|
| 299 |
+
assert (
|
| 300 |
+
flatten_spec is not None
|
| 301 |
+
), "Expecting spec to be not None from `__tensor_flatten__` return value!"
|
| 302 |
+
local_tensor = inner_tensors["_local_tensor"]
|
| 303 |
+
spec, requires_grad = flatten_spec
|
| 304 |
+
unflatten_tensor_meta = TensorMeta(
|
| 305 |
+
shape=outer_size,
|
| 306 |
+
stride=outer_stride,
|
| 307 |
+
dtype=spec.tensor_meta.dtype,
|
| 308 |
+
)
|
| 309 |
+
unflatten_spec = DTensorSpec(
|
| 310 |
+
spec.mesh,
|
| 311 |
+
spec.placements,
|
| 312 |
+
tensor_meta=unflatten_tensor_meta,
|
| 313 |
+
)
|
| 314 |
+
return DTensor(
|
| 315 |
+
local_tensor,
|
| 316 |
+
unflatten_spec,
|
| 317 |
+
requires_grad=requires_grad,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def __coerce_tangent_metadata__(self):
|
| 321 |
+
if not any(isinstance(p, Partial) for p in self.placements):
|
| 322 |
+
return self
|
| 323 |
+
placements = [
|
| 324 |
+
Replicate() if isinstance(p, Partial) else p for p in self.placements
|
| 325 |
+
]
|
| 326 |
+
return self.redistribute(device_mesh=self.device_mesh, placements=placements)
|
| 327 |
+
|
| 328 |
+
def __coerce_same_metadata_as_tangent__(self, flatten_spec):
|
| 329 |
+
(spec, _) = flatten_spec # Result of tensor_flatten()
|
| 330 |
+
return self.redistribute(
|
| 331 |
+
device_mesh=self.device_mesh,
|
| 332 |
+
placements=spec.placements,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@classmethod
|
| 336 |
+
@torch._disable_dynamo
|
| 337 |
+
# pyre-fixme[3]: Return type must be annotated.
|
| 338 |
+
# pyre-fixme[2]: Parameter must be annotated.
|
| 339 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 340 |
+
return DTensor._op_dispatcher.dispatch(
|
| 341 |
+
func,
|
| 342 |
+
args,
|
| 343 |
+
kwargs or {},
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
@staticmethod
|
| 347 |
+
def from_local(
|
| 348 |
+
local_tensor: torch.Tensor,
|
| 349 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 350 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 351 |
+
*,
|
| 352 |
+
run_check: bool = False,
|
| 353 |
+
shape: Optional[torch.Size] = None,
|
| 354 |
+
stride: Optional[Tuple[int, ...]] = None,
|
| 355 |
+
) -> "DTensor":
|
| 356 |
+
"""
|
| 357 |
+
Create a :class:`DTensor` from a local torch.Tensor on each rank
|
| 358 |
+
according to the ``device_mesh`` and ``placements`` specified.
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
local_tensor (torch.Tensor): local torch.Tensor on each rank.
|
| 362 |
+
device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to place the
|
| 363 |
+
tensor, if not specified, must be called under a DeviceMesh
|
| 364 |
+
context manager, default: None
|
| 365 |
+
placements (List[:class:`Placement`], optional): the placements that
|
| 366 |
+
describes how to place the local torch.Tensor on DeviceMesh, must
|
| 367 |
+
have the same number of elements as ``device_mesh.ndim``.
|
| 368 |
+
|
| 369 |
+
Keyword args:
|
| 370 |
+
run_check (bool, optional): at a cost of extra communications, perform
|
| 371 |
+
sanity check across ranks to check each local tensor's meta information
|
| 372 |
+
to ensure correctness. If have :class:`Replicate` in ``placements``, the
|
| 373 |
+
data on first rank of the device mesh dimension will be broadcasted
|
| 374 |
+
to other ranks. default: False
|
| 375 |
+
shape (torch.Size, optional): A List of int which specifies the size of
|
| 376 |
+
DTensor which build on top of `local_tensor`. Note this needs to be
|
| 377 |
+
provided if the shape of ``local_tensor`` are different across the ranks.
|
| 378 |
+
If not provided, ``shape`` will be computed assuming the given distributed
|
| 379 |
+
tensor is evenly sharded across ranks. default: None
|
| 380 |
+
stride (tuple, optional): A List of int which specifies the stride of DTensor.
|
| 381 |
+
If not provided, ``stride`` will be computed assuming the given distributed
|
| 382 |
+
tensor is evenly sharded across ranks. default: None
|
| 383 |
+
|
| 384 |
+
Returns:
|
| 385 |
+
A :class:`DTensor` object
|
| 386 |
+
|
| 387 |
+
.. note:: When ``run_check=False``, it is the user's responsibility to ensure the
|
| 388 |
+
local tensor passed in is correct across ranks (i.e. the tensor is sharded for
|
| 389 |
+
the ``Shard(dim)`` placement or replicated for the ``Replicate()`` placement).
|
| 390 |
+
If not, the behavior of the created DTensor is undefined.
|
| 391 |
+
|
| 392 |
+
.. note:: ``from_local`` is differentiable, the `requires_grad` of the created
|
| 393 |
+
`DTensor` object will depend on if `local_tensor` requires_grad or not.
|
| 394 |
+
"""
|
| 395 |
+
# if same shape/dtype, no need to run_check, if not, must allgather
|
| 396 |
+
# the metadatas to check the size/dtype across ranks
|
| 397 |
+
# There should be no data communication unless there's replication
|
| 398 |
+
# strategy, where we broadcast the replication from the first rank
|
| 399 |
+
# in the mesh dimension
|
| 400 |
+
device_mesh = device_mesh or _mesh_resources.get_current_mesh()
|
| 401 |
+
device_type = device_mesh.device_type
|
| 402 |
+
|
| 403 |
+
# convert the local tensor to desired device base on device mesh's device_type
|
| 404 |
+
if device_type != local_tensor.device.type and not local_tensor.is_meta:
|
| 405 |
+
local_tensor = local_tensor.to(device_type)
|
| 406 |
+
|
| 407 |
+
# set default placements to replicated if not specified
|
| 408 |
+
if placements is None:
|
| 409 |
+
placements = [Replicate() for _ in range(device_mesh.ndim)]
|
| 410 |
+
else:
|
| 411 |
+
placements = list(placements)
|
| 412 |
+
for idx, placement in enumerate(placements):
|
| 413 |
+
# normalize shard dim to be positive
|
| 414 |
+
if placement.is_shard():
|
| 415 |
+
placement = cast(Shard, placement)
|
| 416 |
+
if placement.dim < 0:
|
| 417 |
+
placements[idx] = Shard(placement.dim + local_tensor.ndim)
|
| 418 |
+
|
| 419 |
+
# `from_local` is differentiable, and the gradient of the dist tensor this function
|
| 420 |
+
# created should flow back the gradients to the local_tensor, so we call an autograd
|
| 421 |
+
# function to construct the dist tensor instead.
|
| 422 |
+
return _FromTorchTensor.apply( # pyre-ignore[16]: autograd func
|
| 423 |
+
local_tensor,
|
| 424 |
+
device_mesh,
|
| 425 |
+
tuple(placements),
|
| 426 |
+
run_check,
|
| 427 |
+
shape,
|
| 428 |
+
stride,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
def to_local(
|
| 432 |
+
self, *, grad_placements: Optional[Sequence[Placement]] = None
|
| 433 |
+
) -> torch.Tensor:
|
| 434 |
+
"""
|
| 435 |
+
Get the local tensor of this DTensor on its current rank. For sharding it returns
|
| 436 |
+
a local shard of the logical tensor view, for replication it returns the replica on
|
| 437 |
+
its current rank.
|
| 438 |
+
|
| 439 |
+
Keyword args:
|
| 440 |
+
grad_placements (List[:class:`Placement`], optional): the placements describes
|
| 441 |
+
the future layout of any gradient layout of the Tensor returned from this
|
| 442 |
+
function.
|
| 443 |
+
`to_local` converts DTensor to local tensor and the returned local tensor
|
| 444 |
+
might not be used as the original DTensor layout later in the code. This
|
| 445 |
+
argument is the hint that user can give to autograd in case the gradient
|
| 446 |
+
layout of the returned tensor does not match the original DTensor layout.
|
| 447 |
+
If not specified, we will assume the gradient layout remains the same
|
| 448 |
+
as the original DTensor and use that for gradient computation.
|
| 449 |
+
|
| 450 |
+
Returns:
|
| 451 |
+
A :class:`torch.Tensor` or ``AsyncCollectiveTensor`` object. it represents the
|
| 452 |
+
local tensor on its current rank. When an ``AsyncCollectiveTensor`` object is returned,
|
| 453 |
+
it means the local tensor is not ready yet (i.e. communication is not finished). In this
|
| 454 |
+
case, user needs to call ``wait`` to wait the local tensor to be ready.
|
| 455 |
+
|
| 456 |
+
.. note:: ``to_local`` is differentiable, the ``requires_grad`` of the local tensor returned
|
| 457 |
+
will depend on if the `DTensor` requires_grad or not.
|
| 458 |
+
"""
|
| 459 |
+
if not torch.is_grad_enabled():
|
| 460 |
+
return self._local_tensor
|
| 461 |
+
|
| 462 |
+
if grad_placements is not None and not isinstance(grad_placements, tuple):
|
| 463 |
+
grad_placements = tuple(grad_placements)
|
| 464 |
+
return _ToTorchTensor.apply(
|
| 465 |
+
self, grad_placements
|
| 466 |
+
) # pyre-ignore[16]: autograd func
|
| 467 |
+
|
| 468 |
+
def redistribute(
|
| 469 |
+
self,
|
| 470 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 471 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 472 |
+
*,
|
| 473 |
+
async_op: bool = False,
|
| 474 |
+
) -> "DTensor":
|
| 475 |
+
"""
|
| 476 |
+
``redistribute`` performs necessary collective operations that redistribute the current
|
| 477 |
+
DTensor from its current placements to a new placements, or from is current DeviceMesh
|
| 478 |
+
to a new DeviceMesh. i.e. we can turn a Sharded DTensor to a Replicated DTensor by
|
| 479 |
+
specifying a Replicate placement for each dimension of the DeviceMesh.
|
| 480 |
+
|
| 481 |
+
When redistributing from current to the new placements on one device mesh dimension, we
|
| 482 |
+
will perform the following operations including communication collective or local operation:
|
| 483 |
+
|
| 484 |
+
1. ``Shard(dim)`` -> ``Replicate()``: ``all_gather``
|
| 485 |
+
2. ``Shard(src_dim)`` -> ``Shard(dst_dim)``: ``all_to_all``
|
| 486 |
+
3. ``Replicate()`` -> ``Shard(dim)``: local chunking (i.e. ``torch.chunk``)
|
| 487 |
+
4. ``Partial()`` -> ``Replicate()``: ``all_reduce``
|
| 488 |
+
5. ``Partial()`` -> ``Shard(dim)``: ``reduce_scatter``
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
``redistribute`` would correctly figure out the necessary redistribute steps for DTensors
|
| 492 |
+
that are created either on 1-D or N-D DeviceMesh.
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to place the
|
| 496 |
+
DTensor. If not specified, it would use the current DTensor's DeviceMesh.
|
| 497 |
+
default: None
|
| 498 |
+
placements (List[:class:`Placement`], optional): the new placements that
|
| 499 |
+
describes how to place the DTensor into the DeviceMesh, must
|
| 500 |
+
have the same number of elements as ``device_mesh.ndim``.
|
| 501 |
+
default: replicate on all mesh dimensions
|
| 502 |
+
|
| 503 |
+
Keyword args:
|
| 504 |
+
async_op (bool, optional): whether to perform the DTensor redistribute operation
|
| 505 |
+
asynchronously or not. Default: False
|
| 506 |
+
|
| 507 |
+
Returns:
|
| 508 |
+
A :class:`DTensor` object
|
| 509 |
+
|
| 510 |
+
.. note:: ``redistribute`` is differentiable, which means user do not need to worry about
|
| 511 |
+
the backward formula of the redistribute operation.
|
| 512 |
+
|
| 513 |
+
.. note:: ``redistribute`` currently only supports redistributing DTensor on the same DeviceMesh,
|
| 514 |
+
Please file an issue if you need to redistribute DTensor to different DeviceMesh.
|
| 515 |
+
"""
|
| 516 |
+
# NOTE: This redistribute API currently only supports out
|
| 517 |
+
# of place redistribution, i.e. it always create a new
|
| 518 |
+
# DTensor object and leave the original one unchanged.
|
| 519 |
+
|
| 520 |
+
# if device_mesh is not specified, use the current device_mesh
|
| 521 |
+
device_mesh = device_mesh or self.device_mesh
|
| 522 |
+
# raise error if new placements not specified
|
| 523 |
+
if placements is None:
|
| 524 |
+
raise RuntimeError("placements is needed for redistribute!")
|
| 525 |
+
|
| 526 |
+
placements = list(placements)
|
| 527 |
+
for i, placement in enumerate(placements):
|
| 528 |
+
if placement.is_partial():
|
| 529 |
+
raise RuntimeError(
|
| 530 |
+
"Can not redistribute to Partial, redistributing to Partial is for internal use only!"
|
| 531 |
+
)
|
| 532 |
+
elif isinstance(placement, Shard) and placement.dim < 0:
|
| 533 |
+
# normalize shard dim to be positive
|
| 534 |
+
placements[i] = Shard(placement.dim + self.ndim)
|
| 535 |
+
placements = tuple(placements)
|
| 536 |
+
|
| 537 |
+
# pyre-fixme[16]: `Redistribute` has no attribute `apply`.
|
| 538 |
+
return Redistribute.apply(self, device_mesh, placements, async_op)
|
| 539 |
+
|
| 540 |
+
def full_tensor(
|
| 541 |
+
self, *, grad_placements: Optional[Sequence[Placement]] = None
|
| 542 |
+
) -> torch.Tensor:
|
| 543 |
+
"""
|
| 544 |
+
Return the full tensor of this DTensor. It will perform necessary collectives
|
| 545 |
+
to gather the local tensors from other ranks in its DeviceMesh and concatenate
|
| 546 |
+
them together. It's a syntatic sugar of the following code:
|
| 547 |
+
|
| 548 |
+
``dtensor.redistribute(placements=[Replicate()] * mesh.ndim).to_local()``
|
| 549 |
+
|
| 550 |
+
Keyword args:
|
| 551 |
+
grad_placements (List[:class:`Placement`], optional): the placements describes
|
| 552 |
+
the future layout of any gradient layout of the full Tensor returned from this
|
| 553 |
+
function.
|
| 554 |
+
`full_tensor` converts DTensor to a full torch.Tensor and the returned torch.tensor
|
| 555 |
+
might not be used as the original replicated DTensor layout later in the code. This
|
| 556 |
+
argument is the hint that user can give to autograd in case the gradient
|
| 557 |
+
layout of the returned tensor does not match the original replicated DTensor layout.
|
| 558 |
+
If not specified, we will assume the gradient layout of the full tensor be replicated.
|
| 559 |
+
|
| 560 |
+
Returns:
|
| 561 |
+
A :class:`torch.Tensor` object that represents the full tensor of this DTensor.
|
| 562 |
+
|
| 563 |
+
.. note:: ``full_tensor`` is differentiable.
|
| 564 |
+
"""
|
| 565 |
+
|
| 566 |
+
redist_res = self.redistribute(
|
| 567 |
+
placements=[Replicate()] * self.device_mesh.ndim, async_op=False
|
| 568 |
+
)
|
| 569 |
+
return _ToTorchTensor.apply(redist_res, grad_placements)
|
| 570 |
+
|
| 571 |
+
@property
|
| 572 |
+
def device_mesh(self) -> DeviceMesh:
|
| 573 |
+
"""
|
| 574 |
+
The :class:`DeviceMesh` attribute that associates with this DTensor object.
|
| 575 |
+
|
| 576 |
+
.. note:: ``device_mesh`` is a read-only property, it can not be set.
|
| 577 |
+
"""
|
| 578 |
+
return self._spec.mesh
|
| 579 |
+
|
| 580 |
+
@property
|
| 581 |
+
def placements(self) -> Tuple[Placement, ...]:
|
| 582 |
+
"""
|
| 583 |
+
The placements attribute of this DTensor that describes the layout of this
|
| 584 |
+
DTensor on the its DeviceMesh.
|
| 585 |
+
|
| 586 |
+
.. note:: ``placements`` is a read-only property, it can not be set.
|
| 587 |
+
"""
|
| 588 |
+
return self._spec.placements
|
| 589 |
+
|
| 590 |
+
def __create_write_items__(self, fqn: str, object: Any):
|
| 591 |
+
from torch.distributed.checkpoint.planner_helpers import (
|
| 592 |
+
_create_write_items_for_dtensor,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if hasattr(self._local_tensor, "__create_write_items__"):
|
| 596 |
+
return self._local_tensor.__create_write_items__(fqn, object) # type: ignore[attr-defined]
|
| 597 |
+
elif isinstance(self._local_tensor, torch.Tensor):
|
| 598 |
+
return [_create_write_items_for_dtensor(fqn, object)]
|
| 599 |
+
else:
|
| 600 |
+
raise RuntimeError("Unsupported tensor type!")
|
| 601 |
+
|
| 602 |
+
def __create_chunk_list__(self):
|
| 603 |
+
from torch.distributed.checkpoint.planner_helpers import (
|
| 604 |
+
_create_chunk_from_dtensor,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
if hasattr(self._local_tensor, "__create_chunk_list__"):
|
| 608 |
+
return self._local_tensor.__create_chunk_list__() # type: ignore[attr-defined]
|
| 609 |
+
elif isinstance(self._local_tensor, torch.Tensor):
|
| 610 |
+
return [_create_chunk_from_dtensor(self)]
|
| 611 |
+
else:
|
| 612 |
+
raise RuntimeError("Unsupported tensor type!")
|
| 613 |
+
|
| 614 |
+
def __get_tensor_shard__(self, index):
|
| 615 |
+
if hasattr(self._local_tensor, "__get_tensor_shard__"):
|
| 616 |
+
return self._local_tensor.__get_tensor_shard__(index) # type: ignore[attr-defined]
|
| 617 |
+
elif isinstance(self._local_tensor, torch.Tensor):
|
| 618 |
+
return self.to_local()
|
| 619 |
+
else:
|
| 620 |
+
raise RuntimeError("Unsupported tensor type!")
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def distribute_tensor(
|
| 624 |
+
tensor: torch.Tensor,
|
| 625 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 626 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 627 |
+
) -> DTensor:
|
| 628 |
+
"""
|
| 629 |
+
Distribute a leaf ``torch.Tensor`` (i.e. nn.Parameter/buffers) to the ``device_mesh`` according
|
| 630 |
+
to the ``placements`` specified. The rank of ``device_mesh`` and ``placements`` must be the
|
| 631 |
+
same. The ``tensor`` to distribute is the logical or "global" tensor, and the API would use
|
| 632 |
+
the ``tensor`` from first rank of the DeviceMesh dimension as the source of truth to perserve
|
| 633 |
+
the single-device semantic. If you want to construct a DTensor in the middle of the Autograd
|
| 634 |
+
computation, please use :meth:`DTensor.from_local` instead.
|
| 635 |
+
|
| 636 |
+
Args:
|
| 637 |
+
tensor (torch.Tensor): torch.Tensor to be distributed. Note that if you
|
| 638 |
+
want to shard a tensor on a dimension that is not evenly divisible by
|
| 639 |
+
the number of devices in that mesh dimension, we use ``torch.chunk``
|
| 640 |
+
semantic to shard the tensor and scatter the shards. The uneven sharding
|
| 641 |
+
behavior is experimental and subject to change.
|
| 642 |
+
device_mesh (:class:`DeviceMesh`, optional): DeviceMesh to distribute the
|
| 643 |
+
tensor, if not specified, must be called under a DeviceMesh context
|
| 644 |
+
manager, default: None
|
| 645 |
+
placements (List[:class:`Placement`], optional): the placements that
|
| 646 |
+
describes how to place the tensor on DeviceMesh, must have the same
|
| 647 |
+
number of elements as ``device_mesh.ndim``. If not specified, we will
|
| 648 |
+
by default replicate the tensor across the ``device_mesh`` from the
|
| 649 |
+
first rank of each dimension of the `device_mesh`.
|
| 650 |
+
|
| 651 |
+
Returns:
|
| 652 |
+
A :class:`DTensor` or ``XLAShardedTensor`` object.
|
| 653 |
+
|
| 654 |
+
.. note::
|
| 655 |
+
When initialize the DeviceMesh with the ``xla`` device_type, ``distribute_tensor``
|
| 656 |
+
return `XLAShardedTensor` instead. see `this issue <https://github.com/pytorch/pytorch/issues/92909>`__
|
| 657 |
+
for more details. The XLA integration is experimental and subject to change.
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
torch._C._log_api_usage_once("torch.dtensor.distribute_tensor")
|
| 661 |
+
|
| 662 |
+
# get default device mesh if there's nothing specified
|
| 663 |
+
device_mesh = device_mesh or _mesh_resources.get_current_mesh()
|
| 664 |
+
device_type = device_mesh.device_type
|
| 665 |
+
if device_type == "xla":
|
| 666 |
+
try:
|
| 667 |
+
# call PyTorch/XLA SPMD for `xla` backend type device mesh.
|
| 668 |
+
# This returns XLAShardedTensor
|
| 669 |
+
from torch_xla.distributed.spmd import ( # type:ignore[import]
|
| 670 |
+
xla_distribute_tensor,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
return xla_distribute_tensor(
|
| 674 |
+
tensor, device_mesh, placements
|
| 675 |
+
) # type:ignore[return-value]
|
| 676 |
+
except ImportError as e:
|
| 677 |
+
msg = "To use DTensor API with xla, you must install the torch_xla package!"
|
| 678 |
+
raise ImportError(msg) from e
|
| 679 |
+
|
| 680 |
+
# instantiate a RNG tracker if haven't. By default DTensor uses an
|
| 681 |
+
# OffsetBasedRNGTracker to perform random operators.
|
| 682 |
+
# TODO: the value assignment to global variable is not the ideal solution
|
| 683 |
+
# we can replace it in future.
|
| 684 |
+
if not random._rng_tracker and is_rng_supported_mesh(device_mesh):
|
| 685 |
+
random._rng_tracker = OffsetBasedRNGTracker(device_type)
|
| 686 |
+
|
| 687 |
+
if not tensor.is_leaf:
|
| 688 |
+
raise RuntimeError(
|
| 689 |
+
"`distribute_tensor` should be used to distribute leaf tensors! but found non-leaf tensor!"
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
# convert tensor to the corresponding device type if it's not in that device type
|
| 693 |
+
if device_type != tensor.device.type and not tensor.is_meta:
|
| 694 |
+
tensor = tensor.to(device_type)
|
| 695 |
+
|
| 696 |
+
# set default placements to replicated if not specified
|
| 697 |
+
if placements is None:
|
| 698 |
+
placements = [Replicate() for _ in range(device_mesh.ndim)]
|
| 699 |
+
|
| 700 |
+
if len(placements) != device_mesh.ndim:
|
| 701 |
+
raise ValueError(
|
| 702 |
+
f"`placements` must have the same length as `device_mesh.ndim`! "
|
| 703 |
+
f"Found placements length: {len(placements)}, and device_mesh.ndim: {device_mesh.ndim}."
|
| 704 |
+
)
|
| 705 |
+
if isinstance(tensor, DTensor):
|
| 706 |
+
# if the tensor is already a DTensor, we need to check:
|
| 707 |
+
# 1. if the we can further shard this DTensor if the two device mesh belong to
|
| 708 |
+
# the same parenet mesh and further sharding is possible.
|
| 709 |
+
# 2. check if device mesh and placements are the same
|
| 710 |
+
if tensor.device_mesh != device_mesh:
|
| 711 |
+
raise ValueError(
|
| 712 |
+
f"Cannot distribute a DTensor with device mesh {tensor.device_mesh} "
|
| 713 |
+
f"to a different device mesh {device_mesh}."
|
| 714 |
+
)
|
| 715 |
+
if tensor.placements != tuple(placements):
|
| 716 |
+
raise ValueError(
|
| 717 |
+
f"Cannot distribute a DTensor with placements {tensor.placements} "
|
| 718 |
+
f"to a different placements {placements}. do you want to call "
|
| 719 |
+
f"`redistribute` instead?"
|
| 720 |
+
)
|
| 721 |
+
return tensor
|
| 722 |
+
|
| 723 |
+
local_tensor = tensor.detach()
|
| 724 |
+
|
| 725 |
+
# TODO(xilun): address sharding order
|
| 726 |
+
# distribute the tensor according to the placements.
|
| 727 |
+
placements = list(placements)
|
| 728 |
+
for idx, placement in enumerate(placements):
|
| 729 |
+
if placement.is_shard():
|
| 730 |
+
placement = cast(Shard, placement)
|
| 731 |
+
if placement.dim < 0:
|
| 732 |
+
# normalize shard placement dim
|
| 733 |
+
placement = Shard(placement.dim + tensor.ndim)
|
| 734 |
+
placements[idx] = placement
|
| 735 |
+
local_tensor = placement._shard_tensor(local_tensor, device_mesh, idx)
|
| 736 |
+
elif placement.is_replicate():
|
| 737 |
+
placement = cast(Replicate, placement)
|
| 738 |
+
local_tensor = placement._replicate_tensor(local_tensor, device_mesh, idx)
|
| 739 |
+
else:
|
| 740 |
+
raise RuntimeError(
|
| 741 |
+
f"Trying to distribute tensor with unsupported placements {placement} on device mesh dimension {idx}!"
|
| 742 |
+
)
|
| 743 |
+
placements = tuple(placements)
|
| 744 |
+
|
| 745 |
+
assert local_tensor is not None, "distributing a tensor should not be None"
|
| 746 |
+
# detach the local tensor passed to DTensor since after the construction
|
| 747 |
+
# of DTensor, autograd would work on top of DTensor instead of local tensor
|
| 748 |
+
spec = DTensorSpec(
|
| 749 |
+
mesh=device_mesh,
|
| 750 |
+
placements=placements,
|
| 751 |
+
tensor_meta=TensorMeta(
|
| 752 |
+
shape=tensor.size(),
|
| 753 |
+
stride=tensor.stride(),
|
| 754 |
+
dtype=tensor.dtype,
|
| 755 |
+
),
|
| 756 |
+
)
|
| 757 |
+
return DTensor(
|
| 758 |
+
local_tensor.requires_grad_(tensor.requires_grad),
|
| 759 |
+
spec,
|
| 760 |
+
requires_grad=tensor.requires_grad,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def distribute_module(
|
| 765 |
+
module: nn.Module,
|
| 766 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 767 |
+
partition_fn: Optional[Callable[[str, nn.Module, DeviceMesh], None]] = None,
|
| 768 |
+
input_fn: Optional[Callable[[nn.Module, Any, DeviceMesh], None]] = None,
|
| 769 |
+
output_fn: Optional[Callable[[nn.Module, Any, DeviceMesh], None]] = None,
|
| 770 |
+
) -> nn.Module:
|
| 771 |
+
"""
|
| 772 |
+
This function expose three functions to control the parameters/inputs/outputs of the module:
|
| 773 |
+
|
| 774 |
+
1. To perform sharding on the module before runtime execution by specifying the
|
| 775 |
+
``partition_fn`` (i.e. allow user to convert Module parameters to :class:`DTensor`
|
| 776 |
+
parameters according to the `partition_fn` specified).
|
| 777 |
+
2. To control the inputs or outputs of the module during runtime execution by
|
| 778 |
+
specifying the ``input_fn`` and ``output_fn``. (i.e. convert the input to
|
| 779 |
+
:class:`DTensor`, convert the output back to ``torch.Tensor``)
|
| 780 |
+
|
| 781 |
+
Args:
|
| 782 |
+
module (:class:`nn.Module`): user module to be partitioned.
|
| 783 |
+
device_mesh (:class:`DeviceMesh`): the device mesh to place the module.
|
| 784 |
+
partition_fn (Callable): the function to partition parameters (i.e. shard certain
|
| 785 |
+
parameters across the ``device_mesh``). If ``partition_fn`` is not specified,
|
| 786 |
+
by default we replicate all module parameters of ``module`` across the mesh.
|
| 787 |
+
input_fn (Callable): specify the input distribution, i.e. could control how the
|
| 788 |
+
input of the module is sharded. ``input_fn`` will be installed as a module
|
| 789 |
+
``forward_pre_hook`` (pre forward hook).
|
| 790 |
+
output_fn (Callable): specify the output distribution, i.e. could control how the
|
| 791 |
+
output is sharded, or convert it back to torch.Tensor. ``output_fn`` will be
|
| 792 |
+
installed as a module ``forward_hook`` (post forward hook).
|
| 793 |
+
|
| 794 |
+
Returns:
|
| 795 |
+
A module that contains parameters/buffers that are all ``DTensor`` s.
|
| 796 |
+
|
| 797 |
+
.. note::
|
| 798 |
+
When initialize the DeviceMesh with the ``xla`` device_type, ``distribute_module``
|
| 799 |
+
return nn.Module with PyTorch/XLA SPMD annotated parameters. See
|
| 800 |
+
`this issue <https://github.com/pytorch/pytorch/issues/92909>`__
|
| 801 |
+
for more details. The XLA integration is experimental and subject to change.
|
| 802 |
+
|
| 803 |
+
"""
|
| 804 |
+
|
| 805 |
+
torch._C._log_api_usage_once("torch.dtensor.distribute_module")
|
| 806 |
+
|
| 807 |
+
device_mesh = device_mesh or _mesh_resources.get_current_mesh()
|
| 808 |
+
device_type = device_mesh.device_type
|
| 809 |
+
if device_type == "xla":
|
| 810 |
+
try:
|
| 811 |
+
# This function annotates all module parameters for auto-partitioning with
|
| 812 |
+
# PyTorch/XLA SPMD or explicitly partition to :class:`XLAShardedTensor` parameters
|
| 813 |
+
# according to the `partition_fn` specified.
|
| 814 |
+
from torch_xla.distributed.spmd import ( # type:ignore[import]
|
| 815 |
+
xla_distribute_module,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
return xla_distribute_module(
|
| 819 |
+
module, device_mesh, partition_fn, input_fn, output_fn
|
| 820 |
+
) # type:ignore[return-value]
|
| 821 |
+
except ImportError as e:
|
| 822 |
+
msg = "To use DTensor API with xla, you must install the torch_xla package!"
|
| 823 |
+
raise ImportError(msg) from e
|
| 824 |
+
|
| 825 |
+
def replicate_module_params_buffers(m: nn.Module, mesh: DeviceMesh) -> None:
|
| 826 |
+
# This function loop over the immediate module parameters and
|
| 827 |
+
# buffers, replicate all non DTensor params/buffers to DTensor
|
| 828 |
+
# parameters/buffers, if they have not been partitioned in the
|
| 829 |
+
# partition_fn, we can't easily use `module._apply` here
|
| 830 |
+
# because we don't know what happened inside partition_fn as
|
| 831 |
+
# user could do anything, i.e. install hooks, and we want to
|
| 832 |
+
# preserve those.
|
| 833 |
+
full_replicate = [Replicate()] * mesh.ndim
|
| 834 |
+
for key, param in m._parameters.items():
|
| 835 |
+
if param is not None and not isinstance(param, DTensor):
|
| 836 |
+
m.register_parameter(
|
| 837 |
+
key,
|
| 838 |
+
nn.Parameter(distribute_tensor(param.data, mesh, full_replicate)),
|
| 839 |
+
)
|
| 840 |
+
for key, buffer in m._buffers.items():
|
| 841 |
+
if buffer is not None and not isinstance(buffer, DTensor):
|
| 842 |
+
m._buffers[key] = distribute_tensor(buffer, mesh, full_replicate)
|
| 843 |
+
|
| 844 |
+
if partition_fn is None:
|
| 845 |
+
# if partition_fn not specified, we by default replicate
|
| 846 |
+
# all module params/buffers
|
| 847 |
+
for name, submod in module.named_modules():
|
| 848 |
+
replicate_module_params_buffers(submod, device_mesh)
|
| 849 |
+
else:
|
| 850 |
+
# apply partition_fun to submodules
|
| 851 |
+
for name, submod in module.named_modules():
|
| 852 |
+
partition_fn(name, submod, device_mesh)
|
| 853 |
+
replicate_module_params_buffers(submod, device_mesh)
|
| 854 |
+
|
| 855 |
+
# register input_fn as module forward pre hook
|
| 856 |
+
if input_fn is not None:
|
| 857 |
+
# check the input_fn signature
|
| 858 |
+
num_args = len(inspect.signature(input_fn).parameters)
|
| 859 |
+
if num_args == 2:
|
| 860 |
+
# input_fn only takes in inputs and device mesh
|
| 861 |
+
warnings.warn(
|
| 862 |
+
"Deprecating input_fn that takes two arguments (inputs, device_mesh), "
|
| 863 |
+
"please use input_fn that takes in (module, inputs, device_mesh) instead!",
|
| 864 |
+
FutureWarning,
|
| 865 |
+
stacklevel=2,
|
| 866 |
+
)
|
| 867 |
+
module.register_forward_pre_hook(lambda _, inputs: input_fn(inputs, device_mesh)) # type: ignore[call-arg]
|
| 868 |
+
elif num_args == 3:
|
| 869 |
+
# input_fn takes in module, inputs, device mesh
|
| 870 |
+
module.register_forward_pre_hook(
|
| 871 |
+
lambda mod, inputs: input_fn(mod, inputs, device_mesh)
|
| 872 |
+
)
|
| 873 |
+
else:
|
| 874 |
+
raise ValueError(
|
| 875 |
+
f"input_fn should take in 3 arguments, but got {num_args} arguments!"
|
| 876 |
+
)
|
| 877 |
+
# register output_fn as module forward hook
|
| 878 |
+
if output_fn is not None:
|
| 879 |
+
num_args = len(inspect.signature(output_fn).parameters)
|
| 880 |
+
if num_args == 2:
|
| 881 |
+
# output_fn only takes in outputs and device mesh
|
| 882 |
+
warnings.warn(
|
| 883 |
+
"Deprecating output_fn that takes two arguments (inputs, device_mesh), "
|
| 884 |
+
"please use output_fn that takes in (module, inputs, device_mesh) instead!",
|
| 885 |
+
FutureWarning,
|
| 886 |
+
stacklevel=2,
|
| 887 |
+
)
|
| 888 |
+
module.register_forward_hook(
|
| 889 |
+
lambda mod, inputs, outputs: output_fn(outputs, device_mesh) # type: ignore[call-arg]
|
| 890 |
+
)
|
| 891 |
+
elif num_args == 3:
|
| 892 |
+
module.register_forward_hook(
|
| 893 |
+
lambda mod, inputs, outputs: output_fn(mod, outputs, device_mesh)
|
| 894 |
+
)
|
| 895 |
+
else:
|
| 896 |
+
raise ValueError(
|
| 897 |
+
f"output_fn should take in 3 arguments, but got {num_args} arguments!"
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
return module
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
# Below are tensor factory function APIs, which are used to create a DTensor directly. We need
|
| 904 |
+
# to make separate factory function APIs because tensor subclass could not override the tensor
|
| 905 |
+
# factory methods, and we need user to call the factory functions with user intended device_mesh
|
| 906 |
+
# and placements to create a proper DTensor.
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _dtensor_init_helper( # type: ignore[no-untyped-def]
|
| 910 |
+
init_op,
|
| 911 |
+
size: torch.Size,
|
| 912 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 913 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 914 |
+
**kwargs,
|
| 915 |
+
) -> DTensor:
|
| 916 |
+
# from torch.distributed._tensor.placement_types import DTensorSpec, TensorMeta
|
| 917 |
+
|
| 918 |
+
# if device_mesh is None, use the one from mesh resources
|
| 919 |
+
device_mesh = device_mesh or _mesh_resources.get_current_mesh()
|
| 920 |
+
kwargs["device"] = device_mesh.device_type
|
| 921 |
+
|
| 922 |
+
# set default placements to replicated if not specified
|
| 923 |
+
placements = placements or tuple(Replicate() for _ in range(device_mesh.ndim))
|
| 924 |
+
|
| 925 |
+
# check device_mesh againts placements
|
| 926 |
+
assert device_mesh.ndim == len(
|
| 927 |
+
placements
|
| 928 |
+
), "mesh dimension does not match the length of placements"
|
| 929 |
+
|
| 930 |
+
assert kwargs["layout"] == torch.strided, "layout value not supported!"
|
| 931 |
+
torch_stride = torch._prims_common.make_contiguous_strides_for(size)
|
| 932 |
+
|
| 933 |
+
# get local tensor shape
|
| 934 |
+
local_shape = compute_local_shape(size, device_mesh, placements)
|
| 935 |
+
# initialize the local tensor
|
| 936 |
+
if init_op == torch.full:
|
| 937 |
+
fill_value = kwargs.pop("fill_value", 0)
|
| 938 |
+
local_tensor = init_op(local_shape, fill_value, **kwargs)
|
| 939 |
+
elif init_op == torch.rand or init_op == torch.randn:
|
| 940 |
+
# this tensor meta is not used except `shape`
|
| 941 |
+
dtype = kwargs.get("dtype", torch.get_default_dtype())
|
| 942 |
+
|
| 943 |
+
tensor_meta = TensorMeta(size, (0,), dtype)
|
| 944 |
+
spec = DTensorSpec(device_mesh, tuple(placements), tensor_meta=tensor_meta)
|
| 945 |
+
|
| 946 |
+
if random.is_rng_supported_mesh(device_mesh) and not random._rng_tracker:
|
| 947 |
+
random._rng_tracker = random.OffsetBasedRNGTracker()
|
| 948 |
+
|
| 949 |
+
assert random._rng_tracker is not None
|
| 950 |
+
with random._rng_tracker._distribute_region(spec):
|
| 951 |
+
local_tensor = init_op(local_shape, **kwargs)
|
| 952 |
+
else:
|
| 953 |
+
local_tensor = init_op(local_shape, **kwargs)
|
| 954 |
+
|
| 955 |
+
spec = DTensorSpec(
|
| 956 |
+
device_mesh,
|
| 957 |
+
tuple(placements),
|
| 958 |
+
tensor_meta=TensorMeta(
|
| 959 |
+
size,
|
| 960 |
+
torch_stride,
|
| 961 |
+
local_tensor.dtype,
|
| 962 |
+
),
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
return DTensor(
|
| 966 |
+
local_tensor,
|
| 967 |
+
spec,
|
| 968 |
+
requires_grad=kwargs["requires_grad"],
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def ones( # type: ignore[no-untyped-def]
|
| 973 |
+
*size,
|
| 974 |
+
dtype: Optional[torch.dtype] = None,
|
| 975 |
+
layout: torch.layout = torch.strided,
|
| 976 |
+
requires_grad: bool = False,
|
| 977 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 978 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 979 |
+
) -> DTensor:
|
| 980 |
+
"""
|
| 981 |
+
Returns a :class:`DTensor` filled with the scalar value 1, with the shape defined
|
| 982 |
+
by the variable argument ``size``.
|
| 983 |
+
|
| 984 |
+
Args:
|
| 985 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 986 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 987 |
+
E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
|
| 988 |
+
|
| 989 |
+
Keyword args:
|
| 990 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 991 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
|
| 992 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
|
| 993 |
+
Default: ``torch.strided``.
|
| 994 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 995 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 996 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
|
| 997 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 998 |
+
|
| 999 |
+
Returns:
|
| 1000 |
+
A :class:`DTensor` object on each rank
|
| 1001 |
+
"""
|
| 1002 |
+
torch_size = normalize_to_torch_size(size)
|
| 1003 |
+
|
| 1004 |
+
return _dtensor_init_helper(
|
| 1005 |
+
torch.ones,
|
| 1006 |
+
torch_size,
|
| 1007 |
+
dtype=dtype,
|
| 1008 |
+
layout=layout,
|
| 1009 |
+
requires_grad=requires_grad,
|
| 1010 |
+
device_mesh=device_mesh,
|
| 1011 |
+
placements=placements,
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def empty( # type: ignore[no-untyped-def]
|
| 1016 |
+
*size,
|
| 1017 |
+
dtype: Optional[torch.dtype] = None,
|
| 1018 |
+
layout: torch.layout = torch.strided,
|
| 1019 |
+
requires_grad: bool = False,
|
| 1020 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 1021 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 1022 |
+
) -> DTensor:
|
| 1023 |
+
"""
|
| 1024 |
+
Returns a :class:`DTensor` filled with uninitialized data. The shape of the :class:`DTensor`
|
| 1025 |
+
is defined by the variable argument ``size``.
|
| 1026 |
+
|
| 1027 |
+
Args:
|
| 1028 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 1029 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 1030 |
+
E.g.: empty(1,2,3..) or empty([1,2,3..]) or empty((1,2,3..))
|
| 1031 |
+
|
| 1032 |
+
Keyword args:
|
| 1033 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 1034 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).\
|
| 1035 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned :class:`DTensor`.
|
| 1036 |
+
Default: ``torch.strided``.
|
| 1037 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 1038 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 1039 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
|
| 1040 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 1041 |
+
|
| 1042 |
+
Returns:
|
| 1043 |
+
A :class:`DTensor` object on each rank
|
| 1044 |
+
"""
|
| 1045 |
+
torch_size = normalize_to_torch_size(size)
|
| 1046 |
+
|
| 1047 |
+
return _dtensor_init_helper(
|
| 1048 |
+
torch.empty,
|
| 1049 |
+
torch_size,
|
| 1050 |
+
dtype=dtype,
|
| 1051 |
+
layout=layout,
|
| 1052 |
+
requires_grad=requires_grad,
|
| 1053 |
+
device_mesh=device_mesh,
|
| 1054 |
+
placements=placements,
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
def full( # type: ignore[no-untyped-def]
|
| 1059 |
+
size,
|
| 1060 |
+
fill_value,
|
| 1061 |
+
*,
|
| 1062 |
+
dtype: Optional[torch.dtype] = None,
|
| 1063 |
+
layout: torch.layout = torch.strided,
|
| 1064 |
+
requires_grad: bool = False,
|
| 1065 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 1066 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 1067 |
+
) -> DTensor:
|
| 1068 |
+
"""
|
| 1069 |
+
Returns a :class:`DTensor` filled with ``fill_value`` according to ``device_mesh`` and
|
| 1070 |
+
``placements``, with the shape defined by the argument ``size``.
|
| 1071 |
+
|
| 1072 |
+
Args:
|
| 1073 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 1074 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 1075 |
+
E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
|
| 1076 |
+
fill_value(Scalar): the value to fill the output tensor with.
|
| 1077 |
+
|
| 1078 |
+
Keyword args:
|
| 1079 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 1080 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
|
| 1081 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
|
| 1082 |
+
Default: ``torch.strided``.
|
| 1083 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 1084 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 1085 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
|
| 1086 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 1087 |
+
|
| 1088 |
+
Returns:
|
| 1089 |
+
A :class:`DTensor` object on each rank
|
| 1090 |
+
"""
|
| 1091 |
+
torch_size = normalize_to_torch_size(size)
|
| 1092 |
+
|
| 1093 |
+
return _dtensor_init_helper(
|
| 1094 |
+
torch.full,
|
| 1095 |
+
torch_size,
|
| 1096 |
+
fill_value=fill_value,
|
| 1097 |
+
dtype=dtype,
|
| 1098 |
+
layout=layout,
|
| 1099 |
+
requires_grad=requires_grad,
|
| 1100 |
+
device_mesh=device_mesh,
|
| 1101 |
+
placements=placements,
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
def rand( # type: ignore[no-untyped-def]
|
| 1106 |
+
*size,
|
| 1107 |
+
requires_grad: bool = False,
|
| 1108 |
+
dtype: Optional[torch.dtype] = None,
|
| 1109 |
+
layout: torch.layout = torch.strided,
|
| 1110 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 1111 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 1112 |
+
) -> DTensor:
|
| 1113 |
+
"""
|
| 1114 |
+
Returns a :class:`DTensor` filled with random numbers from a uniform distribution
|
| 1115 |
+
on the interval ``[0, 1)``. The shape of the tensor is defined by the variable
|
| 1116 |
+
argument ``size``.
|
| 1117 |
+
|
| 1118 |
+
Args:
|
| 1119 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 1120 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 1121 |
+
E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
|
| 1122 |
+
|
| 1123 |
+
Keyword args:
|
| 1124 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 1125 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
|
| 1126 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
|
| 1127 |
+
Default: ``torch.strided``.
|
| 1128 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 1129 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 1130 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
|
| 1131 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 1132 |
+
|
| 1133 |
+
Returns:
|
| 1134 |
+
A :class:`DTensor` object on each rank
|
| 1135 |
+
"""
|
| 1136 |
+
torch_size = normalize_to_torch_size(size)
|
| 1137 |
+
|
| 1138 |
+
return _dtensor_init_helper(
|
| 1139 |
+
torch.rand,
|
| 1140 |
+
torch_size,
|
| 1141 |
+
dtype=dtype,
|
| 1142 |
+
layout=layout,
|
| 1143 |
+
requires_grad=requires_grad,
|
| 1144 |
+
device_mesh=device_mesh,
|
| 1145 |
+
placements=placements,
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
|
| 1149 |
+
def randn( # type: ignore[no-untyped-def]
|
| 1150 |
+
*size,
|
| 1151 |
+
requires_grad: bool = False,
|
| 1152 |
+
dtype: Optional[torch.dtype] = None,
|
| 1153 |
+
layout: torch.layout = torch.strided,
|
| 1154 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 1155 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 1156 |
+
) -> DTensor:
|
| 1157 |
+
"""
|
| 1158 |
+
Returns a :class:`DTensor` filled with random numbers from a normal distribution
|
| 1159 |
+
with mean 0 and variance 1. The shape of the tensor is defined by the variable
|
| 1160 |
+
argument ``size``.
|
| 1161 |
+
|
| 1162 |
+
Args:
|
| 1163 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 1164 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 1165 |
+
E.g.: ones(1,2,3..) or ones([1,2,3..]) or ones((1,2,3..))
|
| 1166 |
+
|
| 1167 |
+
Keyword args:
|
| 1168 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 1169 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
|
| 1170 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned DTensor.
|
| 1171 |
+
Default: ``torch.strided``.
|
| 1172 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 1173 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 1174 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks.
|
| 1175 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 1176 |
+
|
| 1177 |
+
Returns:
|
| 1178 |
+
A :class:`DTensor` object on each rank
|
| 1179 |
+
"""
|
| 1180 |
+
torch_size = normalize_to_torch_size(size)
|
| 1181 |
+
|
| 1182 |
+
return _dtensor_init_helper(
|
| 1183 |
+
torch.randn,
|
| 1184 |
+
torch_size,
|
| 1185 |
+
dtype=dtype,
|
| 1186 |
+
layout=layout,
|
| 1187 |
+
requires_grad=requires_grad,
|
| 1188 |
+
device_mesh=device_mesh,
|
| 1189 |
+
placements=placements,
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
def zeros( # type: ignore[no-untyped-def]
|
| 1194 |
+
*size,
|
| 1195 |
+
requires_grad: bool = False,
|
| 1196 |
+
dtype: Optional[torch.dtype] = None,
|
| 1197 |
+
layout: torch.layout = torch.strided,
|
| 1198 |
+
device_mesh: Optional[DeviceMesh] = None,
|
| 1199 |
+
placements: Optional[Sequence[Placement]] = None,
|
| 1200 |
+
) -> DTensor:
|
| 1201 |
+
"""
|
| 1202 |
+
Returns a :class:`DTensor` filled with the scalar value 0.
|
| 1203 |
+
|
| 1204 |
+
Args:
|
| 1205 |
+
size (int...): a sequence of integers defining the shape of the output :class:`DTensor`.
|
| 1206 |
+
Can be a variable number of arguments or a collection like a list or tuple.
|
| 1207 |
+
E.g.: zeros(1,2,3..) or zeros([1,2,3..]) or zeros((1,2,3..))
|
| 1208 |
+
Keyword args:
|
| 1209 |
+
requires_grad (bool, optional): If autograd should record operations on the
|
| 1210 |
+
returned :class:`DTensor`. Default: ``False``.
|
| 1211 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of returned :class:`DTensor`.
|
| 1212 |
+
Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
|
| 1213 |
+
layout (:class:`torch.layout`, optional): the desired layout of returned :class:`DTensor`.
|
| 1214 |
+
Default: ``torch.strided``.
|
| 1215 |
+
device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks
|
| 1216 |
+
placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate``
|
| 1217 |
+
|
| 1218 |
+
Returns:
|
| 1219 |
+
A :class:`DTensor` object on each rank
|
| 1220 |
+
"""
|
| 1221 |
+
torch_size = normalize_to_torch_size(size)
|
| 1222 |
+
|
| 1223 |
+
return _dtensor_init_helper(
|
| 1224 |
+
torch.zeros,
|
| 1225 |
+
torch_size,
|
| 1226 |
+
dtype=dtype,
|
| 1227 |
+
layout=layout,
|
| 1228 |
+
requires_grad=requires_grad,
|
| 1229 |
+
device_mesh=device_mesh,
|
| 1230 |
+
placements=placements,
|
| 1231 |
+
)
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 2 |
+
from ._conv_ops import * # noqa: F403
|
| 3 |
+
from ._embedding_ops import * # noqa: F403
|
| 4 |
+
from ._experimental_ops import * # noqa: F403
|
| 5 |
+
from ._math_ops import * # noqa: F403
|
| 6 |
+
from ._matrix_ops import * # noqa: F403
|
| 7 |
+
from ._pointwise_ops import * # noqa: F403
|
| 8 |
+
from ._random_ops import * # noqa: F403
|
| 9 |
+
from ._tensor_ops import * # noqa: F403
|
| 10 |
+
from ._view_ops import * # noqa: F403
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (397 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-310.pyc
ADDED
|
Binary file (6.07 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-310.pyc
ADDED
|
Binary file (2.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-310.pyc
ADDED
|
Binary file (3.76 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-310.pyc
ADDED
|
Binary file (6.43 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-310.pyc
ADDED
|
Binary file (1.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-310.pyc
ADDED
|
Binary file (20.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-310.pyc
ADDED
|
Binary file (7.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-310.pyc
ADDED
|
Binary file (14.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-310.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-310.pyc
ADDED
|
Binary file (16 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-310.pyc
ADDED
|
Binary file (21.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (7.59 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_common_rules.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 2 |
+
from typing import cast, Dict, List, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
|
| 6 |
+
from torch.distributed.tensor._op_schema import (
|
| 7 |
+
_is_inplace_op,
|
| 8 |
+
_is_out_variant_op,
|
| 9 |
+
OpSchema,
|
| 10 |
+
OutputSharding,
|
| 11 |
+
)
|
| 12 |
+
from torch.distributed.tensor._ops.utils import prod
|
| 13 |
+
from torch.distributed.tensor._utils import compute_local_shape
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _replace_char_in_str(string: str, new_char: str, idx: int) -> str:
|
| 17 |
+
return string[:idx] + new_char + string[idx + 1 :]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _gen_reshard_suggestions(
|
| 21 |
+
op_schema: OpSchema,
|
| 22 |
+
input_dims: List[str],
|
| 23 |
+
input_specs: Tuple[DTensorSpec, ...],
|
| 24 |
+
dim_to_sharding: Dict[str, int],
|
| 25 |
+
pending_sum: List[int],
|
| 26 |
+
) -> OutputSharding:
|
| 27 |
+
suggested_arg_specs: List[DTensorSpec] = []
|
| 28 |
+
for input_dim, input_spec in zip(input_dims, input_specs):
|
| 29 |
+
dim_map = [dim_to_sharding[dim] for dim in input_dim]
|
| 30 |
+
suggested_arg_specs.append(
|
| 31 |
+
DTensorSpec.from_dim_map(
|
| 32 |
+
mesh=input_spec.mesh,
|
| 33 |
+
dim_map=dim_map,
|
| 34 |
+
sums=pending_sum,
|
| 35 |
+
tensor_meta=input_spec.tensor_meta,
|
| 36 |
+
)
|
| 37 |
+
)
|
| 38 |
+
suggested_schema = OpSchema(op_schema.op, tuple(suggested_arg_specs), {})
|
| 39 |
+
suggested_schema._inplace_rewrap_schema_suggestion(op_schema)
|
| 40 |
+
return OutputSharding(
|
| 41 |
+
None,
|
| 42 |
+
redistribute_schema=suggested_schema,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def einop_rule(
|
| 47 |
+
equation: str,
|
| 48 |
+
op_schema: OpSchema,
|
| 49 |
+
*,
|
| 50 |
+
linearity: bool = False,
|
| 51 |
+
enforce_sharding: Optional[Dict[str, int]] = None,
|
| 52 |
+
) -> OutputSharding:
|
| 53 |
+
"""
|
| 54 |
+
Propagate the sharding of inputs to output for ops whose data moves according to einsum notation.
|
| 55 |
+
|
| 56 |
+
This is mostly borrowed from @zdevito's sharding simulator. Examples:
|
| 57 |
+
mk,kn->mn - einsum
|
| 58 |
+
ij,ij->ij - addition
|
| 59 |
+
ij,j->ij - broadcasted addition
|
| 60 |
+
ij->i - reduction
|
| 61 |
+
Other ops could use this propagation algorithm when applied, note
|
| 62 |
+
that einsum propagation only deal with list of specs (DTensor specs)
|
| 63 |
+
as it only works on list of tensors!
|
| 64 |
+
|
| 65 |
+
linearity in einop_rule means that the calling op `f` follows this rule:
|
| 66 |
+
f(a + b) = f(a) + f(b)
|
| 67 |
+
|
| 68 |
+
In this case we can propagate the partial sum, note that linearity in einop
|
| 69 |
+
only applies to partial sum, not other operations like min/max (which are
|
| 70 |
+
associative but not linear).
|
| 71 |
+
"""
|
| 72 |
+
# parse einop equation and extract arg specs
|
| 73 |
+
inputs, outputs = equation.split("->")
|
| 74 |
+
input_dims, output_dims = inputs.split(","), outputs.split(",")
|
| 75 |
+
input_specs = op_schema.args_spec
|
| 76 |
+
# NOTE: only support single output unless needed in future
|
| 77 |
+
output_dim = output_dims[0]
|
| 78 |
+
|
| 79 |
+
dim_to_sharding: Dict[str, int] = {}
|
| 80 |
+
dim_to_size: Dict[str, int] = {}
|
| 81 |
+
# record pending sum, key is mesh dimension, value is pending sum
|
| 82 |
+
# counter across input specs
|
| 83 |
+
pending_sums_counter: Dict[int, int] = {}
|
| 84 |
+
seen_shardings: Dict[int, str] = {}
|
| 85 |
+
needs_reshard = False
|
| 86 |
+
|
| 87 |
+
def merge_sharding(dim: str, a: int, b: int) -> int:
|
| 88 |
+
# merge the sharding of inputs if it's able to merge, i.e. we can merge
|
| 89 |
+
# replicate and shard to shard, but this will trigger an reshard operation
|
| 90 |
+
if a != b:
|
| 91 |
+
if a == -1 or b == -1:
|
| 92 |
+
# reshard the replicate to match the sharded one
|
| 93 |
+
nonlocal needs_reshard
|
| 94 |
+
needs_reshard = True
|
| 95 |
+
return a if a != -1 else b
|
| 96 |
+
else:
|
| 97 |
+
# TODO: further merge the sharding properly (i.e. reshard one input to replicate)
|
| 98 |
+
raise RuntimeError(
|
| 99 |
+
f"{equation}: dim {dim} sharded two different ways: {a} and {b}"
|
| 100 |
+
)
|
| 101 |
+
else:
|
| 102 |
+
return a
|
| 103 |
+
|
| 104 |
+
for input_dim, input_spec in zip(input_dims, input_specs):
|
| 105 |
+
# deal with partial sums
|
| 106 |
+
input_sums = input_spec.sums
|
| 107 |
+
for sum_dim in input_sums:
|
| 108 |
+
if sum_dim not in pending_sums_counter:
|
| 109 |
+
seen_shardings[sum_dim] = "+"
|
| 110 |
+
# update pending sum counter for pending sum mesh
|
| 111 |
+
# dimension with the occurrence from each input
|
| 112 |
+
pending_sums_counter[sum_dim] = pending_sums_counter.get(sum_dim, 0) + 1
|
| 113 |
+
|
| 114 |
+
for idx, (dim, mesh_dim) in enumerate(zip(input_dim, input_spec.dim_map)):
|
| 115 |
+
if enforce_sharding and dim in enforce_sharding:
|
| 116 |
+
if enforce_sharding[dim] != mesh_dim:
|
| 117 |
+
needs_reshard = True
|
| 118 |
+
dim_to_sharding[dim] = enforce_sharding[dim]
|
| 119 |
+
dim_to_size[dim] = input_spec.shape[idx]
|
| 120 |
+
elif dim not in dim_to_sharding:
|
| 121 |
+
dim_to_sharding[dim] = mesh_dim
|
| 122 |
+
dim_to_size[dim] = input_spec.shape[idx]
|
| 123 |
+
else:
|
| 124 |
+
dim_to_sharding[dim] = merge_sharding(
|
| 125 |
+
dim, dim_to_sharding[dim], mesh_dim
|
| 126 |
+
)
|
| 127 |
+
assert dim_to_size[dim] == input_spec.shape[idx]
|
| 128 |
+
|
| 129 |
+
# after merging sharding, we check if there're multiple
|
| 130 |
+
# sharding on the same mesh dim.
|
| 131 |
+
merged_sharding_for_dim = dim_to_sharding[dim]
|
| 132 |
+
if merged_sharding_for_dim != -1:
|
| 133 |
+
if (
|
| 134 |
+
merged_sharding_for_dim in seen_shardings
|
| 135 |
+
and dim != seen_shardings[merged_sharding_for_dim]
|
| 136 |
+
):
|
| 137 |
+
needs_reshard = True
|
| 138 |
+
seen_shardings[merged_sharding_for_dim] += dim
|
| 139 |
+
else:
|
| 140 |
+
seen_shardings[merged_sharding_for_dim] = dim
|
| 141 |
+
|
| 142 |
+
if pending_sums_counter and not linearity:
|
| 143 |
+
# return reshard suggestion with no pending sum, because we already properly
|
| 144 |
+
# merge the sharding, this reshard suggestion is legit to use
|
| 145 |
+
return _gen_reshard_suggestions(
|
| 146 |
+
op_schema, input_dims, input_specs, dim_to_sharding, []
|
| 147 |
+
)
|
| 148 |
+
else:
|
| 149 |
+
# It's a op that support linearity, but not all input arguments are partial
|
| 150 |
+
# we fail the sharding propagation with suggestion to make all inputs be
|
| 151 |
+
# partial on the corresponding mesh dim (all inputs should be partial for
|
| 152 |
+
# the mesh dims in order to execute locally and delay the sum reduction)
|
| 153 |
+
for value in pending_sums_counter.values():
|
| 154 |
+
if value != len(input_specs):
|
| 155 |
+
needs_reshard = True
|
| 156 |
+
|
| 157 |
+
for mesh_dim, dims in seen_shardings.items():
|
| 158 |
+
if len(dims) > 1:
|
| 159 |
+
# we found different input dims are being sharded on the same mesh dim
|
| 160 |
+
# in order to perform local op computation, we need to reshard inputs
|
| 161 |
+
# base on some simple heuristics, now we simply pick the one with least comm
|
| 162 |
+
# volume. (i.e. the input with least size)
|
| 163 |
+
# TODO: consider a more advanced heuristic to pick the best sharding
|
| 164 |
+
costs = []
|
| 165 |
+
for d in dims:
|
| 166 |
+
cost = 0
|
| 167 |
+
for input_dim, input_spec in zip(input_dims, input_specs):
|
| 168 |
+
if (
|
| 169 |
+
d in input_dim
|
| 170 |
+
and input_spec.dim_map[input_dim.index(d)] == mesh_dim
|
| 171 |
+
):
|
| 172 |
+
assert input_spec.tensor_meta is not None
|
| 173 |
+
global_shape = input_spec.tensor_meta.shape
|
| 174 |
+
local_shape = compute_local_shape(
|
| 175 |
+
global_shape, input_spec.mesh, input_spec.placements
|
| 176 |
+
)
|
| 177 |
+
cost += prod(local_shape) * input_spec.mesh.size(mesh_dim)
|
| 178 |
+
costs.append(cost)
|
| 179 |
+
d_to_keep_sharding = dims[costs.index(max(costs))]
|
| 180 |
+
for d in dims:
|
| 181 |
+
# update dim_to_sharding to keep the sharding of the dim with
|
| 182 |
+
# highest comm and make the rest of the dims to replicate
|
| 183 |
+
if d != d_to_keep_sharding:
|
| 184 |
+
dim_to_sharding[d] = -1
|
| 185 |
+
|
| 186 |
+
pending_sums = list(pending_sums_counter.keys())
|
| 187 |
+
if needs_reshard:
|
| 188 |
+
return _gen_reshard_suggestions(
|
| 189 |
+
op_schema, input_dims, input_specs, dim_to_sharding, pending_sums
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# generate output pending sum if a dim is sharded, and it appears in input
|
| 193 |
+
# but not output
|
| 194 |
+
for dim, shard_on_mesh in dim_to_sharding.items():
|
| 195 |
+
if dim not in output_dims[0] and shard_on_mesh != -1:
|
| 196 |
+
pending_sums.append(shard_on_mesh)
|
| 197 |
+
|
| 198 |
+
# if no need to reshard, we directly generate the output sharding
|
| 199 |
+
output_dim_map = []
|
| 200 |
+
output_shape = []
|
| 201 |
+
for dim in output_dim:
|
| 202 |
+
if dim == "1":
|
| 203 |
+
# find output dim that is a singleton dimension, mark sharding and shape
|
| 204 |
+
output_dim_map.append(-1)
|
| 205 |
+
output_shape.append(1)
|
| 206 |
+
else:
|
| 207 |
+
output_dim_map.append(dim_to_sharding[dim])
|
| 208 |
+
output_shape.append(dim_to_size[dim])
|
| 209 |
+
|
| 210 |
+
# XXX: since we still need to have intermediate shape calculation, we need
|
| 211 |
+
# to pass in the shape here. We should remove this once sharding decomp works
|
| 212 |
+
# for ops like addmm
|
| 213 |
+
assert input_specs[0].tensor_meta is not None
|
| 214 |
+
tensor_meta = TensorMeta(
|
| 215 |
+
torch.Size(output_shape),
|
| 216 |
+
input_specs[0].tensor_meta.stride,
|
| 217 |
+
input_specs[0].tensor_meta.dtype,
|
| 218 |
+
)
|
| 219 |
+
return OutputSharding(
|
| 220 |
+
DTensorSpec.from_dim_map(
|
| 221 |
+
input_specs[0].mesh,
|
| 222 |
+
output_dim_map,
|
| 223 |
+
pending_sums,
|
| 224 |
+
tensor_meta=tensor_meta,
|
| 225 |
+
)
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def pointwise_rule(op_schema: OpSchema, linearity: bool = False) -> OutputSharding:
|
| 230 |
+
"""
|
| 231 |
+
Propagate the sharding for pointwise operations.
|
| 232 |
+
|
| 233 |
+
Examples:
|
| 234 |
+
ij,ij->ij - addition/mul
|
| 235 |
+
ij,j->ij - broadcasted addition
|
| 236 |
+
"""
|
| 237 |
+
alphabet = "abcdefghijklmnopqrstuvwxyz"
|
| 238 |
+
# find the max_dim first in case we need to broadcasting
|
| 239 |
+
input_specs = op_schema.args_spec
|
| 240 |
+
max_dim = max(input.ndim for input in input_specs)
|
| 241 |
+
dimchars = []
|
| 242 |
+
singleton_counter: List[int] = [0] * max_dim
|
| 243 |
+
for input in input_specs:
|
| 244 |
+
start_dim = max_dim - input.ndim
|
| 245 |
+
p = alphabet[start_dim:max_dim]
|
| 246 |
+
# handle the "broadcasting to a common shape case"
|
| 247 |
+
# see https://pytorch.org/docs/stable/notes/broadcasting.html
|
| 248 |
+
# If any of the dimensions is singleton dimension (i.e. 1).
|
| 249 |
+
# we mark the dim char as a special "1" to distinguish with
|
| 250 |
+
# the non-singleton dimension, so that sharding propagation
|
| 251 |
+
# should just ignore the singleton dimension.
|
| 252 |
+
if len(input_specs) > 1:
|
| 253 |
+
for i in range(max_dim):
|
| 254 |
+
if i < start_dim:
|
| 255 |
+
# treat the leading miss dim chars as singleton
|
| 256 |
+
singleton_counter[i] += 1
|
| 257 |
+
elif input.shape[i - start_dim] == 1:
|
| 258 |
+
# mark singleton dim char as a special "1" in einop rule
|
| 259 |
+
singleton_counter[i] += 1
|
| 260 |
+
p = _replace_char_in_str(p, "1", (i - start_dim))
|
| 261 |
+
|
| 262 |
+
dimchars.append(p)
|
| 263 |
+
out_dimchars = alphabet[:max_dim]
|
| 264 |
+
# check if we replace the all inputs dim char with singleton dimension,
|
| 265 |
+
# if we replace all inputs, we also need to replace the output dimension.
|
| 266 |
+
for output_dim_idx in range(len(out_dimchars)):
|
| 267 |
+
out_dimchar = out_dimchars[output_dim_idx]
|
| 268 |
+
if singleton_counter[output_dim_idx] == len(input_specs):
|
| 269 |
+
out_dimchars = _replace_char_in_str(out_dimchars, "1", output_dim_idx)
|
| 270 |
+
|
| 271 |
+
fmt = f"{','.join(p for p in dimchars)}->{out_dimchars}"
|
| 272 |
+
|
| 273 |
+
enforce_sharding: Dict[str, int] = {}
|
| 274 |
+
if _is_inplace_op(op_schema.op):
|
| 275 |
+
# inplace op should keep the input sharding it writes to
|
| 276 |
+
for out_dimchar, mesh_dim in zip(out_dimchars, input_specs[0].dim_map):
|
| 277 |
+
enforce_sharding[out_dimchar] = mesh_dim
|
| 278 |
+
elif _is_out_variant_op(op_schema.op):
|
| 279 |
+
out_spec = cast(DTensorSpec, op_schema.kwargs_schema["out"])
|
| 280 |
+
for out_dimchar, mesh_dim in zip(out_dimchars, out_spec.dim_map):
|
| 281 |
+
enforce_sharding[out_dimchar] = mesh_dim
|
| 282 |
+
|
| 283 |
+
return einop_rule(
|
| 284 |
+
fmt,
|
| 285 |
+
op_schema,
|
| 286 |
+
linearity=linearity,
|
| 287 |
+
enforce_sharding=enforce_sharding,
|
| 288 |
+
)
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_conv_ops.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 3 |
+
# implement matrix related ops for distributed tensor
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
|
| 8 |
+
from torch.distributed.tensor._op_schema import OpSchema, OutputSharding
|
| 9 |
+
from torch.distributed.tensor._ops.utils import register_prop_rule
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
aten = torch.ops.aten
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@register_prop_rule(aten.convolution.default)
|
| 16 |
+
def convolution_rules(op_schema: OpSchema) -> OutputSharding:
|
| 17 |
+
(
|
| 18 |
+
input_spec,
|
| 19 |
+
weight_spec,
|
| 20 |
+
bias_spec,
|
| 21 |
+
stride,
|
| 22 |
+
padding,
|
| 23 |
+
dilation,
|
| 24 |
+
transposed,
|
| 25 |
+
output_padding,
|
| 26 |
+
groups,
|
| 27 |
+
) = op_schema.args_schema
|
| 28 |
+
|
| 29 |
+
assert isinstance(input_spec, DTensorSpec)
|
| 30 |
+
assert isinstance(weight_spec, DTensorSpec)
|
| 31 |
+
assert isinstance(bias_spec, DTensorSpec)
|
| 32 |
+
assert input_spec.tensor_meta is not None
|
| 33 |
+
assert weight_spec.tensor_meta is not None
|
| 34 |
+
in_shape = input_spec.tensor_meta.shape
|
| 35 |
+
weight_shape = weight_spec.tensor_meta.shape
|
| 36 |
+
assert isinstance(stride, List)
|
| 37 |
+
assert isinstance(padding, List)
|
| 38 |
+
assert isinstance(dilation, List)
|
| 39 |
+
assert isinstance(weight_shape, torch.Size)
|
| 40 |
+
N, C_in, H_in, W_in = in_shape[0], in_shape[1], in_shape[2], in_shape[3]
|
| 41 |
+
C_out = weight_shape[0]
|
| 42 |
+
H_out = (H_in + 2 * padding[0] - dilation[0] * (weight_shape[2] - 1) - 1) // stride[
|
| 43 |
+
0
|
| 44 |
+
] + 1
|
| 45 |
+
W_out = (W_in + 2 * padding[1] - dilation[1] * (weight_shape[3] - 1) - 1) // stride[
|
| 46 |
+
1
|
| 47 |
+
] + 1
|
| 48 |
+
output_shape = [N, C_out, H_out, W_out]
|
| 49 |
+
output_stride = (C_out * H_out * W_out, H_out * W_out, W_out, 1)
|
| 50 |
+
output_dim_map = input_spec.dim_map
|
| 51 |
+
pending_sums = input_spec.sums
|
| 52 |
+
|
| 53 |
+
tensor_meta = TensorMeta(
|
| 54 |
+
torch.Size(output_shape),
|
| 55 |
+
output_stride,
|
| 56 |
+
input_spec.tensor_meta.dtype,
|
| 57 |
+
)
|
| 58 |
+
return OutputSharding(
|
| 59 |
+
DTensorSpec.from_dim_map(
|
| 60 |
+
input_spec.mesh,
|
| 61 |
+
output_dim_map,
|
| 62 |
+
pending_sums,
|
| 63 |
+
tensor_meta=tensor_meta,
|
| 64 |
+
)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@register_prop_rule(aten.convolution_backward.default)
|
| 69 |
+
def convolution_backward_rules(op_schema: OpSchema) -> OutputSharding:
|
| 70 |
+
input_spec = op_schema.args_schema[0]
|
| 71 |
+
(
|
| 72 |
+
grad_output_spec,
|
| 73 |
+
input_spec,
|
| 74 |
+
weight_spec,
|
| 75 |
+
bias_shape_opt,
|
| 76 |
+
stride,
|
| 77 |
+
padding,
|
| 78 |
+
dilation,
|
| 79 |
+
transposed,
|
| 80 |
+
output_padding,
|
| 81 |
+
groups,
|
| 82 |
+
output_mask,
|
| 83 |
+
) = op_schema.args_schema
|
| 84 |
+
|
| 85 |
+
assert isinstance(grad_output_spec, DTensorSpec)
|
| 86 |
+
assert isinstance(input_spec, DTensorSpec)
|
| 87 |
+
assert isinstance(weight_spec, DTensorSpec)
|
| 88 |
+
assert isinstance(bias_shape_opt, List)
|
| 89 |
+
assert input_spec.tensor_meta is not None
|
| 90 |
+
weight_tensor_meta = weight_spec.tensor_meta
|
| 91 |
+
bias_tensor_meta = TensorMeta(
|
| 92 |
+
torch.Size(bias_shape_opt),
|
| 93 |
+
(1,),
|
| 94 |
+
input_spec.tensor_meta.dtype,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
grad_input_spec = input_spec
|
| 98 |
+
grad_weight_spec = DTensorSpec.from_dim_map(
|
| 99 |
+
input_spec.mesh,
|
| 100 |
+
[-1, -1, -1, -1],
|
| 101 |
+
[0],
|
| 102 |
+
tensor_meta=weight_tensor_meta,
|
| 103 |
+
)
|
| 104 |
+
grad_bias_spec = DTensorSpec.from_dim_map(
|
| 105 |
+
input_spec.mesh,
|
| 106 |
+
[-1],
|
| 107 |
+
[0],
|
| 108 |
+
tensor_meta=bias_tensor_meta,
|
| 109 |
+
)
|
| 110 |
+
return OutputSharding([grad_input_spec, grad_weight_spec, grad_bias_spec])
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import List, Set, Tuple
|
| 4 |
+
|
| 5 |
+
from torch.distributed.device_mesh import DeviceMesh
|
| 6 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec
|
| 7 |
+
from torch.distributed.tensor._op_schema import OpStrategy, PlacementStrategy
|
| 8 |
+
from torch.distributed.tensor.placement_types import (
|
| 9 |
+
Partial,
|
| 10 |
+
Placement,
|
| 11 |
+
Replicate,
|
| 12 |
+
Shard,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class EinsumDims:
|
| 18 |
+
contracting_dims: List[str]
|
| 19 |
+
batch_dims: List[str]
|
| 20 |
+
lhs_out_only_dims: List[str]
|
| 21 |
+
rhs_out_only_dims: List[str]
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def parse_equation(cls, equation: str) -> Tuple[List[str], str]:
|
| 25 |
+
# parse einop equation and extract arg specs
|
| 26 |
+
"""
|
| 27 |
+
Parse the einsum equation str to input dim chars and output dim char
|
| 28 |
+
"""
|
| 29 |
+
inputs, outputs = equation.split("->")
|
| 30 |
+
input_dims, output_dims = inputs.split(","), outputs.split(",")
|
| 31 |
+
|
| 32 |
+
# NOTE: only support at most two inputs, and single output
|
| 33 |
+
# extend to support more inputs if needed in future
|
| 34 |
+
assert len(input_dims) <= 2, "Only support at most two inputs"
|
| 35 |
+
assert len(output_dims) == 1, "Only support single output"
|
| 36 |
+
output_dim = output_dims[0]
|
| 37 |
+
return input_dims, output_dim
|
| 38 |
+
|
| 39 |
+
@classmethod
|
| 40 |
+
def parse_dims(cls, input_dims: List[str], output_dim: str) -> "EinsumDims":
|
| 41 |
+
"""
|
| 42 |
+
Parse the dims and extract the contracting, batch, and free dimensions
|
| 43 |
+
for the left and right hand sides.
|
| 44 |
+
"""
|
| 45 |
+
dim_char_set: Set[str] = set()
|
| 46 |
+
for input_dim in input_dims:
|
| 47 |
+
dim_char_set.update(input_dim)
|
| 48 |
+
|
| 49 |
+
# get a determinisitc order of all dim chars
|
| 50 |
+
all_dim_chars = sorted(dim_char_set)
|
| 51 |
+
|
| 52 |
+
# parse input and output dimensions
|
| 53 |
+
lhs_out_only_dims, rhs_out_only_dims = [], []
|
| 54 |
+
batch_dims, contracting_dims = [], []
|
| 55 |
+
|
| 56 |
+
for dim_char in all_dim_chars:
|
| 57 |
+
if dim_char not in output_dim:
|
| 58 |
+
contracting_dims.append(dim_char)
|
| 59 |
+
else:
|
| 60 |
+
is_batch_dim = True
|
| 61 |
+
for input_dim in input_dims:
|
| 62 |
+
is_batch_dim = is_batch_dim and dim_char in input_dim
|
| 63 |
+
|
| 64 |
+
if is_batch_dim:
|
| 65 |
+
batch_dims.append(dim_char)
|
| 66 |
+
else:
|
| 67 |
+
assert (
|
| 68 |
+
len(input_dims) == 2
|
| 69 |
+
), "free dimension only supported for two inputs!"
|
| 70 |
+
lhs, rhs = input_dims
|
| 71 |
+
if dim_char in lhs:
|
| 72 |
+
lhs_out_only_dims.append(dim_char)
|
| 73 |
+
elif dim_char in rhs:
|
| 74 |
+
rhs_out_only_dims.append(dim_char)
|
| 75 |
+
else:
|
| 76 |
+
raise RuntimeError("Invalid dimension character")
|
| 77 |
+
|
| 78 |
+
return cls(
|
| 79 |
+
contracting_dims=contracting_dims,
|
| 80 |
+
batch_dims=batch_dims,
|
| 81 |
+
lhs_out_only_dims=lhs_out_only_dims,
|
| 82 |
+
rhs_out_only_dims=rhs_out_only_dims,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def gen_einsum_strategies(
|
| 87 |
+
equation: str,
|
| 88 |
+
mesh: DeviceMesh,
|
| 89 |
+
*,
|
| 90 |
+
linearity: bool = False,
|
| 91 |
+
) -> OpStrategy:
|
| 92 |
+
"""
|
| 93 |
+
Generate a strategy list for the ops that follow einsum style notation.
|
| 94 |
+
"""
|
| 95 |
+
# parse einop equation and extract dims
|
| 96 |
+
input_dims, output_dim = EinsumDims.parse_equation(equation)
|
| 97 |
+
edims = EinsumDims.parse_dims(input_dims, output_dim)
|
| 98 |
+
|
| 99 |
+
all_mesh_dim_strategies = []
|
| 100 |
+
|
| 101 |
+
# generate strategies for each mesh dim
|
| 102 |
+
for mesh_dim in range(mesh.ndim):
|
| 103 |
+
mesh_dim_strategies = []
|
| 104 |
+
|
| 105 |
+
# placement list stores placements of [output, input1, input2, ...]
|
| 106 |
+
# first we always have replicate all for inputs and output
|
| 107 |
+
placement_list: List[Placement] = [Replicate()] * (len(input_dims) + 1)
|
| 108 |
+
mesh_dim_strategies.append(placement_list)
|
| 109 |
+
|
| 110 |
+
if mesh.size(mesh_dim) <= 1:
|
| 111 |
+
# only replicate strategy for mesh dim with size 1
|
| 112 |
+
# TODO: see if this is valid for the submesh case
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
# split batch dim
|
| 116 |
+
for batch_dim in edims.batch_dims:
|
| 117 |
+
output_batch_dim = output_dim.index(batch_dim)
|
| 118 |
+
placement_list = [Shard(output_batch_dim)]
|
| 119 |
+
for input_dim in input_dims:
|
| 120 |
+
input_batch_dim = input_dim.index(batch_dim)
|
| 121 |
+
placement_list.append(Shard(input_batch_dim))
|
| 122 |
+
|
| 123 |
+
mesh_dim_strategies.append(placement_list)
|
| 124 |
+
|
| 125 |
+
# split contracting dim
|
| 126 |
+
for contracting_dim in edims.contracting_dims:
|
| 127 |
+
placement_list = [Partial()]
|
| 128 |
+
for input_dim in input_dims:
|
| 129 |
+
input_contracting_dim = input_dim.index(contracting_dim)
|
| 130 |
+
placement_list.append(Shard(input_contracting_dim))
|
| 131 |
+
|
| 132 |
+
mesh_dim_strategies.append(placement_list)
|
| 133 |
+
|
| 134 |
+
# split lhs free dim
|
| 135 |
+
for lhs_dim in edims.lhs_out_only_dims:
|
| 136 |
+
lhs_free_dim = output_dim.index(lhs_dim)
|
| 137 |
+
# this means split the lhs input and output
|
| 138 |
+
# i.e. S(0), R -> S(0)
|
| 139 |
+
lhs_placement_list: List[Placement] = [
|
| 140 |
+
Shard(lhs_free_dim),
|
| 141 |
+
Shard(lhs_free_dim),
|
| 142 |
+
Replicate(),
|
| 143 |
+
]
|
| 144 |
+
mesh_dim_strategies.append(lhs_placement_list)
|
| 145 |
+
|
| 146 |
+
# split rhs free dim
|
| 147 |
+
for rhs_dim in edims.rhs_out_only_dims:
|
| 148 |
+
rhs_free_dim = output_dim.index(rhs_dim)
|
| 149 |
+
rhs_placement_list: List[Placement] = [
|
| 150 |
+
Shard(rhs_free_dim),
|
| 151 |
+
Replicate(),
|
| 152 |
+
Shard(rhs_free_dim),
|
| 153 |
+
]
|
| 154 |
+
mesh_dim_strategies.append(rhs_placement_list)
|
| 155 |
+
|
| 156 |
+
# linearity strategy
|
| 157 |
+
if linearity:
|
| 158 |
+
linearity_placement_list: List[Placement] = [Partial()]
|
| 159 |
+
for input_dim in input_dims:
|
| 160 |
+
linearity_placement_list.append(Partial())
|
| 161 |
+
mesh_dim_strategies.append(linearity_placement_list)
|
| 162 |
+
|
| 163 |
+
all_mesh_dim_strategies.append(mesh_dim_strategies)
|
| 164 |
+
|
| 165 |
+
# generate strategies for entire mesh
|
| 166 |
+
strategy_combs = itertools.product(*all_mesh_dim_strategies)
|
| 167 |
+
|
| 168 |
+
# TODO: filter out invalid strategies, at this point we generate
|
| 169 |
+
# all possible strategies without considering the whether the tensor
|
| 170 |
+
# dim could be sharded or not, we would need to filter out invalid
|
| 171 |
+
# strategies base on the actual tensor shape
|
| 172 |
+
# (i.e. for Shard, tensor dim size must > mesh size)
|
| 173 |
+
all_strategies = []
|
| 174 |
+
for strategy_comb in strategy_combs:
|
| 175 |
+
spec_list = []
|
| 176 |
+
for specs in zip(*strategy_comb):
|
| 177 |
+
spec_list.append(DTensorSpec(mesh, tuple(specs)))
|
| 178 |
+
strat = PlacementStrategy(output_specs=spec_list[0], input_specs=spec_list[1:])
|
| 179 |
+
all_strategies.append(strat)
|
| 180 |
+
|
| 181 |
+
return OpStrategy(all_strategies)
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_experimental_ops.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 3 |
+
# implement matrix related ops for distributed tensor
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec
|
| 7 |
+
from torch.distributed.tensor._op_schema import (
|
| 8 |
+
OpSchema,
|
| 9 |
+
OpStrategy,
|
| 10 |
+
PlacementStrategy,
|
| 11 |
+
StrategyType,
|
| 12 |
+
)
|
| 13 |
+
from torch.distributed.tensor._ops.utils import register_op_strategy
|
| 14 |
+
from torch.distributed.tensor.device_mesh import DeviceMesh
|
| 15 |
+
from torch.distributed.tensor.placement_types import Replicate
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
aten = torch.ops.aten
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@register_op_strategy(aten.slice_backward.default)
|
| 22 |
+
def slice_backward_rules(mesh: DeviceMesh, op_schema: OpSchema) -> StrategyType:
|
| 23 |
+
"""
|
| 24 |
+
slice_backward is a new_zeros + slice_scatter, we only allow replication
|
| 25 |
+
on the input/output for now since new_zeros would produce replication
|
| 26 |
+
"""
|
| 27 |
+
replicate_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
|
| 28 |
+
return OpStrategy([PlacementStrategy(replicate_spec)])
|
vllm/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_math_ops.py
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 4 |
+
import math
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from typing import cast, List, Optional, Sequence, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch.distributed.device_mesh import DeviceMesh
|
| 11 |
+
from torch.distributed.tensor._dtensor_spec import DTensorSpec
|
| 12 |
+
from torch.distributed.tensor._op_schema import (
|
| 13 |
+
OpSchema,
|
| 14 |
+
OpStrategy,
|
| 15 |
+
PlacementList,
|
| 16 |
+
PlacementStrategy,
|
| 17 |
+
RuntimeSchemaInfo,
|
| 18 |
+
TupleStrategy,
|
| 19 |
+
)
|
| 20 |
+
from torch.distributed.tensor._ops.utils import (
|
| 21 |
+
as_list,
|
| 22 |
+
expand_to_full_mesh_op_strategy,
|
| 23 |
+
generate_redistribute_costs,
|
| 24 |
+
is_tensor_evenly_shardable,
|
| 25 |
+
normalize_dim,
|
| 26 |
+
normalize_dims,
|
| 27 |
+
register_op_strategy,
|
| 28 |
+
)
|
| 29 |
+
from torch.distributed.tensor._utils import normalize_to_torch_size
|
| 30 |
+
from torch.distributed.tensor.placement_types import (
|
| 31 |
+
Partial,
|
| 32 |
+
Placement,
|
| 33 |
+
Replicate,
|
| 34 |
+
Shard,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
aten = torch.ops.aten
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Reduction(Enum):
|
| 42 |
+
NONE = 0
|
| 43 |
+
MEAN = 1
|
| 44 |
+
SUM = 2
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass(frozen=True)
|
| 48 |
+
class NormReduction:
|
| 49 |
+
norm_type: Union[int, float, str]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
ReductionOpType = Union[NormReduction, str]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class _NormPartial(Partial):
|
| 57 |
+
"""
|
| 58 |
+
This placement is used for partial vector norm.
|
| 59 |
+
|
| 60 |
+
For p-norms (where p not inf or -inf), the p-norm over n elements computes
|
| 61 |
+
(sum_i x_i^p)^(1/p)
|
| 62 |
+
where the sum is from i=1 to n. The reduction op is the p-norm itself.
|
| 63 |
+
For example, consider 2 ranks, a (4,) tensor sharded on dim-0, and 2-norm:
|
| 64 |
+
Rank 0: [t1, t2] | Rank 1: [t3, t4]
|
| 65 |
+
After computing 2-norm per gradient (partial placement):
|
| 66 |
+
Rank 0: [sqrt(t1^2 + t2^2)] | Rank 1: [sqrt(t3^2 + t4^2)]
|
| 67 |
+
Converting from partial to replicate wants to ultimately get:
|
| 68 |
+
Rank 0/1: [sqrt(t1^2 + t2^2 + t3^2 + t4^2)]
|
| 69 |
+
This can be achieved by computing 2-norm on each rank's result. This holds
|
| 70 |
+
similarly for inf and -inf norm. For 0-norm, the reduction op is sum.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
norm_type: Union[int, float, str] = 2
|
| 74 |
+
|
| 75 |
+
def __post_init__(self):
|
| 76 |
+
"""Set the appropriate reduce op based on the norm type."""
|
| 77 |
+
# Use `object.__setattr__` to bypass frozen checks
|
| 78 |
+
if self.norm_type in (float("inf"), "inf"):
|
| 79 |
+
object.__setattr__(self, "reduce_op", "max")
|
| 80 |
+
elif self.norm_type in (float("-inf"), "-inf"):
|
| 81 |
+
object.__setattr__(self, "reduce_op", "min")
|
| 82 |
+
elif isinstance(self.norm_type, (int, float)):
|
| 83 |
+
object.__setattr__(self, "reduce_op", "sum")
|
| 84 |
+
else:
|
| 85 |
+
raise NotImplementedError(f"Unsupported norm type: {self.norm_type}")
|
| 86 |
+
|
| 87 |
+
def _partition_value(
|
| 88 |
+
self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
|
| 89 |
+
) -> torch.Tensor:
|
| 90 |
+
"""
|
| 91 |
+
For example, consider 4 ranks, a (3,) replicated tensor, and 2-norm:
|
| 92 |
+
Ranks 0 and 1: sqrt(t1^2 + t2^2 + t3^3)
|
| 93 |
+
To convert from replicated to partial, we want f(x) such that
|
| 94 |
+
sqrt(t1^2 + t2^2 + t3^3) = sqrt(4f(t1)^2 + 4f(t2)^2 + 4f(t3)^2)
|
| 95 |
+
= sqrt(4) sqrt(f(t1)^2 + f(t2)^2 + f(t3)^2).
|
| 96 |
+
One such f(x) is f(x) = x / sqrt(4). This generalizes to d ranks and
|
| 97 |
+
p-norm as f(x) = x / d^(1/p).
|
| 98 |
+
"""
|
| 99 |
+
if self.reduce_op in ("max", "min"):
|
| 100 |
+
return tensor
|
| 101 |
+
elif self.reduce_op == "sum":
|
| 102 |
+
if self.norm_type == 0:
|
| 103 |
+
raise NotImplementedError(f"Unsupported norm type:: {self.norm_type}")
|
| 104 |
+
elif self.norm_type == 1:
|
| 105 |
+
return tensor / mesh.size(mesh_dim)
|
| 106 |
+
assert isinstance(self.norm_type, (int, float))
|
| 107 |
+
return tensor / math.pow(mesh.size(mesh_dim), 1 / self.norm_type)
|
| 108 |
+
raise NotImplementedError(self.reduce_op)
|
| 109 |
+
|
| 110 |
+
def _reduce_shard_value(
|
| 111 |
+
self,
|
| 112 |
+
tensor: torch.Tensor,
|
| 113 |
+
mesh: DeviceMesh,
|
| 114 |
+
mesh_dim: int,
|
| 115 |
+
shard_spec: Placement,
|
| 116 |
+
) -> torch.Tensor:
|
| 117 |
+
assert isinstance(shard_spec, Shard), f"{shard_spec}"
|
| 118 |
+
tensor = self._pre_reduce_transform(tensor)
|
| 119 |
+
reduced_tensor = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
|
| 120 |
+
return self._post_reduce_transform(reduced_tensor)
|
| 121 |
+
|
| 122 |
+
def _reduce_value(
|
| 123 |
+
self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
|
| 124 |
+
) -> torch.Tensor:
|
| 125 |
+
tensor = self._pre_reduce_transform(tensor)
|
| 126 |
+
reduced_tensor = super()._reduce_value(tensor, mesh, mesh_dim)
|
| 127 |
+
return self._post_reduce_transform(reduced_tensor)
|
| 128 |
+
|
| 129 |
+
def _pre_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 130 |
+
if self.reduce_op == "sum":
|
| 131 |
+
assert isinstance(self.norm_type, (int, float)), f"{self.norm_type}"
|
| 132 |
+
if self.norm_type != 0 and self.norm_type != 1:
|
| 133 |
+
return tensor**self.norm_type
|
| 134 |
+
return tensor
|
| 135 |
+
|
| 136 |
+
def _post_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 137 |
+
if self.reduce_op == "sum":
|
| 138 |
+
assert isinstance(self.norm_type, (int, float)), f"{self.norm_type}"
|
| 139 |
+
if self.norm_type != 0 and self.norm_type != 1:
|
| 140 |
+
return tensor ** (1.0 / self.norm_type)
|
| 141 |
+
return tensor
|
| 142 |
+
|
| 143 |
+
def __eq__(self, other: object) -> bool:
|
| 144 |
+
if not isinstance(other, _NormPartial):
|
| 145 |
+
return False
|
| 146 |
+
return self.norm_type == other.norm_type
|
| 147 |
+
|
| 148 |
+
def __hash__(self) -> int:
|
| 149 |
+
return 1 + hash(self.norm_type)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _infer_reduction_dims(dims_arg: object, ndim: int) -> Optional[List[int]]:
|
| 153 |
+
if dims_arg is None:
|
| 154 |
+
return None
|
| 155 |
+
dims = cast(List[int], as_list(dims_arg))
|
| 156 |
+
dims = cast(List[int], normalize_dims(dims, ndim))
|
| 157 |
+
empty_dims = [[0], [-1], []]
|
| 158 |
+
if ndim == 0 and dims_arg in empty_dims:
|
| 159 |
+
return None
|
| 160 |
+
return dims
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _infer_reduce_dims_map(
|
| 164 |
+
reduction_dims: List[int], input_ndim: int, keep_dim=False
|
| 165 |
+
) -> List[int]:
|
| 166 |
+
reduction_dims_map = []
|
| 167 |
+
new_dim_count = 0
|
| 168 |
+
for input_dim in range(input_ndim):
|
| 169 |
+
if input_dim in reduction_dims and not keep_dim:
|
| 170 |
+
# if input dim in reduction dims, mark it as -1
|
| 171 |
+
reduction_dims_map.append(-1)
|
| 172 |
+
else:
|
| 173 |
+
# otherwise mark it as the new dim
|
| 174 |
+
reduction_dims_map.append(new_dim_count)
|
| 175 |
+
new_dim_count += 1
|
| 176 |
+
|
| 177 |
+
return reduction_dims_map
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _replicate_dims_start_at(
|
| 181 |
+
placements: Sequence[Placement], start_dim: int = 0
|
| 182 |
+
) -> Tuple[Placement, ...]:
|
| 183 |
+
new_placements: List[Placement] = []
|
| 184 |
+
for p in placements:
|
| 185 |
+
if p.is_partial() or (isinstance(p, Shard) and p.dim >= start_dim):
|
| 186 |
+
new_placements.append(Replicate()) # make it replicate
|
| 187 |
+
else:
|
| 188 |
+
new_placements.append(p) # keep the placement
|
| 189 |
+
return tuple(new_placements)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# return new_placements which align with placements but skip the skipped_dim
|
| 193 |
+
def _skip_dim(
|
| 194 |
+
placements: Tuple[Placement, ...], skipped_dim: int
|
| 195 |
+
) -> Tuple[Placement, ...]:
|
| 196 |
+
new_placements: List[Placement] = []
|
| 197 |
+
for p in placements:
|
| 198 |
+
if isinstance(p, Shard) and p.dim >= skipped_dim:
|
| 199 |
+
new_placements.append(Shard(p.dim - 1))
|
| 200 |
+
else:
|
| 201 |
+
new_placements.append(p)
|
| 202 |
+
return tuple(new_placements)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def replicate_reduction_dims(
|
| 206 |
+
placements: Tuple[Placement, ...], reduction_dims: List[int]
|
| 207 |
+
) -> Tuple[Placement, ...]:
|
| 208 |
+
# replicate the reduction dims if not reduction_linear
|
| 209 |
+
new_placements: List[Placement] = []
|
| 210 |
+
|
| 211 |
+
for p in placements:
|
| 212 |
+
if p.is_partial():
|
| 213 |
+
new_placements.append(Replicate())
|
| 214 |
+
elif isinstance(p, Shard) and p.dim in reduction_dims:
|
| 215 |
+
new_placements.append(Replicate())
|
| 216 |
+
else:
|
| 217 |
+
new_placements.append(p)
|
| 218 |
+
|
| 219 |
+
return tuple(new_placements)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def map_placements_after_reduction(
|
| 223 |
+
placements: Tuple[Placement, ...],
|
| 224 |
+
reduction_dims: List[int],
|
| 225 |
+
reduction_dims_map: List[int],
|
| 226 |
+
reduction_op: ReductionOpType,
|
| 227 |
+
) -> Tuple[Placement, ...]:
|
| 228 |
+
"""
|
| 229 |
+
Map each placement based on the output shape after reduction.
|
| 230 |
+
"""
|
| 231 |
+
new_placements: List[Placement] = []
|
| 232 |
+
for placement in placements:
|
| 233 |
+
if isinstance(placement, (Replicate, Partial)):
|
| 234 |
+
new_placements.append(placement)
|
| 235 |
+
else:
|
| 236 |
+
assert isinstance(placement, Shard)
|
| 237 |
+
shard_dim = placement.dim
|
| 238 |
+
new_shard_dim = reduction_dims_map[shard_dim]
|
| 239 |
+
if new_shard_dim == -1 or shard_dim in reduction_dims:
|
| 240 |
+
# if new_shard_dim collapsed or its in the reduction dims
|
| 241 |
+
# (i.e. for the case where keepdims=True), we generate partial
|
| 242 |
+
new_placements.append(get_placement_from_reduction_op(reduction_op))
|
| 243 |
+
else:
|
| 244 |
+
new_placements.append(Shard(new_shard_dim))
|
| 245 |
+
return tuple(new_placements)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def get_placement_from_reduction_op(reduction_op: ReductionOpType) -> Placement:
|
| 249 |
+
if isinstance(reduction_op, NormReduction):
|
| 250 |
+
return _NormPartial(norm_type=reduction_op.norm_type)
|
| 251 |
+
return Partial(reduction_op)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def common_reduction_strategy(
|
| 255 |
+
mesh: DeviceMesh,
|
| 256 |
+
input_strategy: OpStrategy,
|
| 257 |
+
reduce_dims: List[int],
|
| 258 |
+
keep_dim: bool = False,
|
| 259 |
+
reduction_linear: bool = True,
|
| 260 |
+
reduction_op: ReductionOpType = "sum",
|
| 261 |
+
) -> OpStrategy:
|
| 262 |
+
"""
|
| 263 |
+
reduction_linear means that the reduction `f` follows this rule:
|
| 264 |
+
f([f(a), f(b)]) = f([a, b])
|
| 265 |
+
|
| 266 |
+
reduction linear should be super set of linearity.
|
| 267 |
+
"""
|
| 268 |
+
# by default follow reduction input strategy
|
| 269 |
+
reduction_strategy = OpStrategy([])
|
| 270 |
+
|
| 271 |
+
for strtg in input_strategy.strategies:
|
| 272 |
+
if not reduction_linear:
|
| 273 |
+
# input placements for this strategy should clear out pending sum and sharding
|
| 274 |
+
# on the reduction dimension
|
| 275 |
+
input_placements = replicate_reduction_dims(
|
| 276 |
+
strtg.output_spec.placements, reduce_dims
|
| 277 |
+
)
|
| 278 |
+
else:
|
| 279 |
+
input_placements = strtg.output_spec.placements
|
| 280 |
+
|
| 281 |
+
input_spec = DTensorSpec(
|
| 282 |
+
mesh=mesh,
|
| 283 |
+
placements=input_placements,
|
| 284 |
+
tensor_meta=strtg.output_spec.tensor_meta,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
reduce_dims_map = _infer_reduce_dims_map(reduce_dims, input_spec.ndim, keep_dim)
|
| 288 |
+
out_placements = map_placements_after_reduction(
|
| 289 |
+
input_spec.placements, reduce_dims, reduce_dims_map, reduction_op
|
| 290 |
+
)
|
| 291 |
+
redistribute_cost = [generate_redistribute_costs(input_strategy, input_spec)]
|
| 292 |
+
reduction_strategy.strategies.append(
|
| 293 |
+
PlacementStrategy(
|
| 294 |
+
output_specs=DTensorSpec(
|
| 295 |
+
mesh=mesh,
|
| 296 |
+
placements=out_placements,
|
| 297 |
+
),
|
| 298 |
+
input_specs=(input_spec,),
|
| 299 |
+
redistribute_cost=redistribute_cost,
|
| 300 |
+
)
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
return reduction_strategy
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
LINEAR_REDUCTION_OP_MAP = {
|
| 307 |
+
aten.all.default: "sum",
|
| 308 |
+
aten.all.dim: "sum",
|
| 309 |
+
aten.sum.default: "sum",
|
| 310 |
+
aten.sum.dim_IntList: "sum",
|
| 311 |
+
aten.prod.default: "product",
|
| 312 |
+
aten.prod.dim_int: "product",
|
| 313 |
+
aten.prod.int_out: "product",
|
| 314 |
+
aten.mean.default: "avg",
|
| 315 |
+
aten.mean.dim: "avg",
|
| 316 |
+
aten.mean.out: "avg",
|
| 317 |
+
aten.max.default: "max",
|
| 318 |
+
aten.max.dim: "max",
|
| 319 |
+
aten.max.out: "max",
|
| 320 |
+
aten.min.default: "min",
|
| 321 |
+
aten.min.dim: "min",
|
| 322 |
+
aten.min.out: "min",
|
| 323 |
+
aten.any.default: "sum",
|
| 324 |
+
aten.any.dim: "sum",
|
| 325 |
+
aten.any.out: "sum",
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@register_op_strategy(
|
| 330 |
+
list(LINEAR_REDUCTION_OP_MAP.keys()), schema_info=RuntimeSchemaInfo(1)
|
| 331 |
+
)
|
| 332 |
+
def linear_reduction_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 333 |
+
args_schema = op_schema.args_schema
|
| 334 |
+
input_strategy = args_schema[0]
|
| 335 |
+
assert isinstance(input_strategy, OpStrategy)
|
| 336 |
+
dims = None
|
| 337 |
+
if len(op_schema.args_schema) > 1:
|
| 338 |
+
dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
|
| 339 |
+
|
| 340 |
+
reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
|
| 341 |
+
|
| 342 |
+
keep_dim = len(op_schema.args_schema) > 2 and bool(op_schema.args_schema[2])
|
| 343 |
+
reduction_op = LINEAR_REDUCTION_OP_MAP[op_schema.op]
|
| 344 |
+
return common_reduction_strategy(
|
| 345 |
+
mesh,
|
| 346 |
+
input_strategy,
|
| 347 |
+
reduce_dims,
|
| 348 |
+
keep_dim=keep_dim,
|
| 349 |
+
reduction_linear=True,
|
| 350 |
+
reduction_op=reduction_op,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@register_op_strategy(
|
| 355 |
+
[aten.var.correction, aten.var.correction_out],
|
| 356 |
+
schema_info=RuntimeSchemaInfo(1, ["keepdim"]),
|
| 357 |
+
)
|
| 358 |
+
def var_reduction_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 359 |
+
args_schema = op_schema.args_schema
|
| 360 |
+
input_strategy = args_schema[0]
|
| 361 |
+
assert isinstance(input_strategy, OpStrategy)
|
| 362 |
+
dims = None
|
| 363 |
+
if len(op_schema.args_schema) > 1:
|
| 364 |
+
dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
|
| 365 |
+
|
| 366 |
+
reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
|
| 367 |
+
|
| 368 |
+
keep_dim = cast(bool, op_schema.kwargs_schema.get("keepdim", False))
|
| 369 |
+
return common_reduction_strategy(
|
| 370 |
+
mesh, input_strategy, reduce_dims, keep_dim=keep_dim, reduction_linear=False
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@register_op_strategy(
|
| 375 |
+
[aten.linalg_vector_norm.default], schema_info=RuntimeSchemaInfo(1)
|
| 376 |
+
)
|
| 377 |
+
def vector_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 378 |
+
args_schema = op_schema.args_schema
|
| 379 |
+
input_strategy = args_schema[0]
|
| 380 |
+
assert isinstance(input_strategy, OpStrategy)
|
| 381 |
+
norm_type = args_schema[1] if len(args_schema) > 1 else 2
|
| 382 |
+
assert isinstance(norm_type, (int, float, str)), f"{norm_type}"
|
| 383 |
+
dim = args_schema[2] if len(args_schema) > 2 else None
|
| 384 |
+
keepdim = args_schema[3] if len(args_schema) > 3 else False
|
| 385 |
+
dims = _infer_reduction_dims(dim, input_strategy.ndim)
|
| 386 |
+
reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
|
| 387 |
+
return common_reduction_strategy(
|
| 388 |
+
mesh,
|
| 389 |
+
input_strategy,
|
| 390 |
+
reduce_dims,
|
| 391 |
+
keep_dim=cast(bool, keepdim),
|
| 392 |
+
reduction_linear=True,
|
| 393 |
+
reduction_op=NormReduction(norm_type),
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@register_op_strategy(
|
| 398 |
+
[aten._foreach_norm.Scalar], schema_info=RuntimeSchemaInfo(1, needs_pytree=True)
|
| 399 |
+
)
|
| 400 |
+
def foreach_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> TupleStrategy:
|
| 401 |
+
args_schema = op_schema.args_schema
|
| 402 |
+
input_tuple_strategy = args_schema[0]
|
| 403 |
+
assert isinstance(input_tuple_strategy, TupleStrategy)
|
| 404 |
+
norm_type = args_schema[1] if len(args_schema) > 1 else 2
|
| 405 |
+
assert isinstance(norm_type, (int, float, str)), f"{norm_type}"
|
| 406 |
+
output_tuple_strategy_childs: List[OpStrategy] = []
|
| 407 |
+
for op_strategy in input_tuple_strategy.childs:
|
| 408 |
+
assert isinstance(op_strategy, OpStrategy), f"{op_strategy}"
|
| 409 |
+
reduce_dims = list(range(op_strategy.ndim))
|
| 410 |
+
output_strategy = common_reduction_strategy(
|
| 411 |
+
mesh,
|
| 412 |
+
op_strategy,
|
| 413 |
+
reduce_dims,
|
| 414 |
+
reduction_linear=True,
|
| 415 |
+
reduction_op=NormReduction(norm_type),
|
| 416 |
+
)
|
| 417 |
+
output_tuple_strategy_childs.append(output_strategy)
|
| 418 |
+
return TupleStrategy(output_tuple_strategy_childs)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@register_op_strategy(
|
| 422 |
+
[
|
| 423 |
+
aten._linalg_svd.default,
|
| 424 |
+
aten.linalg_qr.default,
|
| 425 |
+
# TODO: The diagonal ops can have an improved sharding strategy for
|
| 426 |
+
# shard placements that does not require redistributing to replicate.
|
| 427 |
+
aten.diagonal_copy.default,
|
| 428 |
+
aten.diag_embed.default,
|
| 429 |
+
aten.diag.default,
|
| 430 |
+
aten.diagonal.default,
|
| 431 |
+
aten.tril.default,
|
| 432 |
+
aten.triu.default,
|
| 433 |
+
aten._linalg_eigh.default,
|
| 434 |
+
],
|
| 435 |
+
schema_info=RuntimeSchemaInfo(1),
|
| 436 |
+
)
|
| 437 |
+
def linalg_replicate_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 438 |
+
"""
|
| 439 |
+
Since we do not have a simple way to compute some linear algebra operations
|
| 440 |
+
like SVD or QR decomposition, always fall back to replicate.
|
| 441 |
+
"""
|
| 442 |
+
args_schema = op_schema.args_schema
|
| 443 |
+
input_strategy = args_schema[0]
|
| 444 |
+
assert isinstance(input_strategy, OpStrategy), f"{input_strategy}"
|
| 445 |
+
output_strategies: List[PlacementStrategy] = []
|
| 446 |
+
for placement_strategy in input_strategy.strategies:
|
| 447 |
+
replicate_placements = tuple(Replicate() for _ in range(mesh.ndim))
|
| 448 |
+
replicate_spec = DTensorSpec(
|
| 449 |
+
mesh=mesh,
|
| 450 |
+
placements=replicate_placements,
|
| 451 |
+
tensor_meta=placement_strategy.output_spec.tensor_meta,
|
| 452 |
+
)
|
| 453 |
+
redistribute_cost = [
|
| 454 |
+
generate_redistribute_costs(input_strategy, replicate_spec)
|
| 455 |
+
]
|
| 456 |
+
replicate_strategy = PlacementStrategy(
|
| 457 |
+
output_specs=replicate_spec,
|
| 458 |
+
input_specs=(replicate_spec,),
|
| 459 |
+
redistribute_cost=redistribute_cost,
|
| 460 |
+
)
|
| 461 |
+
output_strategies.append(replicate_strategy)
|
| 462 |
+
return OpStrategy(output_strategies)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
@register_op_strategy(
|
| 466 |
+
[aten._log_softmax.default, aten._softmax.default, aten._safe_softmax.default],
|
| 467 |
+
schema_info=RuntimeSchemaInfo(1),
|
| 468 |
+
)
|
| 469 |
+
def softmax_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 470 |
+
input_strategy, softmax_dim, *_ = op_schema.args_schema
|
| 471 |
+
input_strategy = cast(OpStrategy, input_strategy)
|
| 472 |
+
softmax_dim = cast(int, softmax_dim)
|
| 473 |
+
softmax_dim = normalize_dim(softmax_dim, input_strategy.ndim)
|
| 474 |
+
|
| 475 |
+
output_strategy = OpStrategy([])
|
| 476 |
+
for idx, input_placement_strategy in enumerate(input_strategy.strategies):
|
| 477 |
+
redistribute_costs = []
|
| 478 |
+
input_src_spec = input_placement_strategy.output_spec
|
| 479 |
+
|
| 480 |
+
# make sure input is replicated along the softmax dim
|
| 481 |
+
input_target_spec = DTensorSpec(
|
| 482 |
+
mesh=mesh,
|
| 483 |
+
placements=replicate_reduction_dims(
|
| 484 |
+
input_src_spec.placements, [softmax_dim]
|
| 485 |
+
),
|
| 486 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 487 |
+
)
|
| 488 |
+
redistribute_costs.append(
|
| 489 |
+
generate_redistribute_costs(input_strategy, input_target_spec)
|
| 490 |
+
)
|
| 491 |
+
output_target_spec = input_target_spec
|
| 492 |
+
output_strategy.strategies.append(
|
| 493 |
+
PlacementStrategy(
|
| 494 |
+
output_specs=output_target_spec,
|
| 495 |
+
input_specs=[input_target_spec],
|
| 496 |
+
redistribute_cost=redistribute_costs,
|
| 497 |
+
)
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
return output_strategy
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@register_op_strategy(
|
| 504 |
+
[
|
| 505 |
+
aten._log_softmax_backward_data.default,
|
| 506 |
+
aten._softmax_backward_data.default,
|
| 507 |
+
],
|
| 508 |
+
schema_info=RuntimeSchemaInfo(2),
|
| 509 |
+
)
|
| 510 |
+
def softmax_backward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 511 |
+
grad_out_strategy, out_strategy, softmax_dim, _ = op_schema.args_schema
|
| 512 |
+
grad_out_strategy = cast(OpStrategy, grad_out_strategy)
|
| 513 |
+
out_strategy = cast(OpStrategy, out_strategy)
|
| 514 |
+
softmax_dim = cast(int, softmax_dim)
|
| 515 |
+
softmax_dim = normalize_dim(softmax_dim, grad_out_strategy.ndim)
|
| 516 |
+
|
| 517 |
+
grad_in_strategy = OpStrategy([])
|
| 518 |
+
for grad_out_placement_strat, out_placement_strat in zip(
|
| 519 |
+
grad_out_strategy.strategies, out_strategy.strategies
|
| 520 |
+
):
|
| 521 |
+
# follow the sharding of the grad_out or out depending on which has more shards
|
| 522 |
+
grad_out_src_spec = grad_out_placement_strat.output_spec
|
| 523 |
+
out_src_spec = out_placement_strat.output_spec
|
| 524 |
+
src_spec = (
|
| 525 |
+
grad_out_src_spec
|
| 526 |
+
if grad_out_src_spec.num_shards >= out_src_spec.num_shards
|
| 527 |
+
else out_src_spec
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# make sure inputs are replicated along the softmax dim
|
| 531 |
+
tgt_spec = DTensorSpec(
|
| 532 |
+
mesh=mesh,
|
| 533 |
+
placements=replicate_reduction_dims(src_spec.placements, [softmax_dim]),
|
| 534 |
+
)
|
| 535 |
+
redist_grad_out_cost = generate_redistribute_costs(grad_out_strategy, tgt_spec)
|
| 536 |
+
redist_out_cost = generate_redistribute_costs(out_strategy, tgt_spec)
|
| 537 |
+
grad_in_strategy.strategies.append(
|
| 538 |
+
PlacementStrategy(
|
| 539 |
+
output_specs=tgt_spec,
|
| 540 |
+
redistribute_cost=[redist_grad_out_cost, redist_out_cost],
|
| 541 |
+
)
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
return grad_in_strategy
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
@register_op_strategy(
|
| 548 |
+
[aten.nll_loss_forward.default, aten.nll_loss2d_forward.default],
|
| 549 |
+
schema_info=RuntimeSchemaInfo(3),
|
| 550 |
+
)
|
| 551 |
+
def nll_loss_forward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 552 |
+
assert len(op_schema.args_schema) == 5
|
| 553 |
+
(
|
| 554 |
+
input_strategy,
|
| 555 |
+
target_strategy,
|
| 556 |
+
weight_strategy,
|
| 557 |
+
reduction,
|
| 558 |
+
_,
|
| 559 |
+
) = op_schema.args_schema
|
| 560 |
+
input_strategy = cast(OpStrategy, input_strategy)
|
| 561 |
+
target_strategy = cast(OpStrategy, target_strategy)
|
| 562 |
+
reduction = cast(int, reduction)
|
| 563 |
+
|
| 564 |
+
input_shape = input_strategy.shape
|
| 565 |
+
channel_dim = 1 if len(input_shape) >= 2 else 0
|
| 566 |
+
|
| 567 |
+
output_strategy = OpStrategy([])
|
| 568 |
+
for idx, input_placement_strategy in enumerate(input_strategy.strategies):
|
| 569 |
+
op_args_target_specs = []
|
| 570 |
+
redistribute_costs = []
|
| 571 |
+
|
| 572 |
+
# make sure input is replicated along the channel dim
|
| 573 |
+
input_src_spec = input_placement_strategy.output_spec
|
| 574 |
+
input_expected_spec = DTensorSpec(
|
| 575 |
+
mesh=mesh,
|
| 576 |
+
placements=replicate_reduction_dims(
|
| 577 |
+
input_src_spec.placements, [channel_dim]
|
| 578 |
+
),
|
| 579 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 580 |
+
)
|
| 581 |
+
op_args_target_specs.append(input_expected_spec)
|
| 582 |
+
redistribute_costs.append(
|
| 583 |
+
generate_redistribute_costs(input_strategy, input_expected_spec)
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# target doesn't have channel dim, and it follows input on other dims
|
| 587 |
+
target_src_spec = target_strategy.strategies[idx].output_spec
|
| 588 |
+
target_expected_spec = DTensorSpec(
|
| 589 |
+
mesh=mesh,
|
| 590 |
+
placements=_skip_dim(input_expected_spec.placements, channel_dim),
|
| 591 |
+
tensor_meta=target_src_spec.tensor_meta,
|
| 592 |
+
)
|
| 593 |
+
op_args_target_specs.append(target_expected_spec)
|
| 594 |
+
redistribute_costs.append(
|
| 595 |
+
generate_redistribute_costs(target_strategy, target_expected_spec)
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
# weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
|
| 599 |
+
# make sure it is replicated
|
| 600 |
+
if weight_strategy is not None:
|
| 601 |
+
assert isinstance(weight_strategy, OpStrategy)
|
| 602 |
+
weight_src_spec = weight_strategy.strategies[idx].output_spec
|
| 603 |
+
weight_expected_spec = DTensorSpec(
|
| 604 |
+
mesh=mesh,
|
| 605 |
+
placements=_replicate_dims_start_at(weight_src_spec.placements),
|
| 606 |
+
tensor_meta=weight_src_spec.tensor_meta,
|
| 607 |
+
)
|
| 608 |
+
op_args_target_specs.append(weight_expected_spec)
|
| 609 |
+
redistribute_costs.append(
|
| 610 |
+
generate_redistribute_costs(weight_strategy, weight_expected_spec)
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
if reduction == Reduction.NONE.value:
|
| 614 |
+
output_expected_spec = target_expected_spec
|
| 615 |
+
total_weight_expected_spec = DTensorSpec(
|
| 616 |
+
mesh=mesh, placements=tuple([Replicate()] * mesh.ndim)
|
| 617 |
+
)
|
| 618 |
+
else:
|
| 619 |
+
if reduction == Reduction.MEAN.value:
|
| 620 |
+
reduction_op = "avg"
|
| 621 |
+
if not is_tensor_evenly_shardable(
|
| 622 |
+
target_expected_spec.shape, target_expected_spec
|
| 623 |
+
):
|
| 624 |
+
raise ValueError(
|
| 625 |
+
"The intermediate results of nll_loss cannot be evenly sharded, \
|
| 626 |
+
resulting in biased mean result."
|
| 627 |
+
)
|
| 628 |
+
else: # reduction == Reduction.SUM.value:
|
| 629 |
+
reduction_op = "sum"
|
| 630 |
+
reduce_dims = list(range(target_expected_spec.ndim))
|
| 631 |
+
reduce_dims_map = _infer_reduce_dims_map(
|
| 632 |
+
reduce_dims, target_expected_spec.ndim, keep_dim=False
|
| 633 |
+
)
|
| 634 |
+
out_placements = map_placements_after_reduction(
|
| 635 |
+
target_expected_spec.placements,
|
| 636 |
+
reduce_dims,
|
| 637 |
+
reduce_dims_map,
|
| 638 |
+
reduction_op,
|
| 639 |
+
)
|
| 640 |
+
output_expected_spec = DTensorSpec(
|
| 641 |
+
mesh=mesh,
|
| 642 |
+
placements=out_placements,
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
# whether reduction is sum or mean, the total weight has to be summed up if not replicated
|
| 646 |
+
total_weight_placements = map_placements_after_reduction(
|
| 647 |
+
target_expected_spec.placements,
|
| 648 |
+
reduce_dims,
|
| 649 |
+
reduce_dims_map,
|
| 650 |
+
"sum",
|
| 651 |
+
)
|
| 652 |
+
total_weight_expected_spec = DTensorSpec(
|
| 653 |
+
mesh=mesh,
|
| 654 |
+
placements=total_weight_placements,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
output_strategy.strategies.append(
|
| 658 |
+
PlacementStrategy(
|
| 659 |
+
output_specs=(output_expected_spec, total_weight_expected_spec),
|
| 660 |
+
input_specs=op_args_target_specs,
|
| 661 |
+
redistribute_cost=redistribute_costs,
|
| 662 |
+
)
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
return output_strategy
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
@register_op_strategy(
|
| 669 |
+
[aten.nll_loss_backward.default, aten.nll_loss2d_backward.default],
|
| 670 |
+
schema_info=RuntimeSchemaInfo(4),
|
| 671 |
+
)
|
| 672 |
+
def nll_loss_backward_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 673 |
+
assert len(op_schema.args_schema) == 7
|
| 674 |
+
(
|
| 675 |
+
grad_out_strategy,
|
| 676 |
+
input_strategy,
|
| 677 |
+
target_strategy,
|
| 678 |
+
weight_strategy,
|
| 679 |
+
reduction,
|
| 680 |
+
_,
|
| 681 |
+
total_weight_strategy,
|
| 682 |
+
) = op_schema.args_schema
|
| 683 |
+
grad_out_strategy = cast(OpStrategy, grad_out_strategy)
|
| 684 |
+
input_strategy = cast(OpStrategy, input_strategy)
|
| 685 |
+
target_strategy = cast(OpStrategy, target_strategy)
|
| 686 |
+
reduction = cast(int, reduction)
|
| 687 |
+
total_weight_strategy = cast(OpStrategy, total_weight_strategy)
|
| 688 |
+
|
| 689 |
+
input_shape = input_strategy.shape
|
| 690 |
+
channel_dim = 1 if len(input_shape) >= 2 else 0
|
| 691 |
+
|
| 692 |
+
grad_in_strategy = OpStrategy([])
|
| 693 |
+
for idx, input_placement_strategy in enumerate(input_strategy.strategies):
|
| 694 |
+
op_args_target_specs = []
|
| 695 |
+
redistribute_costs = []
|
| 696 |
+
|
| 697 |
+
# make sure input is replicated along the channel dim
|
| 698 |
+
input_src_spec = input_placement_strategy.output_spec
|
| 699 |
+
input_expected_spec = DTensorSpec(
|
| 700 |
+
mesh=mesh,
|
| 701 |
+
placements=replicate_reduction_dims(
|
| 702 |
+
input_src_spec.placements, [channel_dim]
|
| 703 |
+
),
|
| 704 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 705 |
+
)
|
| 706 |
+
op_args_target_specs.append(input_expected_spec)
|
| 707 |
+
redistribute_costs.append(
|
| 708 |
+
generate_redistribute_costs(input_strategy, input_expected_spec)
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# target doesn't have channel dim, and it follows input on other dims
|
| 712 |
+
target_src_spec = target_strategy.strategies[idx].output_spec
|
| 713 |
+
target_expected_spec = DTensorSpec(
|
| 714 |
+
mesh=mesh,
|
| 715 |
+
placements=_skip_dim(input_expected_spec.placements, channel_dim),
|
| 716 |
+
tensor_meta=target_src_spec.tensor_meta,
|
| 717 |
+
)
|
| 718 |
+
op_args_target_specs.append(target_expected_spec)
|
| 719 |
+
redistribute_costs.append(
|
| 720 |
+
generate_redistribute_costs(target_strategy, target_expected_spec)
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
# grad_out follows target if there is no reduction;
|
| 724 |
+
# otherwise, it should be a replicated scalar.
|
| 725 |
+
grad_out_src_spec = grad_out_strategy.strategies[idx].output_spec
|
| 726 |
+
if reduction == Reduction.NONE.value:
|
| 727 |
+
grad_out_expected_spec = target_expected_spec
|
| 728 |
+
else:
|
| 729 |
+
grad_out_expected_spec = DTensorSpec(
|
| 730 |
+
mesh=mesh,
|
| 731 |
+
placements=_replicate_dims_start_at(grad_out_src_spec.placements),
|
| 732 |
+
tensor_meta=grad_out_src_spec.tensor_meta,
|
| 733 |
+
)
|
| 734 |
+
op_args_target_specs.insert(0, grad_out_expected_spec)
|
| 735 |
+
redistribute_costs.insert(
|
| 736 |
+
0, generate_redistribute_costs(grad_out_strategy, grad_out_expected_spec)
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
# weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
|
| 740 |
+
# make sure it is replicated
|
| 741 |
+
if weight_strategy is not None:
|
| 742 |
+
assert isinstance(weight_strategy, OpStrategy)
|
| 743 |
+
weight_src_spec = weight_strategy.strategies[idx].output_spec
|
| 744 |
+
weight_expected_spec = DTensorSpec(
|
| 745 |
+
mesh=mesh,
|
| 746 |
+
placements=_replicate_dims_start_at(weight_src_spec.placements),
|
| 747 |
+
tensor_meta=weight_src_spec.tensor_meta,
|
| 748 |
+
)
|
| 749 |
+
op_args_target_specs.append(weight_expected_spec)
|
| 750 |
+
redistribute_costs.append(
|
| 751 |
+
generate_redistribute_costs(weight_strategy, weight_expected_spec)
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
# total_weight should always be replicated
|
| 755 |
+
total_weight_src_spec = total_weight_strategy.strategies[idx].output_spec
|
| 756 |
+
total_weight_expected_spec = DTensorSpec(
|
| 757 |
+
mesh=mesh,
|
| 758 |
+
placements=_replicate_dims_start_at(total_weight_src_spec.placements),
|
| 759 |
+
tensor_meta=total_weight_src_spec.tensor_meta,
|
| 760 |
+
)
|
| 761 |
+
op_args_target_specs.append(total_weight_expected_spec)
|
| 762 |
+
redistribute_costs.append(
|
| 763 |
+
generate_redistribute_costs(
|
| 764 |
+
total_weight_strategy, total_weight_expected_spec
|
| 765 |
+
)
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
grad_in_expected_spec = input_expected_spec
|
| 769 |
+
grad_in_strategy.strategies.append(
|
| 770 |
+
PlacementStrategy(
|
| 771 |
+
output_specs=grad_in_expected_spec,
|
| 772 |
+
input_specs=op_args_target_specs,
|
| 773 |
+
redistribute_cost=redistribute_costs,
|
| 774 |
+
)
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
return grad_in_strategy
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
@register_op_strategy(
|
| 781 |
+
[aten.native_layer_norm.default],
|
| 782 |
+
schema_info=RuntimeSchemaInfo(1),
|
| 783 |
+
)
|
| 784 |
+
def layer_norm_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 785 |
+
# args must be: input, normalized_shape, weight, bias, eps
|
| 786 |
+
# for None weight and bias, their corresponding objects will
|
| 787 |
+
# be None as well. layer_norm_strategy returns one OpStrategy
|
| 788 |
+
# for the triple return values (out, mean, rstd).
|
| 789 |
+
assert len(op_schema.args_schema) == 5
|
| 790 |
+
(
|
| 791 |
+
input_strategy,
|
| 792 |
+
normalized_shape,
|
| 793 |
+
weight_strategy,
|
| 794 |
+
bias_strategy,
|
| 795 |
+
_,
|
| 796 |
+
) = op_schema.args_schema
|
| 797 |
+
|
| 798 |
+
# the current layer norm implementation requires that all
|
| 799 |
+
# input DTensor's sharding must be in form of OpStrategy
|
| 800 |
+
assert isinstance(input_strategy, OpStrategy)
|
| 801 |
+
assert isinstance(normalized_shape, (int, Sequence, torch.Size))
|
| 802 |
+
normalized_size = normalize_to_torch_size(normalized_shape)
|
| 803 |
+
|
| 804 |
+
input_ndim = input_strategy.ndim
|
| 805 |
+
axis = input_ndim - len(normalized_size)
|
| 806 |
+
|
| 807 |
+
# we use OpStrategy because the output (out, mean, rstd)
|
| 808 |
+
# should have the same placements
|
| 809 |
+
output_strategy = OpStrategy([])
|
| 810 |
+
for idx, input_placement_strategy in enumerate(input_strategy.strategies):
|
| 811 |
+
op_args_target_specs = []
|
| 812 |
+
redistribute_costs = []
|
| 813 |
+
input_src_spec = input_placement_strategy.output_spec
|
| 814 |
+
|
| 815 |
+
# for the input tensor, we replicate it on the inner dims if necessary
|
| 816 |
+
# TODO: we can avoid forcing the redistribution once we figure out
|
| 817 |
+
# how to decompose layer norm
|
| 818 |
+
input_target_spec = DTensorSpec(
|
| 819 |
+
mesh=mesh,
|
| 820 |
+
placements=_replicate_dims_start_at(input_src_spec.placements, axis),
|
| 821 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 822 |
+
)
|
| 823 |
+
op_args_target_specs.append(input_target_spec)
|
| 824 |
+
redistribute_costs.append(
|
| 825 |
+
generate_redistribute_costs(input_strategy, input_target_spec)
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
if weight_strategy is not None:
|
| 829 |
+
assert isinstance(weight_strategy, OpStrategy)
|
| 830 |
+
weight_src_spec = weight_strategy.strategies[idx].output_spec
|
| 831 |
+
|
| 832 |
+
# for the weight tensor, we replicate it on all dims if necessary
|
| 833 |
+
# TODO: we can avoid forcing the redistribution once we figure out
|
| 834 |
+
# how to decompose layer norm
|
| 835 |
+
weight_target_spec = DTensorSpec(
|
| 836 |
+
mesh=mesh,
|
| 837 |
+
placements=_replicate_dims_start_at(weight_src_spec.placements),
|
| 838 |
+
tensor_meta=weight_src_spec.tensor_meta,
|
| 839 |
+
)
|
| 840 |
+
op_args_target_specs.append(weight_target_spec)
|
| 841 |
+
redistribute_costs.append(
|
| 842 |
+
generate_redistribute_costs(weight_strategy, weight_target_spec)
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
if bias_strategy is not None:
|
| 846 |
+
assert isinstance(bias_strategy, OpStrategy)
|
| 847 |
+
bias_src_spec = bias_strategy.strategies[idx].output_spec
|
| 848 |
+
|
| 849 |
+
# for the bias tensor, we replicate it on all dims if necessary
|
| 850 |
+
# TODO: we can avoid forcing the redistribution once we figure out
|
| 851 |
+
# how to decompose layer norm
|
| 852 |
+
bias_target_spec = DTensorSpec(
|
| 853 |
+
mesh=mesh,
|
| 854 |
+
placements=_replicate_dims_start_at(bias_src_spec.placements),
|
| 855 |
+
tensor_meta=bias_src_spec.tensor_meta,
|
| 856 |
+
)
|
| 857 |
+
op_args_target_specs.append(bias_target_spec)
|
| 858 |
+
redistribute_costs.append(
|
| 859 |
+
generate_redistribute_costs(bias_strategy, bias_target_spec)
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
# the output spec is the same as input spec
|
| 863 |
+
output_target_spec = input_target_spec
|
| 864 |
+
output_strategy.strategies.append(
|
| 865 |
+
PlacementStrategy(
|
| 866 |
+
output_specs=output_target_spec,
|
| 867 |
+
input_specs=op_args_target_specs,
|
| 868 |
+
redistribute_cost=redistribute_costs,
|
| 869 |
+
)
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
return output_strategy
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
@register_op_strategy(
|
| 876 |
+
[aten.native_layer_norm_backward.default],
|
| 877 |
+
schema_info=RuntimeSchemaInfo(2),
|
| 878 |
+
)
|
| 879 |
+
def layer_norm_bwd_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 880 |
+
# args must be: grad_out, input, normalized_shape, mean, rstd,
|
| 881 |
+
# weight, bias, output_mask. For None weight and bias, their
|
| 882 |
+
# corresponding objects will be None as well.
|
| 883 |
+
assert len(op_schema.args_schema) == 8
|
| 884 |
+
(
|
| 885 |
+
grad_out_strategy,
|
| 886 |
+
input_strategy,
|
| 887 |
+
normalized_shape,
|
| 888 |
+
mean_strategy,
|
| 889 |
+
rstd_strategy,
|
| 890 |
+
weight_strategy,
|
| 891 |
+
bias_strategy,
|
| 892 |
+
output_mask,
|
| 893 |
+
) = op_schema.args_schema
|
| 894 |
+
|
| 895 |
+
assert isinstance(grad_out_strategy, OpStrategy)
|
| 896 |
+
assert isinstance(input_strategy, OpStrategy)
|
| 897 |
+
assert isinstance(mean_strategy, OpStrategy)
|
| 898 |
+
assert isinstance(rstd_strategy, OpStrategy)
|
| 899 |
+
|
| 900 |
+
assert isinstance(normalized_shape, (int, Sequence, torch.Size))
|
| 901 |
+
normalized_size = normalize_to_torch_size(normalized_shape)
|
| 902 |
+
input_ndim = input_strategy.ndim
|
| 903 |
+
axis = input_ndim - len(normalized_size)
|
| 904 |
+
outer_dims = list(range(axis))
|
| 905 |
+
|
| 906 |
+
assert isinstance(output_mask, List) and len(output_mask) == 3
|
| 907 |
+
|
| 908 |
+
# output triple: (d_input, d_weight, d_bias)
|
| 909 |
+
out_tuple_strategy = OpStrategy([])
|
| 910 |
+
for idx, input_placement_strategy in enumerate(input_strategy.strategies):
|
| 911 |
+
# args for PlacementStrategy
|
| 912 |
+
output_specs_list: List[Optional[DTensorSpec]] = []
|
| 913 |
+
input_specs_list: List[DTensorSpec] = []
|
| 914 |
+
redistribute_costs = []
|
| 915 |
+
|
| 916 |
+
input_src_spec = input_placement_strategy.output_spec
|
| 917 |
+
# arg: grad_out
|
| 918 |
+
# TODO: change the strategy to the following rule.
|
| 919 |
+
# d_input is basically a product of element-wise mul of
|
| 920 |
+
# grad_out, rstd, and normalized input, among which rstd
|
| 921 |
+
# and normalized input (x_hat) should have the same sharding
|
| 922 |
+
# placements, and grad_out's sharding is determined by the
|
| 923 |
+
# pointwise result of x_hat and weight/bias.
|
| 924 |
+
# TODO: now grad_out spec follows input spec. we may need
|
| 925 |
+
# to change it to apply a pointwise rule over grad_out,
|
| 926 |
+
# input, and weight.
|
| 927 |
+
grad_out_target_spec = DTensorSpec(
|
| 928 |
+
mesh=mesh,
|
| 929 |
+
placements=_replicate_dims_start_at(input_src_spec.placements, axis),
|
| 930 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 931 |
+
)
|
| 932 |
+
input_specs_list.append(grad_out_target_spec)
|
| 933 |
+
redistribute_costs.append(
|
| 934 |
+
generate_redistribute_costs(grad_out_strategy, grad_out_target_spec)
|
| 935 |
+
)
|
| 936 |
+
output_specs_list.append(grad_out_target_spec if output_mask[0] else None)
|
| 937 |
+
|
| 938 |
+
# arg: input
|
| 939 |
+
input_target_spec = DTensorSpec(
|
| 940 |
+
mesh=mesh,
|
| 941 |
+
placements=_replicate_dims_start_at(input_src_spec.placements, axis),
|
| 942 |
+
tensor_meta=input_src_spec.tensor_meta,
|
| 943 |
+
)
|
| 944 |
+
input_specs_list.append(input_target_spec)
|
| 945 |
+
redistribute_costs.append(
|
| 946 |
+
generate_redistribute_costs(input_strategy, input_target_spec)
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
# arg: mean, rstd
|
| 950 |
+
mean_src_spec = mean_strategy.strategies[idx].output_spec
|
| 951 |
+
input_specs_list.append(mean_src_spec)
|
| 952 |
+
redistribute_costs.append([0.0 for _ in mean_strategy.strategies])
|
| 953 |
+
rstd_src_spec = rstd_strategy.strategies[idx].output_spec
|
| 954 |
+
input_specs_list.append(rstd_src_spec)
|
| 955 |
+
redistribute_costs.append([0.0 for _ in rstd_strategy.strategies])
|
| 956 |
+
|
| 957 |
+
def _add_target_input_spec(strategy) -> DTensorSpec:
|
| 958 |
+
# shared logic for setting the weight and bias target input specs
|
| 959 |
+
assert isinstance(strategy, OpStrategy)
|
| 960 |
+
src_spec = strategy.strategies[idx].output_spec
|
| 961 |
+
# no need to redistribute since they should be replicated in forward pass
|
| 962 |
+
input_specs_list.append(src_spec)
|
| 963 |
+
redistribute_costs.append([0.0 for _ in strategy.strategies])
|
| 964 |
+
return src_spec
|
| 965 |
+
|
| 966 |
+
# arg: weight
|
| 967 |
+
# d_weight = sum(grad_out * (input - mean) / rstd, outer_dim, keepdim=False)
|
| 968 |
+
if weight_strategy is not None:
|
| 969 |
+
weight_src_spec = _add_target_input_spec(weight_strategy)
|
| 970 |
+
# TODO: now d_weight spec follows input spec w/ a reduction.
|
| 971 |
+
# we may need to change to a pointwise rule over grad_out and
|
| 972 |
+
# input, then apply a reduction.
|
| 973 |
+
inp_placements = _replicate_dims_start_at(input_src_spec.placements, axis)
|
| 974 |
+
reduce_dims_map = _infer_reduce_dims_map(
|
| 975 |
+
outer_dims, input_src_spec.ndim, False
|
| 976 |
+
)
|
| 977 |
+
out_placements = map_placements_after_reduction(
|
| 978 |
+
inp_placements, outer_dims, reduce_dims_map, "sum"
|
| 979 |
+
)
|
| 980 |
+
weight_out_spec = DTensorSpec(
|
| 981 |
+
mesh=mesh,
|
| 982 |
+
placements=out_placements,
|
| 983 |
+
tensor_meta=weight_src_spec.tensor_meta,
|
| 984 |
+
)
|
| 985 |
+
output_specs_list.append(weight_out_spec if output_mask[1] else None)
|
| 986 |
+
else:
|
| 987 |
+
assert (
|
| 988 |
+
output_mask[1] is False
|
| 989 |
+
), "output_mask[1] should not be `True` while weight argument is `None` in native_layer_norm_backward."
|
| 990 |
+
output_specs_list.append(None)
|
| 991 |
+
|
| 992 |
+
# arg: bias
|
| 993 |
+
# d_bias = sum(grad_out, outer_dim, keepdim=False)
|
| 994 |
+
if bias_strategy is not None:
|
| 995 |
+
bias_src_spec = _add_target_input_spec(bias_strategy)
|
| 996 |
+
# d_bias spec follows a reduction over grad_out
|
| 997 |
+
inp_placements = _replicate_dims_start_at(
|
| 998 |
+
grad_out_target_spec.placements, axis
|
| 999 |
+
)
|
| 1000 |
+
reduce_dims_map = _infer_reduce_dims_map(
|
| 1001 |
+
outer_dims, grad_out_target_spec.ndim, False
|
| 1002 |
+
)
|
| 1003 |
+
out_placements = map_placements_after_reduction(
|
| 1004 |
+
inp_placements, outer_dims, reduce_dims_map, "sum"
|
| 1005 |
+
)
|
| 1006 |
+
bias_out_spec = DTensorSpec(
|
| 1007 |
+
mesh=mesh,
|
| 1008 |
+
placements=out_placements,
|
| 1009 |
+
tensor_meta=bias_src_spec.tensor_meta,
|
| 1010 |
+
)
|
| 1011 |
+
output_specs_list.append(bias_out_spec if output_mask[2] else None)
|
| 1012 |
+
else:
|
| 1013 |
+
assert (
|
| 1014 |
+
output_mask[2] is False
|
| 1015 |
+
), "output_mask[2] should not be `True` while bias argument is `None` in native_layer_norm_backward."
|
| 1016 |
+
output_specs_list.append(None)
|
| 1017 |
+
|
| 1018 |
+
out_tuple_strategy.strategies.append(
|
| 1019 |
+
PlacementStrategy(
|
| 1020 |
+
output_specs=tuple(output_specs_list),
|
| 1021 |
+
input_specs=input_specs_list,
|
| 1022 |
+
redistribute_cost=redistribute_costs,
|
| 1023 |
+
)
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
return out_tuple_strategy
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
@register_op_strategy(
|
| 1030 |
+
[aten.topk.default],
|
| 1031 |
+
schema_info=RuntimeSchemaInfo(2),
|
| 1032 |
+
)
|
| 1033 |
+
def topk_strategy(mesh: DeviceMesh, op_schema: OpSchema) -> OpStrategy:
|
| 1034 |
+
input_strategy = cast(OpStrategy, op_schema.args_schema[0])
|
| 1035 |
+
k = cast(int, op_schema.args_schema[1])
|
| 1036 |
+
input_shape = input_strategy.shape
|
| 1037 |
+
topk_dim = (
|
| 1038 |
+
cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else -1
|
| 1039 |
+
)
|
| 1040 |
+
topk_dim = normalize_dim(topk_dim, input_strategy.ndim)
|
| 1041 |
+
|
| 1042 |
+
single_mesh_dim_strategies = []
|
| 1043 |
+
|
| 1044 |
+
# two outputs (values, indices), 1 input
|
| 1045 |
+
# replicate always works
|
| 1046 |
+
all_replicate: PlacementList = [Replicate()] * 3
|
| 1047 |
+
single_mesh_dim_strategies.append(all_replicate)
|
| 1048 |
+
|
| 1049 |
+
# every dim except topk dim should work
|
| 1050 |
+
for dim in range(input_strategy.ndim):
|
| 1051 |
+
if dim != topk_dim:
|
| 1052 |
+
dim_shardings: PlacementList = [Shard(dim)] * 3
|
| 1053 |
+
single_mesh_dim_strategies.append(dim_shardings)
|
| 1054 |
+
# TODO: topk on sharded dim requries non-trival reduction, address it later
|
| 1055 |
+
|
| 1056 |
+
return expand_to_full_mesh_op_strategy(
|
| 1057 |
+
mesh, op_schema, single_mesh_dim_strategies, input_index=2
|
| 1058 |
+
)
|