Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .venv/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi +0 -0
- .venv/lib/python3.10/site-packages/torch/_C/__init__.pyi +0 -0
- .venv/lib/python3.10/site-packages/torch/_C/_acc/__init__.pyi +15 -0
- .venv/lib/python3.10/site-packages/torch/_C/_aoti.pyi +164 -0
- .venv/lib/python3.10/site-packages/torch/_C/_autograd.pyi +144 -0
- .venv/lib/python3.10/site-packages/torch/_C/_cpu.pyi +8 -0
- .venv/lib/python3.10/site-packages/torch/_C/_cudnn.pyi +14 -0
- .venv/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi +1 -0
- .venv/lib/python3.10/site-packages/torch/_C/_distributed.pyi +21 -0
- .venv/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi +26 -0
- .venv/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi +895 -0
- .venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi +188 -0
- .venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi +32 -0
- .venv/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi +4 -0
- .venv/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi +13 -0
- .venv/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi +91 -0
- .venv/lib/python3.10/site-packages/torch/_C/_dynamo/guards.pyi +499 -0
- .venv/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi +9 -0
- .venv/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi +25 -0
- .venv/lib/python3.10/site-packages/torch/_C/_functionalization.pyi +16 -0
- .venv/lib/python3.10/site-packages/torch/_C/_functions.pyi +19 -0
- .venv/lib/python3.10/site-packages/torch/_C/_functorch.pyi +100 -0
- .venv/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi +4 -0
- .venv/lib/python3.10/site-packages/torch/_C/_itt.pyi +5 -0
- .venv/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi +202 -0
- .venv/lib/python3.10/site-packages/torch/_C/_lazy.pyi +26 -0
- .venv/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi +12 -0
- .venv/lib/python3.10/site-packages/torch/_C/_monitor.pyi +58 -0
- .venv/lib/python3.10/site-packages/torch/_C/_nn.pyi +341 -0
- .venv/lib/python3.10/site-packages/torch/_C/_nvtx.pyi +9 -0
- .venv/lib/python3.10/site-packages/torch/_C/_onnx.pyi +39 -0
- .venv/lib/python3.10/site-packages/torch/_C/_profiler.pyi +247 -0
- .venv/lib/python3.10/site-packages/torch/_C/_verbose.pyi +3 -0
- .venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py +0 -0
- .venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py +314 -0
- .venv/lib/python3.10/site-packages/torch/_custom_op/impl.py +721 -0
- .venv/lib/python3.10/site-packages/torch/_decomp/__init__.py +559 -0
- .venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py +0 -0
- .venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py +345 -0
- .venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_rng.py +272 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/__init__.py +223 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py +262 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/aot_compile.py +504 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/aot_compile_types.py +211 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/__init__.py +0 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/common.py +185 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/cudagraphs.py +300 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/debugging.py +675 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/distributed.py +622 -0
- .venv/lib/python3.10/site-packages/torch/_dynamo/backends/inductor.py +31 -0
.venv/lib/python3.10/site-packages/torch/_C/_VariableFunctions.pyi
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.10/site-packages/torch/_C/__init__.pyi
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.10/site-packages/torch/_C/_acc/__init__.pyi
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch import Tensor
|
| 2 |
+
from torch.types import _dtype, _int, Device
|
| 3 |
+
|
| 4 |
+
# Defined in torch/csrc/acc/Module.cpp
|
| 5 |
+
class PrivateUse1Hooks:
|
| 6 |
+
def has_primary_context(self, device_index: _int) -> bool: ...
|
| 7 |
+
def is_built(self) -> bool: ...
|
| 8 |
+
def is_available(self) -> bool: ...
|
| 9 |
+
|
| 10 |
+
class DeviceGuard:
|
| 11 |
+
def type_(self) -> Device: ...
|
| 12 |
+
|
| 13 |
+
def register_python_privateuseone_device_guard(guard: DeviceGuard) -> bool: ...
|
| 14 |
+
def register_python_privateuseone_hook(hook: PrivateUse1Hooks) -> bool: ...
|
| 15 |
+
def create_empty_tensor(shape: tuple[_int, ...], dtype: _dtype) -> Tensor: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_aoti.pyi
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ctypes import c_void_p
|
| 2 |
+
from typing import overload, Protocol
|
| 3 |
+
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
|
| 6 |
+
# Defined in torch/csrc/inductor/aoti_runner/pybind.cpp
|
| 7 |
+
|
| 8 |
+
# Tensor to AtenTensorHandle
|
| 9 |
+
def unsafe_alloc_void_ptrs_from_tensors(tensors: list[Tensor]) -> list[c_void_p]: ...
|
| 10 |
+
def unsafe_alloc_void_ptr_from_tensor(tensor: Tensor) -> c_void_p: ...
|
| 11 |
+
|
| 12 |
+
# AtenTensorHandle to Tensor
|
| 13 |
+
def alloc_tensors_by_stealing_from_void_ptrs(
|
| 14 |
+
handles: list[c_void_p],
|
| 15 |
+
) -> list[Tensor]: ...
|
| 16 |
+
def alloc_tensor_by_stealing_from_void_ptr(
|
| 17 |
+
handle: c_void_p,
|
| 18 |
+
) -> Tensor: ...
|
| 19 |
+
|
| 20 |
+
class AOTIModelContainerRunner(Protocol):
|
| 21 |
+
def run(
|
| 22 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 23 |
+
) -> list[Tensor]: ...
|
| 24 |
+
def get_call_spec(self) -> list[str]: ...
|
| 25 |
+
def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
|
| 26 |
+
def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
|
| 27 |
+
def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
|
| 28 |
+
def update_constant_buffer(
|
| 29 |
+
self,
|
| 30 |
+
tensor_map: dict[str, Tensor],
|
| 31 |
+
use_inactive: bool,
|
| 32 |
+
validate_full_updates: bool,
|
| 33 |
+
user_managed: bool = ...,
|
| 34 |
+
) -> None: ...
|
| 35 |
+
def swap_constant_buffer(self) -> None: ...
|
| 36 |
+
def free_inactive_constant_buffer(self) -> None: ...
|
| 37 |
+
|
| 38 |
+
class AOTIModelContainerRunnerCpu:
|
| 39 |
+
def __init__(self, model_so_path: str, num_models: int) -> None: ...
|
| 40 |
+
def run(
|
| 41 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 42 |
+
) -> list[Tensor]: ...
|
| 43 |
+
def get_call_spec(self) -> list[str]: ...
|
| 44 |
+
def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
|
| 45 |
+
def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
|
| 46 |
+
def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
|
| 47 |
+
def update_constant_buffer(
|
| 48 |
+
self,
|
| 49 |
+
tensor_map: dict[str, Tensor],
|
| 50 |
+
use_inactive: bool,
|
| 51 |
+
validate_full_updates: bool,
|
| 52 |
+
user_managed: bool = ...,
|
| 53 |
+
) -> None: ...
|
| 54 |
+
def swap_constant_buffer(self) -> None: ...
|
| 55 |
+
def free_inactive_constant_buffer(self) -> None: ...
|
| 56 |
+
|
| 57 |
+
class AOTIModelContainerRunnerCuda:
|
| 58 |
+
@overload
|
| 59 |
+
def __init__(self, model_so_path: str, num_models: int) -> None: ...
|
| 60 |
+
@overload
|
| 61 |
+
def __init__(
|
| 62 |
+
self, model_so_path: str, num_models: int, device_str: str
|
| 63 |
+
) -> None: ...
|
| 64 |
+
@overload
|
| 65 |
+
def __init__(
|
| 66 |
+
self, model_so_path: str, num_models: int, device_str: str, cubin_dir: str
|
| 67 |
+
) -> None: ...
|
| 68 |
+
def run(
|
| 69 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 70 |
+
) -> list[Tensor]: ...
|
| 71 |
+
def get_call_spec(self) -> list[str]: ...
|
| 72 |
+
def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
|
| 73 |
+
def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
|
| 74 |
+
def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
|
| 75 |
+
def update_constant_buffer(
|
| 76 |
+
self,
|
| 77 |
+
tensor_map: dict[str, Tensor],
|
| 78 |
+
use_inactive: bool,
|
| 79 |
+
validate_full_updates: bool,
|
| 80 |
+
user_managed: bool = ...,
|
| 81 |
+
) -> None: ...
|
| 82 |
+
def swap_constant_buffer(self) -> None: ...
|
| 83 |
+
def free_inactive_constant_buffer(self) -> None: ...
|
| 84 |
+
|
| 85 |
+
class AOTIModelContainerRunnerXpu:
|
| 86 |
+
@overload
|
| 87 |
+
def __init__(self, model_so_path: str, num_models: int) -> None: ...
|
| 88 |
+
@overload
|
| 89 |
+
def __init__(
|
| 90 |
+
self, model_so_path: str, num_models: int, device_str: str
|
| 91 |
+
) -> None: ...
|
| 92 |
+
@overload
|
| 93 |
+
def __init__(
|
| 94 |
+
self, model_so_path: str, num_models: int, device_str: str, kernel_bin_dir: str
|
| 95 |
+
) -> None: ...
|
| 96 |
+
def run(
|
| 97 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 98 |
+
) -> list[Tensor]: ...
|
| 99 |
+
def get_call_spec(self) -> list[str]: ...
|
| 100 |
+
def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
|
| 101 |
+
def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
|
| 102 |
+
def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
|
| 103 |
+
def update_constant_buffer(
|
| 104 |
+
self,
|
| 105 |
+
tensor_map: dict[str, Tensor],
|
| 106 |
+
use_inactive: bool,
|
| 107 |
+
validate_full_updates: bool,
|
| 108 |
+
user_managed: bool = ...,
|
| 109 |
+
) -> None: ...
|
| 110 |
+
def swap_constant_buffer(self) -> None: ...
|
| 111 |
+
def free_inactive_constant_buffer(self) -> None: ...
|
| 112 |
+
|
| 113 |
+
class AOTIModelContainerRunnerMps:
|
| 114 |
+
def __init__(self, model_so_path: str, num_models: int) -> None: ...
|
| 115 |
+
def run(
|
| 116 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 117 |
+
) -> list[Tensor]: ...
|
| 118 |
+
def get_call_spec(self) -> list[str]: ...
|
| 119 |
+
def get_constant_names_to_original_fqns(self) -> dict[str, str]: ...
|
| 120 |
+
def get_constant_names_to_dtypes(self) -> dict[str, int]: ...
|
| 121 |
+
def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ...
|
| 122 |
+
def update_constant_buffer(
|
| 123 |
+
self,
|
| 124 |
+
tensor_map: dict[str, Tensor],
|
| 125 |
+
use_inactive: bool,
|
| 126 |
+
validate_full_updates: bool,
|
| 127 |
+
user_managed: bool = ...,
|
| 128 |
+
) -> None: ...
|
| 129 |
+
def swap_constant_buffer(self) -> None: ...
|
| 130 |
+
def free_inactive_constant_buffer(self) -> None: ...
|
| 131 |
+
|
| 132 |
+
# Defined in torch/csrc/inductor/aoti_package/pybind.cpp
|
| 133 |
+
class AOTIModelPackageLoader:
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
model_package_path: str,
|
| 137 |
+
model_name: str,
|
| 138 |
+
run_single_threaded: bool,
|
| 139 |
+
num_runners: int,
|
| 140 |
+
device_index: int,
|
| 141 |
+
) -> None: ...
|
| 142 |
+
def get_metadata(self) -> dict[str, str]: ...
|
| 143 |
+
def run(
|
| 144 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 145 |
+
) -> list[Tensor]: ...
|
| 146 |
+
def boxed_run(
|
| 147 |
+
self, inputs: list[Tensor], stream_handle: c_void_p = ...
|
| 148 |
+
) -> list[Tensor]: ...
|
| 149 |
+
def get_call_spec(self) -> list[str]: ...
|
| 150 |
+
def get_constant_fqns(self) -> list[str]: ...
|
| 151 |
+
def load_constants(
|
| 152 |
+
self,
|
| 153 |
+
constants_map: dict[str, Tensor],
|
| 154 |
+
use_inactive: bool,
|
| 155 |
+
check_full_update: bool,
|
| 156 |
+
user_managed: bool = ...,
|
| 157 |
+
) -> None: ...
|
| 158 |
+
def update_constant_buffer(
|
| 159 |
+
self,
|
| 160 |
+
tensor_map: dict[str, Tensor],
|
| 161 |
+
use_inactive: bool,
|
| 162 |
+
validate_full_updates: bool,
|
| 163 |
+
user_managed: bool = ...,
|
| 164 |
+
) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_autograd.pyi
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from enum import Enum
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._C._profiler import (
|
| 8 |
+
_ProfilerEvent,
|
| 9 |
+
ActiveProfilerType,
|
| 10 |
+
ProfilerActivity,
|
| 11 |
+
ProfilerConfig,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Defined in torch/csrc/autograd/init.cpp
|
| 15 |
+
|
| 16 |
+
class DeviceType(Enum):
|
| 17 |
+
CPU = ...
|
| 18 |
+
CUDA = ...
|
| 19 |
+
XPU = ...
|
| 20 |
+
MKLDNN = ...
|
| 21 |
+
OPENGL = ...
|
| 22 |
+
OPENCL = ...
|
| 23 |
+
IDEEP = ...
|
| 24 |
+
HIP = ...
|
| 25 |
+
FPGA = ...
|
| 26 |
+
MAIA = ...
|
| 27 |
+
XLA = ...
|
| 28 |
+
MTIA = ...
|
| 29 |
+
MPS = ...
|
| 30 |
+
HPU = ...
|
| 31 |
+
Meta = ...
|
| 32 |
+
Vulkan = ...
|
| 33 |
+
Metal = ...
|
| 34 |
+
PrivateUse1 = ...
|
| 35 |
+
|
| 36 |
+
class ProfilerEvent:
|
| 37 |
+
def cpu_elapsed_us(self, other: ProfilerEvent) -> float: ...
|
| 38 |
+
def cpu_memory_usage(self) -> int: ...
|
| 39 |
+
def cuda_elapsed_us(self, other: ProfilerEvent) -> float: ...
|
| 40 |
+
def privateuse1_elapsed_us(self, other: ProfilerEvent) -> float: ...
|
| 41 |
+
def cuda_memory_usage(self) -> int: ...
|
| 42 |
+
def device(self) -> int: ...
|
| 43 |
+
def handle(self) -> int: ...
|
| 44 |
+
def has_cuda(self) -> bool: ...
|
| 45 |
+
def is_remote(self) -> bool: ...
|
| 46 |
+
def kind(self) -> int: ...
|
| 47 |
+
def name(self) -> str: ...
|
| 48 |
+
def node_id(self) -> int: ...
|
| 49 |
+
def sequence_nr(self) -> int: ...
|
| 50 |
+
def shapes(self) -> list[list[int]]: ...
|
| 51 |
+
def thread_id(self) -> int: ...
|
| 52 |
+
def flops(self) -> float: ...
|
| 53 |
+
def is_async(self) -> bool: ...
|
| 54 |
+
|
| 55 |
+
class _KinetoEvent:
|
| 56 |
+
def name(self) -> str: ...
|
| 57 |
+
def overload_name(self) -> str: ...
|
| 58 |
+
def device_index(self) -> int: ...
|
| 59 |
+
def device_resource_id(self) -> int: ...
|
| 60 |
+
def start_ns(self) -> int: ...
|
| 61 |
+
def end_ns(self) -> int: ...
|
| 62 |
+
def duration_ns(self) -> int: ...
|
| 63 |
+
def is_async(self) -> bool: ...
|
| 64 |
+
def linked_correlation_id(self) -> int: ...
|
| 65 |
+
def shapes(self) -> list[list[int]]: ...
|
| 66 |
+
def dtypes(self) -> list[str]: ...
|
| 67 |
+
def concrete_inputs(self) -> list[Any]: ...
|
| 68 |
+
def kwinputs(self) -> dict[str, Any]: ...
|
| 69 |
+
def device_type(self) -> DeviceType: ...
|
| 70 |
+
def start_thread_id(self) -> int: ...
|
| 71 |
+
def end_thread_id(self) -> int: ...
|
| 72 |
+
def correlation_id(self) -> int: ...
|
| 73 |
+
def fwd_thread_id(self) -> int: ...
|
| 74 |
+
def stack(self) -> list[str]: ...
|
| 75 |
+
def scope(self) -> int: ...
|
| 76 |
+
def sequence_nr(self) -> int: ...
|
| 77 |
+
def flops(self) -> int: ...
|
| 78 |
+
def cuda_elapsed_us(self) -> int: ...
|
| 79 |
+
def privateuse1_elapsed_us(self) -> int: ...
|
| 80 |
+
def is_user_annotation(self) -> bool: ...
|
| 81 |
+
def is_hidden_event(self) -> bool: ...
|
| 82 |
+
def metadata_json(self) -> str: ...
|
| 83 |
+
|
| 84 |
+
class _ProfilerResult:
|
| 85 |
+
def events(self) -> list[_KinetoEvent]: ...
|
| 86 |
+
def legacy_events(self) -> list[list[ProfilerEvent]]: ...
|
| 87 |
+
def save(self, path: str) -> None: ...
|
| 88 |
+
def experimental_event_tree(self) -> list[_ProfilerEvent]: ...
|
| 89 |
+
def trace_start_ns(self) -> int: ...
|
| 90 |
+
|
| 91 |
+
class SavedTensor: ...
|
| 92 |
+
|
| 93 |
+
def _enable_profiler(
|
| 94 |
+
config: ProfilerConfig,
|
| 95 |
+
activities: set[ProfilerActivity],
|
| 96 |
+
) -> None: ...
|
| 97 |
+
def _prepare_profiler(
|
| 98 |
+
config: ProfilerConfig,
|
| 99 |
+
activities: set[ProfilerActivity],
|
| 100 |
+
) -> None: ...
|
| 101 |
+
def _toggle_collection_dynamic(
|
| 102 |
+
enable: bool,
|
| 103 |
+
activities: set[ProfilerActivity],
|
| 104 |
+
) -> None: ...
|
| 105 |
+
def _disable_profiler() -> _ProfilerResult: ...
|
| 106 |
+
def _profiler_enabled() -> bool: ...
|
| 107 |
+
def _add_metadata_json(key: str, value: str) -> None: ...
|
| 108 |
+
def _kineto_step() -> None: ...
|
| 109 |
+
def _get_current_graph_task_keep_graph() -> bool: ...
|
| 110 |
+
def _get_sequence_nr() -> int: ...
|
| 111 |
+
def kineto_available() -> bool: ...
|
| 112 |
+
def _record_function_with_args_enter(name: str, *args) -> torch.Tensor: ...
|
| 113 |
+
def _record_function_with_args_exit(handle: torch.Tensor) -> None: ...
|
| 114 |
+
def _supported_activities() -> set[ProfilerActivity]: ...
|
| 115 |
+
def _enable_record_function(enable: bool) -> None: ...
|
| 116 |
+
def _set_empty_test_observer(is_global: bool, sampling_prob: float) -> None: ...
|
| 117 |
+
def _push_saved_tensors_default_hooks(
|
| 118 |
+
pack_hook: Callable[[torch.Tensor], Any],
|
| 119 |
+
unpack_hook: Callable[[Any], torch.Tensor],
|
| 120 |
+
) -> None: ...
|
| 121 |
+
def _pop_saved_tensors_default_hooks() -> None: ...
|
| 122 |
+
def _top_saved_tensors_default_hooks(
|
| 123 |
+
ignore_is_tracing: bool,
|
| 124 |
+
) -> tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]]: ...
|
| 125 |
+
def _unsafe_set_version_counter(
|
| 126 |
+
t: tuple[torch.Tensor, ...], prev_version: tuple[int, ...]
|
| 127 |
+
) -> None: ...
|
| 128 |
+
def _enable_profiler_legacy(config: ProfilerConfig) -> None: ...
|
| 129 |
+
def _disable_profiler_legacy() -> list[list[ProfilerEvent]]: ...
|
| 130 |
+
def _profiler_type() -> ActiveProfilerType: ...
|
| 131 |
+
def _saved_tensors_hooks_enable() -> None: ...
|
| 132 |
+
def _saved_tensors_hooks_disable(message: str, fail_if_non_empty=True) -> None: ...
|
| 133 |
+
def _saved_tensors_hooks_get_disabled_error_message() -> str | None: ...
|
| 134 |
+
def _saved_tensors_hooks_set_tracing(is_tracing: bool) -> bool: ...
|
| 135 |
+
|
| 136 |
+
class CreationMeta(Enum):
|
| 137 |
+
DEFAULT = ...
|
| 138 |
+
IN_CUSTOM_FUNCTION = ...
|
| 139 |
+
MULTI_OUTPUT_NODE = ...
|
| 140 |
+
NO_GRAD_MODE = ...
|
| 141 |
+
INFERENCE_MODE = ...
|
| 142 |
+
|
| 143 |
+
def _set_creation_meta(t: torch.Tensor, creation_meta: CreationMeta) -> None: ...
|
| 144 |
+
def _get_creation_meta(t: torch.Tensor) -> CreationMeta: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_cpu.pyi
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from torch.types import _bool
|
| 4 |
+
|
| 5 |
+
# Defined in torch/csrc/cpu/Module.cpp
|
| 6 |
+
|
| 7 |
+
def _init_amx() -> _bool: ...
|
| 8 |
+
def _get_cpu_capability() -> dict[str, Any]: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_cudnn.pyi
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import IntEnum
|
| 2 |
+
|
| 3 |
+
# Defined in torch/csrc/cuda/shared/cudnn.cpp
|
| 4 |
+
is_cuda: bool
|
| 5 |
+
|
| 6 |
+
def getRuntimeVersion() -> tuple[int, int, int]: ...
|
| 7 |
+
def getCompileVersion() -> tuple[int, int, int]: ...
|
| 8 |
+
def getVersionInt() -> int: ...
|
| 9 |
+
|
| 10 |
+
class RNNMode(IntEnum):
|
| 11 |
+
rnn_relu = ...
|
| 12 |
+
rnn_tanh = ...
|
| 13 |
+
lstm = ...
|
| 14 |
+
gru = ...
|
.venv/lib/python3.10/site-packages/torch/_C/_cusparselt.pyi
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
def getVersionInt() -> int: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_distributed.pyi
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This module is defined in torch/csrc/distributed/python_placement.cpp
|
| 2 |
+
|
| 3 |
+
class Placement:
|
| 4 |
+
def is_partial(self, reduce_op: str | None = None) -> bool: ...
|
| 5 |
+
def is_replicate(self) -> bool: ...
|
| 6 |
+
def is_shard(self, dim: int | None = None) -> bool: ...
|
| 7 |
+
|
| 8 |
+
class Shard(Placement):
|
| 9 |
+
dim: int
|
| 10 |
+
def __init__(self, dim: int): ...
|
| 11 |
+
|
| 12 |
+
class StridedShard(Placement):
|
| 13 |
+
dim: int
|
| 14 |
+
split_factor: int
|
| 15 |
+
def __init__(self, dim: int, *, split_factor: int): ...
|
| 16 |
+
|
| 17 |
+
class Replicate(Placement): ...
|
| 18 |
+
|
| 19 |
+
class Partial(Placement):
|
| 20 |
+
reduce_op: str
|
| 21 |
+
def __init__(self, reduce_op: str | None = None): ...
|
.venv/lib/python3.10/site-packages/torch/_C/_distributed_autograd.pyi
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# This module is defined in torch/csrc/distributed/autograd/init.cpp
|
| 6 |
+
|
| 7 |
+
class DistAutogradContext:
|
| 8 |
+
def _context_id(self) -> int: ...
|
| 9 |
+
def _recv_functions(self) -> dict[int, Any]: ...
|
| 10 |
+
def _send_functions(self) -> dict[int, Any]: ...
|
| 11 |
+
def _known_worker_ids(self) -> set[int]: ...
|
| 12 |
+
|
| 13 |
+
def _new_context() -> DistAutogradContext: ...
|
| 14 |
+
def _release_context(context_id: int) -> None: ...
|
| 15 |
+
def _get_max_id() -> int: ...
|
| 16 |
+
def _is_valid_context(worker_id: int) -> bool: ...
|
| 17 |
+
def _retrieve_context(context_id: int) -> DistAutogradContext: ...
|
| 18 |
+
def _current_context() -> DistAutogradContext: ...
|
| 19 |
+
def _init(worker_id: int) -> None: ...
|
| 20 |
+
def _get_debug_info() -> dict[str, str]: ...
|
| 21 |
+
def backward(
|
| 22 |
+
context_id: int,
|
| 23 |
+
roots: list[torch.Tensor],
|
| 24 |
+
retain_graph: bool = False,
|
| 25 |
+
) -> None: ...
|
| 26 |
+
def get_gradients(context_id: int) -> dict[torch.Tensor, torch.Tensor]: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_distributed_c10d.pyi
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# mypy: disable-error-code="type-arg"
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from datetime import timedelta
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from typing import Any, Optional, overload, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
from torch._C import ScriptObject
|
| 11 |
+
from torch._C._autograd import DeviceType
|
| 12 |
+
from torch.distributed.distributed_c10d import GroupName
|
| 13 |
+
from torch.futures import Future
|
| 14 |
+
|
| 15 |
+
# This module is defined in torch/csrc/distributed/c10d/init.cpp
|
| 16 |
+
|
| 17 |
+
_DEFAULT_FIRST_BUCKET_BYTES: int
|
| 18 |
+
_DEFAULT_NO_TIMEOUT: timedelta
|
| 19 |
+
_DEFAULT_PG_TIMEOUT: timedelta
|
| 20 |
+
_DEFAULT_PG_NCCL_TIMEOUT: timedelta
|
| 21 |
+
|
| 22 |
+
class BuiltinCommHookType(Enum):
|
| 23 |
+
ALLREDUCE = ...
|
| 24 |
+
FP16_COMPRESS = ...
|
| 25 |
+
|
| 26 |
+
def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ...
|
| 27 |
+
def _register_builtin_comm_hook(
|
| 28 |
+
reducer: Reducer,
|
| 29 |
+
comm_hook_type: BuiltinCommHookType,
|
| 30 |
+
): ...
|
| 31 |
+
def _set_global_rank(rank: int) -> None: ...
|
| 32 |
+
def _hash_tensors(tensors: list[Tensor]) -> int: ...
|
| 33 |
+
|
| 34 |
+
class GradBucket:
|
| 35 |
+
def index(self) -> int: ...
|
| 36 |
+
def buffer(self) -> Tensor: ...
|
| 37 |
+
def gradients(self) -> list[Tensor]: ...
|
| 38 |
+
def is_last(self) -> bool: ...
|
| 39 |
+
def set_buffer(self, tensor: Tensor) -> None: ...
|
| 40 |
+
def parameters(self) -> list[Tensor]: ...
|
| 41 |
+
|
| 42 |
+
class Reducer:
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
params: list[Tensor],
|
| 46 |
+
bucket_indices: list[list[int]],
|
| 47 |
+
per_bucket_size_limits: list[int],
|
| 48 |
+
process_group: ProcessGroup,
|
| 49 |
+
expect_sparse_gradients: list[bool] = ...,
|
| 50 |
+
bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp
|
| 51 |
+
find_unused_parameters: bool = ...,
|
| 52 |
+
gradient_as_bucket_view: bool = ...,
|
| 53 |
+
param_to_name_mapping: dict[int, str] = ...,
|
| 54 |
+
first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp
|
| 55 |
+
skip_all_reduce_unused_params: bool = ...,
|
| 56 |
+
use_python_reducer: bool = ...,
|
| 57 |
+
bucket_bytes_cap_list: list[int] = ...,
|
| 58 |
+
) -> None: ...
|
| 59 |
+
def prepare_for_forward(self) -> None: ...
|
| 60 |
+
def prepare_for_backward(self, output: list[Tensor]) -> None: ...
|
| 61 |
+
def get_backward_stats(self) -> list[int]: ...
|
| 62 |
+
def _install_post_backward_futures(self, futures: list[Future]) -> None: ...
|
| 63 |
+
def _rebuild_buckets(self) -> bool: ...
|
| 64 |
+
def _get_zeros_like_grad_buckets(self) -> list[GradBucket]: ...
|
| 65 |
+
def _push_all_rebuilt_params(self) -> None: ...
|
| 66 |
+
def _set_forward_pass_work_handle(
|
| 67 |
+
self,
|
| 68 |
+
work: Work,
|
| 69 |
+
use_static_world_size: bool,
|
| 70 |
+
): ...
|
| 71 |
+
def _get_local_used_map(self) -> Tensor: ...
|
| 72 |
+
def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ...
|
| 73 |
+
def _set_static_graph(self) -> None: ...
|
| 74 |
+
def _run_comm_hook(self, bucket: GradBucket) -> Future: ...
|
| 75 |
+
def set_logger(self, logger: Logger) -> None: ...
|
| 76 |
+
def _remove_autograd_hooks(self) -> None: ...
|
| 77 |
+
def _check_reducer_finalized(self) -> None: ...
|
| 78 |
+
def _set_sparse_metadata(self, global_unique_ids: dict[str, Tensor]) -> None: ...
|
| 79 |
+
def _reset_state(self) -> None: ...
|
| 80 |
+
def _update_process_group(self, new_process_group: ProcessGroup) -> None: ...
|
| 81 |
+
|
| 82 |
+
class DDPLoggingData:
|
| 83 |
+
strs_map: dict[str, str]
|
| 84 |
+
ints_map: dict[str, int]
|
| 85 |
+
|
| 86 |
+
class Logger:
|
| 87 |
+
def __init__(self, reducer: Reducer) -> None: ...
|
| 88 |
+
def set_construction_data_and_log(
|
| 89 |
+
self,
|
| 90 |
+
module_name: str,
|
| 91 |
+
device_ids: list[int],
|
| 92 |
+
output_device: int,
|
| 93 |
+
broadcast_buffers: bool,
|
| 94 |
+
has_sync_bn: bool,
|
| 95 |
+
static_graph: bool,
|
| 96 |
+
) -> None: ...
|
| 97 |
+
def set_runtime_stats_and_log(self) -> None: ...
|
| 98 |
+
def set_error_and_log(self, error: str) -> None: ...
|
| 99 |
+
def _get_ddp_logging_data(self) -> DDPLoggingData: ...
|
| 100 |
+
def _set_comm_hook_name(self, comm_hook: str) -> None: ...
|
| 101 |
+
def _set_uneven_input_join(self) -> None: ...
|
| 102 |
+
def _set_static_graph(self) -> None: ...
|
| 103 |
+
|
| 104 |
+
class _WorkerServer:
|
| 105 |
+
port: int
|
| 106 |
+
|
| 107 |
+
def __init__(self, host_or_file: str, port: int = ...) -> None: ...
|
| 108 |
+
def shutdown(self) -> None: ...
|
| 109 |
+
|
| 110 |
+
class DebugLevel(Enum):
|
| 111 |
+
OFF = ...
|
| 112 |
+
INFO = ...
|
| 113 |
+
DETAIL = ...
|
| 114 |
+
|
| 115 |
+
def get_debug_level() -> DebugLevel: ...
|
| 116 |
+
def set_debug_level(level: DebugLevel) -> None: ...
|
| 117 |
+
def set_debug_level_from_env() -> None: ...
|
| 118 |
+
|
| 119 |
+
class ReduceOp:
|
| 120 |
+
# pyrefly: ignore # unknown-name
|
| 121 |
+
def __init__(self, op: RedOpType) -> None: ...
|
| 122 |
+
|
| 123 |
+
# pyrefly: ignore # unknown-name
|
| 124 |
+
SUM: RedOpType = ...
|
| 125 |
+
# pyrefly: ignore # unknown-name
|
| 126 |
+
AVG: RedOpType = ...
|
| 127 |
+
# pyrefly: ignore # unknown-name
|
| 128 |
+
PRODUCT: RedOpType = ...
|
| 129 |
+
# pyrefly: ignore # unknown-name
|
| 130 |
+
MIN: RedOpType = ...
|
| 131 |
+
# pyrefly: ignore # unknown-name
|
| 132 |
+
MAX: RedOpType = ...
|
| 133 |
+
# pyrefly: ignore # unknown-name
|
| 134 |
+
BAND: RedOpType = ...
|
| 135 |
+
# pyrefly: ignore # unknown-name
|
| 136 |
+
BOR: RedOpType = ...
|
| 137 |
+
# pyrefly: ignore # unknown-name
|
| 138 |
+
BXOR: RedOpType = ...
|
| 139 |
+
# pyrefly: ignore # unknown-name
|
| 140 |
+
PREMUL_SUM: RedOpType = ...
|
| 141 |
+
# pyrefly: ignore # unknown-name
|
| 142 |
+
UNUSED: RedOpType = ...
|
| 143 |
+
|
| 144 |
+
# mypy error being ignored:
|
| 145 |
+
# Detected enum "torch._C._distributed_c10d.ReduceOp.RedOpType" in a type
|
| 146 |
+
# stub with zero members. There is a chance this is due to a recent change
|
| 147 |
+
# in the semantics of enum membership. If so, use `member = value` to mark
|
| 148 |
+
# an enum member, instead of `member: type`
|
| 149 |
+
class RedOpType(Enum): ... # type: ignore[misc]
|
| 150 |
+
|
| 151 |
+
class BroadcastOptions:
|
| 152 |
+
rootRank: int
|
| 153 |
+
rootTensor: int
|
| 154 |
+
timeout: timedelta
|
| 155 |
+
asyncOp: bool
|
| 156 |
+
|
| 157 |
+
class AllreduceOptions:
|
| 158 |
+
reduceOp: ReduceOp
|
| 159 |
+
timeout: timedelta
|
| 160 |
+
asyncOp: bool
|
| 161 |
+
sparseIndices: Optional[Tensor]
|
| 162 |
+
|
| 163 |
+
class AllreduceCoalescedOptions(AllreduceOptions): ...
|
| 164 |
+
|
| 165 |
+
class ReduceOptions:
|
| 166 |
+
reduceOp: ReduceOp
|
| 167 |
+
rootRank: int
|
| 168 |
+
rootTensor: int
|
| 169 |
+
timeout: timedelta
|
| 170 |
+
asyncOp: bool
|
| 171 |
+
|
| 172 |
+
class AllgatherOptions:
|
| 173 |
+
timeout: timedelta
|
| 174 |
+
asyncOp: bool
|
| 175 |
+
|
| 176 |
+
class GatherOptions:
|
| 177 |
+
rootRank: int
|
| 178 |
+
timeout: timedelta
|
| 179 |
+
asyncOp: bool
|
| 180 |
+
|
| 181 |
+
class ScatterOptions:
|
| 182 |
+
rootRank: int
|
| 183 |
+
timeout: timedelta
|
| 184 |
+
asyncOp: bool
|
| 185 |
+
|
| 186 |
+
class ReduceScatterOptions:
|
| 187 |
+
reduceOp: ReduceOp
|
| 188 |
+
timeout: timedelta
|
| 189 |
+
asyncOp: bool
|
| 190 |
+
|
| 191 |
+
class BarrierOptions:
|
| 192 |
+
device_ids: list[int]
|
| 193 |
+
device: torch.device
|
| 194 |
+
timeout: timedelta
|
| 195 |
+
asyncOp: bool
|
| 196 |
+
|
| 197 |
+
class AllToAllOptions:
|
| 198 |
+
timeout: timedelta
|
| 199 |
+
asyncOp: bool
|
| 200 |
+
|
| 201 |
+
class Store:
|
| 202 |
+
def set(self, key: str, value: str) -> None: ...
|
| 203 |
+
def get(self, key: str) -> bytes: ...
|
| 204 |
+
def add(self, key: str, value: int) -> int: ...
|
| 205 |
+
def check(self, keys: list[str]) -> bool: ...
|
| 206 |
+
def compare_set(
|
| 207 |
+
self,
|
| 208 |
+
key: str,
|
| 209 |
+
expected_value: str,
|
| 210 |
+
desired_value: str,
|
| 211 |
+
) -> bytes: ...
|
| 212 |
+
def delete_key(self, key: str) -> bool: ...
|
| 213 |
+
def multi_get(self, keys: list[str]) -> list[bytes]: ...
|
| 214 |
+
def num_keys(self) -> int: ...
|
| 215 |
+
def set_timeout(self, timeout: timedelta) -> None: ...
|
| 216 |
+
@overload
|
| 217 |
+
def wait(self, keys: list[str]) -> None: ...
|
| 218 |
+
@overload
|
| 219 |
+
def wait(self, keys: list[str], timeout: timedelta) -> None: ...
|
| 220 |
+
def queue_pop(self, key: str, block: bool = True) -> bytes: ...
|
| 221 |
+
def queue_push(self, key: str, value: Union[bytes, str]) -> None: ...
|
| 222 |
+
def queue_len(self, key: str) -> int: ...
|
| 223 |
+
def list_keys(self) -> list[str]: ...
|
| 224 |
+
|
| 225 |
+
class FileStore(Store):
|
| 226 |
+
def __init__(self, path: str, numWorkers: int = ...) -> None: ...
|
| 227 |
+
|
| 228 |
+
class HashStore(Store):
|
| 229 |
+
def __init__(self) -> None: ...
|
| 230 |
+
|
| 231 |
+
class TCPStore(Store):
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
host_name: str,
|
| 235 |
+
port: int,
|
| 236 |
+
world_size: int | None = ...,
|
| 237 |
+
is_master: bool = ...,
|
| 238 |
+
timeout: timedelta = ...,
|
| 239 |
+
wait_for_workers: bool = ...,
|
| 240 |
+
multi_tenant: bool = ...,
|
| 241 |
+
master_listen_fd: int | None = ...,
|
| 242 |
+
use_libuv: bool | None = ...,
|
| 243 |
+
) -> None: ...
|
| 244 |
+
@property
|
| 245 |
+
def host(self) -> str: ...
|
| 246 |
+
@property
|
| 247 |
+
def port(self) -> int: ...
|
| 248 |
+
|
| 249 |
+
class PrefixStore(Store):
|
| 250 |
+
def __init__(self, prefix: str, store: Store) -> None: ...
|
| 251 |
+
@property
|
| 252 |
+
def underlying_store(self) -> Store: ...
|
| 253 |
+
|
| 254 |
+
class _ControlCollectives:
|
| 255 |
+
def barrier(self, key: str, timeout: timedelta, blocking: bool) -> None: ...
|
| 256 |
+
def broadcast_send(self, key: str, data: str, timeout: timedelta) -> None: ...
|
| 257 |
+
def broadcast_recv(self, key: str, timeout: timedelta) -> str: ...
|
| 258 |
+
def gather_send(self, key: str, data: str, timeout: timedelta) -> None: ...
|
| 259 |
+
def gather_recv(self, key: str, timeout: timedelta) -> str: ...
|
| 260 |
+
def scatter_send(self, key: str, data: str, timeout: timedelta) -> None: ...
|
| 261 |
+
def scatter_recv(self, key: str, timeout: timedelta) -> str: ...
|
| 262 |
+
def all_gather(self, key: str, data: str, timeout: timedelta) -> str: ...
|
| 263 |
+
def all_sum(self, key: str, data: int, timeout: timedelta) -> int: ...
|
| 264 |
+
|
| 265 |
+
class _StoreCollectives(_ControlCollectives):
|
| 266 |
+
def __init__(self, store: Store, rank: int, world_size: int) -> None: ...
|
| 267 |
+
|
| 268 |
+
class _DistributedBackendOptions:
|
| 269 |
+
def __init__(self) -> None: ...
|
| 270 |
+
@property
|
| 271 |
+
def store(self) -> Store: ...
|
| 272 |
+
@store.setter
|
| 273 |
+
def store(self, store: Store) -> None: ...
|
| 274 |
+
@property
|
| 275 |
+
def group_rank(self) -> int: ...
|
| 276 |
+
@group_rank.setter
|
| 277 |
+
def group_rank(self, rank: int) -> None: ...
|
| 278 |
+
@property
|
| 279 |
+
def group_size(self) -> int: ...
|
| 280 |
+
@group_size.setter
|
| 281 |
+
def group_size(self, size: int) -> None: ...
|
| 282 |
+
@property
|
| 283 |
+
def timeout(self) -> timedelta: ...
|
| 284 |
+
@timeout.setter
|
| 285 |
+
def timeout(self, timeout: timedelta) -> None: ...
|
| 286 |
+
@property
|
| 287 |
+
def group_id(self) -> str: ...
|
| 288 |
+
@group_id.setter
|
| 289 |
+
def group_id(self, group_id: str) -> None: ...
|
| 290 |
+
@property
|
| 291 |
+
def global_ranks_in_group(self) -> list[int]: ...
|
| 292 |
+
@global_ranks_in_group.setter
|
| 293 |
+
def global_ranks_in_group(self, ranks: list[int]) -> None: ...
|
| 294 |
+
|
| 295 |
+
class Work:
|
| 296 |
+
def is_completed(self) -> bool: ...
|
| 297 |
+
def is_success(self) -> bool: ...
|
| 298 |
+
def exception(self) -> Any: ...
|
| 299 |
+
def wait(self, timeout: timedelta = ...) -> bool: ...
|
| 300 |
+
def block_current_stream(self) -> None: ...
|
| 301 |
+
def get_future(self) -> Future: ...
|
| 302 |
+
def source_rank(self) -> int: ...
|
| 303 |
+
def _source_rank(self) -> int: ...
|
| 304 |
+
def result(self) -> list[Tensor]: ...
|
| 305 |
+
def synchronize(self) -> None: ...
|
| 306 |
+
def boxed(self) -> ScriptObject: ...
|
| 307 |
+
@staticmethod
|
| 308 |
+
def unbox(obj: ScriptObject) -> Work: ...
|
| 309 |
+
|
| 310 |
+
class Backend:
|
| 311 |
+
class Options:
|
| 312 |
+
def __init__(self, backend: str, timeout: timedelta = ...) -> None: ...
|
| 313 |
+
@property
|
| 314 |
+
def backend(self) -> str: ...
|
| 315 |
+
@property
|
| 316 |
+
def _timeout(self) -> timedelta: ...
|
| 317 |
+
@_timeout.setter
|
| 318 |
+
def _timeout(self, val: timedelta) -> None: ...
|
| 319 |
+
global_ranks_in_group: list[int]
|
| 320 |
+
group_name: GroupName
|
| 321 |
+
|
| 322 |
+
def __init__(
|
| 323 |
+
self,
|
| 324 |
+
rank: int,
|
| 325 |
+
size: int,
|
| 326 |
+
) -> None: ...
|
| 327 |
+
@property
|
| 328 |
+
def supports_splitting(self) -> bool: ...
|
| 329 |
+
@property
|
| 330 |
+
def supports_coalescing(self) -> bool: ...
|
| 331 |
+
@property
|
| 332 |
+
def supports_time_estimate(self) -> bool: ...
|
| 333 |
+
def set_timeout(self, timeout: timedelta) -> None: ...
|
| 334 |
+
@property
|
| 335 |
+
def options(self) -> Options: ...
|
| 336 |
+
def rank(self) -> int: ...
|
| 337 |
+
def size(self) -> int: ...
|
| 338 |
+
def name(self) -> str: ...
|
| 339 |
+
def abort(self) -> None: ...
|
| 340 |
+
def shutdown(self) -> None: ...
|
| 341 |
+
def eager_connect_single_device(self, device: torch.device | None) -> None: ...
|
| 342 |
+
def _set_sequence_number_for_group(self) -> None: ...
|
| 343 |
+
def _set_default_timeout(self, timeout: timedelta) -> None: ...
|
| 344 |
+
def get_error(self) -> ErrorType: ...
|
| 345 |
+
def supports_tensor_alloc(self, device: torch.device) -> bool: ...
|
| 346 |
+
def allocate_tensor(
|
| 347 |
+
self,
|
| 348 |
+
size: int,
|
| 349 |
+
*,
|
| 350 |
+
dtype: torch.dtype,
|
| 351 |
+
device: torch.device,
|
| 352 |
+
) -> Tensor: ...
|
| 353 |
+
@property
|
| 354 |
+
def mem_allocator(self) -> Any: ...
|
| 355 |
+
|
| 356 |
+
class ProcessGroup:
|
| 357 |
+
class BackendType(Enum):
|
| 358 |
+
UNDEFINED = ...
|
| 359 |
+
GLOO = ...
|
| 360 |
+
NCCL = ...
|
| 361 |
+
UCC = ...
|
| 362 |
+
MPI = ...
|
| 363 |
+
XCCL = ...
|
| 364 |
+
CUSTOM = ...
|
| 365 |
+
|
| 366 |
+
def __init__(
|
| 367 |
+
self,
|
| 368 |
+
store: Store,
|
| 369 |
+
rank: int,
|
| 370 |
+
size: int,
|
| 371 |
+
) -> None: ...
|
| 372 |
+
def rank(self) -> int: ...
|
| 373 |
+
def size(self) -> int: ...
|
| 374 |
+
def get_group_store(self) -> Store: ...
|
| 375 |
+
def split_group(
|
| 376 |
+
self,
|
| 377 |
+
new_ranks: list[int],
|
| 378 |
+
timeout: Optional[timedelta] = None,
|
| 379 |
+
opts: Optional[Backend.Options] = None,
|
| 380 |
+
group_name: GroupName | None = None,
|
| 381 |
+
group_desc: Optional[str] = None,
|
| 382 |
+
) -> Optional[ProcessGroup]: ...
|
| 383 |
+
def merge_remote_group(
|
| 384 |
+
self,
|
| 385 |
+
store: Store,
|
| 386 |
+
size: int,
|
| 387 |
+
timeout: timedelta,
|
| 388 |
+
group_name: GroupName | None = None,
|
| 389 |
+
group_desc: Optional[str] = None,
|
| 390 |
+
) -> ProcessGroup: ...
|
| 391 |
+
def abort(self) -> None: ...
|
| 392 |
+
def set_timeout(self, timeout: timedelta) -> None: ...
|
| 393 |
+
def shutdown(self) -> None: ...
|
| 394 |
+
@overload
|
| 395 |
+
def broadcast(
|
| 396 |
+
self,
|
| 397 |
+
tensors: list[Tensor],
|
| 398 |
+
opts=...,
|
| 399 |
+
) -> Work: ...
|
| 400 |
+
@overload
|
| 401 |
+
def broadcast(
|
| 402 |
+
self,
|
| 403 |
+
tensor: Tensor,
|
| 404 |
+
root: int,
|
| 405 |
+
timeout: timedelta | None = None,
|
| 406 |
+
) -> Work: ...
|
| 407 |
+
@overload
|
| 408 |
+
def allreduce(
|
| 409 |
+
self,
|
| 410 |
+
tensors: list[Tensor],
|
| 411 |
+
opts: AllreduceOptions = ...,
|
| 412 |
+
) -> Work: ...
|
| 413 |
+
@overload
|
| 414 |
+
def allreduce(
|
| 415 |
+
self,
|
| 416 |
+
tensors: list[Tensor],
|
| 417 |
+
op=...,
|
| 418 |
+
timeout: timedelta | None = None,
|
| 419 |
+
) -> Work: ...
|
| 420 |
+
@overload
|
| 421 |
+
def allreduce(
|
| 422 |
+
self,
|
| 423 |
+
tensor: Tensor,
|
| 424 |
+
op=...,
|
| 425 |
+
timeout: timedelta | None = None,
|
| 426 |
+
) -> Work: ...
|
| 427 |
+
def allreduce_coalesced(
|
| 428 |
+
self,
|
| 429 |
+
tensors: list[Tensor],
|
| 430 |
+
opts=...,
|
| 431 |
+
) -> Work: ...
|
| 432 |
+
def reduce_scatter_tensor_coalesced(
|
| 433 |
+
self,
|
| 434 |
+
outputTensors: list[Tensor],
|
| 435 |
+
inputTensors: list[Tensor],
|
| 436 |
+
opts: ReduceScatterOptions | None = None,
|
| 437 |
+
) -> Work: ...
|
| 438 |
+
@overload
|
| 439 |
+
def reduce(
|
| 440 |
+
self,
|
| 441 |
+
tensors: list[Tensor],
|
| 442 |
+
opts=...,
|
| 443 |
+
) -> Work: ...
|
| 444 |
+
@overload
|
| 445 |
+
def reduce(
|
| 446 |
+
self,
|
| 447 |
+
tensor: Tensor,
|
| 448 |
+
root: int,
|
| 449 |
+
op=...,
|
| 450 |
+
timeout: timedelta | None = None,
|
| 451 |
+
) -> Work: ...
|
| 452 |
+
@overload
|
| 453 |
+
def allgather(
|
| 454 |
+
self,
|
| 455 |
+
output_tensors: list[list[Tensor]],
|
| 456 |
+
input_tensors: list[Tensor],
|
| 457 |
+
opts=...,
|
| 458 |
+
) -> Work: ...
|
| 459 |
+
@overload
|
| 460 |
+
def allgather(
|
| 461 |
+
self,
|
| 462 |
+
output_tensors: list[Tensor],
|
| 463 |
+
input_tensor: Tensor,
|
| 464 |
+
timeout: timedelta | None = None,
|
| 465 |
+
) -> Work: ...
|
| 466 |
+
def _allgather_base(
|
| 467 |
+
self,
|
| 468 |
+
output: Tensor,
|
| 469 |
+
input: Tensor,
|
| 470 |
+
opts=...,
|
| 471 |
+
) -> Work: ...
|
| 472 |
+
def allgather_coalesced(
|
| 473 |
+
self,
|
| 474 |
+
output_lists: list[list[Tensor]],
|
| 475 |
+
input_list: list[Tensor],
|
| 476 |
+
opts=...,
|
| 477 |
+
) -> Work: ...
|
| 478 |
+
def allgather_into_tensor_coalesced(
|
| 479 |
+
self,
|
| 480 |
+
output_lists: list[Tensor],
|
| 481 |
+
input_list: list[Tensor],
|
| 482 |
+
opts=...,
|
| 483 |
+
) -> Work: ...
|
| 484 |
+
@overload
|
| 485 |
+
def gather(
|
| 486 |
+
self,
|
| 487 |
+
output_tensors: list[list[Tensor]],
|
| 488 |
+
input_tensors: list[Tensor],
|
| 489 |
+
opts=...,
|
| 490 |
+
) -> Work: ...
|
| 491 |
+
@overload
|
| 492 |
+
def gather(
|
| 493 |
+
self,
|
| 494 |
+
output_tensors: list[Tensor],
|
| 495 |
+
input_tensor: Tensor,
|
| 496 |
+
root: int,
|
| 497 |
+
timeout: timedelta | None = None,
|
| 498 |
+
) -> Work: ...
|
| 499 |
+
@overload
|
| 500 |
+
def scatter(
|
| 501 |
+
self,
|
| 502 |
+
output_tensors: list[Tensor],
|
| 503 |
+
input_tensors: list[list[Tensor]],
|
| 504 |
+
opts=...,
|
| 505 |
+
) -> Work: ...
|
| 506 |
+
@overload
|
| 507 |
+
def scatter(
|
| 508 |
+
self,
|
| 509 |
+
output_tensor: Tensor,
|
| 510 |
+
input_tensors: list[Tensor],
|
| 511 |
+
root: int,
|
| 512 |
+
timeout: timedelta | None = None,
|
| 513 |
+
) -> Work: ...
|
| 514 |
+
@overload
|
| 515 |
+
def reduce_scatter(
|
| 516 |
+
self,
|
| 517 |
+
output_tensors: list[Tensor],
|
| 518 |
+
input_tensors: list[list[Tensor]],
|
| 519 |
+
opts=...,
|
| 520 |
+
) -> Work: ...
|
| 521 |
+
@overload
|
| 522 |
+
def reduce_scatter(
|
| 523 |
+
self,
|
| 524 |
+
output_tensors: Tensor,
|
| 525 |
+
input_tensor: list[Tensor],
|
| 526 |
+
op=...,
|
| 527 |
+
timeout: timedelta | None = None,
|
| 528 |
+
) -> Work: ...
|
| 529 |
+
def _reduce_scatter_base(
|
| 530 |
+
self,
|
| 531 |
+
outputTensor: Tensor,
|
| 532 |
+
inputTensor: Tensor,
|
| 533 |
+
opts: ReduceScatterOptions | None,
|
| 534 |
+
) -> Work: ...
|
| 535 |
+
@overload
|
| 536 |
+
def alltoall_base(
|
| 537 |
+
self,
|
| 538 |
+
output_tensor: Tensor,
|
| 539 |
+
input_tensor: Tensor,
|
| 540 |
+
output_split_sizes: list[int],
|
| 541 |
+
input_split_sizes: list[int],
|
| 542 |
+
opts=...,
|
| 543 |
+
) -> Work: ...
|
| 544 |
+
@overload
|
| 545 |
+
def alltoall_base(
|
| 546 |
+
self,
|
| 547 |
+
output: Tensor,
|
| 548 |
+
input: Tensor,
|
| 549 |
+
output_split_sizes: list[int],
|
| 550 |
+
input_split_sizes: list[int],
|
| 551 |
+
timeout: timedelta | None = None,
|
| 552 |
+
) -> Work: ...
|
| 553 |
+
@overload
|
| 554 |
+
def alltoall(
|
| 555 |
+
self,
|
| 556 |
+
output_tensor: list[Tensor],
|
| 557 |
+
input_tensor: list[Tensor],
|
| 558 |
+
opts=...,
|
| 559 |
+
) -> Work: ...
|
| 560 |
+
@overload
|
| 561 |
+
def alltoall(
|
| 562 |
+
self,
|
| 563 |
+
output: list[Tensor],
|
| 564 |
+
input: list[Tensor],
|
| 565 |
+
timeout: timedelta | None = None,
|
| 566 |
+
) -> Work: ...
|
| 567 |
+
def send(
|
| 568 |
+
self,
|
| 569 |
+
tensors: list[Tensor],
|
| 570 |
+
dstRank: int,
|
| 571 |
+
tag: int,
|
| 572 |
+
) -> Work: ...
|
| 573 |
+
def recv(
|
| 574 |
+
self,
|
| 575 |
+
tensors: list[Tensor],
|
| 576 |
+
srcRank: int,
|
| 577 |
+
tag: int,
|
| 578 |
+
) -> Work: ...
|
| 579 |
+
def recv_anysource(self, tensors: list[Tensor], tag: int) -> Work: ...
|
| 580 |
+
@overload
|
| 581 |
+
def barrier(self, opts=...) -> Work: ...
|
| 582 |
+
@overload
|
| 583 |
+
def barrier(self, timeout: timedelta | None = None) -> Work: ...
|
| 584 |
+
def boxed(self) -> ScriptObject: ...
|
| 585 |
+
@staticmethod
|
| 586 |
+
def unbox(obj: ScriptObject) -> ProcessGroup: ...
|
| 587 |
+
def _start_coalescing(self, device: torch.device) -> None: ...
|
| 588 |
+
def _end_coalescing(self, device: torch.device) -> Work: ...
|
| 589 |
+
def _get_backend_name(self) -> str: ...
|
| 590 |
+
def _backend_id(self, backend_type: BackendType) -> int: ...
|
| 591 |
+
@property
|
| 592 |
+
def _device_types(self) -> list[torch.device]: ...
|
| 593 |
+
def _get_backend(self, device: torch.device) -> Backend: ...
|
| 594 |
+
def _set_default_backend(self, backend_type: BackendType) -> None: ...
|
| 595 |
+
def _register_backend(
|
| 596 |
+
self,
|
| 597 |
+
device: torch.device,
|
| 598 |
+
backend_type: BackendType,
|
| 599 |
+
backend: Backend | None,
|
| 600 |
+
) -> None: ...
|
| 601 |
+
def _set_group_name(self, name: GroupName) -> None: ...
|
| 602 |
+
def _set_group_desc(self, desc: str) -> None: ...
|
| 603 |
+
def name(self) -> str: ...
|
| 604 |
+
def _has_hooks(self) -> bool: ...
|
| 605 |
+
def _wait_for_pending_works(self) -> None: ...
|
| 606 |
+
def _set_sequence_number_for_group(self) -> None: ...
|
| 607 |
+
@property
|
| 608 |
+
def bound_device_id(self) -> torch.device | None: ...
|
| 609 |
+
@bound_device_id.setter
|
| 610 |
+
def bound_device_id(self, device: torch.device | None) -> None: ...
|
| 611 |
+
@property
|
| 612 |
+
def group_name(self) -> GroupName: ...
|
| 613 |
+
@property
|
| 614 |
+
def group_desc(self) -> str: ...
|
| 615 |
+
|
| 616 |
+
class FakeProcessGroup(Backend):
|
| 617 |
+
@staticmethod
|
| 618 |
+
def _create_internal(rank: int, world_size: int) -> FakeProcessGroup: ...
|
| 619 |
+
|
| 620 |
+
class FakeWork(Work):
|
| 621 |
+
seq_id: int
|
| 622 |
+
def __init__(self) -> None: ...
|
| 623 |
+
def wait(self, timeout: timedelta = ...) -> bool: ...
|
| 624 |
+
def getFuture(self) -> Future: ...
|
| 625 |
+
|
| 626 |
+
class PythonCallbackWork(Work):
|
| 627 |
+
def __init__(self, callback: Callable[[timedelta], bool]) -> None: ...
|
| 628 |
+
def wait(self, timeout: timedelta = ...) -> bool: ...
|
| 629 |
+
def get_future(self) -> Future: ...
|
| 630 |
+
|
| 631 |
+
class ProcessGroupGloo(Backend):
|
| 632 |
+
class Device: ...
|
| 633 |
+
|
| 634 |
+
class Options(Backend.Options):
|
| 635 |
+
devices: list[ProcessGroupGloo.Device]
|
| 636 |
+
threads: int
|
| 637 |
+
|
| 638 |
+
def __init__(self): ...
|
| 639 |
+
|
| 640 |
+
def __init__(
|
| 641 |
+
self,
|
| 642 |
+
store: Store,
|
| 643 |
+
rank: int,
|
| 644 |
+
size: int,
|
| 645 |
+
timeout: timedelta,
|
| 646 |
+
) -> None: ...
|
| 647 |
+
@staticmethod
|
| 648 |
+
def create_device(hostname="", interface="", lazy_init=None) -> Device: ...
|
| 649 |
+
@staticmethod
|
| 650 |
+
def create_default_device(lazy_init=None) -> Device: ...
|
| 651 |
+
def _set_default_timeout(self, timeout) -> None: ...
|
| 652 |
+
@property
|
| 653 |
+
def options(self) -> Options: ... # type: ignore[override]
|
| 654 |
+
|
| 655 |
+
class _ProcessGroupWrapper(Backend):
|
| 656 |
+
def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo) -> None: ...
|
| 657 |
+
wrapped_pg: Backend
|
| 658 |
+
@property
|
| 659 |
+
def options(self) -> Backend.Options: ...
|
| 660 |
+
def get_error(self) -> ErrorType: ...
|
| 661 |
+
|
| 662 |
+
class ErrorType(Enum):
|
| 663 |
+
SUCCESS = ...
|
| 664 |
+
TIMEOUT = ...
|
| 665 |
+
COMM_ERROR = ...
|
| 666 |
+
REMOTE_ERROR = ...
|
| 667 |
+
|
| 668 |
+
class ProcessGroupNCCL(Backend):
|
| 669 |
+
class NCCLConfig:
|
| 670 |
+
blocking: int
|
| 671 |
+
cga_cluster_size: int
|
| 672 |
+
min_ctas: int
|
| 673 |
+
max_ctas: int
|
| 674 |
+
def unsafe_get_ptr(self) -> int: ...
|
| 675 |
+
|
| 676 |
+
class Options(Backend.Options):
|
| 677 |
+
config: ProcessGroupNCCL.NCCLConfig
|
| 678 |
+
is_high_priority_stream: bool
|
| 679 |
+
split_from: ProcessGroupNCCL
|
| 680 |
+
split_color: int
|
| 681 |
+
|
| 682 |
+
def __init__(self, is_high_priority_stream: bool = False): ...
|
| 683 |
+
|
| 684 |
+
def __init__(
|
| 685 |
+
self,
|
| 686 |
+
store: Store,
|
| 687 |
+
rank: int,
|
| 688 |
+
size: int,
|
| 689 |
+
options: Options,
|
| 690 |
+
) -> None: ...
|
| 691 |
+
def _group_start(self) -> None: ...
|
| 692 |
+
def _group_end(self) -> None: ...
|
| 693 |
+
def _start_time_estimate(self) -> None: ...
|
| 694 |
+
def _end_time_estimate(self) -> float: ...
|
| 695 |
+
def _set_default_timeout(self, timeout) -> None: ...
|
| 696 |
+
def perform_nocolor_split(self, device: torch.device) -> None: ...
|
| 697 |
+
def register_mem_pool(self, pool: torch.cuda.MemPool) -> None: ...
|
| 698 |
+
def deregister_mem_pool(self, pool: torch.cuda.MemPool) -> None: ...
|
| 699 |
+
def comm_split_count(self) -> int: ...
|
| 700 |
+
def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ...
|
| 701 |
+
def abort(self) -> None: ...
|
| 702 |
+
def _is_initialized(self) -> bool: ...
|
| 703 |
+
@property
|
| 704 |
+
def uid(self) -> int: ...
|
| 705 |
+
@property
|
| 706 |
+
def options(self) -> Options: ... # type: ignore[override]
|
| 707 |
+
@staticmethod
|
| 708 |
+
def get_build_nccl_version(self) -> tuple[int, int, int]: ...
|
| 709 |
+
@staticmethod
|
| 710 |
+
def get_runtime_nccl_version(self) -> tuple[int, int, int]: ...
|
| 711 |
+
|
| 712 |
+
class ProcessGroupUCC(Backend):
|
| 713 |
+
def __init__(
|
| 714 |
+
self,
|
| 715 |
+
store: Store,
|
| 716 |
+
rank: int,
|
| 717 |
+
size: int,
|
| 718 |
+
timeout: timedelta,
|
| 719 |
+
) -> None: ...
|
| 720 |
+
|
| 721 |
+
class ProcessGroupMPI(Backend):
|
| 722 |
+
def __init__(
|
| 723 |
+
self,
|
| 724 |
+
rank: int,
|
| 725 |
+
size: int,
|
| 726 |
+
pgComm: int,
|
| 727 |
+
) -> None: ...
|
| 728 |
+
@staticmethod
|
| 729 |
+
def create(ranks: list[int]) -> ProcessGroupMPI: ...
|
| 730 |
+
|
| 731 |
+
def _compute_bucket_assignment_by_size(
|
| 732 |
+
tensors: list[Tensor],
|
| 733 |
+
bucket_size_limits: list[int],
|
| 734 |
+
expect_sparse_gradient: list[bool] = ...,
|
| 735 |
+
tensor_indices: list[int] = ...,
|
| 736 |
+
) -> tuple[list[list[int]], list[int]]: ...
|
| 737 |
+
def _broadcast_coalesced(
|
| 738 |
+
process_group: ProcessGroup,
|
| 739 |
+
tensors: list[Tensor],
|
| 740 |
+
buffer_size: int,
|
| 741 |
+
src: int,
|
| 742 |
+
): ...
|
| 743 |
+
def _test_python_store(store: Store): ...
|
| 744 |
+
def _verify_params_across_processes(
|
| 745 |
+
process_group: ProcessGroup,
|
| 746 |
+
params: list[Tensor],
|
| 747 |
+
logger: Logger | None,
|
| 748 |
+
): ...
|
| 749 |
+
def _make_nccl_premul_sum(factor: float | list[Tensor]) -> ReduceOp: ...
|
| 750 |
+
def _register_process_group(
|
| 751 |
+
group_name: GroupName,
|
| 752 |
+
process_group: ProcessGroup,
|
| 753 |
+
) -> None: ...
|
| 754 |
+
def _resolve_process_group(group_name: GroupName) -> ProcessGroup: ...
|
| 755 |
+
def _register_work(tensor: torch.Tensor, work: Work) -> ProcessGroup: ...
|
| 756 |
+
def _get_work_registry_size() -> int: ...
|
| 757 |
+
def _set_allow_inflight_collective_as_graph_input(
|
| 758 |
+
value: bool,
|
| 759 |
+
) -> None: ...
|
| 760 |
+
def _allow_inflight_collective_as_graph_input() -> bool: ...
|
| 761 |
+
def _unregister_all_process_groups() -> None: ...
|
| 762 |
+
def _unregister_process_group(group_name: GroupName) -> None: ...
|
| 763 |
+
|
| 764 |
+
# Initializes the device state in CUmodule so that it's able to perform NVSHMEM
|
| 765 |
+
# operations. CUmodule is a pointer to a CUDA module, carried by a int64 in
|
| 766 |
+
# Python. At C++ interface, it is converted to a uintptr_t.
|
| 767 |
+
def _nvshmemx_cumodule_init(module: int) -> None: ...
|
| 768 |
+
|
| 769 |
+
# Check if NVSHMEM is available on current system.
|
| 770 |
+
def _is_nvshmem_available() -> bool: ...
|
| 771 |
+
|
| 772 |
+
class _SymmetricMemory:
|
| 773 |
+
@staticmethod
|
| 774 |
+
def set_group_info(
|
| 775 |
+
group_name: str,
|
| 776 |
+
rank: int,
|
| 777 |
+
world_size: int,
|
| 778 |
+
store: Store,
|
| 779 |
+
) -> None: ...
|
| 780 |
+
@staticmethod
|
| 781 |
+
def empty_strided_p2p(
|
| 782 |
+
size: torch.types._size,
|
| 783 |
+
stride: torch.types._size,
|
| 784 |
+
dtype: torch.dtype,
|
| 785 |
+
device: torch.device,
|
| 786 |
+
group_name: str | None = None,
|
| 787 |
+
alloc_id: int | None = None,
|
| 788 |
+
) -> torch.Tensor: ...
|
| 789 |
+
@staticmethod
|
| 790 |
+
def has_multicast_support(
|
| 791 |
+
device_type: DeviceType,
|
| 792 |
+
device_idx: int,
|
| 793 |
+
) -> bool: ...
|
| 794 |
+
# Set Symmetric Memory allocation backend.
|
| 795 |
+
@staticmethod
|
| 796 |
+
def set_backend(name: str) -> None: ...
|
| 797 |
+
@staticmethod
|
| 798 |
+
def get_backend(device: torch.device) -> Optional[str]: ...
|
| 799 |
+
@staticmethod
|
| 800 |
+
def get_mempool_allocator(device: torch.device) -> Any: ...
|
| 801 |
+
signal_pad_size: int
|
| 802 |
+
@property
|
| 803 |
+
def rank(self) -> int: ...
|
| 804 |
+
@property
|
| 805 |
+
def world_size(self) -> int: ...
|
| 806 |
+
@staticmethod
|
| 807 |
+
def rendezvous(
|
| 808 |
+
tensor: torch.Tensor, group_name: str | None = None
|
| 809 |
+
) -> _SymmetricMemory: ...
|
| 810 |
+
def get_buffer(
|
| 811 |
+
self,
|
| 812 |
+
rank: int,
|
| 813 |
+
sizes: torch.types._size,
|
| 814 |
+
dtype: torch.dtype,
|
| 815 |
+
storage_offset: int | None = 0,
|
| 816 |
+
) -> torch.Tensor: ...
|
| 817 |
+
def get_signal_pad(
|
| 818 |
+
self,
|
| 819 |
+
rank: int,
|
| 820 |
+
sizes: torch.types._size = [],
|
| 821 |
+
dtype: torch.dtype | None = None,
|
| 822 |
+
storage_offset: int | None = 0,
|
| 823 |
+
) -> torch.Tensor: ...
|
| 824 |
+
def barrier(self, channel: int = 0, timeout_ms: int = 0) -> None: ...
|
| 825 |
+
def put_signal(
|
| 826 |
+
self,
|
| 827 |
+
dst_rank: int,
|
| 828 |
+
channel: int = 0,
|
| 829 |
+
timeout_ms: int = 0,
|
| 830 |
+
) -> None: ...
|
| 831 |
+
def wait_signal(
|
| 832 |
+
self,
|
| 833 |
+
src_rank: int,
|
| 834 |
+
channel: int = 0,
|
| 835 |
+
timeout_ms: int = 0,
|
| 836 |
+
) -> None: ...
|
| 837 |
+
def get_remote_tensor(
|
| 838 |
+
self,
|
| 839 |
+
peer: int,
|
| 840 |
+
sizes: torch.types._size,
|
| 841 |
+
dtype: torch.dtype,
|
| 842 |
+
) -> torch.Tensor: ...
|
| 843 |
+
@staticmethod
|
| 844 |
+
def memset32(
|
| 845 |
+
tensor: torch.Tensor, offset: int, val: int, count: int = 1
|
| 846 |
+
) -> torch.Tensor: ...
|
| 847 |
+
@staticmethod
|
| 848 |
+
def stream_write_value32(
|
| 849 |
+
tensor: torch.Tensor, offset: int, val: int
|
| 850 |
+
) -> torch.Tensor: ...
|
| 851 |
+
@property
|
| 852 |
+
def buffer_ptrs(self) -> list[int]: ...
|
| 853 |
+
@property
|
| 854 |
+
def buffer_ptrs_dev(self) -> int: ...
|
| 855 |
+
@property
|
| 856 |
+
def signal_pad_ptrs(self) -> list[int]: ...
|
| 857 |
+
@property
|
| 858 |
+
def signal_pad_ptrs_dev(self) -> int: ...
|
| 859 |
+
@property
|
| 860 |
+
def multicast_ptr(self) -> int: ...
|
| 861 |
+
@property
|
| 862 |
+
def buffer_size(self) -> int: ...
|
| 863 |
+
@property
|
| 864 |
+
def device(self) -> torch.device: ...
|
| 865 |
+
|
| 866 |
+
class ProcessGroupXCCL(Backend):
|
| 867 |
+
class Options(Backend.Options):
|
| 868 |
+
is_high_priority_stream: bool
|
| 869 |
+
|
| 870 |
+
def __init__(self, is_high_priority_stream: bool = False): ...
|
| 871 |
+
|
| 872 |
+
def __init__(
|
| 873 |
+
self,
|
| 874 |
+
store: Store,
|
| 875 |
+
rank: int,
|
| 876 |
+
size: int,
|
| 877 |
+
options: Options,
|
| 878 |
+
) -> None: ...
|
| 879 |
+
@property
|
| 880 |
+
def options(self) -> Options: ... # type: ignore[override]
|
| 881 |
+
|
| 882 |
+
def _set_process_group(pg: ProcessGroup) -> None: ...
|
| 883 |
+
def _current_process_group() -> ProcessGroup: ...
|
| 884 |
+
|
| 885 |
+
class _Request:
|
| 886 |
+
def body(self) -> bytes: ...
|
| 887 |
+
def get_param(self, str) -> str: ...
|
| 888 |
+
|
| 889 |
+
class _Response:
|
| 890 |
+
def set_content(self, content: str | bytes, content_type: str) -> None: ...
|
| 891 |
+
def set_status(self, status: int) -> None: ...
|
| 892 |
+
|
| 893 |
+
def _register_handler(
|
| 894 |
+
name: str, handler: Callable[[_Request, _Response], None]
|
| 895 |
+
) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc.pyi
ADDED
|
@@ -0,0 +1,188 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# mypy: disable-error-code="type-arg"
|
| 3 |
+
from datetime import timedelta
|
| 4 |
+
from typing import Any, Generic, overload, TypeVar
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._C import Future
|
| 8 |
+
from torch._C._autograd import ProfilerEvent
|
| 9 |
+
from torch._C._distributed_c10d import Store
|
| 10 |
+
from torch._C._profiler import ProfilerConfig
|
| 11 |
+
|
| 12 |
+
# This module is defined in torch/csrc/distributed/rpc/init.cpp
|
| 13 |
+
|
| 14 |
+
_DEFAULT_INIT_METHOD: str
|
| 15 |
+
_DEFAULT_NUM_WORKER_THREADS: int
|
| 16 |
+
_UNSET_RPC_TIMEOUT: float
|
| 17 |
+
_DEFAULT_RPC_TIMEOUT_SEC: float
|
| 18 |
+
|
| 19 |
+
_T = TypeVar("_T")
|
| 20 |
+
|
| 21 |
+
class RpcBackendOptions:
|
| 22 |
+
rpc_timeout: float
|
| 23 |
+
init_method: str
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
rpc_timeout: float = ...,
|
| 27 |
+
init_method: str = ...,
|
| 28 |
+
) -> None: ...
|
| 29 |
+
|
| 30 |
+
class WorkerInfo:
|
| 31 |
+
def __init__(self, name: str, worker_id: int) -> None: ...
|
| 32 |
+
@property
|
| 33 |
+
def name(self) -> str: ...
|
| 34 |
+
@property
|
| 35 |
+
def id(self) -> int: ...
|
| 36 |
+
def __eq__(self, other: object) -> bool: ...
|
| 37 |
+
|
| 38 |
+
class RpcAgent:
|
| 39 |
+
def join(self, shutdown: bool = False, timeout: float = 0): ...
|
| 40 |
+
def sync(self): ...
|
| 41 |
+
def shutdown(self): ...
|
| 42 |
+
@overload
|
| 43 |
+
def get_worker_info(self) -> WorkerInfo: ...
|
| 44 |
+
@overload
|
| 45 |
+
def get_worker_info(self, workerName: str) -> WorkerInfo: ...
|
| 46 |
+
def get_worker_infos(self) -> list[WorkerInfo]: ...
|
| 47 |
+
def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ...
|
| 48 |
+
def get_debug_info(self) -> dict[str, str]: ...
|
| 49 |
+
def get_metrics(self) -> dict[str, str]: ...
|
| 50 |
+
|
| 51 |
+
class PyRRef(Generic[_T]):
|
| 52 |
+
def __init__(self, value: _T, type_hint: Any = None) -> None: ...
|
| 53 |
+
def is_owner(self) -> bool: ...
|
| 54 |
+
def confirmed_by_owner(self) -> bool: ...
|
| 55 |
+
def owner(self) -> WorkerInfo: ...
|
| 56 |
+
def owner_name(self) -> str: ...
|
| 57 |
+
def to_here(self, timeout: float = ...) -> _T: ...
|
| 58 |
+
def local_value(self) -> Any: ...
|
| 59 |
+
def rpc_sync(self, timeout: float = ...) -> Any: ...
|
| 60 |
+
def rpc_async(self, timeout: float = ...) -> Any: ...
|
| 61 |
+
def remote(self, timeout: float = ...) -> Any: ...
|
| 62 |
+
def _serialize(self) -> tuple: ...
|
| 63 |
+
@staticmethod
|
| 64 |
+
def _deserialize(tp: tuple) -> PyRRef: ...
|
| 65 |
+
def _get_type(self) -> type[_T]: ...
|
| 66 |
+
def _get_future(self) -> Future[_T]: ...
|
| 67 |
+
def _get_profiling_future(self) -> Future[_T]: ...
|
| 68 |
+
def _set_profiling_future(self, profilingFuture: Future[_T]): ...
|
| 69 |
+
|
| 70 |
+
class _TensorPipeRpcBackendOptionsBase(RpcBackendOptions):
|
| 71 |
+
num_worker_threads: int
|
| 72 |
+
device_maps: dict[str, dict[torch.device, torch.device]]
|
| 73 |
+
devices: list[torch.device]
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
num_worker_threads: int,
|
| 77 |
+
_transports: list | None,
|
| 78 |
+
_channels: list | None,
|
| 79 |
+
rpc_timeout: float = ...,
|
| 80 |
+
init_method: str = ...,
|
| 81 |
+
device_maps: dict[str, dict[torch.device, torch.device]] = {}, # noqa: B006
|
| 82 |
+
devices: list[torch.device] = [], # noqa: B006
|
| 83 |
+
) -> None: ...
|
| 84 |
+
def _set_device_map(
|
| 85 |
+
self,
|
| 86 |
+
to: str,
|
| 87 |
+
device_map: dict[torch.device, torch.device],
|
| 88 |
+
): ...
|
| 89 |
+
|
| 90 |
+
class TensorPipeAgent(RpcAgent):
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
store: Store,
|
| 94 |
+
name: str,
|
| 95 |
+
worker_id: int,
|
| 96 |
+
world_size: int | None,
|
| 97 |
+
opts: _TensorPipeRpcBackendOptionsBase,
|
| 98 |
+
reverse_device_maps: dict[str, dict[torch.device, torch.device]],
|
| 99 |
+
devices: list[torch.device],
|
| 100 |
+
) -> None: ...
|
| 101 |
+
def join(self, shutdown: bool = False, timeout: float = 0): ...
|
| 102 |
+
def shutdown(self): ...
|
| 103 |
+
@overload
|
| 104 |
+
def get_worker_info(self) -> WorkerInfo: ...
|
| 105 |
+
@overload
|
| 106 |
+
def get_worker_info(self, workerName: str) -> WorkerInfo: ...
|
| 107 |
+
@overload
|
| 108 |
+
def get_worker_info(self, id: int) -> WorkerInfo: ...
|
| 109 |
+
def get_worker_infos(self) -> list[WorkerInfo]: ...
|
| 110 |
+
def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ...
|
| 111 |
+
def _update_group_membership(
|
| 112 |
+
self,
|
| 113 |
+
worker_info: WorkerInfo,
|
| 114 |
+
my_devices: list[torch.device],
|
| 115 |
+
reverse_device_map: dict[str, dict[torch.device, torch.device]],
|
| 116 |
+
is_join: bool,
|
| 117 |
+
): ...
|
| 118 |
+
def _get_backend_options(self) -> _TensorPipeRpcBackendOptionsBase: ...
|
| 119 |
+
@property
|
| 120 |
+
def is_static_group(self) -> bool: ...
|
| 121 |
+
@property
|
| 122 |
+
def store(self) -> Store: ...
|
| 123 |
+
|
| 124 |
+
def _is_current_rpc_agent_set() -> bool: ...
|
| 125 |
+
def _get_current_rpc_agent() -> RpcAgent: ...
|
| 126 |
+
def _set_and_start_rpc_agent(agent: RpcAgent): ...
|
| 127 |
+
def _reset_current_rpc_agent(): ...
|
| 128 |
+
def _delete_all_user_and_unforked_owner_rrefs(timeout: timedelta = ...): ...
|
| 129 |
+
def _destroy_rref_context(ignoreRRefLeak: bool): ...
|
| 130 |
+
def _rref_context_get_debug_info() -> dict[str, str]: ...
|
| 131 |
+
def _cleanup_python_rpc_handler(): ...
|
| 132 |
+
def _invoke_rpc_builtin(
|
| 133 |
+
dst: WorkerInfo,
|
| 134 |
+
opName: str,
|
| 135 |
+
rpcTimeoutSeconds: float,
|
| 136 |
+
*args: Any,
|
| 137 |
+
**kwargs: Any,
|
| 138 |
+
): ...
|
| 139 |
+
def _invoke_rpc_python_udf(
|
| 140 |
+
dst: WorkerInfo,
|
| 141 |
+
pickledPythonUDF: str,
|
| 142 |
+
tensors: list[torch.Tensor],
|
| 143 |
+
rpcTimeoutSeconds: float,
|
| 144 |
+
isAsyncExecution: bool,
|
| 145 |
+
): ...
|
| 146 |
+
def _invoke_rpc_torchscript(
|
| 147 |
+
dstWorkerName: str,
|
| 148 |
+
qualifiedNameStr: str,
|
| 149 |
+
argsTuple: tuple,
|
| 150 |
+
kwargsDict: dict,
|
| 151 |
+
rpcTimeoutSeconds: float,
|
| 152 |
+
isAsyncExecution: bool,
|
| 153 |
+
): ...
|
| 154 |
+
def _invoke_remote_builtin(
|
| 155 |
+
dst: WorkerInfo,
|
| 156 |
+
opName: str,
|
| 157 |
+
rpcTimeoutSeconds: float,
|
| 158 |
+
*args: Any,
|
| 159 |
+
**kwargs: Any,
|
| 160 |
+
): ...
|
| 161 |
+
def _invoke_remote_python_udf(
|
| 162 |
+
dst: WorkerInfo,
|
| 163 |
+
pickledPythonUDF: str,
|
| 164 |
+
tensors: list[torch.Tensor],
|
| 165 |
+
rpcTimeoutSeconds: float,
|
| 166 |
+
isAsyncExecution: bool,
|
| 167 |
+
): ...
|
| 168 |
+
def _invoke_remote_torchscript(
|
| 169 |
+
dstWorkerName: WorkerInfo,
|
| 170 |
+
qualifiedNameStr: str,
|
| 171 |
+
rpcTimeoutSeconds: float,
|
| 172 |
+
isAsyncExecution: bool,
|
| 173 |
+
*args: Any,
|
| 174 |
+
**kwargs: Any,
|
| 175 |
+
): ...
|
| 176 |
+
def get_rpc_timeout() -> float: ...
|
| 177 |
+
def enable_gil_profiling(flag: bool): ...
|
| 178 |
+
def _set_rpc_timeout(rpcTimeoutSeconds: float): ...
|
| 179 |
+
|
| 180 |
+
class RemoteProfilerManager:
|
| 181 |
+
@staticmethod
|
| 182 |
+
def set_current_profiling_key(key: str): ...
|
| 183 |
+
|
| 184 |
+
def _enable_server_process_global_profiler(new_config: ProfilerConfig): ...
|
| 185 |
+
def _disable_server_process_global_profiler() -> list[list[list[ProfilerEvent]]]: ...
|
| 186 |
+
def _set_profiler_node_id(default_node_id: int): ...
|
| 187 |
+
def _enable_jit_rref_pickle(): ...
|
| 188 |
+
def _disable_jit_rref_pickle(): ...
|
.venv/lib/python3.10/site-packages/torch/_C/_distributed_rpc_testing.pyi
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch._C._distributed_c10d import Store
|
| 3 |
+
from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase, TensorPipeAgent
|
| 4 |
+
|
| 5 |
+
# This module is defined in torch/csrc/distributed/rpc/testing/init.cpp
|
| 6 |
+
|
| 7 |
+
class FaultyTensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase):
|
| 8 |
+
def __init__(
|
| 9 |
+
self,
|
| 10 |
+
num_worker_threads: int,
|
| 11 |
+
rpc_timeout: float,
|
| 12 |
+
init_method: str,
|
| 13 |
+
messages_to_fail: list[str],
|
| 14 |
+
messages_to_delay: dict[str, float],
|
| 15 |
+
num_fail_sends: int,
|
| 16 |
+
) -> None: ...
|
| 17 |
+
num_send_recv_threads: int
|
| 18 |
+
messages_to_fail: list[str]
|
| 19 |
+
messages_to_delay: dict[str, float]
|
| 20 |
+
num_fail_sends: int
|
| 21 |
+
|
| 22 |
+
class FaultyTensorPipeAgent(TensorPipeAgent):
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
store: Store,
|
| 26 |
+
name: str,
|
| 27 |
+
rank: int,
|
| 28 |
+
world_size: int,
|
| 29 |
+
options: FaultyTensorPipeRpcBackendOptions,
|
| 30 |
+
reverse_device_maps: dict[str, dict[torch.device, torch.device]],
|
| 31 |
+
devices: list[torch.device],
|
| 32 |
+
) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_dynamo/__init__.pyi
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import compiled_autograd, eval_frame, guards # noqa: F401
|
| 2 |
+
|
| 3 |
+
def strip_function_call(name: str) -> str: ...
|
| 4 |
+
def is_valid_var_name(name: str) -> bool | int: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_dynamo/compiled_autograd.pyi
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
from torch._dynamo.compiled_autograd import AutogradCompilerInstance
|
| 5 |
+
|
| 6 |
+
def set_autograd_compiler(
|
| 7 |
+
autograd_compiler: Callable[[], AutogradCompilerInstance] | None,
|
| 8 |
+
dynamic: bool,
|
| 9 |
+
) -> tuple[Callable[[], AutogradCompilerInstance] | None, bool]: ...
|
| 10 |
+
def clear_cache() -> None: ...
|
| 11 |
+
def is_cache_empty() -> bool: ...
|
| 12 |
+
def set_verbose_logger(fn: Callable[[str], None] | None) -> bool: ...
|
| 13 |
+
def call_cpp_tensor_pre_hooks(idx: int, grad: Tensor) -> Tensor: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_dynamo/eval_frame.pyi
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
import types
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from typing import Optional, overload
|
| 5 |
+
|
| 6 |
+
from torch._dynamo.guards import GuardManagerWrapper
|
| 7 |
+
from torch._dynamo.types import DynamoCallback, DynamoGuardCompleteHook, DynamoGuardHook
|
| 8 |
+
from torch._guards import CompileId
|
| 9 |
+
|
| 10 |
+
def set_eval_frame(callback: DynamoCallback) -> DynamoCallback: ...
|
| 11 |
+
def set_skip_guard_eval_unsafe(value: bool) -> bool: ...
|
| 12 |
+
def get_eval_frame_callback() -> DynamoCallback: ...
|
| 13 |
+
def reset_code(code: types.CodeType) -> None: ...
|
| 14 |
+
def unsupported(obj1: object, obj2: object) -> object: ...
|
| 15 |
+
def set_code_exec_strategy(
|
| 16 |
+
code: types.CodeType, strategy: _FrameExecStrategy
|
| 17 |
+
) -> None: ...
|
| 18 |
+
def set_guard_error_hook(hook: DynamoGuardHook) -> None: ...
|
| 19 |
+
def set_guard_complete_hook(
|
| 20 |
+
hook: Optional[DynamoGuardCompleteHook],
|
| 21 |
+
) -> Optional[DynamoGuardCompleteHook]: ...
|
| 22 |
+
def raise_sigtrap() -> None: ...
|
| 23 |
+
def set_c_recursion_limit(limit: int) -> None: ...
|
| 24 |
+
def get_c_recursion_limit() -> int: ...
|
| 25 |
+
|
| 26 |
+
class _CacheEntry:
|
| 27 |
+
def check_fn(self, *args: object, **kwargs: object) -> bool: ...
|
| 28 |
+
def update_diff_guard_root_manager(self) -> None: ...
|
| 29 |
+
code: types.CodeType
|
| 30 |
+
compile_id: CompileId
|
| 31 |
+
# If we run into circular issues, just use object
|
| 32 |
+
guard_manager: GuardManagerWrapper
|
| 33 |
+
backend: Callable
|
| 34 |
+
next: _CacheEntry | None
|
| 35 |
+
|
| 36 |
+
class _PrecompileEntry:
|
| 37 |
+
guard_manager: GuardManagerWrapper
|
| 38 |
+
|
| 39 |
+
class _ExtraState:
|
| 40 |
+
def invalidate(
|
| 41 |
+
self, cache_entry: _CacheEntry, guard_manager: GuardManagerWrapper
|
| 42 |
+
) -> None: ...
|
| 43 |
+
|
| 44 |
+
class _FrameAction(enum.IntEnum):
|
| 45 |
+
DEFAULT = 0
|
| 46 |
+
SKIP = 1
|
| 47 |
+
RUN_ONLY = 2
|
| 48 |
+
|
| 49 |
+
class _FrameExecStrategy:
|
| 50 |
+
cur_action: _FrameAction
|
| 51 |
+
recursive_action: _FrameAction
|
| 52 |
+
|
| 53 |
+
@overload
|
| 54 |
+
def __init__(self) -> None: ...
|
| 55 |
+
@overload
|
| 56 |
+
def __init__(
|
| 57 |
+
self, cur_action: _FrameAction, recursive_action: _FrameAction
|
| 58 |
+
) -> None: ...
|
| 59 |
+
|
| 60 |
+
# This is an object that encapsulates the Python FrameType, and exposes
|
| 61 |
+
# properties Dynamo cares about for a frame.
|
| 62 |
+
class _PyInterpreterFrame:
|
| 63 |
+
f_code: types.CodeType
|
| 64 |
+
f_locals: dict[str, object]
|
| 65 |
+
f_globals: dict[str, object]
|
| 66 |
+
f_builtins: dict[str, object]
|
| 67 |
+
f_lasti: int
|
| 68 |
+
f_lineno: int
|
| 69 |
+
f_back: types.FrameType
|
| 70 |
+
# A tuple containing cell objects captured by this frame.
|
| 71 |
+
closure: tuple[types.CellType]
|
| 72 |
+
|
| 73 |
+
def _debug_get_cache_entry_list(code: types.CodeType) -> list[_CacheEntry]: ...
|
| 74 |
+
|
| 75 |
+
py_opcode_caches: list[int]
|
| 76 |
+
|
| 77 |
+
def code_framelocals_names(code: types.CodeType) -> tuple[str, ...]: ...
|
| 78 |
+
def _load_precompile_entry(
|
| 79 |
+
code: types.CodeType,
|
| 80 |
+
guard_manager: GuardManagerWrapper,
|
| 81 |
+
dynamo_code: types.CodeType,
|
| 82 |
+
) -> None: ...
|
| 83 |
+
def _reset_precompile_entries(code: types.CodeType) -> None: ...
|
| 84 |
+
def _debug_get_precompile_entries(code: types.CodeType) -> list[_PrecompileEntry]: ...
|
| 85 |
+
|
| 86 |
+
class _EvalFrameOverride(enum.IntEnum):
|
| 87 |
+
NONE = 0
|
| 88 |
+
SKIP = 1
|
| 89 |
+
ERROR = 2
|
| 90 |
+
|
| 91 |
+
def set_eval_frame_override(override: _EvalFrameOverride) -> _EvalFrameOverride: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_dynamo/guards.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import Callable
|
| 4 |
+
from typing import Any, Optional, TypeAlias
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
# TODO: We should move the `GuardManagerType`
|
| 9 |
+
# defined in `guards.py` here and update other
|
| 10 |
+
# imports
|
| 11 |
+
GuardManagerType: TypeAlias = enum.Enum
|
| 12 |
+
|
| 13 |
+
class GlobalStateGuard:
|
| 14 |
+
def check(self) -> bool: ...
|
| 15 |
+
def reason(self) -> str: ...
|
| 16 |
+
|
| 17 |
+
class LeafGuard:
|
| 18 |
+
def verbose_code_parts(self) -> list[str]: ...
|
| 19 |
+
|
| 20 |
+
class RelationalGuard: ...
|
| 21 |
+
|
| 22 |
+
class GuardDebugInfo:
|
| 23 |
+
verbose_code_parts: list[str]
|
| 24 |
+
result: bool
|
| 25 |
+
num_guards_executed: int
|
| 26 |
+
user_stack: Optional[traceback.StackSummary]
|
| 27 |
+
|
| 28 |
+
class GuardManager:
|
| 29 |
+
def check(self, value: Any) -> bool: ...
|
| 30 |
+
def check_verbose(self, value: Any) -> GuardDebugInfo: ...
|
| 31 |
+
|
| 32 |
+
# Accessors
|
| 33 |
+
def globals_dict_manager(
|
| 34 |
+
self,
|
| 35 |
+
f_globals: dict[str, Any],
|
| 36 |
+
source: str,
|
| 37 |
+
example_value: Any,
|
| 38 |
+
guard_manager_enum: GuardManagerType,
|
| 39 |
+
) -> GuardManager: ...
|
| 40 |
+
def framelocals_manager(
|
| 41 |
+
self,
|
| 42 |
+
key: tuple[str, int],
|
| 43 |
+
source: str,
|
| 44 |
+
example_value: Any,
|
| 45 |
+
guard_manager_enum: GuardManagerType,
|
| 46 |
+
) -> GuardManager: ...
|
| 47 |
+
def dict_getitem_manager(
|
| 48 |
+
self,
|
| 49 |
+
key: Any,
|
| 50 |
+
source: str,
|
| 51 |
+
example_value: Any,
|
| 52 |
+
guard_manager_enum: GuardManagerType,
|
| 53 |
+
) -> GuardManager: ...
|
| 54 |
+
def grad_manager(
|
| 55 |
+
self,
|
| 56 |
+
source: str,
|
| 57 |
+
example_value: Any,
|
| 58 |
+
guard_manager_enum: GuardManagerType,
|
| 59 |
+
) -> GuardManager: ...
|
| 60 |
+
def generic_getattr_manager(
|
| 61 |
+
self,
|
| 62 |
+
attr: str,
|
| 63 |
+
source: str,
|
| 64 |
+
example_value: Any,
|
| 65 |
+
guard_manager_enum: GuardManagerType,
|
| 66 |
+
) -> GuardManager: ...
|
| 67 |
+
def getitem_manager(
|
| 68 |
+
self,
|
| 69 |
+
key: Any,
|
| 70 |
+
source: str,
|
| 71 |
+
example_value: Any,
|
| 72 |
+
guard_manager_enum: GuardManagerType,
|
| 73 |
+
) -> GuardManager: ...
|
| 74 |
+
def get_generic_dict_manager(
|
| 75 |
+
self,
|
| 76 |
+
source: str,
|
| 77 |
+
example_value: Any,
|
| 78 |
+
guard_manager_enum: GuardManagerType,
|
| 79 |
+
) -> GuardManager: ...
|
| 80 |
+
def list_getitem_manager(
|
| 81 |
+
self,
|
| 82 |
+
key: Any,
|
| 83 |
+
source: str,
|
| 84 |
+
example_value: Any,
|
| 85 |
+
guard_manager_enum: GuardManagerType,
|
| 86 |
+
) -> GuardManager: ...
|
| 87 |
+
def tuple_getitem_manager(
|
| 88 |
+
self,
|
| 89 |
+
key: Any,
|
| 90 |
+
source: str,
|
| 91 |
+
example_value: Any,
|
| 92 |
+
guard_manager_enum: GuardManagerType,
|
| 93 |
+
) -> GuardManager: ...
|
| 94 |
+
def set_getitem_manager(
|
| 95 |
+
self,
|
| 96 |
+
index: Any,
|
| 97 |
+
source: str,
|
| 98 |
+
example_value: Any,
|
| 99 |
+
guard_manager_enum: GuardManagerType,
|
| 100 |
+
) -> GuardManager: ...
|
| 101 |
+
def func_defaults_manager(
|
| 102 |
+
self,
|
| 103 |
+
source: str,
|
| 104 |
+
example_value: Any,
|
| 105 |
+
guard_manager_enum: GuardManagerType,
|
| 106 |
+
) -> GuardManager: ...
|
| 107 |
+
def func_kwdefaults_manager(
|
| 108 |
+
self,
|
| 109 |
+
source: str,
|
| 110 |
+
example_value: Any,
|
| 111 |
+
guard_manager_enum: GuardManagerType,
|
| 112 |
+
) -> GuardManager: ...
|
| 113 |
+
def tuple_iterator_getitem_manager(
|
| 114 |
+
self,
|
| 115 |
+
index: Any,
|
| 116 |
+
source: str,
|
| 117 |
+
example_value: Any,
|
| 118 |
+
guard_manager_enum: GuardManagerType,
|
| 119 |
+
) -> GuardManager: ...
|
| 120 |
+
def weakref_call_manager(
|
| 121 |
+
self,
|
| 122 |
+
source: str,
|
| 123 |
+
example_value: Any,
|
| 124 |
+
guard_manager_enum: GuardManagerType,
|
| 125 |
+
) -> GuardManager: ...
|
| 126 |
+
def call_function_no_args_manager(
|
| 127 |
+
self,
|
| 128 |
+
source: str,
|
| 129 |
+
example_value: Any,
|
| 130 |
+
guard_manager_enum: GuardManagerType,
|
| 131 |
+
) -> GuardManager: ...
|
| 132 |
+
def global_weakref_manager(
|
| 133 |
+
self,
|
| 134 |
+
global_name: str,
|
| 135 |
+
source: str,
|
| 136 |
+
example_value: Any,
|
| 137 |
+
guard_manager_enum: GuardManagerType,
|
| 138 |
+
) -> GuardManager: ...
|
| 139 |
+
def type_manager(
|
| 140 |
+
self,
|
| 141 |
+
source: str,
|
| 142 |
+
example_value: Any,
|
| 143 |
+
guard_manager_enum: GuardManagerType,
|
| 144 |
+
) -> GuardManager: ...
|
| 145 |
+
def getattr_manager(
|
| 146 |
+
self,
|
| 147 |
+
attr: str,
|
| 148 |
+
source: str,
|
| 149 |
+
example_value: Any,
|
| 150 |
+
guard_manager_enum: GuardManagerType,
|
| 151 |
+
) -> GuardManager: ...
|
| 152 |
+
def tensor_property_size_manager(
|
| 153 |
+
self,
|
| 154 |
+
idx: int,
|
| 155 |
+
source: str,
|
| 156 |
+
example_value: Any,
|
| 157 |
+
guard_manager_enum: GuardManagerType,
|
| 158 |
+
) -> GuardManager: ...
|
| 159 |
+
def tensor_property_shape_manager(
|
| 160 |
+
self,
|
| 161 |
+
idx: int,
|
| 162 |
+
source: str,
|
| 163 |
+
example_value: Any,
|
| 164 |
+
guard_manager_enum: GuardManagerType,
|
| 165 |
+
) -> GuardManager: ...
|
| 166 |
+
def tensor_property_storage_offset_manager(
|
| 167 |
+
self,
|
| 168 |
+
idx: int,
|
| 169 |
+
source: str,
|
| 170 |
+
example_value: Any,
|
| 171 |
+
guard_manager_enum: GuardManagerType,
|
| 172 |
+
) -> GuardManager: ...
|
| 173 |
+
def indexed_manager(
|
| 174 |
+
self,
|
| 175 |
+
idx: int,
|
| 176 |
+
source: str,
|
| 177 |
+
example_value: Any,
|
| 178 |
+
guard_manager_enum: GuardManagerType,
|
| 179 |
+
) -> GuardManager: ...
|
| 180 |
+
def lambda_manager(
|
| 181 |
+
self,
|
| 182 |
+
python_lambda: Callable[..., Any],
|
| 183 |
+
source: str,
|
| 184 |
+
example_value: Any,
|
| 185 |
+
guard_manager_enum: GuardManagerType,
|
| 186 |
+
) -> GuardManager: ...
|
| 187 |
+
def get_root(self) -> RootGuardManager: ...
|
| 188 |
+
def get_source(self) -> str: ...
|
| 189 |
+
def fail_count(self) -> int: ...
|
| 190 |
+
def get_child_managers(self) -> list[GuardManager]: ...
|
| 191 |
+
def repr(self) -> str: ...
|
| 192 |
+
def type_of_guarded_value(self) -> str: ...
|
| 193 |
+
def get_leaf_guards(self) -> list[LeafGuard]: ...
|
| 194 |
+
def get_accessors(self) -> list[GuardManager]: ...
|
| 195 |
+
def is_guarded_value_immutable(self) -> bool: ...
|
| 196 |
+
def is_tag_safe(self) -> bool: ...
|
| 197 |
+
def is_tag_safe_root(self) -> bool: ...
|
| 198 |
+
def has_no_accessors(self) -> bool: ...
|
| 199 |
+
def has_object_aliasing_guard(self) -> bool: ...
|
| 200 |
+
def get_type_of_guarded_value(self) -> type: ...
|
| 201 |
+
def type_dict_manager(
|
| 202 |
+
self,
|
| 203 |
+
source: str,
|
| 204 |
+
example_value: Any,
|
| 205 |
+
guard_manager_enum: GuardManagerType,
|
| 206 |
+
) -> GuardManager: ...
|
| 207 |
+
def type_mro_manager(
|
| 208 |
+
self,
|
| 209 |
+
source: str,
|
| 210 |
+
example_value: Any,
|
| 211 |
+
guard_manager_enum: GuardManagerType,
|
| 212 |
+
) -> GuardManager: ...
|
| 213 |
+
def code_manager(
|
| 214 |
+
self,
|
| 215 |
+
source: str,
|
| 216 |
+
example_value: Any,
|
| 217 |
+
guard_manager_enum: GuardManagerType,
|
| 218 |
+
) -> GuardManager: ...
|
| 219 |
+
def closure_manager(
|
| 220 |
+
self,
|
| 221 |
+
source: str,
|
| 222 |
+
example_value: Any,
|
| 223 |
+
guard_manager_enum: GuardManagerType,
|
| 224 |
+
) -> GuardManager: ...
|
| 225 |
+
# Leaf guards
|
| 226 |
+
def add_lambda_guard(
|
| 227 |
+
self,
|
| 228 |
+
user_lambda: Callable[..., Any],
|
| 229 |
+
verbose_code_parts: list[str],
|
| 230 |
+
user_stack: Optional[traceback.StackSummary],
|
| 231 |
+
) -> None: ...
|
| 232 |
+
def add_id_match_guard(
|
| 233 |
+
self,
|
| 234 |
+
id_val: int,
|
| 235 |
+
verbose_code_parts: list[str],
|
| 236 |
+
user_stack: Optional[traceback.StackSummary],
|
| 237 |
+
) -> None: ...
|
| 238 |
+
def add_equals_match_guard(
|
| 239 |
+
self,
|
| 240 |
+
equals_val: Any,
|
| 241 |
+
verbose_code_parts: list[str],
|
| 242 |
+
user_stack: Optional[traceback.StackSummary],
|
| 243 |
+
) -> None: ...
|
| 244 |
+
def add_global_state_guard(
|
| 245 |
+
self,
|
| 246 |
+
initial_state: Any,
|
| 247 |
+
verbose_code_parts: list[str],
|
| 248 |
+
user_stack: Optional[traceback.StackSummary],
|
| 249 |
+
) -> None: ...
|
| 250 |
+
def add_torch_function_mode_stack_guard(
|
| 251 |
+
self,
|
| 252 |
+
initial_stack: list[Any],
|
| 253 |
+
verbose_code_parts: list[str],
|
| 254 |
+
user_stack: Optional[traceback.StackSummary],
|
| 255 |
+
) -> None: ...
|
| 256 |
+
def add_mapping_keys_guard(
|
| 257 |
+
self,
|
| 258 |
+
value: Any,
|
| 259 |
+
verbose_code_parts: list[str],
|
| 260 |
+
user_stack: Optional[traceback.StackSummary],
|
| 261 |
+
) -> None: ...
|
| 262 |
+
def add_dict_length_check_guard(
|
| 263 |
+
self,
|
| 264 |
+
value: int,
|
| 265 |
+
verbose_code_parts: list[str],
|
| 266 |
+
user_stack: Optional[traceback.StackSummary],
|
| 267 |
+
) -> None: ...
|
| 268 |
+
def add_length_check_guard(
|
| 269 |
+
self,
|
| 270 |
+
value: int,
|
| 271 |
+
verbose_code_parts: list[str],
|
| 272 |
+
user_stack: Optional[traceback.StackSummary],
|
| 273 |
+
) -> None: ...
|
| 274 |
+
def add_true_match_guard(
|
| 275 |
+
self,
|
| 276 |
+
verbose_code_parts: list[str],
|
| 277 |
+
user_stack: Optional[traceback.StackSummary],
|
| 278 |
+
) -> None: ...
|
| 279 |
+
def add_false_match_guard(
|
| 280 |
+
self,
|
| 281 |
+
verbose_code_parts: list[str],
|
| 282 |
+
user_stack: Optional[traceback.StackSummary],
|
| 283 |
+
) -> None: ...
|
| 284 |
+
def add_none_match_guard(
|
| 285 |
+
self,
|
| 286 |
+
verbose_code_parts: list[str],
|
| 287 |
+
user_stack: Optional[traceback.StackSummary],
|
| 288 |
+
) -> None: ...
|
| 289 |
+
def add_not_none_guard(
|
| 290 |
+
self,
|
| 291 |
+
verbose_code_parts: list[str],
|
| 292 |
+
user_stack: Optional[traceback.StackSummary],
|
| 293 |
+
) -> None: ...
|
| 294 |
+
def add_dispatch_key_set_guard(
|
| 295 |
+
self,
|
| 296 |
+
dispatch_key: Any,
|
| 297 |
+
verbose_code_parts: list[str],
|
| 298 |
+
user_stack: Optional[traceback.StackSummary],
|
| 299 |
+
) -> None: ...
|
| 300 |
+
def add_tensor_match_guard(
|
| 301 |
+
self,
|
| 302 |
+
value: Any,
|
| 303 |
+
sizes: list[int],
|
| 304 |
+
strides: list[int],
|
| 305 |
+
tensor_name: str,
|
| 306 |
+
verbose_code_parts: list[str],
|
| 307 |
+
user_stack: Optional[traceback.StackSummary],
|
| 308 |
+
ptype: Any,
|
| 309 |
+
dispatch_keys: Any,
|
| 310 |
+
) -> None: ...
|
| 311 |
+
def add_dynamic_indices_guard(
|
| 312 |
+
self,
|
| 313 |
+
value: set[Any],
|
| 314 |
+
verbose_code_parts: list[str],
|
| 315 |
+
user_stack: Optional[traceback.StackSummary],
|
| 316 |
+
) -> None: ...
|
| 317 |
+
def add_no_hasattr_guard(
|
| 318 |
+
self,
|
| 319 |
+
attr_name: str,
|
| 320 |
+
verbose_code_parts: list[str],
|
| 321 |
+
user_stack: Optional[traceback.StackSummary],
|
| 322 |
+
) -> None: ...
|
| 323 |
+
def add_dict_contains_guard(
|
| 324 |
+
self,
|
| 325 |
+
contains: bool,
|
| 326 |
+
key: Any,
|
| 327 |
+
verbose_code_parts: list[str],
|
| 328 |
+
user_stack: Optional[traceback.StackSummary],
|
| 329 |
+
) -> None: ...
|
| 330 |
+
def add_type_match_guard(
|
| 331 |
+
self,
|
| 332 |
+
value: int,
|
| 333 |
+
verbose_code_parts: list[str],
|
| 334 |
+
user_stack: Optional[traceback.StackSummary],
|
| 335 |
+
) -> None: ...
|
| 336 |
+
def add_dict_version_guard(
|
| 337 |
+
self,
|
| 338 |
+
value: Any,
|
| 339 |
+
verbose_code_parts: list[str],
|
| 340 |
+
user_stack: Optional[traceback.StackSummary],
|
| 341 |
+
) -> None: ...
|
| 342 |
+
def add_set_contains_guard(
|
| 343 |
+
self,
|
| 344 |
+
contains: bool,
|
| 345 |
+
item: Any,
|
| 346 |
+
verbose_code_parts: list[str],
|
| 347 |
+
user_stack: Optional[traceback.StackSummary],
|
| 348 |
+
) -> None: ...
|
| 349 |
+
def add_dual_level_match_guard(
|
| 350 |
+
self,
|
| 351 |
+
level: int,
|
| 352 |
+
verbose_code_parts: list[str],
|
| 353 |
+
user_stack: Optional[traceback.StackSummary],
|
| 354 |
+
) -> None: ...
|
| 355 |
+
def add_float_is_nan_guard(
|
| 356 |
+
self,
|
| 357 |
+
verbose_code_parts: list[str],
|
| 358 |
+
user_stack: Optional[traceback.StackSummary],
|
| 359 |
+
) -> None: ...
|
| 360 |
+
def add_complex_is_nan_guard(
|
| 361 |
+
self,
|
| 362 |
+
verbose_code_parts: list[str],
|
| 363 |
+
user_stack: Optional[traceback.StackSummary],
|
| 364 |
+
) -> None: ...
|
| 365 |
+
def add_tuple_iterator_length_guard(
|
| 366 |
+
self,
|
| 367 |
+
length: int,
|
| 368 |
+
type_id: int,
|
| 369 |
+
verbose_code_parts: list[str],
|
| 370 |
+
user_stack: Optional[traceback.StackSummary],
|
| 371 |
+
) -> None: ...
|
| 372 |
+
def add_range_iterator_match_guard(
|
| 373 |
+
self,
|
| 374 |
+
start: int,
|
| 375 |
+
stop: int,
|
| 376 |
+
step: int,
|
| 377 |
+
type_id: int,
|
| 378 |
+
verbose_code_parts: list[str],
|
| 379 |
+
user_stack: Optional[traceback.StackSummary],
|
| 380 |
+
) -> None: ...
|
| 381 |
+
def add_default_device_guard(
|
| 382 |
+
self,
|
| 383 |
+
verbose_code_parts: list[str],
|
| 384 |
+
user_stack: Optional[traceback.StackSummary],
|
| 385 |
+
) -> None: ...
|
| 386 |
+
def mark_tag_safe(self) -> None: ...
|
| 387 |
+
def mark_tag_safe_root(self) -> None: ...
|
| 388 |
+
|
| 389 |
+
class RootGuardManager(GuardManager):
|
| 390 |
+
def get_epilogue_lambda_guards(self) -> list[LeafGuard]: ...
|
| 391 |
+
def add_epilogue_lambda_guard(
|
| 392 |
+
self,
|
| 393 |
+
guard: LeafGuard,
|
| 394 |
+
verbose_code_parts: list[str],
|
| 395 |
+
user_stack: Optional[traceback.StackSummary],
|
| 396 |
+
) -> None: ...
|
| 397 |
+
def clone_manager(
|
| 398 |
+
self, clone_filter_fn: Callable[[GuardManager], bool]
|
| 399 |
+
) -> RootGuardManager: ...
|
| 400 |
+
def attach_compile_id(self, compile_id: str) -> None: ...
|
| 401 |
+
|
| 402 |
+
class DictGuardManager(GuardManager):
|
| 403 |
+
def get_key_manager(
|
| 404 |
+
self,
|
| 405 |
+
index: int,
|
| 406 |
+
source: str,
|
| 407 |
+
example_value: Any,
|
| 408 |
+
guard_manager_enum: GuardManagerType,
|
| 409 |
+
) -> GuardManager: ...
|
| 410 |
+
def get_value_manager(
|
| 411 |
+
self,
|
| 412 |
+
index: int,
|
| 413 |
+
source: str,
|
| 414 |
+
example_value: Any,
|
| 415 |
+
guard_manager_enum: GuardManagerType,
|
| 416 |
+
) -> GuardManager: ...
|
| 417 |
+
def get_key_value_managers(
|
| 418 |
+
self,
|
| 419 |
+
) -> dict[int, tuple[GuardManager, GuardManager]]: ...
|
| 420 |
+
|
| 421 |
+
# Guard accessor stubs
|
| 422 |
+
class GuardAccessor: ...
|
| 423 |
+
class DictGetItemGuardAccessor(GuardAccessor): ...
|
| 424 |
+
class GetGenericDictGuardAccessor(GuardAccessor): ...
|
| 425 |
+
class TypeDictGuardAccessor(GuardAccessor): ...
|
| 426 |
+
class TypeMROGuardAccessor(GuardAccessor): ...
|
| 427 |
+
class ClosureGuardAccessor(GuardAccessor): ...
|
| 428 |
+
class TupleGetItemGuardAccessor(GuardAccessor): ...
|
| 429 |
+
class TypeGuardAccessor(GuardAccessor): ...
|
| 430 |
+
class CodeGuardAccessor(GuardAccessor): ...
|
| 431 |
+
class FuncDefaultsGuardAccessor(GuardAccessor): ...
|
| 432 |
+
class FuncKwDefaultsGuardAccessor(GuardAccessor): ...
|
| 433 |
+
|
| 434 |
+
class GetAttrGuardAccessor(GuardAccessor):
|
| 435 |
+
def get_attr_name(self) -> str: ...
|
| 436 |
+
|
| 437 |
+
def install_object_aliasing_guard(
|
| 438 |
+
x: GuardManager,
|
| 439 |
+
y: GuardManager,
|
| 440 |
+
verbose_code_parts: list[str],
|
| 441 |
+
user_stack: Optional[traceback.StackSummary],
|
| 442 |
+
) -> None: ...
|
| 443 |
+
def install_no_tensor_aliasing_guard(
|
| 444 |
+
guard_managers: list[GuardManager],
|
| 445 |
+
tensor_names: list[str],
|
| 446 |
+
verbose_code_parts: list[str],
|
| 447 |
+
user_stack: Optional[traceback.StackSummary],
|
| 448 |
+
) -> None: ...
|
| 449 |
+
def install_storage_overlapping_guard(
|
| 450 |
+
overlapping_guard_managers: list[GuardManager],
|
| 451 |
+
non_overlapping_guard_managers: list[GuardManager],
|
| 452 |
+
verbose_code_parts: list[str],
|
| 453 |
+
user_stack: Optional[traceback.StackSummary],
|
| 454 |
+
) -> None: ...
|
| 455 |
+
def install_symbolic_shape_guard(
|
| 456 |
+
guard_managers: list[GuardManager],
|
| 457 |
+
nargs_int: int,
|
| 458 |
+
nargs_float: int,
|
| 459 |
+
py_addr: int,
|
| 460 |
+
py_addr_keep_alive: Any,
|
| 461 |
+
verbose_code_parts: list[str],
|
| 462 |
+
user_stack: Optional[traceback.StackSummary],
|
| 463 |
+
) -> None: ...
|
| 464 |
+
def profile_guard_manager(
|
| 465 |
+
guard_manager: GuardManager,
|
| 466 |
+
f_locals: dict[str, Any],
|
| 467 |
+
n_iters: int,
|
| 468 |
+
) -> float: ...
|
| 469 |
+
|
| 470 |
+
class TensorGuards:
|
| 471 |
+
def __init__(
|
| 472 |
+
self,
|
| 473 |
+
*,
|
| 474 |
+
dynamic_dims_sizes: list[torch.SymInt | None] | None = None,
|
| 475 |
+
dynamic_dims_strides: list[torch.SymInt | None] | None = None,
|
| 476 |
+
) -> None: ...
|
| 477 |
+
def check(self, *args: Any) -> bool: ...
|
| 478 |
+
def check_verbose(
|
| 479 |
+
self, *args: Any, tensor_check_names: Optional[list[str]] = None
|
| 480 |
+
) -> bool | str: ...
|
| 481 |
+
|
| 482 |
+
def assert_size_stride(
|
| 483 |
+
item: torch.Tensor,
|
| 484 |
+
size: torch.types._size,
|
| 485 |
+
stride: torch.types._size,
|
| 486 |
+
op_name: str | None = None,
|
| 487 |
+
) -> None: ...
|
| 488 |
+
def assert_alignment(
|
| 489 |
+
item: torch.Tensor,
|
| 490 |
+
alignment: int,
|
| 491 |
+
op_name: str | None = None,
|
| 492 |
+
) -> None: ...
|
| 493 |
+
def check_obj_id(obj: object, expected: int) -> bool: ...
|
| 494 |
+
def check_type_id(obj: object, expected: int) -> bool: ...
|
| 495 |
+
def dict_version(d: dict[Any, Any]) -> int: ...
|
| 496 |
+
def compute_overlapping_tensors(
|
| 497 |
+
tensors: list[torch.Tensor], symbolic: bool = True
|
| 498 |
+
) -> set[int]: ...
|
| 499 |
+
def set_is_in_mode_without_ignore_compile_internals(value: bool) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_export/__init__.pyi
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/export/pybind.cpp
|
| 2 |
+
class CppExportedProgram: ...
|
| 3 |
+
|
| 4 |
+
def deserialize_exported_program(
|
| 5 |
+
serialized_program: str,
|
| 6 |
+
) -> CppExportedProgram: ...
|
| 7 |
+
def serialize_exported_program(
|
| 8 |
+
cpp_exported_program: CppExportedProgram,
|
| 9 |
+
) -> str: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_export/pt2_archive_constants.pyi
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/export/pt2_archive_constants.h
|
| 2 |
+
|
| 3 |
+
ARCHIVE_ROOT_NAME: str = ...
|
| 4 |
+
ARCHIVE_FORMAT_PATH: str = ...
|
| 5 |
+
ARCHIVE_FORMAT_VALUE: str = ...
|
| 6 |
+
ARCHIVE_VERSION_PATH: str = ...
|
| 7 |
+
ARCHIVE_VERSION_VALUE: str = ...
|
| 8 |
+
MODELS_DIR: str = ...
|
| 9 |
+
MODELS_FILENAME_FORMAT: str = ...
|
| 10 |
+
AOTINDUCTOR_DIR: str = ...
|
| 11 |
+
MTIA_DIR: str = ...
|
| 12 |
+
WEIGHTS_DIR: str = ...
|
| 13 |
+
WEIGHTS_CONFIG_FILENAME_FORMAT: str = ...
|
| 14 |
+
WEIGHT_FILENAME_PREFIX: str = ...
|
| 15 |
+
CONSTANTS_DIR: str = ...
|
| 16 |
+
CONSTANTS_CONFIG_FILENAME_FORMAT: str = ...
|
| 17 |
+
TENSOR_CONSTANT_FILENAME_PREFIX: str = ...
|
| 18 |
+
CUSTOM_OBJ_FILENAME_PREFIX: str = ...
|
| 19 |
+
SAMPLE_INPUTS_DIR: str = ...
|
| 20 |
+
SAMPLE_INPUTS_FILENAME_FORMAT: str = ...
|
| 21 |
+
EXECUTORCH_DIR: str = ...
|
| 22 |
+
EXTRA_DIR: str = ...
|
| 23 |
+
MODULE_INFO_PATH: str = ...
|
| 24 |
+
XL_MODEL_WEIGHTS_DIR: str = ...
|
| 25 |
+
XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = ...
|
.venv/lib/python3.10/site-packages/torch/_C/_functionalization.pyi
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch import Tensor
|
| 2 |
+
from torch.types import _bool
|
| 3 |
+
|
| 4 |
+
# Defined in torch/csrc/functionalization/Module.cpp
|
| 5 |
+
|
| 6 |
+
class ViewMeta:
|
| 7 |
+
has_symbolic_inputs: _bool
|
| 8 |
+
|
| 9 |
+
# Returns the list of ViewMeta instances of the given functional tensor.
|
| 10 |
+
#
|
| 11 |
+
# Although we do have python bindings for their types, we won't
|
| 12 |
+
# expose them here, since they should not be used by users.
|
| 13 |
+
def get_view_meta_sequence(tensor: Tensor) -> list[ViewMeta]: ...
|
| 14 |
+
|
| 15 |
+
# Applies the ViewMeta sequence on top of the given base.
|
| 16 |
+
def apply_view_meta_sequence(base: Tensor, sequence: list[ViewMeta]) -> Tensor: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_functions.pyi
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import AnyStr, overload
|
| 2 |
+
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
|
| 5 |
+
class UndefinedGrad:
|
| 6 |
+
def __init__(self) -> None: ...
|
| 7 |
+
def __call__(self, *inputs: Tensor) -> list[Tensor]: ...
|
| 8 |
+
|
| 9 |
+
class DelayedError:
|
| 10 |
+
def __init__(self, msg: AnyStr, num_inputs: int) -> None: ...
|
| 11 |
+
|
| 12 |
+
# __call__ should really be a higher-kinded type:
|
| 13 |
+
# def __call__(self, arg: Tensor) -> Tensor: ...
|
| 14 |
+
# def __call__(self, *args: Tensor * num_inputs) -> Tuple[Tensor * num_inputs]: ...
|
| 15 |
+
|
| 16 |
+
@overload
|
| 17 |
+
def __call__(self, i0: Tensor) -> Tensor: ...
|
| 18 |
+
@overload
|
| 19 |
+
def __call__(self, *args: Tensor) -> tuple[Tensor, ...]: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_functorch.pyi
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from enum import Enum
|
| 3 |
+
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
|
| 6 |
+
# Defined in torch/csrc/functorch/init.cpp
|
| 7 |
+
|
| 8 |
+
def _assert_wrapped_functional(
|
| 9 |
+
input_tensor: Tensor, wrapped_tensor: Tensor
|
| 10 |
+
) -> None: ...
|
| 11 |
+
def _func_decrement_nesting() -> int: ...
|
| 12 |
+
def _func_increment_nesting(reapply_views: bool) -> int: ...
|
| 13 |
+
def _propagate_functional_input_mutation(
|
| 14 |
+
input_tensor: Tensor, wrapped_tensor: Tensor
|
| 15 |
+
) -> None: ...
|
| 16 |
+
def set_inplace_requires_grad_allowed(allowed: bool) -> None: ...
|
| 17 |
+
def get_inplace_requires_grad_allowed() -> bool: ...
|
| 18 |
+
def _set_dynamic_layer_keys_included(included: bool) -> None: ...
|
| 19 |
+
def get_unwrapped(tensor: Tensor) -> Tensor: ...
|
| 20 |
+
def is_batchedtensor(tensor: Tensor) -> bool: ...
|
| 21 |
+
def is_functionaltensor(tensor: Tensor) -> bool: ...
|
| 22 |
+
def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ...
|
| 23 |
+
def is_gradtrackingtensor(tensor: Tensor) -> bool: ...
|
| 24 |
+
def is_legacy_batchedtensor(tensor: Tensor) -> bool: ...
|
| 25 |
+
def maybe_get_bdim(tensor: Tensor) -> int: ...
|
| 26 |
+
def maybe_get_level(tensor: Tensor) -> int: ...
|
| 27 |
+
def maybe_current_level() -> int | None: ...
|
| 28 |
+
def unwrap_if_dead(tensor: Tensor) -> Tensor: ...
|
| 29 |
+
def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ...
|
| 30 |
+
def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ...
|
| 31 |
+
def _unwrap_batched(tensor: Tensor, level: int) -> tuple[Tensor, int | None]: ...
|
| 32 |
+
def current_level() -> int: ...
|
| 33 |
+
def count_jvp_interpreters() -> int: ...
|
| 34 |
+
def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ...
|
| 35 |
+
def _remove_batch_dim(
|
| 36 |
+
tensor: Tensor, level: int, batch_size: int, out_dim: int
|
| 37 |
+
) -> Tensor: ...
|
| 38 |
+
def _maybe_unsafe_set_level(tensor: Tensor, level: int) -> None: ...
|
| 39 |
+
def set_single_level_autograd_function_allowed(allowed: bool) -> None: ...
|
| 40 |
+
def get_single_level_autograd_function_allowed() -> bool: ...
|
| 41 |
+
def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ...
|
| 42 |
+
def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ...
|
| 43 |
+
def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ...
|
| 44 |
+
def _vmap_decrement_nesting() -> int: ...
|
| 45 |
+
def _grad_increment_nesting() -> int: ...
|
| 46 |
+
def _grad_decrement_nesting() -> int: ...
|
| 47 |
+
def _jvp_increment_nesting() -> int: ...
|
| 48 |
+
def _jvp_decrement_nesting() -> int: ...
|
| 49 |
+
|
| 50 |
+
# Defined in aten/src/ATen/functorch/Interpreter.h
|
| 51 |
+
class TransformType(Enum):
|
| 52 |
+
Torch = ...
|
| 53 |
+
Vmap = ...
|
| 54 |
+
Grad = ...
|
| 55 |
+
Jvp = ...
|
| 56 |
+
Functionalize = ...
|
| 57 |
+
|
| 58 |
+
class RandomnessType(Enum):
|
| 59 |
+
Error = ...
|
| 60 |
+
Same = ...
|
| 61 |
+
Different = ...
|
| 62 |
+
|
| 63 |
+
class CInterpreter:
|
| 64 |
+
def key(self) -> TransformType: ...
|
| 65 |
+
def level(self) -> int: ...
|
| 66 |
+
def serialize(self) -> bytes: ...
|
| 67 |
+
@staticmethod
|
| 68 |
+
def deserialize(bytes) -> CInterpreter: ...
|
| 69 |
+
|
| 70 |
+
class CGradInterpreterPtr:
|
| 71 |
+
def __init__(self, interpreter: CInterpreter) -> None: ...
|
| 72 |
+
def lift(self, Tensor) -> Tensor: ...
|
| 73 |
+
def prevGradMode(self) -> bool: ...
|
| 74 |
+
|
| 75 |
+
class CJvpInterpreterPtr:
|
| 76 |
+
def __init__(self, interpreter: CInterpreter) -> None: ...
|
| 77 |
+
def lift(self, Tensor) -> Tensor: ...
|
| 78 |
+
def prevFwdGradMode(self) -> bool: ...
|
| 79 |
+
|
| 80 |
+
class CFunctionalizeInterpreterPtr:
|
| 81 |
+
def __init__(self, interpreter: CInterpreter) -> None: ...
|
| 82 |
+
def key(self) -> TransformType: ...
|
| 83 |
+
def level(self) -> int: ...
|
| 84 |
+
def functionalizeAddBackViews(self) -> bool: ...
|
| 85 |
+
|
| 86 |
+
class CVmapInterpreterPtr:
|
| 87 |
+
def __init__(self, interpreter: CInterpreter) -> None: ...
|
| 88 |
+
def key(self) -> TransformType: ...
|
| 89 |
+
def level(self) -> int: ...
|
| 90 |
+
def batchSize(self) -> int: ...
|
| 91 |
+
def randomness(self) -> RandomnessType: ...
|
| 92 |
+
|
| 93 |
+
class DynamicLayer: ...
|
| 94 |
+
|
| 95 |
+
def get_dynamic_layer_stack_depth() -> int: ...
|
| 96 |
+
def get_interpreter_stack() -> list[CInterpreter]: ...
|
| 97 |
+
def peek_interpreter_stack() -> CInterpreter: ...
|
| 98 |
+
def pop_dynamic_layer_stack() -> DynamicLayer: ...
|
| 99 |
+
def pop_dynamic_layer_stack_and_undo_to_depth(int) -> None: ...
|
| 100 |
+
def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_instruction_counter.pyi
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/instruction_counter/Module.cpp
|
| 2 |
+
|
| 3 |
+
def start() -> int: ...
|
| 4 |
+
def end(id: int) -> int: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_itt.pyi
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/itt.cpp
|
| 2 |
+
def is_available() -> None: ...
|
| 3 |
+
def rangePush(message: str) -> None: ...
|
| 4 |
+
def rangePop() -> None: ...
|
| 5 |
+
def mark(message: str) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_jit_tree_views.pyi
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
|
| 3 |
+
# Defined in torch/csrc/jit/python/python_tree_views.cpp
|
| 4 |
+
|
| 5 |
+
class SourceRange:
|
| 6 |
+
def highlight(self) -> str: ...
|
| 7 |
+
@property
|
| 8 |
+
def start(self) -> int: ...
|
| 9 |
+
@property
|
| 10 |
+
def end(self) -> int: ...
|
| 11 |
+
|
| 12 |
+
class SourceRangeFactory:
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
text: str,
|
| 16 |
+
filename: Any,
|
| 17 |
+
file_lineno: int,
|
| 18 |
+
leading_whitespace_chars: int,
|
| 19 |
+
) -> None: ...
|
| 20 |
+
def make_range(self, line: int, start_col: int, end_col: int) -> SourceRange: ...
|
| 21 |
+
def make_raw_range(self, start: int, end: int) -> SourceRange: ...
|
| 22 |
+
@property
|
| 23 |
+
def source(self) -> str: ...
|
| 24 |
+
|
| 25 |
+
class TreeView:
|
| 26 |
+
def range(self) -> SourceRange: ...
|
| 27 |
+
def dump(self) -> None: ...
|
| 28 |
+
|
| 29 |
+
class Ident(TreeView):
|
| 30 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
|
| 31 |
+
@property
|
| 32 |
+
def name(self) -> str: ...
|
| 33 |
+
|
| 34 |
+
class Param(TreeView):
|
| 35 |
+
def __init__(self, type: Optional[Any], name: Ident, kwarg_only: bool) -> None: ...
|
| 36 |
+
|
| 37 |
+
class Attribute(TreeView):
|
| 38 |
+
def __init__(self, name: Ident, value: Any) -> None: ...
|
| 39 |
+
|
| 40 |
+
# Literals
|
| 41 |
+
def TrueLiteral(range: SourceRange) -> Any: ...
|
| 42 |
+
def FalseLiteral(range: SourceRange) -> Any: ...
|
| 43 |
+
def NoneLiteral(range: SourceRange) -> Any: ...
|
| 44 |
+
|
| 45 |
+
# Tree nodes
|
| 46 |
+
class Stmt(TreeView):
|
| 47 |
+
def __init__(self, thing: TreeView) -> None: ...
|
| 48 |
+
|
| 49 |
+
class Expr(TreeView): ...
|
| 50 |
+
|
| 51 |
+
class Def(TreeView):
|
| 52 |
+
def __init__(self, name: Ident, decl: Any, body: list[Stmt]) -> None: ...
|
| 53 |
+
def decl(self) -> Any: ...
|
| 54 |
+
def name(self) -> Ident: ...
|
| 55 |
+
|
| 56 |
+
class Property(TreeView):
|
| 57 |
+
def __init__(
|
| 58 |
+
self, r: SourceRange, name: Ident, getter: Def, setter: Optional[Def]
|
| 59 |
+
) -> None: ...
|
| 60 |
+
def name(self) -> Ident: ...
|
| 61 |
+
def getter_name(self) -> str: ...
|
| 62 |
+
def setter_name(self) -> Optional[Ident]: ...
|
| 63 |
+
|
| 64 |
+
class ClassDef(TreeView):
|
| 65 |
+
def __init__(
|
| 66 |
+
self, name: Ident, body: list[Stmt], props: list[Property], assigns: list[Any]
|
| 67 |
+
) -> None: ...
|
| 68 |
+
|
| 69 |
+
class Decl(TreeView):
|
| 70 |
+
def __init__(
|
| 71 |
+
self, r: SourceRange, params: list[Param], return_type: Optional[Expr]
|
| 72 |
+
) -> None: ...
|
| 73 |
+
|
| 74 |
+
class Delete(Stmt):
|
| 75 |
+
def __init__(self, range: SourceRange, targets: list[Expr]) -> None: ...
|
| 76 |
+
|
| 77 |
+
class WithItem(Expr):
|
| 78 |
+
def __init__(
|
| 79 |
+
self, range: SourceRange, target: Expr, var: Optional[Any]
|
| 80 |
+
) -> None: ...
|
| 81 |
+
|
| 82 |
+
class Assign(Stmt):
|
| 83 |
+
def __init__(
|
| 84 |
+
self, lhs: list[Expr], rhs: Expr, type: Optional[Expr] = None
|
| 85 |
+
) -> None: ...
|
| 86 |
+
|
| 87 |
+
class AugAssign(Stmt):
|
| 88 |
+
def __init__(self, lhs: Expr, kind_str: str, rhs: Expr) -> None: ...
|
| 89 |
+
|
| 90 |
+
class Return(Stmt):
|
| 91 |
+
def __init__(self, range: SourceRange, value: Optional[Expr]) -> None: ...
|
| 92 |
+
|
| 93 |
+
class Raise(Stmt):
|
| 94 |
+
def __init__(self, range: SourceRange, expr: Expr) -> None: ...
|
| 95 |
+
|
| 96 |
+
class Assert(Stmt):
|
| 97 |
+
def __init__(self, range: SourceRange, test: Expr, msg: Optional[Expr]) -> None: ...
|
| 98 |
+
|
| 99 |
+
class Pass(Stmt):
|
| 100 |
+
def __init__(self, range: SourceRange) -> None: ...
|
| 101 |
+
|
| 102 |
+
class Break(Stmt): ...
|
| 103 |
+
class Continue(Stmt): ...
|
| 104 |
+
|
| 105 |
+
class Dots(Expr, TreeView):
|
| 106 |
+
def __init__(self, range: SourceRange) -> None: ...
|
| 107 |
+
|
| 108 |
+
class If(Stmt):
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
range: SourceRange,
|
| 112 |
+
cond: Expr,
|
| 113 |
+
true_branch: list[Stmt],
|
| 114 |
+
false_branch: list[Stmt],
|
| 115 |
+
) -> None: ...
|
| 116 |
+
|
| 117 |
+
class While(Stmt):
|
| 118 |
+
def __init__(self, range: SourceRange, cond: Expr, body: list[Stmt]) -> None: ...
|
| 119 |
+
|
| 120 |
+
class With(Stmt):
|
| 121 |
+
def __init__(
|
| 122 |
+
self, range: SourceRange, targets: list[WithItem], body: list[Stmt]
|
| 123 |
+
) -> None: ...
|
| 124 |
+
|
| 125 |
+
class For(Stmt):
|
| 126 |
+
def __init__(
|
| 127 |
+
self,
|
| 128 |
+
range: SourceRange,
|
| 129 |
+
targets: list[Expr],
|
| 130 |
+
itrs: list[Expr],
|
| 131 |
+
body: list[Stmt],
|
| 132 |
+
) -> None: ...
|
| 133 |
+
|
| 134 |
+
class ExprStmt(Stmt):
|
| 135 |
+
def __init__(self, expr: Expr) -> None: ...
|
| 136 |
+
|
| 137 |
+
class Var(Expr):
|
| 138 |
+
def __init__(self, name: Ident) -> None: ...
|
| 139 |
+
@property
|
| 140 |
+
def name(self) -> str: ...
|
| 141 |
+
|
| 142 |
+
class BinOp(Expr):
|
| 143 |
+
def __init__(self, kind: str, lhs: Expr, rhs: Expr) -> None: ...
|
| 144 |
+
|
| 145 |
+
class UnaryOp(Expr):
|
| 146 |
+
def __init__(self, range: SourceRange, kind: str, expr: Expr) -> None: ...
|
| 147 |
+
|
| 148 |
+
class Const(Expr):
|
| 149 |
+
def __init__(self, range: SourceRange, value: str) -> None: ...
|
| 150 |
+
|
| 151 |
+
class StringLiteral(Expr):
|
| 152 |
+
def __init__(self, range: SourceRange, value: str) -> None: ...
|
| 153 |
+
|
| 154 |
+
class Apply(Expr):
|
| 155 |
+
def __init__(
|
| 156 |
+
self, expr: Expr, args: list[Expr], kwargs: list[Attribute]
|
| 157 |
+
) -> None: ...
|
| 158 |
+
|
| 159 |
+
class Select(Expr):
|
| 160 |
+
def __init__(self, expr: Expr, field: Ident) -> None: ...
|
| 161 |
+
|
| 162 |
+
class TernaryIf(Expr):
|
| 163 |
+
def __init__(self, cond: Expr, true_expr: Expr, false_expr: Expr) -> None: ...
|
| 164 |
+
|
| 165 |
+
class ListComp(Expr):
|
| 166 |
+
def __init__(
|
| 167 |
+
self, range: SourceRange, elt: Expr, target: Expr, iter: Expr
|
| 168 |
+
) -> None: ...
|
| 169 |
+
|
| 170 |
+
class DictComp(Expr):
|
| 171 |
+
def __init__(
|
| 172 |
+
self, range: SourceRange, key: Expr, value: Expr, target: Expr, iter: Expr
|
| 173 |
+
) -> None: ...
|
| 174 |
+
|
| 175 |
+
class ListLiteral(Expr):
|
| 176 |
+
def __init__(self, range: SourceRange, args: list[Expr]) -> None: ...
|
| 177 |
+
|
| 178 |
+
class TupleLiteral(Expr):
|
| 179 |
+
def __init__(self, range: SourceRange, args: list[Expr]) -> None: ...
|
| 180 |
+
|
| 181 |
+
class DictLiteral(Expr):
|
| 182 |
+
def __init__(
|
| 183 |
+
self, range: SourceRange, keys: list[Expr], values: list[Expr]
|
| 184 |
+
) -> None: ...
|
| 185 |
+
|
| 186 |
+
class Subscript(Expr):
|
| 187 |
+
def __init__(self, base: Expr, subscript_exprs: list[Expr]) -> None: ...
|
| 188 |
+
|
| 189 |
+
class SliceExpr(Expr):
|
| 190 |
+
def __init__(
|
| 191 |
+
self,
|
| 192 |
+
range: SourceRange,
|
| 193 |
+
lower: Optional[Expr],
|
| 194 |
+
upper: Optional[Expr],
|
| 195 |
+
step: Optional[Expr],
|
| 196 |
+
) -> None: ...
|
| 197 |
+
|
| 198 |
+
class Starred(Expr):
|
| 199 |
+
def __init__(self, range: SourceRange, expr: Expr) -> None: ...
|
| 200 |
+
|
| 201 |
+
class EmptyTypeAnnotation(TreeView):
|
| 202 |
+
def __init__(self, range: SourceRange) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_lazy.pyi
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch import Tensor
|
| 2 |
+
|
| 3 |
+
# defined in torch/csrc/lazy/python/init.cpp
|
| 4 |
+
def _mark_step(device: str, devices: list[str], wait: bool) -> None: ...
|
| 5 |
+
def _wait_device_ops(devices: list[str]) -> None: ...
|
| 6 |
+
def _reset_metrics() -> None: ...
|
| 7 |
+
def _counter_names() -> list[str]: ...
|
| 8 |
+
def _counter_value(name: str) -> int: ...
|
| 9 |
+
def _metrics_report() -> str: ...
|
| 10 |
+
def _get_graph_hash(tensors: list[Tensor]) -> str: ...
|
| 11 |
+
def _sync_multi(
|
| 12 |
+
tensors: list[Tensor],
|
| 13 |
+
devices: list[str],
|
| 14 |
+
wait: bool = True,
|
| 15 |
+
sync_ltc_data: bool = True,
|
| 16 |
+
) -> None: ...
|
| 17 |
+
def _get_tensor_id(tensor: Tensor) -> int: ...
|
| 18 |
+
def _get_tensors_text(tensors: list[Tensor]) -> str: ...
|
| 19 |
+
def _get_tensors_dot(tensors: list[Tensor]) -> str: ...
|
| 20 |
+
def _get_tensors_backend(tensors: list[Tensor]) -> str: ...
|
| 21 |
+
def _get_force_fallback() -> str: ...
|
| 22 |
+
def _set_force_fallback(newval: str) -> None: ...
|
| 23 |
+
def _clear_ir_cache() -> None: ...
|
| 24 |
+
def _dump_ir_cache(filename: str) -> None: ...
|
| 25 |
+
def _set_reuse_ir(val: bool) -> None: ...
|
| 26 |
+
def _get_default_device_type() -> str: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_lazy_ts_backend.pyi
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# defined in torch/csrc/lazy/python/init.cpp
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
def _init(): ...
|
| 9 |
+
def _get_tensors_ts_device_data_node(
|
| 10 |
+
tensors: list[Tensor],
|
| 11 |
+
) -> tuple[list[int], list[Any]]: ...
|
| 12 |
+
def _run_cached_graph(hash_str: str, graph_inputs: list[Any]) -> list[Tensor]: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_monitor.pyi
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/monitor/python_init.cpp
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
|
| 8 |
+
class Aggregation(Enum):
|
| 9 |
+
VALUE = ...
|
| 10 |
+
MEAN = ...
|
| 11 |
+
COUNT = ...
|
| 12 |
+
SUM = ...
|
| 13 |
+
MAX = ...
|
| 14 |
+
MIN = ...
|
| 15 |
+
|
| 16 |
+
class Stat:
|
| 17 |
+
name: str
|
| 18 |
+
count: int
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
name: str,
|
| 22 |
+
aggregations: list[Aggregation],
|
| 23 |
+
window_size: int,
|
| 24 |
+
max_samples: int = -1,
|
| 25 |
+
) -> None: ...
|
| 26 |
+
def add(self, v: float) -> None: ...
|
| 27 |
+
def get(self) -> dict[Aggregation, float]: ...
|
| 28 |
+
|
| 29 |
+
class Event:
|
| 30 |
+
name: str
|
| 31 |
+
timestamp: datetime.datetime
|
| 32 |
+
data: dict[str, int | float | bool | str]
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
name: str,
|
| 36 |
+
timestamp: datetime.datetime,
|
| 37 |
+
data: dict[str, int | float | bool | str],
|
| 38 |
+
) -> None: ...
|
| 39 |
+
|
| 40 |
+
def log_event(e: Event) -> None: ...
|
| 41 |
+
|
| 42 |
+
class EventHandlerHandle: ...
|
| 43 |
+
|
| 44 |
+
def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ...
|
| 45 |
+
def unregister_event_handler(handle: EventHandlerHandle) -> None: ...
|
| 46 |
+
|
| 47 |
+
class _WaitCounterTracker:
|
| 48 |
+
def __enter__(self) -> None: ...
|
| 49 |
+
def __exit__(
|
| 50 |
+
self,
|
| 51 |
+
exc_type: type[BaseException] | None = None,
|
| 52 |
+
exc_value: BaseException | None = None,
|
| 53 |
+
traceback: TracebackType | None = None,
|
| 54 |
+
) -> None: ...
|
| 55 |
+
|
| 56 |
+
class _WaitCounter:
|
| 57 |
+
def __init__(self, key: str) -> None: ...
|
| 58 |
+
def guard(self) -> _WaitCounterTracker: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_nn.pyi
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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pyi.in
|
| 2 |
+
# mypy: disable-error-code="type-arg"
|
| 3 |
+
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from typing import Literal, overload
|
| 6 |
+
|
| 7 |
+
from torch import memory_format, Tensor
|
| 8 |
+
from torch.types import _bool, _device, _dtype, _int, _size
|
| 9 |
+
|
| 10 |
+
# Defined in tools/autograd/templates/python_nn_functions.cpp
|
| 11 |
+
|
| 12 |
+
def adaptive_avg_pool2d(input: Tensor, output_size: _int | _size) -> Tensor: ...
|
| 13 |
+
def adaptive_avg_pool3d(input: Tensor, output_size: _int | _size) -> Tensor: ...
|
| 14 |
+
def adaptive_max_pool2d(
|
| 15 |
+
input: Tensor,
|
| 16 |
+
output_size: _int | _size,
|
| 17 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 18 |
+
def adaptive_max_pool3d(
|
| 19 |
+
input: Tensor,
|
| 20 |
+
output_size: _int | _size,
|
| 21 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 22 |
+
def avg_pool2d(
|
| 23 |
+
input: Tensor,
|
| 24 |
+
kernel_size: _int | _size,
|
| 25 |
+
stride: _int | _size | None = None,
|
| 26 |
+
padding: _int | _size = 0,
|
| 27 |
+
ceil_mode: bool = False,
|
| 28 |
+
count_include_pad: bool = True,
|
| 29 |
+
divisor_override: int | None = None,
|
| 30 |
+
) -> Tensor: ...
|
| 31 |
+
def avg_pool3d(
|
| 32 |
+
input: Tensor,
|
| 33 |
+
kernel_size: _int | _size,
|
| 34 |
+
stride: _int | _size | None = None,
|
| 35 |
+
padding: _int | _size = 0,
|
| 36 |
+
ceil_mode: bool = False,
|
| 37 |
+
count_include_pad: bool = True,
|
| 38 |
+
divisor_override: int | None = None,
|
| 39 |
+
) -> Tensor: ...
|
| 40 |
+
def binary_cross_entropy(
|
| 41 |
+
input: Tensor,
|
| 42 |
+
target: Tensor,
|
| 43 |
+
weight: Tensor | None = None,
|
| 44 |
+
reduction: str = ...,
|
| 45 |
+
) -> Tensor: ...
|
| 46 |
+
def col2im(
|
| 47 |
+
input: Tensor,
|
| 48 |
+
output_size: _int | _size,
|
| 49 |
+
kernel_size: _int | _size,
|
| 50 |
+
dilation: _int | _size,
|
| 51 |
+
stride: _int | _size | None = None,
|
| 52 |
+
padding: _int | _size = 0,
|
| 53 |
+
) -> Tensor: ...
|
| 54 |
+
def cross_entropy_loss(
|
| 55 |
+
input: Tensor,
|
| 56 |
+
target: Tensor,
|
| 57 |
+
weight: Tensor | None = None,
|
| 58 |
+
reduction: str = ...,
|
| 59 |
+
ignore_index: int = -100,
|
| 60 |
+
label_smoothing: float = 0.0,
|
| 61 |
+
) -> Tensor: ...
|
| 62 |
+
def elu(
|
| 63 |
+
input: Tensor,
|
| 64 |
+
alpha: float = 1.0,
|
| 65 |
+
scale: float = 1.0,
|
| 66 |
+
input_scale: float = 1.0,
|
| 67 |
+
) -> Tensor: ...
|
| 68 |
+
def elu_(input: Tensor, alpha: float = ...) -> Tensor: ...
|
| 69 |
+
def fractional_max_pool2d(
|
| 70 |
+
input: Tensor,
|
| 71 |
+
kernel_size: _int | _size,
|
| 72 |
+
output_size: _int | _size,
|
| 73 |
+
_random_samples: Tensor,
|
| 74 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 75 |
+
def fractional_max_pool3d(
|
| 76 |
+
input: Tensor,
|
| 77 |
+
kernel_size: _int | _size,
|
| 78 |
+
output_size: _int | _size,
|
| 79 |
+
_random_samples: Tensor,
|
| 80 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 81 |
+
def gelu(input: Tensor, approximate: str = ...) -> Tensor: ...
|
| 82 |
+
def glu(input: Tensor, dim: int = -1) -> Tensor: ...
|
| 83 |
+
def hardsigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: ...
|
| 84 |
+
def hardsigmoid_(input: Tensor) -> Tensor: ...
|
| 85 |
+
def hardswish(input: Tensor) -> Tensor: ...
|
| 86 |
+
def hardswish_(input: Tensor) -> Tensor: ...
|
| 87 |
+
def hardtanh(
|
| 88 |
+
input: Tensor,
|
| 89 |
+
min_val: float = ...,
|
| 90 |
+
max_val: float = ...,
|
| 91 |
+
*,
|
| 92 |
+
out: Tensor | None = None,
|
| 93 |
+
) -> Tensor: ...
|
| 94 |
+
def hardtanh_(
|
| 95 |
+
input: Tensor,
|
| 96 |
+
min_val: float = ...,
|
| 97 |
+
max_val: float = ...,
|
| 98 |
+
) -> Tensor: ...
|
| 99 |
+
def huber_loss(
|
| 100 |
+
input: Tensor,
|
| 101 |
+
target: Tensor,
|
| 102 |
+
reduction: str = ...,
|
| 103 |
+
delta: float = 1.0,
|
| 104 |
+
) -> Tensor: ...
|
| 105 |
+
def im2col(
|
| 106 |
+
input: Tensor,
|
| 107 |
+
kernel_size: _int | _size,
|
| 108 |
+
dilation: _int | _size,
|
| 109 |
+
padding: _int | _size,
|
| 110 |
+
stride: _int | _size,
|
| 111 |
+
) -> Tensor: ...
|
| 112 |
+
def l1_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ...
|
| 113 |
+
def leaky_relu(
|
| 114 |
+
input: Tensor,
|
| 115 |
+
negative_slope: float = ...,
|
| 116 |
+
*,
|
| 117 |
+
out: Tensor | None = None,
|
| 118 |
+
) -> Tensor: ...
|
| 119 |
+
def leaky_relu_(input: Tensor, negative_slope: float = ...) -> Tensor: ...
|
| 120 |
+
def linear(
|
| 121 |
+
input: Tensor,
|
| 122 |
+
weight: Tensor,
|
| 123 |
+
bias: Tensor | None = None,
|
| 124 |
+
) -> Tensor: ...
|
| 125 |
+
def log_sigmoid(input: Tensor) -> Tensor: ...
|
| 126 |
+
def max_pool2d_with_indices(
|
| 127 |
+
input: Tensor,
|
| 128 |
+
kernel_size: _int | _size,
|
| 129 |
+
stride: _int | _size | None = None,
|
| 130 |
+
padding: _int | _size = 0,
|
| 131 |
+
dilation: _int | _size = 1,
|
| 132 |
+
ceil_mode: bool = False,
|
| 133 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 134 |
+
def max_pool3d_with_indices(
|
| 135 |
+
input: Tensor,
|
| 136 |
+
kernel_size: _int | _size,
|
| 137 |
+
stride: _int | _size | None = None,
|
| 138 |
+
padding: _int | _size = 0,
|
| 139 |
+
dilation: _int | _size = 1,
|
| 140 |
+
ceil_mode: bool = False,
|
| 141 |
+
) -> tuple[Tensor, Tensor]: ...
|
| 142 |
+
def max_unpool2d(
|
| 143 |
+
input: Tensor,
|
| 144 |
+
indices: Tensor,
|
| 145 |
+
output_size: Sequence[int] | None,
|
| 146 |
+
) -> Tensor: ...
|
| 147 |
+
def max_unpool3d(
|
| 148 |
+
input: Tensor,
|
| 149 |
+
indices: Tensor,
|
| 150 |
+
output_size: Sequence[int] | None,
|
| 151 |
+
stride: _int | _size,
|
| 152 |
+
padding: _int | _size,
|
| 153 |
+
) -> Tensor: ...
|
| 154 |
+
def mish(input: Tensor) -> Tensor: ...
|
| 155 |
+
def mish_(input: Tensor) -> Tensor: ...
|
| 156 |
+
def mse_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ...
|
| 157 |
+
def multi_margin_loss(
|
| 158 |
+
input: Tensor,
|
| 159 |
+
target: Tensor,
|
| 160 |
+
p: float = 1.0,
|
| 161 |
+
margin: float = 1.0,
|
| 162 |
+
weight: Tensor | None = None,
|
| 163 |
+
reduction: str = ...,
|
| 164 |
+
) -> Tensor: ...
|
| 165 |
+
def multilabel_margin_loss(
|
| 166 |
+
input: Tensor,
|
| 167 |
+
target: Tensor,
|
| 168 |
+
reduction: str = ...,
|
| 169 |
+
) -> Tensor: ...
|
| 170 |
+
def nll_loss_nd(
|
| 171 |
+
input: Tensor,
|
| 172 |
+
target: Tensor,
|
| 173 |
+
weight: Tensor | None = None,
|
| 174 |
+
reduction: str = ...,
|
| 175 |
+
ignore_index: int = -100,
|
| 176 |
+
) -> Tensor: ...
|
| 177 |
+
def one_hot(tensor: Tensor, num_classes: int = ...) -> Tensor: ...
|
| 178 |
+
def pad(
|
| 179 |
+
input: Tensor,
|
| 180 |
+
pad: Sequence[int],
|
| 181 |
+
mode: str = ...,
|
| 182 |
+
value: float | None = None,
|
| 183 |
+
) -> Tensor: ...
|
| 184 |
+
def relu6(input: Tensor) -> Tensor: ...
|
| 185 |
+
def relu6_(input: Tensor) -> Tensor: ...
|
| 186 |
+
def scaled_dot_product_attention(
|
| 187 |
+
query: Tensor,
|
| 188 |
+
key: Tensor,
|
| 189 |
+
value: Tensor,
|
| 190 |
+
attn_mask: Tensor | None = None,
|
| 191 |
+
dropout_p: float = 0.0,
|
| 192 |
+
is_causal: bool = False,
|
| 193 |
+
scale: float | None = None,
|
| 194 |
+
enable_gqa: bool = False,
|
| 195 |
+
) -> Tensor: ...
|
| 196 |
+
def silu(input: Tensor) -> Tensor: ...
|
| 197 |
+
def silu_(input: Tensor) -> Tensor: ...
|
| 198 |
+
def smooth_l1_loss(
|
| 199 |
+
input: Tensor,
|
| 200 |
+
target: Tensor,
|
| 201 |
+
reduction: str = ...,
|
| 202 |
+
beta: float = 1.0,
|
| 203 |
+
) -> Tensor: ...
|
| 204 |
+
def soft_margin_loss(
|
| 205 |
+
input: Tensor,
|
| 206 |
+
target: Tensor,
|
| 207 |
+
reduction: str = ...,
|
| 208 |
+
) -> Tensor: ...
|
| 209 |
+
def softplus(
|
| 210 |
+
input: Tensor,
|
| 211 |
+
beta: float = ...,
|
| 212 |
+
threshold: float = ...,
|
| 213 |
+
) -> Tensor: ...
|
| 214 |
+
def softshrink(input: Tensor, lambd: float = ...) -> Tensor: ...
|
| 215 |
+
|
| 216 |
+
# Defined in aten/src/ATen/native/mkldnn/Linear.cpp
|
| 217 |
+
def mkldnn_linear(input: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: ...
|
| 218 |
+
|
| 219 |
+
# Defined at aten/src/ATen/native/mkldnn/MKLDNNConversions.cpp
|
| 220 |
+
def mkldnn_reorder_conv2d_weight(
|
| 221 |
+
self: Tensor,
|
| 222 |
+
padding: list,
|
| 223 |
+
stride: list,
|
| 224 |
+
dilatation: list,
|
| 225 |
+
groups: int,
|
| 226 |
+
) -> Tensor: ...
|
| 227 |
+
def mkldnn_reorder_conv3d_weight(
|
| 228 |
+
self: Tensor,
|
| 229 |
+
padding: list,
|
| 230 |
+
stride: list,
|
| 231 |
+
dilatation: list,
|
| 232 |
+
groups: int,
|
| 233 |
+
) -> Tensor: ...
|
| 234 |
+
|
| 235 |
+
# Defined in aten/src/ATen/native/mkldnn/Prelu.cpp
|
| 236 |
+
def mkldnn_prelu(input: Tensor, weight: Tensor) -> Tensor: ...
|
| 237 |
+
|
| 238 |
+
# Defined at tools/autograd/templates/python_nn_functions.cpp
|
| 239 |
+
@overload
|
| 240 |
+
def _parse_to(
|
| 241 |
+
device: _device,
|
| 242 |
+
dtype: _dtype,
|
| 243 |
+
non_blocking: _bool,
|
| 244 |
+
copy: _bool,
|
| 245 |
+
*,
|
| 246 |
+
memory_format: memory_format,
|
| 247 |
+
) -> tuple[_device, _dtype, _bool, memory_format]: ...
|
| 248 |
+
@overload
|
| 249 |
+
def _parse_to(
|
| 250 |
+
dtype: _dtype,
|
| 251 |
+
non_blocking: _bool,
|
| 252 |
+
copy: _bool,
|
| 253 |
+
*,
|
| 254 |
+
memory_format: memory_format,
|
| 255 |
+
) -> tuple[_device, _dtype, _bool, memory_format]: ...
|
| 256 |
+
@overload
|
| 257 |
+
def _parse_to(
|
| 258 |
+
tensor: Tensor,
|
| 259 |
+
non_blocking: _bool,
|
| 260 |
+
copy: _bool,
|
| 261 |
+
*,
|
| 262 |
+
memory_format: memory_format,
|
| 263 |
+
) -> tuple[_device, _dtype, _bool, memory_format]: ...
|
| 264 |
+
|
| 265 |
+
# Defined in aten/src/ATen/native/PackedSequence.cpp
|
| 266 |
+
def pad_sequence(
|
| 267 |
+
sequences: list[Tensor] | tuple[Tensor, ...],
|
| 268 |
+
batch_first: bool = False,
|
| 269 |
+
padding_value: float = 0.0,
|
| 270 |
+
padding_side: Literal["left", "right"] = "right",
|
| 271 |
+
) -> Tensor: ...
|
| 272 |
+
|
| 273 |
+
# Upsample functions used by torch.nn.functional.interpolate
|
| 274 |
+
def upsample_nearest1d(
|
| 275 |
+
input: Tensor,
|
| 276 |
+
output_size: Sequence[int] | None,
|
| 277 |
+
scale_factors: Sequence[float] | None,
|
| 278 |
+
) -> Tensor: ...
|
| 279 |
+
def upsample_nearest2d(
|
| 280 |
+
input: Tensor,
|
| 281 |
+
output_size: Sequence[int] | None,
|
| 282 |
+
scale_factors: Sequence[float] | None,
|
| 283 |
+
) -> Tensor: ...
|
| 284 |
+
def upsample_nearest3d(
|
| 285 |
+
input: Tensor,
|
| 286 |
+
output_size: Sequence[int] | None,
|
| 287 |
+
scale_factors: Sequence[float] | None,
|
| 288 |
+
) -> Tensor: ...
|
| 289 |
+
def _upsample_nearest_exact1d(
|
| 290 |
+
input: Tensor,
|
| 291 |
+
output_size: Sequence[int] | None,
|
| 292 |
+
scale_factors: Sequence[float] | None,
|
| 293 |
+
) -> Tensor: ...
|
| 294 |
+
def _upsample_nearest_exact2d(
|
| 295 |
+
input: Tensor,
|
| 296 |
+
output_size: Sequence[int] | None,
|
| 297 |
+
scale_factors: Sequence[float] | None,
|
| 298 |
+
) -> Tensor: ...
|
| 299 |
+
def _upsample_nearest_exact3d(
|
| 300 |
+
input: Tensor,
|
| 301 |
+
output_size: Sequence[int] | None,
|
| 302 |
+
scale_factors: Sequence[float] | None,
|
| 303 |
+
) -> Tensor: ...
|
| 304 |
+
def upsample_linear1d(
|
| 305 |
+
input: Tensor,
|
| 306 |
+
output_size: Sequence[int] | None,
|
| 307 |
+
align_corners: bool,
|
| 308 |
+
scale_factors: Sequence[float] | None,
|
| 309 |
+
) -> Tensor: ...
|
| 310 |
+
def _upsample_bilinear2d_aa(
|
| 311 |
+
input: Tensor,
|
| 312 |
+
output_size: Sequence[int] | None,
|
| 313 |
+
align_corners: bool,
|
| 314 |
+
scale_factors: Sequence[float] | None,
|
| 315 |
+
) -> Tensor: ...
|
| 316 |
+
def upsample_bilinear2d(
|
| 317 |
+
input: Tensor,
|
| 318 |
+
output_size: Sequence[int] | None,
|
| 319 |
+
align_corners: bool,
|
| 320 |
+
scale_factors: Sequence[float] | None,
|
| 321 |
+
) -> Tensor: ...
|
| 322 |
+
def upsample_trilinear3d(
|
| 323 |
+
input: Tensor,
|
| 324 |
+
output_size: Sequence[int] | None,
|
| 325 |
+
align_corners: bool,
|
| 326 |
+
scale_factors: Sequence[float] | None,
|
| 327 |
+
) -> Tensor: ...
|
| 328 |
+
def _upsample_bicubic2d_aa(
|
| 329 |
+
input: Tensor,
|
| 330 |
+
output_size: Sequence[int] | None,
|
| 331 |
+
align_corners: bool,
|
| 332 |
+
scale_factors: Sequence[float] | None,
|
| 333 |
+
) -> Tensor: ...
|
| 334 |
+
def upsample_bicubic2d(
|
| 335 |
+
input: Tensor,
|
| 336 |
+
output_size: Sequence[int] | None,
|
| 337 |
+
align_corners: bool,
|
| 338 |
+
scale_factors: Sequence[float] | None,
|
| 339 |
+
) -> Tensor: ...
|
| 340 |
+
def flatten_dense_tensors(tensors: list[Tensor]) -> Tensor: ...
|
| 341 |
+
def unflatten_dense_tensors(flat: Tensor, tensors: list[Tensor]) -> list[Tensor]: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_nvtx.pyi
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# Defined in torch/csrc/cuda/shared/nvtx.cpp
|
| 3 |
+
def rangePushA(message: str) -> int: ...
|
| 4 |
+
def rangePop() -> int: ...
|
| 5 |
+
def rangeStartA(message: str) -> int: ...
|
| 6 |
+
def rangeEnd(int) -> None: ...
|
| 7 |
+
def markA(message: str) -> None: ...
|
| 8 |
+
def deviceRangeStart(message: str, stream: int) -> object: ...
|
| 9 |
+
def deviceRangeEnd(range_handle: object, stream: int) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_onnx.pyi
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/onnx/init.cpp
|
| 2 |
+
|
| 3 |
+
from enum import Enum
|
| 4 |
+
|
| 5 |
+
PRODUCER_VERSION: str
|
| 6 |
+
|
| 7 |
+
class TensorProtoDataType(Enum):
|
| 8 |
+
UNDEFINED = ...
|
| 9 |
+
FLOAT = ...
|
| 10 |
+
UINT8 = ...
|
| 11 |
+
INT8 = ...
|
| 12 |
+
UINT16 = ...
|
| 13 |
+
INT16 = ...
|
| 14 |
+
INT32 = ...
|
| 15 |
+
INT64 = ...
|
| 16 |
+
STRING = ...
|
| 17 |
+
BOOL = ...
|
| 18 |
+
FLOAT16 = ...
|
| 19 |
+
DOUBLE = ...
|
| 20 |
+
UINT32 = ...
|
| 21 |
+
UINT64 = ...
|
| 22 |
+
COMPLEX64 = ...
|
| 23 |
+
COMPLEX128 = ...
|
| 24 |
+
BFLOAT16 = ...
|
| 25 |
+
FLOAT8E5M2 = ...
|
| 26 |
+
FLOAT8E4M3FN = ...
|
| 27 |
+
FLOAT8E5M2FNUZ = ...
|
| 28 |
+
FLOAT8E4M3FNUZ = ...
|
| 29 |
+
|
| 30 |
+
class OperatorExportTypes(Enum):
|
| 31 |
+
ONNX = ...
|
| 32 |
+
ONNX_ATEN = ...
|
| 33 |
+
ONNX_ATEN_FALLBACK = ...
|
| 34 |
+
ONNX_FALLTHROUGH = ...
|
| 35 |
+
|
| 36 |
+
class TrainingMode(Enum):
|
| 37 |
+
EVAL = ...
|
| 38 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
from typing import Literal, TypeAlias
|
| 3 |
+
|
| 4 |
+
from torch._C import device, dtype, layout
|
| 5 |
+
|
| 6 |
+
# defined in torch/csrc/profiler/python/init.cpp
|
| 7 |
+
|
| 8 |
+
class RecordScope(Enum):
|
| 9 |
+
FUNCTION = ...
|
| 10 |
+
BACKWARD_FUNCTION = ...
|
| 11 |
+
TORCHSCRIPT_FUNCTION = ...
|
| 12 |
+
KERNEL_FUNCTION_DTYPE = ...
|
| 13 |
+
CUSTOM_CLASS = ...
|
| 14 |
+
BUILD_FEATURE = ...
|
| 15 |
+
LITE_INTERPRETER = ...
|
| 16 |
+
USER_SCOPE = ...
|
| 17 |
+
STATIC_RUNTIME_OP = ...
|
| 18 |
+
STATIC_RUNTIME_MODEL = ...
|
| 19 |
+
|
| 20 |
+
class ProfilerState(Enum):
|
| 21 |
+
Disabled = ...
|
| 22 |
+
CPU = ...
|
| 23 |
+
CUDA = ...
|
| 24 |
+
NVTX = ...
|
| 25 |
+
ITT = ...
|
| 26 |
+
PRIVATEUSE1 = ...
|
| 27 |
+
KINETO = ...
|
| 28 |
+
KINETO_GPU_FALLBACK = ...
|
| 29 |
+
KINETO_PRIVATEUSE1_FALLBACK = ...
|
| 30 |
+
|
| 31 |
+
class ActiveProfilerType(Enum):
|
| 32 |
+
NONE = ...
|
| 33 |
+
LEGACY = ...
|
| 34 |
+
KINETO = ...
|
| 35 |
+
NVTX = ...
|
| 36 |
+
ITT = ...
|
| 37 |
+
PRIVATEUSE1 = ...
|
| 38 |
+
|
| 39 |
+
class ProfilerActivity(Enum):
|
| 40 |
+
CPU = ...
|
| 41 |
+
CUDA = ...
|
| 42 |
+
XPU = ...
|
| 43 |
+
MTIA = ...
|
| 44 |
+
HPU = ...
|
| 45 |
+
PrivateUse1 = ...
|
| 46 |
+
|
| 47 |
+
class _EventType(Enum):
|
| 48 |
+
TorchOp = ...
|
| 49 |
+
Backend = ...
|
| 50 |
+
Allocation = ...
|
| 51 |
+
OutOfMemory = ...
|
| 52 |
+
PyCall = ...
|
| 53 |
+
PyCCall = ...
|
| 54 |
+
Kineto = ...
|
| 55 |
+
|
| 56 |
+
class _ExperimentalConfig:
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
profiler_metrics: list[str] = ...,
|
| 60 |
+
profiler_measure_per_kernel: bool = ...,
|
| 61 |
+
verbose: bool = ...,
|
| 62 |
+
performance_events: list[str] = ...,
|
| 63 |
+
enable_cuda_sync_events: bool = ...,
|
| 64 |
+
profile_all_threads: bool = ...,
|
| 65 |
+
) -> None: ...
|
| 66 |
+
|
| 67 |
+
class ProfilerConfig:
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
state: ProfilerState,
|
| 71 |
+
report_input_shapes: bool,
|
| 72 |
+
profile_memory: bool,
|
| 73 |
+
with_stack: bool,
|
| 74 |
+
with_flops: bool,
|
| 75 |
+
with_modules: bool,
|
| 76 |
+
experimental_config: _ExperimentalConfig,
|
| 77 |
+
trace_id: str | None = None,
|
| 78 |
+
) -> None: ...
|
| 79 |
+
|
| 80 |
+
class _ProfilerEvent:
|
| 81 |
+
start_tid: int
|
| 82 |
+
start_time_ns: int
|
| 83 |
+
children: list[_ProfilerEvent]
|
| 84 |
+
|
| 85 |
+
# TODO(robieta): remove in favor of `self.typed`
|
| 86 |
+
extra_fields: (
|
| 87 |
+
_ExtraFields_TorchOp
|
| 88 |
+
| _ExtraFields_Backend
|
| 89 |
+
| _ExtraFields_Allocation
|
| 90 |
+
| _ExtraFields_OutOfMemory
|
| 91 |
+
| _ExtraFields_PyCall
|
| 92 |
+
| _ExtraFields_PyCCall
|
| 93 |
+
| _ExtraFields_Kineto
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def typed(
|
| 98 |
+
self,
|
| 99 |
+
) -> (
|
| 100 |
+
tuple[Literal[_EventType.TorchOp], _ExtraFields_TorchOp]
|
| 101 |
+
| tuple[Literal[_EventType.Backend], _ExtraFields_Backend]
|
| 102 |
+
| tuple[Literal[_EventType.Allocation], _ExtraFields_Allocation]
|
| 103 |
+
| tuple[Literal[_EventType.OutOfMemory], _ExtraFields_OutOfMemory]
|
| 104 |
+
| tuple[Literal[_EventType.PyCall], _ExtraFields_PyCall]
|
| 105 |
+
| tuple[Literal[_EventType.PyCCall], _ExtraFields_PyCCall]
|
| 106 |
+
| tuple[Literal[_EventType.Kineto], _ExtraFields_Kineto]
|
| 107 |
+
): ...
|
| 108 |
+
@property
|
| 109 |
+
def name(self) -> str: ...
|
| 110 |
+
@property
|
| 111 |
+
def tag(self) -> _EventType: ...
|
| 112 |
+
@property
|
| 113 |
+
def id(self) -> int: ...
|
| 114 |
+
@property
|
| 115 |
+
def parent(self) -> _ProfilerEvent | None: ...
|
| 116 |
+
@property
|
| 117 |
+
def correlation_id(self) -> int: ...
|
| 118 |
+
@property
|
| 119 |
+
def end_time_ns(self) -> int: ...
|
| 120 |
+
@property
|
| 121 |
+
def duration_time_ns(self) -> int: ...
|
| 122 |
+
|
| 123 |
+
class _TensorMetadata:
|
| 124 |
+
impl_ptr: int | None
|
| 125 |
+
storage_data_ptr: int | None
|
| 126 |
+
id: int | None
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def allocation_id(self) -> int | None: ...
|
| 130 |
+
@property
|
| 131 |
+
def layout(self) -> layout: ...
|
| 132 |
+
@property
|
| 133 |
+
def device(self) -> device: ...
|
| 134 |
+
@property
|
| 135 |
+
def dtype(self) -> dtype: ...
|
| 136 |
+
@property
|
| 137 |
+
def sizes(self) -> list[int]: ...
|
| 138 |
+
@property
|
| 139 |
+
def strides(self) -> list[int]: ...
|
| 140 |
+
|
| 141 |
+
Scalar: TypeAlias = int | float | bool | complex
|
| 142 |
+
Input: TypeAlias = _TensorMetadata | list[_TensorMetadata] | Scalar | None
|
| 143 |
+
|
| 144 |
+
class _ExtraFields_TorchOp:
|
| 145 |
+
name: str
|
| 146 |
+
sequence_number: int
|
| 147 |
+
allow_tf32_cublas: bool
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def inputs(self) -> list[Input]: ...
|
| 151 |
+
@property
|
| 152 |
+
def scope(self) -> RecordScope: ...
|
| 153 |
+
|
| 154 |
+
class _ExtraFields_Backend: ...
|
| 155 |
+
|
| 156 |
+
class _ExtraFields_Allocation:
|
| 157 |
+
ptr: int
|
| 158 |
+
id: int | None
|
| 159 |
+
alloc_size: int
|
| 160 |
+
total_allocated: int
|
| 161 |
+
total_reserved: int
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def allocation_id(self) -> int | None: ...
|
| 165 |
+
@property
|
| 166 |
+
def device(self) -> device: ...
|
| 167 |
+
|
| 168 |
+
class _ExtraFields_OutOfMemory: ...
|
| 169 |
+
|
| 170 |
+
class _PyFrameState:
|
| 171 |
+
line_number: int
|
| 172 |
+
function_name: str
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def file_name(self) -> str: ...
|
| 176 |
+
|
| 177 |
+
class _NNModuleInfo:
|
| 178 |
+
@property
|
| 179 |
+
def self_ptr(self) -> int: ...
|
| 180 |
+
@property
|
| 181 |
+
def cls_ptr(self) -> int: ...
|
| 182 |
+
@property
|
| 183 |
+
def cls_name(self) -> str: ...
|
| 184 |
+
@property
|
| 185 |
+
def parameters(
|
| 186 |
+
self,
|
| 187 |
+
) -> list[tuple[str, _TensorMetadata, _TensorMetadata | None]]: ...
|
| 188 |
+
|
| 189 |
+
class _OptimizerInfo:
|
| 190 |
+
@property
|
| 191 |
+
def parameters(
|
| 192 |
+
self,
|
| 193 |
+
) -> list[
|
| 194 |
+
tuple[
|
| 195 |
+
# Parameter
|
| 196 |
+
_TensorMetadata,
|
| 197 |
+
#
|
| 198 |
+
# Gradient (if present during optimizer.step())
|
| 199 |
+
_TensorMetadata | None,
|
| 200 |
+
#
|
| 201 |
+
# Optimizer state for Parameter as (name, tensor) pairs
|
| 202 |
+
list[tuple[str, _TensorMetadata]],
|
| 203 |
+
]
|
| 204 |
+
]: ...
|
| 205 |
+
|
| 206 |
+
class _ExtraFields_PyCCall:
|
| 207 |
+
@property
|
| 208 |
+
def caller(self) -> _PyFrameState: ...
|
| 209 |
+
|
| 210 |
+
class _ExtraFields_PyCall:
|
| 211 |
+
@property
|
| 212 |
+
def callsite(self) -> _PyFrameState: ...
|
| 213 |
+
@property
|
| 214 |
+
def caller(self) -> _PyFrameState: ...
|
| 215 |
+
@property
|
| 216 |
+
def module(self) -> _NNModuleInfo | None: ...
|
| 217 |
+
@property
|
| 218 |
+
def optimizer(self) -> _OptimizerInfo | None: ...
|
| 219 |
+
|
| 220 |
+
class _ExtraFields_Kineto: ...
|
| 221 |
+
|
| 222 |
+
def _add_execution_trace_observer(output_file_path: str) -> bool: ...
|
| 223 |
+
def _remove_execution_trace_observer() -> None: ...
|
| 224 |
+
def _enable_execution_trace_observer() -> None: ...
|
| 225 |
+
def _disable_execution_trace_observer() -> None: ...
|
| 226 |
+
def _set_record_concrete_inputs_enabled_val(val: bool) -> None: ...
|
| 227 |
+
def _set_fwd_bwd_enabled_val(val: bool) -> None: ...
|
| 228 |
+
def _set_cuda_sync_enabled_val(val: bool) -> None: ...
|
| 229 |
+
|
| 230 |
+
class CapturedTraceback: ...
|
| 231 |
+
|
| 232 |
+
def gather_traceback(python: bool, script: bool, cpp: bool) -> CapturedTraceback: ...
|
| 233 |
+
|
| 234 |
+
# The Dict has name, filename, line
|
| 235 |
+
def symbolize_tracebacks(
|
| 236 |
+
to_symbolize: list[CapturedTraceback],
|
| 237 |
+
) -> list[list[dict[str, str]]]: ...
|
| 238 |
+
|
| 239 |
+
class _RecordFunctionFast:
|
| 240 |
+
def __init__(
|
| 241 |
+
self,
|
| 242 |
+
name: str,
|
| 243 |
+
input_values: list | tuple | None = None,
|
| 244 |
+
keyword_values: dict | None = None,
|
| 245 |
+
) -> None: ...
|
| 246 |
+
def __enter__(self) -> None: ...
|
| 247 |
+
def __exit__(self, *exc_info: object) -> None: ...
|
.venv/lib/python3.10/site-packages/torch/_C/_verbose.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defined in torch/csrc/utils/verbose.cpp
|
| 2 |
+
def mkl_set_verbose(enable: int) -> int: ...
|
| 3 |
+
def mkldnn_set_verbose(level: int) -> int: ...
|
.venv/lib/python3.10/site-packages/torch/_custom_op/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.10/site-packages/torch/_custom_op/autograd.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from collections import namedtuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# NOTE [CustomOp autograd kernel indirection]
|
| 10 |
+
# We register `inner` as the autograd kernel for this custom_op.
|
| 11 |
+
# `inner` either calls the autograd formula registered by the user,
|
| 12 |
+
# or goes into an `autograd_not_implemented` kernel.
|
| 13 |
+
#
|
| 14 |
+
# The reason why this indirection exists is
|
| 15 |
+
# so that we can swap out the autograd kernel (the PyTorch dispatcher
|
| 16 |
+
# doesn't actually allow us to do this). By default, we want
|
| 17 |
+
# the `autograd_not_implemented` behavior, but then the user may come
|
| 18 |
+
# and register something that is actually a backward formula
|
| 19 |
+
def autograd_kernel_indirection(custom_op):
|
| 20 |
+
autograd_fallback = autograd_not_implemented(custom_op)
|
| 21 |
+
|
| 22 |
+
def inner(*args, **kwargs):
|
| 23 |
+
if custom_op._has_impl("autograd"):
|
| 24 |
+
kernel = custom_op._get_impl("autograd").func
|
| 25 |
+
return kernel(*args, **kwargs)
|
| 26 |
+
# As explained in NOTE ["backward", "save_for_backward", and "autograd"],
|
| 27 |
+
# after the user gives us "backward" and "save_for_backward", we generate
|
| 28 |
+
# the "autograd" impl. If the user only provided one, then we tell
|
| 29 |
+
# the user they've done something wrong.
|
| 30 |
+
if custom_op._has_impl("save_for_backward") or custom_op._has_impl("backward"):
|
| 31 |
+
missing = (
|
| 32 |
+
"save_for_backward" if custom_op._has_impl("backward") else "backward"
|
| 33 |
+
)
|
| 34 |
+
found = "save_for_backward" if missing == "backward" else "backward"
|
| 35 |
+
loc = custom_op._get_impl(found).location
|
| 36 |
+
raise RuntimeError(
|
| 37 |
+
f"We found a '{found}' registration for {custom_op} at "
|
| 38 |
+
f"{loc} but were unable to find a '{missing}' registration. "
|
| 39 |
+
f"To use the CustomOp API to register a backward formula, "
|
| 40 |
+
f"please provide us both a backward function and a "
|
| 41 |
+
f"'save for backward' function via `impl_backward` and "
|
| 42 |
+
f"`impl_save_for_backward` respectively."
|
| 43 |
+
)
|
| 44 |
+
return autograd_fallback(*args, **kwargs)
|
| 45 |
+
|
| 46 |
+
return inner
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# TODO(#101191): Use the actual C++ autograd not implemented fallback,
|
| 50 |
+
# or change the default autograd fallback to the autograd not implemented fallback.
|
| 51 |
+
def autograd_not_implemented(custom_op):
|
| 52 |
+
def kernel(*args, **kwargs):
|
| 53 |
+
if torch.is_grad_enabled() and pytree.tree_any(
|
| 54 |
+
lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs)
|
| 55 |
+
):
|
| 56 |
+
raise RuntimeError("Autograd has not been implemented for operator")
|
| 57 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 58 |
+
return custom_op(*args, **kwargs)
|
| 59 |
+
|
| 60 |
+
return kernel
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def mark_non_differentiable(ctx, output, output_differentiability):
|
| 64 |
+
# Output types are restricted to be:
|
| 65 |
+
# - Tensor
|
| 66 |
+
# - Tensor[]
|
| 67 |
+
# - int, bool, Scalar, float
|
| 68 |
+
# See _check_can_register_backward
|
| 69 |
+
if output_differentiability is not None:
|
| 70 |
+
if not isinstance(output, tuple):
|
| 71 |
+
tuple_output = (output,)
|
| 72 |
+
else:
|
| 73 |
+
tuple_output = output # type: ignore[assignment]
|
| 74 |
+
if len(output_differentiability) != len(tuple_output):
|
| 75 |
+
raise AssertionError(
|
| 76 |
+
f"output_differentiability length {len(output_differentiability)} "
|
| 77 |
+
f"!= output length {len(tuple_output)}"
|
| 78 |
+
)
|
| 79 |
+
non_differentiable_tensors = []
|
| 80 |
+
for idx, (differentiable, out) in enumerate(
|
| 81 |
+
zip(output_differentiability, tuple_output)
|
| 82 |
+
):
|
| 83 |
+
if isinstance(out, torch.Tensor):
|
| 84 |
+
if not differentiable:
|
| 85 |
+
non_differentiable_tensors.append(out)
|
| 86 |
+
continue
|
| 87 |
+
if isinstance(out, list):
|
| 88 |
+
if not differentiable:
|
| 89 |
+
non_differentiable_tensors.extend(out)
|
| 90 |
+
continue
|
| 91 |
+
if differentiable:
|
| 92 |
+
raise RuntimeError(
|
| 93 |
+
f"With output_differentiability={output_differentiability}. "
|
| 94 |
+
f"At idx {idx}, we received an object of type {type(out)} that "
|
| 95 |
+
f"is not a Tensor, so it cannot have be marked as differentiable in "
|
| 96 |
+
f"output_differentiability."
|
| 97 |
+
)
|
| 98 |
+
if non_differentiable_tensors:
|
| 99 |
+
ctx.mark_non_differentiable(*non_differentiable_tensors)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def construct_autograd_kernel(
|
| 103 |
+
schema,
|
| 104 |
+
output_differentiability,
|
| 105 |
+
custom_op,
|
| 106 |
+
op_overload,
|
| 107 |
+
save_for_backward_fn,
|
| 108 |
+
backward_fn,
|
| 109 |
+
):
|
| 110 |
+
def apply(*args):
|
| 111 |
+
flat_args, spec = pytree.tree_flatten(args)
|
| 112 |
+
out_spec = None
|
| 113 |
+
|
| 114 |
+
def forward(ctx, *flat_args):
|
| 115 |
+
ctx.set_materialize_grads(True)
|
| 116 |
+
args = pytree.tree_unflatten(list(flat_args), spec)
|
| 117 |
+
with torch._C._AutoDispatchBelowAutograd():
|
| 118 |
+
output = op_overload(*args)
|
| 119 |
+
|
| 120 |
+
# We use the info about args to give better error messages in backward
|
| 121 |
+
args_info = namedtuple_args(schema, pytree.tree_map(type, args))
|
| 122 |
+
|
| 123 |
+
save_for_backward_fn_inputs = namedtuple_args(schema, args)
|
| 124 |
+
to_save = save_for_backward_fn(save_for_backward_fn_inputs, output)
|
| 125 |
+
|
| 126 |
+
save_pytree_for_backward(ctx, (to_save, args_info))
|
| 127 |
+
mark_non_differentiable(ctx, output, output_differentiability)
|
| 128 |
+
|
| 129 |
+
nonlocal out_spec
|
| 130 |
+
flat_output, out_spec = pytree.tree_flatten(output)
|
| 131 |
+
return tuple(flat_output)
|
| 132 |
+
|
| 133 |
+
def backward(ctx, *flat_grad_output):
|
| 134 |
+
if out_spec is None:
|
| 135 |
+
raise AssertionError("out_spec is unexpectedly None")
|
| 136 |
+
grads = pytree.tree_unflatten(list(flat_grad_output), out_spec)
|
| 137 |
+
saved, args_info = unpack_saved(ctx)
|
| 138 |
+
# There is nothing on the ctx object for now, it is just there so
|
| 139 |
+
# that we can add additional things in the future.
|
| 140 |
+
inner_ctx = object()
|
| 141 |
+
if not isinstance(grads, tuple):
|
| 142 |
+
grads = (grads,)
|
| 143 |
+
grad_inputs_dict = backward_fn(inner_ctx, saved, *grads)
|
| 144 |
+
|
| 145 |
+
# Massage the grad_inputs_dict to a form acceptable by
|
| 146 |
+
# autograd.Function.
|
| 147 |
+
validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info)
|
| 148 |
+
return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info)
|
| 149 |
+
|
| 150 |
+
generated_cls = gen_autograd_function(
|
| 151 |
+
custom_op._opname + "_customop", forward, backward
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
flat_output = generated_cls.apply(*flat_args)
|
| 155 |
+
if out_spec is None:
|
| 156 |
+
raise AssertionError("out_spec is unexpectedly None")
|
| 157 |
+
return pytree.tree_unflatten(list(flat_output), out_spec)
|
| 158 |
+
|
| 159 |
+
return apply
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def gen_autograd_function(name, forward, backward):
|
| 163 |
+
generated_cls = type(
|
| 164 |
+
name,
|
| 165 |
+
(torch.autograd.Function,),
|
| 166 |
+
{
|
| 167 |
+
"forward": staticmethod(forward),
|
| 168 |
+
"backward": staticmethod(backward),
|
| 169 |
+
},
|
| 170 |
+
)
|
| 171 |
+
return generated_cls
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@functools.lru_cache
|
| 175 |
+
def namedtuple_args_cls(schema):
|
| 176 |
+
attribs = [arg.name for arg in schema.arguments.flat_all]
|
| 177 |
+
name = str(schema.name) + "_args"
|
| 178 |
+
# mypy doesn't support dynamic namedtuple name
|
| 179 |
+
tuple_cls = namedtuple(name, attribs) # type: ignore[misc]
|
| 180 |
+
return tuple_cls
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def namedtuple_args(schema, args):
|
| 184 |
+
if not isinstance(args, tuple):
|
| 185 |
+
raise AssertionError(f"expected tuple, got {type(args)}")
|
| 186 |
+
tuple_cls = namedtuple_args_cls(schema)
|
| 187 |
+
return tuple_cls(*args)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info):
|
| 191 |
+
def error(what):
|
| 192 |
+
backward = forward_op._get_impl("backward")
|
| 193 |
+
raise RuntimeError(
|
| 194 |
+
f"In the backward function defined for {forward_op} at "
|
| 195 |
+
f"{backward.location} using the CustomOp API, {what}"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
if not isinstance(grad_inputs_dict, dict):
|
| 199 |
+
error(
|
| 200 |
+
f"expected the output of the backward function to be a dict but "
|
| 201 |
+
f"got {type(grad_inputs_dict)}"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
expected_keys = {
|
| 205 |
+
arg.name
|
| 206 |
+
for arg in forward_op._schema.arguments.flat_all
|
| 207 |
+
if arg.type.is_tensor_like()
|
| 208 |
+
}
|
| 209 |
+
actual_keys = grad_inputs_dict.keys()
|
| 210 |
+
if expected_keys != actual_keys:
|
| 211 |
+
error(
|
| 212 |
+
f"expected the returned grad_input dict to have keys "
|
| 213 |
+
f"{expected_keys} but got {actual_keys}. The backward "
|
| 214 |
+
f"function must return a gradient (can be None) for each arg "
|
| 215 |
+
f"to the CustomOp that may be a Tensor or Sequence[Tensor]. "
|
| 216 |
+
f"Args declared to be non-Tensor-like types should not appear "
|
| 217 |
+
f"in the grad_input dict"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
for name, grad in grad_inputs_dict.items():
|
| 221 |
+
arg_info = getattr(args_info, name)
|
| 222 |
+
|
| 223 |
+
if isinstance(arg_info, list):
|
| 224 |
+
if not isinstance(grad, (tuple, list)):
|
| 225 |
+
error(
|
| 226 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 227 |
+
f"hold a list of gradients but got object of type "
|
| 228 |
+
f"{type(grad)}."
|
| 229 |
+
)
|
| 230 |
+
if len(grad) != len(arg_info):
|
| 231 |
+
error(
|
| 232 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 233 |
+
f"hold a list of {len(arg_info)} gradients but got "
|
| 234 |
+
f"{len(grad)}"
|
| 235 |
+
)
|
| 236 |
+
for idx, (g, info) in enumerate(zip(grad, arg_info)):
|
| 237 |
+
if g is None:
|
| 238 |
+
continue
|
| 239 |
+
if not isinstance(g, torch.Tensor):
|
| 240 |
+
error(
|
| 241 |
+
f"for input '{name}' expected the grad_input dict to "
|
| 242 |
+
f"hold a list of None or Tensor gradients but got "
|
| 243 |
+
f"object of {type(g)} at index {idx}"
|
| 244 |
+
)
|
| 245 |
+
if not issubclass(info, torch.Tensor):
|
| 246 |
+
error(
|
| 247 |
+
f"for input '{name}', got a Tensor as the gradient "
|
| 248 |
+
f"for the {idx}-th value but expected None because "
|
| 249 |
+
f"the {idx}-th value was not a Tensor (it was "
|
| 250 |
+
f"type {arg_info}"
|
| 251 |
+
)
|
| 252 |
+
continue
|
| 253 |
+
|
| 254 |
+
if grad is None:
|
| 255 |
+
continue
|
| 256 |
+
if not isinstance(grad, torch.Tensor):
|
| 257 |
+
error(
|
| 258 |
+
f"got object of type {type(grad)} as the gradient for input "
|
| 259 |
+
f"'{name}', "
|
| 260 |
+
f"but expected the gradient to be either None or a Tensor"
|
| 261 |
+
)
|
| 262 |
+
if not issubclass(arg_info, torch.Tensor):
|
| 263 |
+
error(
|
| 264 |
+
f"got a Tensor as the gradient for input '{name}' but "
|
| 265 |
+
f"expected None as the gradient because input '{name}' "
|
| 266 |
+
f"was not a Tensor (it was type {arg_info})."
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info):
|
| 271 |
+
result = []
|
| 272 |
+
for name, arg_info in args_info._asdict().items():
|
| 273 |
+
if name not in grad_inputs_dict:
|
| 274 |
+
result.append(pytree.tree_map(lambda x: None, arg_info))
|
| 275 |
+
continue
|
| 276 |
+
result.append(grad_inputs_dict[name])
|
| 277 |
+
return tuple(pytree.tree_leaves(result))
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it.
|
| 281 |
+
# autograd.Function prefers that users use ctx.save_for_backward to
|
| 282 |
+
# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the
|
| 283 |
+
# ctx object.
|
| 284 |
+
def save_pytree_for_backward(ctx, stuff):
|
| 285 |
+
flat_stuff, spec = pytree.tree_flatten(stuff)
|
| 286 |
+
num_elts = len(flat_stuff)
|
| 287 |
+
tensor_idxs = [
|
| 288 |
+
idx for idx, thing in enumerate(flat_stuff) if isinstance(thing, torch.Tensor)
|
| 289 |
+
]
|
| 290 |
+
non_tensor_idxs = [
|
| 291 |
+
idx
|
| 292 |
+
for idx, thing in enumerate(flat_stuff)
|
| 293 |
+
if not isinstance(thing, torch.Tensor)
|
| 294 |
+
]
|
| 295 |
+
tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)]
|
| 296 |
+
non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)]
|
| 297 |
+
|
| 298 |
+
ctx.spec = spec
|
| 299 |
+
ctx.num_elts = num_elts
|
| 300 |
+
ctx.save_for_backward(*tensors)
|
| 301 |
+
ctx.tensor_idxs = tensor_idxs
|
| 302 |
+
ctx.saved_non_tensors = non_tensors
|
| 303 |
+
ctx.non_tensor_idxs = non_tensor_idxs
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# Inverse operation to save_pytree_for_backward
|
| 307 |
+
def unpack_saved(ctx):
|
| 308 |
+
flat_stuff = [None] * ctx.num_elts
|
| 309 |
+
for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs):
|
| 310 |
+
flat_stuff[idx] = tensor
|
| 311 |
+
for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs):
|
| 312 |
+
flat_stuff[idx] = non_tensor
|
| 313 |
+
stuff = pytree.tree_unflatten(flat_stuff, ctx.spec)
|
| 314 |
+
return stuff
|
.venv/lib/python3.10/site-packages/torch/_custom_op/impl.py
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import dataclasses
|
| 3 |
+
import functools
|
| 4 |
+
import inspect
|
| 5 |
+
import sys
|
| 6 |
+
import typing
|
| 7 |
+
import warnings
|
| 8 |
+
import weakref
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch._C as _C
|
| 12 |
+
import torch._library.infer_schema
|
| 13 |
+
import torch.library as library
|
| 14 |
+
from torch._library.infer_schema import infer_schema
|
| 15 |
+
from torch.library import get_ctx
|
| 16 |
+
from torchgen.model import (
|
| 17 |
+
BaseTy,
|
| 18 |
+
BaseType,
|
| 19 |
+
FunctionSchema,
|
| 20 |
+
ListType,
|
| 21 |
+
OperatorName,
|
| 22 |
+
SchemaKind,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
from .autograd import autograd_kernel_indirection, construct_autograd_kernel
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library.
|
| 30 |
+
Please use those APIs instead.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
__all__ = ["custom_op", "CustomOp", "get_ctx"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
SUPPORTED_DEVICE_TYPE_TO_KEY = {
|
| 37 |
+
"cpu": "CPU",
|
| 38 |
+
"cuda": "CUDA",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
# We will not let users register CustomOps with anything that could look like
|
| 42 |
+
# PyTorch internals to avoid confusion.
|
| 43 |
+
RESERVED_NS = {
|
| 44 |
+
"prim",
|
| 45 |
+
"prims",
|
| 46 |
+
"aten",
|
| 47 |
+
"at",
|
| 48 |
+
"torch",
|
| 49 |
+
"pytorch",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def warn_deprecated():
|
| 54 |
+
warnings.warn(
|
| 55 |
+
"torch._custom_op is deprecated and will be removed in PyTorch 2.6, please "
|
| 56 |
+
"use the equivalent torch.library API instead.",
|
| 57 |
+
DeprecationWarning,
|
| 58 |
+
stacklevel=2,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def custom_op(
|
| 63 |
+
qualname: str, manual_schema: typing.Optional[str] = None
|
| 64 |
+
) -> typing.Callable:
|
| 65 |
+
r"""
|
| 66 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 67 |
+
"""
|
| 68 |
+
warn_deprecated()
|
| 69 |
+
|
| 70 |
+
def inner(func):
|
| 71 |
+
if not inspect.isfunction(func):
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"custom_op(...)(func): Expected `func` to be a Python "
|
| 74 |
+
f"function, got: {type(func)}"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
ns, name = parse_qualname(qualname)
|
| 78 |
+
validate_namespace(ns)
|
| 79 |
+
if func.__name__ != name:
|
| 80 |
+
raise ValueError(
|
| 81 |
+
f"custom_op(qualname='{qualname}', ...)(func): expected `func` "
|
| 82 |
+
f"to have name '{name}' but got '{func.__name__}'. "
|
| 83 |
+
f"Please either change the name of `func` or the qualname that "
|
| 84 |
+
f"is passed to `custom_op`"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
schema = (
|
| 88 |
+
infer_schema(func, mutates_args=())
|
| 89 |
+
if manual_schema is None
|
| 90 |
+
else manual_schema
|
| 91 |
+
)
|
| 92 |
+
schema_str = f"{name}{schema}"
|
| 93 |
+
function_schema = FunctionSchema.parse(schema_str)
|
| 94 |
+
validate_schema(function_schema)
|
| 95 |
+
if manual_schema is not None:
|
| 96 |
+
validate_function_matches_schema(function_schema, func)
|
| 97 |
+
|
| 98 |
+
lib = library.Library(ns, "FRAGMENT")
|
| 99 |
+
lib.define(schema_str)
|
| 100 |
+
ophandle = find_ophandle_or_throw(ns, function_schema.name)
|
| 101 |
+
result = CustomOp(
|
| 102 |
+
lib, ns, function_schema, name, ophandle, _private_access=True
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
result.__name__ = func.__name__ # pyrefly: ignore [bad-assignment]
|
| 106 |
+
result.__module__ = func.__module__
|
| 107 |
+
result.__doc__ = func.__doc__
|
| 108 |
+
|
| 109 |
+
library.impl(lib, result._opname, "Autograd")(
|
| 110 |
+
autograd_kernel_indirection(weakref.proxy(result))
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
torch._C._dispatch_set_report_error_callback(
|
| 114 |
+
ophandle, functools.partial(report_error_callback, weakref.proxy(result))
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return result
|
| 118 |
+
|
| 119 |
+
return inner
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Global dictionary holding references to all CustomOp objects
|
| 123 |
+
# Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime])
|
| 124 |
+
# Used to query the CustomOp associated with a specific C++ dispatcher operator.
|
| 125 |
+
# An example usage is FakeTensor: FakeTensor checks if a specific operator
|
| 126 |
+
# has an implementation registered via the CustomOp API.
|
| 127 |
+
# Indexed by qualname (e.g. aten::foo)
|
| 128 |
+
global_registry: dict[str, "CustomOp"] = {}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class CustomOp:
|
| 132 |
+
r"""
|
| 133 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False
|
| 138 |
+
):
|
| 139 |
+
super().__init__()
|
| 140 |
+
warn_deprecated()
|
| 141 |
+
if not _private_access:
|
| 142 |
+
raise RuntimeError(
|
| 143 |
+
"The CustomOp constructor is private and we do not guarantee "
|
| 144 |
+
"BC for it. Please use custom_op(...) to create a CustomOp object"
|
| 145 |
+
)
|
| 146 |
+
name = f"{cpp_ns}::{operator_name}"
|
| 147 |
+
self._schema = schema
|
| 148 |
+
self._cpp_ns = cpp_ns
|
| 149 |
+
self._lib: library.Library = lib
|
| 150 |
+
self._ophandle: _C._DispatchOperatorHandle = ophandle
|
| 151 |
+
# Has the name of the op, e.g. "foo". We cache here for convenience.
|
| 152 |
+
self._opname: str = operator_name
|
| 153 |
+
# this is _opname but with namespace. e.g. "custom::foo"
|
| 154 |
+
self._qualname: str = name
|
| 155 |
+
self.__name__ = None # mypy requires this
|
| 156 |
+
# NB: Some of these impls are registered as kernels to DispatchKeys.
|
| 157 |
+
# Modifying the _impls dict directly won't do anything in that case.
|
| 158 |
+
self._impls: dict[str, typing.Optional[FuncAndLocation]] = {}
|
| 159 |
+
# See NOTE [CustomOp autograd kernel indirection]
|
| 160 |
+
self._registered_autograd_kernel_indirection = False
|
| 161 |
+
|
| 162 |
+
global_registry[self._qualname] = self
|
| 163 |
+
|
| 164 |
+
def _register_autograd_kernel_indirection(self):
|
| 165 |
+
if self._registered_autograd_kernel_indirection:
|
| 166 |
+
raise AssertionError("autograd kernel indirection already registered")
|
| 167 |
+
self._lib.impl(
|
| 168 |
+
self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd"
|
| 169 |
+
)
|
| 170 |
+
self._registered_autograd_kernel_indirection = True
|
| 171 |
+
|
| 172 |
+
# Records the impl and the source location in self._impls
|
| 173 |
+
# Note that this doesn't cause torch.library to use the impl, that
|
| 174 |
+
# needs to be done in a separate self._lib.impl call.
|
| 175 |
+
def _register_impl(self, kind, func, stacklevel=2):
|
| 176 |
+
if self._has_impl(kind):
|
| 177 |
+
func_and_location = self._impls[kind]
|
| 178 |
+
if func_and_location is None:
|
| 179 |
+
raise AssertionError("func_and_location is unexpectedly None")
|
| 180 |
+
location = func_and_location.location
|
| 181 |
+
raise RuntimeError(
|
| 182 |
+
f"Attempting to register a {kind} impl for operator {self._qualname} "
|
| 183 |
+
f"that already has a {kind} impl registered from Python at "
|
| 184 |
+
f"{location}. This is not supported."
|
| 185 |
+
)
|
| 186 |
+
frame = inspect.getframeinfo(sys._getframe(stacklevel))
|
| 187 |
+
location = f"{frame.filename}:{frame.lineno}"
|
| 188 |
+
self._impls[kind] = FuncAndLocation(func, location)
|
| 189 |
+
|
| 190 |
+
def _get_impl(self, kind):
|
| 191 |
+
return self._impls[kind]
|
| 192 |
+
|
| 193 |
+
def _has_impl(self, kind):
|
| 194 |
+
return kind in self._impls
|
| 195 |
+
|
| 196 |
+
def _destroy(self):
|
| 197 |
+
# NOTE: [CustomOp lifetime]
|
| 198 |
+
# A CustomOp, once created, lives forever. The mechanism is that the
|
| 199 |
+
# global registry holds a reference to it. However, to make testing
|
| 200 |
+
# easier, we want to be able to destroy CustomOp objects.
|
| 201 |
+
# CustomOp._destroy does the job, though it leaves the CustomOp
|
| 202 |
+
# in a garbage state.
|
| 203 |
+
del self._lib
|
| 204 |
+
|
| 205 |
+
opnamespace = getattr(torch.ops, self._cpp_ns)
|
| 206 |
+
if hasattr(opnamespace, self._opname):
|
| 207 |
+
delattr(opnamespace, self._opname)
|
| 208 |
+
|
| 209 |
+
del global_registry[self._qualname]
|
| 210 |
+
|
| 211 |
+
def __repr__(self):
|
| 212 |
+
return f'<CustomOp(op="{self._qualname}")>'
|
| 213 |
+
|
| 214 |
+
def __call__(self, *args, **kwargs):
|
| 215 |
+
# Bypass torch.ops.* and directly do OperatorHandle::callBoxed.
|
| 216 |
+
# Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime
|
| 217 |
+
# issues from caching operators that make testing CustomOp difficult).
|
| 218 |
+
result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs)
|
| 219 |
+
return result
|
| 220 |
+
|
| 221 |
+
def impl(
|
| 222 |
+
self,
|
| 223 |
+
device_types: typing.Union[str, typing.Iterable[str]],
|
| 224 |
+
_stacklevel=2,
|
| 225 |
+
) -> typing.Callable:
|
| 226 |
+
r"""
|
| 227 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 228 |
+
"""
|
| 229 |
+
if isinstance(device_types, str):
|
| 230 |
+
device_types = [device_types]
|
| 231 |
+
for device_type in device_types:
|
| 232 |
+
validate_device_type(device_type)
|
| 233 |
+
|
| 234 |
+
def inner(f):
|
| 235 |
+
for device_type in set(device_types):
|
| 236 |
+
self._check_doesnt_have_library_impl(device_type)
|
| 237 |
+
self._register_impl(device_type, f, stacklevel=_stacklevel)
|
| 238 |
+
dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
|
| 239 |
+
library.impl(self._lib, self._opname, dispatch_key)(f)
|
| 240 |
+
return f
|
| 241 |
+
|
| 242 |
+
return inner
|
| 243 |
+
|
| 244 |
+
def _check_doesnt_have_library_impl(self, device_type):
|
| 245 |
+
if self._has_impl(device_type):
|
| 246 |
+
return
|
| 247 |
+
key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type]
|
| 248 |
+
if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key):
|
| 249 |
+
raise RuntimeError(
|
| 250 |
+
f"impl(..., device_types={device_type}): the operator {self._qualname} "
|
| 251 |
+
f"already has an implementation for this device type via a "
|
| 252 |
+
f"pre-existing torch.library or TORCH_LIBRARY registration."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def impl_factory(self) -> typing.Callable:
|
| 256 |
+
r"""Register an implementation for a factory function."""
|
| 257 |
+
|
| 258 |
+
def inner(f):
|
| 259 |
+
self._register_impl("factory", f)
|
| 260 |
+
library.impl(self._lib, self._opname, "BackendSelect")(f)
|
| 261 |
+
return f
|
| 262 |
+
|
| 263 |
+
return inner
|
| 264 |
+
|
| 265 |
+
def impl_abstract(self, _stacklevel=2) -> typing.Callable:
|
| 266 |
+
r"""
|
| 267 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
def inner(f):
|
| 271 |
+
self._check_doesnt_have_library_meta_impl()
|
| 272 |
+
self._register_impl("abstract", f, stacklevel=_stacklevel)
|
| 273 |
+
location = self._get_impl("abstract").location
|
| 274 |
+
|
| 275 |
+
qualname = self._qualname
|
| 276 |
+
|
| 277 |
+
# Handle DispatchKey.Meta registration
|
| 278 |
+
@functools.wraps(f)
|
| 279 |
+
def f_with_ctx(*args, **kwargs):
|
| 280 |
+
def error_on_ctx():
|
| 281 |
+
raise RuntimeError(
|
| 282 |
+
f"Attempted to call get_ctx() for the meta implementation "
|
| 283 |
+
f"for {qualname}."
|
| 284 |
+
f"You have presumably called get_ctx() because the operator "
|
| 285 |
+
f"has a data-dependent output shape; if so, there is no "
|
| 286 |
+
f"such meta implementation and this error is the correct "
|
| 287 |
+
f"behavior. Otherwise, please remove the call to get_ctx() "
|
| 288 |
+
f"in the implementation registered with impl_abstract "
|
| 289 |
+
f"at {location}"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
with torch._library.fake_impl.set_ctx_getter(error_on_ctx):
|
| 293 |
+
return f(*args, **kwargs)
|
| 294 |
+
|
| 295 |
+
self._lib.impl(self._opname, f_with_ctx, "Meta")
|
| 296 |
+
return f
|
| 297 |
+
|
| 298 |
+
return inner
|
| 299 |
+
|
| 300 |
+
def _check_can_register_backward(self):
|
| 301 |
+
def error(detail):
|
| 302 |
+
raise RuntimeError(
|
| 303 |
+
f"Cannot use torch._custom_ops APIs to register backward "
|
| 304 |
+
f"formula for {detail}. Got operator "
|
| 305 |
+
f"{self._qualname} with schema: {schema}"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
schema = self._schema
|
| 309 |
+
if schema.kind() != SchemaKind.functional:
|
| 310 |
+
error("non-functional operator")
|
| 311 |
+
|
| 312 |
+
rets = schema.returns
|
| 313 |
+
if not schema.returns:
|
| 314 |
+
error("operator with no returns")
|
| 315 |
+
|
| 316 |
+
if len(rets) <= 0:
|
| 317 |
+
raise AssertionError(f"expected at least one return, got {len(rets)}")
|
| 318 |
+
is_non_mutating_view = any(
|
| 319 |
+
r.annotation is not None and not r.annotation.is_write for r in rets
|
| 320 |
+
)
|
| 321 |
+
if is_non_mutating_view:
|
| 322 |
+
error("operator that returns views")
|
| 323 |
+
|
| 324 |
+
# We make assumptions about the schema's return types.
|
| 325 |
+
allowed_return_types = {
|
| 326 |
+
BaseType(BaseTy.int): "int",
|
| 327 |
+
BaseType(BaseTy.SymInt): "SymInt",
|
| 328 |
+
BaseType(BaseTy.bool): "bool",
|
| 329 |
+
BaseType(BaseTy.float): "float",
|
| 330 |
+
BaseType(BaseTy.Tensor): "Tensor",
|
| 331 |
+
ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]",
|
| 332 |
+
}
|
| 333 |
+
for ret in schema.returns:
|
| 334 |
+
if ret.type in allowed_return_types:
|
| 335 |
+
continue
|
| 336 |
+
error(
|
| 337 |
+
f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
def _check_doesnt_have_library_autograd_impl(self):
|
| 341 |
+
if self._registered_autograd_kernel_indirection:
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 345 |
+
self._qualname, "CompositeImplicitAutograd"
|
| 346 |
+
):
|
| 347 |
+
raise RuntimeError(
|
| 348 |
+
f"impl_backward/impl_save_for_backward: the operator {self._qualname} "
|
| 349 |
+
f"already has an implementation for this device type via a "
|
| 350 |
+
f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
|
| 351 |
+
f"CompositeImplicitAutograd operators do not need an autograd formula; "
|
| 352 |
+
f"instead, the operator will decompose into its constituents and those "
|
| 353 |
+
f"can have autograd formulas defined on them."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# We can improve this by adding "all Autograd<BACKEND> keys", but
|
| 357 |
+
# realistically people will just be using this API for CPU/CUDA for now.
|
| 358 |
+
for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]:
|
| 359 |
+
if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key):
|
| 360 |
+
raise RuntimeError(
|
| 361 |
+
f"impl_backward/impl_save_for_backward: "
|
| 362 |
+
f"the operator {self._qualname} already has an Autograd kernel "
|
| 363 |
+
f"registered to DispatchKey::{key} vi a pre-existing "
|
| 364 |
+
f"torch.library or TORCH_LIBRARY registration. Please either "
|
| 365 |
+
f"remove those registrations or don't use the torch._custom_ops APIs"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
def _check_doesnt_have_library_meta_impl(self):
|
| 369 |
+
if self._has_impl("abstract"):
|
| 370 |
+
return
|
| 371 |
+
|
| 372 |
+
# If the user's operator is CompositeExplicitAutograd,
|
| 373 |
+
# allow them to impl_abstract. This is being pragmatic
|
| 374 |
+
# (existing custom ops may have CompositeExplicitAutograd
|
| 375 |
+
# registration that don't work with Meta kernels, so this
|
| 376 |
+
# gives them an escape hatch).
|
| 377 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 378 |
+
self._qualname, "CompositeExplicitAutograd"
|
| 379 |
+
) and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"):
|
| 380 |
+
return
|
| 381 |
+
|
| 382 |
+
# Otherwise, if the user's already has a Meta kernel or their
|
| 383 |
+
# op is CompositeImplicitAutograd or some other alias dispatch key,
|
| 384 |
+
# raise.
|
| 385 |
+
|
| 386 |
+
# Special case for CompositeImplicitAutograd
|
| 387 |
+
if _C._dispatch_has_kernel_for_dispatch_key(
|
| 388 |
+
self._qualname, "CompositeImplicitAutograd"
|
| 389 |
+
):
|
| 390 |
+
raise RuntimeError(
|
| 391 |
+
f"impl_abstract(...): the operator {self._qualname} "
|
| 392 |
+
f"already has an implementation for this device type via a "
|
| 393 |
+
f"pre-existing registration to DispatchKey::CompositeImplicitAutograd."
|
| 394 |
+
f"CompositeImplicitAutograd operators do not need an abstract impl; "
|
| 395 |
+
f"instead, the operator will decompose into its constituents and those "
|
| 396 |
+
f"can have abstract impls defined on them."
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"):
|
| 400 |
+
raise RuntimeError(
|
| 401 |
+
f"impl_abstract(...): the operator {self._qualname} "
|
| 402 |
+
f"already has an DispatchKey::Meta implementation via a "
|
| 403 |
+
f"pre-existing torch.library or TORCH_LIBRARY registration. "
|
| 404 |
+
f"Please either remove that registration or don't call impl_abstract."
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# NOTE ["backward", "save_for_backward", and "autograd"]
|
| 408 |
+
# As a part of the explicit autograd API, a user must provide us
|
| 409 |
+
# a "save_for_backward" function and a "backward" function.
|
| 410 |
+
# When both of these have been provided, then we automatically
|
| 411 |
+
# construct the "autograd" kernel.
|
| 412 |
+
def _register_autograd_kernel(self):
|
| 413 |
+
if not self._has_impl("backward"):
|
| 414 |
+
raise AssertionError("backward impl must be registered first")
|
| 415 |
+
if not self._has_impl("save_for_backward"):
|
| 416 |
+
raise AssertionError("save_for_backward impl must be registered first")
|
| 417 |
+
kernel = construct_autograd_kernel(
|
| 418 |
+
self._schema,
|
| 419 |
+
self._output_differentiability,
|
| 420 |
+
self,
|
| 421 |
+
get_op(self._qualname),
|
| 422 |
+
self._get_impl("save_for_backward").func,
|
| 423 |
+
self._get_impl("backward").func,
|
| 424 |
+
)
|
| 425 |
+
self._register_impl("autograd", kernel)
|
| 426 |
+
|
| 427 |
+
def impl_save_for_backward(self, _stacklevel=2):
|
| 428 |
+
r"""Register a function that tells us what to save for backward.
|
| 429 |
+
|
| 430 |
+
Please see impl_backward for more details.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def inner(f):
|
| 434 |
+
self._check_can_register_backward()
|
| 435 |
+
self._check_doesnt_have_library_autograd_impl()
|
| 436 |
+
if not self._registered_autograd_kernel_indirection:
|
| 437 |
+
self._register_autograd_kernel_indirection()
|
| 438 |
+
self._register_impl("save_for_backward", f, stacklevel=_stacklevel)
|
| 439 |
+
if self._has_impl("backward"):
|
| 440 |
+
self._register_autograd_kernel()
|
| 441 |
+
|
| 442 |
+
return inner
|
| 443 |
+
|
| 444 |
+
def impl_backward(self, output_differentiability=None, _stacklevel=2):
|
| 445 |
+
r"""
|
| 446 |
+
This API is deprecated, please use torch.library.custom_op instead
|
| 447 |
+
"""
|
| 448 |
+
if output_differentiability is not None:
|
| 449 |
+
|
| 450 |
+
def yell():
|
| 451 |
+
raise RuntimeError(
|
| 452 |
+
f"impl_backward(output_differentiability): expected "
|
| 453 |
+
f"output_differentiability to be a list of bools with "
|
| 454 |
+
f"length equal to the number of outputs of this CustomOp "
|
| 455 |
+
f"got: {output_differentiability}"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
if not isinstance(output_differentiability, list):
|
| 459 |
+
yell()
|
| 460 |
+
for diff in output_differentiability:
|
| 461 |
+
if not isinstance(diff, bool):
|
| 462 |
+
yell()
|
| 463 |
+
if len(self._schema.returns) != len(output_differentiability):
|
| 464 |
+
yell()
|
| 465 |
+
|
| 466 |
+
def inner(f):
|
| 467 |
+
self._check_can_register_backward()
|
| 468 |
+
self._check_doesnt_have_library_autograd_impl()
|
| 469 |
+
if not self._registered_autograd_kernel_indirection:
|
| 470 |
+
self._register_autograd_kernel_indirection()
|
| 471 |
+
self._register_impl("backward", f, stacklevel=_stacklevel)
|
| 472 |
+
self._output_differentiability = output_differentiability
|
| 473 |
+
if self._has_impl("save_for_backward"):
|
| 474 |
+
self._register_autograd_kernel()
|
| 475 |
+
|
| 476 |
+
return inner
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@dataclasses.dataclass
|
| 480 |
+
class FuncAndLocation:
|
| 481 |
+
func: typing.Callable
|
| 482 |
+
location: str
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName):
|
| 486 |
+
overload_name = (
|
| 487 |
+
"" if operator_name.overload_name is None else operator_name.overload_name
|
| 488 |
+
)
|
| 489 |
+
return _C._dispatch_find_schema_or_throw(
|
| 490 |
+
f"{cpp_ns}::{str(operator_name.name)}", overload_name
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def validate_namespace(ns: str) -> None:
|
| 495 |
+
if "." in ns:
|
| 496 |
+
raise ValueError(
|
| 497 |
+
f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a '
|
| 498 |
+
f"valid variable name)"
|
| 499 |
+
)
|
| 500 |
+
if ns in RESERVED_NS:
|
| 501 |
+
raise ValueError(
|
| 502 |
+
f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, "
|
| 503 |
+
f"please choose something else. "
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def validate_schema(schema: FunctionSchema) -> None:
|
| 508 |
+
if not torch._library.utils.is_functional_schema(schema):
|
| 509 |
+
raise ValueError(
|
| 510 |
+
f"custom_op only supports functional operators "
|
| 511 |
+
f"(ops that do not mutate any inputs, do not return "
|
| 512 |
+
f"views of the inputs, and has at least one return). "
|
| 513 |
+
f"Got the following non-functional schema: {schema}"
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
# For simplicity: don't allow self arguments
|
| 517 |
+
if schema.arguments.self_arg is not None:
|
| 518 |
+
raise ValueError(
|
| 519 |
+
f"custom_op does not support arguments named 'self'. Please "
|
| 520 |
+
f"rename your argument. Got: {schema}"
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def parse_qualname(qualname: str) -> tuple[str, str]:
|
| 525 |
+
names = qualname.split("::", 1)
|
| 526 |
+
if len(names) != 2:
|
| 527 |
+
raise ValueError(
|
| 528 |
+
f"Expected there to be a namespace in {qualname}, i.e. The "
|
| 529 |
+
f"operator name should look something like ns::foo"
|
| 530 |
+
)
|
| 531 |
+
if "." in names[1]:
|
| 532 |
+
raise ValueError(
|
| 533 |
+
f"The torch.custom_ops APIs do not handle overloads, "
|
| 534 |
+
f"i.e. operator names with '.' in them. "
|
| 535 |
+
f"Please name your operator something like ns::foo. "
|
| 536 |
+
f"Got: {qualname}"
|
| 537 |
+
)
|
| 538 |
+
return names[0], names[1]
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def validate_device_type(device_type: str) -> None:
|
| 542 |
+
if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY:
|
| 543 |
+
raise ValueError(
|
| 544 |
+
f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type "
|
| 545 |
+
f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}."
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def supported_param(param: inspect.Parameter) -> bool:
|
| 550 |
+
return param.kind in (
|
| 551 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 552 |
+
inspect.Parameter.KEYWORD_ONLY,
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def validate_function_matches_schema(
|
| 557 |
+
schema: FunctionSchema, func: typing.Callable
|
| 558 |
+
) -> None:
|
| 559 |
+
sig = inspect.signature(func)
|
| 560 |
+
|
| 561 |
+
if not all(supported_param(p) for _, p in sig.parameters.items()):
|
| 562 |
+
raise ValueError(
|
| 563 |
+
f"custom_op(..., manual_schema)(func): positional-only args, "
|
| 564 |
+
f"varargs, and kwargs are not supported. Please rewrite `func` "
|
| 565 |
+
f"to not have them. Got `func` with signature: {sig}"
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
if (
|
| 569 |
+
any(
|
| 570 |
+
p.annotation is not inspect.Parameter.empty
|
| 571 |
+
for _, p in sig.parameters.items()
|
| 572 |
+
)
|
| 573 |
+
or sig.return_annotation is not inspect.Signature.empty
|
| 574 |
+
):
|
| 575 |
+
raise ValueError(
|
| 576 |
+
f"custom_op(..., manual_schema)(func): When passing in a manual "
|
| 577 |
+
f"schema, we expect `func` to have no type annotations to avoid "
|
| 578 |
+
f"ambiguity. Got `func` with signature: {sig}"
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
positional = [
|
| 582 |
+
(name, param)
|
| 583 |
+
for name, param in sig.parameters.items()
|
| 584 |
+
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
|
| 585 |
+
]
|
| 586 |
+
kwargonly = [
|
| 587 |
+
(name, param)
|
| 588 |
+
for name, param in sig.parameters.items()
|
| 589 |
+
if param.kind == inspect.Parameter.KEYWORD_ONLY
|
| 590 |
+
]
|
| 591 |
+
|
| 592 |
+
def error():
|
| 593 |
+
raise ValueError(
|
| 594 |
+
f"custom_op(..., manual_schema)(func): When passing in a manual "
|
| 595 |
+
f"schema, we expect `func`'s signature to match `manual_schema` "
|
| 596 |
+
f"(aside from type annotations). "
|
| 597 |
+
f"func's signature: {sig}, manual_schema: {schema}"
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
def error_default_args():
|
| 601 |
+
raise ValueError(
|
| 602 |
+
f"custom_op(..., manual_schema)(func): "
|
| 603 |
+
f"neither func nor manual_schema should have default "
|
| 604 |
+
f"arguments. Got "
|
| 605 |
+
f"func's signature: {sig}, manual_schema: {schema}"
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
def compare(sig_args, schema_args):
|
| 609 |
+
if len(sig_args) != len(schema_args):
|
| 610 |
+
error()
|
| 611 |
+
for (name, param), arg in zip(sig_args, schema_args):
|
| 612 |
+
if name != arg.name:
|
| 613 |
+
error()
|
| 614 |
+
if param.default is not inspect.Parameter.empty or arg.default is not None:
|
| 615 |
+
error_default_args()
|
| 616 |
+
|
| 617 |
+
compare(positional, schema.arguments.flat_positional)
|
| 618 |
+
compare(kwargonly, schema.arguments.flat_kwarg_only)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def report_error_callback(custom_op: typing.Any, key: str) -> None:
|
| 622 |
+
if key == "Undefined":
|
| 623 |
+
raise NotImplementedError(
|
| 624 |
+
f"{custom_op}: There were no Tensor inputs to this operator "
|
| 625 |
+
f"(e.g. you passed an empty list of Tensors). If your operator is a "
|
| 626 |
+
f"factory function (that is, it takes no Tensors and constructs "
|
| 627 |
+
f"a new one), then please use CustomOp.impl_factory to register "
|
| 628 |
+
f"an implementation for it"
|
| 629 |
+
)
|
| 630 |
+
if key == "Meta":
|
| 631 |
+
raise NotImplementedError(
|
| 632 |
+
f"{custom_op}: when running with device='Meta' tensors: there is no "
|
| 633 |
+
f"abstract impl registered for this CustomOp. Please register one via "
|
| 634 |
+
f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors"
|
| 635 |
+
)
|
| 636 |
+
if key in ("CPU", "CUDA"):
|
| 637 |
+
device = key.lower()
|
| 638 |
+
raise NotImplementedError(
|
| 639 |
+
f"{custom_op}: when running with device='{device}' tensors: there is no "
|
| 640 |
+
f"{device} impl registered for this CustomOp. Please register one via "
|
| 641 |
+
f"CustomOp.impl(device_type='{device}')"
|
| 642 |
+
)
|
| 643 |
+
raise NotImplementedError(
|
| 644 |
+
f"{custom_op}: No implementation for dispatch key {key}. It is likely "
|
| 645 |
+
f"that we have not added this functionality yet, please either open an "
|
| 646 |
+
f"issue or if you're feeling adventurous, use the low-level "
|
| 647 |
+
f"torch.library API"
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def custom_op_from_existing(op):
|
| 652 |
+
ns = op.namespace
|
| 653 |
+
lib = torch.library.Library(ns, "FRAGMENT")
|
| 654 |
+
name = op.name().split("::")[-1]
|
| 655 |
+
schema_str = str(op._schema)
|
| 656 |
+
# CustomOp expects the schema string without the namespace
|
| 657 |
+
schema_str = schema_str.rsplit("::", maxsplit=1)[-1]
|
| 658 |
+
schema = FunctionSchema.parse(schema_str)
|
| 659 |
+
return CustomOp(lib, ns, schema, name, op, _private_access=True)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def get_op(qualname):
|
| 663 |
+
def error_not_found():
|
| 664 |
+
raise ValueError(
|
| 665 |
+
f"Could not find the operator {qualname}. Please make sure you have "
|
| 666 |
+
f"already registered the operator and (if registered from C++) "
|
| 667 |
+
f"loaded it via torch.ops.load_library."
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
ns, name = parse_qualname(qualname)
|
| 671 |
+
if not hasattr(torch.ops, ns):
|
| 672 |
+
error_not_found()
|
| 673 |
+
opnamespace = getattr(torch.ops, ns)
|
| 674 |
+
if not hasattr(opnamespace, name):
|
| 675 |
+
error_not_found()
|
| 676 |
+
packet = getattr(opnamespace, name)
|
| 677 |
+
if not hasattr(packet, "default"):
|
| 678 |
+
error_not_found()
|
| 679 |
+
return packet.default
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def _find_custom_op(qualname, also_check_torch_library=False):
|
| 683 |
+
if qualname in global_registry:
|
| 684 |
+
return global_registry[qualname]
|
| 685 |
+
if not also_check_torch_library:
|
| 686 |
+
raise RuntimeError(
|
| 687 |
+
f'Could not find custom op "{qualname}". Did you register it via '
|
| 688 |
+
f"the torch._custom_ops API?"
|
| 689 |
+
)
|
| 690 |
+
overload = get_op(qualname)
|
| 691 |
+
result = custom_op_from_existing(overload)
|
| 692 |
+
return result
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def get_abstract_impl(qualname):
|
| 696 |
+
if qualname not in torch._custom_op.impl.global_registry:
|
| 697 |
+
return None
|
| 698 |
+
custom_op = torch._custom_op.impl.global_registry[qualname]
|
| 699 |
+
if custom_op is None:
|
| 700 |
+
return None
|
| 701 |
+
if not custom_op._has_impl("abstract"):
|
| 702 |
+
return None
|
| 703 |
+
return custom_op._get_impl("abstract").func
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True):
|
| 707 |
+
ns, name = qualname.split("::")
|
| 708 |
+
schema_str = f"{name}{schema}"
|
| 709 |
+
function_schema = FunctionSchema.parse(schema_str)
|
| 710 |
+
validate_schema(function_schema)
|
| 711 |
+
tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else []
|
| 712 |
+
lib = library.Library(ns, "FRAGMENT")
|
| 713 |
+
lib.define(schema_str, tags=tags)
|
| 714 |
+
ophandle = find_ophandle_or_throw(ns, function_schema.name)
|
| 715 |
+
result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True)
|
| 716 |
+
result._register_autograd_kernel_indirection()
|
| 717 |
+
|
| 718 |
+
torch._C._dispatch_set_report_error_callback(
|
| 719 |
+
ophandle, functools.partial(report_error_callback, weakref.proxy(result))
|
| 720 |
+
)
|
| 721 |
+
return get_op(qualname)
|
.venv/lib/python3.10/site-packages/torch/_decomp/__init__.py
ADDED
|
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import inspect
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from collections.abc import Callable, Sequence
|
| 5 |
+
from functools import lru_cache, partial, wraps
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from typing import Optional, TYPE_CHECKING, TypeVar, Union
|
| 8 |
+
from typing_extensions import ParamSpec
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from torch.export.decomp_utils import CustomDecompTable
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.library
|
| 16 |
+
from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket
|
| 17 |
+
from torch._prims_common import CustomOutParamAnnotation
|
| 18 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 19 |
+
from torch.utils import _pytree as pytree
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"decomposition_table",
|
| 24 |
+
"pre_autograd_decomposition_table",
|
| 25 |
+
"meta_table",
|
| 26 |
+
"register_decomposition",
|
| 27 |
+
"get_decompositions",
|
| 28 |
+
"core_aten_decompositions",
|
| 29 |
+
"_should_decompose_because_unsafe_op",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
_T = TypeVar("_T")
|
| 33 |
+
_P = ParamSpec("_P")
|
| 34 |
+
|
| 35 |
+
# TODO: relax key type here; torch registrations should be possible to; but
|
| 36 |
+
# right now this type is accurate
|
| 37 |
+
global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = (
|
| 38 |
+
defaultdict(dict)
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
decomposition_table = global_decomposition_table["post_autograd"]
|
| 42 |
+
pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"]
|
| 43 |
+
meta_table = global_decomposition_table["meta"]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool:
|
| 47 |
+
"""
|
| 48 |
+
Returns True if the op must always decompose in export/compile tracing system
|
| 49 |
+
|
| 50 |
+
In export, we always decompose certain CIA ops that are tagged with
|
| 51 |
+
maybe_aliasing_or_mutating because we statically need to know if the op is
|
| 52 |
+
mutating or not. But these CIA ops could have different behaviour in runtime.
|
| 53 |
+
|
| 54 |
+
native_batch_norm is a prim op which has a wrong schema and it needs to be replaced
|
| 55 |
+
with correct schema. But until then, we will force decompose it via this tag.
|
| 56 |
+
"""
|
| 57 |
+
if not isinstance(op, torch._ops.OpOverload):
|
| 58 |
+
return False
|
| 59 |
+
if torch.Tag.maybe_aliasing_or_mutating in op.tags:
|
| 60 |
+
return True
|
| 61 |
+
return op is torch.ops.aten.native_batch_norm.default
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _add_op_to_registry(registry, op, fn):
|
| 65 |
+
"""
|
| 66 |
+
This is an internal API for adding an op to the decomposition table.
|
| 67 |
+
|
| 68 |
+
If op is OpOverload, it will be added to the registry directly.
|
| 69 |
+
If op is OpOverloadPacket, all the valid op_overloads in the packet will be added to the registry.
|
| 70 |
+
"""
|
| 71 |
+
overloads: list[Union[torch._ops.OperatorBase]] = []
|
| 72 |
+
if isinstance(op, HigherOrderOperator):
|
| 73 |
+
# There's no concept of overloads for HigherOrderOperator
|
| 74 |
+
registry[op] = fn
|
| 75 |
+
return
|
| 76 |
+
elif isinstance(op, OpOverload):
|
| 77 |
+
overloads.append(op)
|
| 78 |
+
else:
|
| 79 |
+
if not isinstance(op, OpOverloadPacket):
|
| 80 |
+
raise AssertionError(f"expected OpOverloadPacket, got {type(op)}")
|
| 81 |
+
for ol in op.overloads():
|
| 82 |
+
overloads.append(getattr(op, ol))
|
| 83 |
+
|
| 84 |
+
for op_overload in overloads:
|
| 85 |
+
if op_overload in registry:
|
| 86 |
+
raise RuntimeError(f"duplicate registrations for {op_overload}")
|
| 87 |
+
# TorchScript dumps a bunch of extra nonsense overloads
|
| 88 |
+
# which don't have corresponding dispatcher entries, we need
|
| 89 |
+
# to filter those out, e.g aten.add.float_int
|
| 90 |
+
if torch._C._dispatch_has_kernel(op_overload.name()):
|
| 91 |
+
registry[op_overload] = fn
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _convert_out_params(f):
|
| 95 |
+
out_annotation = f.__annotations__.get("out")
|
| 96 |
+
|
| 97 |
+
# If there are no out params, do not wrap the function.
|
| 98 |
+
if not out_annotation:
|
| 99 |
+
return f
|
| 100 |
+
|
| 101 |
+
# Hack to detect when out is a Tuple. There seems to be no pretty way of doing this
|
| 102 |
+
if getattr(out_annotation, "__origin__", None) is tuple:
|
| 103 |
+
sig = inspect.signature(f)
|
| 104 |
+
out_names = sig.return_annotation._fields
|
| 105 |
+
# If out is a tuple, we need to register a function that unpacks all the out
|
| 106 |
+
# elements as this is what native_functions.yaml expects
|
| 107 |
+
|
| 108 |
+
@wraps(f)
|
| 109 |
+
def _fn(*args, **kwargs):
|
| 110 |
+
out_kwargs = tuple(kwargs.pop(o, None) for o in out_names)
|
| 111 |
+
# Either all of the out kwargs are set or none of them
|
| 112 |
+
is_none = out_kwargs[0] is None
|
| 113 |
+
if not all((o is None) == is_none for o in out_kwargs):
|
| 114 |
+
raise AssertionError(
|
| 115 |
+
f"all out kwargs must be set or none of them, got {out_kwargs}"
|
| 116 |
+
)
|
| 117 |
+
return f(*args, **kwargs, out=None if is_none else out_kwargs)
|
| 118 |
+
|
| 119 |
+
out_params = [
|
| 120 |
+
inspect.Parameter(
|
| 121 |
+
o,
|
| 122 |
+
kind=inspect.Parameter.KEYWORD_ONLY,
|
| 123 |
+
default=None,
|
| 124 |
+
annotation=t,
|
| 125 |
+
)
|
| 126 |
+
for o, t in zip(out_names, out_annotation.__args__)
|
| 127 |
+
]
|
| 128 |
+
# Drop the out parameter and concatenate the new kwargs in the signature
|
| 129 |
+
params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params)
|
| 130 |
+
_fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
|
| 131 |
+
parameters=params, # type: ignore[arg-type]
|
| 132 |
+
return_annotation=sig.return_annotation,
|
| 133 |
+
)
|
| 134 |
+
# Drop the out parameter and concatenate the new kwargs in the annotations
|
| 135 |
+
_fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
|
| 136 |
+
for o in out_params:
|
| 137 |
+
_fn.__annotations__[o.name] = o.annotation
|
| 138 |
+
|
| 139 |
+
# Propagate that this function is wrapped by `out_wrapper`
|
| 140 |
+
_fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined]
|
| 141 |
+
|
| 142 |
+
return _fn
|
| 143 |
+
|
| 144 |
+
# Alternatively, there may be a single tensor out parameter with a name
|
| 145 |
+
# other than "out". This will need special treatment and is indicated by an
|
| 146 |
+
# annotation, which we will remove here so it is not exposed after wrapping.
|
| 147 |
+
custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None)
|
| 148 |
+
if custom_out_param_name:
|
| 149 |
+
|
| 150 |
+
@wraps(f)
|
| 151 |
+
def _fn(*args, **kwargs):
|
| 152 |
+
out_kwarg = kwargs.pop(custom_out_param_name, None)
|
| 153 |
+
return f(*args, **kwargs, out=out_kwarg)
|
| 154 |
+
|
| 155 |
+
out_param = inspect.Parameter(
|
| 156 |
+
custom_out_param_name,
|
| 157 |
+
kind=inspect.Parameter.KEYWORD_ONLY,
|
| 158 |
+
default=None,
|
| 159 |
+
annotation=out_annotation,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Drop the out parameter and concatenate the new kwarg in the signature
|
| 163 |
+
sig = inspect.signature(f)
|
| 164 |
+
params = chain(
|
| 165 |
+
(v for k, v in sig.parameters.items() if k != "out"), (out_param,)
|
| 166 |
+
)
|
| 167 |
+
_fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
|
| 168 |
+
parameters=params, # type: ignore[arg-type]
|
| 169 |
+
return_annotation=sig.return_annotation,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# Drop the out parameter and concatenate the new kwargs in the annotations
|
| 173 |
+
_fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"}
|
| 174 |
+
_fn.__annotations__[out_param.name] = out_param.annotation
|
| 175 |
+
|
| 176 |
+
return _fn
|
| 177 |
+
|
| 178 |
+
return f
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def register_decomposition(
|
| 182 |
+
aten_op, registry=None, *, type="post_autograd", unsafe=False
|
| 183 |
+
) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
|
| 184 |
+
"""
|
| 185 |
+
A decorator to register a function as a decomposition to the Python
|
| 186 |
+
decomposition table. Use it like this::
|
| 187 |
+
|
| 188 |
+
@register_decomposition(torch.ops.aten.clamp_min)
|
| 189 |
+
def clamp_min(x):
|
| 190 |
+
return torch.clamp(self, min=min)
|
| 191 |
+
|
| 192 |
+
If you are writing a new decomposition, consider contributing it
|
| 193 |
+
directly to PyTorch in torch._decomp.decompositions.
|
| 194 |
+
|
| 195 |
+
This API is experimental; we are almost certainly going to extend
|
| 196 |
+
the API when we make decompositions eligible for use in transforms (e.g.,
|
| 197 |
+
autograd) and not just backend tracing, where we then need to know if a
|
| 198 |
+
decomposition can be used to simulate a transform.
|
| 199 |
+
|
| 200 |
+
By default, we also will register it to the Meta key of dispatcher,
|
| 201 |
+
and replace the c++ Meta implementation if there is already one.
|
| 202 |
+
|
| 203 |
+
unsafe kwarg is for reuse of this function for registering non-function
|
| 204 |
+
things
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
if type not in {"post_autograd", "pre_autograd", "meta"}:
|
| 208 |
+
raise AssertionError(
|
| 209 |
+
f"type must be one of post_autograd, pre_autograd, or meta, got {type}"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]:
|
| 213 |
+
orig_fn = fn
|
| 214 |
+
if not unsafe:
|
| 215 |
+
fn = _convert_out_params(fn)
|
| 216 |
+
|
| 217 |
+
nonlocal registry
|
| 218 |
+
if registry is None:
|
| 219 |
+
registry = global_decomposition_table[type]
|
| 220 |
+
|
| 221 |
+
def register(op):
|
| 222 |
+
_add_op_to_registry(registry, op, fn)
|
| 223 |
+
|
| 224 |
+
# To handle allowing multiple aten_ops at once
|
| 225 |
+
pytree.tree_map_(register, aten_op)
|
| 226 |
+
return orig_fn
|
| 227 |
+
|
| 228 |
+
return decomposition_decorator
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def get_decompositions(
|
| 232 |
+
aten_ops: Sequence[Union[torch._ops.OperatorBase, OpOverloadPacket]],
|
| 233 |
+
type: str = "post_autograd",
|
| 234 |
+
) -> dict[torch._ops.OperatorBase, Callable]:
|
| 235 |
+
"""
|
| 236 |
+
Retrieve a dictionary of decompositions corresponding to the list of
|
| 237 |
+
operator overloads and overload packets passed as input. Overload
|
| 238 |
+
packets will include all decomposed overloads in the packet. If there is
|
| 239 |
+
no decomposition for a requested operator, it is silently ignored.
|
| 240 |
+
|
| 241 |
+
This API is experimental; we are almost certainly going to give an alternate,
|
| 242 |
+
more recommended formulation, where a user provides the set of operators
|
| 243 |
+
they know how to implement, and we provide decompositions for everything
|
| 244 |
+
not in this set.
|
| 245 |
+
"""
|
| 246 |
+
if type not in {"post_autograd", "pre_autograd", "meta"}:
|
| 247 |
+
raise AssertionError(
|
| 248 |
+
f"type must be one of post_autograd, pre_autograd, or meta, got {type}"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
registry = global_decomposition_table[type]
|
| 252 |
+
packets_to_overloads = defaultdict(list)
|
| 253 |
+
|
| 254 |
+
for opo in registry:
|
| 255 |
+
if isinstance(opo, (OpOverload, OpOverloadPacket)):
|
| 256 |
+
packets_to_overloads[opo.overloadpacket].append(opo)
|
| 257 |
+
decompositions: dict[torch._ops.OperatorBase, Callable] = {}
|
| 258 |
+
for op in aten_ops:
|
| 259 |
+
if isinstance(op, OpOverloadPacket) and op in packets_to_overloads:
|
| 260 |
+
for op_overload in packets_to_overloads[op]:
|
| 261 |
+
decompositions[op_overload] = registry[op_overload]
|
| 262 |
+
elif isinstance(op, (torch._ops.OperatorBase)) and op in registry:
|
| 263 |
+
decompositions[op] = registry[op]
|
| 264 |
+
return decompositions
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def remove_decompositions(
|
| 268 |
+
decompositions: dict[torch._ops.OperatorBase, Callable],
|
| 269 |
+
aten_ops: Sequence[Union[OpOverload, OpOverloadPacket]],
|
| 270 |
+
) -> None:
|
| 271 |
+
"""
|
| 272 |
+
Given a dictionary of decompositions obtained from get_decompositions(), removes
|
| 273 |
+
operators associated with a list of operator overloads and overload packets passed
|
| 274 |
+
as input. If the decomposition dictionary does not contain a decomposition that is
|
| 275 |
+
specified to be removed, it is silently ignored.
|
| 276 |
+
"""
|
| 277 |
+
for op in aten_ops:
|
| 278 |
+
if isinstance(op, OpOverloadPacket):
|
| 279 |
+
for overload_name in op.overloads():
|
| 280 |
+
opo = getattr(op, overload_name)
|
| 281 |
+
decompositions.pop(opo, None)
|
| 282 |
+
elif isinstance(op, OpOverload):
|
| 283 |
+
decompositions.pop(op, None)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# populate the table
|
| 287 |
+
import torch._decomp.decompositions
|
| 288 |
+
import torch._refs
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def core_aten_decompositions() -> "CustomDecompTable":
|
| 292 |
+
from torch.export.exported_program import default_decompositions
|
| 293 |
+
|
| 294 |
+
return default_decompositions()
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# See NOTE [Core ATen Ops]
|
| 298 |
+
#
|
| 299 |
+
# list was copied from torch/_inductor/decomposition.py
|
| 300 |
+
# excluding decompositions that results in prim ops
|
| 301 |
+
# Resulting opset of decomposition is core aten ops
|
| 302 |
+
def _core_aten_decompositions_post_autograd() -> dict[
|
| 303 |
+
torch._ops.OperatorBase, Callable
|
| 304 |
+
]:
|
| 305 |
+
aten = torch.ops.aten
|
| 306 |
+
return get_decompositions(
|
| 307 |
+
[
|
| 308 |
+
aten.addcdiv,
|
| 309 |
+
aten.addcdiv_,
|
| 310 |
+
aten.addcmul,
|
| 311 |
+
aten.addcmul_,
|
| 312 |
+
aten.addr,
|
| 313 |
+
aten.affine_grid_generator,
|
| 314 |
+
aten.alias_copy,
|
| 315 |
+
aten.all,
|
| 316 |
+
aten.aminmax,
|
| 317 |
+
aten.arange.default,
|
| 318 |
+
aten.arange.start,
|
| 319 |
+
aten.avg_pool2d_backward,
|
| 320 |
+
aten.baddbmm,
|
| 321 |
+
aten.binary_cross_entropy,
|
| 322 |
+
aten.binary_cross_entropy_backward,
|
| 323 |
+
aten.binary_cross_entropy_with_logits,
|
| 324 |
+
aten.block_diag,
|
| 325 |
+
aten.bernoulli.p,
|
| 326 |
+
aten.bernoulli.default,
|
| 327 |
+
aten.celu,
|
| 328 |
+
aten.celu_,
|
| 329 |
+
aten.channel_shuffle,
|
| 330 |
+
aten.clamp_max,
|
| 331 |
+
aten.clamp_min,
|
| 332 |
+
aten.col2im,
|
| 333 |
+
aten.count_nonzero,
|
| 334 |
+
aten.linalg_cross,
|
| 335 |
+
aten.cudnn_batch_norm,
|
| 336 |
+
aten.cudnn_batch_norm_backward,
|
| 337 |
+
aten.miopen_batch_norm_backward,
|
| 338 |
+
aten.deg2rad,
|
| 339 |
+
aten.deg2rad_,
|
| 340 |
+
aten.detach,
|
| 341 |
+
aten.diag_embed,
|
| 342 |
+
aten.diagonal_backward,
|
| 343 |
+
aten.diagonal_copy,
|
| 344 |
+
aten.dot,
|
| 345 |
+
aten.vdot,
|
| 346 |
+
aten.elu_,
|
| 347 |
+
aten.elu_backward,
|
| 348 |
+
aten._embedding_bag,
|
| 349 |
+
aten.embedding_dense_backward,
|
| 350 |
+
aten.empty_like,
|
| 351 |
+
aten._euclidean_dist.default,
|
| 352 |
+
aten.expand_as,
|
| 353 |
+
aten.expand_copy,
|
| 354 |
+
aten.eye,
|
| 355 |
+
aten.fill,
|
| 356 |
+
aten.fill_,
|
| 357 |
+
aten.floor_divide,
|
| 358 |
+
aten.frac,
|
| 359 |
+
aten.frac_,
|
| 360 |
+
aten._fused_moving_avg_obs_fq_helper,
|
| 361 |
+
aten.gelu_,
|
| 362 |
+
aten.gelu_backward,
|
| 363 |
+
aten.glu,
|
| 364 |
+
aten.glu_backward,
|
| 365 |
+
aten.hardshrink,
|
| 366 |
+
aten.hardsigmoid,
|
| 367 |
+
aten.hardsigmoid_,
|
| 368 |
+
aten.hardsigmoid_backward,
|
| 369 |
+
aten.hardswish,
|
| 370 |
+
aten.hardswish_,
|
| 371 |
+
aten.hardswish_backward,
|
| 372 |
+
aten.hardtanh_,
|
| 373 |
+
aten.hardtanh_backward,
|
| 374 |
+
aten.heaviside,
|
| 375 |
+
aten.heaviside_,
|
| 376 |
+
aten.huber_loss,
|
| 377 |
+
aten.huber_loss_backward,
|
| 378 |
+
aten.im2col,
|
| 379 |
+
aten.index_add.out,
|
| 380 |
+
aten.index_add.default,
|
| 381 |
+
aten.index_add_,
|
| 382 |
+
aten.index_copy.out,
|
| 383 |
+
aten.index_copy.default,
|
| 384 |
+
aten.index_copy_,
|
| 385 |
+
aten.index_fill.int_Scalar,
|
| 386 |
+
aten.index_fill.int_Tensor,
|
| 387 |
+
aten.index_fill.int_Scalar_out,
|
| 388 |
+
aten.index_fill.int_Tensor_out,
|
| 389 |
+
aten.index_fill_,
|
| 390 |
+
aten.isin,
|
| 391 |
+
aten.isneginf,
|
| 392 |
+
aten.isposinf,
|
| 393 |
+
aten.l1_loss,
|
| 394 |
+
aten._lazy_clone,
|
| 395 |
+
aten._test_parallel_materialize,
|
| 396 |
+
aten.leaky_relu_,
|
| 397 |
+
aten.leaky_relu_backward,
|
| 398 |
+
aten.lerp,
|
| 399 |
+
aten.lerp_,
|
| 400 |
+
aten.linspace,
|
| 401 |
+
aten.logaddexp,
|
| 402 |
+
aten.logaddexp2,
|
| 403 |
+
aten.logit,
|
| 404 |
+
aten.logit_,
|
| 405 |
+
aten.logit_backward,
|
| 406 |
+
aten.log_sigmoid_backward,
|
| 407 |
+
aten.log_sigmoid_forward,
|
| 408 |
+
aten._log_softmax_backward_data,
|
| 409 |
+
aten.logspace,
|
| 410 |
+
aten.logsumexp.default,
|
| 411 |
+
aten.masked_fill,
|
| 412 |
+
aten.masked_fill_,
|
| 413 |
+
aten.max_unpool2d,
|
| 414 |
+
aten.max_unpool3d,
|
| 415 |
+
aten.mish,
|
| 416 |
+
aten.mish_,
|
| 417 |
+
aten.mish_backward,
|
| 418 |
+
aten.mse_loss,
|
| 419 |
+
aten.mse_loss_backward,
|
| 420 |
+
aten.multi_margin_loss,
|
| 421 |
+
aten.multilabel_margin_loss_forward,
|
| 422 |
+
aten.mv,
|
| 423 |
+
aten.mvlgamma,
|
| 424 |
+
aten.mvlgamma_,
|
| 425 |
+
aten.nansum,
|
| 426 |
+
aten.nan_to_num,
|
| 427 |
+
aten.nan_to_num_,
|
| 428 |
+
aten.narrow,
|
| 429 |
+
aten.native_batch_norm_backward,
|
| 430 |
+
aten.native_dropout_backward,
|
| 431 |
+
aten.native_group_norm_backward,
|
| 432 |
+
aten.native_layer_norm_backward,
|
| 433 |
+
aten._fused_rms_norm,
|
| 434 |
+
aten._fused_rms_norm_backward,
|
| 435 |
+
aten.new_empty,
|
| 436 |
+
aten.new_full,
|
| 437 |
+
aten.new_ones,
|
| 438 |
+
aten.new_zeros,
|
| 439 |
+
aten.nll_loss2d_forward,
|
| 440 |
+
aten.nll_loss2d_backward,
|
| 441 |
+
aten.nll_loss_backward,
|
| 442 |
+
aten.nll_loss_forward,
|
| 443 |
+
aten.norm.ScalarOpt_dtype,
|
| 444 |
+
aten.norm.Scalar,
|
| 445 |
+
aten.norm.ScalarOpt_dim_dtype,
|
| 446 |
+
aten.norm.ScalarOpt_dim,
|
| 447 |
+
aten.norm.dtype_out,
|
| 448 |
+
aten.norm.out,
|
| 449 |
+
aten.norm.names_dtype_out,
|
| 450 |
+
aten.norm.names_out,
|
| 451 |
+
aten.norm.ScalarOpt_dtype_out,
|
| 452 |
+
aten.norm.Scalar_out,
|
| 453 |
+
aten.ones,
|
| 454 |
+
aten.ones_like,
|
| 455 |
+
aten.pixel_shuffle,
|
| 456 |
+
aten.pixel_unshuffle,
|
| 457 |
+
aten._prelu_kernel,
|
| 458 |
+
aten._prelu_kernel_backward,
|
| 459 |
+
aten._reshape_alias,
|
| 460 |
+
aten.rad2deg,
|
| 461 |
+
aten.rad2deg_,
|
| 462 |
+
aten.reflection_pad1d,
|
| 463 |
+
aten.reflection_pad1d_backward,
|
| 464 |
+
aten.reflection_pad2d,
|
| 465 |
+
aten.reflection_pad2d_backward,
|
| 466 |
+
aten.reflection_pad3d,
|
| 467 |
+
aten.reflection_pad3d_backward,
|
| 468 |
+
aten.replication_pad1d,
|
| 469 |
+
aten.replication_pad2d,
|
| 470 |
+
aten.replication_pad3d,
|
| 471 |
+
aten.renorm,
|
| 472 |
+
aten.renorm_,
|
| 473 |
+
aten.replication_pad2d,
|
| 474 |
+
aten.resize_as,
|
| 475 |
+
aten.roll,
|
| 476 |
+
aten.rot90,
|
| 477 |
+
aten.rrelu_with_noise,
|
| 478 |
+
aten.rrelu_with_noise_,
|
| 479 |
+
aten.rsub,
|
| 480 |
+
aten._safe_softmax,
|
| 481 |
+
aten._scaled_dot_product_flash_attention_for_cpu.default,
|
| 482 |
+
aten.select_backward,
|
| 483 |
+
aten.select_scatter,
|
| 484 |
+
aten.sgn,
|
| 485 |
+
aten.sgn_,
|
| 486 |
+
aten.sigmoid_backward,
|
| 487 |
+
aten.silu,
|
| 488 |
+
aten.silu_,
|
| 489 |
+
aten.silu_backward.grad_input,
|
| 490 |
+
aten.silu_backward,
|
| 491 |
+
aten.sinc,
|
| 492 |
+
aten.sinc_,
|
| 493 |
+
aten.slice_backward,
|
| 494 |
+
aten.smooth_l1_loss,
|
| 495 |
+
aten.smooth_l1_loss_backward,
|
| 496 |
+
aten.soft_margin_loss,
|
| 497 |
+
aten.soft_margin_loss_backward,
|
| 498 |
+
aten._softmax_backward_data,
|
| 499 |
+
aten.softplus,
|
| 500 |
+
aten.softplus_backward,
|
| 501 |
+
aten.softshrink,
|
| 502 |
+
aten.special_entr,
|
| 503 |
+
aten.special_log_ndtr,
|
| 504 |
+
aten.special_xlog1py,
|
| 505 |
+
aten.split.Tensor,
|
| 506 |
+
aten.split_with_sizes_copy,
|
| 507 |
+
aten.squeeze_copy,
|
| 508 |
+
aten.squeeze.default,
|
| 509 |
+
aten.squeeze.dim,
|
| 510 |
+
aten.std.correction,
|
| 511 |
+
aten.std.out,
|
| 512 |
+
aten.std.correction_out,
|
| 513 |
+
aten.std.names_out,
|
| 514 |
+
aten.std.correction_names_out,
|
| 515 |
+
aten.std_mean.correction,
|
| 516 |
+
aten.std_mean.correction_out,
|
| 517 |
+
aten.stack,
|
| 518 |
+
aten.sum.default,
|
| 519 |
+
aten.sum.out,
|
| 520 |
+
aten.t,
|
| 521 |
+
aten.t_copy,
|
| 522 |
+
aten.take,
|
| 523 |
+
aten.tanh_backward,
|
| 524 |
+
aten.threshold,
|
| 525 |
+
aten.threshold_,
|
| 526 |
+
aten.threshold_backward,
|
| 527 |
+
aten.trace,
|
| 528 |
+
aten.transpose.int,
|
| 529 |
+
aten.transpose_copy,
|
| 530 |
+
aten.tril,
|
| 531 |
+
aten.tril_,
|
| 532 |
+
aten.triu,
|
| 533 |
+
aten.triu_,
|
| 534 |
+
aten.unbind,
|
| 535 |
+
aten.unfold_backward,
|
| 536 |
+
aten.unfold_copy,
|
| 537 |
+
aten._unsafe_index,
|
| 538 |
+
aten._unsafe_index_put,
|
| 539 |
+
aten._unsafe_masked_index,
|
| 540 |
+
aten._unsafe_masked_index_put_accumulate,
|
| 541 |
+
aten.unsafe_split.Tensor,
|
| 542 |
+
aten.unsafe_split_with_sizes,
|
| 543 |
+
aten.unsqueeze_copy,
|
| 544 |
+
aten._unsafe_view,
|
| 545 |
+
aten.upsample_linear1d,
|
| 546 |
+
aten.upsample_bilinear2d.out,
|
| 547 |
+
aten.upsample_trilinear3d.out,
|
| 548 |
+
aten.upsample_nearest2d_backward,
|
| 549 |
+
aten.view_as_complex,
|
| 550 |
+
aten.xlogy,
|
| 551 |
+
aten.xlogy_,
|
| 552 |
+
aten.zero,
|
| 553 |
+
aten.zero_,
|
| 554 |
+
aten.zeros,
|
| 555 |
+
aten.zeros_like,
|
| 556 |
+
aten._chunk_cat,
|
| 557 |
+
aten._weight_norm_interface,
|
| 558 |
+
]
|
| 559 |
+
)
|
.venv/lib/python3.10/site-packages/torch/_decomp/decompositions.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.10/site-packages/torch/_decomp/decompositions_for_jvp.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import inspect
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch._decomp
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
from torch._prims_common.wrappers import _maybe_remove_out_wrapper
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
decomposition_table = torch._decomp.decomposition_table
|
| 14 |
+
decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {}
|
| 15 |
+
register_decomposition = torch._decomp.register_decomposition
|
| 16 |
+
aten = torch.ops.aten
|
| 17 |
+
|
| 18 |
+
# NOTE: [forward-mode AD decompositions mechanism]
|
| 19 |
+
#
|
| 20 |
+
# The mechanism is in VariableType,
|
| 21 |
+
# IF any inputs have forward grad
|
| 22 |
+
# AND there is no forward AD formula implemented
|
| 23 |
+
# AND the functions are actually differentiable
|
| 24 |
+
# run the decomposition
|
| 25 |
+
# See run_jit_decomposition_with_args_for_jvp
|
| 26 |
+
# We currently use python decompositions that we torchscript.
|
| 27 |
+
#
|
| 28 |
+
# Note that we would be building the backward graph at the decomposed level
|
| 29 |
+
# too, but that is OK, because we would've errored out otherwise anyway.
|
| 30 |
+
#
|
| 31 |
+
# TODO: The mechanism we are using to register decompositions doesn't
|
| 32 |
+
# seem to be exclusively used for jvp. So open question here is whether
|
| 33 |
+
# torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things.
|
| 34 |
+
# If that is the case, we may go down the decomposition path unexpectedly
|
| 35 |
+
# (and possibly produce an unintelligible error) vs erroring out earlier and
|
| 36 |
+
# printing that the forward AD formula is not implemented.
|
| 37 |
+
#
|
| 38 |
+
# The solution to this may be to have an explicitly white list control when
|
| 39 |
+
# to enable the decomposition.
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def maybe_register_decomposition(op):
|
| 43 |
+
def decorator(f):
|
| 44 |
+
try:
|
| 45 |
+
return register_decomposition(op)(f)
|
| 46 |
+
except Exception:
|
| 47 |
+
return f
|
| 48 |
+
|
| 49 |
+
return decorator
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Functions where we need a special decomposition for jvp but there's another version that
|
| 53 |
+
# should be used more generally (ex. for jvp we need to recompute the mean and variance for
|
| 54 |
+
# the backwards of a normalization function. Without jvp, it should use the saved value)
|
| 55 |
+
decomposition_table_for_jvp = {}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def register_decomposition_for_jvp(fn):
|
| 59 |
+
return register_decomposition(fn, registry=decomposition_table_for_jvp)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _register_jit_decomposition_for_jvp(decomp, use_python=False):
|
| 63 |
+
if decomp in decomposition_table_for_jvp:
|
| 64 |
+
decomposition_table_used = decomposition_table_for_jvp
|
| 65 |
+
elif decomp in decomposition_table:
|
| 66 |
+
decomposition_table_used = decomposition_table
|
| 67 |
+
else:
|
| 68 |
+
raise RuntimeError(f"could not find decomposition for {decomp}")
|
| 69 |
+
decomp_fn = decomposition_table_used[decomp]
|
| 70 |
+
|
| 71 |
+
# `out_wrapper` extends a decompositions signature with
|
| 72 |
+
# an `out` parameter. However jit will use the unwrapped function's
|
| 73 |
+
# signature instead so we need to unwrap here to prevent an error
|
| 74 |
+
decomp_fn = _maybe_remove_out_wrapper(decomp_fn)
|
| 75 |
+
|
| 76 |
+
if use_python:
|
| 77 |
+
decomp_fn = torch.jit.ignore(decomp_fn)
|
| 78 |
+
sig = inspect.signature(decomp_fn)
|
| 79 |
+
|
| 80 |
+
# Create a string wrapping the function from the signature
|
| 81 |
+
# example output:
|
| 82 |
+
# def wrapped_decomp(x: torch.Tensor, y: int, z: int):
|
| 83 |
+
# return decomp_fn(x, y, z)
|
| 84 |
+
# Thanks copilot!
|
| 85 |
+
def get_function_def(sig):
|
| 86 |
+
param_def = [f"{param_str}" for param_str in sig.parameters.values()]
|
| 87 |
+
param_use = [f"{param_str}" for param_str in sig.parameters]
|
| 88 |
+
|
| 89 |
+
return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n"
|
| 90 |
+
|
| 91 |
+
f_str = get_function_def(sig)
|
| 92 |
+
graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph
|
| 93 |
+
else:
|
| 94 |
+
graph = torch.jit.script(decomp_fn).graph
|
| 95 |
+
torch.jit._register_decomposition(decomp, graph)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# The only decompositions here are temporary or hacks for the purposes of jvp
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# TODO: do these also belong here?
|
| 102 |
+
@maybe_register_decomposition(aten.trace.default)
|
| 103 |
+
def trace(self: Tensor) -> Tensor:
|
| 104 |
+
return torch.sum(torch.diag(self))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@maybe_register_decomposition(aten.log_sigmoid_forward.default)
|
| 108 |
+
def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]:
|
| 109 |
+
min = torch.minimum(self.new_zeros(()), self)
|
| 110 |
+
z = torch.exp(-torch.abs(self))
|
| 111 |
+
if self.is_cuda or self.is_xpu:
|
| 112 |
+
buffer = self.new_zeros((0,))
|
| 113 |
+
else:
|
| 114 |
+
buffer = z
|
| 115 |
+
return min - torch.log1p(z), buffer
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def recompute_mean_var(
|
| 119 |
+
input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool
|
| 120 |
+
):
|
| 121 |
+
# for most norm decompositions, it will be the same as the core version except for here.
|
| 122 |
+
# We recompute the mean and variance so that they track gradients through input
|
| 123 |
+
|
| 124 |
+
mean = torch.mean(input, dim=inner_dim_indices, keepdim=keepdim)
|
| 125 |
+
var = torch.var(input, dim=inner_dim_indices, unbiased=False, keepdim=keepdim)
|
| 126 |
+
eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside
|
| 127 |
+
eps = eps.detach()
|
| 128 |
+
rstd = 1 / torch.sqrt(var + eps)
|
| 129 |
+
return mean, rstd
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@register_decomposition_for_jvp(aten.native_layer_norm_backward)
|
| 133 |
+
def native_layer_norm_backward(
|
| 134 |
+
grad_out: Tensor,
|
| 135 |
+
input: Tensor,
|
| 136 |
+
normalized_shape: list[int],
|
| 137 |
+
mean: Tensor,
|
| 138 |
+
rstd: Tensor,
|
| 139 |
+
weight: Optional[Tensor],
|
| 140 |
+
bias: Optional[Tensor],
|
| 141 |
+
output_mask: list[bool],
|
| 142 |
+
) -> tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor]]:
|
| 143 |
+
input_shape = input.shape
|
| 144 |
+
input_ndim = input.dim()
|
| 145 |
+
|
| 146 |
+
axis = input_ndim - len(normalized_shape)
|
| 147 |
+
inner_dims = input_shape[axis:]
|
| 148 |
+
outer_dims = input_shape[:axis]
|
| 149 |
+
inner_dim_indices = list(range(axis, input_ndim))
|
| 150 |
+
outer_dim_indices = list(range(axis))
|
| 151 |
+
|
| 152 |
+
N = 1
|
| 153 |
+
for i in inner_dims:
|
| 154 |
+
N *= i
|
| 155 |
+
M = 1
|
| 156 |
+
for i in outer_dims:
|
| 157 |
+
M *= i
|
| 158 |
+
if M <= 0 or N <= 0:
|
| 159 |
+
return (
|
| 160 |
+
input.new_zeros(input_shape),
|
| 161 |
+
input.new_zeros(input_shape[axis:]),
|
| 162 |
+
input.new_zeros(input_shape[axis:]),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True)
|
| 166 |
+
|
| 167 |
+
x_hat = (input - mean_) * rstd_
|
| 168 |
+
if weight is not None:
|
| 169 |
+
grad_x_hat = grad_out * weight
|
| 170 |
+
else:
|
| 171 |
+
grad_x_hat = grad_out
|
| 172 |
+
a = grad_x_hat * N
|
| 173 |
+
b = torch.sum(grad_x_hat, inner_dim_indices, True)
|
| 174 |
+
c1 = torch.mul(grad_x_hat, x_hat)
|
| 175 |
+
c2 = torch.sum(c1, inner_dim_indices, True)
|
| 176 |
+
c3 = torch.mul(x_hat, c2)
|
| 177 |
+
inner = a - b - c3
|
| 178 |
+
|
| 179 |
+
if output_mask[0]:
|
| 180 |
+
d_input: Optional[Tensor] = (rstd_ / N) * inner
|
| 181 |
+
else:
|
| 182 |
+
d_input = torch.zeros_like(input) # should be None but doesn't work with vjp
|
| 183 |
+
|
| 184 |
+
if output_mask[1] and weight is not None:
|
| 185 |
+
if len(outer_dim_indices) > 0:
|
| 186 |
+
d_weight: Optional[Tensor] = torch.sum(
|
| 187 |
+
grad_out * x_hat, outer_dim_indices, False
|
| 188 |
+
)
|
| 189 |
+
else:
|
| 190 |
+
d_weight = grad_out * x_hat
|
| 191 |
+
elif weight is not None:
|
| 192 |
+
d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp
|
| 193 |
+
else:
|
| 194 |
+
d_weight = torch.zeros(()) # should be None but doesn't work with vjp
|
| 195 |
+
|
| 196 |
+
if output_mask[2] and bias is not None:
|
| 197 |
+
if len(outer_dim_indices) > 0:
|
| 198 |
+
d_bias: Optional[Tensor] = torch.sum(grad_out, outer_dim_indices, False)
|
| 199 |
+
else:
|
| 200 |
+
d_bias = grad_out.clone()
|
| 201 |
+
elif bias is not None:
|
| 202 |
+
d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp
|
| 203 |
+
else:
|
| 204 |
+
d_bias = torch.zeros(()) # should be None but doesn't work with vjp
|
| 205 |
+
|
| 206 |
+
return (d_input, d_weight, d_bias)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def prod(x: list[int]):
|
| 210 |
+
r = 1
|
| 211 |
+
for i in x:
|
| 212 |
+
r *= i
|
| 213 |
+
return r
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@register_decomposition_for_jvp(aten.native_batch_norm_backward)
|
| 217 |
+
def native_batch_norm_backward(
|
| 218 |
+
grad_out: Tensor,
|
| 219 |
+
input: Tensor,
|
| 220 |
+
weight: Optional[Tensor],
|
| 221 |
+
running_mean: Optional[Tensor],
|
| 222 |
+
running_var: Optional[Tensor],
|
| 223 |
+
save_mean: Optional[Tensor],
|
| 224 |
+
save_invstd: Optional[Tensor],
|
| 225 |
+
train: bool,
|
| 226 |
+
eps: float,
|
| 227 |
+
output_mask: list[bool],
|
| 228 |
+
) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 229 |
+
input_shape = input.shape
|
| 230 |
+
input_rank = input.dim()
|
| 231 |
+
if input_rank < 2:
|
| 232 |
+
raise AssertionError(f"rank of the input must be at least 2, got {input_rank}")
|
| 233 |
+
|
| 234 |
+
axis = 1
|
| 235 |
+
num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type]
|
| 236 |
+
mean = save_mean
|
| 237 |
+
invstd = save_invstd
|
| 238 |
+
if train:
|
| 239 |
+
if save_mean is None or save_invstd is None:
|
| 240 |
+
raise AssertionError(
|
| 241 |
+
"when train=True, save_mean and save_invstd are required"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
reduciton_dims = [0] + list(range(2, input.dim()))
|
| 245 |
+
if invstd is None:
|
| 246 |
+
raise AssertionError("invstd must not be None for typing")
|
| 247 |
+
mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False)
|
| 248 |
+
else:
|
| 249 |
+
if running_mean is None or running_var is None:
|
| 250 |
+
raise AssertionError(
|
| 251 |
+
"running_mean and running_var must not be None when train=False"
|
| 252 |
+
)
|
| 253 |
+
mean = running_mean
|
| 254 |
+
invstd = torch.rsqrt(running_var + eps)
|
| 255 |
+
|
| 256 |
+
if invstd is None or mean is None:
|
| 257 |
+
raise AssertionError(
|
| 258 |
+
f"invstd and mean must not be None, got invstd={invstd}, mean={mean}"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
broadcast_mask = [1] * input_rank
|
| 262 |
+
broadcast_mask[axis] = input_shape[axis]
|
| 263 |
+
|
| 264 |
+
reduction_axes: list[int] = []
|
| 265 |
+
for i in range(input_rank):
|
| 266 |
+
if i != axis:
|
| 267 |
+
reduction_axes.append(i)
|
| 268 |
+
|
| 269 |
+
mean = torch.reshape(mean, broadcast_mask)
|
| 270 |
+
norm = 1.0 / num_features
|
| 271 |
+
grad_output_sum = torch.sum(grad_out, reduction_axes)
|
| 272 |
+
dot_p = torch.sum(grad_out * (input - mean), reduction_axes)
|
| 273 |
+
|
| 274 |
+
grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask)
|
| 275 |
+
proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask)
|
| 276 |
+
|
| 277 |
+
if weight is None:
|
| 278 |
+
grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0
|
| 279 |
+
else:
|
| 280 |
+
grad_scale = torch.reshape(invstd * weight, broadcast_mask)
|
| 281 |
+
|
| 282 |
+
if train:
|
| 283 |
+
proj = (input - mean) * proj_scale
|
| 284 |
+
grad_input = ((grad_out - proj) - grad_mean) * grad_scale
|
| 285 |
+
else:
|
| 286 |
+
grad_input = grad_out * grad_scale
|
| 287 |
+
|
| 288 |
+
if output_mask[1]:
|
| 289 |
+
grad_weight = dot_p * invstd
|
| 290 |
+
elif weight is not None:
|
| 291 |
+
grad_weight = torch.zeros_like(
|
| 292 |
+
weight
|
| 293 |
+
) # should be None but doesn't work with vjp
|
| 294 |
+
else:
|
| 295 |
+
grad_weight = torch.zeros(()) # should be None but doesn't work with vjp
|
| 296 |
+
|
| 297 |
+
if output_mask[2]:
|
| 298 |
+
grad_bias = grad_output_sum
|
| 299 |
+
else:
|
| 300 |
+
grad_bias = torch.zeros_like(
|
| 301 |
+
grad_output_sum
|
| 302 |
+
) # should be None but doesn't work with vjp
|
| 303 |
+
|
| 304 |
+
return (grad_input, grad_weight, grad_bias)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@register_decomposition_for_jvp(aten.batch_norm_backward)
|
| 308 |
+
def batch_norm_backward(
|
| 309 |
+
grad_out: Tensor,
|
| 310 |
+
input: Tensor,
|
| 311 |
+
weight: Tensor,
|
| 312 |
+
running_mean: Optional[Tensor],
|
| 313 |
+
running_var: Optional[Tensor],
|
| 314 |
+
save_mean: Optional[Tensor],
|
| 315 |
+
save_var: Optional[Tensor],
|
| 316 |
+
update: bool,
|
| 317 |
+
eps: float,
|
| 318 |
+
output_mask: list[bool],
|
| 319 |
+
reserve: Tensor,
|
| 320 |
+
) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
|
| 321 |
+
return native_batch_norm_backward(
|
| 322 |
+
grad_out,
|
| 323 |
+
input,
|
| 324 |
+
weight,
|
| 325 |
+
running_mean,
|
| 326 |
+
running_var,
|
| 327 |
+
save_mean,
|
| 328 |
+
save_var,
|
| 329 |
+
update,
|
| 330 |
+
eps,
|
| 331 |
+
output_mask,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True)
|
| 336 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default)
|
| 337 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default)
|
| 338 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default)
|
| 339 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default)
|
| 340 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default)
|
| 341 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default)
|
| 342 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default)
|
| 343 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default)
|
| 344 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default)
|
| 345 |
+
_register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default)
|
.venv/lib/python3.10/site-pack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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import functools
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch._decomp as decomp
|
| 9 |
+
from torch._decomp import get_decompositions
|
| 10 |
+
from torch._ops import OpOverload
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
aten = torch.ops.aten
|
| 14 |
+
|
| 15 |
+
rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def register_rng_decomposition(aten_op):
|
| 19 |
+
return decomp.register_decomposition(aten_op, rng_decompositions)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def throw_on_non_cuda(device):
|
| 23 |
+
raise RuntimeError(
|
| 24 |
+
f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not "
|
| 25 |
+
f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is "
|
| 26 |
+
"not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU."
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# TODO - We have to register many more distributions here, and also higher level
|
| 31 |
+
# ops like dropout which have fused implementation and can hide the rand inside.
|
| 32 |
+
@register_rng_decomposition(aten.rand)
|
| 33 |
+
def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False):
|
| 34 |
+
if device and device.type != "cuda":
|
| 35 |
+
throw_on_non_cuda(device)
|
| 36 |
+
seed, offset = PhiloxStateTracker.get_state_as_tuple()
|
| 37 |
+
dtype = dtype or torch.float32
|
| 38 |
+
out, offset_jump = torch.ops.rngprims.philox_rand(
|
| 39 |
+
shape, seed, offset, None, device, dtype
|
| 40 |
+
)
|
| 41 |
+
PhiloxStateTracker.advance_offset(offset_jump)
|
| 42 |
+
return out
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@register_rng_decomposition(aten.rand_like)
|
| 46 |
+
def rand_like(
|
| 47 |
+
x: torch.Tensor,
|
| 48 |
+
dtype=None,
|
| 49 |
+
layout=None,
|
| 50 |
+
device=None,
|
| 51 |
+
pin_memory=False,
|
| 52 |
+
memory_format=torch.preserve_format,
|
| 53 |
+
):
|
| 54 |
+
device = device or x.device
|
| 55 |
+
if device.type != "cuda":
|
| 56 |
+
throw_on_non_cuda(device)
|
| 57 |
+
dtype = dtype or x.dtype
|
| 58 |
+
seed, offset = PhiloxStateTracker.get_state_as_tuple()
|
| 59 |
+
out, offset_jump = torch.ops.rngprims.philox_rand(
|
| 60 |
+
x.shape, seed, offset, None, device, dtype
|
| 61 |
+
)
|
| 62 |
+
PhiloxStateTracker.advance_offset(offset_jump)
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class PhiloxState:
|
| 67 |
+
"""
|
| 68 |
+
Represents a PhiloxRngState - (seed, offset) where offset = base_offset +
|
| 69 |
+
relative_offset. seed and base_offset basically point to the rng state just
|
| 70 |
+
before tracing starts. relative offset tracks the totally consumed offset at
|
| 71 |
+
trace time.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self) -> None:
|
| 75 |
+
self.reset()
|
| 76 |
+
|
| 77 |
+
def reset(self):
|
| 78 |
+
self.seed = torch.tensor(())
|
| 79 |
+
self.base_offset = torch.tensor(())
|
| 80 |
+
self.relative_offset = 0
|
| 81 |
+
self.offset_advanced_alteast_once = False
|
| 82 |
+
|
| 83 |
+
def validate_state(self):
|
| 84 |
+
if self.seed.numel() == 0 or self.base_offset.numel() == 0:
|
| 85 |
+
raise AssertionError(
|
| 86 |
+
f"seed and base_offset must not be empty, got "
|
| 87 |
+
f"seed.numel()={self.seed.numel()}, base_offset.numel()={self.base_offset.numel()}"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def advance_offset(self, consumed_offset):
|
| 91 |
+
self.offset_advanced_alteast_once = True
|
| 92 |
+
self.relative_offset = self.relative_offset + consumed_offset
|
| 93 |
+
|
| 94 |
+
def set_state(self, seed, base_offset, relative_offset=0):
|
| 95 |
+
self.seed = seed
|
| 96 |
+
self.base_offset = base_offset
|
| 97 |
+
self.relative_offset = relative_offset
|
| 98 |
+
|
| 99 |
+
def get_state_as_tuple(self):
|
| 100 |
+
self.validate_state()
|
| 101 |
+
return (self.seed, self.base_offset + self.relative_offset)
|
| 102 |
+
|
| 103 |
+
def get_state_as_tensor(self):
|
| 104 |
+
# Only needed because we override get_rng_state.
|
| 105 |
+
self.validate_state()
|
| 106 |
+
return torch.stack([self.seed, self.base_offset + self.relative_offset])
|
| 107 |
+
|
| 108 |
+
def set_state_from_tensor(self, state):
|
| 109 |
+
# Only needed because we override set_rng_state.
|
| 110 |
+
self.seed, self.base_offset = torch.unbind(state)
|
| 111 |
+
self.relative_offset = 0
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class PhiloxStateTracker:
|
| 115 |
+
"""
|
| 116 |
+
Singleton class to track the philox rng state during AOT Autograd tracing.
|
| 117 |
+
For each aot tracing instance, AOT Autograd resets this tracker and keeps
|
| 118 |
+
track of both forward and backward offsets. At runtime, we only care about
|
| 119 |
+
the total consumed forward and backward offsets. For dynamic shapes, these
|
| 120 |
+
offsets are a function of input shapes. Therefore, the AOT generated graphs
|
| 121 |
+
have additional outputs that compute total consumed forward and backward
|
| 122 |
+
offsets.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
running_state: PhiloxState
|
| 126 |
+
fwd_state: PhiloxState
|
| 127 |
+
bwd_state: PhiloxState
|
| 128 |
+
|
| 129 |
+
def __enter__(self):
|
| 130 |
+
PhiloxStateTracker.reset()
|
| 131 |
+
return self
|
| 132 |
+
|
| 133 |
+
def __exit__(self, exc_type, exc_cal, exc_tb):
|
| 134 |
+
PhiloxStateTracker.reset()
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def reset(cls):
|
| 138 |
+
cls.running_state = PhiloxState()
|
| 139 |
+
cls.fwd_state = PhiloxState()
|
| 140 |
+
cls.bwd_state = PhiloxState()
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def mark_beginning_of_forward(cls):
|
| 144 |
+
# Tells the tracker to use fwd_state as the running state
|
| 145 |
+
cls.running_state = cls.fwd_state
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def mark_beginning_of_backward(cls):
|
| 149 |
+
# Tells the tracker to use bwd_state as the running state
|
| 150 |
+
cls.running_state = cls.bwd_state
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def record_state(cls, seed, offset, mode):
|
| 154 |
+
# Records the seed and offset tensors. These tensors are used to invoke
|
| 155 |
+
# the philox_rand functional primitives.
|
| 156 |
+
if mode == "forward":
|
| 157 |
+
cls.fwd_state.set_state(seed, offset)
|
| 158 |
+
cls.mark_beginning_of_forward()
|
| 159 |
+
else:
|
| 160 |
+
if mode != "backward":
|
| 161 |
+
raise AssertionError(f"mode must be 'backward', got {mode}")
|
| 162 |
+
cls.bwd_state.set_state(seed, offset)
|
| 163 |
+
|
| 164 |
+
@classmethod
|
| 165 |
+
def get_state_as_tensor(cls):
|
| 166 |
+
# The only reason this exists is because we override get_rng_state and
|
| 167 |
+
# set_rng_state during tracing. get_rng_state expects a tensor output,
|
| 168 |
+
# so return (seed, offset) tuple upset other parts of the program like
|
| 169 |
+
# ctx.saved_tensors.
|
| 170 |
+
|
| 171 |
+
# A bad consequence is that if user saves and restores rng state, we
|
| 172 |
+
# have little bit of ugliness in the generated code, where we first
|
| 173 |
+
# concat the (seed, offset) to create a tensor for get_rng_state, and
|
| 174 |
+
# then split it back to get (seed, offset) tuple in set_rng_state.
|
| 175 |
+
|
| 176 |
+
# TODO: Investigate if there is be a better way to wrap the tuple in a
|
| 177 |
+
# false Tensor object, and then desugar it later on.
|
| 178 |
+
return cls.running_state.get_state_as_tensor()
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def get_state_as_tuple(cls):
|
| 182 |
+
return cls.running_state.get_state_as_tuple()
|
| 183 |
+
|
| 184 |
+
@classmethod
|
| 185 |
+
def set_state_from_tensor(cls, x):
|
| 186 |
+
# This is only needed because we override set_rng_state. Look at the
|
| 187 |
+
# comment in get_state_from_tensor method.
|
| 188 |
+
cls.running_state.set_state_from_tensor(x)
|
| 189 |
+
|
| 190 |
+
@classmethod
|
| 191 |
+
def advance_offset(cls, consumed_offset):
|
| 192 |
+
cls.running_state.advance_offset(consumed_offset)
|
| 193 |
+
|
| 194 |
+
@classmethod
|
| 195 |
+
def get_current_relative_offset(cls):
|
| 196 |
+
return cls.running_state.relative_offset
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def multiple_of_4(offset):
|
| 200 |
+
# torch cuda rng state offset must be a multiple of 4. For inductor, as
|
| 201 |
+
# we sum up all the numel, the result might not be a multiple of 4. This
|
| 202 |
+
# method achieves that.
|
| 203 |
+
return (offset + 3) // 4 * 4
|
| 204 |
+
|
| 205 |
+
@classmethod
|
| 206 |
+
def get_updated_fwd_offset(cls):
|
| 207 |
+
# Short circuit if no rand ops were observed
|
| 208 |
+
if not cls.fwd_state.offset_advanced_alteast_once:
|
| 209 |
+
return cls.fwd_state.base_offset
|
| 210 |
+
return cls.multiple_of_4(
|
| 211 |
+
cls.fwd_state.base_offset + cls.fwd_state.relative_offset
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def get_updated_bwd_offset(cls):
|
| 216 |
+
# Short circuit if no rand ops were observed
|
| 217 |
+
if not cls.bwd_state.offset_advanced_alteast_once:
|
| 218 |
+
return cls.bwd_state.base_offset
|
| 219 |
+
return cls.multiple_of_4(
|
| 220 |
+
cls.bwd_state.base_offset + cls.bwd_state.relative_offset
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Adding more decompositions which eventually use rand_like inside decomps.
|
| 225 |
+
# Adding these in rng_decompositions ensures the functionalization of rand_like
|
| 226 |
+
# ops used in these decomps. The list is copied from inductor codebase, which
|
| 227 |
+
# uses it for similar purpose.
|
| 228 |
+
#
|
| 229 |
+
# Caution - These decomps do not have same accuracy as that of eager. However,
|
| 230 |
+
# we can't just disable them with a config flag like fallback_random, because
|
| 231 |
+
# for functionalization of rng ops, we have to decompose these ops.
|
| 232 |
+
extra_random_decomps = get_decompositions(
|
| 233 |
+
[
|
| 234 |
+
aten.cauchy,
|
| 235 |
+
aten.cauchy_,
|
| 236 |
+
aten.exponential,
|
| 237 |
+
aten.exponential_,
|
| 238 |
+
aten.geometric,
|
| 239 |
+
aten.geometric_,
|
| 240 |
+
aten.native_dropout,
|
| 241 |
+
aten.normal,
|
| 242 |
+
aten.normal_,
|
| 243 |
+
aten.normal_functional,
|
| 244 |
+
aten.log_normal,
|
| 245 |
+
aten.log_normal_,
|
| 246 |
+
aten.rrelu_with_noise,
|
| 247 |
+
aten.rrelu_with_noise_,
|
| 248 |
+
aten.uniform_,
|
| 249 |
+
]
|
| 250 |
+
)
|
| 251 |
+
register_extra_random_decomp = functools.partial(
|
| 252 |
+
decomp.register_decomposition, registry=extra_random_decomps
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@register_extra_random_decomp([aten.bernoulli_])
|
| 257 |
+
def bernoulli_(self, p=0.5):
|
| 258 |
+
if self.device == torch.device("cpu"):
|
| 259 |
+
return NotImplemented
|
| 260 |
+
return self.copy_(torch.rand_like(self, dtype=torch.float32) < p)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@register_extra_random_decomp([aten.bernoulli.p])
|
| 264 |
+
def bernoulli_p(self, p=0.5, *, generator=None):
|
| 265 |
+
if self.device == torch.device("cpu"):
|
| 266 |
+
return NotImplemented
|
| 267 |
+
if generator is not None:
|
| 268 |
+
raise AssertionError(f"generator must be None, got {generator}")
|
| 269 |
+
return torch.rand_like(self, dtype=torch.float32) < p
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type]
|
.venv/lib/python3.10/site-packages/torch/_dynamo/__init__.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
TorchDynamo is a Python-level JIT compiler designed to make unmodified PyTorch programs faster.
|
| 3 |
+
TorchDynamo hooks into the frame evaluation API in CPython (PEP 523) to dynamically modify Python
|
| 4 |
+
bytecode right before it is executed. It rewrites Python bytecode in order to extract sequences of
|
| 5 |
+
PyTorch operations into an FX Graph which is then just-in-time compiled with a customizable backend.
|
| 6 |
+
It creates this FX Graph through bytecode analysis and is designed to mix Python execution with
|
| 7 |
+
compiled backends to get the best of both worlds: usability and performance. This allows it to
|
| 8 |
+
seamlessly optimize PyTorch programs, including those using modern Python features.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from . import (
|
| 14 |
+
aot_compile,
|
| 15 |
+
config,
|
| 16 |
+
convert_frame,
|
| 17 |
+
eval_frame,
|
| 18 |
+
functional_export,
|
| 19 |
+
resume_execution,
|
| 20 |
+
)
|
| 21 |
+
from .backends.registry import list_backends, lookup_backend, register_backend
|
| 22 |
+
from .callback import callback_handler, on_compile_end, on_compile_start
|
| 23 |
+
from .code_context import code_context
|
| 24 |
+
from .convert_frame import replay
|
| 25 |
+
from .decorators import (
|
| 26 |
+
allow_in_graph,
|
| 27 |
+
assume_constant_result,
|
| 28 |
+
disable,
|
| 29 |
+
disable_nested_graph_breaks,
|
| 30 |
+
disallow_in_graph,
|
| 31 |
+
dont_skip_tracing,
|
| 32 |
+
error_on_graph_break,
|
| 33 |
+
forbid_in_graph,
|
| 34 |
+
graph_break,
|
| 35 |
+
is_dynamo_disable_recursive,
|
| 36 |
+
mark_dynamic,
|
| 37 |
+
mark_static,
|
| 38 |
+
mark_static_address,
|
| 39 |
+
maybe_mark_dynamic,
|
| 40 |
+
nonstrict_trace,
|
| 41 |
+
patch_dynamo_config,
|
| 42 |
+
run,
|
| 43 |
+
set_stance,
|
| 44 |
+
skip_frame,
|
| 45 |
+
step_unsupported,
|
| 46 |
+
substitute_in_graph,
|
| 47 |
+
)
|
| 48 |
+
from .eval_frame import (
|
| 49 |
+
_reset_guarded_backend_cache,
|
| 50 |
+
explain,
|
| 51 |
+
export,
|
| 52 |
+
is_dynamo_supported,
|
| 53 |
+
is_inductor_supported,
|
| 54 |
+
optimize,
|
| 55 |
+
optimize_assert,
|
| 56 |
+
OptimizedModule,
|
| 57 |
+
reset_code,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# pyrefly: ignore [deprecated]
|
| 61 |
+
from .external_utils import is_compiling
|
| 62 |
+
from .mutation_guard import GenerationTracker
|
| 63 |
+
from .pgo import reset_code_state
|
| 64 |
+
from .symbolic_convert import TensorifyState
|
| 65 |
+
from .utils import (
|
| 66 |
+
graph_break_reasons,
|
| 67 |
+
guard_failures,
|
| 68 |
+
orig_code_map,
|
| 69 |
+
register_hook_for_recompile_user_context,
|
| 70 |
+
reset_frame_count,
|
| 71 |
+
reset_recompile_user_contexts,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# Register polyfill functions
|
| 76 |
+
from .polyfills import loader as _ # usort: skip # noqa: F401
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
__all__ = [
|
| 80 |
+
"allow_in_graph",
|
| 81 |
+
"assume_constant_result",
|
| 82 |
+
"config",
|
| 83 |
+
"disable",
|
| 84 |
+
"disable_nested_graph_breaks",
|
| 85 |
+
"disallow_in_graph",
|
| 86 |
+
"dont_skip_tracing",
|
| 87 |
+
"export",
|
| 88 |
+
"explain",
|
| 89 |
+
"forbid_in_graph",
|
| 90 |
+
"graph_break",
|
| 91 |
+
"is_compiling",
|
| 92 |
+
"is_dynamo_disable_recursive",
|
| 93 |
+
"list_backends",
|
| 94 |
+
"lookup_backend",
|
| 95 |
+
"mark_dynamic",
|
| 96 |
+
"maybe_mark_dynamic",
|
| 97 |
+
"mark_static",
|
| 98 |
+
"mark_static_address",
|
| 99 |
+
"nonstrict_trace",
|
| 100 |
+
"optimize",
|
| 101 |
+
"optimize_assert",
|
| 102 |
+
"OptimizedModule",
|
| 103 |
+
"patch_dynamo_config",
|
| 104 |
+
"register_backend",
|
| 105 |
+
"replay",
|
| 106 |
+
"reset",
|
| 107 |
+
"reset_recompile_user_contexts",
|
| 108 |
+
"run",
|
| 109 |
+
"error_on_graph_break",
|
| 110 |
+
"set_recursion_limit",
|
| 111 |
+
"set_stance",
|
| 112 |
+
"skip_frame",
|
| 113 |
+
"step_unsupported",
|
| 114 |
+
"substitute_in_graph",
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
# allowlist this for weights_only load of NJTs
|
| 118 |
+
torch.serialization.add_safe_globals([torch._dynamo.decorators._DimRange])
|
| 119 |
+
|
| 120 |
+
if torch.manual_seed is torch.random.manual_seed:
|
| 121 |
+
import torch.jit._builtins
|
| 122 |
+
|
| 123 |
+
# Wrap manual_seed with the disable decorator.
|
| 124 |
+
# Can't do it at its implementation due to dependency issues.
|
| 125 |
+
torch.manual_seed = torch._disable_dynamo(torch.manual_seed)
|
| 126 |
+
# Add the new manual_seed to the builtin registry.
|
| 127 |
+
torch.jit._builtins._register_builtin(torch.manual_seed, "aten::manual_seed")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def reset() -> None:
|
| 131 |
+
"""
|
| 132 |
+
Clear all compile caches and restore initial state. This function is intended
|
| 133 |
+
to reset Dynamo's state *as if* you had started a fresh process invocation, which
|
| 134 |
+
makes it good for testing scenarios where you want to behave as if you started
|
| 135 |
+
a new process. It does NOT affect any file system caches.
|
| 136 |
+
|
| 137 |
+
NB: this does NOT reset logging state. Don't use this to test logging
|
| 138 |
+
initialization/reinitialization.
|
| 139 |
+
"""
|
| 140 |
+
# TODO: https://github.com/pytorch/pytorch/issues/139200
|
| 141 |
+
import logging
|
| 142 |
+
|
| 143 |
+
log = logging.getLogger(__name__)
|
| 144 |
+
log.info("torch._dynamo.reset")
|
| 145 |
+
with convert_frame.compile_lock:
|
| 146 |
+
reset_code_caches()
|
| 147 |
+
convert_frame.input_codes.clear()
|
| 148 |
+
reset_code_state()
|
| 149 |
+
convert_frame.output_codes.clear()
|
| 150 |
+
orig_code_map.clear()
|
| 151 |
+
guard_failures.clear()
|
| 152 |
+
graph_break_reasons.clear()
|
| 153 |
+
resume_execution.ContinueExecutionCache.cache.clear()
|
| 154 |
+
_reset_guarded_backend_cache()
|
| 155 |
+
reset_frame_count()
|
| 156 |
+
torch._dynamo.compiled_autograd.reset()
|
| 157 |
+
convert_frame.FRAME_COUNTER = 0
|
| 158 |
+
convert_frame.FRAME_COMPILE_COUNTER.clear()
|
| 159 |
+
callback_handler.clear()
|
| 160 |
+
GenerationTracker.clear()
|
| 161 |
+
TensorifyState.clear()
|
| 162 |
+
torch._dynamo.utils.warn_once_cache.clear()
|
| 163 |
+
torch._C._autograd._saved_tensors_hooks_set_tracing(False)
|
| 164 |
+
|
| 165 |
+
# Reset cudagraph trees unconditionally since they are global state
|
| 166 |
+
# not tied to a specific backend instance
|
| 167 |
+
if torch.cuda.is_available():
|
| 168 |
+
from torch._inductor.cudagraph_trees import reset_cudagraph_trees
|
| 169 |
+
|
| 170 |
+
reset_cudagraph_trees()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def reset_code_caches() -> None:
|
| 174 |
+
"""
|
| 175 |
+
Clears in-memory code cache, which is what stores compiled products. This
|
| 176 |
+
resets less state than :func:`reset` and is mostly only used for testing
|
| 177 |
+
purposes.
|
| 178 |
+
"""
|
| 179 |
+
# TODO: https://github.com/pytorch/pytorch/issues/139200
|
| 180 |
+
import logging
|
| 181 |
+
|
| 182 |
+
log = logging.getLogger(__name__)
|
| 183 |
+
log.info("torch._dynamo.reset_code_caches")
|
| 184 |
+
"""Clear compile caches that are keyed by code objects"""
|
| 185 |
+
with convert_frame.compile_lock:
|
| 186 |
+
reset_code_state()
|
| 187 |
+
for weak_code in (
|
| 188 |
+
convert_frame.input_codes.seen + convert_frame.output_codes.seen
|
| 189 |
+
):
|
| 190 |
+
code = weak_code()
|
| 191 |
+
if code:
|
| 192 |
+
reset_code(code)
|
| 193 |
+
code_context.clear()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def get_recursion_limit() -> int:
|
| 197 |
+
"""
|
| 198 |
+
Returns the internal dynamo recursion limit set by `torch._dynamo.set_recursion_limit`.
|
| 199 |
+
|
| 200 |
+
Returns -1 if no c recursion limit has been set.
|
| 201 |
+
"""
|
| 202 |
+
return torch._C._dynamo.eval_frame.get_c_recursion_limit()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def set_recursion_limit(limit: int) -> None:
|
| 206 |
+
"""
|
| 207 |
+
Sets an internal dynamo recursion limit. The limit must be >= 1, or -1 to reset
|
| 208 |
+
to the default (unset) state.
|
| 209 |
+
|
| 210 |
+
This is possibly needed in Python 3.12-3.13 since there is a separate C recursion limit
|
| 211 |
+
that is not visible at the Python level. If you are getting RecursionErrors during
|
| 212 |
+
Dynamo compilation and `sys.setrecursionlimit()` doesn't help, this function may alleviate
|
| 213 |
+
the issue.
|
| 214 |
+
|
| 215 |
+
NOTE: this function does NOT call `sys.setrecursionlimit()` - the user is expected to manually
|
| 216 |
+
call this if required. This is because the 2 recursion limits are not sync'd up - e.g. in
|
| 217 |
+
Python 3.12, functions can be inline-evaluated, which apparently doesn't use up the C stack.
|
| 218 |
+
|
| 219 |
+
WARNING: increasing the recursion limit to an arbitrary large value may cause segfaults
|
| 220 |
+
due to stack overflows! You can try also try to manually increase the stack size, e.g.
|
| 221 |
+
with `$ ulimit -s ...`
|
| 222 |
+
"""
|
| 223 |
+
torch._C._dynamo.eval_frame.set_c_recursion_limit(limit)
|
.venv/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""trace_wrapped(*args, fn) is equivalent to fn(*args), but with a twist:
|
| 2 |
+
if you make_fx trace through this call, we will not actually trace into fn; instead,
|
| 3 |
+
we will directly insert it as a call_function to fn in the graph.
|
| 4 |
+
(Unlike make_fx, Dynamo WILL inline into fn.)
|
| 5 |
+
You can think of this as a one off allow_in_graph equivalent for proxy tensor tracing.
|
| 6 |
+
|
| 7 |
+
Because proxy tensor tracing does not actually run the function, there are
|
| 8 |
+
requirements on the behavior of fn. We are still figuring it out, but here is the current state:
|
| 9 |
+
|
| 10 |
+
1) fn SHOULD only take a single argument, which must be a tensor
|
| 11 |
+
2) fn MUST return a new tensor with the same metadata as the original tensor
|
| 12 |
+
(e.g., zeros_like(input) is a permissible implementation of fn).
|
| 13 |
+
This is verified via an extra assert that is inserted into the traced graph.
|
| 14 |
+
3) fn MAY have side effects, but it MAY NOT perform metadata mutation on other tensors
|
| 15 |
+
participating in proxy tensor tracing (it MAY mutate other tensors, it MAY mutate Python state)
|
| 16 |
+
These requirements stem from the requirement that we need to continue performing proxy tensor tracing,
|
| 17 |
+
which assumes accurate fake tensor metadata, without actually running fn.
|
| 18 |
+
In the future, we may allow for a "meta" function associated with fn to allow for more interesting input-output patterns.
|
| 19 |
+
|
| 20 |
+
Note that tensors / Python state are allowed to be mutated.
|
| 21 |
+
This is relaxed constraint is not always sound, but it is sound for backward tracing with fake
|
| 22 |
+
tensors as it takes place in AOTAutograd, as the backward pass is guaranteed not to depend on concrete
|
| 23 |
+
tensor values (via fake tensor) or Python state (because the autograd engine doesn't depend on Python).
|
| 24 |
+
|
| 25 |
+
The intended use case for this function is to allow AOTAutograd to defer complex
|
| 26 |
+
backward hooks to compiled autograd. AOTAutograd performs a make_fx trace which preserves
|
| 27 |
+
the function call as is in the graph, and only when we Dynamo through the backward graph in
|
| 28 |
+
compiled autograd do we inline into the function.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from typing import Any, Optional
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
import torch.utils._pytree as pytree
|
| 35 |
+
from torch._C import DispatchKey
|
| 36 |
+
from torch._higher_order_ops.utils import autograd_not_implemented
|
| 37 |
+
from torch._ops import HigherOrderOperator, OpOverload
|
| 38 |
+
from torch._subclasses import FakeTensorMode
|
| 39 |
+
from torch.fx.experimental._backward_state import BackwardState
|
| 40 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
|
| 41 |
+
from torch.overrides import TorchFunctionMode
|
| 42 |
+
from torch.utils._python_dispatch import _get_current_dispatch_mode
|
| 43 |
+
from torch.utils._pytree import tree_map_only
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
Tensor = torch.Tensor
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__all__ = ["trace_wrapped"]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@torch.library.custom_op("flex_lib::zeros_and_scatter", mutates_args=()) # type: ignore[misc]
|
| 53 |
+
def zeros_and_scatter(
|
| 54 |
+
shape: list[int],
|
| 55 |
+
indices: list[Tensor],
|
| 56 |
+
vals: Tensor,
|
| 57 |
+
) -> Tensor:
|
| 58 |
+
"""Custom Op so that we can register a custom lowering for the new_output + scatter in the backwards pass"""
|
| 59 |
+
grad = torch.zeros(shape, device=vals.device, dtype=vals.dtype)
|
| 60 |
+
return torch.ops.aten.index_put(grad, indices, vals, accumulate=True)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@zeros_and_scatter.register_fake # type: ignore[misc]
|
| 64 |
+
def _(
|
| 65 |
+
shape: list[int],
|
| 66 |
+
indices: list[Tensor],
|
| 67 |
+
vals: Tensor,
|
| 68 |
+
) -> Tensor:
|
| 69 |
+
return vals.new_empty(shape)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@zeros_and_scatter.register_vmap # type: ignore[misc]
|
| 73 |
+
def _(info, indims, shape, indices, value): # type: ignore[no-untyped-def]
|
| 74 |
+
"""The batching rule is special in that it returns a tensor that is not batched"""
|
| 75 |
+
indices_indims = indims[1]
|
| 76 |
+
expanded_indices = []
|
| 77 |
+
for idx, idx_indim in zip(indices, indices_indims):
|
| 78 |
+
# The index is not a being batched, we should unsqueeze and expand to val
|
| 79 |
+
if idx_indim is None:
|
| 80 |
+
expanded_indices.append(idx.expand(value.shape))
|
| 81 |
+
else:
|
| 82 |
+
# the index is being part of the vmap batch, it should be the same size as val
|
| 83 |
+
assert idx.shape == value.shape
|
| 84 |
+
expanded_indices.append(idx)
|
| 85 |
+
|
| 86 |
+
out = torch.ops.flex_lib.zeros_and_scatter(
|
| 87 |
+
shape,
|
| 88 |
+
expanded_indices,
|
| 89 |
+
value,
|
| 90 |
+
)
|
| 91 |
+
return out, None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class ModIndex(torch.autograd.Function):
|
| 95 |
+
generate_vmap_rule = True
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
# pyrefly: ignore [bad-override]
|
| 99 |
+
def forward(x: Tensor, indices: list[Tensor]) -> Tensor:
|
| 100 |
+
return torch.ops.aten.index(x, indices)
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None:
|
| 104 |
+
x, indices = inputs
|
| 105 |
+
ctx.save_for_backward(*indices)
|
| 106 |
+
ctx.input_shape = x.shape
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def backward(ctx, gradOut): # type: ignore[no-untyped-def]
|
| 110 |
+
indices = ctx.saved_tensors
|
| 111 |
+
return (
|
| 112 |
+
torch.ops.flex_lib.zeros_and_scatter(
|
| 113 |
+
ctx.input_shape,
|
| 114 |
+
indices,
|
| 115 |
+
gradOut,
|
| 116 |
+
),
|
| 117 |
+
None,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
@classmethod
|
| 121 |
+
@torch._export.wrappers.allow_in_pre_dispatch_graph
|
| 122 |
+
def apply(cls, *args, **kwargs): # type: ignore[no-untyped-def]
|
| 123 |
+
return super().apply(*args, **kwargs)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
mod_index = ModIndex.apply
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TransformGetItemToIndex(TorchFunctionMode):
|
| 130 |
+
# This is needed since we want to support calling
|
| 131 |
+
# A[q_idx], where q_idx is a scalar tensor in score_mod.
|
| 132 |
+
# Today, when q_idx is a scalar tensor, we implicitly convert it to a python
|
| 133 |
+
# scalar and create a view. We do not want that behavior in this case, so we
|
| 134 |
+
# use this torchfunctionmode to override that behavior for score_mod
|
| 135 |
+
# wherever we're running it.
|
| 136 |
+
#
|
| 137 |
+
# We also convert integer indices to 0-D tensors so that temp[0] produces
|
| 138 |
+
# the same backward graph as temp[0 * q_idx] (zeros_and_scatter with atomic_add).
|
| 139 |
+
def __torch_function__(
|
| 140 |
+
self,
|
| 141 |
+
func: OpOverload,
|
| 142 |
+
types: tuple[torch._C._TensorMeta, ...],
|
| 143 |
+
args: tuple[object, ...] = (),
|
| 144 |
+
kwargs: Optional[dict[str, object]] = None,
|
| 145 |
+
) -> object:
|
| 146 |
+
if func is torch.Tensor.__getitem__:
|
| 147 |
+
tensor_to_index = args[0]
|
| 148 |
+
assert isinstance(tensor_to_index, torch.Tensor)
|
| 149 |
+
index_args = pytree.tree_leaves(args[1])
|
| 150 |
+
if all(isinstance(x, (torch.Tensor, int)) for x in index_args):
|
| 151 |
+
converted_indices = [
|
| 152 |
+
torch.tensor(x, dtype=torch.int64, device=tensor_to_index.device)
|
| 153 |
+
if isinstance(x, int)
|
| 154 |
+
else x
|
| 155 |
+
for x in index_args
|
| 156 |
+
]
|
| 157 |
+
return mod_index(tensor_to_index, converted_indices)
|
| 158 |
+
return func(*args, **(kwargs or {}))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def trace_wrapped(*args: Any, **kwargs: Any) -> Any:
|
| 162 |
+
with torch.no_grad():
|
| 163 |
+
return _trace_wrapped_op(*args, **kwargs)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class TraceWrapped(HigherOrderOperator):
|
| 167 |
+
def __init__(self) -> None:
|
| 168 |
+
super().__init__("trace_wrapped")
|
| 169 |
+
|
| 170 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 171 |
+
# pyrefly: ignore [missing-attribute]
|
| 172 |
+
return super().__call__(*args, **kwargs)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# TODO(jansel): need to ensure this does not get DCEed
|
| 176 |
+
_trace_wrapped_op = TraceWrapped()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _assert_meta(
|
| 180 |
+
grad: torch.Tensor,
|
| 181 |
+
size: tuple[int, ...],
|
| 182 |
+
stride: tuple[int, ...],
|
| 183 |
+
dtype: torch.dtype,
|
| 184 |
+
) -> torch.Tensor:
|
| 185 |
+
assert grad.size() == size, "size mismatch"
|
| 186 |
+
assert grad.stride() == stride, "stride mismatch"
|
| 187 |
+
assert grad.dtype == dtype, "dtype mismatch"
|
| 188 |
+
return grad
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@_trace_wrapped_op.py_impl(ProxyTorchDispatchMode)
|
| 192 |
+
def inner_trace(
|
| 193 |
+
mode: ProxyTorchDispatchMode,
|
| 194 |
+
*args: Any,
|
| 195 |
+
bw_state: Optional[BackwardState] = None,
|
| 196 |
+
**kwargs: Any,
|
| 197 |
+
) -> Any:
|
| 198 |
+
def self_invoke(*args: Any, **dyn_kwargs: Any) -> Any:
|
| 199 |
+
with torch.no_grad():
|
| 200 |
+
return _trace_wrapped_op(*args, **dyn_kwargs, **kwargs)
|
| 201 |
+
|
| 202 |
+
def unwrap_proxies(x: Any) -> Any:
|
| 203 |
+
if isinstance(x, torch.Tensor):
|
| 204 |
+
return mode.tracer.unwrap_proxy(x) # type: ignore[union-attr]
|
| 205 |
+
if isinstance(x, (list, tuple)):
|
| 206 |
+
return type(x)(map(unwrap_proxies, x))
|
| 207 |
+
if x is None:
|
| 208 |
+
return None
|
| 209 |
+
raise AssertionError(f"unhandled type: {type(x)}")
|
| 210 |
+
|
| 211 |
+
proxy_kwargs = {}
|
| 212 |
+
if bw_state is not None:
|
| 213 |
+
assert isinstance(bw_state, BackwardState) and bw_state.proxy is not None
|
| 214 |
+
proxy_kwargs["bw_state"] = bw_state.proxy
|
| 215 |
+
out_proxy = mode.tracer.create_proxy(
|
| 216 |
+
"call_function",
|
| 217 |
+
self_invoke,
|
| 218 |
+
unwrap_proxies(args),
|
| 219 |
+
proxy_kwargs,
|
| 220 |
+
name="trace_wrapped",
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if args[0] is None:
|
| 224 |
+
grad = args[1] # module backward hooks
|
| 225 |
+
else:
|
| 226 |
+
grad = args[0] # other backward hooks
|
| 227 |
+
grad = tree_map_only(torch.Tensor, torch.empty_like, grad)
|
| 228 |
+
track_tensor_tree(grad, out_proxy, constant=None, tracer=mode.tracer)
|
| 229 |
+
return grad
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@_trace_wrapped_op.py_impl(FakeTensorMode)
|
| 233 |
+
def inner_fake(*args: Any, **kwargs: Any) -> None:
|
| 234 |
+
raise RuntimeError("This op should never be invoked here")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@_trace_wrapped_op.py_impl(DispatchKey.CompositeExplicitAutograd)
|
| 238 |
+
def _trace_wrapped_op_dense(*args: Any, fn: Any, **kwargs: Any) -> Any:
|
| 239 |
+
mode = _get_current_dispatch_mode()
|
| 240 |
+
assert mode is None, "Mode should never be enabled for CPU/CUDA key"
|
| 241 |
+
return fn(*args, **kwargs)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
_trace_wrapped_op.py_impl(DispatchKey.Autograd)(
|
| 245 |
+
autograd_not_implemented(_trace_wrapped_op, deferred_error=True)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@_trace_wrapped_op.py_functionalize_impl
|
| 250 |
+
def _trace_wrapped_functionalized(ctx: Any, *args: Any, **kwargs: Any) -> Any:
|
| 251 |
+
unwrapped_args = ctx.unwrap_tensors(args)
|
| 252 |
+
with ctx.redispatch_to_next():
|
| 253 |
+
return ctx.wrap_tensors(_trace_wrapped_op(*unwrapped_args, **kwargs))
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def autograd_function_backward_rewritten(original_backward: Any) -> Any:
|
| 257 |
+
def new_backward(ctx: Any, *grads: Any) -> Any:
|
| 258 |
+
# pyrefly: ignore [bad-assignment]
|
| 259 |
+
grads = [g.contiguous() for g in grads]
|
| 260 |
+
return original_backward(ctx, *grads)
|
| 261 |
+
|
| 262 |
+
return new_backward
|
.venv/lib/python3.10/site-packages/torch/_dynamo/aot_compile.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import importlib
|
| 3 |
+
import inspect
|
| 4 |
+
import io
|
| 5 |
+
import logging
|
| 6 |
+
import pickle
|
| 7 |
+
import types
|
| 8 |
+
from collections.abc import Callable, Sequence
|
| 9 |
+
from contextlib import AbstractContextManager, ExitStack, nullcontext
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.fx
|
| 15 |
+
from torch._dynamo.convert_frame import GraphRuntimeEnv
|
| 16 |
+
from torch._dynamo.graph_utils import _graph_device_type
|
| 17 |
+
from torch._dynamo.package import SystemInfo
|
| 18 |
+
|
| 19 |
+
from . import convert_frame
|
| 20 |
+
from .aot_compile_types import (
|
| 21 |
+
BundledAOTAutogradSerializableCallable,
|
| 22 |
+
SerializableCallable,
|
| 23 |
+
)
|
| 24 |
+
from .hooks import Hooks
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if TYPE_CHECKING:
|
| 28 |
+
from .guards import GuardManagerWrapper
|
| 29 |
+
from .package import SerializedCode, SourceInfo
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def bind_locals(
|
| 36 |
+
signature: inspect.Signature, *args: Any, **kwargs: Any
|
| 37 |
+
) -> dict[str, Any]:
|
| 38 |
+
bound_arguments = signature.bind(*args, **kwargs)
|
| 39 |
+
bound_arguments.apply_defaults()
|
| 40 |
+
return bound_arguments.arguments
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class CompileArtifacts:
|
| 45 |
+
signature: inspect.Signature
|
| 46 |
+
guard_manager: Optional["GuardManagerWrapper"]
|
| 47 |
+
guards_state: bytes
|
| 48 |
+
backend_id: str
|
| 49 |
+
compiled_fn: SerializableCallable
|
| 50 |
+
original_code: types.CodeType
|
| 51 |
+
runtime_env: GraphRuntimeEnv
|
| 52 |
+
source_info: "SourceInfo"
|
| 53 |
+
device_type: str
|
| 54 |
+
backend_name: str
|
| 55 |
+
system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current)
|
| 56 |
+
|
| 57 |
+
def check_compatibility(self) -> None:
|
| 58 |
+
current_system = SystemInfo.current()
|
| 59 |
+
current_system.check_compatibility(self.system_info, self.device_type)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class AOTCompilePickler(pickle.Pickler):
|
| 63 |
+
def __init__(self, external_data: dict[str, object], buf: io.BytesIO) -> None:
|
| 64 |
+
super().__init__(buf)
|
| 65 |
+
self.external_data = external_data
|
| 66 |
+
self.id_map: dict[int, str] = {
|
| 67 |
+
id(value): key for key, value in external_data.items()
|
| 68 |
+
}
|
| 69 |
+
self.errors = {}
|
| 70 |
+
|
| 71 |
+
def persistent_id(self, obj: object) -> int | str | None:
|
| 72 |
+
if id(obj) in self.id_map:
|
| 73 |
+
return self.id_map[id(obj)]
|
| 74 |
+
elif isinstance(obj, torch.nn.Module):
|
| 75 |
+
self.errors[id(obj)] = obj
|
| 76 |
+
return id(obj)
|
| 77 |
+
else:
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def _unpickle_cell(cls, val: object) -> object:
|
| 82 |
+
def _() -> object:
|
| 83 |
+
return val
|
| 84 |
+
|
| 85 |
+
assert _.__closure__ is not None
|
| 86 |
+
return _.__closure__[0]
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
# pyrefly: ignore [implicit-any]
|
| 90 |
+
def _unpickle_bound_method(cls, func: Callable, base: object) -> types.MethodType:
|
| 91 |
+
return types.MethodType(func, base)
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def _unpickle_module(cls, name: str) -> types.ModuleType:
|
| 95 |
+
return importlib.import_module(name)
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def _unpickle_code(cls, serialized_code: "SerializedCode") -> types.CodeType:
|
| 99 |
+
from torch._dynamo.package import SerializedCode
|
| 100 |
+
|
| 101 |
+
return SerializedCode.to_code_object(serialized_code)
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def _unpickle_nested_function(
|
| 105 |
+
cls,
|
| 106 |
+
code: types.CodeType,
|
| 107 |
+
module: str,
|
| 108 |
+
qualname: str,
|
| 109 |
+
argdefs: tuple[object, ...] | None,
|
| 110 |
+
closure: tuple[types.CellType, ...] | None,
|
| 111 |
+
) -> types.FunctionType:
|
| 112 |
+
f_globals = importlib.import_module(module).__dict__
|
| 113 |
+
return types.FunctionType(code, f_globals, qualname, argdefs, closure)
|
| 114 |
+
|
| 115 |
+
# pyrefly: ignore [bad-override]
|
| 116 |
+
def reducer_override(self, obj: Any) -> Any:
|
| 117 |
+
if isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002
|
| 118 |
+
return type(self)._unpickle_cell, (obj.cell_contents,)
|
| 119 |
+
elif inspect.iscode(obj):
|
| 120 |
+
from torch._dynamo.package import SerializedCode
|
| 121 |
+
|
| 122 |
+
return type(self)._unpickle_code, (SerializedCode.from_code_object(obj),)
|
| 123 |
+
|
| 124 |
+
elif inspect.ismodule(obj):
|
| 125 |
+
return type(self)._unpickle_module, (obj.__name__,)
|
| 126 |
+
elif inspect.ismethod(obj):
|
| 127 |
+
"""
|
| 128 |
+
By default, pickle will call getattr() directly on the self object
|
| 129 |
+
for pickling bounded methods, this is not what we want, instead we
|
| 130 |
+
always want to serialize the original function and the self object
|
| 131 |
+
in their original form.
|
| 132 |
+
"""
|
| 133 |
+
func = obj.__func__
|
| 134 |
+
method_self = obj.__self__
|
| 135 |
+
inner_func = getattr(method_self, func.__name__)
|
| 136 |
+
if inspect.ismethod(inner_func):
|
| 137 |
+
inner_func = inner_func.__func__
|
| 138 |
+
if func is not inner_func:
|
| 139 |
+
return type(self)._unpickle_bound_method, (func, method_self)
|
| 140 |
+
elif inspect.isfunction(obj):
|
| 141 |
+
if "<locals>" in obj.__qualname__:
|
| 142 |
+
return type(self)._unpickle_nested_function, (
|
| 143 |
+
obj.__code__,
|
| 144 |
+
obj.__module__,
|
| 145 |
+
obj.__qualname__,
|
| 146 |
+
obj.__defaults__,
|
| 147 |
+
obj.__closure__,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
return NotImplemented
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class AOTCompileUnpickler(pickle.Unpickler):
|
| 154 |
+
def __init__(self, external_data: dict[str, object], file: io.BytesIO) -> object:
|
| 155 |
+
super().__init__(file)
|
| 156 |
+
self.external_data = external_data
|
| 157 |
+
|
| 158 |
+
def persistent_load(self, key: str) -> object:
|
| 159 |
+
if key not in self.external_data:
|
| 160 |
+
raise RuntimeError(
|
| 161 |
+
f"Missing required external reference to data: {key}. "
|
| 162 |
+
"Please load AOT compiled function with "
|
| 163 |
+
"`external_data=<external data dictionary>`"
|
| 164 |
+
f"{self.external_data}"
|
| 165 |
+
)
|
| 166 |
+
return self.external_data[key]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@dataclass
|
| 170 |
+
class AOTCompileSaveResult:
|
| 171 |
+
serialized_data: bytes
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@dataclass
|
| 175 |
+
class AOTCompiledFunction:
|
| 176 |
+
_artifacts: CompileArtifacts
|
| 177 |
+
_guard_check_enabled: bool = True
|
| 178 |
+
_extra_globals: dict[str, object] | None = None
|
| 179 |
+
|
| 180 |
+
def prepare_f_locals(self, *args: object, **kwargs: object) -> dict[str, object]:
|
| 181 |
+
f_locals: dict[str, object] = {}
|
| 182 |
+
env = self._artifacts.runtime_env
|
| 183 |
+
if env.closure:
|
| 184 |
+
assert env.bytecode.co_freevars and len(env.closure) == len(
|
| 185 |
+
env.bytecode.co_freevars
|
| 186 |
+
)
|
| 187 |
+
f_locals = {
|
| 188 |
+
name: cell.cell_contents
|
| 189 |
+
for name, cell in zip(env.bytecode.co_freevars, env.closure)
|
| 190 |
+
}
|
| 191 |
+
f_locals.update(bind_locals(self._artifacts.signature, *args, **kwargs))
|
| 192 |
+
return f_locals
|
| 193 |
+
|
| 194 |
+
def guard_check(self, *args: Any, **kwargs: Any) -> bool:
|
| 195 |
+
f_locals = self.prepare_f_locals(*args, **kwargs)
|
| 196 |
+
assert self._artifacts.guard_manager is not None
|
| 197 |
+
return self._artifacts.guard_manager.check(f_locals)
|
| 198 |
+
|
| 199 |
+
def __post_init__(self) -> None:
|
| 200 |
+
from .package import load_guard_manager, load_guards_state
|
| 201 |
+
|
| 202 |
+
self._artifacts.check_compatibility()
|
| 203 |
+
|
| 204 |
+
self.fn = self._artifacts.runtime_env.forward_callable(
|
| 205 |
+
self._artifacts.backend_id,
|
| 206 |
+
self._artifacts.compiled_fn,
|
| 207 |
+
extra_globals=self._extra_globals,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
if self._artifacts.guard_manager is None:
|
| 211 |
+
guards_state = load_guards_state(self._artifacts.guards_state)
|
| 212 |
+
self._artifacts.guard_manager = load_guard_manager(
|
| 213 |
+
guards_state,
|
| 214 |
+
self._artifacts.original_code,
|
| 215 |
+
self.fn.__globals__,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 219 |
+
assert self._artifacts.guard_manager is not None
|
| 220 |
+
if self._guard_check_enabled and not self.guard_check(*args, **kwargs):
|
| 221 |
+
f_locals = self.prepare_f_locals(*args, **kwargs)
|
| 222 |
+
reason = str(self._artifacts.guard_manager.check_verbose(f_locals))
|
| 223 |
+
raise RuntimeError(f"GuardManager check failed, reason: {reason}")
|
| 224 |
+
return self.fn(*args, **kwargs)
|
| 225 |
+
|
| 226 |
+
def source_info(self) -> "SourceInfo":
|
| 227 |
+
return self._artifacts.source_info
|
| 228 |
+
|
| 229 |
+
def save_compiled_function(
|
| 230 |
+
self, path: str, external_data: dict[str, Any] | None = None
|
| 231 |
+
) -> AOTCompileSaveResult:
|
| 232 |
+
with open(path, "wb") as f:
|
| 233 |
+
result = type(self).serialize(self, external_data)
|
| 234 |
+
f.write(result.serialized_data)
|
| 235 |
+
return result
|
| 236 |
+
|
| 237 |
+
@classmethod
|
| 238 |
+
def serialize(
|
| 239 |
+
cls, fn: "AOTCompiledFunction", external_data: dict[str, Any] | None = None
|
| 240 |
+
) -> AOTCompileSaveResult:
|
| 241 |
+
from torch._dynamo.package import SerializedCode
|
| 242 |
+
|
| 243 |
+
state = fn._artifacts.__dict__.copy()
|
| 244 |
+
state["guard_manager"] = None
|
| 245 |
+
state["runtime_env"] = dataclasses.replace(
|
| 246 |
+
state["runtime_env"],
|
| 247 |
+
bytecode=SerializedCode.from_code_object(state["runtime_env"].bytecode),
|
| 248 |
+
)
|
| 249 |
+
compiled_fn = state["compiled_fn"]
|
| 250 |
+
state["compiled_fn"] = (
|
| 251 |
+
type(compiled_fn).deserialize_compile_artifacts,
|
| 252 |
+
type(compiled_fn).serialize_compile_artifacts(compiled_fn),
|
| 253 |
+
)
|
| 254 |
+
state["original_code"] = SerializedCode.from_code_object(state["original_code"])
|
| 255 |
+
buf = io.BytesIO()
|
| 256 |
+
pickler = AOTCompilePickler(external_data or {}, buf)
|
| 257 |
+
pickler.dump(state)
|
| 258 |
+
if pickler.errors:
|
| 259 |
+
raise RuntimeError(
|
| 260 |
+
f"Failed to serialize the following objects: {list(pickler.errors.values())}\n"
|
| 261 |
+
"Please mark these as external data by using `external_data={'key': ...}`"
|
| 262 |
+
)
|
| 263 |
+
return AOTCompileSaveResult(serialized_data=buf.getvalue())
|
| 264 |
+
|
| 265 |
+
@classmethod
|
| 266 |
+
def deserialize(
|
| 267 |
+
cls,
|
| 268 |
+
data: bytes,
|
| 269 |
+
f_globals: dict[str, object] | None = None,
|
| 270 |
+
external_closure_data: dict[str, Any] | None = None,
|
| 271 |
+
) -> "AOTCompiledFunction":
|
| 272 |
+
from torch._dynamo.package import SerializedCode
|
| 273 |
+
|
| 274 |
+
f = io.BytesIO(data)
|
| 275 |
+
f.seek(0)
|
| 276 |
+
unpickler = AOTCompileUnpickler(external_closure_data or {}, f)
|
| 277 |
+
state = unpickler.load()
|
| 278 |
+
f.close()
|
| 279 |
+
state["runtime_env"] = dataclasses.replace(
|
| 280 |
+
state["runtime_env"],
|
| 281 |
+
bytecode=SerializedCode.to_code_object(state["runtime_env"].bytecode),
|
| 282 |
+
)
|
| 283 |
+
deserializer, compiled_fn_state = state["compiled_fn"]
|
| 284 |
+
with torch._inductor.config.patch(enable_autograd_for_aot=True):
|
| 285 |
+
state["compiled_fn"] = deserializer(compiled_fn_state)
|
| 286 |
+
state["original_code"] = SerializedCode.to_code_object(state["original_code"])
|
| 287 |
+
|
| 288 |
+
artifacts = CompileArtifacts(**state)
|
| 289 |
+
return cls(artifacts, _extra_globals=f_globals)
|
| 290 |
+
|
| 291 |
+
def disable_guard_check(self) -> None:
|
| 292 |
+
self._guard_check_enabled = False
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def aot_compile_fullgraph(
|
| 296 |
+
model: Any,
|
| 297 |
+
example_inputs: tuple[tuple[Any, ...], dict[str, Any]],
|
| 298 |
+
hooks: Hooks,
|
| 299 |
+
backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable],
|
| 300 |
+
dynamic: bool | None = None,
|
| 301 |
+
) -> AOTCompiledFunction:
|
| 302 |
+
from torch._dynamo.guards import CheckFunctionManager
|
| 303 |
+
from torch._dynamo.package import SourceInfo
|
| 304 |
+
from torch._dynamo.utils import dynamo_timed, get_metrics_context
|
| 305 |
+
from torch._guards import TracingContext
|
| 306 |
+
|
| 307 |
+
args, kwargs = example_inputs
|
| 308 |
+
|
| 309 |
+
dynamic_ctx = nullcontext()
|
| 310 |
+
if dynamic is not None:
|
| 311 |
+
from torch._dynamo.eval_frame import set_enable_dynamic
|
| 312 |
+
|
| 313 |
+
dynamic_ctx = set_enable_dynamic(dynamic)
|
| 314 |
+
|
| 315 |
+
with (
|
| 316 |
+
get_metrics_context(),
|
| 317 |
+
dynamo_timed("fullgraph_capture"),
|
| 318 |
+
torch._functorch.config.patch(strict_autograd_cache=True),
|
| 319 |
+
dynamic_ctx,
|
| 320 |
+
):
|
| 321 |
+
capture_output = convert_frame.fullgraph_capture(model, args, kwargs)
|
| 322 |
+
graph_capture_output = capture_output.graph_capture_output
|
| 323 |
+
assert graph_capture_output.output_graph is not None
|
| 324 |
+
|
| 325 |
+
if not hooks.guard_filter_fn:
|
| 326 |
+
from torch._dynamo.types import GuardFilterEntry
|
| 327 |
+
|
| 328 |
+
def new_guard_filter_fn(
|
| 329 |
+
guard_entries: Sequence[GuardFilterEntry],
|
| 330 |
+
) -> Sequence[bool]:
|
| 331 |
+
return [
|
| 332 |
+
(
|
| 333 |
+
not (
|
| 334 |
+
g.is_global
|
| 335 |
+
or g.guard_type
|
| 336 |
+
in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES
|
| 337 |
+
)
|
| 338 |
+
)
|
| 339 |
+
for g in guard_entries
|
| 340 |
+
]
|
| 341 |
+
|
| 342 |
+
hooks.guard_filter_fn = new_guard_filter_fn
|
| 343 |
+
|
| 344 |
+
fn, _ = convert_frame.get_traced_fn(model)
|
| 345 |
+
|
| 346 |
+
backend_input = capture_output.backend_input
|
| 347 |
+
assert backend_input is not None
|
| 348 |
+
backend_input.graph_module._backend_id = backend_input.backend_id # type: ignore[assignment]
|
| 349 |
+
device_type = _graph_device_type(backend_input.graph_module.graph)
|
| 350 |
+
assert (
|
| 351 |
+
backend_input.fake_mode.shape_env
|
| 352 |
+
is graph_capture_output.output_graph.shape_env
|
| 353 |
+
)
|
| 354 |
+
tracing_context = TracingContext(backend_input.fake_mode)
|
| 355 |
+
tracing_context.tensor_to_context = backend_input.tensor_to_context
|
| 356 |
+
with (
|
| 357 |
+
torch._guards.tracing(tracing_context),
|
| 358 |
+
torch._functorch.config.patch(
|
| 359 |
+
{
|
| 360 |
+
"strict_autograd_cache": True,
|
| 361 |
+
"bypass_autograd_cache_key": True,
|
| 362 |
+
"bundled_autograd_cache": True,
|
| 363 |
+
"force_non_lazy_backward_lowering": True,
|
| 364 |
+
"force_autograd_cache": True,
|
| 365 |
+
}
|
| 366 |
+
),
|
| 367 |
+
):
|
| 368 |
+
compiled_fn = backend(
|
| 369 |
+
backend_input.graph_module, backend_input.example_inputs
|
| 370 |
+
)
|
| 371 |
+
# If Inductor backend is used, grab the compiled_fn from PrecompileContext
|
| 372 |
+
# TODO: this should be replaced once we make the backend return the SerializableCallable directly.
|
| 373 |
+
if isinstance(backend, torch._TorchCompileInductorWrapper) or (
|
| 374 |
+
hasattr(backend, "compiler_fn")
|
| 375 |
+
and isinstance(
|
| 376 |
+
backend.compiler_fn, torch._dynamo.backends.common.AotAutograd
|
| 377 |
+
)
|
| 378 |
+
):
|
| 379 |
+
compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn)
|
| 380 |
+
|
| 381 |
+
if not isinstance(compiled_fn, SerializableCallable):
|
| 382 |
+
if hasattr(backend, "compiler_fn"):
|
| 383 |
+
compiler_fn = backend.compiler_fn
|
| 384 |
+
else:
|
| 385 |
+
compiler_fn = backend
|
| 386 |
+
raise RuntimeError(
|
| 387 |
+
f"Compiled function type {type(compiled_fn)} (produced "
|
| 388 |
+
+ f"from backend {compiler_fn}) does not implement SerializableCallable."
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
check_fn = graph_capture_output.build_guards(
|
| 392 |
+
fn.__code__, hooks=hooks, save=True, strict_error=True
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
assert check_fn.guards_state is not None
|
| 396 |
+
|
| 397 |
+
source_info = SourceInfo(inlined_sources=set())
|
| 398 |
+
for traced_code in graph_capture_output.traced_code:
|
| 399 |
+
source_info.add_code(traced_code)
|
| 400 |
+
|
| 401 |
+
artifacts = CompileArtifacts(
|
| 402 |
+
signature=convert_frame._get_signature(fn),
|
| 403 |
+
guard_manager=check_fn.guard_manager,
|
| 404 |
+
guards_state=check_fn.guards_state,
|
| 405 |
+
backend_id=backend_input.backend_id,
|
| 406 |
+
compiled_fn=compiled_fn,
|
| 407 |
+
original_code=fn.__code__,
|
| 408 |
+
runtime_env=graph_capture_output.get_runtime_env(),
|
| 409 |
+
source_info=source_info,
|
| 410 |
+
device_type=device_type,
|
| 411 |
+
backend_name=getattr(backend, "compiler_name", "unknown"),
|
| 412 |
+
)
|
| 413 |
+
aot_compiled_fn = AOTCompiledFunction(
|
| 414 |
+
_artifacts=artifacts, _extra_globals=fn.__globals__
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
return aot_compiled_fn
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@dataclass
|
| 421 |
+
class ModelInput:
|
| 422 |
+
"""
|
| 423 |
+
WIP type: represents a single model input
|
| 424 |
+
Which consists of a tuple of arguments and a set of contexts in which to run the model.
|
| 425 |
+
|
| 426 |
+
For each ModelInput, we'll compile one full graph of the model, and then use the guards generated
|
| 427 |
+
to dispatch between the compiled graphs.
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
"""
|
| 431 |
+
|
| 432 |
+
args: tuple[Any]
|
| 433 |
+
kwargs: dict[str, Any]
|
| 434 |
+
contexts: list[AbstractContextManager[Any]]
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
@dataclass
|
| 438 |
+
class AOTCompiledModel:
|
| 439 |
+
# Represents a single forward function of a model along with dispatch
|
| 440 |
+
# compiled_results is serializable. We require the model to deserialize again.
|
| 441 |
+
model: torch.nn.Module
|
| 442 |
+
compiled_results: list[AOTCompiledFunction]
|
| 443 |
+
|
| 444 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 445 |
+
for result in self.compiled_results:
|
| 446 |
+
if result.guard_check(self.model, *args, **kwargs):
|
| 447 |
+
return result(self.model, *args, **kwargs)
|
| 448 |
+
# All guards failed, just run one of them and throw the guard check error.
|
| 449 |
+
return self.compiled_results[0](self.model, *args, **kwargs)
|
| 450 |
+
|
| 451 |
+
def serialize(self) -> bytes:
|
| 452 |
+
data: list[bytes] = []
|
| 453 |
+
for result in self.compiled_results:
|
| 454 |
+
data.append(AOTCompiledFunction.serialize(result).serialized_data)
|
| 455 |
+
return pickle.dumps(data)
|
| 456 |
+
|
| 457 |
+
@classmethod
|
| 458 |
+
def deserialize(cls, model: torch.nn.Module, data: bytes) -> "AOTCompiledModel":
|
| 459 |
+
from torch._dynamo.utils import get_metrics_context
|
| 460 |
+
from torch._guards import compile_context, CompileContext
|
| 461 |
+
|
| 462 |
+
results: list[bytes] = pickle.loads(data)
|
| 463 |
+
compiled_results = []
|
| 464 |
+
for result in results:
|
| 465 |
+
with (
|
| 466 |
+
compile_context(CompileContext(convert_frame.get_compile_id({}))),
|
| 467 |
+
get_metrics_context(),
|
| 468 |
+
):
|
| 469 |
+
compiled_results.append(AOTCompiledFunction.deserialize(result))
|
| 470 |
+
return cls(model, compiled_results)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def aot_compile_module(
|
| 474 |
+
model: torch.nn.Module,
|
| 475 |
+
inputs: list[ModelInput],
|
| 476 |
+
hooks: Hooks,
|
| 477 |
+
backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable],
|
| 478 |
+
) -> AOTCompiledModel:
|
| 479 |
+
"""
|
| 480 |
+
Compiles a single nn.Module with any number of inputs, and returns a compiled forward function.
|
| 481 |
+
"""
|
| 482 |
+
|
| 483 |
+
def compile_single_graph(model_input: ModelInput) -> AOTCompiledFunction:
|
| 484 |
+
example_inputs = (model_input.args, model_input.kwargs)
|
| 485 |
+
orig_forward = model.forward
|
| 486 |
+
with ExitStack() as stack:
|
| 487 |
+
for ctx in model_input.contexts:
|
| 488 |
+
stack.enter_context(ctx)
|
| 489 |
+
return aot_compile_fullgraph(
|
| 490 |
+
orig_forward,
|
| 491 |
+
example_inputs,
|
| 492 |
+
hooks=hooks,
|
| 493 |
+
backend=backend,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
# pyrefly: ignore [implicit-any]
|
| 497 |
+
compiled_results = []
|
| 498 |
+
for model_input in inputs:
|
| 499 |
+
log.info("Compiling input %s..", model_input)
|
| 500 |
+
compiled_results.append(compile_single_graph(model_input))
|
| 501 |
+
|
| 502 |
+
assert len(compiled_results) > 0
|
| 503 |
+
|
| 504 |
+
return AOTCompiledModel(model, compiled_results)
|
.venv/lib/python3.10/site-packages/torch/_dynamo/aot_compile_types.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import importlib
|
| 3 |
+
import pickle
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _serialize_triton_kernel(kernel: Any) -> tuple[str, str]:
|
| 10 |
+
"""
|
| 11 |
+
Serialize a triton kernel by extracting its module path and function name.
|
| 12 |
+
Returns (module_path, function_name) tuple.
|
| 13 |
+
|
| 14 |
+
Triton JITFunction objects contain unpicklable _thread.RLock objects, so we
|
| 15 |
+
serialize the import path instead and reimport on load.
|
| 16 |
+
|
| 17 |
+
Raises:
|
| 18 |
+
RuntimeError: If the kernel cannot be serialized (missing attributes).
|
| 19 |
+
"""
|
| 20 |
+
fn = getattr(kernel, "fn", None)
|
| 21 |
+
module_path = fn and getattr(fn, "__module__", None)
|
| 22 |
+
func_name = fn and getattr(fn, "__name__", None)
|
| 23 |
+
if fn is None or module_path is None or func_name is None:
|
| 24 |
+
raise RuntimeError(
|
| 25 |
+
f"Kernel fn missing __module__ or __name__: "
|
| 26 |
+
f"module={module_path}, name={func_name}. "
|
| 27 |
+
f"Cannot serialize for precompilation."
|
| 28 |
+
)
|
| 29 |
+
return (module_path, func_name)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _deserialize_triton_kernel(kernel_info: tuple[str, str]) -> Any:
|
| 33 |
+
"""
|
| 34 |
+
Deserialize a triton kernel by reimporting from its module.
|
| 35 |
+
kernel_info is (module_path, function_name) tuple.
|
| 36 |
+
"""
|
| 37 |
+
module_path, func_name = kernel_info
|
| 38 |
+
module = importlib.import_module(module_path)
|
| 39 |
+
kernel = getattr(module, func_name)
|
| 40 |
+
return kernel
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Note: [Triton Kernel Side Table Serialization]
|
| 44 |
+
#
|
| 45 |
+
# When dynamo captures user-defined triton kernels, it creates FX graph nodes
|
| 46 |
+
# (triton_kernel_wrapper_mutation/functional) with a `kernel_idx` parameter that
|
| 47 |
+
# references the global `kernel_side_table` in triton_kernel_wrap.py. This side
|
| 48 |
+
# table maps integer indices to actual triton kernel objects.
|
| 49 |
+
#
|
| 50 |
+
# For kernels that go through inductor's codegen path, this is fine - inductor
|
| 51 |
+
# looks up the kernel from the side table at codegen time and embeds the kernel
|
| 52 |
+
# source code directly into the generated wrapper. The compiled code doesn't
|
| 53 |
+
# need the side table at runtime.
|
| 54 |
+
#
|
| 55 |
+
# However, not all triton kernels go through inductor codegen. When using
|
| 56 |
+
# regional_inductor, only annotated regions are compiled by inductor. Triton
|
| 57 |
+
# kernels outside these regions are executed via the FX interpreter, which
|
| 58 |
+
# calls the higher-order op directly and needs the kernel to be in the side
|
| 59 |
+
# table at runtime.
|
| 60 |
+
#
|
| 61 |
+
# When serializing/deserializing bundled AOT artifacts across process boundaries,
|
| 62 |
+
# the kernel_side_table is empty in the new process, causing:
|
| 63 |
+
# AssertionError: Kernel index X not found in id_to_kernel
|
| 64 |
+
#
|
| 65 |
+
# To fix this, we capture the kernel_side_table state during serialization and
|
| 66 |
+
# restore it during deserialization. Kernels are serialized by their import path
|
| 67 |
+
# (module_path, function_name) since triton JITFunction objects contain
|
| 68 |
+
# unpicklable RLock objects.
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class SerializableCallable(abc.ABC):
|
| 72 |
+
@classmethod
|
| 73 |
+
@abc.abstractmethod
|
| 74 |
+
def serialize_compile_artifacts(cls, fn: Any) -> bytes:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
@abc.abstractmethod
|
| 79 |
+
def deserialize_compile_artifacts(cls, data: bytes) -> Any:
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
@abc.abstractmethod
|
| 83 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class GraphModuleSerializableCallable(SerializableCallable):
|
| 88 |
+
def __init__(self, graph_module: torch.fx.GraphModule) -> None:
|
| 89 |
+
assert isinstance(graph_module, torch.fx.GraphModule)
|
| 90 |
+
self.graph_module = graph_module
|
| 91 |
+
|
| 92 |
+
@classmethod
|
| 93 |
+
def serialize_compile_artifacts(
|
| 94 |
+
cls, fn: "GraphModuleSerializableCallable"
|
| 95 |
+
) -> bytes:
|
| 96 |
+
from torch.fx._graph_pickler import GraphPickler, Options
|
| 97 |
+
|
| 98 |
+
state = fn.__dict__.copy()
|
| 99 |
+
|
| 100 |
+
graph_module = state["graph_module"]
|
| 101 |
+
for node in graph_module.graph.nodes:
|
| 102 |
+
node.meta.pop("nn_module_stack", None)
|
| 103 |
+
node.meta.pop("source_fn_stack", None)
|
| 104 |
+
node.meta.pop("example_value", None)
|
| 105 |
+
|
| 106 |
+
state["graph_module"] = GraphPickler.dumps(
|
| 107 |
+
graph_module, Options(ops_filter=None)
|
| 108 |
+
)
|
| 109 |
+
return pickle.dumps(state)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def deserialize_compile_artifacts(cls, data: bytes) -> Any:
|
| 113 |
+
from torch._subclasses import FakeTensorMode
|
| 114 |
+
from torch.fx._graph_pickler import GraphPickler
|
| 115 |
+
from torch.fx.experimental.symbolic_shapes import ShapeEnv
|
| 116 |
+
|
| 117 |
+
state = pickle.loads(data)
|
| 118 |
+
|
| 119 |
+
fake_mode = FakeTensorMode(shape_env=ShapeEnv())
|
| 120 |
+
state["graph_module"] = GraphPickler.loads(state["graph_module"], fake_mode)
|
| 121 |
+
assert isinstance(state["graph_module"], torch.fx.GraphModule)
|
| 122 |
+
state["graph_module"].recompile()
|
| 123 |
+
|
| 124 |
+
return cls(**state)
|
| 125 |
+
|
| 126 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 127 |
+
return self.graph_module.forward(*args, **kwargs)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class BundledAOTAutogradSerializableCallable(SerializableCallable):
|
| 131 |
+
"""
|
| 132 |
+
Represents a serializable callable generated by compile_fx.
|
| 133 |
+
This class wraps around the compiled function generated by AOTAutograd.
|
| 134 |
+
|
| 135 |
+
TODO: Instead of using PrecompileContext to grab it from AOTAutograd,
|
| 136 |
+
this object should be what's *returned* by aot_module_simplified.
|
| 137 |
+
We'll do that refactor in a later PR.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
def __init__(self, compiled_fn: Any) -> None:
|
| 141 |
+
"""
|
| 142 |
+
Takes in a BundledAOTAutogradCacheArtifact, which is the serialized form
|
| 143 |
+
of a compiled function generated by AOTAutograd.
|
| 144 |
+
"""
|
| 145 |
+
assert hasattr(compiled_fn, "serialize")
|
| 146 |
+
self.compiled_fn = compiled_fn
|
| 147 |
+
|
| 148 |
+
def __getattr__(self, attr: Any) -> Any:
|
| 149 |
+
return getattr(self.compiled_fn, attr)
|
| 150 |
+
|
| 151 |
+
@classmethod
|
| 152 |
+
def serialize_compile_artifacts(
|
| 153 |
+
cls, fn: "BundledAOTAutogradSerializableCallable"
|
| 154 |
+
) -> bytes:
|
| 155 |
+
from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table
|
| 156 |
+
|
| 157 |
+
# See Note: [Triton Kernel Side Table Serialization]
|
| 158 |
+
# Capture triton kernel side table state BEFORE serialization.
|
| 159 |
+
triton_kernels: dict[int, tuple[str, str]] = {
|
| 160 |
+
idx: _serialize_triton_kernel(kernel)
|
| 161 |
+
for idx, kernel in kernel_side_table.id_to_kernel.items()
|
| 162 |
+
}
|
| 163 |
+
triton_constant_args: dict[int, dict[str, Any]] = dict(
|
| 164 |
+
kernel_side_table.constant_args
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
with torch._functorch.config.patch("bundled_autograd_cache", True):
|
| 168 |
+
serialized_entry = fn.compiled_fn.serialize()
|
| 169 |
+
# Bundle the triton kernel side table with the serialized entry
|
| 170 |
+
bundle = (serialized_entry, triton_kernels, triton_constant_args)
|
| 171 |
+
result = pickle.dumps(bundle)
|
| 172 |
+
return result
|
| 173 |
+
|
| 174 |
+
@classmethod
|
| 175 |
+
def deserialize_compile_artifacts(cls, data: bytes) -> Any:
|
| 176 |
+
from torch._functorch._aot_autograd.aot_autograd_result import (
|
| 177 |
+
deserialize_bundled_cache_entry,
|
| 178 |
+
)
|
| 179 |
+
from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table
|
| 180 |
+
|
| 181 |
+
bundle = pickle.loads(data)
|
| 182 |
+
|
| 183 |
+
# Handle both old format (just entry) and new format (entry, kernels, const_args)
|
| 184 |
+
if isinstance(bundle, tuple) and len(bundle) == 3:
|
| 185 |
+
entry, triton_kernels, triton_constant_args = bundle
|
| 186 |
+
else:
|
| 187 |
+
# Backwards compatibility with old serialized artifacts
|
| 188 |
+
entry = bundle
|
| 189 |
+
# pyrefly: ignore [implicit-any]
|
| 190 |
+
triton_kernels = {}
|
| 191 |
+
# pyrefly: ignore [implicit-any]
|
| 192 |
+
triton_constant_args = {}
|
| 193 |
+
|
| 194 |
+
# See Note: [Triton Kernel Side Table Serialization]
|
| 195 |
+
# Restore triton kernel side table BEFORE deserializing the compiled function.
|
| 196 |
+
# The compiled function may reference kernels by index if any triton kernels
|
| 197 |
+
# don't go through inductor codegen (e.g., triton kernels outside of
|
| 198 |
+
# regional_inductor compiled regions).
|
| 199 |
+
for idx, kernel_info in triton_kernels.items():
|
| 200 |
+
kernel = _deserialize_triton_kernel(kernel_info)
|
| 201 |
+
kernel_side_table.id_to_kernel[idx] = kernel
|
| 202 |
+
kernel_side_table.kernel_to_id[kernel] = idx
|
| 203 |
+
|
| 204 |
+
for idx, args in triton_constant_args.items():
|
| 205 |
+
kernel_side_table.constant_args[idx] = args
|
| 206 |
+
|
| 207 |
+
compiled_fn = deserialize_bundled_cache_entry(entry)
|
| 208 |
+
return cls(compiled_fn)
|
| 209 |
+
|
| 210 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 211 |
+
return self.compiled_fn(*args, **kwargs)
|
.venv/lib/python3.10/site-packages/torch/_dynamo/backends/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.10/site-packages/torch/_dynamo/backends/common.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides common utilities and base classes for TorchDynamo backends.
|
| 3 |
+
|
| 4 |
+
Key components:
|
| 5 |
+
- AotAutograd: Base class for implementing AOT (Ahead-of-Time) autograd backends
|
| 6 |
+
- Backend utilities for handling:
|
| 7 |
+
- Fake tensor conversion
|
| 8 |
+
- Device/dtype detection from inputs
|
| 9 |
+
- Memory efficient fusion
|
| 10 |
+
- Graph flattening
|
| 11 |
+
- Common compiler configurations
|
| 12 |
+
|
| 13 |
+
The utilities here are used by various backend implementations to handle
|
| 14 |
+
common operations and provide consistent behavior across different backends.
|
| 15 |
+
AOT autograd functionality is particularly important as it enables ahead-of-time
|
| 16 |
+
optimization of both forward and backward passes.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import contextlib
|
| 20 |
+
import functools
|
| 21 |
+
import logging
|
| 22 |
+
from collections.abc import Callable, Iterable
|
| 23 |
+
from typing import Any
|
| 24 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 25 |
+
from unittest.mock import patch
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
from torch._dynamo import disable
|
| 29 |
+
from torch._dynamo.exc import TensorifyScalarRestartAnalysis
|
| 30 |
+
from torch._dynamo.utils import counters, defake, flatten_graph_inputs
|
| 31 |
+
from torch._functorch.aot_autograd import (
|
| 32 |
+
aot_module_simplified,
|
| 33 |
+
SerializableAOTDispatchCompiler,
|
| 34 |
+
)
|
| 35 |
+
from torch.utils._python_dispatch import _disable_current_modes
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
log = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
P = ParamSpec("P")
|
| 41 |
+
R = TypeVar("R")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class AotAutograd:
|
| 45 |
+
def __init__(self, **kwargs: Any) -> None:
|
| 46 |
+
self.__name__ = "compiler_fn"
|
| 47 |
+
self.kwargs = kwargs
|
| 48 |
+
|
| 49 |
+
def __call__(
|
| 50 |
+
self, gm: torch.fx.GraphModule, example_inputs: Iterable[Any], **kwargs: Any
|
| 51 |
+
) -> Callable[..., Any]:
|
| 52 |
+
if kwargs:
|
| 53 |
+
log.warning("aot_autograd-based backend ignoring extra kwargs %s", kwargs)
|
| 54 |
+
|
| 55 |
+
if any(isinstance(x, (list, tuple, dict)) for x in example_inputs):
|
| 56 |
+
return flatten_graph_inputs(
|
| 57 |
+
gm,
|
| 58 |
+
example_inputs,
|
| 59 |
+
self,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Hack to get around circular import problems with aot_eager_decomp_partition
|
| 63 |
+
if callable(self.kwargs.get("decompositions")):
|
| 64 |
+
self.kwargs["decompositions"] = self.kwargs["decompositions"]()
|
| 65 |
+
|
| 66 |
+
# NB: dont delete counter increment
|
| 67 |
+
counters["aot_autograd"]["total"] += 1
|
| 68 |
+
use_fallback = False
|
| 69 |
+
|
| 70 |
+
if use_fallback:
|
| 71 |
+
log.debug("Unable to use AOT Autograd because graph has mutation")
|
| 72 |
+
counters["aot_autograd"]["not_ok"] += 1
|
| 73 |
+
# pyrefly: ignore [bad-return]
|
| 74 |
+
return gm
|
| 75 |
+
|
| 76 |
+
def wrap_bw_compiler(bw_compiler_fn: Callable[P, R]) -> Callable[..., R]:
|
| 77 |
+
def _wrapped_bw_compiler(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 78 |
+
# Note [Wrapping bw_compiler in disable]
|
| 79 |
+
# The two disables here:
|
| 80 |
+
# - stop TorchDynamo from trying to compile the bw_compiler function itself
|
| 81 |
+
# - stop TorchDynamo from trying to compile our the generated backwards pass bw_compiler produces
|
| 82 |
+
|
| 83 |
+
return disable(
|
| 84 |
+
disable(
|
| 85 |
+
bw_compiler_fn, reason="do not trace backward compiler function"
|
| 86 |
+
)(*args, **kwargs), # type: ignore[misc]
|
| 87 |
+
reason="do not trace generated backwards pass",
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
_wrapped_bw_compiler._is_wrapped_bw_compiler = ( # pyrefly: ignore [missing-attribute]
|
| 91 |
+
True
|
| 92 |
+
)
|
| 93 |
+
return _wrapped_bw_compiler
|
| 94 |
+
|
| 95 |
+
bw_compiler = self.kwargs.get("bw_compiler") or self.kwargs["fw_compiler"]
|
| 96 |
+
|
| 97 |
+
if isinstance(bw_compiler, SerializableAOTDispatchCompiler):
|
| 98 |
+
bw_compiler.compiler_fn = wrap_bw_compiler(bw_compiler.compiler_fn)
|
| 99 |
+
elif getattr(bw_compiler, "_is_wrapped_bw_compiler", False):
|
| 100 |
+
bw_compiler.compiler_fn = bw_compiler
|
| 101 |
+
else:
|
| 102 |
+
bw_compiler = wrap_bw_compiler(bw_compiler)
|
| 103 |
+
|
| 104 |
+
self.kwargs["bw_compiler"] = bw_compiler
|
| 105 |
+
self.kwargs["inference_compiler"] = (
|
| 106 |
+
self.kwargs.get("inference_compiler") or self.kwargs["fw_compiler"]
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
from functorch.compile import nop
|
| 110 |
+
from torch._inductor.debug import enable_aot_logging
|
| 111 |
+
|
| 112 |
+
# debug asserts slow down compile time noticeably,
|
| 113 |
+
# So only default them on when the aot_eager backend is used.
|
| 114 |
+
if self.kwargs.get("fw_compiler", None) is nop:
|
| 115 |
+
patch_config: contextlib.AbstractContextManager[Any] = patch(
|
| 116 |
+
"functorch.compile.config.debug_assert", True
|
| 117 |
+
)
|
| 118 |
+
else:
|
| 119 |
+
patch_config = contextlib.nullcontext()
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
# NB: NOT cloned!
|
| 123 |
+
with enable_aot_logging(), patch_config:
|
| 124 |
+
cg = aot_module_simplified(gm, example_inputs, **self.kwargs)
|
| 125 |
+
counters["aot_autograd"]["ok"] += 1
|
| 126 |
+
return disable(cg, reason="do not trace AOT-compiled graph")
|
| 127 |
+
except TensorifyScalarRestartAnalysis:
|
| 128 |
+
raise
|
| 129 |
+
except Exception:
|
| 130 |
+
counters["aot_autograd"]["not_ok"] += 1
|
| 131 |
+
raise
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def aot_autograd(**kwargs: Any) -> AotAutograd:
|
| 135 |
+
return AotAutograd(**kwargs)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def mem_efficient_fusion_kwargs(use_decomps: bool) -> dict[str, Any]:
|
| 139 |
+
from functorch.compile import (
|
| 140 |
+
default_decompositions,
|
| 141 |
+
min_cut_rematerialization_partition,
|
| 142 |
+
ts_compile,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
kwargs = {
|
| 146 |
+
# these are taken from memory_efficient_fusion()
|
| 147 |
+
"fw_compiler": ts_compile,
|
| 148 |
+
"bw_compiler": ts_compile,
|
| 149 |
+
"partition_fn": min_cut_rematerialization_partition,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
if use_decomps:
|
| 153 |
+
# pyrefly: ignore [bad-typed-dict-key, unsupported-operation]
|
| 154 |
+
kwargs["decompositions"] = default_decompositions
|
| 155 |
+
|
| 156 |
+
return kwargs
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def fake_tensor_unsupported(fn: Callable[[Any, list[Any], Any], R]) -> Any:
|
| 160 |
+
"""
|
| 161 |
+
Decorator for backends that need real inputs. We swap out fake
|
| 162 |
+
tensors for zero tensors.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
@functools.wraps(fn)
|
| 166 |
+
def wrapper(model: Any, inputs: Any, **kwargs: Any) -> Any:
|
| 167 |
+
with _disable_current_modes():
|
| 168 |
+
inputs = list(map(defake, inputs))
|
| 169 |
+
return fn(model, inputs, **kwargs) # type: ignore[call-arg]
|
| 170 |
+
|
| 171 |
+
return wrapper
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def device_from_inputs(example_inputs: Iterable[Any]) -> torch.device:
|
| 175 |
+
for x in example_inputs:
|
| 176 |
+
if hasattr(x, "device"):
|
| 177 |
+
return x.device
|
| 178 |
+
return torch.device("cpu") # Default fallback
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def dtype_from_inputs(example_inputs: Iterable[Any]) -> torch.dtype:
|
| 182 |
+
for x in example_inputs:
|
| 183 |
+
if hasattr(x, "dtype"):
|
| 184 |
+
return x.dtype
|
| 185 |
+
return torch.float32 # Default fallback
|
.venv/lib/python3.10/site-packages/torch/_dynamo/backends/cudagraphs.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements CUDA graphs support for TorchDynamo backends.
|
| 3 |
+
|
| 4 |
+
CUDA graphs allow for capturing and replaying GPU operations, which can significantly
|
| 5 |
+
reduce CPU overhead in GPU-accelerated PyTorch models. This module provides:
|
| 6 |
+
|
| 7 |
+
- CUDA graph creation and management for both forward and backward passes
|
| 8 |
+
- Input mutation detection and handling
|
| 9 |
+
- Device compatibility checking
|
| 10 |
+
- Stack trace management for debugging
|
| 11 |
+
- Integration with TorchInductor's cudagraph trees
|
| 12 |
+
|
| 13 |
+
The backend supports two main modes:
|
| 14 |
+
1. cudagraphs: Full CUDA graph support with both forward and backward pass optimization
|
| 15 |
+
2. cudagraphs_inner: Lower-level CUDA graph implementation used for benchmarking
|
| 16 |
+
|
| 17 |
+
Key components:
|
| 18 |
+
- CudagraphsBackend: Main backend class for CUDA graph integration
|
| 19 |
+
- Mutation detection utilities to ensure graph safety
|
| 20 |
+
- Device mapping and compatibility checks
|
| 21 |
+
- Stack trace collection for debugging
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import functools
|
| 25 |
+
from collections import defaultdict
|
| 26 |
+
from collections.abc import Callable, Sequence
|
| 27 |
+
from typing import Any, Optional
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
import torch.fx
|
| 31 |
+
from torch._dynamo import config
|
| 32 |
+
from torch._dynamo.backends.common import aot_autograd
|
| 33 |
+
from torch._dynamo.backends.debugging import boxed_nop
|
| 34 |
+
from torch._inductor.cudagraph_utils import (
|
| 35 |
+
BoxedDeviceIndex,
|
| 36 |
+
check_multiple_devices_or_any_cpu_nodes,
|
| 37 |
+
format_default_skip_message,
|
| 38 |
+
get_mutation_stack_trace,
|
| 39 |
+
get_placeholder_info,
|
| 40 |
+
log_cudagraph_skip_and_bump_counter,
|
| 41 |
+
)
|
| 42 |
+
from torch._inductor.utils import (
|
| 43 |
+
BoxedBool,
|
| 44 |
+
count_tangents,
|
| 45 |
+
get_first_incompatible_cudagraph_node,
|
| 46 |
+
num_fw_fixed_arguments,
|
| 47 |
+
output_node,
|
| 48 |
+
)
|
| 49 |
+
from torch.multiprocessing.reductions import StorageWeakRef
|
| 50 |
+
|
| 51 |
+
from .registry import register_backend
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def find_input_mutations(g: torch.fx.Graph) -> set[int]:
|
| 55 |
+
def meta_fk(meta: dict[str, Any]) -> Any:
|
| 56 |
+
return meta["val"] if "val" in meta else meta["fake_result"]
|
| 57 |
+
|
| 58 |
+
inputs = defaultdict(set)
|
| 59 |
+
input_idx = 0
|
| 60 |
+
mutated_inputs = set()
|
| 61 |
+
for n in g.nodes:
|
| 62 |
+
if n.op == "placeholder":
|
| 63 |
+
if isinstance(meta_fk(n.meta), torch.Tensor):
|
| 64 |
+
inputs[StorageWeakRef(meta_fk(n.meta)._typed_storage())].add(input_idx)
|
| 65 |
+
input_idx += 1
|
| 66 |
+
elif n.op == "call_function":
|
| 67 |
+
if not hasattr(n.target, "_schema"):
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
schema = n.target._schema
|
| 71 |
+
for i, arg in enumerate(schema.arguments):
|
| 72 |
+
if i < len(n.args):
|
| 73 |
+
argument = n.args[i]
|
| 74 |
+
else:
|
| 75 |
+
if arg.name not in n.kwargs:
|
| 76 |
+
continue
|
| 77 |
+
argument = n.kwargs[arg.name]
|
| 78 |
+
mut_arg = False
|
| 79 |
+
if arg.alias_info:
|
| 80 |
+
if arg.alias_info.is_write:
|
| 81 |
+
mut_arg = True
|
| 82 |
+
if mut_arg:
|
| 83 |
+
# TODO: not correct for args that contain tensors in a struct
|
| 84 |
+
# like list
|
| 85 |
+
mutated_inputs |= inputs[
|
| 86 |
+
StorageWeakRef(meta_fk(argument.meta)._typed_storage())
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
# TODO: error on unrecognized nodes
|
| 90 |
+
return mutated_inputs
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get_device_node_mapping(
|
| 94 |
+
gm: torch.fx.GraphModule,
|
| 95 |
+
) -> dict[torch.device, torch.fx.Node]:
|
| 96 |
+
device_node_mapping: dict[torch.device, torch.fx.Node] = {}
|
| 97 |
+
for n in gm.graph.nodes:
|
| 98 |
+
t = n.meta.get("val", None)
|
| 99 |
+
if isinstance(t, torch.Tensor) and t.device not in device_node_mapping:
|
| 100 |
+
device_node_mapping[t.device] = n
|
| 101 |
+
return device_node_mapping
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def check_for_mutation_ignore_cuda_graph_managed_tensor(
|
| 105 |
+
aot_model: torch.fx.GraphModule, num_fixed: int
|
| 106 |
+
) -> Optional[str]:
|
| 107 |
+
mutation_indices = find_input_mutations(aot_model.graph) - set(range(num_fixed))
|
| 108 |
+
if not mutation_indices:
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
placeholders = get_placeholder_info(aot_model.graph)
|
| 112 |
+
return get_mutation_stack_trace(placeholders, mutation_indices)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def check_for_skip(aot_model: torch.fx.GraphModule, num_fixed: int) -> Optional[str]:
|
| 116 |
+
if not config.cudagraph_backend_support_input_mutation:
|
| 117 |
+
if mut_skip := check_for_mutation_ignore_cuda_graph_managed_tensor(
|
| 118 |
+
aot_model, num_fixed
|
| 119 |
+
):
|
| 120 |
+
return mut_skip
|
| 121 |
+
|
| 122 |
+
if skip := check_multiple_devices_or_any_cpu_nodes(
|
| 123 |
+
get_device_node_mapping(aot_model)
|
| 124 |
+
):
|
| 125 |
+
return skip
|
| 126 |
+
|
| 127 |
+
if node := get_first_incompatible_cudagraph_node(aot_model):
|
| 128 |
+
return format_default_skip_message(f"incompatible op ({node.name})")
|
| 129 |
+
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def get_device_index(gm: torch.fx.GraphModule) -> int:
|
| 134 |
+
device = next(iter(get_device_node_mapping(gm)))
|
| 135 |
+
assert device.type == "cuda"
|
| 136 |
+
return device.index
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def get_stack_traces(gm: torch.fx.GraphModule) -> list[Optional[str]]:
|
| 140 |
+
output = output_node(gm)
|
| 141 |
+
assert len(output.args) == 1
|
| 142 |
+
args = output.args[0]
|
| 143 |
+
if not hasattr(args, "__iter__"):
|
| 144 |
+
return []
|
| 145 |
+
return [
|
| 146 |
+
(arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None)
|
| 147 |
+
for arg in args # type: ignore[union-attr]
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def cudagraphs(dynamo_model: torch.fx.GraphModule, dynamo_inputs: Sequence[Any]) -> Any:
|
| 152 |
+
from torch._inductor.cudagraph_trees import cudagraphify_impl
|
| 153 |
+
|
| 154 |
+
do_cudagraphs = BoxedBool(True)
|
| 155 |
+
boxed_device_index = BoxedDeviceIndex(None)
|
| 156 |
+
|
| 157 |
+
def forward_cudagraphs(
|
| 158 |
+
aot_model: torch.fx.GraphModule,
|
| 159 |
+
aot_inputs: list[Any],
|
| 160 |
+
is_inference: bool = False,
|
| 161 |
+
) -> Any:
|
| 162 |
+
interp = boxed_nop(aot_model, aot_inputs)
|
| 163 |
+
fixed = num_fw_fixed_arguments(len(dynamo_inputs), len(aot_inputs))
|
| 164 |
+
if skip_msg := check_for_skip(aot_model, fixed):
|
| 165 |
+
BoxedBool.disable(do_cudagraphs)
|
| 166 |
+
log_cudagraph_skip_and_bump_counter(
|
| 167 |
+
f"skipping cudagraphs due to {skip_msg}"
|
| 168 |
+
)
|
| 169 |
+
return interp
|
| 170 |
+
|
| 171 |
+
boxed_device_index.set(get_device_index(aot_model))
|
| 172 |
+
out = cudagraphify_impl(
|
| 173 |
+
interp,
|
| 174 |
+
aot_inputs,
|
| 175 |
+
range(fixed),
|
| 176 |
+
device_index=boxed_device_index.value,
|
| 177 |
+
is_backward=False,
|
| 178 |
+
is_inference=is_inference,
|
| 179 |
+
stack_traces=get_stack_traces(aot_model),
|
| 180 |
+
placeholders=get_placeholder_info(aot_model.graph),
|
| 181 |
+
mutated_input_idxs=find_input_mutations(aot_model.graph),
|
| 182 |
+
)
|
| 183 |
+
out._boxed_call = True # type: ignore[attr-defined]
|
| 184 |
+
return out
|
| 185 |
+
|
| 186 |
+
def backward_cudagraphs(
|
| 187 |
+
aot_model: torch.fx.GraphModule, aot_inputs: list[Any]
|
| 188 |
+
) -> Any:
|
| 189 |
+
interp = boxed_nop(aot_model, aot_inputs)
|
| 190 |
+
if not do_cudagraphs:
|
| 191 |
+
return aot_model
|
| 192 |
+
|
| 193 |
+
fixed = count_tangents(aot_model)
|
| 194 |
+
if skip_msg := check_for_skip(aot_model, fixed):
|
| 195 |
+
log_cudagraph_skip_and_bump_counter(
|
| 196 |
+
f"skipping cudagraphs due to {skip_msg}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# See [Backward Generation Handling]
|
| 200 |
+
device_idx = boxed_device_index.value
|
| 201 |
+
if device_idx is None:
|
| 202 |
+
device_idx = 0 # Default to device 0 if not set
|
| 203 |
+
manager = torch._inductor.cudagraph_trees.get_manager(
|
| 204 |
+
device_idx, create_if_none_exists=False
|
| 205 |
+
)
|
| 206 |
+
assert manager is not None
|
| 207 |
+
|
| 208 |
+
def fn(inputs: list[Any]) -> Any:
|
| 209 |
+
# pyrefly: ignore [missing-attribute]
|
| 210 |
+
manager.set_to_running_backward()
|
| 211 |
+
return aot_model(inputs)
|
| 212 |
+
|
| 213 |
+
fn._boxed_call = True # type: ignore[attr-defined]
|
| 214 |
+
return fn
|
| 215 |
+
|
| 216 |
+
out = cudagraphify_impl(
|
| 217 |
+
interp,
|
| 218 |
+
aot_inputs,
|
| 219 |
+
range(fixed),
|
| 220 |
+
device_index=get_device_index(aot_model),
|
| 221 |
+
is_backward=True,
|
| 222 |
+
is_inference=False,
|
| 223 |
+
stack_traces=get_stack_traces(aot_model),
|
| 224 |
+
placeholders=get_placeholder_info(aot_model.graph),
|
| 225 |
+
mutated_input_idxs=find_input_mutations(aot_model.graph),
|
| 226 |
+
)
|
| 227 |
+
out._boxed_call = True # type: ignore[attr-defined]
|
| 228 |
+
return out
|
| 229 |
+
|
| 230 |
+
aot_cudagraphs = aot_autograd(
|
| 231 |
+
fw_compiler=forward_cudagraphs,
|
| 232 |
+
bw_compiler=backward_cudagraphs,
|
| 233 |
+
inference_compiler=functools.partial(forward_cudagraphs, is_inference=True),
|
| 234 |
+
keep_inference_input_mutations=torch._dynamo.config.cudagraph_backend_keep_input_mutation,
|
| 235 |
+
)
|
| 236 |
+
return aot_cudagraphs(dynamo_model, dynamo_inputs)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class CudagraphsBackend:
|
| 240 |
+
compiler_name = "cudagraphs"
|
| 241 |
+
|
| 242 |
+
@staticmethod
|
| 243 |
+
def reset() -> None:
|
| 244 |
+
from torch._inductor.cudagraph_trees import reset_cudagraph_trees
|
| 245 |
+
|
| 246 |
+
reset_cudagraph_trees()
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def __call__(model: torch.fx.GraphModule, inputs: Sequence[Any]) -> Any:
|
| 250 |
+
return cudagraphs(model, inputs)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# aot_cudagraphs only applies CUDA graphs to the graph. It is also helpful
|
| 254 |
+
# for debugging and can serve as a perf baseline.
|
| 255 |
+
register_backend(name="cudagraphs", compiler_fn=CudagraphsBackend())
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def cudagraphs_inner(
|
| 259 |
+
model: Callable[..., Any],
|
| 260 |
+
inputs: Sequence[Any],
|
| 261 |
+
copy_outputs: bool = True,
|
| 262 |
+
copy_inputs: bool = True,
|
| 263 |
+
) -> Callable[..., Sequence[Any]]:
|
| 264 |
+
"""This isn't registered as a backend, but is used in some benchmarks"""
|
| 265 |
+
assert isinstance(inputs, (list, tuple))
|
| 266 |
+
if copy_inputs:
|
| 267 |
+
# pyrefly: ignore [bad-argument-type]
|
| 268 |
+
static_inputs = [torch.zeros_like(x) for x in inputs]
|
| 269 |
+
else:
|
| 270 |
+
static_inputs = list(inputs)
|
| 271 |
+
|
| 272 |
+
# warmup
|
| 273 |
+
torch.cuda.synchronize()
|
| 274 |
+
stream = torch.cuda.Stream()
|
| 275 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 276 |
+
with torch.cuda.stream(stream):
|
| 277 |
+
model(*inputs)
|
| 278 |
+
stream.synchronize()
|
| 279 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 280 |
+
torch.cuda.synchronize()
|
| 281 |
+
|
| 282 |
+
# record
|
| 283 |
+
graph = torch.cuda.CUDAGraph()
|
| 284 |
+
with torch.cuda.graph(graph, stream=stream):
|
| 285 |
+
static_outputs = model(*static_inputs)
|
| 286 |
+
if not isinstance(static_outputs, (list, tuple)):
|
| 287 |
+
static_outputs = (static_outputs,)
|
| 288 |
+
|
| 289 |
+
def run(*new_inputs: Any) -> Sequence[Any]:
|
| 290 |
+
assert len(static_inputs) == len(new_inputs)
|
| 291 |
+
if copy_inputs:
|
| 292 |
+
for dst, src in zip(static_inputs, new_inputs):
|
| 293 |
+
dst.copy_(src)
|
| 294 |
+
graph.replay()
|
| 295 |
+
if copy_outputs:
|
| 296 |
+
return [x.clone() for x in static_outputs]
|
| 297 |
+
else:
|
| 298 |
+
return static_out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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides debugging backends for TorchDynamo to help diagnose and troubleshoot
|
| 3 |
+
compilation and execution issues. It includes:
|
| 4 |
+
|
| 5 |
+
Key Debugging Backends:
|
| 6 |
+
- eager: Simple pass-through backend that runs models in eager mode
|
| 7 |
+
- eager_noexcept: Similar to eager but with additional exception handling
|
| 8 |
+
- eager_debug: Adds schema validation checks for custom operators
|
| 9 |
+
- aot_eager: Uses AOT Autograd with nop compiler for debugging
|
| 10 |
+
- aot_eager_decomp_partition: Uses TorchInductor decompositions for debugging
|
| 11 |
+
- torchscript: Compiles using TorchScript for debugging JIT-related issues
|
| 12 |
+
|
| 13 |
+
Testing and Development Tools:
|
| 14 |
+
- Backends for inducing specific errors (compile/runtime/accuracy)
|
| 15 |
+
- ExplainOutput class for detailed graph compilation analysis
|
| 16 |
+
- Utilities for cross-referencing and mode management
|
| 17 |
+
- Tools for graph detail inspection and break reason analysis
|
| 18 |
+
|
| 19 |
+
These backends are primarily used for:
|
| 20 |
+
1. Debugging graph breaks and compilation failures
|
| 21 |
+
2. Testing error handling and recovery mechanisms
|
| 22 |
+
3. Analyzing performance bottlenecks
|
| 23 |
+
4. Validating operator schemas and decompositions
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import dataclasses
|
| 27 |
+
import functools
|
| 28 |
+
import logging
|
| 29 |
+
from collections.abc import Callable, Iterable
|
| 30 |
+
from importlib import import_module
|
| 31 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
from functorch.compile import min_cut_rematerialization_partition
|
| 35 |
+
from torch import _guards
|
| 36 |
+
from torch._dynamo.output_graph import GraphCompileReason
|
| 37 |
+
from torch._functorch import config as functorch_config
|
| 38 |
+
from torch._functorch.compilers import ts_compile
|
| 39 |
+
|
| 40 |
+
from .common import aot_autograd
|
| 41 |
+
from .registry import CompiledFn, CompilerFn, register_debug_backend as register_backend
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from torch.fx.node import Target
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
log = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@register_backend
|
| 52 |
+
def eager(
|
| 53 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 54 |
+
) -> Callable[..., Any]:
|
| 55 |
+
if kwargs:
|
| 56 |
+
log.warning("eager backend ignoring extra kwargs %s", kwargs)
|
| 57 |
+
|
| 58 |
+
if torch._functorch.config.force_autograd_cache:
|
| 59 |
+
from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable
|
| 60 |
+
|
| 61 |
+
return GraphModuleSerializableCallable(gm)
|
| 62 |
+
return gm.forward
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def make_eager_backend_with_torch_function_mode(
|
| 66 |
+
mode: torch.overrides.TorchFunctionMode,
|
| 67 |
+
) -> Callable[..., Any]:
|
| 68 |
+
return make_eager_backend_with_torch_function_modes([mode])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def make_eager_backend_with_torch_function_modes(
|
| 72 |
+
modes: Iterable[torch.overrides.TorchFunctionMode],
|
| 73 |
+
) -> Callable[..., Any]:
|
| 74 |
+
"""Used to trace HOPs (cond and while) for eager execution, the metadata
|
| 75 |
+
TF mode mutates vars outside of the scope of the HOP, and we can't have graph breaks
|
| 76 |
+
in the HOP, so we need to externally run this mode and not trace it."""
|
| 77 |
+
from contextlib import ExitStack
|
| 78 |
+
|
| 79 |
+
def fn(
|
| 80 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 81 |
+
) -> Callable[..., Any]:
|
| 82 |
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 83 |
+
with ExitStack() as stack:
|
| 84 |
+
for mode in modes:
|
| 85 |
+
stack.enter_context(mode)
|
| 86 |
+
return gm.forward(*args, **kwargs)
|
| 87 |
+
|
| 88 |
+
return wrapper
|
| 89 |
+
|
| 90 |
+
return fn
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@register_backend
|
| 94 |
+
def eager_noexcept(
|
| 95 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 96 |
+
) -> Callable[..., Any]:
|
| 97 |
+
if kwargs:
|
| 98 |
+
log.warning("eager_noexcept backend ignoring extra kwargs %s", kwargs)
|
| 99 |
+
|
| 100 |
+
# This backend is intended to check that dynamo-generated GraphModules
|
| 101 |
+
# do not cause errors.
|
| 102 |
+
def inner(*args: Any) -> Any:
|
| 103 |
+
try:
|
| 104 |
+
return gm(*args)
|
| 105 |
+
except Exception as e:
|
| 106 |
+
raise torch._dynamo.exc.TorchDynamoException(
|
| 107 |
+
"Unexpected exception when running generated GraphModule"
|
| 108 |
+
) from e
|
| 109 |
+
|
| 110 |
+
return inner
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@register_backend
|
| 114 |
+
def pre_dispatch_eager(
|
| 115 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 116 |
+
) -> torch.fx.GraphModule:
|
| 117 |
+
if kwargs:
|
| 118 |
+
log.warning("pre_dispatch_eager backend ignoring extra kwargs %s", kwargs)
|
| 119 |
+
|
| 120 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 121 |
+
|
| 122 |
+
def runnable_gm(*args: Any) -> Any:
|
| 123 |
+
return torch.fx.Interpreter(gm).run(*args)
|
| 124 |
+
|
| 125 |
+
pre_dispatch_gm = make_fx(runnable_gm, pre_dispatch=True)(*fake_tensor_inputs)
|
| 126 |
+
pre_dispatch_gm.print_readable()
|
| 127 |
+
|
| 128 |
+
return pre_dispatch_gm
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@register_backend
|
| 132 |
+
def eager_debug(
|
| 133 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 134 |
+
) -> Callable[..., Any]:
|
| 135 |
+
if kwargs:
|
| 136 |
+
log.warning("eager_debug backend ignoring extra kwargs %s", kwargs)
|
| 137 |
+
|
| 138 |
+
from torch._subclasses.schema_check_mode import SchemaCheckMode
|
| 139 |
+
|
| 140 |
+
# We could add more debugging bits here.
|
| 141 |
+
# Right now, this backend can be used to check for and error on
|
| 142 |
+
# custom dispatcher ops that have incorrect schemas.
|
| 143 |
+
def inner(*args: Any) -> Any:
|
| 144 |
+
with SchemaCheckMode():
|
| 145 |
+
return torch.fx.Interpreter(gm).run(*args)
|
| 146 |
+
|
| 147 |
+
return inner
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@register_backend(name="ts") # type: ignore[misc]
|
| 151 |
+
def torchscript(
|
| 152 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor]
|
| 153 |
+
) -> torch.jit.ScriptModule:
|
| 154 |
+
return torch.jit.script(gm)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def invoke_subgraph_inner_compiler(
|
| 158 |
+
subgraph: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 159 |
+
) -> Callable[..., Any]:
|
| 160 |
+
"""Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP.
|
| 161 |
+
|
| 162 |
+
This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting
|
| 163 |
+
function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining.
|
| 164 |
+
"""
|
| 165 |
+
from torch._dynamo import disable
|
| 166 |
+
from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_infer
|
| 167 |
+
|
| 168 |
+
@disable
|
| 169 |
+
@torch._dynamo.allow_in_graph
|
| 170 |
+
def invoke_subgraph_wrapper_unboxed(*operands: Any) -> Any:
|
| 171 |
+
return invoke_subgraph_infer(subgraph, *operands)
|
| 172 |
+
|
| 173 |
+
# NB: The direct to unboxed path is broken, you MUST DO THIS
|
| 174 |
+
|
| 175 |
+
def invoke_subgraph_wrapper(args: list[Any]) -> Any:
|
| 176 |
+
return invoke_subgraph_wrapper_unboxed(*args)
|
| 177 |
+
|
| 178 |
+
invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined]
|
| 179 |
+
|
| 180 |
+
return invoke_subgraph_wrapper
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# I cannot say how many times I had to revert to this vibe coded version of
|
| 184 |
+
# the code, which worked, and the cleaner versions of the code did not work,
|
| 185 |
+
# so I'm leaving this here until we fix the rest of the bugs.
|
| 186 |
+
'''
|
| 187 |
+
# Counter for unique subgraph names in invoke_subgraph backend
|
| 188 |
+
_invoke_subgraph_counter = 0
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def invoke_subgraph_inner_compiler_good(
|
| 192 |
+
fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 193 |
+
) -> Callable[..., Any]:
|
| 194 |
+
"""Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP.
|
| 195 |
+
|
| 196 |
+
This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting
|
| 197 |
+
function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining.
|
| 198 |
+
"""
|
| 199 |
+
from torch._higher_order_ops.invoke_subgraph import (
|
| 200 |
+
invoke_subgraph as invoke_subgraph_hop,
|
| 201 |
+
)
|
| 202 |
+
from torch.fx.experimental.proxy_tensor import get_proxy_mode
|
| 203 |
+
|
| 204 |
+
global _invoke_subgraph_counter
|
| 205 |
+
_invoke_subgraph_counter += 1
|
| 206 |
+
name = f"invoke_subgraph_{_invoke_subgraph_counter}"
|
| 207 |
+
|
| 208 |
+
from torch._dynamo import disable
|
| 209 |
+
|
| 210 |
+
# Check if fx_g uses boxed calling convention
|
| 211 |
+
fx_g_is_boxed = getattr(fx_g, "_boxed_call", False)
|
| 212 |
+
|
| 213 |
+
@disable
|
| 214 |
+
@torch._dynamo.allow_in_graph
|
| 215 |
+
def invoke_subgraph_wrapper_unboxed(*args: Any) -> Any:
|
| 216 |
+
proxy_mode = get_proxy_mode()
|
| 217 |
+
if proxy_mode is not None:
|
| 218 |
+
# When being traced by make_fx, emit invoke_subgraph HOP
|
| 219 |
+
return invoke_subgraph_hop(fx_g, name, *args) # type: ignore[arg-type]
|
| 220 |
+
else:
|
| 221 |
+
# Normal execution path - call fx_g with proper calling convention
|
| 222 |
+
if fx_g_is_boxed:
|
| 223 |
+
return fx_g(list(args))
|
| 224 |
+
else:
|
| 225 |
+
return fx_g(*args)
|
| 226 |
+
|
| 227 |
+
# Wrap to handle boxed arguments (list of args) as expected by AOTAutograd
|
| 228 |
+
def invoke_subgraph_wrapper(args: list[Any]) -> Any:
|
| 229 |
+
return invoke_subgraph_wrapper_unboxed(*args)
|
| 230 |
+
|
| 231 |
+
invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined]
|
| 232 |
+
return invoke_subgraph_wrapper
|
| 233 |
+
'''
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@register_backend
|
| 237 |
+
def invoke_subgraph(
|
| 238 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 239 |
+
) -> Callable[..., Any]:
|
| 240 |
+
"""Backend that wraps forward/backward graphs in invoke_subgraph HOP when traced by make_fx.
|
| 241 |
+
|
| 242 |
+
This backend uses AOTAutograd to partition into forward/backward graphs, then wraps
|
| 243 |
+
each in an invoke_subgraph HOP. This is useful for recursive Dynamo tracing scenarios
|
| 244 |
+
where you want the compiled subgraph to appear as invoke_subgraph HOPs in the outer
|
| 245 |
+
trace rather than being inlined.
|
| 246 |
+
|
| 247 |
+
Requires:
|
| 248 |
+
- torch._dynamo.config.force_compile_during_fx_trace = True
|
| 249 |
+
(this implicitly overrides error_on_nested_fx_trace)
|
| 250 |
+
"""
|
| 251 |
+
if kwargs:
|
| 252 |
+
log.warning("invoke_subgraph backend ignoring extra kwargs %s", kwargs)
|
| 253 |
+
|
| 254 |
+
# Use AOTAutograd to partition into forward/backward
|
| 255 |
+
return aot_autograd(
|
| 256 |
+
fw_compiler=invoke_subgraph_inner_compiler,
|
| 257 |
+
bw_compiler=invoke_subgraph_inner_compiler,
|
| 258 |
+
partition_fn=min_cut_rematerialization_partition,
|
| 259 |
+
keep_inference_input_mutations=True,
|
| 260 |
+
)(gm, fake_tensor_inputs)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# used boxed call to discard inputs when they are no longer needed
|
| 264 |
+
def boxed_nop(
|
| 265 |
+
fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 266 |
+
) -> Callable[..., Any]:
|
| 267 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 268 |
+
|
| 269 |
+
# Set the graph to use boxed codegen
|
| 270 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 271 |
+
fx_g.recompile()
|
| 272 |
+
|
| 273 |
+
# Wrap the forward method in a function so we can set _boxed_call attribute
|
| 274 |
+
forward_fn = fx_g.forward
|
| 275 |
+
|
| 276 |
+
def run(args: Any) -> Any:
|
| 277 |
+
from torch.utils._debug_mode import DebugInterpreter, get_active_debug_mode
|
| 278 |
+
|
| 279 |
+
if (
|
| 280 |
+
debug_mode := get_active_debug_mode()
|
| 281 |
+
) is not None and debug_mode.run_compile_with_interpreter:
|
| 282 |
+
return DebugInterpreter(fx_g, backend="aot_eager").run(*args)
|
| 283 |
+
return forward_fn(args)
|
| 284 |
+
|
| 285 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 286 |
+
return run
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def boxed_nop_with_mode(
|
| 290 |
+
fx_g: torch.fx.GraphModule,
|
| 291 |
+
example_inputs: list[torch.Tensor],
|
| 292 |
+
*,
|
| 293 |
+
mode: torch.overrides.TorchFunctionMode,
|
| 294 |
+
) -> Callable[..., Any]:
|
| 295 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 296 |
+
|
| 297 |
+
# Set the graph to use boxed codegen
|
| 298 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 299 |
+
fx_g.recompile()
|
| 300 |
+
|
| 301 |
+
# Create a wrapper that runs with the mode
|
| 302 |
+
forward_fn = fx_g.forward
|
| 303 |
+
|
| 304 |
+
def run(args: Any) -> Any:
|
| 305 |
+
with mode:
|
| 306 |
+
return forward_fn(args)
|
| 307 |
+
|
| 308 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 309 |
+
return run
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def fake_crossref_boxed_nop(
|
| 313 |
+
fx_g: torch.fx.GraphModule,
|
| 314 |
+
example_inputs: list[torch.Tensor],
|
| 315 |
+
ignore_op_fn: Optional[Callable[[torch._ops.OpOverload], bool]] = None,
|
| 316 |
+
) -> Callable[..., Any]:
|
| 317 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 318 |
+
|
| 319 |
+
# Set the graph to use boxed codegen
|
| 320 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 321 |
+
fx_g.recompile()
|
| 322 |
+
|
| 323 |
+
# Create a wrapper that runs with the mode
|
| 324 |
+
forward_fn = fx_g.forward
|
| 325 |
+
|
| 326 |
+
def run(args: Any) -> Any:
|
| 327 |
+
with torch._subclasses.CrossRefFakeMode(ignore_op_fn):
|
| 328 |
+
return forward_fn(args)
|
| 329 |
+
|
| 330 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 331 |
+
return run
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def ignore_builtins(op: torch._ops.OpOverload) -> bool:
|
| 335 |
+
return op.namespace in ("aten", "prims", "prim")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def get_nop_func() -> Callable[
|
| 339 |
+
[torch.fx.GraphModule, list[torch.Tensor]], Callable[..., Any]
|
| 340 |
+
]:
|
| 341 |
+
if not torch._functorch.config.fake_tensor_crossref:
|
| 342 |
+
return boxed_nop
|
| 343 |
+
elif torch._functorch.config.fake_tensor_crossref == "all":
|
| 344 |
+
return fake_crossref_boxed_nop
|
| 345 |
+
else:
|
| 346 |
+
assert torch._functorch.config.fake_tensor_crossref == "custom_ops"
|
| 347 |
+
return functools.partial(fake_crossref_boxed_nop, ignore_op_fn=ignore_builtins)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# Useful for debugging purpose
|
| 351 |
+
# aot_eager uses AOT Autograd backend with nop compiler. It is helpful in debugging.
|
| 352 |
+
def aot_eager(
|
| 353 |
+
gm: torch.fx.GraphModule,
|
| 354 |
+
fake_tensor_inputs: list[torch.Tensor],
|
| 355 |
+
fw_compiler: Optional[Callable[..., Any]] = None,
|
| 356 |
+
bw_compiler: Optional[Callable[..., Any]] = None,
|
| 357 |
+
**kwargs: Any,
|
| 358 |
+
) -> Callable[..., Any]:
|
| 359 |
+
return aot_autograd(
|
| 360 |
+
fw_compiler=fw_compiler or boxed_nop,
|
| 361 |
+
bw_compiler=bw_compiler or boxed_nop,
|
| 362 |
+
partition_fn=min_cut_rematerialization_partition,
|
| 363 |
+
keep_inference_input_mutations=True,
|
| 364 |
+
)(gm, fake_tensor_inputs, **kwargs)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
register_backend(name="aot_eager", compiler_fn=aot_eager)
|
| 368 |
+
|
| 369 |
+
aot_eager_default_partitioner = aot_autograd(
|
| 370 |
+
fw_compiler=boxed_nop, keep_inference_input_mutations=True
|
| 371 |
+
)
|
| 372 |
+
register_backend(
|
| 373 |
+
name="aot_eager_default_partitioner", compiler_fn=aot_eager_default_partitioner
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
# Uses TorchInductor AOT Autograd decomps and partitioner to isolate aot vs
|
| 378 |
+
# inductor problems.
|
| 379 |
+
# aot_eager_decomp_partition just replaces the inductor compiler with nop to help
|
| 380 |
+
# isolate inductor vs aot_eager errors
|
| 381 |
+
def aot_eager_decomp_partition(
|
| 382 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 383 |
+
) -> Callable[..., Any]:
|
| 384 |
+
if kwargs:
|
| 385 |
+
log.warning(
|
| 386 |
+
"aot_eager_decomp_partition backend ignoring extra kwargs %s", kwargs
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
from torch._inductor.compiler_bisector import CompilerBisector
|
| 390 |
+
|
| 391 |
+
config_patches = {"unlift_effect_tokens": True}
|
| 392 |
+
if bisect_changes := CompilerBisector.get_config_change(
|
| 393 |
+
"aot_eager_decomp_partition"
|
| 394 |
+
):
|
| 395 |
+
config_patches.update(bisect_changes) # type: ignore[arg-type]
|
| 396 |
+
|
| 397 |
+
with functorch_config.patch(config_patches):
|
| 398 |
+
return aot_autograd(
|
| 399 |
+
# these are taken from memory_efficient_fusion()
|
| 400 |
+
fw_compiler=get_nop_func(),
|
| 401 |
+
bw_compiler=get_nop_func(),
|
| 402 |
+
# NB: lambda here is to delay import of inductor
|
| 403 |
+
decompositions=lambda: import_module(
|
| 404 |
+
"torch._inductor.compile_fx"
|
| 405 |
+
).select_decomp_table(),
|
| 406 |
+
partition_fn=functools.partial(
|
| 407 |
+
min_cut_rematerialization_partition, compiler="inductor"
|
| 408 |
+
),
|
| 409 |
+
)(gm, fake_tensor_inputs)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
register_backend(
|
| 413 |
+
name="aot_eager_decomp_partition", compiler_fn=aot_eager_decomp_partition
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# aot_eager_decomp_partition_with_mode is similar as aot_eager_decomp_partition,
|
| 418 |
+
# except that it takes a TorchDispatchMode mode and run the fw/bw in the mode
|
| 419 |
+
def aot_eager_decomp_partition_with_mode(
|
| 420 |
+
gm: torch.fx.GraphModule,
|
| 421 |
+
fake_tensor_inputs: list[torch.Tensor],
|
| 422 |
+
mode: Any,
|
| 423 |
+
**kwarg: Any,
|
| 424 |
+
) -> Callable[..., Any]:
|
| 425 |
+
return aot_autograd(
|
| 426 |
+
# these are taken from memory_efficient_fusion()
|
| 427 |
+
fw_compiler=functools.partial(boxed_nop_with_mode, mode=mode),
|
| 428 |
+
bw_compiler=functools.partial(boxed_nop_with_mode, mode=mode),
|
| 429 |
+
# NB: lambda here is to delay import of inductor
|
| 430 |
+
decompositions=lambda: import_module(
|
| 431 |
+
"torch._inductor.compile_fx"
|
| 432 |
+
).select_decomp_table(),
|
| 433 |
+
partition_fn=functools.partial(
|
| 434 |
+
min_cut_rematerialization_partition, compiler="inductor"
|
| 435 |
+
),
|
| 436 |
+
)(gm, fake_tensor_inputs)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
register_backend(
|
| 440 |
+
name="aot_eager_decomp_partition_with_mode",
|
| 441 |
+
compiler_fn=aot_eager_decomp_partition_with_mode, # type: ignore[arg-type]
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def aot_eager_decomp_partition_crossref(
|
| 446 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 447 |
+
) -> Callable[..., Any]:
|
| 448 |
+
# if the config is set, respect it, otherwise only test custom_ops.
|
| 449 |
+
# custom_op bad metas always manifest as an error whereas aten will only sometimes.
|
| 450 |
+
# by default, use the less noisy option
|
| 451 |
+
config_val = (
|
| 452 |
+
"custom_ops"
|
| 453 |
+
if not functorch_config.fake_tensor_crossref
|
| 454 |
+
else functorch_config.fake_tensor_crossref
|
| 455 |
+
)
|
| 456 |
+
with functorch_config.patch(fake_tensor_crossref=config_val):
|
| 457 |
+
return aot_eager_decomp_partition(gm, fake_tensor_inputs, **kwargs)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
register_backend(
|
| 461 |
+
name="aot_eager_decomp_partition_crossref",
|
| 462 |
+
compiler_fn=aot_eager_decomp_partition_crossref,
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# AOT Autograd with torchscript backend. Default partitioner.
|
| 467 |
+
# aot_ts uses torchscript backend. We can use this with both nnc and nvfuser
|
| 468 |
+
# by using the relevant fuser with torch.jit.fuser(...)
|
| 469 |
+
aot_ts = aot_autograd(fw_compiler=ts_compile)
|
| 470 |
+
register_backend(name="aot_ts", compiler_fn=aot_ts)
|
| 471 |
+
|
| 472 |
+
# These buggy backends are used for inducing bugs so that we can test
|
| 473 |
+
# our repro extraction / minifier scripts
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
class ReluCompileError(Exception):
|
| 477 |
+
pass
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class TestingOnlyCompileError(Exception):
|
| 481 |
+
pass
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@register_backend
|
| 485 |
+
def relu_compile_error_TESTING_ONLY(
|
| 486 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 487 |
+
) -> torch.fx.GraphModule:
|
| 488 |
+
for node in gm.graph.nodes:
|
| 489 |
+
if node.target is torch.relu:
|
| 490 |
+
raise ReluCompileError
|
| 491 |
+
return gm
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
@register_backend
|
| 495 |
+
def relu_runtime_error_TESTING_ONLY(
|
| 496 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 497 |
+
) -> torch.fx.GraphModule:
|
| 498 |
+
for node in gm.graph.nodes:
|
| 499 |
+
if node.target is torch.relu:
|
| 500 |
+
node.target = torch._assert
|
| 501 |
+
node.args = (False, "ReluRuntimeError")
|
| 502 |
+
gm.recompile()
|
| 503 |
+
return gm
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
@register_backend
|
| 507 |
+
def relu_accuracy_error_TESTING_ONLY(
|
| 508 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 509 |
+
) -> torch.fx.GraphModule:
|
| 510 |
+
for node in gm.graph.nodes:
|
| 511 |
+
if node.target is torch.relu:
|
| 512 |
+
node.target = torch.add
|
| 513 |
+
node.args = (node.args[0], 1)
|
| 514 |
+
gm.recompile()
|
| 515 |
+
|
| 516 |
+
return gm
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
@register_backend
|
| 520 |
+
def non_leaf_compile_error_TESTING_ONLY(
|
| 521 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 522 |
+
) -> torch.fx.GraphModule:
|
| 523 |
+
# Require at least one non-trivial thing in the graph,
|
| 524 |
+
# see https://github.com/pytorch/pytorch/issues/102898
|
| 525 |
+
for node in gm.graph.nodes:
|
| 526 |
+
if node.op == "call_function":
|
| 527 |
+
break
|
| 528 |
+
else:
|
| 529 |
+
return gm
|
| 530 |
+
for t in example_inputs:
|
| 531 |
+
if not t.is_leaf:
|
| 532 |
+
raise TestingOnlyCompileError
|
| 533 |
+
return gm
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
@dataclasses.dataclass
|
| 537 |
+
class ExplainOutput:
|
| 538 |
+
"""
|
| 539 |
+
This is the output of :func:`torch._dynamo.explain()`
|
| 540 |
+
There is no reason to create this class directly.
|
| 541 |
+
"""
|
| 542 |
+
|
| 543 |
+
graphs: list[torch.fx.GraphModule]
|
| 544 |
+
graph_count: int
|
| 545 |
+
graph_break_count: int
|
| 546 |
+
break_reasons: list[GraphCompileReason]
|
| 547 |
+
op_count: int
|
| 548 |
+
ops_per_graph: Optional[list[list["Target"]]] = None
|
| 549 |
+
out_guards: Optional[list[_guards.Guard]] = None
|
| 550 |
+
compile_times: Optional[str] = None
|
| 551 |
+
|
| 552 |
+
def __str__(self) -> str:
|
| 553 |
+
output = f"Graph Count: {self.graph_count}\n"
|
| 554 |
+
output += f"Graph Break Count: {self.graph_break_count}\n"
|
| 555 |
+
output += f"Op Count: {self.op_count}\n"
|
| 556 |
+
|
| 557 |
+
output += "Break Reasons:\n"
|
| 558 |
+
for idx, break_reason in enumerate(self.break_reasons):
|
| 559 |
+
output += f" Break Reason {idx + 1}:\n"
|
| 560 |
+
output += f" Reason: {break_reason.reason}\n"
|
| 561 |
+
output += " User Stack:\n"
|
| 562 |
+
for frame_summary in break_reason.user_stack:
|
| 563 |
+
output += f" {frame_summary}\n"
|
| 564 |
+
|
| 565 |
+
if self.ops_per_graph is not None:
|
| 566 |
+
output += "Ops per Graph:\n"
|
| 567 |
+
for idx, ops in enumerate(self.ops_per_graph):
|
| 568 |
+
output += f" Ops {idx + 1}:\n"
|
| 569 |
+
for op in ops:
|
| 570 |
+
output += f" {op}\n"
|
| 571 |
+
|
| 572 |
+
if self.out_guards is not None:
|
| 573 |
+
output += "Out Guards:\n"
|
| 574 |
+
for i, guard in enumerate(self.out_guards):
|
| 575 |
+
output += f" Guard {i + 1}:\n"
|
| 576 |
+
output += f" {str(guard)}"
|
| 577 |
+
|
| 578 |
+
if self.compile_times is not None:
|
| 579 |
+
output += f"Compile Times: {self.compile_times}\n"
|
| 580 |
+
return output
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _explain_graph_detail(
|
| 584 |
+
gm: torch.fx.GraphModule,
|
| 585 |
+
graphs: list[torch.fx.GraphModule],
|
| 586 |
+
op_count: int,
|
| 587 |
+
ops_per_graph: list[list["Target"]],
|
| 588 |
+
break_reasons: list[GraphCompileReason],
|
| 589 |
+
) -> tuple[
|
| 590 |
+
torch.fx.GraphModule,
|
| 591 |
+
list[torch.fx.GraphModule],
|
| 592 |
+
int,
|
| 593 |
+
list[list["Target"]],
|
| 594 |
+
list[GraphCompileReason],
|
| 595 |
+
]:
|
| 596 |
+
"""
|
| 597 |
+
This function is a utility which processes a torch.fx.GraphModule and
|
| 598 |
+
accumulates information about its ops, graph breaks, and other details. It
|
| 599 |
+
is intended to be used by the ExplainWithBackend class and
|
| 600 |
+
`torch._dynamo.explain()` to provide details from Dynamo's graph capture.
|
| 601 |
+
|
| 602 |
+
Parameters:
|
| 603 |
+
gm (torch.fx.GraphModule): The GraphModule to be processed.
|
| 604 |
+
graphs (list): A list that accumulates all the GraphModules processed.
|
| 605 |
+
op_count (int): The total count of operations in all GraphModules processed so far.
|
| 606 |
+
ops_per_graph (list): A list that accumulates the operations of each GraphModule.
|
| 607 |
+
break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule.
|
| 608 |
+
|
| 609 |
+
Returns:
|
| 610 |
+
tuple: A tuple containing the processed GraphModule, the updated lists of graphs,
|
| 611 |
+
operations per graph, and break reasons, and the updated operation count.
|
| 612 |
+
"""
|
| 613 |
+
graphs.append(gm)
|
| 614 |
+
ops = [node.target for node in gm.graph.nodes if node.op == "call_function"]
|
| 615 |
+
op_count += len(ops)
|
| 616 |
+
ops_per_graph.append(ops)
|
| 617 |
+
if gm.compile_subgraph_reason.graph_break: # type: ignore[union-attr]
|
| 618 |
+
break_reasons.append(gm.compile_subgraph_reason) # type: ignore[arg-type]
|
| 619 |
+
|
| 620 |
+
return gm, graphs, op_count, ops_per_graph, break_reasons
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class ExplainWithBackend:
|
| 624 |
+
"""
|
| 625 |
+
This class is intended to be used as a backend for `torch.compile`. It is
|
| 626 |
+
composable with other backends. When used in this way, it accumulates
|
| 627 |
+
information about graph breaks, ops, and other info and provides a string
|
| 628 |
+
representation summarizing this information.
|
| 629 |
+
|
| 630 |
+
Attributes:
|
| 631 |
+
backend (str): The name of the backend to use for optimization.
|
| 632 |
+
graphs (list): A list of the graphs captured by TorchDynamo.
|
| 633 |
+
op_count (int): The total number of operations in all optimized graphs.
|
| 634 |
+
break_reasons (list): A list of graph break reasons with stack traces.
|
| 635 |
+
|
| 636 |
+
Example Usage:
|
| 637 |
+
def fn(x):
|
| 638 |
+
x = torch.sigmoid(x)
|
| 639 |
+
return x
|
| 640 |
+
|
| 641 |
+
torch._dynamo.reset()
|
| 642 |
+
eb = ExplainWithBackend("inductor")
|
| 643 |
+
optimized_fn = torch.compile(fn, backend=eb)
|
| 644 |
+
result = optimized_fn(torch.randn(5))
|
| 645 |
+
print(eb.output())
|
| 646 |
+
"""
|
| 647 |
+
|
| 648 |
+
def __init__(self, backend: Union[CompilerFn, str]) -> None:
|
| 649 |
+
from .registry import lookup_backend
|
| 650 |
+
|
| 651 |
+
self.backend = lookup_backend(backend)
|
| 652 |
+
self.graphs: list[torch.fx.GraphModule] = []
|
| 653 |
+
self.op_count = 0
|
| 654 |
+
self.break_reasons: list[GraphCompileReason] = []
|
| 655 |
+
|
| 656 |
+
def __call__(
|
| 657 |
+
self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 658 |
+
) -> CompiledFn:
|
| 659 |
+
ops_per_graph: list[list[Target]] = []
|
| 660 |
+
gm, self.graphs, self.op_count, _, self.break_reasons = _explain_graph_detail(
|
| 661 |
+
gm, self.graphs, self.op_count, ops_per_graph, self.break_reasons
|
| 662 |
+
)
|
| 663 |
+
return self.backend(gm, example_inputs)
|
| 664 |
+
|
| 665 |
+
def output(self) -> ExplainOutput:
|
| 666 |
+
graph_count = len(self.graphs)
|
| 667 |
+
output = ExplainOutput(
|
| 668 |
+
self.graphs,
|
| 669 |
+
graph_count,
|
| 670 |
+
graph_count - 1,
|
| 671 |
+
self.break_reasons,
|
| 672 |
+
self.op_count,
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
return output
|
.venv/lib/python3.10/site-packages/torch/_dynamo/backends/distributed.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements distributed training optimizations for TorchDynamo backends.
|
| 3 |
+
|
| 4 |
+
It provides functionality to optimize models wrapped in DistributedDataParallel (DDP)
|
| 5 |
+
by intelligently splitting compiled graphs to align with DDP's gradient synchronization
|
| 6 |
+
boundaries. Key features include:
|
| 7 |
+
|
| 8 |
+
- Graph partitioning based on parameter bucket sizes
|
| 9 |
+
- Optimization of allreduce operations for distributed training
|
| 10 |
+
- Support for parameter ignoring and buffer handling
|
| 11 |
+
- Submodule compilation and management
|
| 12 |
+
- Debugging utilities for distributed training
|
| 13 |
+
|
| 14 |
+
The main component is the DDPOptimizer class, which handles graph splitting and
|
| 15 |
+
recompilation to enable efficient distributed training while maintaining the benefits
|
| 16 |
+
of compilation.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import traceback
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 24 |
+
from unittest import mock
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
from torch import fx
|
| 28 |
+
from torch._dynamo.backends.registry import CompiledFn, CompilerFn
|
| 29 |
+
from torch._dynamo.output_graph import GraphCompileReason
|
| 30 |
+
from torch._dynamo.utils import deepcopy_to_fake_tensor, detect_fake_mode
|
| 31 |
+
from torch._logging import trace_structured
|
| 32 |
+
from torch.fx.node import Node
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Regular log messages should go through 'log'.
|
| 40 |
+
# ddp_graph_log is a separate artifact logger reserved for dumping graphs.
|
| 41 |
+
# See docs/source/logging.rst for more info.
|
| 42 |
+
log = logging.getLogger(__name__)
|
| 43 |
+
ddp_graph_log = torch._logging.getArtifactLogger(__name__, "ddp_graphs")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def args_str(args: Any) -> str:
|
| 47 |
+
# a debug helper
|
| 48 |
+
if torch.is_tensor(args):
|
| 49 |
+
return f"T[{args.shape}]"
|
| 50 |
+
elif isinstance(args, tuple):
|
| 51 |
+
return f"tuple({', '.join([args_str(x) for x in args])})"
|
| 52 |
+
elif isinstance(args, list):
|
| 53 |
+
return f"list({', '.join([args_str(x) for x in args])})"
|
| 54 |
+
else:
|
| 55 |
+
return str(args)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class Bucket:
|
| 60 |
+
size: int = 0
|
| 61 |
+
params: list[str] = field(default_factory=list)
|
| 62 |
+
nodes: list[fx.Node] = field(default_factory=list)
|
| 63 |
+
|
| 64 |
+
# param_ids is just used for unit testing
|
| 65 |
+
param_ids: list[int] = field(default_factory=list)
|
| 66 |
+
|
| 67 |
+
# keep track of any buckets that were extended for logging purposes
|
| 68 |
+
opcount_increased_to_capture_external_output: int = 0
|
| 69 |
+
paramsize_before_opcount_increase: int = 0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def bucket_has_external_output(bucket: Bucket) -> bool:
|
| 73 |
+
nodes_in_bucket = set()
|
| 74 |
+
# we want to iterate in reverse order, but clumsi-luckily the bucket.nodes list was already created backwards
|
| 75 |
+
# so we don't reverse it here
|
| 76 |
+
for node in bucket.nodes:
|
| 77 |
+
# assume node.op != output, since those are filtered in the original iteration
|
| 78 |
+
nodes_in_bucket.add(node)
|
| 79 |
+
for user in node.users:
|
| 80 |
+
if user not in nodes_in_bucket:
|
| 81 |
+
return True
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def pretty_print_buckets(buckets: list[Bucket], bucket_bytes_cap: int) -> None:
|
| 86 |
+
headers = ("Index", "Size (b)", "Param Names")
|
| 87 |
+
rows: list[tuple[Optional[int], Optional[int], str]] = []
|
| 88 |
+
# pyrefly: ignore [implicit-any]
|
| 89 |
+
extended_buckets = []
|
| 90 |
+
for idx, bucket in enumerate(reversed(buckets)):
|
| 91 |
+
if len(bucket.params) > 0:
|
| 92 |
+
rows.append((idx, bucket.size, bucket.params[0]))
|
| 93 |
+
rows.extend((None, None, param) for param in bucket.params[1:])
|
| 94 |
+
if bucket.opcount_increased_to_capture_external_output > 0:
|
| 95 |
+
extended_buckets.append(
|
| 96 |
+
(
|
| 97 |
+
idx,
|
| 98 |
+
bucket.opcount_increased_to_capture_external_output,
|
| 99 |
+
bucket.size - bucket.paramsize_before_opcount_increase,
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if rows:
|
| 104 |
+
log.info(
|
| 105 |
+
"\nDDPOptimizer used bucket cap %s and created %d buckets. Enable debug logs for detailed bucket info.",
|
| 106 |
+
bucket_bytes_cap,
|
| 107 |
+
len(buckets),
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if extended_buckets:
|
| 111 |
+
log.warning(
|
| 112 |
+
"Some buckets were extended beyond their requested parameter capacities"
|
| 113 |
+
" in order to ensure each subgraph has an output node, required for fx graph partitioning."
|
| 114 |
+
" This can be the case when a subgraph would have only contained nodes performing inplace mutation,"
|
| 115 |
+
" and returning no logical outputs. This should not be a problem, unless it results in too few graph"
|
| 116 |
+
" partitions for optimal DDP performance."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
from tabulate import tabulate
|
| 121 |
+
|
| 122 |
+
log.debug(
|
| 123 |
+
"\nDDPOptimizer produced the following bucket assignments:\n%s",
|
| 124 |
+
tabulate(rows, headers=headers, tablefmt="simple_grid"),
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if extended_buckets:
|
| 128 |
+
log.warning(
|
| 129 |
+
"DDPOptimizer extended these buckets to ensure per-subgraph output nodes:\n%s",
|
| 130 |
+
tabulate(
|
| 131 |
+
extended_buckets,
|
| 132 |
+
headers=("Index", "Extra Ops", "Extra Param Size (b)"),
|
| 133 |
+
tablefmt="simple_grid",
|
| 134 |
+
),
|
| 135 |
+
)
|
| 136 |
+
except ImportError:
|
| 137 |
+
log.debug(
|
| 138 |
+
"Please `pip install tabulate` in order to display ddp bucket sizes and diagnostic information."
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
log.debug("DDPOptimizer captured no parameters and did not split this graph.")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def has_higher_order_op(gm: fx.GraphModule) -> bool:
|
| 145 |
+
# Check if there is a higher order op in the graph
|
| 146 |
+
for node in gm.graph.nodes:
|
| 147 |
+
if node.op == "get_attr":
|
| 148 |
+
maybe_param = getattr(gm, node.target)
|
| 149 |
+
if isinstance(maybe_param, torch.fx.GraphModule):
|
| 150 |
+
return True
|
| 151 |
+
return False
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def propagate_metadata(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None:
|
| 155 |
+
for name, module in split_gm.named_modules():
|
| 156 |
+
if "." not in name and len(name):
|
| 157 |
+
# TODO: add split id to CompileId: https://github.com/pytorch/tlparse/pull/83/files#r1880649384
|
| 158 |
+
module.meta = orig_gm.meta
|
| 159 |
+
module._param_name_to_source = orig_gm._param_name_to_source
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def propagate_dynamo_source(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None:
|
| 163 |
+
name_to_dynamo_source = {}
|
| 164 |
+
for node in orig_gm.graph.find_nodes(op="placeholder"):
|
| 165 |
+
name_to_dynamo_source[node.name] = node._dynamo_source
|
| 166 |
+
|
| 167 |
+
for name, module in split_gm.named_modules():
|
| 168 |
+
if "." not in name and len(name):
|
| 169 |
+
for node in module.graph.find_nodes(op="placeholder"):
|
| 170 |
+
# non-placeholder in original_gm may become placeholder in submodules
|
| 171 |
+
node._dynamo_source = name_to_dynamo_source.get(node.name)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class DDPOptimizerContext:
|
| 175 |
+
def __init__(self) -> None:
|
| 176 |
+
self.curr_bucket: int = -1
|
| 177 |
+
self.metadata_per_bucket: list[ViewAndMutationMeta] = []
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# compile each of the partitioned submodules using the user-provided compiler
|
| 181 |
+
class SubmodCompiler(torch.fx.interpreter.Interpreter):
|
| 182 |
+
def __init__(
|
| 183 |
+
self,
|
| 184 |
+
module: fx.GraphModule,
|
| 185 |
+
compiler: CompilerFn,
|
| 186 |
+
fake_mode: torch._subclasses.fake_tensor.FakeTensorMode,
|
| 187 |
+
) -> None:
|
| 188 |
+
super().__init__(module)
|
| 189 |
+
self.compiler = compiler
|
| 190 |
+
self.fake_mode = fake_mode
|
| 191 |
+
# See Note [DDPOptimizer and fw_metadata]
|
| 192 |
+
ctx = torch._guards.TracingContext.try_get()
|
| 193 |
+
if ctx is not None:
|
| 194 |
+
ctx.ddp_optimizer_ctx = DDPOptimizerContext()
|
| 195 |
+
|
| 196 |
+
def compile_submod(
|
| 197 |
+
self, input_mod: fx.GraphModule, args: list[torch.Tensor], kwargs: Any
|
| 198 |
+
) -> Any:
|
| 199 |
+
"""
|
| 200 |
+
Compile the submodule,
|
| 201 |
+
using a wrapper to make sure its output is always a tuple,
|
| 202 |
+
which is required by AotAutograd based compilers
|
| 203 |
+
"""
|
| 204 |
+
assert len(kwargs) == 0, "We assume only args for these modules"
|
| 205 |
+
|
| 206 |
+
class WrapperModule(torch.nn.Module):
|
| 207 |
+
def __init__(
|
| 208 |
+
self, submod: Callable[..., Any], unwrap_singleton_tuple: bool
|
| 209 |
+
) -> None:
|
| 210 |
+
super().__init__()
|
| 211 |
+
self.submod = submod
|
| 212 |
+
self.unwrap_singleton_tuple = unwrap_singleton_tuple
|
| 213 |
+
|
| 214 |
+
def forward(self, *args: Any) -> Any:
|
| 215 |
+
x = self.submod(*args)
|
| 216 |
+
# TODO(whc)
|
| 217 |
+
# for some reason the isinstance check is necessary if I split one node per submod
|
| 218 |
+
# - even though I supposedly wrapped the output in a tuple in those cases, the real
|
| 219 |
+
# compiled module was still returning a tensor
|
| 220 |
+
if self.unwrap_singleton_tuple and isinstance(x, (tuple, list)):
|
| 221 |
+
return x[0]
|
| 222 |
+
return x
|
| 223 |
+
|
| 224 |
+
unwrap_singleton_tuple = False
|
| 225 |
+
for sn in input_mod.graph.nodes:
|
| 226 |
+
if sn.op == "output":
|
| 227 |
+
if not isinstance(sn.args[0], tuple):
|
| 228 |
+
unwrap_singleton_tuple = True
|
| 229 |
+
sn.args = (sn.args,)
|
| 230 |
+
|
| 231 |
+
input_mod.recompile()
|
| 232 |
+
input_mod.compile_subgraph_reason = GraphCompileReason( # type: ignore[assignment]
|
| 233 |
+
"DDPOptimizer intentional graph-break (See Note [DDPOptimizer])."
|
| 234 |
+
" Set `torch._dynamo.config.optimize_ddp = False` to disable.",
|
| 235 |
+
[
|
| 236 |
+
# it's close to useless to get a real stacktrace here, and quite verbose.
|
| 237 |
+
traceback.FrameSummary(__file__, 0, "DDPOptimizer"),
|
| 238 |
+
],
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
wrapper = WrapperModule(
|
| 242 |
+
self.compiler(input_mod, args),
|
| 243 |
+
unwrap_singleton_tuple,
|
| 244 |
+
)
|
| 245 |
+
return wrapper
|
| 246 |
+
|
| 247 |
+
# Note:
|
| 248 |
+
#
|
| 249 |
+
# The way distributed works today around fake tensors can be somewhat confusing.
|
| 250 |
+
# Some of these codepaths are shared in both runtime, and compile time. The presence
|
| 251 |
+
# of a fake_mode, read off of fake tensor inputs, dictates how we will operate.
|
| 252 |
+
#
|
| 253 |
+
# A few things to keep in mind:
|
| 254 |
+
#
|
| 255 |
+
# 1) We invoke `compile_submod` with a real module. The output of that gets stored
|
| 256 |
+
# on the graph via `self.module.add_submodule(n.target, compiled_submod_real)`.
|
| 257 |
+
#
|
| 258 |
+
# 2) When running a call_module targeted node, if we have a fake_mode, we fakify the
|
| 259 |
+
# module we got from self.fetch_attr(n.target). Regardless of fake_mode, we then execute it.
|
| 260 |
+
#
|
| 261 |
+
# 3) Fake tensors should always be around during compile time.
|
| 262 |
+
#
|
| 263 |
+
# 4) Fake tensors should never be around at runtime.
|
| 264 |
+
#
|
| 265 |
+
# 5) We end up with a compilation mode that takes a real submodule and fake tensors,
|
| 266 |
+
# to match what aot_autograd expects. See Note: [Fake Modules and AOTAutograd]
|
| 267 |
+
def run_node(self, n: Node) -> Any:
|
| 268 |
+
args, kwargs = self.fetch_args_kwargs_from_env(n)
|
| 269 |
+
new_args = []
|
| 270 |
+
assert self.fake_mode
|
| 271 |
+
for arg in args:
|
| 272 |
+
if isinstance(arg, torch.Tensor) and not isinstance(
|
| 273 |
+
arg, torch._subclasses.FakeTensor
|
| 274 |
+
):
|
| 275 |
+
new_args.append(torch._dynamo.utils.to_fake_tensor(arg, self.fake_mode))
|
| 276 |
+
else:
|
| 277 |
+
new_args.append(arg)
|
| 278 |
+
|
| 279 |
+
log.debug("run_node %s, %s got args %s", n.op, n.target, args_str(args))
|
| 280 |
+
assert isinstance(args, tuple)
|
| 281 |
+
assert isinstance(kwargs, dict)
|
| 282 |
+
|
| 283 |
+
if n.op == "call_module":
|
| 284 |
+
real_mod = self.fetch_attr(str(n.target))
|
| 285 |
+
if self.fake_mode:
|
| 286 |
+
curr_submod = deepcopy_to_fake_tensor(real_mod, self.fake_mode)
|
| 287 |
+
else:
|
| 288 |
+
curr_submod = real_mod
|
| 289 |
+
|
| 290 |
+
ddp_graph_log.debug("\n---%s graph---\n%s", n.target, curr_submod.graph)
|
| 291 |
+
|
| 292 |
+
# When calling the compiler on the submod, inputs (new_args) are expected to
|
| 293 |
+
# be FakeTensors already since Dynamo would have made them FakeTensors in the
|
| 294 |
+
# non-DDP flow. However, the parameters are _not_ expected to be FakeTensors,
|
| 295 |
+
# since this wrapping happens during compilation
|
| 296 |
+
|
| 297 |
+
# Note: Returning Fake Tensors on First AOT Autograd Call
|
| 298 |
+
#
|
| 299 |
+
# Inductor will optimize strides of outputs when it deems it profitable.
|
| 300 |
+
# For instance, converting to channels last. When we split the graph here
|
| 301 |
+
# into multiple inductor compilations, we need to make sure that the
|
| 302 |
+
# output strides of one compilation is appropriately passed to the subsequent
|
| 303 |
+
# compilations. However, the mapping from inductor output to dynamo output
|
| 304 |
+
# is non-trivial due to aot_autograd's deduping, de-aliasing, mutation, re-writing,
|
| 305 |
+
# subclass handling, etc. In order to replay all this logic we set a flag such that
|
| 306 |
+
# the first invocation of inductor in aot_autograd will return Fake Tensors with
|
| 307 |
+
# appropriate strides. Then, all of aot autograd's runtime logic is replayed.
|
| 308 |
+
# This gives us the appropriately strided outputs here which will reflect runtime strides.
|
| 309 |
+
|
| 310 |
+
class FakeifyFirstAOTInvocationGuard:
|
| 311 |
+
def __init__(self) -> None:
|
| 312 |
+
self.tc = torch._guards.TracingContext.try_get()
|
| 313 |
+
assert self.tc
|
| 314 |
+
self.tc.fakify_first_call = True
|
| 315 |
+
|
| 316 |
+
def __del__(self) -> None:
|
| 317 |
+
self.tc.fakify_first_call = False # type: ignore[union-attr]
|
| 318 |
+
|
| 319 |
+
# For aot_eager and other backends, tracing context is not set
|
| 320 |
+
has_tracing_context = torch._guards.TracingContext.try_get() is not None
|
| 321 |
+
if has_tracing_context:
|
| 322 |
+
g = FakeifyFirstAOTInvocationGuard() # noqa: F841
|
| 323 |
+
|
| 324 |
+
from torch._dynamo.utils import counters
|
| 325 |
+
|
| 326 |
+
init = counters["aot_autograd"]["total"]
|
| 327 |
+
compiled_submod_real = self.compile_submod(real_mod, new_args, kwargs)
|
| 328 |
+
|
| 329 |
+
# TODO - better way of doing this?
|
| 330 |
+
# Only aot autograd handles fakifying first call
|
| 331 |
+
invoked_aot_autograd = init != counters["aot_autograd"]["total"]
|
| 332 |
+
|
| 333 |
+
# We update the original (outer) graph with a call into the compiled module
|
| 334 |
+
# instead of the uncompiled one.
|
| 335 |
+
self.module.delete_submodule(n.target) # type: ignore[operator]
|
| 336 |
+
n.target = "compiled_" + n.target # type: ignore[operator]
|
| 337 |
+
self.module.add_submodule(n.target, compiled_submod_real) # type: ignore[operator]
|
| 338 |
+
|
| 339 |
+
# Finally, we have to produce inputs for use compiling the next submodule,
|
| 340 |
+
# and these need to be FakeTensors, so we execute the module under fake_mode
|
| 341 |
+
# Because parameters are not fake we patch fake tensor mode to allow non fake inputs
|
| 342 |
+
with (
|
| 343 |
+
self.fake_mode,
|
| 344 |
+
mock.patch.object(self.fake_mode, "allow_non_fake_inputs", True),
|
| 345 |
+
):
|
| 346 |
+
if has_tracing_context and invoked_aot_autograd:
|
| 347 |
+
tracing_ctx = torch._guards.TracingContext.try_get()
|
| 348 |
+
assert tracing_ctx is not None
|
| 349 |
+
# DDPOptimizer maintains 1 dynamo graph -> N AOT graphs
|
| 350 |
+
# Dynamo only has 1 tracing context, so it needs to maintain all N AOT metadata instances
|
| 351 |
+
ddp_ctx = tracing_ctx.ddp_optimizer_ctx
|
| 352 |
+
assert ddp_ctx is not None
|
| 353 |
+
assert tracing_ctx.fw_metadata is not None
|
| 354 |
+
ddp_ctx.curr_bucket += 1
|
| 355 |
+
ddp_ctx.metadata_per_bucket.append(tracing_ctx.fw_metadata)
|
| 356 |
+
|
| 357 |
+
out = compiled_submod_real(*new_args, **kwargs)
|
| 358 |
+
# output should be fake or subclass
|
| 359 |
+
assert all(
|
| 360 |
+
(not isinstance(t, torch.Tensor) or type(t) is not torch.Tensor)
|
| 361 |
+
for t in (out if isinstance(out, (list, tuple)) else [out])
|
| 362 |
+
)
|
| 363 |
+
return out
|
| 364 |
+
else:
|
| 365 |
+
return curr_submod(*new_args, **kwargs)
|
| 366 |
+
else:
|
| 367 |
+
# placeholder or output nodes don't need to get compiled, just executed
|
| 368 |
+
return getattr(self, n.op)(n.target, new_args, kwargs)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class DDPOptimizer:
|
| 372 |
+
"""Note [DDPOptimizer]
|
| 373 |
+
DDPOptimizer applies when dynamo compiles models wrapped in DistributedDataParallel (DDP),
|
| 374 |
+
breaking the dynamo graph into chunks to compile separately, with the breaks aligning to
|
| 375 |
+
the boundaries of gradient-allreduce buckets chosen by DDP.
|
| 376 |
+
|
| 377 |
+
Background/Motivation
|
| 378 |
+
- DDP uses allreduce collectives to synchronize partial gradients computed on different workers
|
| 379 |
+
- DDP groups gradient allreduces into 'buckets' to optimize communication efficiency of all-reduce
|
| 380 |
+
- Parameters grouped into buckets are assumed to be adjacent in time, so they become ready
|
| 381 |
+
at around the same time during backward and thus can share the same allreduce efficiently
|
| 382 |
+
- Allreduces must overlap with backward compute for optimal training performance
|
| 383 |
+
- DDP schedules allreduces using 'hooks' fired from the c++ autograd engine in pytorch, which
|
| 384 |
+
operates when individual grads become 'ready'
|
| 385 |
+
- Dynamo+AOTAutograd produces a single fused graph that runs 'atomically' from the perspective of the
|
| 386 |
+
autograd engine, such that all gradients become 'ready' at the same time. Hooks fire after the whole
|
| 387 |
+
fused backward function executes, preventing any overlap of compute and communication
|
| 388 |
+
|
| 389 |
+
Algorithm
|
| 390 |
+
- DDPOptimizer starts off with an FX graph traced by dynamo which represents forward. It can traverse
|
| 391 |
+
this graph in reverse order to determine the true order that gradients will become ready during backward.
|
| 392 |
+
- Parameter sizes are counted in reverse order, up to a bucket size limit, at which point a new bucket is started
|
| 393 |
+
and a graph break introduced
|
| 394 |
+
- Each of the subgraphs is compiled by the compiler provided to dynamo by the user, and then fused back together
|
| 395 |
+
into an outer module that is returned to the user
|
| 396 |
+
|
| 397 |
+
Notes
|
| 398 |
+
- It would be better to enforce (by adding an API to DDP) that the bucket splits chosen here are used by DDP,
|
| 399 |
+
and that DDP does not need to detect or optimize bucket order by observing execution at runtime, as it does
|
| 400 |
+
in eager.
|
| 401 |
+
- If Dynamo can't capture a whole graph for the portion of the model wrapped by DDP, this algorithm will currently
|
| 402 |
+
produce splits that do not necessarily align with the buckets used by DDP. This should result in performance
|
| 403 |
+
degradation approaching the baseline case where graph-splits are not used, but not worse.
|
| 404 |
+
- If the backend compiler fails to compile a single subgraph, it will execute eagerly despite the rest of the
|
| 405 |
+
subgraphs being compiled
|
| 406 |
+
- DDP has a 'parameters_and_buffers_to_ignore' field, which DDPOptimizer attempts to honor by reading markers
|
| 407 |
+
left by DDP on individual parameters. In cases where other transformations, such as reparameterization, are
|
| 408 |
+
also used, the ignore markers could be lost. If DDPOptimizer fails to ignore a parameter ignored by DDP,
|
| 409 |
+
it is not catastrophic but could impact performance by choosing sub-optimal bucket splits.
|
| 410 |
+
- DDPOptimizer always ignores all buffers, regardless of their ignore flag, since buffers do not require gradients,
|
| 411 |
+
and therefore aren't allreduced by DDP. (They are broadcast during forward, but this is not covered by
|
| 412 |
+
DDPOptimizer)
|
| 413 |
+
|
| 414 |
+
Debugging
|
| 415 |
+
- Generally, it is easiest to debug DDPOptimizer in a single process program, using pdb.
|
| 416 |
+
- In many cases, the log messages are helpful (they show bucket size assignments)-
|
| 417 |
+
just set TORCH_LOGS env to include any of 'dynamo', 'distributed', or 'dist_ddp'.
|
| 418 |
+
- See `benchmarks/dynamo/distributed.py` for a simple harness that will run a toy model or a torchbench model
|
| 419 |
+
in a single process (or with torchrun, in multiple processes)
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
bucket_bytes_cap (int): Controls the size of buckets, in bytes, used to determine graphbreaks. Should be
|
| 423 |
+
set to match the equivalent parameter on the original DDP module.
|
| 424 |
+
|
| 425 |
+
backend_compile_fn (callable): A dynamo compiler function, to be invoked to compile each subgraph.
|
| 426 |
+
|
| 427 |
+
first_bucket_cap (int): Controls the size of the first bucket. Should match DDP's first bucket cap. DDP
|
| 428 |
+
special-cases the first bucket size since it is sometimes optimal to start a small allreduce early.
|
| 429 |
+
|
| 430 |
+
"""
|
| 431 |
+
|
| 432 |
+
def __init__(
|
| 433 |
+
self,
|
| 434 |
+
bucket_bytes_cap: int,
|
| 435 |
+
backend_compile_fn: CompilerFn,
|
| 436 |
+
first_bucket_cap: Optional[int] = None,
|
| 437 |
+
) -> None:
|
| 438 |
+
if first_bucket_cap is not None:
|
| 439 |
+
self.first_bucket_cap = first_bucket_cap
|
| 440 |
+
elif torch.distributed.is_available():
|
| 441 |
+
# this constant comes from C10D lib which is not always built
|
| 442 |
+
self.first_bucket_cap = torch.distributed._DEFAULT_FIRST_BUCKET_BYTES
|
| 443 |
+
else:
|
| 444 |
+
self.first_bucket_cap = bucket_bytes_cap
|
| 445 |
+
|
| 446 |
+
self.bucket_bytes_cap = bucket_bytes_cap
|
| 447 |
+
assert self.first_bucket_cap <= self.bucket_bytes_cap, (
|
| 448 |
+
"First bucket should be smaller/equal to other buckets to get comms warmed up ASAP"
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
self.backend_compile_fn = backend_compile_fn
|
| 452 |
+
|
| 453 |
+
def _ignore_parameter(self, parameter: torch.nn.Parameter) -> bool:
|
| 454 |
+
return hasattr(parameter, "_ddp_ignored") and parameter._ddp_ignored
|
| 455 |
+
|
| 456 |
+
def add_param(self, bucket: Bucket, param: torch.nn.Parameter, name: str) -> None:
|
| 457 |
+
bucket.size += param.untyped_storage().nbytes()
|
| 458 |
+
bucket.params.append(name)
|
| 459 |
+
bucket.param_ids.append(id(param))
|
| 460 |
+
|
| 461 |
+
def add_module_params_to_bucket(
|
| 462 |
+
self,
|
| 463 |
+
mod: torch.nn.Module,
|
| 464 |
+
bucket: Bucket,
|
| 465 |
+
processed_modules: set[torch.nn.Module],
|
| 466 |
+
prefix: str,
|
| 467 |
+
) -> None:
|
| 468 |
+
processed_modules.add(mod)
|
| 469 |
+
for name, param in mod.named_parameters():
|
| 470 |
+
if param.requires_grad and not self._ignore_parameter(param):
|
| 471 |
+
self.add_param(bucket, param, f"{prefix}_{name}")
|
| 472 |
+
|
| 473 |
+
def add_param_args(self, bucket: Bucket, node: fx.Node) -> None:
|
| 474 |
+
for arg in node.args:
|
| 475 |
+
if not isinstance(arg, torch.fx.node.Node):
|
| 476 |
+
continue
|
| 477 |
+
if arg.op != "placeholder":
|
| 478 |
+
continue
|
| 479 |
+
param = arg.meta["example_value"]
|
| 480 |
+
if (
|
| 481 |
+
isinstance(param, torch.nn.Parameter)
|
| 482 |
+
and param.requires_grad
|
| 483 |
+
and not self._ignore_parameter(param)
|
| 484 |
+
):
|
| 485 |
+
self.add_param(bucket, param, str(arg.target))
|
| 486 |
+
|
| 487 |
+
def compile_fn(
|
| 488 |
+
self, gm: fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 489 |
+
) -> CompiledFn:
|
| 490 |
+
"""
|
| 491 |
+
Implements graph splitting, first determining a set of of buckets by counting
|
| 492 |
+
parameter sizes in reverse graph order, then invoking the user/backend compiler
|
| 493 |
+
to compile each subgraph. Finally, stitches compiled graphs into one graphmodule
|
| 494 |
+
and returns its callable.
|
| 495 |
+
"""
|
| 496 |
+
# 1: compute the partition map according to DDP bucket logic
|
| 497 |
+
buckets = [Bucket()] # (size, param_names)
|
| 498 |
+
processed_modules: set[torch.nn.Module] = set()
|
| 499 |
+
for node in reversed(gm.graph.nodes):
|
| 500 |
+
if node.op in ("output", "placeholder"):
|
| 501 |
+
continue
|
| 502 |
+
|
| 503 |
+
if (
|
| 504 |
+
buckets[0].size >= self.bucket_bytes_cap
|
| 505 |
+
or len(buckets) == 1
|
| 506 |
+
and buckets[0].size >= self.first_bucket_cap
|
| 507 |
+
):
|
| 508 |
+
if bucket_has_external_output(buckets[0]):
|
| 509 |
+
buckets.insert(0, Bucket())
|
| 510 |
+
else:
|
| 511 |
+
# continue building this bucket past the point of filling its parameter capacity,
|
| 512 |
+
# to increase chances it contains at least one node that is either a global output or
|
| 513 |
+
# passed as input to a subsequent graph
|
| 514 |
+
|
| 515 |
+
if buckets[0].opcount_increased_to_capture_external_output == 0:
|
| 516 |
+
buckets[0].paramsize_before_opcount_increase = buckets[0].size
|
| 517 |
+
buckets[0].opcount_increased_to_capture_external_output += 1
|
| 518 |
+
|
| 519 |
+
if node.op == "call_function":
|
| 520 |
+
self.add_param_args(buckets[0], node)
|
| 521 |
+
|
| 522 |
+
elif node.op == "call_module":
|
| 523 |
+
target_mod = gm.get_submodule(node.target)
|
| 524 |
+
if target_mod not in processed_modules:
|
| 525 |
+
self.add_module_params_to_bucket(
|
| 526 |
+
target_mod, buckets[0], processed_modules, node.target
|
| 527 |
+
)
|
| 528 |
+
elif node.op == "call_method":
|
| 529 |
+
if isinstance(node.args[0].target, str):
|
| 530 |
+
target_mod = None
|
| 531 |
+
try:
|
| 532 |
+
target_mod = gm.get_submodule(node.args[0].target)
|
| 533 |
+
except AttributeError:
|
| 534 |
+
pass
|
| 535 |
+
if target_mod is not None and target_mod not in processed_modules:
|
| 536 |
+
self.add_module_params_to_bucket(
|
| 537 |
+
target_mod, buckets[0], processed_modules, node.target
|
| 538 |
+
)
|
| 539 |
+
# This handles situations like tmp = torch.mm(x, self.weight.t())
|
| 540 |
+
# t: "f32[512, 512]" = l_self_seq_2_weight.t(); l_self_seq_2_weight = None
|
| 541 |
+
# tmp: "f32[512, 512]" = torch.mm(input_2, t); input_2 = t = None
|
| 542 |
+
self.add_param_args(buckets[0], node)
|
| 543 |
+
|
| 544 |
+
elif node.op == "get_attr":
|
| 545 |
+
maybe_param = getattr(gm, node.target)
|
| 546 |
+
if (
|
| 547 |
+
isinstance(maybe_param, torch.nn.Parameter)
|
| 548 |
+
and maybe_param.requires_grad
|
| 549 |
+
and not self._ignore_parameter(maybe_param)
|
| 550 |
+
):
|
| 551 |
+
self.add_param(buckets[0], maybe_param, node.target)
|
| 552 |
+
|
| 553 |
+
# All nodes have to be mapped to a bucket, even if they don't have their own params
|
| 554 |
+
# Ignored params still end up in buckets, we just don't count them towards the capacity
|
| 555 |
+
buckets[0].nodes.append(node)
|
| 556 |
+
|
| 557 |
+
if len(buckets) > 1 and buckets[0].size == 0:
|
| 558 |
+
# we collected a small preamble graph with ops that don't include parameters, fuse it back
|
| 559 |
+
buckets[1].nodes.extend(buckets[0].nodes)
|
| 560 |
+
assert len(buckets[0].params) == 0, "Params should be empty if size is 0"
|
| 561 |
+
del buckets[0]
|
| 562 |
+
|
| 563 |
+
# stash buckets for testing/debugging purposes
|
| 564 |
+
self.buckets = buckets
|
| 565 |
+
pretty_print_buckets(buckets, self.bucket_bytes_cap)
|
| 566 |
+
|
| 567 |
+
if len(buckets) == 1:
|
| 568 |
+
# bypass split/fuse logic if there is only one bucket
|
| 569 |
+
return self.backend_compile_fn(gm, example_inputs)
|
| 570 |
+
|
| 571 |
+
# 2: partition the graphmodule according to bucket capacity
|
| 572 |
+
partition_map = {}
|
| 573 |
+
for idx, b in enumerate(buckets):
|
| 574 |
+
for node in b.nodes:
|
| 575 |
+
partition_map[node] = idx
|
| 576 |
+
|
| 577 |
+
split_gm = fx.passes.split_module.split_module(
|
| 578 |
+
gm,
|
| 579 |
+
None, # type: ignore[arg-type]
|
| 580 |
+
lambda node: partition_map[node],
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
# See note [Assumption on Dynamo Metadata]
|
| 584 |
+
propagate_dynamo_source(gm, split_gm)
|
| 585 |
+
propagate_metadata(gm, split_gm)
|
| 586 |
+
|
| 587 |
+
debug_str = (
|
| 588 |
+
f"\n---orig graph---\n{gm.graph}\n"
|
| 589 |
+
+ f"\n---split graph---\n{split_gm.graph}\n"
|
| 590 |
+
)
|
| 591 |
+
for name, module in split_gm.named_modules():
|
| 592 |
+
if "." not in name and len(name):
|
| 593 |
+
# only print the submod graphs, not their children
|
| 594 |
+
debug_str += f"\n---{name} graph---\n{module.graph}\n"
|
| 595 |
+
debug_str += "\n---------------\n"
|
| 596 |
+
ddp_graph_log.debug(debug_str)
|
| 597 |
+
|
| 598 |
+
trace_structured(
|
| 599 |
+
"optimize_ddp_split_graph",
|
| 600 |
+
payload_fn=lambda: split_gm.print_readable(print_output=False),
|
| 601 |
+
)
|
| 602 |
+
for name, module in split_gm.named_modules():
|
| 603 |
+
if "." not in name and len(name):
|
| 604 |
+
trace_structured(
|
| 605 |
+
"optimize_ddp_split_child",
|
| 606 |
+
lambda: {"name": name},
|
| 607 |
+
payload_fn=lambda: module.print_readable(print_output=False),
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
fake_mode = detect_fake_mode(example_inputs)
|
| 611 |
+
if fake_mode is None:
|
| 612 |
+
fake_mode = torch._subclasses.fake_tensor.FakeTensorMode()
|
| 613 |
+
|
| 614 |
+
submod_compiler = SubmodCompiler(split_gm, self.backend_compile_fn, fake_mode)
|
| 615 |
+
with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing():
|
| 616 |
+
submod_compiler.run(*example_inputs)
|
| 617 |
+
split_gm.recompile()
|
| 618 |
+
|
| 619 |
+
ddp_graph_log.debug(
|
| 620 |
+
"\n---final graph---\n%s\n---------------\n", split_gm.graph
|
| 621 |
+
)
|
| 622 |
+
return split_gm
|
.venv/lib/python3.10/site-packages/torch/_dynamo/backends/inductor.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides the TorchInductor backend integration for TorchDynamo.
|
| 3 |
+
|
| 4 |
+
TorchInductor is a compiler backend that generates optimized code for both CPU and GPU.
|
| 5 |
+
This module lazily imports and registers the TorchInductor compiler to avoid loading it
|
| 6 |
+
into memory when it is not being used. This helps reduce memory overhead when using
|
| 7 |
+
other backends.
|
| 8 |
+
|
| 9 |
+
The inductor backend can be used with torch.compile():
|
| 10 |
+
model = torch.compile(model, backend="inductor")
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
from torch._dynamo import register_backend
|
| 16 |
+
from torch._dynamo.utils import dynamo_timed
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@register_backend
|
| 20 |
+
def inductor(*args: Any, **kwargs: Any) -> Any:
|
| 21 |
+
with dynamo_timed("inductor_import", log_pt2_compile_event=True):
|
| 22 |
+
# do import here to avoid loading inductor into memory when it is not used
|
| 23 |
+
# The AsyncCompile subproc pool can be slow to start, so warm it up as early
|
| 24 |
+
# as possible.
|
| 25 |
+
from torch._inductor.async_compile import maybe_warm_pool
|
| 26 |
+
|
| 27 |
+
maybe_warm_pool()
|
| 28 |
+
|
| 29 |
+
from torch._inductor.compile_fx import compile_fx
|
| 30 |
+
|
| 31 |
+
return compile_fx(*args, **kwargs)
|