Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/common.py +183 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/cudagraphs.py +299 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/debugging.py +558 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/distributed.py +621 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/inductor.py +31 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/onnxrt.py +39 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/registry.py +179 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/tensorrt.py +12 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/torchxla.py +55 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/tvm.py +197 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/funcname_cache.py +75 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/functional_export.py +850 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_break_hints.py +26 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_break_registry.json +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_bytecode_inputs.py +96 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_deduplication.py +610 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_region_tracker.py +502 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_utils.py +116 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/guards.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/hooks.py +25 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/logging.py +73 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/metrics_context.py +251 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/mutation_guard.py +160 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/output_graph.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/package.py +1157 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/pgo.py +1004 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/__init__.py +431 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/_collections.py +33 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/builtins.py +123 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/functools.py +47 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/fx.py +41 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/heapq.py +119 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/itertools.py +276 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/loader.py +45 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/operator.py +119 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/os.py +37 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/pytree.py +758 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/struct.py +27 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/sys.py +34 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/tensor.py +40 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/precompile_context.py +231 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/profiler.py +177 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/replay_record.py +130 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/after_aot.py +1281 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/after_dynamo.py +637 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/aoti.py +661 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/resume_execution.py +746 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/side_effects.py +1234 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/common.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
return gm
|
| 74 |
+
|
| 75 |
+
def wrap_bw_compiler(bw_compiler_fn: Callable[P, R]) -> Callable[..., R]:
|
| 76 |
+
def _wrapped_bw_compiler(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 77 |
+
# Note [Wrapping bw_compiler in disable]
|
| 78 |
+
# The two disables here:
|
| 79 |
+
# - stop TorchDynamo from trying to compile the bw_compiler function itself
|
| 80 |
+
# - stop TorchDynamo from trying to compile our the generated backwards pass bw_compiler produces
|
| 81 |
+
|
| 82 |
+
return disable(
|
| 83 |
+
disable(
|
| 84 |
+
bw_compiler_fn, reason="do not trace backward compiler function"
|
| 85 |
+
)(*args, **kwargs), # type: ignore[misc]
|
| 86 |
+
reason="do not trace generated backwards pass",
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
_wrapped_bw_compiler._is_wrapped_bw_compiler = ( # pyrefly: ignore [missing-attribute]
|
| 90 |
+
True
|
| 91 |
+
)
|
| 92 |
+
return _wrapped_bw_compiler
|
| 93 |
+
|
| 94 |
+
bw_compiler = self.kwargs.get("bw_compiler") or self.kwargs["fw_compiler"]
|
| 95 |
+
|
| 96 |
+
if isinstance(bw_compiler, SerializableAOTDispatchCompiler):
|
| 97 |
+
bw_compiler.compiler_fn = wrap_bw_compiler(bw_compiler.compiler_fn)
|
| 98 |
+
elif getattr(bw_compiler, "_is_wrapped_bw_compiler", False):
|
| 99 |
+
bw_compiler.compiler_fn = bw_compiler
|
| 100 |
+
else:
|
| 101 |
+
bw_compiler = wrap_bw_compiler(bw_compiler)
|
| 102 |
+
|
| 103 |
+
self.kwargs["bw_compiler"] = bw_compiler
|
| 104 |
+
self.kwargs["inference_compiler"] = (
|
| 105 |
+
self.kwargs.get("inference_compiler") or self.kwargs["fw_compiler"]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
from functorch.compile import nop
|
| 109 |
+
from torch._inductor.debug import enable_aot_logging
|
| 110 |
+
|
| 111 |
+
# debug asserts slow down compile time noticeably,
|
| 112 |
+
# So only default them on when the aot_eager backend is used.
|
| 113 |
+
if self.kwargs.get("fw_compiler", None) is nop:
|
| 114 |
+
patch_config: contextlib.AbstractContextManager[Any] = patch(
|
| 115 |
+
"functorch.compile.config.debug_assert", True
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
patch_config = contextlib.nullcontext()
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
# NB: NOT cloned!
|
| 122 |
+
with enable_aot_logging(), patch_config:
|
| 123 |
+
cg = aot_module_simplified(gm, example_inputs, **self.kwargs)
|
| 124 |
+
counters["aot_autograd"]["ok"] += 1
|
| 125 |
+
return disable(cg, reason="do not trace AOT-compiled graph")
|
| 126 |
+
except TensorifyScalarRestartAnalysis:
|
| 127 |
+
raise
|
| 128 |
+
except Exception:
|
| 129 |
+
counters["aot_autograd"]["not_ok"] += 1
|
| 130 |
+
raise
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def aot_autograd(**kwargs: Any) -> AotAutograd:
|
| 134 |
+
return AotAutograd(**kwargs)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def mem_efficient_fusion_kwargs(use_decomps: bool) -> dict[str, Any]:
|
| 138 |
+
from functorch.compile import (
|
| 139 |
+
default_decompositions,
|
| 140 |
+
min_cut_rematerialization_partition,
|
| 141 |
+
ts_compile,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
kwargs = {
|
| 145 |
+
# these are taken from memory_efficient_fusion()
|
| 146 |
+
"fw_compiler": ts_compile,
|
| 147 |
+
"bw_compiler": ts_compile,
|
| 148 |
+
"partition_fn": min_cut_rematerialization_partition,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
if use_decomps:
|
| 152 |
+
kwargs["decompositions"] = default_decompositions
|
| 153 |
+
|
| 154 |
+
return kwargs
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def fake_tensor_unsupported(fn: Callable[[Any, list[Any], Any], R]) -> Any:
|
| 158 |
+
"""
|
| 159 |
+
Decorator for backends that need real inputs. We swap out fake
|
| 160 |
+
tensors for zero tensors.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
@functools.wraps(fn)
|
| 164 |
+
def wrapper(model: Any, inputs: Any, **kwargs: Any) -> Any:
|
| 165 |
+
with _disable_current_modes():
|
| 166 |
+
inputs = list(map(defake, inputs))
|
| 167 |
+
return fn(model, inputs, **kwargs) # type: ignore[call-arg]
|
| 168 |
+
|
| 169 |
+
return wrapper
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def device_from_inputs(example_inputs: Iterable[Any]) -> torch.device:
|
| 173 |
+
for x in example_inputs:
|
| 174 |
+
if hasattr(x, "device"):
|
| 175 |
+
return x.device
|
| 176 |
+
return torch.device("cpu") # Default fallback
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def dtype_from_inputs(example_inputs: Iterable[Any]) -> torch.dtype:
|
| 180 |
+
for x in example_inputs:
|
| 181 |
+
if hasattr(x, "dtype"):
|
| 182 |
+
return x.dtype
|
| 183 |
+
return torch.float32 # Default fallback
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/cudagraphs.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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=False, # Q: should forward is_inference here?
|
| 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 |
+
static_inputs = [torch.zeros_like(x) for x in inputs]
|
| 268 |
+
else:
|
| 269 |
+
static_inputs = list(inputs)
|
| 270 |
+
|
| 271 |
+
# warmup
|
| 272 |
+
torch.cuda.synchronize()
|
| 273 |
+
stream = torch.cuda.Stream()
|
| 274 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 275 |
+
with torch.cuda.stream(stream):
|
| 276 |
+
model(*inputs)
|
| 277 |
+
stream.synchronize()
|
| 278 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 279 |
+
torch.cuda.synchronize()
|
| 280 |
+
|
| 281 |
+
# record
|
| 282 |
+
graph = torch.cuda.CUDAGraph()
|
| 283 |
+
with torch.cuda.graph(graph, stream=stream):
|
| 284 |
+
static_outputs = model(*static_inputs)
|
| 285 |
+
if not isinstance(static_outputs, (list, tuple)):
|
| 286 |
+
static_outputs = (static_outputs,)
|
| 287 |
+
|
| 288 |
+
def run(*new_inputs: Any) -> Sequence[Any]:
|
| 289 |
+
assert len(static_inputs) == len(new_inputs)
|
| 290 |
+
if copy_inputs:
|
| 291 |
+
for dst, src in zip(static_inputs, new_inputs):
|
| 292 |
+
dst.copy_(src)
|
| 293 |
+
graph.replay()
|
| 294 |
+
if copy_outputs:
|
| 295 |
+
return [x.clone() for x in static_outputs]
|
| 296 |
+
else:
|
| 297 |
+
return static_outputs
|
| 298 |
+
|
| 299 |
+
return run
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/debugging.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
return gm.forward
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def make_eager_backend_with_torch_function_mode(
|
| 61 |
+
mode: torch.overrides.TorchFunctionMode,
|
| 62 |
+
) -> Callable[..., Any]:
|
| 63 |
+
return make_eager_backend_with_torch_function_modes([mode])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def make_eager_backend_with_torch_function_modes(
|
| 67 |
+
modes: Iterable[torch.overrides.TorchFunctionMode],
|
| 68 |
+
) -> Callable[..., Any]:
|
| 69 |
+
"""Used to trace HOPs (cond and while) for eager execution, the metadata
|
| 70 |
+
TF mode mutates vars outside of the scope of the HOP, and we can't have graph breaks
|
| 71 |
+
in the HOP, so we need to externally run this mode and not trace it."""
|
| 72 |
+
from contextlib import ExitStack
|
| 73 |
+
|
| 74 |
+
def fn(
|
| 75 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 76 |
+
) -> Callable[..., Any]:
|
| 77 |
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 78 |
+
with ExitStack() as stack:
|
| 79 |
+
for mode in modes:
|
| 80 |
+
stack.enter_context(mode)
|
| 81 |
+
return gm.forward(*args, **kwargs)
|
| 82 |
+
|
| 83 |
+
return wrapper
|
| 84 |
+
|
| 85 |
+
return fn
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@register_backend
|
| 89 |
+
def eager_noexcept(
|
| 90 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 91 |
+
) -> Callable[..., Any]:
|
| 92 |
+
if kwargs:
|
| 93 |
+
log.warning("eager_noexcept backend ignoring extra kwargs %s", kwargs)
|
| 94 |
+
|
| 95 |
+
# This backend is intended to check that dynamo-generated GraphModules
|
| 96 |
+
# do not cause errors.
|
| 97 |
+
def inner(*args: Any) -> Any:
|
| 98 |
+
try:
|
| 99 |
+
return gm(*args)
|
| 100 |
+
except Exception as e:
|
| 101 |
+
raise torch._dynamo.exc.TorchDynamoException(
|
| 102 |
+
"Unexpected exception when running generated GraphModule"
|
| 103 |
+
) from e
|
| 104 |
+
|
| 105 |
+
return inner
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@register_backend
|
| 109 |
+
def pre_dispatch_eager(
|
| 110 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 111 |
+
) -> torch.fx.GraphModule:
|
| 112 |
+
if kwargs:
|
| 113 |
+
log.warning("pre_dispatch_eager backend ignoring extra kwargs %s", kwargs)
|
| 114 |
+
|
| 115 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 116 |
+
|
| 117 |
+
def runnable_gm(*args: Any) -> Any:
|
| 118 |
+
return torch.fx.Interpreter(gm).run(*args)
|
| 119 |
+
|
| 120 |
+
pre_dispatch_gm = make_fx(runnable_gm, pre_dispatch=True)(*fake_tensor_inputs)
|
| 121 |
+
pre_dispatch_gm.print_readable()
|
| 122 |
+
|
| 123 |
+
return pre_dispatch_gm
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@register_backend
|
| 127 |
+
def eager_debug(
|
| 128 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 129 |
+
) -> Callable[..., Any]:
|
| 130 |
+
if kwargs:
|
| 131 |
+
log.warning("eager_debug backend ignoring extra kwargs %s", kwargs)
|
| 132 |
+
|
| 133 |
+
from torch._subclasses.schema_check_mode import SchemaCheckMode
|
| 134 |
+
|
| 135 |
+
# We could add more debugging bits here.
|
| 136 |
+
# Right now, this backend can be used to check for and error on
|
| 137 |
+
# custom dispatcher ops that have incorrect schemas.
|
| 138 |
+
def inner(*args: Any) -> Any:
|
| 139 |
+
with SchemaCheckMode():
|
| 140 |
+
return torch.fx.Interpreter(gm).run(*args)
|
| 141 |
+
|
| 142 |
+
return inner
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@register_backend(name="ts") # type: ignore[misc]
|
| 146 |
+
def torchscript(
|
| 147 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor]
|
| 148 |
+
) -> torch.jit.ScriptModule:
|
| 149 |
+
return torch.jit.script(gm)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# used boxed call to discard inputs when they are no longer needed
|
| 153 |
+
def boxed_nop(
|
| 154 |
+
fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 155 |
+
) -> Callable[..., Any]:
|
| 156 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 157 |
+
|
| 158 |
+
# Set the graph to use boxed codegen
|
| 159 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 160 |
+
fx_g.recompile()
|
| 161 |
+
|
| 162 |
+
# Wrap the forward method in a function so we can set _boxed_call attribute
|
| 163 |
+
forward_fn = fx_g.forward
|
| 164 |
+
|
| 165 |
+
def run(args: Any) -> Any:
|
| 166 |
+
return forward_fn(args)
|
| 167 |
+
|
| 168 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 169 |
+
return run
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def boxed_nop_with_mode(
|
| 173 |
+
fx_g: torch.fx.GraphModule,
|
| 174 |
+
example_inputs: list[torch.Tensor],
|
| 175 |
+
*,
|
| 176 |
+
mode: torch.overrides.TorchFunctionMode,
|
| 177 |
+
) -> Callable[..., Any]:
|
| 178 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 179 |
+
|
| 180 |
+
# Set the graph to use boxed codegen
|
| 181 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 182 |
+
fx_g.recompile()
|
| 183 |
+
|
| 184 |
+
# Create a wrapper that runs with the mode
|
| 185 |
+
forward_fn = fx_g.forward
|
| 186 |
+
|
| 187 |
+
def run(args: Any) -> Any:
|
| 188 |
+
with mode:
|
| 189 |
+
return forward_fn(args)
|
| 190 |
+
|
| 191 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 192 |
+
return run
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def fake_crossref_boxed_nop(
|
| 196 |
+
fx_g: torch.fx.GraphModule,
|
| 197 |
+
example_inputs: list[torch.Tensor],
|
| 198 |
+
ignore_op_fn: Optional[Callable[[torch._ops.OpOverload], bool]] = None,
|
| 199 |
+
) -> Callable[..., Any]:
|
| 200 |
+
from torch.fx.graph import _BoxedCodeGen
|
| 201 |
+
|
| 202 |
+
# Set the graph to use boxed codegen
|
| 203 |
+
fx_g.graph.set_codegen(_BoxedCodeGen())
|
| 204 |
+
fx_g.recompile()
|
| 205 |
+
|
| 206 |
+
# Create a wrapper that runs with the mode
|
| 207 |
+
forward_fn = fx_g.forward
|
| 208 |
+
|
| 209 |
+
def run(args: Any) -> Any:
|
| 210 |
+
with torch._subclasses.CrossRefFakeMode(ignore_op_fn):
|
| 211 |
+
return forward_fn(args)
|
| 212 |
+
|
| 213 |
+
run._boxed_call = True # type: ignore[attr-defined]
|
| 214 |
+
return run
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def ignore_builtins(op: torch._ops.OpOverload) -> bool:
|
| 218 |
+
return op.namespace in ("aten", "prims", "prim")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def get_nop_func() -> Callable[
|
| 222 |
+
[torch.fx.GraphModule, list[torch.Tensor]], Callable[..., Any]
|
| 223 |
+
]:
|
| 224 |
+
if not torch._functorch.config.fake_tensor_crossref:
|
| 225 |
+
return boxed_nop
|
| 226 |
+
elif torch._functorch.config.fake_tensor_crossref == "all":
|
| 227 |
+
return fake_crossref_boxed_nop
|
| 228 |
+
else:
|
| 229 |
+
assert torch._functorch.config.fake_tensor_crossref == "custom_ops"
|
| 230 |
+
return functools.partial(fake_crossref_boxed_nop, ignore_op_fn=ignore_builtins)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# Useful for debugging purpose
|
| 234 |
+
# aot_eager uses AOT Autograd backend with nop compiler. It is helpful in debugging.
|
| 235 |
+
def aot_eager(
|
| 236 |
+
gm: torch.fx.GraphModule,
|
| 237 |
+
fake_tensor_inputs: list[torch.Tensor],
|
| 238 |
+
fw_compiler: Optional[Callable[..., Any]] = None,
|
| 239 |
+
bw_compiler: Optional[Callable[..., Any]] = None,
|
| 240 |
+
**kwargs: Any,
|
| 241 |
+
) -> Callable[..., Any]:
|
| 242 |
+
return aot_autograd(
|
| 243 |
+
fw_compiler=fw_compiler or boxed_nop,
|
| 244 |
+
bw_compiler=bw_compiler or boxed_nop,
|
| 245 |
+
partition_fn=min_cut_rematerialization_partition,
|
| 246 |
+
keep_inference_input_mutations=True,
|
| 247 |
+
)(gm, fake_tensor_inputs, **kwargs)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
register_backend(name="aot_eager", compiler_fn=aot_eager)
|
| 251 |
+
|
| 252 |
+
aot_eager_default_partitioner = aot_autograd(
|
| 253 |
+
fw_compiler=boxed_nop, keep_inference_input_mutations=True
|
| 254 |
+
)
|
| 255 |
+
register_backend(
|
| 256 |
+
name="aot_eager_default_partitioner", compiler_fn=aot_eager_default_partitioner
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# Uses TorchInductor AOT Autograd decomps and partitioner to isolate aot vs
|
| 261 |
+
# inductor problems.
|
| 262 |
+
# aot_eager_decomp_partition just replaces the inductor compiler with nop to help
|
| 263 |
+
# isolate inductor vs aot_eager errors
|
| 264 |
+
def aot_eager_decomp_partition(
|
| 265 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 266 |
+
) -> Callable[..., Any]:
|
| 267 |
+
if kwargs:
|
| 268 |
+
log.warning(
|
| 269 |
+
"aot_eager_decomp_partition backend ignoring extra kwargs %s", kwargs
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
from torch._inductor.compiler_bisector import CompilerBisector
|
| 273 |
+
|
| 274 |
+
config_patches = {"unlift_effect_tokens": True}
|
| 275 |
+
if bisect_changes := CompilerBisector.get_config_change(
|
| 276 |
+
"aot_eager_decomp_partition"
|
| 277 |
+
):
|
| 278 |
+
config_patches.update(bisect_changes) # type: ignore[arg-type]
|
| 279 |
+
|
| 280 |
+
with functorch_config.patch(config_patches):
|
| 281 |
+
return aot_autograd(
|
| 282 |
+
# these are taken from memory_efficient_fusion()
|
| 283 |
+
fw_compiler=get_nop_func(),
|
| 284 |
+
bw_compiler=get_nop_func(),
|
| 285 |
+
# NB: lambda here is to delay import of inductor
|
| 286 |
+
decompositions=lambda: import_module(
|
| 287 |
+
"torch._inductor.compile_fx"
|
| 288 |
+
).select_decomp_table(),
|
| 289 |
+
partition_fn=functools.partial(
|
| 290 |
+
min_cut_rematerialization_partition, compiler="inductor"
|
| 291 |
+
),
|
| 292 |
+
)(gm, fake_tensor_inputs)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
register_backend(
|
| 296 |
+
name="aot_eager_decomp_partition", compiler_fn=aot_eager_decomp_partition
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# aot_eager_decomp_partition_with_mode is similar as aot_eager_decomp_partition,
|
| 301 |
+
# except that it takes a TorchDispatchMode mode and run the fw/bw in the mode
|
| 302 |
+
def aot_eager_decomp_partition_with_mode(
|
| 303 |
+
gm: torch.fx.GraphModule,
|
| 304 |
+
fake_tensor_inputs: list[torch.Tensor],
|
| 305 |
+
mode: Any,
|
| 306 |
+
**kwarg: Any,
|
| 307 |
+
) -> Callable[..., Any]:
|
| 308 |
+
return aot_autograd(
|
| 309 |
+
# these are taken from memory_efficient_fusion()
|
| 310 |
+
fw_compiler=functools.partial(boxed_nop_with_mode, mode=mode),
|
| 311 |
+
bw_compiler=functools.partial(boxed_nop_with_mode, mode=mode),
|
| 312 |
+
# NB: lambda here is to delay import of inductor
|
| 313 |
+
decompositions=lambda: import_module(
|
| 314 |
+
"torch._inductor.compile_fx"
|
| 315 |
+
).select_decomp_table(),
|
| 316 |
+
partition_fn=functools.partial(
|
| 317 |
+
min_cut_rematerialization_partition, compiler="inductor"
|
| 318 |
+
),
|
| 319 |
+
)(gm, fake_tensor_inputs)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
register_backend(
|
| 323 |
+
name="aot_eager_decomp_partition_with_mode",
|
| 324 |
+
compiler_fn=aot_eager_decomp_partition_with_mode, # type: ignore[arg-type]
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def aot_eager_decomp_partition_crossref(
|
| 329 |
+
gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any
|
| 330 |
+
) -> Callable[..., Any]:
|
| 331 |
+
# if the config is set, respect it, otherwise only test custom_ops.
|
| 332 |
+
# custom_op bad metas always manifest as an error whereas aten will only sometimes.
|
| 333 |
+
# by default, use the less noisy option
|
| 334 |
+
config_val = (
|
| 335 |
+
"custom_ops"
|
| 336 |
+
if not functorch_config.fake_tensor_crossref
|
| 337 |
+
else functorch_config.fake_tensor_crossref
|
| 338 |
+
)
|
| 339 |
+
with functorch_config.patch(fake_tensor_crossref=config_val):
|
| 340 |
+
return aot_eager_decomp_partition(gm, fake_tensor_inputs, **kwargs)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
register_backend(
|
| 344 |
+
name="aot_eager_decomp_partition_crossref",
|
| 345 |
+
compiler_fn=aot_eager_decomp_partition_crossref,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
# AOT Autograd with torchscript backend. Default partitioner.
|
| 350 |
+
# aot_ts uses torchscript backend. We can use this with both nnc and nvfuser
|
| 351 |
+
# by using the relevant fuser with torch.jit.fuser(...)
|
| 352 |
+
aot_ts = aot_autograd(fw_compiler=ts_compile)
|
| 353 |
+
register_backend(name="aot_ts", compiler_fn=aot_ts)
|
| 354 |
+
|
| 355 |
+
# These buggy backends are used for inducing bugs so that we can test
|
| 356 |
+
# our repro extraction / minifier scripts
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class ReluCompileError(Exception):
|
| 360 |
+
pass
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class TestingOnlyCompileError(Exception):
|
| 364 |
+
pass
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@register_backend
|
| 368 |
+
def relu_compile_error_TESTING_ONLY(
|
| 369 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 370 |
+
) -> torch.fx.GraphModule:
|
| 371 |
+
for node in gm.graph.nodes:
|
| 372 |
+
if node.target is torch.relu:
|
| 373 |
+
raise ReluCompileError
|
| 374 |
+
return gm
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@register_backend
|
| 378 |
+
def relu_runtime_error_TESTING_ONLY(
|
| 379 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 380 |
+
) -> torch.fx.GraphModule:
|
| 381 |
+
for node in gm.graph.nodes:
|
| 382 |
+
if node.target is torch.relu:
|
| 383 |
+
node.target = torch._assert
|
| 384 |
+
node.args = (False, "ReluRuntimeError")
|
| 385 |
+
gm.recompile()
|
| 386 |
+
return gm
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@register_backend
|
| 390 |
+
def relu_accuracy_error_TESTING_ONLY(
|
| 391 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 392 |
+
) -> torch.fx.GraphModule:
|
| 393 |
+
for node in gm.graph.nodes:
|
| 394 |
+
if node.target is torch.relu:
|
| 395 |
+
node.target = torch.add
|
| 396 |
+
node.args = (node.args[0], 1)
|
| 397 |
+
gm.recompile()
|
| 398 |
+
|
| 399 |
+
return gm
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@register_backend
|
| 403 |
+
def non_leaf_compile_error_TESTING_ONLY(
|
| 404 |
+
gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 405 |
+
) -> torch.fx.GraphModule:
|
| 406 |
+
# Require at least one non-trivial thing in the graph,
|
| 407 |
+
# see https://github.com/pytorch/pytorch/issues/102898
|
| 408 |
+
for node in gm.graph.nodes:
|
| 409 |
+
if node.op == "call_function":
|
| 410 |
+
break
|
| 411 |
+
else:
|
| 412 |
+
return gm
|
| 413 |
+
for t in example_inputs:
|
| 414 |
+
if not t.is_leaf:
|
| 415 |
+
raise TestingOnlyCompileError
|
| 416 |
+
return gm
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@dataclasses.dataclass
|
| 420 |
+
class ExplainOutput:
|
| 421 |
+
"""
|
| 422 |
+
This is the output of :func:`torch._dynamo.explain()`
|
| 423 |
+
There is no reason to create this class directly.
|
| 424 |
+
"""
|
| 425 |
+
|
| 426 |
+
graphs: list[torch.fx.GraphModule]
|
| 427 |
+
graph_count: int
|
| 428 |
+
graph_break_count: int
|
| 429 |
+
break_reasons: list[GraphCompileReason]
|
| 430 |
+
op_count: int
|
| 431 |
+
ops_per_graph: Optional[list[list["Target"]]] = None
|
| 432 |
+
out_guards: Optional[list[_guards.Guard]] = None
|
| 433 |
+
compile_times: Optional[str] = None
|
| 434 |
+
|
| 435 |
+
def __str__(self) -> str:
|
| 436 |
+
output = f"Graph Count: {self.graph_count}\n"
|
| 437 |
+
output += f"Graph Break Count: {self.graph_break_count}\n"
|
| 438 |
+
output += f"Op Count: {self.op_count}\n"
|
| 439 |
+
|
| 440 |
+
output += "Break Reasons:\n"
|
| 441 |
+
for idx, break_reason in enumerate(self.break_reasons):
|
| 442 |
+
output += f" Break Reason {idx + 1}:\n"
|
| 443 |
+
output += f" Reason: {break_reason.reason}\n"
|
| 444 |
+
output += " User Stack:\n"
|
| 445 |
+
for frame_summary in break_reason.user_stack:
|
| 446 |
+
output += f" {frame_summary}\n"
|
| 447 |
+
|
| 448 |
+
if self.ops_per_graph is not None:
|
| 449 |
+
output += "Ops per Graph:\n"
|
| 450 |
+
for idx, ops in enumerate(self.ops_per_graph):
|
| 451 |
+
output += f" Ops {idx + 1}:\n"
|
| 452 |
+
for op in ops:
|
| 453 |
+
output += f" {op}\n"
|
| 454 |
+
|
| 455 |
+
if self.out_guards is not None:
|
| 456 |
+
output += "Out Guards:\n"
|
| 457 |
+
for i, guard in enumerate(self.out_guards):
|
| 458 |
+
output += f" Guard {i + 1}:\n"
|
| 459 |
+
output += f" {str(guard)}"
|
| 460 |
+
|
| 461 |
+
if self.compile_times is not None:
|
| 462 |
+
output += f"Compile Times: {self.compile_times}\n"
|
| 463 |
+
return output
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _explain_graph_detail(
|
| 467 |
+
gm: torch.fx.GraphModule,
|
| 468 |
+
graphs: list[torch.fx.GraphModule],
|
| 469 |
+
op_count: int,
|
| 470 |
+
ops_per_graph: list[list["Target"]],
|
| 471 |
+
break_reasons: list[GraphCompileReason],
|
| 472 |
+
) -> tuple[
|
| 473 |
+
torch.fx.GraphModule,
|
| 474 |
+
list[torch.fx.GraphModule],
|
| 475 |
+
int,
|
| 476 |
+
list[list["Target"]],
|
| 477 |
+
list[GraphCompileReason],
|
| 478 |
+
]:
|
| 479 |
+
"""
|
| 480 |
+
This function is a utility which processes a torch.fx.GraphModule and
|
| 481 |
+
accumulates information about its ops, graph breaks, and other details. It
|
| 482 |
+
is intended to be used by the ExplainWithBackend class and
|
| 483 |
+
`torch._dynamo.explain()` to provide details from Dynamo's graph capture.
|
| 484 |
+
|
| 485 |
+
Parameters:
|
| 486 |
+
gm (torch.fx.GraphModule): The GraphModule to be processed.
|
| 487 |
+
graphs (list): A list that accumulates all the GraphModules processed.
|
| 488 |
+
op_count (int): The total count of operations in all GraphModules processed so far.
|
| 489 |
+
ops_per_graph (list): A list that accumulates the operations of each GraphModule.
|
| 490 |
+
break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule.
|
| 491 |
+
|
| 492 |
+
Returns:
|
| 493 |
+
tuple: A tuple containing the processed GraphModule, the updated lists of graphs,
|
| 494 |
+
operations per graph, and break reasons, and the updated operation count.
|
| 495 |
+
"""
|
| 496 |
+
graphs.append(gm)
|
| 497 |
+
ops = [node.target for node in gm.graph.nodes if node.op == "call_function"]
|
| 498 |
+
op_count += len(ops)
|
| 499 |
+
ops_per_graph.append(ops)
|
| 500 |
+
if gm.compile_subgraph_reason.graph_break: # type: ignore[union-attr]
|
| 501 |
+
break_reasons.append(gm.compile_subgraph_reason) # type: ignore[arg-type]
|
| 502 |
+
|
| 503 |
+
return gm, graphs, op_count, ops_per_graph, break_reasons
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
class ExplainWithBackend:
|
| 507 |
+
"""
|
| 508 |
+
This class is intended to be used as a backend for `torch.compile`. It is
|
| 509 |
+
composable with other backends. When used in this way, it accumulates
|
| 510 |
+
information about graph breaks, ops, and other info and provides a string
|
| 511 |
+
representation summarizing this information.
|
| 512 |
+
|
| 513 |
+
Attributes:
|
| 514 |
+
backend (str): The name of the backend to use for optimization.
|
| 515 |
+
graphs (list): A list of the graphs captured by TorchDynamo.
|
| 516 |
+
op_count (int): The total number of operations in all optimized graphs.
|
| 517 |
+
break_reasons (list): A list of graph break reasons with stack traces.
|
| 518 |
+
|
| 519 |
+
Example Usage:
|
| 520 |
+
def fn(x):
|
| 521 |
+
x = torch.sigmoid(x)
|
| 522 |
+
return x
|
| 523 |
+
|
| 524 |
+
torch._dynamo.reset()
|
| 525 |
+
eb = ExplainWithBackend("inductor")
|
| 526 |
+
optimized_fn = torch.compile(fn, backend=eb)
|
| 527 |
+
result = optimized_fn(torch.randn(5))
|
| 528 |
+
print(eb.output())
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
def __init__(self, backend: Union[CompilerFn, str]) -> None:
|
| 532 |
+
from .registry import lookup_backend
|
| 533 |
+
|
| 534 |
+
self.backend = lookup_backend(backend)
|
| 535 |
+
self.graphs: list[torch.fx.GraphModule] = []
|
| 536 |
+
self.op_count = 0
|
| 537 |
+
self.break_reasons: list[GraphCompileReason] = []
|
| 538 |
+
|
| 539 |
+
def __call__(
|
| 540 |
+
self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 541 |
+
) -> CompiledFn:
|
| 542 |
+
ops_per_graph: list[list[Target]] = []
|
| 543 |
+
gm, self.graphs, self.op_count, _, self.break_reasons = _explain_graph_detail(
|
| 544 |
+
gm, self.graphs, self.op_count, ops_per_graph, self.break_reasons
|
| 545 |
+
)
|
| 546 |
+
return self.backend(gm, example_inputs)
|
| 547 |
+
|
| 548 |
+
def output(self) -> ExplainOutput:
|
| 549 |
+
graph_count = len(self.graphs)
|
| 550 |
+
output = ExplainOutput(
|
| 551 |
+
self.graphs,
|
| 552 |
+
graph_count,
|
| 553 |
+
graph_count - 1,
|
| 554 |
+
self.break_reasons,
|
| 555 |
+
self.op_count,
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
return output
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/distributed.py
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
extended_buckets = []
|
| 89 |
+
for idx, bucket in enumerate(reversed(buckets)):
|
| 90 |
+
if len(bucket.params) > 0:
|
| 91 |
+
rows.append((idx, bucket.size, bucket.params[0]))
|
| 92 |
+
rows.extend((None, None, param) for param in bucket.params[1:])
|
| 93 |
+
if bucket.opcount_increased_to_capture_external_output > 0:
|
| 94 |
+
extended_buckets.append(
|
| 95 |
+
(
|
| 96 |
+
idx,
|
| 97 |
+
bucket.opcount_increased_to_capture_external_output,
|
| 98 |
+
bucket.size - bucket.paramsize_before_opcount_increase,
|
| 99 |
+
)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if rows:
|
| 103 |
+
log.info(
|
| 104 |
+
"\nDDPOptimizer used bucket cap %s and created %d buckets. Enable debug logs for detailed bucket info.",
|
| 105 |
+
bucket_bytes_cap,
|
| 106 |
+
len(buckets),
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if extended_buckets:
|
| 110 |
+
log.warning(
|
| 111 |
+
"Some buckets were extended beyond their requested parameter capacities"
|
| 112 |
+
" in order to ensure each subgraph has an output node, required for fx graph partitioning."
|
| 113 |
+
" This can be the case when a subgraph would have only contained nodes performing inplace mutation,"
|
| 114 |
+
" and returning no logical outputs. This should not be a problem, unless it results in too few graph"
|
| 115 |
+
" partitions for optimal DDP performance."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
from tabulate import tabulate
|
| 120 |
+
|
| 121 |
+
log.debug(
|
| 122 |
+
"\nDDPOptimizer produced the following bucket assignments:\n%s",
|
| 123 |
+
tabulate(rows, headers=headers, tablefmt="simple_grid"),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
if extended_buckets:
|
| 127 |
+
log.warning(
|
| 128 |
+
"DDPOptimizer extended these buckets to ensure per-subgraph output nodes:\n%s",
|
| 129 |
+
tabulate(
|
| 130 |
+
extended_buckets,
|
| 131 |
+
headers=("Index", "Extra Ops", "Extra Param Size (b)"),
|
| 132 |
+
tablefmt="simple_grid",
|
| 133 |
+
),
|
| 134 |
+
)
|
| 135 |
+
except ImportError:
|
| 136 |
+
log.debug(
|
| 137 |
+
"Please `pip install tabulate` in order to display ddp bucket sizes and diagnostic information."
|
| 138 |
+
)
|
| 139 |
+
else:
|
| 140 |
+
log.debug("DDPOptimizer captured no parameters and did not split this graph.")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def has_higher_order_op(gm: fx.GraphModule) -> bool:
|
| 144 |
+
# Check if there is a higher order op in the graph
|
| 145 |
+
for node in gm.graph.nodes:
|
| 146 |
+
if node.op == "get_attr":
|
| 147 |
+
maybe_param = getattr(gm, node.target)
|
| 148 |
+
if isinstance(maybe_param, torch.fx.GraphModule):
|
| 149 |
+
return True
|
| 150 |
+
return False
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def propagate_metadata(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None:
|
| 154 |
+
for name, module in split_gm.named_modules():
|
| 155 |
+
if "." not in name and len(name):
|
| 156 |
+
# TODO: add split id to CompileId: https://github.com/pytorch/tlparse/pull/83/files#r1880649384
|
| 157 |
+
module.meta = orig_gm.meta
|
| 158 |
+
module._param_name_to_source = orig_gm._param_name_to_source
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def propagate_dynamo_source(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None:
|
| 162 |
+
name_to_dynamo_source = {}
|
| 163 |
+
for node in orig_gm.graph.find_nodes(op="placeholder"):
|
| 164 |
+
name_to_dynamo_source[node.name] = node._dynamo_source
|
| 165 |
+
|
| 166 |
+
for name, module in split_gm.named_modules():
|
| 167 |
+
if "." not in name and len(name):
|
| 168 |
+
for node in module.graph.find_nodes(op="placeholder"):
|
| 169 |
+
# non-placeholder in original_gm may become placeholder in submodules
|
| 170 |
+
node._dynamo_source = name_to_dynamo_source.get(node.name, None)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class DDPOptimizerContext:
|
| 174 |
+
def __init__(self) -> None:
|
| 175 |
+
self.curr_bucket: int = -1
|
| 176 |
+
self.metadata_per_bucket: list[ViewAndMutationMeta] = []
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# compile each of the partitioned submodules using the user-provided compiler
|
| 180 |
+
class SubmodCompiler(torch.fx.interpreter.Interpreter):
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
module: fx.GraphModule,
|
| 184 |
+
compiler: CompilerFn,
|
| 185 |
+
fake_mode: torch._subclasses.fake_tensor.FakeTensorMode,
|
| 186 |
+
) -> None:
|
| 187 |
+
super().__init__(module)
|
| 188 |
+
self.compiler = compiler
|
| 189 |
+
self.fake_mode = fake_mode
|
| 190 |
+
# See Note [DDPOptimizer and fw_metadata]
|
| 191 |
+
ctx = torch._guards.TracingContext.try_get()
|
| 192 |
+
if ctx is not None:
|
| 193 |
+
ctx.ddp_optimizer_ctx = DDPOptimizerContext()
|
| 194 |
+
|
| 195 |
+
def compile_submod(
|
| 196 |
+
self, input_mod: fx.GraphModule, args: list[torch.Tensor], kwargs: Any
|
| 197 |
+
) -> Any:
|
| 198 |
+
"""
|
| 199 |
+
Compile the submodule,
|
| 200 |
+
using a wrapper to make sure its output is always a tuple,
|
| 201 |
+
which is required by AotAutograd based compilers
|
| 202 |
+
"""
|
| 203 |
+
assert len(kwargs) == 0, "We assume only args for these modules"
|
| 204 |
+
|
| 205 |
+
class WrapperModule(torch.nn.Module):
|
| 206 |
+
def __init__(
|
| 207 |
+
self, submod: Callable[..., Any], unwrap_singleton_tuple: bool
|
| 208 |
+
) -> None:
|
| 209 |
+
super().__init__()
|
| 210 |
+
self.submod = submod
|
| 211 |
+
self.unwrap_singleton_tuple = unwrap_singleton_tuple
|
| 212 |
+
|
| 213 |
+
def forward(self, *args: Any) -> Any:
|
| 214 |
+
x = self.submod(*args)
|
| 215 |
+
# TODO(whc)
|
| 216 |
+
# for some reason the isinstance check is necessary if I split one node per submod
|
| 217 |
+
# - even though I supposedly wrapped the output in a tuple in those cases, the real
|
| 218 |
+
# compiled module was still returning a tensor
|
| 219 |
+
if self.unwrap_singleton_tuple and isinstance(x, (tuple, list)):
|
| 220 |
+
return x[0]
|
| 221 |
+
return x
|
| 222 |
+
|
| 223 |
+
unwrap_singleton_tuple = False
|
| 224 |
+
for sn in input_mod.graph.nodes:
|
| 225 |
+
if sn.op == "output":
|
| 226 |
+
if not isinstance(sn.args[0], tuple):
|
| 227 |
+
unwrap_singleton_tuple = True
|
| 228 |
+
sn.args = (sn.args,)
|
| 229 |
+
|
| 230 |
+
input_mod.recompile()
|
| 231 |
+
input_mod.compile_subgraph_reason = GraphCompileReason( # type: ignore[assignment]
|
| 232 |
+
"DDPOptimizer intentional graph-break (See Note [DDPOptimizer])."
|
| 233 |
+
" Set `torch._dynamo.config.optimize_ddp = False` to disable.",
|
| 234 |
+
[
|
| 235 |
+
# it's close to useless to get a real stacktrace here, and quite verbose.
|
| 236 |
+
traceback.FrameSummary(__file__, 0, "DDPOptimizer"),
|
| 237 |
+
],
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
wrapper = WrapperModule(
|
| 241 |
+
self.compiler(input_mod, args),
|
| 242 |
+
unwrap_singleton_tuple,
|
| 243 |
+
)
|
| 244 |
+
return wrapper
|
| 245 |
+
|
| 246 |
+
# Note:
|
| 247 |
+
#
|
| 248 |
+
# The way distributed works today around fake tensors can be somewhat confusing.
|
| 249 |
+
# Some of these codepaths are shared in both runtime, and compile time. The presence
|
| 250 |
+
# of a fake_mode, read off of fake tensor inputs, dictates how we will operate.
|
| 251 |
+
#
|
| 252 |
+
# A few things to keep in mind:
|
| 253 |
+
#
|
| 254 |
+
# 1) We invoke `compile_submod` with a real module. The output of that gets stored
|
| 255 |
+
# on the graph via `self.module.add_submodule(n.target, compiled_submod_real)`.
|
| 256 |
+
#
|
| 257 |
+
# 2) When running a call_module targeted node, if we have a fake_mode, we fakify the
|
| 258 |
+
# module we got from self.fetch_attr(n.target). Regardless of fake_mode, we then execute it.
|
| 259 |
+
#
|
| 260 |
+
# 3) Fake tensors should always be around during compile time.
|
| 261 |
+
#
|
| 262 |
+
# 4) Fake tensors should never be around at runtime.
|
| 263 |
+
#
|
| 264 |
+
# 5) We end up with a compilation mode that takes a real submodule and fake tensors,
|
| 265 |
+
# to match what aot_autograd expects. See Note: [Fake Modules and AOTAutograd]
|
| 266 |
+
def run_node(self, n: Node) -> Any:
|
| 267 |
+
args, kwargs = self.fetch_args_kwargs_from_env(n)
|
| 268 |
+
new_args = []
|
| 269 |
+
assert self.fake_mode
|
| 270 |
+
for arg in args:
|
| 271 |
+
if isinstance(arg, torch.Tensor) and not isinstance(
|
| 272 |
+
arg, torch._subclasses.FakeTensor
|
| 273 |
+
):
|
| 274 |
+
new_args.append(torch._dynamo.utils.to_fake_tensor(arg, self.fake_mode))
|
| 275 |
+
else:
|
| 276 |
+
new_args.append(arg)
|
| 277 |
+
|
| 278 |
+
log.debug("run_node %s, %s got args %s", n.op, n.target, args_str(args))
|
| 279 |
+
assert isinstance(args, tuple)
|
| 280 |
+
assert isinstance(kwargs, dict)
|
| 281 |
+
|
| 282 |
+
if n.op == "call_module":
|
| 283 |
+
real_mod = self.fetch_attr(str(n.target))
|
| 284 |
+
if self.fake_mode:
|
| 285 |
+
curr_submod = deepcopy_to_fake_tensor(real_mod, self.fake_mode)
|
| 286 |
+
else:
|
| 287 |
+
curr_submod = real_mod
|
| 288 |
+
|
| 289 |
+
ddp_graph_log.debug("\n---%s graph---\n%s", n.target, curr_submod.graph)
|
| 290 |
+
|
| 291 |
+
# When calling the compiler on the submod, inputs (new_args) are expected to
|
| 292 |
+
# be FakeTensors already since Dynamo would have made them FakeTensors in the
|
| 293 |
+
# non-DDP flow. However, the parameters are _not_ expected to be FakeTensors,
|
| 294 |
+
# since this wrapping happens during compilation
|
| 295 |
+
|
| 296 |
+
# Note: Returning Fake Tensors on First AOT Autograd Call
|
| 297 |
+
#
|
| 298 |
+
# Inductor will optimize strides of outputs when it deems it profitable.
|
| 299 |
+
# For instance, converting to channels last. When we split the graph here
|
| 300 |
+
# into multiple inductor compilations, we need to make sure that the
|
| 301 |
+
# output strides of one compilation is appropriately passed to the subsequent
|
| 302 |
+
# compilations. However, the mapping from inductor output to dynamo output
|
| 303 |
+
# is non-trivial due to aot_autograd's deduping, de-aliasing, mutation, re-writing,
|
| 304 |
+
# subclass handling, etc. In order to replay all this logic we set a flag such that
|
| 305 |
+
# the first invocation of inductor in aot_autograd will return Fake Tensors with
|
| 306 |
+
# appropriate strides. Then, all of aot autograd's runtime logic is replayed.
|
| 307 |
+
# This gives us the appropriately strided outputs here which will reflect runtime strides.
|
| 308 |
+
|
| 309 |
+
class FakeifyFirstAOTInvocationGuard:
|
| 310 |
+
def __init__(self) -> None:
|
| 311 |
+
self.tc = torch._guards.TracingContext.try_get()
|
| 312 |
+
assert self.tc
|
| 313 |
+
self.tc.fakify_first_call = True
|
| 314 |
+
|
| 315 |
+
def __del__(self) -> None:
|
| 316 |
+
self.tc.fakify_first_call = False # type: ignore[union-attr]
|
| 317 |
+
|
| 318 |
+
# For aot_eager and other backends, tracing context is not set
|
| 319 |
+
has_tracing_context = torch._guards.TracingContext.try_get() is not None
|
| 320 |
+
if has_tracing_context:
|
| 321 |
+
g = FakeifyFirstAOTInvocationGuard() # noqa: F841
|
| 322 |
+
|
| 323 |
+
from torch._dynamo.utils import counters
|
| 324 |
+
|
| 325 |
+
init = counters["aot_autograd"]["total"]
|
| 326 |
+
compiled_submod_real = self.compile_submod(real_mod, new_args, kwargs)
|
| 327 |
+
|
| 328 |
+
# TODO - better way of doing this?
|
| 329 |
+
# Only aot autograd handles fakifying first call
|
| 330 |
+
invoked_aot_autograd = init != counters["aot_autograd"]["total"]
|
| 331 |
+
|
| 332 |
+
# We update the original (outer) graph with a call into the compiled module
|
| 333 |
+
# instead of the uncompiled one.
|
| 334 |
+
self.module.delete_submodule(n.target) # type: ignore[operator]
|
| 335 |
+
n.target = "compiled_" + n.target # type: ignore[operator]
|
| 336 |
+
self.module.add_submodule(n.target, compiled_submod_real) # type: ignore[operator]
|
| 337 |
+
|
| 338 |
+
# Finally, we have to produce inputs for use compiling the next submodule,
|
| 339 |
+
# and these need to be FakeTensors, so we execute the module under fake_mode
|
| 340 |
+
# Because parameters are not fake we patch fake tensor mode to allow non fake inputs
|
| 341 |
+
with (
|
| 342 |
+
self.fake_mode,
|
| 343 |
+
mock.patch.object(self.fake_mode, "allow_non_fake_inputs", True),
|
| 344 |
+
):
|
| 345 |
+
if has_tracing_context and invoked_aot_autograd:
|
| 346 |
+
tracing_ctx = torch._guards.TracingContext.try_get()
|
| 347 |
+
assert tracing_ctx is not None
|
| 348 |
+
# DDPOptimizer maintains 1 dynamo graph -> N AOT graphs
|
| 349 |
+
# Dynamo only has 1 tracing context, so it needs to maintain all N AOT metadata instances
|
| 350 |
+
ddp_ctx = tracing_ctx.ddp_optimizer_ctx
|
| 351 |
+
assert ddp_ctx is not None
|
| 352 |
+
assert tracing_ctx.fw_metadata is not None
|
| 353 |
+
ddp_ctx.curr_bucket += 1
|
| 354 |
+
ddp_ctx.metadata_per_bucket.append(tracing_ctx.fw_metadata)
|
| 355 |
+
|
| 356 |
+
out = compiled_submod_real(*new_args, **kwargs)
|
| 357 |
+
# output should be fake or subclass
|
| 358 |
+
assert all(
|
| 359 |
+
(not isinstance(t, torch.Tensor) or type(t) is not torch.Tensor)
|
| 360 |
+
for t in (out if isinstance(out, (list, tuple)) else [out])
|
| 361 |
+
)
|
| 362 |
+
return out
|
| 363 |
+
else:
|
| 364 |
+
return curr_submod(*new_args, **kwargs)
|
| 365 |
+
else:
|
| 366 |
+
# placeholder or output nodes don't need to get compiled, just executed
|
| 367 |
+
return getattr(self, n.op)(n.target, new_args, kwargs)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class DDPOptimizer:
|
| 371 |
+
"""Note [DDPOptimizer]
|
| 372 |
+
DDPOptimizer applies when dynamo compiles models wrapped in DistributedDataParallel (DDP),
|
| 373 |
+
breaking the dynamo graph into chunks to compile separately, with the breaks aligning to
|
| 374 |
+
the boundaries of gradient-allreduce buckets chosen by DDP.
|
| 375 |
+
|
| 376 |
+
Background/Motivation
|
| 377 |
+
- DDP uses allreduce collectives to synchronize partial gradients computed on different workers
|
| 378 |
+
- DDP groups gradient allreduces into 'buckets' to optimize communication efficiency of all-reduce
|
| 379 |
+
- Parameters grouped into buckets are assumed to be adjacent in time, so they become ready
|
| 380 |
+
at around the same time during backward and thus can share the same allreduce efficiently
|
| 381 |
+
- Allreduces must overlap with backward compute for optimal training performance
|
| 382 |
+
- DDP schedules allreduces using 'hooks' fired from the c++ autograd engine in pytorch, which
|
| 383 |
+
operates when individual grads become 'ready'
|
| 384 |
+
- Dynamo+AOTAutograd produces a single fused graph that runs 'atomically' from the perspective of the
|
| 385 |
+
autograd engine, such that all gradients become 'ready' at the same time. Hooks fire after the whole
|
| 386 |
+
fused backward function executes, preventing any overlap of compute and communication
|
| 387 |
+
|
| 388 |
+
Algorithm
|
| 389 |
+
- DDPOptimizer starts off with an FX graph traced by dynamo which represents forward. It can traverse
|
| 390 |
+
this graph in reverse order to determine the true order that gradients will become ready during backward.
|
| 391 |
+
- Parameter sizes are counted in reverse order, up to a bucket size limit, at which point a new bucket is started
|
| 392 |
+
and a graph break introduced
|
| 393 |
+
- Each of the subgraphs is compiled by the compiler provided to dynamo by the user, and then fused back together
|
| 394 |
+
into an outer module that is returned to the user
|
| 395 |
+
|
| 396 |
+
Notes
|
| 397 |
+
- It would be better to enforce (by adding an API to DDP) that the bucket splits chosen here are used by DDP,
|
| 398 |
+
and that DDP does not need to detect or optimize bucket order by observing execution at runtime, as it does
|
| 399 |
+
in eager.
|
| 400 |
+
- If Dynamo can't capture a whole graph for the portion of the model wrapped by DDP, this algorithm will currently
|
| 401 |
+
produce splits that do not necessarily align with the buckets used by DDP. This should result in performance
|
| 402 |
+
degradation approaching the baseline case where graph-splits are not used, but not worse.
|
| 403 |
+
- If the backend compiler fails to compile a single subgraph, it will execute eagerly despite the rest of the
|
| 404 |
+
subgraphs being compiled
|
| 405 |
+
- DDP has a 'parameters_and_buffers_to_ignore' field, which DDPOptimizer attempts to honor by reading markers
|
| 406 |
+
left by DDP on individual parameters. In cases where other transformations, such as reparameterization, are
|
| 407 |
+
also used, the ignore markers could be lost. If DDPOptimizer fails to ignore a parameter ignored by DDP,
|
| 408 |
+
it is not catastrophic but could impact performance by choosing sub-optimal bucket splits.
|
| 409 |
+
- DDPOptimizer always ignores all buffers, regardless of their ignore flag, since buffers do not require gradients,
|
| 410 |
+
and therefore aren't allreduced by DDP. (They are broadcast during forward, but this is not covered by
|
| 411 |
+
DDPOptimizer)
|
| 412 |
+
|
| 413 |
+
Debugging
|
| 414 |
+
- Generally, it is easiest to debug DDPOptimizer in a single process program, using pdb.
|
| 415 |
+
- In many cases, the log messages are helpful (they show bucket size assignments)-
|
| 416 |
+
just set TORCH_LOGS env to include any of 'dynamo', 'distributed', or 'dist_ddp'.
|
| 417 |
+
- See `benchmarks/dynamo/distributed.py` for a simple harness that will run a toy model or a torchbench model
|
| 418 |
+
in a single process (or with torchrun, in multiple processes)
|
| 419 |
+
|
| 420 |
+
Args:
|
| 421 |
+
bucket_bytes_cap (int): Controls the size of buckets, in bytes, used to determine graphbreaks. Should be
|
| 422 |
+
set to match the equivalent parameter on the original DDP module.
|
| 423 |
+
|
| 424 |
+
backend_compile_fn (callable): A dynamo compiler function, to be invoked to compile each subgraph.
|
| 425 |
+
|
| 426 |
+
first_bucket_cap (int): Controls the size of the first bucket. Should match DDP's first bucket cap. DDP
|
| 427 |
+
special-cases the first bucket size since it is sometimes optimal to start a small allreduce early.
|
| 428 |
+
|
| 429 |
+
"""
|
| 430 |
+
|
| 431 |
+
def __init__(
|
| 432 |
+
self,
|
| 433 |
+
bucket_bytes_cap: int,
|
| 434 |
+
backend_compile_fn: CompilerFn,
|
| 435 |
+
first_bucket_cap: Optional[int] = None,
|
| 436 |
+
) -> None:
|
| 437 |
+
if first_bucket_cap is not None:
|
| 438 |
+
self.first_bucket_cap = first_bucket_cap
|
| 439 |
+
elif torch.distributed.is_available():
|
| 440 |
+
# this constant comes from C10D lib which is not always built
|
| 441 |
+
self.first_bucket_cap = torch.distributed._DEFAULT_FIRST_BUCKET_BYTES
|
| 442 |
+
else:
|
| 443 |
+
self.first_bucket_cap = bucket_bytes_cap
|
| 444 |
+
|
| 445 |
+
self.bucket_bytes_cap = bucket_bytes_cap
|
| 446 |
+
assert self.first_bucket_cap <= self.bucket_bytes_cap, (
|
| 447 |
+
"First bucket should be smaller/equal to other buckets to get comms warmed up ASAP"
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
self.backend_compile_fn = backend_compile_fn
|
| 451 |
+
|
| 452 |
+
def _ignore_parameter(self, parameter: torch.nn.Parameter) -> bool:
|
| 453 |
+
return hasattr(parameter, "_ddp_ignored") and parameter._ddp_ignored
|
| 454 |
+
|
| 455 |
+
def add_param(self, bucket: Bucket, param: torch.nn.Parameter, name: str) -> None:
|
| 456 |
+
bucket.size += param.untyped_storage().nbytes()
|
| 457 |
+
bucket.params.append(name)
|
| 458 |
+
bucket.param_ids.append(id(param))
|
| 459 |
+
|
| 460 |
+
def add_module_params_to_bucket(
|
| 461 |
+
self,
|
| 462 |
+
mod: torch.nn.Module,
|
| 463 |
+
bucket: Bucket,
|
| 464 |
+
processed_modules: set[torch.nn.Module],
|
| 465 |
+
prefix: str,
|
| 466 |
+
) -> None:
|
| 467 |
+
processed_modules.add(mod)
|
| 468 |
+
for name, param in mod.named_parameters():
|
| 469 |
+
if param.requires_grad and not self._ignore_parameter(param):
|
| 470 |
+
self.add_param(bucket, param, f"{prefix}_{name}")
|
| 471 |
+
|
| 472 |
+
def add_param_args(self, bucket: Bucket, node: fx.Node) -> None:
|
| 473 |
+
for arg in node.args:
|
| 474 |
+
if not isinstance(arg, torch.fx.node.Node):
|
| 475 |
+
continue
|
| 476 |
+
if arg.op != "placeholder":
|
| 477 |
+
continue
|
| 478 |
+
param = arg.meta["example_value"]
|
| 479 |
+
if (
|
| 480 |
+
isinstance(param, torch.nn.Parameter)
|
| 481 |
+
and param.requires_grad
|
| 482 |
+
and not self._ignore_parameter(param)
|
| 483 |
+
):
|
| 484 |
+
self.add_param(bucket, param, str(arg.target))
|
| 485 |
+
|
| 486 |
+
def compile_fn(
|
| 487 |
+
self, gm: fx.GraphModule, example_inputs: list[torch.Tensor]
|
| 488 |
+
) -> CompiledFn:
|
| 489 |
+
"""
|
| 490 |
+
Implements graph splitting, first determining a set of of buckets by counting
|
| 491 |
+
parameter sizes in reverse graph order, then invoking the user/backend compiler
|
| 492 |
+
to compile each subgraph. Finally, stiches compiled graphs into one graphmodule
|
| 493 |
+
and returns its callable.
|
| 494 |
+
"""
|
| 495 |
+
# 1: compute the partition map according to DDP bucket logic
|
| 496 |
+
buckets = [Bucket()] # (size, param_names)
|
| 497 |
+
processed_modules: set[torch.nn.Module] = set()
|
| 498 |
+
for node in reversed(gm.graph.nodes):
|
| 499 |
+
if node.op in ("output", "placeholder"):
|
| 500 |
+
continue
|
| 501 |
+
|
| 502 |
+
if (
|
| 503 |
+
buckets[0].size >= self.bucket_bytes_cap
|
| 504 |
+
or len(buckets) == 1
|
| 505 |
+
and buckets[0].size >= self.first_bucket_cap
|
| 506 |
+
):
|
| 507 |
+
if bucket_has_external_output(buckets[0]):
|
| 508 |
+
buckets.insert(0, Bucket())
|
| 509 |
+
else:
|
| 510 |
+
# continue building this bucket past the point of filling its parameter capacity,
|
| 511 |
+
# to increase chances it contains at least one node that is either a global output or
|
| 512 |
+
# passed as input to a subsequent graph
|
| 513 |
+
|
| 514 |
+
if buckets[0].opcount_increased_to_capture_external_output == 0:
|
| 515 |
+
buckets[0].paramsize_before_opcount_increase = buckets[0].size
|
| 516 |
+
buckets[0].opcount_increased_to_capture_external_output += 1
|
| 517 |
+
|
| 518 |
+
if node.op == "call_function":
|
| 519 |
+
self.add_param_args(buckets[0], node)
|
| 520 |
+
|
| 521 |
+
elif node.op == "call_module":
|
| 522 |
+
target_mod = gm.get_submodule(node.target)
|
| 523 |
+
if target_mod not in processed_modules:
|
| 524 |
+
self.add_module_params_to_bucket(
|
| 525 |
+
target_mod, buckets[0], processed_modules, node.target
|
| 526 |
+
)
|
| 527 |
+
elif node.op == "call_method":
|
| 528 |
+
if isinstance(node.args[0].target, str):
|
| 529 |
+
target_mod = None
|
| 530 |
+
try:
|
| 531 |
+
target_mod = gm.get_submodule(node.args[0].target)
|
| 532 |
+
except AttributeError:
|
| 533 |
+
pass
|
| 534 |
+
if target_mod is not None and target_mod not in processed_modules:
|
| 535 |
+
self.add_module_params_to_bucket(
|
| 536 |
+
target_mod, buckets[0], processed_modules, node.target
|
| 537 |
+
)
|
| 538 |
+
# This handles situations like tmp = torch.mm(x, self.weight.t())
|
| 539 |
+
# t: "f32[512, 512]" = l_self_seq_2_weight.t(); l_self_seq_2_weight = None
|
| 540 |
+
# tmp: "f32[512, 512]" = torch.mm(input_2, t); input_2 = t = None
|
| 541 |
+
self.add_param_args(buckets[0], node)
|
| 542 |
+
|
| 543 |
+
elif node.op == "get_attr":
|
| 544 |
+
maybe_param = getattr(gm, node.target)
|
| 545 |
+
if (
|
| 546 |
+
isinstance(maybe_param, torch.nn.Parameter)
|
| 547 |
+
and maybe_param.requires_grad
|
| 548 |
+
and not self._ignore_parameter(maybe_param)
|
| 549 |
+
):
|
| 550 |
+
self.add_param(buckets[0], maybe_param, node.target)
|
| 551 |
+
|
| 552 |
+
# All nodes have to be mapped to a bucket, even if they don't have their own params
|
| 553 |
+
# Ignored params still end up in buckets, we just don't count them towards the capacity
|
| 554 |
+
buckets[0].nodes.append(node)
|
| 555 |
+
|
| 556 |
+
if len(buckets) > 1 and buckets[0].size == 0:
|
| 557 |
+
# we collected a small preamble graph with ops that don't include parameters, fuse it back
|
| 558 |
+
buckets[1].nodes.extend(buckets[0].nodes)
|
| 559 |
+
assert len(buckets[0].params) == 0, "Params should be empty if size is 0"
|
| 560 |
+
del buckets[0]
|
| 561 |
+
|
| 562 |
+
# stash buckets for testing/debugging purposes
|
| 563 |
+
self.buckets = buckets
|
| 564 |
+
pretty_print_buckets(buckets, self.bucket_bytes_cap)
|
| 565 |
+
|
| 566 |
+
if len(buckets) == 1:
|
| 567 |
+
# bypass split/fuse logic if there is only one bucket
|
| 568 |
+
return self.backend_compile_fn(gm, example_inputs)
|
| 569 |
+
|
| 570 |
+
# 2: partition the graphmodule according to bucket capacity
|
| 571 |
+
partition_map = {}
|
| 572 |
+
for idx, b in enumerate(buckets):
|
| 573 |
+
for node in b.nodes:
|
| 574 |
+
partition_map[node] = idx
|
| 575 |
+
|
| 576 |
+
split_gm = fx.passes.split_module.split_module(
|
| 577 |
+
gm,
|
| 578 |
+
None, # type: ignore[arg-type]
|
| 579 |
+
lambda node: partition_map[node],
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# See note [Assumption on Dynamo Metadata]
|
| 583 |
+
propagate_dynamo_source(gm, split_gm)
|
| 584 |
+
propagate_metadata(gm, split_gm)
|
| 585 |
+
|
| 586 |
+
debug_str = (
|
| 587 |
+
f"\n---orig graph---\n{gm.graph}\n"
|
| 588 |
+
+ f"\n---split graph---\n{split_gm.graph}\n"
|
| 589 |
+
)
|
| 590 |
+
for name, module in split_gm.named_modules():
|
| 591 |
+
if "." not in name and len(name):
|
| 592 |
+
# only print the submod graphs, not their children
|
| 593 |
+
debug_str += f"\n---{name} graph---\n{module.graph}\n"
|
| 594 |
+
debug_str += "\n---------------\n"
|
| 595 |
+
ddp_graph_log.debug(debug_str)
|
| 596 |
+
|
| 597 |
+
trace_structured(
|
| 598 |
+
"optimize_ddp_split_graph",
|
| 599 |
+
payload_fn=lambda: split_gm.print_readable(print_output=False),
|
| 600 |
+
)
|
| 601 |
+
for name, module in split_gm.named_modules():
|
| 602 |
+
if "." not in name and len(name):
|
| 603 |
+
trace_structured(
|
| 604 |
+
"optimize_ddp_split_child",
|
| 605 |
+
lambda: {"name": name},
|
| 606 |
+
payload_fn=lambda: module.print_readable(print_output=False),
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
fake_mode = detect_fake_mode(example_inputs)
|
| 610 |
+
if fake_mode is None:
|
| 611 |
+
fake_mode = torch._subclasses.fake_tensor.FakeTensorMode()
|
| 612 |
+
|
| 613 |
+
submod_compiler = SubmodCompiler(split_gm, self.backend_compile_fn, fake_mode)
|
| 614 |
+
with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing():
|
| 615 |
+
submod_compiler.run(*example_inputs)
|
| 616 |
+
split_gm.recompile()
|
| 617 |
+
|
| 618 |
+
ddp_graph_log.debug(
|
| 619 |
+
"\n---final graph---\n%s\n---------------\n", split_gm.graph
|
| 620 |
+
)
|
| 621 |
+
return split_gm
|
miniconda3/envs/active_proaction/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)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/onnxrt.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This backend is maintained by ONNX team. To direct issues
|
| 2 |
+
# to the right people, please tag related GitHub issues with `module: onnx`.
|
| 3 |
+
#
|
| 4 |
+
# Maintainers' Github IDs: wschin, xadupre
|
| 5 |
+
# from torch.onnx._internal.onnxruntime import (
|
| 6 |
+
# is_onnxrt_backend_supported,
|
| 7 |
+
# torch_compile_backend,
|
| 8 |
+
# )
|
| 9 |
+
|
| 10 |
+
# from .registry import register_backend
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
Placeholder for onnxruntime backend for dynamo
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
# def has_onnxruntime():
|
| 17 |
+
# # FIXME: update test/dynamo/test_backends.py to call is_onnxrt_backend_supported()
|
| 18 |
+
# return is_onnxrt_backend_supported()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# if is_onnxrt_backend_supported():
|
| 22 |
+
# register_backend(name="onnxrt", compiler_fn=torch_compile_backend)
|
| 23 |
+
# else:
|
| 24 |
+
|
| 25 |
+
# def information_displaying_backend(*args, **kwargs):
|
| 26 |
+
# raise ImportError(
|
| 27 |
+
# "onnxrt is not registered as a backend. "
|
| 28 |
+
# "Please make sure all dependencies such as "
|
| 29 |
+
# "numpy, onnx, onnxscript, and onnxruntime-training are installed. "
|
| 30 |
+
# "Suggested procedure to fix dependency problem:\n"
|
| 31 |
+
# " (1) pip or conda install numpy onnx onnxscript onnxruntime-training.\n"
|
| 32 |
+
# " (2) Open a new python terminal.\n"
|
| 33 |
+
# " (3) Call the API `torch.onnx.is_onnxrt_backend_supported()`:\n"
|
| 34 |
+
# " (4) If it returns `True`, then you can use `onnxrt` backend.\n"
|
| 35 |
+
# " (5) If it returns `False`, please execute the package importing section in "
|
| 36 |
+
# "torch/onnx/_internal/onnxruntime.py under pdb line-by-line to see which import fails."
|
| 37 |
+
# )
|
| 38 |
+
|
| 39 |
+
# register_backend(name="onnxrt", compiler_fn=information_displaying_backend)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/registry.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements TorchDynamo's backend registry system for managing compiler backends.
|
| 3 |
+
|
| 4 |
+
The registry provides a centralized way to register, discover and manage different compiler
|
| 5 |
+
backends that can be used with torch.compile(). It handles:
|
| 6 |
+
|
| 7 |
+
- Backend registration and discovery through decorators and entry points
|
| 8 |
+
- Lazy loading of backend implementations
|
| 9 |
+
- Lookup and validation of backend names
|
| 10 |
+
- Categorization of backends using tags (debug, experimental, etc.)
|
| 11 |
+
|
| 12 |
+
Key components:
|
| 13 |
+
- CompilerFn: Type for backend compiler functions that transform FX graphs
|
| 14 |
+
- _BACKENDS: Registry mapping backend names to entry points
|
| 15 |
+
- _COMPILER_FNS: Registry mapping backend names to loaded compiler functions
|
| 16 |
+
|
| 17 |
+
Example usage:
|
| 18 |
+
@register_backend
|
| 19 |
+
def my_compiler(fx_graph, example_inputs):
|
| 20 |
+
# Transform FX graph into optimized implementation
|
| 21 |
+
return compiled_fn
|
| 22 |
+
|
| 23 |
+
# Use registered backend
|
| 24 |
+
torch.compile(model, backend="my_compiler")
|
| 25 |
+
|
| 26 |
+
The registry also supports discovering backends through setuptools entry points
|
| 27 |
+
in the "torch_dynamo_backends" group. Example:
|
| 28 |
+
```
|
| 29 |
+
setup.py
|
| 30 |
+
---
|
| 31 |
+
from setuptools import setup
|
| 32 |
+
|
| 33 |
+
setup(
|
| 34 |
+
name='my_torch_backend',
|
| 35 |
+
version='0.1',
|
| 36 |
+
packages=['my_torch_backend'],
|
| 37 |
+
entry_points={
|
| 38 |
+
'torch_dynamo_backends': [
|
| 39 |
+
# name = path to entry point of backend implementation
|
| 40 |
+
'my_compiler = my_torch_backend.compiler:my_compiler_function',
|
| 41 |
+
],
|
| 42 |
+
},
|
| 43 |
+
)
|
| 44 |
+
```
|
| 45 |
+
```
|
| 46 |
+
my_torch_backend/compiler.py
|
| 47 |
+
---
|
| 48 |
+
def my_compiler_function(fx_graph, example_inputs):
|
| 49 |
+
# Transform FX graph into optimized implementation
|
| 50 |
+
return compiled_fn
|
| 51 |
+
```
|
| 52 |
+
Using `my_compiler` backend:
|
| 53 |
+
```
|
| 54 |
+
import torch
|
| 55 |
+
|
| 56 |
+
model = ... # Your PyTorch model
|
| 57 |
+
optimized_model = torch.compile(model, backend="my_compiler")
|
| 58 |
+
```
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
import functools
|
| 62 |
+
import logging
|
| 63 |
+
from collections.abc import Callable, Sequence
|
| 64 |
+
from importlib.metadata import EntryPoint
|
| 65 |
+
from typing import Any, Optional, Protocol, Union
|
| 66 |
+
|
| 67 |
+
import torch
|
| 68 |
+
from torch import fx
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
log = logging.getLogger(__name__)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class CompiledFn(Protocol):
|
| 75 |
+
def __call__(self, *args: torch.Tensor) -> tuple[torch.Tensor, ...]: ...
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
CompilerFn = Callable[[fx.GraphModule, list[torch.Tensor]], CompiledFn]
|
| 79 |
+
|
| 80 |
+
_BACKENDS: dict[str, Optional[EntryPoint]] = {}
|
| 81 |
+
_COMPILER_FNS: dict[str, CompilerFn] = {}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def register_backend(
|
| 85 |
+
compiler_fn: Optional[CompilerFn] = None,
|
| 86 |
+
name: Optional[str] = None,
|
| 87 |
+
tags: Sequence[str] = (),
|
| 88 |
+
) -> Callable[..., Any]:
|
| 89 |
+
"""
|
| 90 |
+
Decorator to add a given compiler to the registry to allow calling
|
| 91 |
+
`torch.compile` with string shorthand. Note: for projects not
|
| 92 |
+
imported by default, it might be easier to pass a function directly
|
| 93 |
+
as a backend and not use a string.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
compiler_fn: Callable taking a FX graph and fake tensor inputs
|
| 97 |
+
name: Optional name, defaults to `compiler_fn.__name__`
|
| 98 |
+
tags: Optional set of string tags to categorize backend with
|
| 99 |
+
"""
|
| 100 |
+
if compiler_fn is None:
|
| 101 |
+
# @register_backend(name="") syntax
|
| 102 |
+
return functools.partial(register_backend, name=name, tags=tags) # type: ignore[return-value]
|
| 103 |
+
assert callable(compiler_fn)
|
| 104 |
+
name = name or compiler_fn.__name__
|
| 105 |
+
assert name not in _COMPILER_FNS, f"duplicate name: {name}"
|
| 106 |
+
if compiler_fn not in _BACKENDS:
|
| 107 |
+
_BACKENDS[name] = None
|
| 108 |
+
_COMPILER_FNS[name] = compiler_fn
|
| 109 |
+
compiler_fn._tags = tuple(tags) # type: ignore[attr-defined]
|
| 110 |
+
return compiler_fn
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
register_debug_backend = functools.partial(register_backend, tags=("debug",))
|
| 114 |
+
register_experimental_backend = functools.partial(
|
| 115 |
+
register_backend, tags=("experimental",)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def lookup_backend(compiler_fn: Union[str, CompilerFn]) -> CompilerFn:
|
| 120 |
+
"""Expand backend strings to functions"""
|
| 121 |
+
if isinstance(compiler_fn, str):
|
| 122 |
+
if compiler_fn not in _BACKENDS:
|
| 123 |
+
_lazy_import()
|
| 124 |
+
if compiler_fn not in _BACKENDS:
|
| 125 |
+
from ..exc import InvalidBackend
|
| 126 |
+
|
| 127 |
+
raise InvalidBackend(name=compiler_fn)
|
| 128 |
+
|
| 129 |
+
if compiler_fn not in _COMPILER_FNS:
|
| 130 |
+
entry_point = _BACKENDS[compiler_fn]
|
| 131 |
+
if entry_point is not None:
|
| 132 |
+
register_backend(compiler_fn=entry_point.load(), name=compiler_fn)
|
| 133 |
+
compiler_fn = _COMPILER_FNS[compiler_fn]
|
| 134 |
+
return compiler_fn
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# NOTE: can't type this due to public api mismatch; follow up with dev team
|
| 138 |
+
def list_backends(exclude_tags=("debug", "experimental")) -> list[str]: # type: ignore[no-untyped-def]
|
| 139 |
+
"""
|
| 140 |
+
Return valid strings that can be passed to:
|
| 141 |
+
|
| 142 |
+
torch.compile(..., backend="name")
|
| 143 |
+
"""
|
| 144 |
+
_lazy_import()
|
| 145 |
+
exclude_tags_set = set(exclude_tags or ())
|
| 146 |
+
|
| 147 |
+
backends = [
|
| 148 |
+
name
|
| 149 |
+
for name in _BACKENDS
|
| 150 |
+
if name not in _COMPILER_FNS
|
| 151 |
+
or not exclude_tags_set.intersection(_COMPILER_FNS[name]._tags) # type: ignore[attr-defined]
|
| 152 |
+
]
|
| 153 |
+
return sorted(backends)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@functools.cache
|
| 157 |
+
def _lazy_import() -> None:
|
| 158 |
+
from .. import backends
|
| 159 |
+
from ..utils import import_submodule
|
| 160 |
+
|
| 161 |
+
import_submodule(backends)
|
| 162 |
+
|
| 163 |
+
from ..repro.after_dynamo import dynamo_minifier_backend
|
| 164 |
+
|
| 165 |
+
assert dynamo_minifier_backend is not None
|
| 166 |
+
|
| 167 |
+
_discover_entrypoint_backends()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@functools.cache
|
| 171 |
+
def _discover_entrypoint_backends() -> None:
|
| 172 |
+
# importing here so it will pick up the mocked version in test_backends.py
|
| 173 |
+
from importlib.metadata import entry_points
|
| 174 |
+
|
| 175 |
+
group_name = "torch_dynamo_backends"
|
| 176 |
+
eps = entry_points(group=group_name)
|
| 177 |
+
eps_dict = {name: eps[name] for name in eps.names}
|
| 178 |
+
for backend_name in eps_dict:
|
| 179 |
+
_BACKENDS[backend_name] = eps_dict[backend_name]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/tensorrt.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import torch # type: ignore[import]
|
| 2 |
+
# from .common import device_from_inputs, fake_tensor_unsupported # type: ignore[import]
|
| 3 |
+
# from .registry import register_backend # type: ignore[import]
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
Placeholder for TensorRT backend for dynamo via torch-tensorrt
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# @register_backend
|
| 10 |
+
# def tensorrt(gm, example_inputs):
|
| 11 |
+
# import torch_tensorrt # type: ignore[import]
|
| 12 |
+
# pass
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/torchxla.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from functorch.compile import make_boxed_func
|
| 7 |
+
from torch import fx
|
| 8 |
+
|
| 9 |
+
from ..backends.common import aot_autograd
|
| 10 |
+
from .registry import CompiledFn, register_backend, register_experimental_backend
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@register_experimental_backend
|
| 17 |
+
def openxla_eval(
|
| 18 |
+
model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor]
|
| 19 |
+
) -> CompiledFn:
|
| 20 |
+
return xla_backend_helper(model, fake_tensor_inputs, boxed=False)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def openxla_eval_boxed(
|
| 24 |
+
model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor]
|
| 25 |
+
) -> Callable[..., Any]:
|
| 26 |
+
return xla_backend_helper(model, fake_tensor_inputs, boxed=True)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def xla_backend_helper(
|
| 30 |
+
model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], boxed: bool = False
|
| 31 |
+
) -> Callable[..., Any]:
|
| 32 |
+
try:
|
| 33 |
+
import torch_xla.core.dynamo_bridge as bridge
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
raise ImportError(
|
| 36 |
+
"Please follow the instruction in https://github.com/pytorch/xla#pytorchxla to install torch_xla"
|
| 37 |
+
) from e
|
| 38 |
+
|
| 39 |
+
compiled_graph = None
|
| 40 |
+
|
| 41 |
+
def fwd(*args: torch.Tensor) -> Any:
|
| 42 |
+
nonlocal model
|
| 43 |
+
nonlocal compiled_graph
|
| 44 |
+
if compiled_graph is None:
|
| 45 |
+
compiled_graph = bridge.extract_compiled_graph(model, args)
|
| 46 |
+
del model
|
| 47 |
+
return compiled_graph(*args)
|
| 48 |
+
|
| 49 |
+
return make_boxed_func(fwd) if boxed else fwd
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
openxla = aot_autograd(
|
| 53 |
+
fw_compiler=openxla_eval_boxed,
|
| 54 |
+
)
|
| 55 |
+
register_backend(name="openxla", compiler_fn=openxla)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/backends/tvm.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides TVM backend integration for TorchDynamo.
|
| 3 |
+
|
| 4 |
+
Apache TVM is a deep learning compiler framework that can optimize and execute
|
| 5 |
+
models on various hardware backends. This module enables:
|
| 6 |
+
|
| 7 |
+
- Compilation of PyTorch models to TVM's computation graphs
|
| 8 |
+
- Multiple scheduling options:
|
| 9 |
+
- Default scheduler
|
| 10 |
+
- Auto-scheduler for automatic optimization
|
| 11 |
+
- Meta-schedule for evolutionary search-based tuning
|
| 12 |
+
- Hardware-specific optimizations:
|
| 13 |
+
- CUDA GPU support
|
| 14 |
+
- CPU support with LLVM targeting and architecture-specific tuning
|
| 15 |
+
- Automatic detection of CPU capabilities (AVX2, AVX512)
|
| 16 |
+
- Tensor conversion utilities between PyTorch and TVM formats
|
| 17 |
+
- Configurable optimization levels and tuning trials
|
| 18 |
+
|
| 19 |
+
The backend can be used with torch.compile():
|
| 20 |
+
model = torch.compile(model, backend="tvm")
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import functools
|
| 24 |
+
import importlib
|
| 25 |
+
import logging
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
import tempfile
|
| 29 |
+
from collections.abc import Callable
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from types import MappingProxyType
|
| 32 |
+
from typing import Any, Optional
|
| 33 |
+
|
| 34 |
+
import torch
|
| 35 |
+
from torch import fx
|
| 36 |
+
|
| 37 |
+
from .common import device_from_inputs, fake_tensor_unsupported
|
| 38 |
+
from .registry import register_backend
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
log = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@register_backend
|
| 45 |
+
@fake_tensor_unsupported # type: ignore[arg-type]
|
| 46 |
+
def tvm(
|
| 47 |
+
gm: fx.GraphModule,
|
| 48 |
+
example_inputs: list[torch.Tensor],
|
| 49 |
+
*,
|
| 50 |
+
options: Optional[MappingProxyType[str, Any]] = None,
|
| 51 |
+
) -> Callable[..., Any]:
|
| 52 |
+
if options is None:
|
| 53 |
+
options = MappingProxyType({"scheduler": None, "trials": 20000, "opt_level": 3})
|
| 54 |
+
assert options is not None
|
| 55 |
+
import tvm # type: ignore[import]
|
| 56 |
+
from tvm import relay # type: ignore[import]
|
| 57 |
+
from tvm.contrib import graph_executor # type: ignore[import]
|
| 58 |
+
|
| 59 |
+
jit_mod = torch.jit.trace(gm, example_inputs)
|
| 60 |
+
device = device_from_inputs(example_inputs)
|
| 61 |
+
shape_list = [(f"inp_{idx}", i.shape) for idx, i in enumerate(example_inputs)]
|
| 62 |
+
example_outputs = gm(*example_inputs)
|
| 63 |
+
if len(example_outputs) == 0:
|
| 64 |
+
log.warning("Explicitly fall back to eager due to zero output")
|
| 65 |
+
return gm.forward
|
| 66 |
+
mod, params = relay.frontend.from_pytorch(jit_mod, shape_list)
|
| 67 |
+
if device.type == "cuda":
|
| 68 |
+
dev = tvm.cuda(device.index)
|
| 69 |
+
target = tvm.target.cuda()
|
| 70 |
+
else:
|
| 71 |
+
dev = tvm.cpu(0)
|
| 72 |
+
target = tvm.target.Target(llvm_target())
|
| 73 |
+
|
| 74 |
+
scheduler = options.get("scheduler", None)
|
| 75 |
+
if scheduler is None:
|
| 76 |
+
scheduler = os.environ.get("TVM_SCHEDULER", None)
|
| 77 |
+
|
| 78 |
+
trials = options.get("trials", 20000)
|
| 79 |
+
opt_level = options.get("opt_level", 3)
|
| 80 |
+
|
| 81 |
+
if scheduler == "auto_scheduler":
|
| 82 |
+
# pyrefly: ignore [import-error]
|
| 83 |
+
from tvm import auto_scheduler
|
| 84 |
+
|
| 85 |
+
with (
|
| 86 |
+
tempfile.NamedTemporaryFile() as log_file,
|
| 87 |
+
auto_scheduler.ApplyHistoryBest(log_file),
|
| 88 |
+
tvm.transform.PassContext(
|
| 89 |
+
opt_level=opt_level, config={"relay.backend.use_auto_scheduler": True}
|
| 90 |
+
),
|
| 91 |
+
):
|
| 92 |
+
lib = relay.build(mod, target=target, params=params)
|
| 93 |
+
elif scheduler == "meta_schedule":
|
| 94 |
+
# pyrefly: ignore [import-error]
|
| 95 |
+
from tvm import meta_schedule as ms
|
| 96 |
+
|
| 97 |
+
with tempfile.TemporaryDirectory() as work_dir:
|
| 98 |
+
if device.type != "cuda":
|
| 99 |
+
# meta_schedule needs num-cores to be specified
|
| 100 |
+
# here we use the maximum core count
|
| 101 |
+
target = tvm.target.Target(
|
| 102 |
+
f"{llvm_target()} --num-cores {ms.utils.cpu_count(logical=False)}"
|
| 103 |
+
)
|
| 104 |
+
# TODO(shingjan): This could be replaced by tvm.contrib.torch.optimize_torch
|
| 105 |
+
# once USE_PT_TVMDSOOP is updated and turned on by default in TVM.
|
| 106 |
+
assert trials > 0
|
| 107 |
+
database = ms.relay_integration.tune_relay(
|
| 108 |
+
mod=mod,
|
| 109 |
+
target=target,
|
| 110 |
+
work_dir=work_dir,
|
| 111 |
+
max_trials_global=trials,
|
| 112 |
+
num_trials_per_iter=64,
|
| 113 |
+
params=params,
|
| 114 |
+
strategy="evolutionary",
|
| 115 |
+
opt_level=opt_level,
|
| 116 |
+
)
|
| 117 |
+
lib = ms.relay_integration.compile_relay(
|
| 118 |
+
database=database,
|
| 119 |
+
mod=mod,
|
| 120 |
+
target=target,
|
| 121 |
+
params=params,
|
| 122 |
+
opt_level=opt_level,
|
| 123 |
+
)
|
| 124 |
+
elif scheduler == "default" or not scheduler:
|
| 125 |
+
# no autotuning
|
| 126 |
+
with tvm.transform.PassContext(opt_level=opt_level):
|
| 127 |
+
lib = relay.build(mod, target=target, params=params)
|
| 128 |
+
else:
|
| 129 |
+
raise NotImplementedError(
|
| 130 |
+
"This tuning option is invalid/not implemented for torchdynamo's TVM-related backend. "
|
| 131 |
+
"There are three available options: default, auto_scheduler and meta_schedule."
|
| 132 |
+
)
|
| 133 |
+
m = graph_executor.GraphModule(lib["default"](dev))
|
| 134 |
+
|
| 135 |
+
def to_torch_tensor(nd_tensor: tvm.nd.array) -> torch.Tensor:
|
| 136 |
+
"""A helper function to transfer a NDArray to torch.tensor."""
|
| 137 |
+
if nd_tensor.dtype == "bool":
|
| 138 |
+
# DLPack does not support boolean so it can't be handled by
|
| 139 |
+
# torch.utils.dlpack.from_pack. Workaround by going through
|
| 140 |
+
# numpy, although this brings additional data copy overhead.
|
| 141 |
+
return torch.from_numpy(nd_tensor.numpy())
|
| 142 |
+
return torch.utils.dlpack.from_dlpack(nd_tensor.to_dlpack())
|
| 143 |
+
|
| 144 |
+
def to_tvm_tensor(torch_tensor: torch.Tensor) -> tvm.nd.array:
|
| 145 |
+
"""A helper function to transfer a torch.tensor to NDArray."""
|
| 146 |
+
if torch_tensor.dtype == torch.bool:
|
| 147 |
+
# same reason as above, fallback to numpy conversion which
|
| 148 |
+
# could introduce data copy overhead
|
| 149 |
+
return tvm.nd.array(torch_tensor.cpu().numpy())
|
| 150 |
+
return tvm.nd.from_dlpack(torch_tensor)
|
| 151 |
+
|
| 152 |
+
def exec_tvm(*i_args: torch.Tensor) -> list[torch.Tensor]:
|
| 153 |
+
args = [a.contiguous() for a in i_args]
|
| 154 |
+
shape_info, _ = m.get_input_info()
|
| 155 |
+
active_inputs = {name for name, _ in shape_info.items()}
|
| 156 |
+
for idx, arg in enumerate(args, 0):
|
| 157 |
+
if arg.dim() != 0:
|
| 158 |
+
if arg.requires_grad:
|
| 159 |
+
arg = arg.detach()
|
| 160 |
+
inp_name = f"inp_{idx}"
|
| 161 |
+
if inp_name not in active_inputs:
|
| 162 |
+
log.warning(
|
| 163 |
+
"input %s skipped as not found in tvm's runtime library",
|
| 164 |
+
inp_name,
|
| 165 |
+
)
|
| 166 |
+
continue
|
| 167 |
+
m.set_input(
|
| 168 |
+
inp_name,
|
| 169 |
+
to_tvm_tensor(arg),
|
| 170 |
+
)
|
| 171 |
+
m.run()
|
| 172 |
+
return [to_torch_tensor(m.get_output(i)) for i in range(m.get_num_outputs())]
|
| 173 |
+
|
| 174 |
+
return exec_tvm
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
tvm_meta_schedule = functools.partial(tvm, scheduler="meta_schedule")
|
| 178 |
+
tvm_auto_scheduler = functools.partial(tvm, scheduler="auto_scheduler")
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def has_tvm() -> bool:
|
| 182 |
+
try:
|
| 183 |
+
importlib.import_module("tvm")
|
| 184 |
+
return True
|
| 185 |
+
except ImportError:
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@functools.cache
|
| 190 |
+
def llvm_target() -> str:
|
| 191 |
+
if sys.platform == "linux":
|
| 192 |
+
cpuinfo = Path("/proc/cpuinfo").read_text()
|
| 193 |
+
if "avx512" in cpuinfo:
|
| 194 |
+
return "llvm -mcpu=skylake-avx512"
|
| 195 |
+
elif "avx2" in cpuinfo:
|
| 196 |
+
return "llvm -mcpu=core-avx2"
|
| 197 |
+
return "llvm"
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/funcname_cache.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides functionality for caching and looking up fully qualified function
|
| 3 |
+
and class names from Python source files by line number.
|
| 4 |
+
|
| 5 |
+
It uses Python's tokenize module to parse source files and tracks function/class
|
| 6 |
+
definitions along with their nesting to build fully qualified names (e.g. 'class.method'
|
| 7 |
+
or 'module.function'). The results are cached in a two-level dictionary mapping:
|
| 8 |
+
|
| 9 |
+
filename -> (line_number -> fully_qualified_name)
|
| 10 |
+
|
| 11 |
+
Example usage:
|
| 12 |
+
name = get_funcname("myfile.py", 42) # Returns name of function/class at line 42
|
| 13 |
+
clearcache() # Clear the cache if file contents have changed
|
| 14 |
+
|
| 15 |
+
The parsing is done lazily when a file is first accessed. Invalid Python files or
|
| 16 |
+
IO errors are handled gracefully by returning empty cache entries.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import tokenize
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
cache: dict[str, dict[int, str]] = {}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def clearcache() -> None:
|
| 27 |
+
cache.clear()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _add_file(filename: str) -> None:
|
| 31 |
+
try:
|
| 32 |
+
with tokenize.open(filename) as f:
|
| 33 |
+
tokens = list(tokenize.generate_tokens(f.readline))
|
| 34 |
+
except (OSError, tokenize.TokenError):
|
| 35 |
+
cache[filename] = {}
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
# NOTE: undefined behavior if file is not valid Python source,
|
| 39 |
+
# since tokenize will have undefined behavior.
|
| 40 |
+
result: dict[int, str] = {}
|
| 41 |
+
# current full funcname, e.g. xxx.yyy.zzz
|
| 42 |
+
cur_name = ""
|
| 43 |
+
cur_indent = 0
|
| 44 |
+
significant_indents: list[int] = []
|
| 45 |
+
|
| 46 |
+
for i, token in enumerate(tokens):
|
| 47 |
+
if token.type == tokenize.INDENT:
|
| 48 |
+
cur_indent += 1
|
| 49 |
+
elif token.type == tokenize.DEDENT:
|
| 50 |
+
cur_indent -= 1
|
| 51 |
+
# possible end of function or class
|
| 52 |
+
if significant_indents and cur_indent == significant_indents[-1]:
|
| 53 |
+
significant_indents.pop()
|
| 54 |
+
# pop the last name
|
| 55 |
+
cur_name = cur_name.rpartition(".")[0]
|
| 56 |
+
elif (
|
| 57 |
+
token.type == tokenize.NAME
|
| 58 |
+
and i + 1 < len(tokens)
|
| 59 |
+
and tokens[i + 1].type == tokenize.NAME
|
| 60 |
+
and (token.string == "class" or token.string == "def")
|
| 61 |
+
):
|
| 62 |
+
# name of class/function always follows class/def token
|
| 63 |
+
significant_indents.append(cur_indent)
|
| 64 |
+
if cur_name:
|
| 65 |
+
cur_name += "."
|
| 66 |
+
cur_name += tokens[i + 1].string
|
| 67 |
+
result[token.start[0]] = cur_name
|
| 68 |
+
|
| 69 |
+
cache[filename] = result
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_funcname(filename: str, lineno: int) -> Optional[str]:
|
| 73 |
+
if filename not in cache:
|
| 74 |
+
_add_file(filename)
|
| 75 |
+
return cache[filename].get(lineno, None)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/functional_export.py
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
from collections import namedtuple
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.fx
|
| 14 |
+
import torch.utils._pytree as pytree
|
| 15 |
+
from torch._dispatch.python import enable_python_dispatcher
|
| 16 |
+
from torch._dynamo.convert_frame import CaptureOutput, fullgraph_capture, get_traced_fn
|
| 17 |
+
from torch._dynamo.eval_frame import argument_names, check_user_input_output
|
| 18 |
+
from torch._dynamo.exc import UserErrorType
|
| 19 |
+
from torch._dynamo.utils import dynamo_timed, get_metrics_context
|
| 20 |
+
from torch._export.utils import _compiling_state_context
|
| 21 |
+
from torch._guards import TracingContext
|
| 22 |
+
from torch.export.dynamic_shapes import _RelaxedConstraint, Constraint
|
| 23 |
+
from torch.fx import Node
|
| 24 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 25 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 26 |
+
ConstraintViolationError,
|
| 27 |
+
DimDynamic,
|
| 28 |
+
ShapeEnv,
|
| 29 |
+
StatelessSymbolicContext,
|
| 30 |
+
)
|
| 31 |
+
from torch.fx.graph import _ExportCodeGen, _PyTreeCodeGen, _PyTreeInfo
|
| 32 |
+
from torch.utils._pytree import TreeSpec
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
log = logging.getLogger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def post_process_error_msg(
|
| 43 |
+
constraint_violation_error: ConstraintViolationError,
|
| 44 |
+
func: Callable[..., Any],
|
| 45 |
+
args: Any,
|
| 46 |
+
kwargs: Any,
|
| 47 |
+
):
|
| 48 |
+
"""
|
| 49 |
+
Because we trace a different callable, the sources are all messed up.
|
| 50 |
+
Manually patch them so the error message looks correct.
|
| 51 |
+
"""
|
| 52 |
+
from torch.export._unlift import _get_input_paths, _replace_sources
|
| 53 |
+
|
| 54 |
+
orig_sig = inspect.signature(func)
|
| 55 |
+
flat_input_paths = _get_input_paths((args, kwargs), orig_sig)
|
| 56 |
+
if constraint_violation_error.args:
|
| 57 |
+
constraint_violation_error.args = (
|
| 58 |
+
_replace_sources(constraint_violation_error.args[0], flat_input_paths),
|
| 59 |
+
)
|
| 60 |
+
return constraint_violation_error
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
EXPORT_ROOT_REPLACEMENTS = [
|
| 64 |
+
("__export_root_", "_"),
|
| 65 |
+
("_export_root.", ""),
|
| 66 |
+
("._export_root", ""),
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def clean_export_root_string(text: str) -> str:
|
| 71 |
+
"""Generic utility to clean export_root patterns from strings."""
|
| 72 |
+
result = text
|
| 73 |
+
for pattern, replacement in EXPORT_ROOT_REPLACEMENTS:
|
| 74 |
+
result = result.replace(pattern, replacement)
|
| 75 |
+
return result
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def clean_nn_module_stack_and_source_fn(
|
| 79 |
+
graph_module: torch.fx.GraphModule, is_inline_builtin=False
|
| 80 |
+
) -> torch.fx.GraphModule:
|
| 81 |
+
"""
|
| 82 |
+
Clean up nn_module_stack metadata by removing export_root references.
|
| 83 |
+
|
| 84 |
+
Removes the _export_root module references from nn_module_stack metadata
|
| 85 |
+
in graph nodes, which are artifacts from the export process. Fixes two patterns:
|
| 86 |
+
|
| 87 |
+
1. Keys: Removes "__export_root_" and "__modules['_export_root']_" prefixes
|
| 88 |
+
- Normal case: "L__self____export_root_child" -> "L__self__child"
|
| 89 |
+
- inline_builtin case: Uses numeric ID strings like "140468831433840"
|
| 90 |
+
|
| 91 |
+
2. Values: Removes "._export_root" and "._modules['_export_root']" from child names
|
| 92 |
+
e.g., "L['self']._export_root.child" -> "L['self'].child"
|
| 93 |
+
e.g., "L['self']._modules['_export_root'].child" -> "L['self'].child"
|
| 94 |
+
|
| 95 |
+
Also removes the root export entry "L__self____export_root" entirely.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
graph_module: The GraphModule to clean up
|
| 99 |
+
is_inline_builtin: If True, keys are numeric ID strings and self references
|
| 100 |
+
(L['self']) are filtered out
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
The cleaned GraphModule (modified in-place)
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def _process_nn_module_stack(nn_module_stack):
|
| 107 |
+
if "L__self____export_root" in nn_module_stack:
|
| 108 |
+
del nn_module_stack["L__self____export_root"]
|
| 109 |
+
|
| 110 |
+
# Clean up remaining entries
|
| 111 |
+
cleaned_stack = {}
|
| 112 |
+
for key, (child_name, child_class) in nn_module_stack.items():
|
| 113 |
+
# Clean key by removing export_root patterns
|
| 114 |
+
clean_key = clean_export_root_string(key)
|
| 115 |
+
|
| 116 |
+
# Clean child_name by removing export_root patterns
|
| 117 |
+
clean_name = clean_export_root_string(child_name)
|
| 118 |
+
|
| 119 |
+
# Skip self reference for inline builtin case
|
| 120 |
+
if is_inline_builtin and clean_name == "L['self']":
|
| 121 |
+
continue
|
| 122 |
+
|
| 123 |
+
cleaned_stack[clean_key] = (clean_name, child_class)
|
| 124 |
+
return cleaned_stack
|
| 125 |
+
|
| 126 |
+
def _process_source_fn(source_fn_stack):
|
| 127 |
+
cleaned_stack = []
|
| 128 |
+
for item in source_fn_stack:
|
| 129 |
+
if isinstance(item, tuple) and len(item) == 2:
|
| 130 |
+
name, cls = item
|
| 131 |
+
if isinstance(name, str):
|
| 132 |
+
clean_name = clean_export_root_string(name)
|
| 133 |
+
cleaned_stack.append((clean_name, cls))
|
| 134 |
+
else:
|
| 135 |
+
cleaned_stack.append(item)
|
| 136 |
+
else:
|
| 137 |
+
cleaned_stack.append(item)
|
| 138 |
+
return cleaned_stack
|
| 139 |
+
|
| 140 |
+
for node in graph_module.graph.nodes:
|
| 141 |
+
if "nn_module_stack" in node.meta:
|
| 142 |
+
node.meta["nn_module_stack"] = _process_nn_module_stack(
|
| 143 |
+
node.meta["nn_module_stack"].copy()
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
source_fn_stack = node.meta.get("source_fn_stack", None)
|
| 147 |
+
if source_fn_stack:
|
| 148 |
+
node.meta["source_fn_stack"] = _process_source_fn(source_fn_stack.copy())
|
| 149 |
+
|
| 150 |
+
if "dynamo_flat_name_to_original_fqn" in graph_module.meta:
|
| 151 |
+
# Clean up flat name to original fqn mapping
|
| 152 |
+
clean_name_to_original_fqn = {}
|
| 153 |
+
for flat_name, original_fqn in graph_module.meta[
|
| 154 |
+
"dynamo_flat_name_to_original_fqn"
|
| 155 |
+
].items():
|
| 156 |
+
clean_name_to_original_fqn[clean_export_root_string(flat_name)] = (
|
| 157 |
+
clean_export_root_string(original_fqn)
|
| 158 |
+
)
|
| 159 |
+
graph_module.meta["dynamo_flat_name_to_original_fqn"] = (
|
| 160 |
+
clean_name_to_original_fqn
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return graph_module
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def clean_export_root(graph_module: torch.fx.GraphModule) -> None:
|
| 167 |
+
"""Remove export_root artifacts from FX graph in-place"""
|
| 168 |
+
|
| 169 |
+
# Unlike getattr node, call_module can be invoked multiple times
|
| 170 |
+
# In those cases, we should fix all invocations of call_module
|
| 171 |
+
clean_named_module_map: dict[str, str] = {}
|
| 172 |
+
|
| 173 |
+
# Update get_attr nodes in-place
|
| 174 |
+
for node in graph_module.graph.nodes:
|
| 175 |
+
if node.op == "get_attr":
|
| 176 |
+
old_target = node.target
|
| 177 |
+
new_target = clean_export_root_string(old_target)
|
| 178 |
+
if new_target != old_target:
|
| 179 |
+
node.target = new_target
|
| 180 |
+
assert hasattr(graph_module, old_target)
|
| 181 |
+
# Move the parameter to the new name
|
| 182 |
+
param = torch.fx.graph_module._get_attr(graph_module, old_target)
|
| 183 |
+
torch.fx.graph_module._assign_attr(param, graph_module, new_target)
|
| 184 |
+
torch.fx.graph_module._del_attr(graph_module, old_target)
|
| 185 |
+
# Dynamo will only have one nested level
|
| 186 |
+
if node.op == "call_module":
|
| 187 |
+
old_target = node.target
|
| 188 |
+
assert isinstance(old_target, str)
|
| 189 |
+
new_target = clean_export_root_string(old_target)
|
| 190 |
+
assert isinstance(new_target, str)
|
| 191 |
+
new_name = clean_export_root_string(node.name)
|
| 192 |
+
if new_target == old_target:
|
| 193 |
+
continue
|
| 194 |
+
|
| 195 |
+
# if this module has already been cleaned before, just lookup from map.
|
| 196 |
+
if old_target in clean_named_module_map:
|
| 197 |
+
node.target = clean_named_module_map[old_target]
|
| 198 |
+
node.name = new_name
|
| 199 |
+
continue
|
| 200 |
+
target = graph_module.get_submodule(old_target)
|
| 201 |
+
graph_module.delete_submodule(old_target)
|
| 202 |
+
graph_module.add_submodule(new_target, target)
|
| 203 |
+
node.target = new_target
|
| 204 |
+
node.name = new_name
|
| 205 |
+
clean_named_module_map[old_target] = new_target
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class ModuleToTrace(torch.nn.Module):
|
| 209 |
+
def __init__(self, foo: Any, in_spec: Any) -> None:
|
| 210 |
+
super().__init__()
|
| 211 |
+
self._export_root = foo
|
| 212 |
+
self.in_spec = in_spec
|
| 213 |
+
|
| 214 |
+
def forward(self, *flat_args: Any) -> "ExportTracerOutput":
|
| 215 |
+
args, kwargs = pytree.tree_unflatten(flat_args, self.in_spec)
|
| 216 |
+
res = self._export_root(*args, **kwargs)
|
| 217 |
+
out_flat, out_spec = pytree.tree_flatten(res)
|
| 218 |
+
return ExportTracerOutput(out_flat, out_spec)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
ExportTracerOutput = namedtuple("ExportTracerOutput", ["flat_args", "out_spec"])
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# mypy: disable-error-code="no-untyped-def,var-annotated,assignment,index,operator"
|
| 225 |
+
class DynamoGraphTransformer(torch.fx.Transformer):
|
| 226 |
+
"""Graph transformer for dynamo export that flattens inputs/outputs without complex matching."""
|
| 227 |
+
|
| 228 |
+
def __init__(
|
| 229 |
+
self,
|
| 230 |
+
module: torch.fx.GraphModule,
|
| 231 |
+
flat_inputs: list[Any],
|
| 232 |
+
flat_args_dynamic_dims: list[set[int]],
|
| 233 |
+
graph_input_order: dict[int, int],
|
| 234 |
+
graph_output_map: dict[int, tuple[str, Any]],
|
| 235 |
+
fake_mode: Optional[Any] = None,
|
| 236 |
+
) -> None:
|
| 237 |
+
super().__init__(module)
|
| 238 |
+
|
| 239 |
+
assert len(flat_args_dynamic_dims) == len(flat_inputs)
|
| 240 |
+
|
| 241 |
+
self.flat_inputs = flat_inputs
|
| 242 |
+
self.flat_args_dynamic_dims = flat_args_dynamic_dims
|
| 243 |
+
self.graph_input_order = graph_input_order
|
| 244 |
+
self.graph_output_map = graph_output_map
|
| 245 |
+
self.fake_mode = fake_mode
|
| 246 |
+
|
| 247 |
+
# Get original placeholders and output
|
| 248 |
+
self.placeholders = [n for n in module.graph.nodes if n.op == "placeholder"]
|
| 249 |
+
self.output_node = next(n for n in module.graph.nodes if n.op == "output")
|
| 250 |
+
|
| 251 |
+
# Create new flattened input placeholders
|
| 252 |
+
self.new_input_nodes: dict[int, torch.fx.Node] = {}
|
| 253 |
+
self._create_flattened_inputs()
|
| 254 |
+
|
| 255 |
+
# Iterator for replacing old placeholders
|
| 256 |
+
self.old_to_new_mapping = {}
|
| 257 |
+
self._create_placeholder_mapping()
|
| 258 |
+
|
| 259 |
+
def _create_flattened_inputs(self) -> None:
|
| 260 |
+
"""Create new placeholder nodes for flattened inputs with proper fake tensors."""
|
| 261 |
+
for i in range(len(self.flat_inputs)):
|
| 262 |
+
placeholder = super().placeholder(f"arg_{i}", (), {})
|
| 263 |
+
|
| 264 |
+
# Check if this user input (index i) maps to a graph placeholder
|
| 265 |
+
if i in self.graph_input_order:
|
| 266 |
+
# graph_input_order[i] gives us which graph placeholder this user input corresponds to
|
| 267 |
+
graph_placeholder_idx = self.graph_input_order[i]
|
| 268 |
+
if graph_placeholder_idx < len(self.placeholders):
|
| 269 |
+
orig_placeholder = self.placeholders[graph_placeholder_idx]
|
| 270 |
+
# Copy other metadata but not "val" yet
|
| 271 |
+
for key, value in orig_placeholder.meta.items():
|
| 272 |
+
if key != "val":
|
| 273 |
+
placeholder.node.meta[key] = value
|
| 274 |
+
|
| 275 |
+
# Always ensure we have proper "val" metadata from fake tensor
|
| 276 |
+
if self.fake_mode is not None and isinstance(
|
| 277 |
+
self.flat_inputs[i], torch.Tensor
|
| 278 |
+
):
|
| 279 |
+
placeholder.node.meta["val"] = self.fake_mode.from_tensor(
|
| 280 |
+
self.flat_inputs[i],
|
| 281 |
+
symbolic_context=StatelessSymbolicContext(
|
| 282 |
+
dynamic_sizes=[
|
| 283 |
+
(
|
| 284 |
+
DimDynamic.DYNAMIC
|
| 285 |
+
if d in self.flat_args_dynamic_dims[i]
|
| 286 |
+
else DimDynamic.STATIC
|
| 287 |
+
)
|
| 288 |
+
for d in range(len(self.flat_inputs[i].shape))
|
| 289 |
+
],
|
| 290 |
+
constraint_sizes=[None] * len(self.flat_inputs[i].shape),
|
| 291 |
+
),
|
| 292 |
+
)
|
| 293 |
+
elif hasattr(self.flat_inputs[i], "val"): # _IntWrapper case
|
| 294 |
+
placeholder.node.meta["val"] = self.flat_inputs[i].val
|
| 295 |
+
else:
|
| 296 |
+
placeholder.node.meta["val"] = self.flat_inputs[i]
|
| 297 |
+
|
| 298 |
+
# pyrefly: ignore [unsupported-operation]
|
| 299 |
+
self.new_input_nodes[i] = placeholder
|
| 300 |
+
|
| 301 |
+
def _create_placeholder_mapping(self) -> None:
|
| 302 |
+
"""Create mapping from old placeholders to new ones."""
|
| 303 |
+
# graph_input_order maps: user_input_index -> graph_placeholder_index
|
| 304 |
+
# We need to create: old_graph_placeholder -> new_user_input_placeholder
|
| 305 |
+
for user_input_idx, graph_placeholder_idx in self.graph_input_order.items():
|
| 306 |
+
if graph_placeholder_idx < len(self.placeholders):
|
| 307 |
+
old_placeholder = self.placeholders[graph_placeholder_idx]
|
| 308 |
+
new_placeholder = self.new_input_nodes[user_input_idx]
|
| 309 |
+
self.old_to_new_mapping[old_placeholder] = new_placeholder
|
| 310 |
+
|
| 311 |
+
def placeholder(self, target, args, kwargs) -> Any:
|
| 312 |
+
"""Replace old placeholders with new flattened ones."""
|
| 313 |
+
# Return the corresponding new placeholder
|
| 314 |
+
if self.current_node in self.old_to_new_mapping:
|
| 315 |
+
new_arg = self.old_to_new_mapping[self.current_node]
|
| 316 |
+
|
| 317 |
+
# Copy over additional metadata from current node, but don't overwrite "val"
|
| 318 |
+
for key in ["tensor_dict", "example_value", "unbacked_bindings"]:
|
| 319 |
+
if key in self.current_node.meta:
|
| 320 |
+
new_arg.node.meta[key] = self.current_node.meta[key]
|
| 321 |
+
|
| 322 |
+
# Only copy "val" if we don't already have a good one
|
| 323 |
+
if "val" in self.current_node.meta and "val" not in new_arg.node.meta:
|
| 324 |
+
new_arg.node.meta["val"] = self.current_node.meta["val"]
|
| 325 |
+
|
| 326 |
+
return new_arg
|
| 327 |
+
else:
|
| 328 |
+
# Shouldn't happen if mapping is correct, but fallback
|
| 329 |
+
return super().placeholder(target, args, kwargs)
|
| 330 |
+
|
| 331 |
+
def output(self, target, args, kwargs) -> Any:
|
| 332 |
+
"""Transform output according to graph_output_map."""
|
| 333 |
+
original_outputs = args[0]
|
| 334 |
+
|
| 335 |
+
# Build new output list based on graph_output_map
|
| 336 |
+
new_outputs = []
|
| 337 |
+
for i in sorted(self.graph_output_map.keys()):
|
| 338 |
+
output_type, val = self.graph_output_map[i]
|
| 339 |
+
|
| 340 |
+
if output_type == "graph_out":
|
| 341 |
+
new_outputs.append(original_outputs[val])
|
| 342 |
+
elif output_type == "input":
|
| 343 |
+
input_idx = val.index
|
| 344 |
+
new_outputs.append(self.new_input_nodes[input_idx])
|
| 345 |
+
elif output_type == "constant":
|
| 346 |
+
new_outputs.append(val)
|
| 347 |
+
|
| 348 |
+
return super().output(target, (tuple(new_outputs),), {})
|
| 349 |
+
|
| 350 |
+
def run_node(self, node: Node) -> Any:
|
| 351 |
+
"""Run node transformation and preserve metadata."""
|
| 352 |
+
self.current_node = node
|
| 353 |
+
result = super().run_node(node)
|
| 354 |
+
|
| 355 |
+
# Copy important metadata
|
| 356 |
+
if hasattr(result, "node") and result.node is not node:
|
| 357 |
+
for key in ["val", "example_value", "unbacked_bindings"]:
|
| 358 |
+
if key in node.meta:
|
| 359 |
+
result.node.meta[key] = node.meta[key]
|
| 360 |
+
|
| 361 |
+
# Preserve node names (except output)
|
| 362 |
+
if node.op != "output" and hasattr(node, "name"):
|
| 363 |
+
result.node._rename(node.name)
|
| 364 |
+
|
| 365 |
+
return result
|
| 366 |
+
|
| 367 |
+
def transform(self) -> torch.fx.GraphModule:
|
| 368 |
+
"""Perform the graph transformation and copy module metadata."""
|
| 369 |
+
result_gm = super().transform()
|
| 370 |
+
|
| 371 |
+
# Copy module metadata like the original implementation
|
| 372 |
+
if hasattr(self.module, "meta"):
|
| 373 |
+
# pyrefly: ignore [unsupported-operation]
|
| 374 |
+
if "dynamo_flat_name_to_original_fqn" in self.module.meta:
|
| 375 |
+
# pyrefly: ignore [index-error]
|
| 376 |
+
result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[
|
| 377 |
+
# pyrefly: ignore [index-error]
|
| 378 |
+
"dynamo_flat_name_to_original_fqn"
|
| 379 |
+
]
|
| 380 |
+
# pyrefly: ignore [unsupported-operation]
|
| 381 |
+
if "dynamo_compile_id" in self.module.meta:
|
| 382 |
+
# pyrefly: ignore [index-error]
|
| 383 |
+
result_gm.meta["dynamo_compile_id"] = self.module.meta[
|
| 384 |
+
# pyrefly: ignore [index-error]
|
| 385 |
+
"dynamo_compile_id"
|
| 386 |
+
]
|
| 387 |
+
|
| 388 |
+
return result_gm
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _suggest_or_raise_constraint_violation(
|
| 392 |
+
module_to_trace: torch.nn.Module,
|
| 393 |
+
orig_callable: Callable, # type: ignore[type-arg]
|
| 394 |
+
fake_mode: Optional["FakeTensorMode"],
|
| 395 |
+
graph_capture_output: CaptureOutput,
|
| 396 |
+
args: Any,
|
| 397 |
+
kwargs: Any,
|
| 398 |
+
dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]],
|
| 399 |
+
):
|
| 400 |
+
constraint_violation_error = None
|
| 401 |
+
try:
|
| 402 |
+
# Check if we have any constraint violations
|
| 403 |
+
fn, _ = get_traced_fn(module_to_trace)
|
| 404 |
+
graph_capture_output.graph_capture_output.build_guards(fn.__code__)
|
| 405 |
+
except ConstraintViolationError as e:
|
| 406 |
+
constraint_violation_error = e
|
| 407 |
+
|
| 408 |
+
if (
|
| 409 |
+
(shape_env := getattr(fake_mode, "shape_env", None)) is not None
|
| 410 |
+
and (dim_constraints := shape_env.dim_constraints) is not None
|
| 411 |
+
and not isinstance(
|
| 412 |
+
module_to_trace.forward,
|
| 413 |
+
torch._ops.OpOverloadPacket | torch._ops.OpOverload,
|
| 414 |
+
)
|
| 415 |
+
):
|
| 416 |
+
dim_constraints.solve()
|
| 417 |
+
|
| 418 |
+
forced_specializations = dim_constraints.forced_specializations()
|
| 419 |
+
|
| 420 |
+
msg = dim_constraints.prettify_results(
|
| 421 |
+
inspect.signature(orig_callable), # type: ignore[attr-defined]
|
| 422 |
+
dynamic_shapes,
|
| 423 |
+
constraint_violation_error,
|
| 424 |
+
forced_specializations,
|
| 425 |
+
)
|
| 426 |
+
if constraint_violation_error:
|
| 427 |
+
if constraint_violation_error.args:
|
| 428 |
+
constraint_violation_error.args = (
|
| 429 |
+
constraint_violation_error.args[0] + msg,
|
| 430 |
+
)
|
| 431 |
+
else:
|
| 432 |
+
constraint_violation_error.args = (msg,)
|
| 433 |
+
else:
|
| 434 |
+
if forced_specializations:
|
| 435 |
+
constraint_violation_error = ConstraintViolationError(msg)
|
| 436 |
+
else:
|
| 437 |
+
log.info(
|
| 438 |
+
"Summary of dimension constraints:%s",
|
| 439 |
+
msg,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Error if we have any constraints on static values
|
| 443 |
+
|
| 444 |
+
for k in shape_env.var_to_range:
|
| 445 |
+
if isinstance(k, sympy.Integer):
|
| 446 |
+
constraint_violation_error = ConstraintViolationError(
|
| 447 |
+
f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n"
|
| 448 |
+
"It appears that you're trying to set a constraint on a "
|
| 449 |
+
f"value which we evaluated to have a static value of {k}. "
|
| 450 |
+
'Set TORCH_LOGS="+export" for more information.'
|
| 451 |
+
)
|
| 452 |
+
if constraint_violation_error:
|
| 453 |
+
constraint_violation_error = post_process_error_msg(
|
| 454 |
+
constraint_violation_error, orig_callable, args, kwargs
|
| 455 |
+
)
|
| 456 |
+
raise constraint_violation_error
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _normalize_shuffle_graph(shuffle_gm: torch.fx.GraphModule) -> None:
|
| 460 |
+
shuffle_gm.graph.eliminate_dead_code()
|
| 461 |
+
shuffle_gm.recompile()
|
| 462 |
+
for name, buffer in list(shuffle_gm.named_buffers()):
|
| 463 |
+
delattr(shuffle_gm, name)
|
| 464 |
+
setattr(shuffle_gm, name, buffer)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@dataclass(frozen=True)
|
| 468 |
+
class PyTreeifyOutput:
|
| 469 |
+
graph_module: torch.fx.GraphModule
|
| 470 |
+
in_spec: TreeSpec
|
| 471 |
+
in_shuffle_graph: torch.fx.GraphModule
|
| 472 |
+
num_flat_args: int
|
| 473 |
+
out_spec: TreeSpec
|
| 474 |
+
out_shuffle_graph: torch.fx.GraphModule
|
| 475 |
+
root: Optional[torch.nn.Module] = None
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def pytreeify(
|
| 479 |
+
out: CaptureOutput, mod: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
|
| 480 |
+
) -> PyTreeifyOutput:
|
| 481 |
+
"""
|
| 482 |
+
Given a dynamo capture output, return a callable graph module that
|
| 483 |
+
contain the following information:
|
| 484 |
+
1. input/output pytree spec
|
| 485 |
+
2. input/output shuffle functions
|
| 486 |
+
Input shuffle functions are the converters taking pytree falttened inputs
|
| 487 |
+
and reorder them to the calling convention of dynamo raw graph module.
|
| 488 |
+
Output shuffle functions are the converters taking the outputs of the
|
| 489 |
+
dynamo raw graph module and convert them to the pytree format.
|
| 490 |
+
|
| 491 |
+
This function will replay any side effects that happened during the bytecode,
|
| 492 |
+
so it is important to check against side effects before calling this function.
|
| 493 |
+
"""
|
| 494 |
+
assert out.backend_input is not None
|
| 495 |
+
backend_input = out.backend_input
|
| 496 |
+
|
| 497 |
+
root = None
|
| 498 |
+
if isinstance(mod, torch.nn.Module):
|
| 499 |
+
args = (mod,) + args
|
| 500 |
+
root = mod
|
| 501 |
+
elif inspect.ismethod(mod):
|
| 502 |
+
args = (mod.__self__,) + args
|
| 503 |
+
root = mod.__self__
|
| 504 |
+
|
| 505 |
+
flat_real_args, in_spec = pytree.tree_flatten((args, kwargs))
|
| 506 |
+
torch._dynamo.eval_frame.check_user_input_output(
|
| 507 |
+
flat_real_args[1 if root else 0 :], UserErrorType.INVALID_INPUT
|
| 508 |
+
)
|
| 509 |
+
f_globals = out.graph_capture_output.f_globals
|
| 510 |
+
|
| 511 |
+
class Yield(Exception):
|
| 512 |
+
pass
|
| 513 |
+
|
| 514 |
+
class InShuffle(torch.nn.Module):
|
| 515 |
+
def __init__(self):
|
| 516 |
+
super().__init__()
|
| 517 |
+
self.mod = mod
|
| 518 |
+
self.num_inputs = len(flat_real_args)
|
| 519 |
+
self.gm_inputs = None
|
| 520 |
+
|
| 521 |
+
def forward(self, *flat_proxy_args):
|
| 522 |
+
args, kwargs = pytree.tree_unflatten(
|
| 523 |
+
[flat_proxy_args[i] for i in range(self.num_inputs)], in_spec
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
def backend_dummy(*example_inputs):
|
| 527 |
+
self.gm_inputs = example_inputs
|
| 528 |
+
raise Yield
|
| 529 |
+
|
| 530 |
+
try:
|
| 531 |
+
out.forward_callable(
|
| 532 |
+
compiled_fn=backend_dummy, extra_globals=f_globals
|
| 533 |
+
)(*args, **kwargs)
|
| 534 |
+
except Yield:
|
| 535 |
+
assert self.gm_inputs is not None
|
| 536 |
+
return self.gm_inputs
|
| 537 |
+
raise RuntimeError
|
| 538 |
+
|
| 539 |
+
fake_mode = torch._dynamo.utils.detect_fake_mode(flat_real_args)
|
| 540 |
+
if fake_mode and fake_mode.shape_env is None:
|
| 541 |
+
fake_mode.shape_env = ShapeEnv()
|
| 542 |
+
in_shuffle_graph = make_fx(
|
| 543 |
+
InShuffle(), tracing_mode="symbolic", proxy_module_inputs=True
|
| 544 |
+
)(*flat_real_args)
|
| 545 |
+
_normalize_shuffle_graph(in_shuffle_graph)
|
| 546 |
+
|
| 547 |
+
output_node = next(iter(reversed(backend_input.graph_module.graph.nodes)))
|
| 548 |
+
|
| 549 |
+
class OutShuffle(torch.nn.Module):
|
| 550 |
+
def __init__(self):
|
| 551 |
+
super().__init__()
|
| 552 |
+
self.num_inputs = len(flat_real_args)
|
| 553 |
+
|
| 554 |
+
self.num_outputs = len(output_node.args[0])
|
| 555 |
+
self.out_spec: Optional[TreeSpec] = None
|
| 556 |
+
|
| 557 |
+
def forward(self, *flat_proxy_args):
|
| 558 |
+
args, kwargs = pytree.tree_unflatten(
|
| 559 |
+
[flat_proxy_args[i] for i in range(self.num_inputs)], in_spec
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
def backend_dummy(*example_inputs):
|
| 563 |
+
return [
|
| 564 |
+
flat_proxy_args[self.num_inputs + i]
|
| 565 |
+
for i in range(self.num_outputs)
|
| 566 |
+
]
|
| 567 |
+
|
| 568 |
+
results = out.forward_callable(
|
| 569 |
+
compiled_fn=backend_dummy, extra_globals=f_globals
|
| 570 |
+
)(*args, **kwargs)
|
| 571 |
+
ret, self.out_spec = pytree.tree_flatten(results)
|
| 572 |
+
return ret
|
| 573 |
+
|
| 574 |
+
out_shuffle = OutShuffle()
|
| 575 |
+
flat_out_shuffle_args = [
|
| 576 |
+
*flat_real_args,
|
| 577 |
+
*pytree.tree_map_only(
|
| 578 |
+
torch.fx.Node,
|
| 579 |
+
lambda x: fake_mode.from_tensor(x.meta["example_value"])
|
| 580 |
+
if fake_mode
|
| 581 |
+
else x.meta["example_value"],
|
| 582 |
+
output_node.args[0],
|
| 583 |
+
),
|
| 584 |
+
]
|
| 585 |
+
fake_mode = torch._dynamo.utils.detect_fake_mode(flat_out_shuffle_args)
|
| 586 |
+
if fake_mode and fake_mode.shape_env is None:
|
| 587 |
+
fake_mode.shape_env = ShapeEnv()
|
| 588 |
+
with enable_python_dispatcher():
|
| 589 |
+
out_shuffle_graph = make_fx(
|
| 590 |
+
out_shuffle, tracing_mode="real", proxy_module_inputs=True
|
| 591 |
+
)(*flat_out_shuffle_args)
|
| 592 |
+
_normalize_shuffle_graph(out_shuffle_graph)
|
| 593 |
+
|
| 594 |
+
assert out_shuffle.out_spec is not None
|
| 595 |
+
return PyTreeifyOutput(
|
| 596 |
+
backend_input.graph_module,
|
| 597 |
+
in_spec,
|
| 598 |
+
in_shuffle_graph,
|
| 599 |
+
len(flat_real_args),
|
| 600 |
+
out_shuffle.out_spec,
|
| 601 |
+
out_shuffle_graph,
|
| 602 |
+
root=root, # type: ignore[arg-type]
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def normalize_graph_module(gm):
|
| 607 |
+
for node in gm.graph.nodes:
|
| 608 |
+
if node.op == "placeholder":
|
| 609 |
+
node.meta["val"] = node.meta["example_value"]
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def dynamo_graph_capture_for_export(
|
| 613 |
+
mod: Callable[..., Any],
|
| 614 |
+
constraints: Optional[list[Constraint]] = None,
|
| 615 |
+
) -> Callable[..., Any]:
|
| 616 |
+
def inner(*args: Any, **kwargs: Any) -> Any:
|
| 617 |
+
assert not torch._dynamo.config.install_free_tensors
|
| 618 |
+
with (
|
| 619 |
+
torch._dynamo.config.patch(side_effect_replay_policy="warn"),
|
| 620 |
+
get_metrics_context(),
|
| 621 |
+
dynamo_timed("fullgraph_capture"),
|
| 622 |
+
):
|
| 623 |
+
out = fullgraph_capture(
|
| 624 |
+
mod,
|
| 625 |
+
args,
|
| 626 |
+
kwargs,
|
| 627 |
+
constraints=constraints,
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
# TODO filter out side effects.
|
| 631 |
+
pyt = pytreeify(out, mod, args, kwargs)
|
| 632 |
+
|
| 633 |
+
graph_module = pyt.graph_module
|
| 634 |
+
tree_leaf_names = [
|
| 635 |
+
graph_module.graph._graph_namespace.create_name(f"_tree_leaf_{i}", None)
|
| 636 |
+
for i in range(pyt.num_flat_args)
|
| 637 |
+
]
|
| 638 |
+
graph_module.graph._codegen = _ExportCodeGen(
|
| 639 |
+
_PyTreeInfo(
|
| 640 |
+
# TODO we should be able to use the names from dynamo graph directly.
|
| 641 |
+
argument_names(inspect.signature(mod), args, kwargs),
|
| 642 |
+
pyt.in_spec,
|
| 643 |
+
pyt.out_spec,
|
| 644 |
+
),
|
| 645 |
+
pyt.in_shuffle_graph,
|
| 646 |
+
pyt.out_shuffle_graph,
|
| 647 |
+
tree_leaf_names,
|
| 648 |
+
graph_module if isinstance(pyt.root, torch.nn.Module) else pyt.root,
|
| 649 |
+
) # type: ignore[attr-defined]
|
| 650 |
+
normalize_graph_module(graph_module)
|
| 651 |
+
if pyt.root is not None:
|
| 652 |
+
graph_module._parameters = pyt.root._parameters.copy()
|
| 653 |
+
graph_module._buffers = pyt.root._buffers.copy()
|
| 654 |
+
assert all(not hasattr(graph_module, m) for m in pyt.root._modules)
|
| 655 |
+
graph_module._modules.update(pyt.root._modules)
|
| 656 |
+
graph_module._non_persistent_buffers_set = (
|
| 657 |
+
pyt.root._non_persistent_buffers_set.copy()
|
| 658 |
+
)
|
| 659 |
+
if sys.version_info >= (3, 14):
|
| 660 |
+
import annotationlib # added in 3.14
|
| 661 |
+
|
| 662 |
+
annotations = annotationlib.get_annotations(torch.nn.Module)
|
| 663 |
+
else:
|
| 664 |
+
annotations = getattr(torch.nn.Module, "__annotations__", None)
|
| 665 |
+
for name, value in pyt.root.__dict__.items():
|
| 666 |
+
if annotations and name not in annotations:
|
| 667 |
+
graph_module.__dict__[name] = value
|
| 668 |
+
graph_module._in_spec = pyt.in_spec
|
| 669 |
+
graph_module._out_spec = pyt.out_spec
|
| 670 |
+
assert not hasattr(graph_module, "_in_shuffle_graph")
|
| 671 |
+
assert not hasattr(graph_module, "_out_shuffle_graph")
|
| 672 |
+
graph_module._in_shuffle_graph = pyt.in_shuffle_graph
|
| 673 |
+
graph_module._out_shuffle_graph = pyt.out_shuffle_graph
|
| 674 |
+
delattr(graph_module, "_param_name_to_source")
|
| 675 |
+
graph_module.recompile()
|
| 676 |
+
graph_module.meta["module_call_specs"] = (
|
| 677 |
+
out.graph_capture_output.output_graph.export_metadata.module_call_spec
|
| 678 |
+
)
|
| 679 |
+
assert out.backend_input is not None
|
| 680 |
+
graph_module.meta["fake_mode"] = out.backend_input.fake_mode # type: ignore[attr-defined]
|
| 681 |
+
graph_module.meta["fake_mode"].allow_non_fake_inputs = True
|
| 682 |
+
tracing_context = TracingContext(graph_module.meta["fake_mode"])
|
| 683 |
+
tracing_context.tensor_to_context = out.backend_input.tensor_to_context # type: ignore[attr-defined]
|
| 684 |
+
graph_module.meta["tracing_context"] = tracing_context
|
| 685 |
+
return graph_module
|
| 686 |
+
|
| 687 |
+
return inner
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def _dynamo_graph_capture_for_export(
|
| 691 |
+
mod: Callable[..., Any],
|
| 692 |
+
*,
|
| 693 |
+
constraints: Optional[list[Constraint]] = None,
|
| 694 |
+
dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]] = None,
|
| 695 |
+
) -> Callable[..., torch.fx.GraphModule]:
|
| 696 |
+
"""
|
| 697 |
+
Improved dynamo graph capture using transformer approach with proper fake tensor handling.
|
| 698 |
+
|
| 699 |
+
This function creates a capture instance that handles:
|
| 700 |
+
1. PyTree flattening/unflattening with proper input ordering
|
| 701 |
+
2. Dynamo graph capture with export-specific context
|
| 702 |
+
3. FX graph transformation for export compatibility
|
| 703 |
+
4. Proper fake tensor metadata preservation
|
| 704 |
+
5. Dynamic dimension constraint handling
|
| 705 |
+
|
| 706 |
+
Notable improvements over manual approach:
|
| 707 |
+
- Uses FX Transformer for cleaner graph manipulation
|
| 708 |
+
- Properly handles fake tensor metadata and dynamic dimensions
|
| 709 |
+
- Preserves all necessary metadata for export
|
| 710 |
+
- More robust error handling and edge case management
|
| 711 |
+
|
| 712 |
+
TODO:
|
| 713 |
+
1. Are we actually gonna run the bytecode?
|
| 714 |
+
2. Need to attach guards
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
_dynamic_shapes = dynamic_shapes
|
| 718 |
+
_constraints = constraints
|
| 719 |
+
|
| 720 |
+
def inner(*args: Any, **kwargs: Any) -> torch.fx.GraphModule:
|
| 721 |
+
# This sets the is_exporting flag when building guards.
|
| 722 |
+
with _compiling_state_context():
|
| 723 |
+
flat_inputs, in_spec = pytree.tree_flatten((args, kwargs))
|
| 724 |
+
check_user_input_output(flat_inputs, UserErrorType.INVALID_INPUT)
|
| 725 |
+
module_to_trace = ModuleToTrace(mod, in_spec)
|
| 726 |
+
orig_callable = mod.forward if isinstance(mod, torch.nn.Module) else mod
|
| 727 |
+
|
| 728 |
+
constraints: Optional[list[Constraint]] = _constraints
|
| 729 |
+
dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]] = (
|
| 730 |
+
_dynamic_shapes
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
from . import reset # type: ignore[attr-defined]
|
| 734 |
+
|
| 735 |
+
reset()
|
| 736 |
+
|
| 737 |
+
dynamo_config_ctx = torch._dynamo.config.patch(
|
| 738 |
+
specialize_int=True,
|
| 739 |
+
specialize_float=True,
|
| 740 |
+
assume_static_by_default=True,
|
| 741 |
+
automatic_dynamic_shapes=False,
|
| 742 |
+
capture_dynamic_output_shape_ops=True,
|
| 743 |
+
capture_scalar_outputs=True,
|
| 744 |
+
constant_fold_autograd_profiler_enabled=True,
|
| 745 |
+
log_graph_in_out_metadata=True,
|
| 746 |
+
# install_free_tensors ensures that params and buffers are still
|
| 747 |
+
# added as graph attributes, and makes Dynamo emits graphs that
|
| 748 |
+
# follow export pytree-able input requirements In future, if we
|
| 749 |
+
# fully rely on bytecode for the runtime, we can turn this flag
|
| 750 |
+
# off.
|
| 751 |
+
install_free_tensors=torch._dynamo.config.install_free_tensors_for_export,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
with (
|
| 755 |
+
get_metrics_context(),
|
| 756 |
+
dynamo_timed("fullgraph_capture"),
|
| 757 |
+
dynamo_config_ctx,
|
| 758 |
+
):
|
| 759 |
+
out = fullgraph_capture(
|
| 760 |
+
module_to_trace,
|
| 761 |
+
tuple(flat_inputs),
|
| 762 |
+
constraints=_constraints,
|
| 763 |
+
_is_export_deprecated_do_not_use=True,
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
assert out.graph_capture_output.output_graph is not None
|
| 767 |
+
|
| 768 |
+
example_inputs: list[Any] = []
|
| 769 |
+
if out.backend_input is not None:
|
| 770 |
+
graph = out.backend_input.graph_module
|
| 771 |
+
fake_mode = out.backend_input.fake_mode
|
| 772 |
+
example_inputs = out.backend_input.example_inputs
|
| 773 |
+
else:
|
| 774 |
+
graph = torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph())
|
| 775 |
+
graph.graph.output(None)
|
| 776 |
+
graph.recompile()
|
| 777 |
+
fake_mode = None
|
| 778 |
+
|
| 779 |
+
_suggest_or_raise_constraint_violation(
|
| 780 |
+
module_to_trace,
|
| 781 |
+
orig_callable,
|
| 782 |
+
fake_mode,
|
| 783 |
+
out,
|
| 784 |
+
args,
|
| 785 |
+
kwargs,
|
| 786 |
+
dynamic_shapes,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
# Extract export metadata from the new location
|
| 790 |
+
export_metadata = out.graph_capture_output.output_graph.export_metadata
|
| 791 |
+
graph_inputs = export_metadata.graph_input_idx_to_local_source
|
| 792 |
+
graph_output_map = export_metadata.output_return_type
|
| 793 |
+
out_spec = export_metadata.out_spec
|
| 794 |
+
module_call_spec = export_metadata.module_call_spec
|
| 795 |
+
|
| 796 |
+
# Compute dynamic dimensions for each input based on constraints
|
| 797 |
+
flat_args_dynamic_dims = [
|
| 798 |
+
{
|
| 799 |
+
c.dim
|
| 800 |
+
for c in (constraints or ())
|
| 801 |
+
if (
|
| 802 |
+
c.t_id == id(x)
|
| 803 |
+
and not isinstance(c, _RelaxedConstraint)
|
| 804 |
+
and c.constraint_range.vr.lower != c.constraint_range.vr.upper
|
| 805 |
+
)
|
| 806 |
+
}
|
| 807 |
+
for x in flat_inputs
|
| 808 |
+
]
|
| 809 |
+
|
| 810 |
+
# Create input order mapping from dynamo's internal order to user order
|
| 811 |
+
graph_input_order: dict[int, int] = {}
|
| 812 |
+
for inp in graph_inputs:
|
| 813 |
+
source = graph_inputs[inp]
|
| 814 |
+
assert isinstance(source, torch._dynamo.source.GetItemSource)
|
| 815 |
+
graph_input_order[source.index] = len(graph_input_order)
|
| 816 |
+
|
| 817 |
+
for real_idx, graph_idx in graph_input_order.items():
|
| 818 |
+
flat_inputs[real_idx] = example_inputs[graph_idx]
|
| 819 |
+
|
| 820 |
+
# Use FX transformer to rebuild the graph cleanly
|
| 821 |
+
transformed_graph = DynamoGraphTransformer(
|
| 822 |
+
graph,
|
| 823 |
+
flat_inputs,
|
| 824 |
+
flat_args_dynamic_dims,
|
| 825 |
+
graph_input_order,
|
| 826 |
+
graph_output_map,
|
| 827 |
+
fake_mode,
|
| 828 |
+
).transform()
|
| 829 |
+
|
| 830 |
+
# Set up PyTree codegen for proper input/output handling
|
| 831 |
+
transformed_graph.graph._codegen = _PyTreeCodeGen(
|
| 832 |
+
_PyTreeInfo(
|
| 833 |
+
argument_names(inspect.signature(orig_callable), args, kwargs), # type: ignore[attr-defined, arg-type]
|
| 834 |
+
in_spec,
|
| 835 |
+
out_spec,
|
| 836 |
+
)
|
| 837 |
+
)
|
| 838 |
+
transformed_graph.recompile()
|
| 839 |
+
|
| 840 |
+
clean_nn_module_stack_and_source_fn(
|
| 841 |
+
transformed_graph, torch._dynamo.config.inline_inbuilt_nn_modules
|
| 842 |
+
)
|
| 843 |
+
clean_export_root(transformed_graph)
|
| 844 |
+
|
| 845 |
+
transformed_graph.meta["module_call_specs"] = module_call_spec
|
| 846 |
+
transformed_graph.meta["fake_mode"] = fake_mode
|
| 847 |
+
|
| 848 |
+
return transformed_graph
|
| 849 |
+
|
| 850 |
+
return inner
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_break_hints.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
USER_ERROR = [
|
| 2 |
+
"Dynamo has detected that tracing the code will result in an error when running in eager. "
|
| 3 |
+
"Please double check that your code doesn't contain a similar error when actually running eager/uncompiled.",
|
| 4 |
+
]
|
| 5 |
+
DYNAMO_BUG = [
|
| 6 |
+
"This is likely to be a Dynamo bug. Please report an issue to PyTorch.",
|
| 7 |
+
]
|
| 8 |
+
DIFFICULT = [
|
| 9 |
+
"This graph break may be difficult to debug. Please report an issue to PyTorch for assistance.",
|
| 10 |
+
]
|
| 11 |
+
FUNDAMENTAL = [
|
| 12 |
+
"This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through "
|
| 13 |
+
"your code. Consider finding a workaround.",
|
| 14 |
+
]
|
| 15 |
+
SUPPORTABLE = [
|
| 16 |
+
"It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you "
|
| 17 |
+
"encounter this graph break often and it is causing performance issues.",
|
| 18 |
+
]
|
| 19 |
+
CAUSED_BY_EARLIER_GRAPH_BREAK = [
|
| 20 |
+
"This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one.",
|
| 21 |
+
]
|
| 22 |
+
INFERENCE_MODE = [
|
| 23 |
+
"Avoid using `tensor.is_inference()` and `torch.is_inference_mode_enabled()` in your compile code. "
|
| 24 |
+
"This is primarily used in conjunction with `torch.inference_mode`. Consider using `torch.no_grad` instead "
|
| 25 |
+
"because `torch.no_grad` leads to same improvements as `inference_mode` when `torch.compile` is used.",
|
| 26 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_break_registry.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_bytecode_inputs.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import weakref
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from torch._dynamo.source import Source
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
PyCodegen = Any
|
| 9 |
+
|
| 10 |
+
# This file is to handle types that we don't want to support
|
| 11 |
+
# as explicit FX graph inputs. This uses a sidetable which
|
| 12 |
+
# we populate in bytecode and is loaded during graph execution
|
| 13 |
+
|
| 14 |
+
# We use a dynamo-generated index as a level of indirection
|
| 15 |
+
# this allows us to register objects externally in pre-graph bytecode that we want
|
| 16 |
+
# to pass to the graph, but not support their types as graph inputs
|
| 17 |
+
index_to_bytecode_constructor: dict[int, Callable[[PyCodegen], None]] = {}
|
| 18 |
+
|
| 19 |
+
index_to_external_object_weakref: dict[int, weakref.ReferenceType[Any]] = {}
|
| 20 |
+
|
| 21 |
+
keep_alive: list[Any] = []
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def has_user_objects() -> bool:
|
| 25 |
+
return bool(index_to_bytecode_constructor)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def stash_graph_created_object(obj: Any) -> Any:
|
| 29 |
+
keep_alive.append(obj)
|
| 30 |
+
return obj
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_external_object_by_index(index: int) -> Any:
|
| 34 |
+
assert index in index_to_external_object_weakref, (
|
| 35 |
+
"Index not registered in index_to_user_object_weakref"
|
| 36 |
+
)
|
| 37 |
+
obj = index_to_external_object_weakref[index]()
|
| 38 |
+
assert obj is not None, "User object is no longer alive"
|
| 39 |
+
return index_to_external_object_weakref[index]()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def store_user_object_weakrefs(*args: Any) -> None:
|
| 43 |
+
global index_to_external_object_weakref
|
| 44 |
+
index_to_external_object_weakref.clear()
|
| 45 |
+
index_to_external_object_weakref.update(
|
| 46 |
+
{i: weakref.ref(arg) for i, arg in enumerate(args)}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def reset_user_object_tracking() -> None:
|
| 51 |
+
index_to_bytecode_constructor.clear()
|
| 52 |
+
index_to_external_object_weakref.clear()
|
| 53 |
+
keep_alive.clear()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def register_graph_created_object(
|
| 57 |
+
example_value: Any, construct_fn: Callable[[int, PyCodegen], None]
|
| 58 |
+
) -> int:
|
| 59 |
+
global index_to_bytecode_constructor
|
| 60 |
+
global keep_alive
|
| 61 |
+
keep_alive.append(example_value)
|
| 62 |
+
index = len(index_to_bytecode_constructor)
|
| 63 |
+
index_to_bytecode_constructor[index] = lambda cg: construct_fn(index, cg)
|
| 64 |
+
try:
|
| 65 |
+
index_to_external_object_weakref[index] = weakref.ref(example_value)
|
| 66 |
+
except TypeError as e:
|
| 67 |
+
from .exc import unimplemented
|
| 68 |
+
|
| 69 |
+
unimplemented(
|
| 70 |
+
gb_type="Failed to make weakref to graph-created external object",
|
| 71 |
+
context=f"user_object: {example_value}",
|
| 72 |
+
explanation="Object does not allow us to make a weakref to it",
|
| 73 |
+
hints=[],
|
| 74 |
+
from_exc=e,
|
| 75 |
+
)
|
| 76 |
+
return index
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Register a user object to be used in the graph
|
| 80 |
+
def register_user_object(value: Any, source: Source) -> int:
|
| 81 |
+
global index_to_bytecode_constructor
|
| 82 |
+
index = len(index_to_bytecode_constructor)
|
| 83 |
+
index_to_bytecode_constructor[index] = lambda cg: cg(source)
|
| 84 |
+
try:
|
| 85 |
+
index_to_external_object_weakref[index] = weakref.ref(value)
|
| 86 |
+
except TypeError as e:
|
| 87 |
+
from .exc import unimplemented
|
| 88 |
+
|
| 89 |
+
unimplemented(
|
| 90 |
+
gb_type="Failed to make weakref to User Object",
|
| 91 |
+
context=f"user_object: {value}",
|
| 92 |
+
explanation="Object does not allow us to make a weakref to it",
|
| 93 |
+
hints=[],
|
| 94 |
+
from_exc=e,
|
| 95 |
+
)
|
| 96 |
+
return index
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_deduplication.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements graph deduplication functionality for TorchDynamo's optimization pipeline.
|
| 3 |
+
Graph deduplication identifies identical subgraphs in the computational graph and merges them
|
| 4 |
+
to reduce redundancy and improve performance. The process involves analyzing regions of the graph,
|
| 5 |
+
identifying structurally equivalent regions, and replacing them with a single shared implementation.
|
| 6 |
+
This optimization is particularly effective for models with repeated patterns or similar computational
|
| 7 |
+
structures across different parts of the network.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
import operator
|
| 12 |
+
from collections import defaultdict, deque
|
| 13 |
+
from collections.abc import Generator, Iterable
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.fx
|
| 18 |
+
from torch._dynamo import config
|
| 19 |
+
from torch.multiprocessing.reductions import StorageWeakRef
|
| 20 |
+
from torch.utils._ordered_set import OrderedSet
|
| 21 |
+
|
| 22 |
+
from .graph_region_tracker import Node, Region
|
| 23 |
+
from .graph_utils import _detect_cycles, _get_flat_args, _get_flat_args_unique
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Represents an index into the region
|
| 27 |
+
# to select a node and then
|
| 28 |
+
# an index into that node's
|
| 29 |
+
# flattened arguments
|
| 30 |
+
UsageIndex = tuple[int, int]
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
last_node_to_additional_deps: Optional[dict[Node, OrderedSet[Node]]] = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def apply_graph_deduplication(output_graph) -> dict[str, torch.fx.GraphModule]: # type: ignore[no-untyped-def]
|
| 38 |
+
"""
|
| 39 |
+
This is the main entry point for applying the graph deduplication pass. \
|
| 40 |
+
Deduplication occurs in two phases:
|
| 41 |
+
1. Subgraph creation:
|
| 42 |
+
Subgraph creation works by taking one representative region from each region \
|
| 43 |
+
group and creating a subgraph from it, which will then be used to replace all regions \
|
| 44 |
+
in the group. This is implemented by first copying all nodes of the region to the new \
|
| 45 |
+
subgraph and then finding all inputs which are not within the region and creating placeholders \
|
| 46 |
+
for them. For the outputs, all regions in a region group need to be scanned to ensure the \
|
| 47 |
+
largest set of outputs is found, and then an output node is created which returns \
|
| 48 |
+
a tuple of all outputs.
|
| 49 |
+
|
| 50 |
+
2. Graph replacement:
|
| 51 |
+
To replace each region with the extracted subgraph, the node index in the region \
|
| 52 |
+
and argument index within the node's flattened args and kwargs are recorded once during \
|
| 53 |
+
subgraph creation. This allows us to determine which (external to the region) nodes and \
|
| 54 |
+
in which order these nodes are passed as inputs. For the outputs, getitem nodes are created \
|
| 55 |
+
for each output, and all nodes in the region with external outputs are replaced by the proper \
|
| 56 |
+
getitem node. Finally, all original nodes are erased (there should be no uses of these \
|
| 57 |
+
left in the graph).
|
| 58 |
+
|
| 59 |
+
The deduplication mutates the output_graph argument in place.
|
| 60 |
+
|
| 61 |
+
Returns a mapping of nodes to their subgraph output replacement node to remap outputs
|
| 62 |
+
when they are created in output_graph.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
duplicated_region_groups = output_graph.region_tracker.get_identical_regions(
|
| 66 |
+
output_graph.graph
|
| 67 |
+
)
|
| 68 |
+
node_to_mutated_arg_positions = (
|
| 69 |
+
output_graph.region_tracker.node_to_mutated_arg_positions
|
| 70 |
+
)
|
| 71 |
+
node_to_additional_deps = _populate_additional_deps(
|
| 72 |
+
output_graph.graph, output_graph.region_tracker.node_to_mutated_arg_positions
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
sub_gms: dict[str, torch.fx.GraphModule] = {}
|
| 76 |
+
|
| 77 |
+
for region_group in duplicated_region_groups:
|
| 78 |
+
inds_with_external_users = _get_all_output_indices(region_group)
|
| 79 |
+
region = region_group[0]
|
| 80 |
+
(
|
| 81 |
+
subgraph,
|
| 82 |
+
external_node_usages,
|
| 83 |
+
node_usage_to_tuple_elems,
|
| 84 |
+
ind_to_tuple_spec,
|
| 85 |
+
) = _create_subgraph(region, inds_with_external_users)
|
| 86 |
+
|
| 87 |
+
# Ignore regions with no args for now, could they possibly be evaluated at compile time?
|
| 88 |
+
if not list(external_node_usages):
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
sub_gm = torch.fx.GraphModule(output_graph.nn_modules, subgraph)
|
| 92 |
+
subgraph_name = output_graph.install_subgraph("subgraph", sub_gm)
|
| 93 |
+
sub_gms[subgraph_name] = sub_gm
|
| 94 |
+
with output_graph.graph.inserting_before():
|
| 95 |
+
get_subgraph_node = output_graph.graph.create_node(
|
| 96 |
+
"get_attr", subgraph_name, (), {}
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
for region in region_group:
|
| 100 |
+
_replace_region_with_subgraph(
|
| 101 |
+
output_graph.graph,
|
| 102 |
+
region,
|
| 103 |
+
get_subgraph_node,
|
| 104 |
+
external_node_usages,
|
| 105 |
+
node_usage_to_tuple_elems,
|
| 106 |
+
ind_to_tuple_spec,
|
| 107 |
+
inds_with_external_users,
|
| 108 |
+
subgraph_name,
|
| 109 |
+
node_to_additional_deps,
|
| 110 |
+
node_to_mutated_arg_positions,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# This is to expose the updated node_to_additional_deps to tests
|
| 114 |
+
global last_node_to_additional_deps
|
| 115 |
+
last_node_to_additional_deps = node_to_additional_deps
|
| 116 |
+
|
| 117 |
+
_stable_topological_sort(
|
| 118 |
+
output_graph.graph,
|
| 119 |
+
node_to_additional_deps,
|
| 120 |
+
)
|
| 121 |
+
return sub_gms
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _replace_region_with_subgraph(
|
| 125 |
+
graph: torch.fx.Graph,
|
| 126 |
+
region: Region,
|
| 127 |
+
get_subgraph_node: Node,
|
| 128 |
+
external_node_usages: Iterable[OrderedSet[UsageIndex]],
|
| 129 |
+
node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]],
|
| 130 |
+
ind_to_tuple_spec: dict[int, dict[tuple[int, ...], int]],
|
| 131 |
+
inds_with_external_users: list[int],
|
| 132 |
+
subgraph_name: str,
|
| 133 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]],
|
| 134 |
+
node_to_mutated_arg_positions: dict[Node, OrderedSet[int]],
|
| 135 |
+
) -> None:
|
| 136 |
+
sub_args = []
|
| 137 |
+
flattened_getitem_nodes: OrderedSet[Node] = OrderedSet()
|
| 138 |
+
for usages in external_node_usages:
|
| 139 |
+
usage = next(iter(usages))
|
| 140 |
+
node_ind, usage_ind = usage
|
| 141 |
+
node = region[node_ind]
|
| 142 |
+
flattened_args_kwargs = _get_flat_args(node, {})
|
| 143 |
+
for user_ind, node_usage_ind in usages:
|
| 144 |
+
user = region[user_ind]
|
| 145 |
+
if user in node_to_mutated_arg_positions:
|
| 146 |
+
if node_usage_ind in node_to_mutated_arg_positions[user]:
|
| 147 |
+
log.debug(
|
| 148 |
+
"NYI: Failed to substitute region %s due to mutation", region
|
| 149 |
+
)
|
| 150 |
+
return
|
| 151 |
+
if usage in node_usage_to_tuple_elems:
|
| 152 |
+
tuple_elems = [region[i] for i in node_usage_to_tuple_elems[usage]]
|
| 153 |
+
flattened_getitem_nodes.update(tuple_elems)
|
| 154 |
+
sub_args.extend(tuple_elems)
|
| 155 |
+
else:
|
| 156 |
+
sub_args.append(flattened_args_kwargs[usage_ind])
|
| 157 |
+
|
| 158 |
+
# Input/Output aliasing not supported in HOPs today
|
| 159 |
+
# Note: we should use the nodes in the original graph (the region here)
|
| 160 |
+
# because we use the original traced example values for this check
|
| 161 |
+
if _has_aliasing(
|
| 162 |
+
region, sub_args, inds_with_external_users, flattened_getitem_nodes
|
| 163 |
+
):
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
invoke_args = (get_subgraph_node, subgraph_name, *sub_args)
|
| 167 |
+
|
| 168 |
+
invoke_subgraph_node = graph.create_node(
|
| 169 |
+
"call_function",
|
| 170 |
+
torch.ops.higher_order.invoke_subgraph,
|
| 171 |
+
invoke_args, # type: ignore[arg-type]
|
| 172 |
+
{},
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
ind = 0
|
| 176 |
+
flattened_output_nodes: OrderedSet[Node] = OrderedSet()
|
| 177 |
+
for external_user_ind in inds_with_external_users:
|
| 178 |
+
node = region[external_user_ind]
|
| 179 |
+
if _is_tuple_node(node):
|
| 180 |
+
tuple_spec = ind_to_tuple_spec[external_user_ind]
|
| 181 |
+
flattened_output_nodes.update(
|
| 182 |
+
_replace_tuple_outputs(
|
| 183 |
+
node, ind, tuple_spec, invoke_subgraph_node, graph
|
| 184 |
+
)
|
| 185 |
+
)
|
| 186 |
+
ind += len(tuple_spec)
|
| 187 |
+
else:
|
| 188 |
+
subgraph_output = graph.create_node(
|
| 189 |
+
"call_function", operator.getitem, (invoke_subgraph_node, ind), {}
|
| 190 |
+
)
|
| 191 |
+
node.replace_all_uses_with(subgraph_output, propagate_meta=True)
|
| 192 |
+
ind += 1
|
| 193 |
+
|
| 194 |
+
# Erase in reverse topological order
|
| 195 |
+
for node in reversed(region):
|
| 196 |
+
if node in flattened_getitem_nodes:
|
| 197 |
+
# Don't erase these, since they will still be used
|
| 198 |
+
continue
|
| 199 |
+
|
| 200 |
+
if node not in flattened_output_nodes:
|
| 201 |
+
graph.erase_node(node)
|
| 202 |
+
|
| 203 |
+
# Remove any nodes with additional deps
|
| 204 |
+
# This is safe; we've guaranteed that there is
|
| 205 |
+
# no input mutation, so all additional deps
|
| 206 |
+
# will be internal to the subgraph
|
| 207 |
+
node_to_additional_deps.pop(node, None)
|
| 208 |
+
for deps in node_to_additional_deps.values():
|
| 209 |
+
try:
|
| 210 |
+
deps.remove(node)
|
| 211 |
+
deps.add(invoke_subgraph_node)
|
| 212 |
+
except KeyError:
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
if config.graph_deduplication_lint:
|
| 216 |
+
print(_detect_cycles(graph, node_to_additional_deps))
|
| 217 |
+
_stable_topological_sort(graph, node_to_additional_deps)
|
| 218 |
+
graph.lint()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _get_external_inputs(
|
| 222 |
+
region: Region,
|
| 223 |
+
) -> dict[Node, OrderedSet[UsageIndex]]:
|
| 224 |
+
external_node_to_usages = defaultdict[Node, OrderedSet[UsageIndex]](OrderedSet)
|
| 225 |
+
region_unique = set(region)
|
| 226 |
+
for node_ind, node in enumerate(region):
|
| 227 |
+
flattened_args_kwargs = _get_flat_args(node, {})
|
| 228 |
+
for arg_ind, in_node in enumerate(flattened_args_kwargs):
|
| 229 |
+
if isinstance(in_node, Node) and in_node not in region_unique:
|
| 230 |
+
# in_node may occur in multiple nodes' flat_args
|
| 231 |
+
# track this so we can check if the arg is mutated
|
| 232 |
+
# Previously, we only needed to track one occurrence
|
| 233 |
+
# to be able to map that node to a placeholder
|
| 234 |
+
external_node_to_usages[in_node].add((node_ind, arg_ind))
|
| 235 |
+
|
| 236 |
+
return external_node_to_usages
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _get_all_output_indices(regions: list[Region]) -> list[int]:
|
| 240 |
+
# Scan all regions to get the set of all possible output nodes indices in the region
|
| 241 |
+
# perhaps we can record this information during region creation for more efficiency?
|
| 242 |
+
inds_with_external_users: set[int] = set()
|
| 243 |
+
for region in regions:
|
| 244 |
+
_get_inds_with_external_users(region, inds_with_external_users)
|
| 245 |
+
|
| 246 |
+
return sorted(inds_with_external_users)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _get_inds_with_external_users(region: Region, inds_unique: set[int]) -> None:
|
| 250 |
+
for ind, node in enumerate(region):
|
| 251 |
+
for user in node.users:
|
| 252 |
+
if user not in region:
|
| 253 |
+
if ind not in inds_unique:
|
| 254 |
+
inds_unique.add(ind)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _create_subgraph(
|
| 258 |
+
region: Region,
|
| 259 |
+
inds_with_external_users: list[int],
|
| 260 |
+
) -> tuple[
|
| 261 |
+
torch.fx.Graph,
|
| 262 |
+
list[OrderedSet[UsageIndex]],
|
| 263 |
+
dict[UsageIndex, OrderedSet[int]],
|
| 264 |
+
dict[int, dict[tuple[int, ...], int]],
|
| 265 |
+
]:
|
| 266 |
+
subgraph: torch.fx.Graph = torch.fx.Graph()
|
| 267 |
+
external_input_to_usages = _get_external_inputs(region)
|
| 268 |
+
external_node_usages = list[OrderedSet[UsageIndex]]()
|
| 269 |
+
region_to_subgraph_node = {}
|
| 270 |
+
flattened_getitem_nodes: OrderedSet[Node] = OrderedSet()
|
| 271 |
+
node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]] = {}
|
| 272 |
+
|
| 273 |
+
for node, usage_indices in external_input_to_usages.items():
|
| 274 |
+
# We don't handle tuples as inputs today
|
| 275 |
+
if _is_tuple_node(node):
|
| 276 |
+
# If a node is a tuple we will possibly create multiple placeholders for them
|
| 277 |
+
# and track which nodes we won't copy into the subgraph because they are flattened away
|
| 278 |
+
# Later, when replacing each region with this subgraph, we will create a getitem node
|
| 279 |
+
# externally which will perform the flattening on the outer nodes.
|
| 280 |
+
flattened_node_indices = _get_flattened_node_indices(node, region)
|
| 281 |
+
for ind in flattened_node_indices:
|
| 282 |
+
placeholder = subgraph.placeholder(
|
| 283 |
+
f"supgraph_input_{node.name}_flattened_{ind}"
|
| 284 |
+
)
|
| 285 |
+
region_to_subgraph_node[region[ind]] = placeholder
|
| 286 |
+
flattened_getitem_nodes.add(region[ind])
|
| 287 |
+
node_usage_to_tuple_elems[next(iter(usage_indices))] = (
|
| 288 |
+
flattened_node_indices
|
| 289 |
+
)
|
| 290 |
+
else:
|
| 291 |
+
placeholder = subgraph.placeholder(f"subgraph_input_{node.name}")
|
| 292 |
+
region_to_subgraph_node[node] = placeholder
|
| 293 |
+
|
| 294 |
+
external_node_usages.append(usage_indices)
|
| 295 |
+
|
| 296 |
+
def map_arg(node: Node) -> Node:
|
| 297 |
+
if node in region_to_subgraph_node:
|
| 298 |
+
return region_to_subgraph_node[node]
|
| 299 |
+
else:
|
| 300 |
+
return node
|
| 301 |
+
|
| 302 |
+
def copy_to_subgraph(node: Node) -> Node:
|
| 303 |
+
subgraph_node = subgraph.node_copy(node, lambda old: map_arg(old))
|
| 304 |
+
region_to_subgraph_node[node] = subgraph_node
|
| 305 |
+
return subgraph_node
|
| 306 |
+
|
| 307 |
+
output_list = []
|
| 308 |
+
ind_to_tuple_spec = {}
|
| 309 |
+
for ind, node in enumerate(region):
|
| 310 |
+
if node not in flattened_getitem_nodes:
|
| 311 |
+
subgraph_node = copy_to_subgraph(node)
|
| 312 |
+
if ind in inds_with_external_users:
|
| 313 |
+
# flatten tuple outputs by generating a getitem node tree
|
| 314 |
+
if _is_tuple_node(node):
|
| 315 |
+
getitem_nodes, ind_to_tuple_spec[ind] = _create_getitem_nodes(
|
| 316 |
+
node, subgraph_node, subgraph
|
| 317 |
+
)
|
| 318 |
+
output_list.extend(getitem_nodes)
|
| 319 |
+
else:
|
| 320 |
+
output_list.append(subgraph_node)
|
| 321 |
+
|
| 322 |
+
subgraph.output(tuple(output_list))
|
| 323 |
+
|
| 324 |
+
return subgraph, external_node_usages, node_usage_to_tuple_elems, ind_to_tuple_spec
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _stable_topological_sort_impl(
|
| 328 |
+
graph: torch.fx.Graph,
|
| 329 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]],
|
| 330 |
+
do_sort: bool = True,
|
| 331 |
+
) -> bool:
|
| 332 |
+
# Nodes are in exactly one of these four collections:
|
| 333 |
+
|
| 334 |
+
# - Nodes in `pending` are waiting to be processed (in reverse order):
|
| 335 |
+
pending = list(reversed(graph.nodes))
|
| 336 |
+
|
| 337 |
+
# - Nodes in `ready` have been processed and are already in the correct
|
| 338 |
+
# order.
|
| 339 |
+
ready = OrderedSet[Node]()
|
| 340 |
+
|
| 341 |
+
# - `waiting` is a mapping from a dependency to nodes which depend on that
|
| 342 |
+
# dependency.
|
| 343 |
+
waiting = defaultdict(list)
|
| 344 |
+
|
| 345 |
+
# - `outputs` are always at the end of the graph
|
| 346 |
+
outputs = OrderedSet[Node]()
|
| 347 |
+
|
| 348 |
+
# The cursor indicates the last processed node so we can add new nodes
|
| 349 |
+
# after it.
|
| 350 |
+
cursor = None
|
| 351 |
+
while pending:
|
| 352 |
+
node = pending.pop()
|
| 353 |
+
|
| 354 |
+
if node.target == "output":
|
| 355 |
+
outputs.add(node)
|
| 356 |
+
assert not node.users, "output nodes should have no users"
|
| 357 |
+
continue
|
| 358 |
+
|
| 359 |
+
waiting_for = [
|
| 360 |
+
x
|
| 361 |
+
for x in _get_flat_args_unique(node, node_to_additional_deps)
|
| 362 |
+
if x not in ready
|
| 363 |
+
]
|
| 364 |
+
if waiting_for:
|
| 365 |
+
# We have unprocessed input nodes. Might as well wait for the last
|
| 366 |
+
# arg so an already sorted list will only recheck this node once.
|
| 367 |
+
waiting[waiting_for[-1]].append(node)
|
| 368 |
+
else:
|
| 369 |
+
ready.add(node)
|
| 370 |
+
if cursor and cursor.next is not node and do_sort:
|
| 371 |
+
cursor.append(node)
|
| 372 |
+
cursor = node
|
| 373 |
+
# Mark the nodes that have been waiting for this node to finish as
|
| 374 |
+
# ready to check again.
|
| 375 |
+
pending.extend(reversed(waiting.pop(node, ())))
|
| 376 |
+
|
| 377 |
+
ready.update(outputs)
|
| 378 |
+
return not waiting and len(ready) == len(graph.nodes)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _stable_topological_sort(
|
| 382 |
+
graph: torch.fx.Graph,
|
| 383 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]],
|
| 384 |
+
) -> None:
|
| 385 |
+
assert _stable_topological_sort_impl(graph, node_to_additional_deps)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _has_cycle(
|
| 389 |
+
graph: torch.fx.Graph,
|
| 390 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]],
|
| 391 |
+
) -> bool:
|
| 392 |
+
return not _stable_topological_sort_impl(
|
| 393 |
+
graph, node_to_additional_deps, do_sort=False
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def _populate_additional_deps(
|
| 398 |
+
graph: torch.fx.Graph, node_to_mutated_arg_positions: dict[Node, OrderedSet[int]]
|
| 399 |
+
) -> dict[Node, OrderedSet[Node]]:
|
| 400 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]] = defaultdict(OrderedSet)
|
| 401 |
+
_add_mutation_dependencies(node_to_mutated_arg_positions, node_to_additional_deps)
|
| 402 |
+
_add_global_state_dependencies(graph, node_to_additional_deps)
|
| 403 |
+
return node_to_additional_deps
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _add_global_state_dependencies(
|
| 407 |
+
graph: torch.fx.Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]]
|
| 408 |
+
) -> None:
|
| 409 |
+
import torch.amp
|
| 410 |
+
|
| 411 |
+
all_nodes = list(graph.nodes)
|
| 412 |
+
|
| 413 |
+
# These are targets of the nodes which need to stay in the same relative place in the graph
|
| 414 |
+
global_state_targets = {torch.amp._enter_autocast, torch.amp._exit_autocast}
|
| 415 |
+
all_nodes_dep_on: list[Node] = []
|
| 416 |
+
|
| 417 |
+
def prev_cur_nodes(
|
| 418 |
+
all_nodes: list[Node],
|
| 419 |
+
) -> Generator[tuple[list[Node], Node], None, None]:
|
| 420 |
+
prev_nodes: list[Node] = []
|
| 421 |
+
next_nodes = list(reversed(all_nodes))
|
| 422 |
+
|
| 423 |
+
while next_nodes:
|
| 424 |
+
cur_node = next_nodes.pop()
|
| 425 |
+
yield prev_nodes, cur_node
|
| 426 |
+
prev_nodes.append(cur_node)
|
| 427 |
+
|
| 428 |
+
for prev_nodes, cur_node in prev_cur_nodes(all_nodes):
|
| 429 |
+
args_unique = _get_flat_args_unique(cur_node, {})
|
| 430 |
+
new_deps = [n for n in all_nodes_dep_on if n not in args_unique]
|
| 431 |
+
|
| 432 |
+
if new_deps:
|
| 433 |
+
additional_deps = node_to_additional_deps[cur_node]
|
| 434 |
+
additional_deps.update(new_deps)
|
| 435 |
+
|
| 436 |
+
if cur_node.target in global_state_targets:
|
| 437 |
+
additional_deps = node_to_additional_deps[cur_node]
|
| 438 |
+
additional_deps.update(n for n in prev_nodes if n not in args_unique)
|
| 439 |
+
all_nodes_dep_on.append(cur_node)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _add_mutation_dependencies(
|
| 443 |
+
node_to_mutated_arg_positions: dict[Node, OrderedSet[int]],
|
| 444 |
+
node_to_additional_deps: dict[Node, OrderedSet[Node]],
|
| 445 |
+
) -> None:
|
| 446 |
+
for node, indices in node_to_mutated_arg_positions.items():
|
| 447 |
+
flat_args_kwargs = _get_flat_args(node, {})
|
| 448 |
+
|
| 449 |
+
# for all mutated args,
|
| 450 |
+
# add dependency on usages which occur after node to ensure
|
| 451 |
+
# node will always be ordered before them
|
| 452 |
+
# also add node as a dependency on usages which
|
| 453 |
+
# occur before node to ensure node is ordered after them
|
| 454 |
+
for index in indices:
|
| 455 |
+
mutated_arg = flat_args_kwargs[index]
|
| 456 |
+
for user in mutated_arg.users:
|
| 457 |
+
if user is node:
|
| 458 |
+
continue
|
| 459 |
+
# pyrefly: ignore # unsupported-operation
|
| 460 |
+
elif user < node:
|
| 461 |
+
node_to_additional_deps[node].add(user)
|
| 462 |
+
# pyrefly: ignore # unsupported-operation
|
| 463 |
+
elif user > node:
|
| 464 |
+
node_to_additional_deps[user].add(node)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def _has_aliasing(
|
| 468 |
+
region: Region,
|
| 469 |
+
inputs: list[Node],
|
| 470 |
+
inds_with_external_users: list[int],
|
| 471 |
+
flattened_getitem_nodes: OrderedSet[Node],
|
| 472 |
+
) -> bool:
|
| 473 |
+
input_storages: dict[StorageWeakRef, Node] = dict()
|
| 474 |
+
for node in inputs:
|
| 475 |
+
if node in flattened_getitem_nodes:
|
| 476 |
+
continue
|
| 477 |
+
example_value = node.meta["example_value"]
|
| 478 |
+
if isinstance(example_value, torch.Tensor):
|
| 479 |
+
storage = StorageWeakRef(example_value._typed_storage())
|
| 480 |
+
if storage in input_storages:
|
| 481 |
+
# input-input aliasing
|
| 482 |
+
log.debug(
|
| 483 |
+
"NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s, %s",
|
| 484 |
+
region,
|
| 485 |
+
input_storages[storage],
|
| 486 |
+
node,
|
| 487 |
+
)
|
| 488 |
+
return True
|
| 489 |
+
input_storages[storage] = node
|
| 490 |
+
output_storages: dict[StorageWeakRef, Node] = dict()
|
| 491 |
+
for i in inds_with_external_users:
|
| 492 |
+
out_node = region[i]
|
| 493 |
+
if out_node in flattened_getitem_nodes:
|
| 494 |
+
continue
|
| 495 |
+
if out_node:
|
| 496 |
+
example_value = out_node.meta["example_value"]
|
| 497 |
+
assert not isinstance(example_value, list)
|
| 498 |
+
if isinstance(example_value, torch.Tensor):
|
| 499 |
+
storage = StorageWeakRef(example_value._typed_storage())
|
| 500 |
+
if storage in output_storages:
|
| 501 |
+
# output-output aliasing
|
| 502 |
+
log.debug(
|
| 503 |
+
"NYI: Failed to substitute region %s due to output-output aliasing detected at nodes %s, %s",
|
| 504 |
+
region,
|
| 505 |
+
output_storages[storage],
|
| 506 |
+
out_node,
|
| 507 |
+
)
|
| 508 |
+
return True
|
| 509 |
+
output_storages[storage] = out_node
|
| 510 |
+
intersected_storages = input_storages.keys() & output_storages.keys()
|
| 511 |
+
if len(intersected_storages) > 0:
|
| 512 |
+
# input-output aliasing
|
| 513 |
+
aliased = [
|
| 514 |
+
(input_storages[s], output_storages[s]) for s in intersected_storages
|
| 515 |
+
]
|
| 516 |
+
aliased = ", ".join([f"{i} and {o}" for i, o in aliased])
|
| 517 |
+
log.debug(
|
| 518 |
+
"NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s",
|
| 519 |
+
region,
|
| 520 |
+
aliased,
|
| 521 |
+
)
|
| 522 |
+
return True
|
| 523 |
+
return False
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _is_tuple_node(node: Node) -> bool:
|
| 527 |
+
return isinstance(node.meta["example_value"], tuple)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _get_children_getitems(node: Node) -> Generator[Node, None, None]:
|
| 531 |
+
for user in node.users:
|
| 532 |
+
if user.target is operator.getitem and isinstance(user.args[1], int):
|
| 533 |
+
yield user
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _get_flattened_node_indices(node: Node, region: Region) -> OrderedSet[int]:
|
| 537 |
+
"""Returns an ordered set of indices, each representing a node in the region which will be flattened"""
|
| 538 |
+
flattened_node_to_ind = {n: i for i, n in enumerate(region)}
|
| 539 |
+
node_indices: OrderedSet[int] = OrderedSet()
|
| 540 |
+
queue = deque(_get_children_getitems(node))
|
| 541 |
+
while queue:
|
| 542 |
+
cur_node = queue.popleft()
|
| 543 |
+
if any(user in region for user in cur_node.users):
|
| 544 |
+
node_indices.add(flattened_node_to_ind[cur_node])
|
| 545 |
+
for child in _get_children_getitems(cur_node):
|
| 546 |
+
queue.append(child)
|
| 547 |
+
return node_indices
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def _create_getitem_nodes(
|
| 551 |
+
node: Node, subgraph_tuple_node: Node, subgraph: torch.fx.Graph
|
| 552 |
+
) -> tuple[list[Node], dict[tuple[int, ...], int]]:
|
| 553 |
+
tup = node.meta["example_value"]
|
| 554 |
+
assert isinstance(tup, tuple), "_get_getitem_children expects tuple"
|
| 555 |
+
|
| 556 |
+
getitem_nodes: list[Node] = []
|
| 557 |
+
queue = deque([(e, (i,), subgraph_tuple_node) for i, e in enumerate(tup)])
|
| 558 |
+
path_to_output_index = {}
|
| 559 |
+
|
| 560 |
+
while queue:
|
| 561 |
+
cur_elem, path, parent = queue.popleft()
|
| 562 |
+
|
| 563 |
+
with subgraph.inserting_after(parent):
|
| 564 |
+
new_getitem_node = subgraph.create_node(
|
| 565 |
+
"call_function", operator.getitem, (parent, path[-1]), {}
|
| 566 |
+
)
|
| 567 |
+
new_getitem_node.meta["example_value"] = cur_elem
|
| 568 |
+
|
| 569 |
+
path_to_output_index[path] = len(getitem_nodes)
|
| 570 |
+
getitem_nodes.append(new_getitem_node)
|
| 571 |
+
|
| 572 |
+
if isinstance(cur_elem, tuple):
|
| 573 |
+
queue.extend(
|
| 574 |
+
[(e, path + (i,), new_getitem_node) for i, e in enumerate(cur_elem)] # type: ignore[arg-type,misc]
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
return getitem_nodes, path_to_output_index # type: ignore[return-value]
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def _replace_tuple_outputs(
|
| 581 |
+
node: Node,
|
| 582 |
+
output_index: int,
|
| 583 |
+
tuple_spec: dict[tuple[int, ...], int],
|
| 584 |
+
invoke_subgraph_node: Node,
|
| 585 |
+
graph: torch.fx.Graph,
|
| 586 |
+
) -> OrderedSet[Node]:
|
| 587 |
+
assert _is_tuple_node(node), "_replace_tuple_outputs expects a tuple node"
|
| 588 |
+
|
| 589 |
+
queue = deque((c, (c.args[1],)) for c in _get_children_getitems(node))
|
| 590 |
+
erased_nodes: OrderedSet[Node] = OrderedSet()
|
| 591 |
+
while queue:
|
| 592 |
+
cur_node, path = queue.pop()
|
| 593 |
+
|
| 594 |
+
for c in _get_children_getitems(cur_node):
|
| 595 |
+
queue.append((c, path + (c.args[1],))) # type: ignore[return-value, arg-type]
|
| 596 |
+
|
| 597 |
+
with graph.inserting_after(invoke_subgraph_node):
|
| 598 |
+
subgraph_output = graph.create_node(
|
| 599 |
+
"call_function",
|
| 600 |
+
operator.getitem,
|
| 601 |
+
(invoke_subgraph_node, output_index + tuple_spec[path]), # type: ignore[index]
|
| 602 |
+
{},
|
| 603 |
+
)
|
| 604 |
+
cur_node.replace_all_uses_with(subgraph_output, propagate_meta=True)
|
| 605 |
+
graph.erase_node(cur_node)
|
| 606 |
+
erased_nodes.add(cur_node)
|
| 607 |
+
|
| 608 |
+
graph.erase_node(node)
|
| 609 |
+
erased_nodes.add(node)
|
| 610 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides functionality for tracking and managing regions in computational graphs.
|
| 3 |
+
It supports graph optimization by identifying and grouping similar regions based on their
|
| 4 |
+
structure and behavior. The module implements algorithms for:
|
| 5 |
+
|
| 6 |
+
1. Tracking nodes and their relationships in the computational graph
|
| 7 |
+
2. Identifying identical or similar regions across the graph
|
| 8 |
+
3. Managing graph regions for optimization purposes
|
| 9 |
+
4. Supporting deduplication and other graph transformation passes
|
| 10 |
+
|
| 11 |
+
The core functionality revolves around the GraphRegionTracker class which maintains
|
| 12 |
+
mappings between nodes and their duplicates, enabling efficient graph analysis and
|
| 13 |
+
optimization operations.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import copyreg
|
| 19 |
+
import io
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import operator
|
| 23 |
+
import pickle
|
| 24 |
+
from collections import defaultdict, deque
|
| 25 |
+
from dataclasses import fields
|
| 26 |
+
from typing import Any, Optional, TYPE_CHECKING, TypeVar
|
| 27 |
+
|
| 28 |
+
import torch._logging
|
| 29 |
+
import torch.fx
|
| 30 |
+
from torch._subclasses.fake_tensor import FakeTensor
|
| 31 |
+
from torch.utils._ordered_set import OrderedSet
|
| 32 |
+
from torch.utils._pytree import tree_flatten
|
| 33 |
+
|
| 34 |
+
from .graph_utils import _get_flat_args_unique
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
T = TypeVar("T")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from collections.abc import Callable
|
| 42 |
+
|
| 43 |
+
from .symbolic_convert import InstructionTranslatorBase
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
Node = torch.fx.Node
|
| 47 |
+
Region = list[Node]
|
| 48 |
+
IdenticalNodes = list[Node]
|
| 49 |
+
GlobalStateKey = tuple[
|
| 50 |
+
bool,
|
| 51 |
+
bool,
|
| 52 |
+
int,
|
| 53 |
+
tuple[bool, bool],
|
| 54 |
+
tuple[bool, bool],
|
| 55 |
+
torch.dtype,
|
| 56 |
+
bool,
|
| 57 |
+
bool,
|
| 58 |
+
bool,
|
| 59 |
+
bool,
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
log = logging.getLogger(__name__)
|
| 63 |
+
graph_expansion_log = torch._logging.getArtifactLogger(
|
| 64 |
+
__name__, "graph_region_expansion"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def debug_log(msg: str, *args) -> None: # type: ignore[no-untyped-def]
|
| 69 |
+
graph_expansion_log.debug(msg, *args)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _extract_tensor_metadata_for_node_hash(
|
| 73 |
+
x: torch.Tensor,
|
| 74 |
+
) -> tuple[Callable[[T], T], tuple[Any, ...]]:
|
| 75 |
+
from torch._inductor.codecache import _ident, extract_tensor_metadata_for_cache_key
|
| 76 |
+
|
| 77 |
+
out = []
|
| 78 |
+
metadata = extract_tensor_metadata_for_cache_key(x)
|
| 79 |
+
for field in fields(metadata):
|
| 80 |
+
out.append(getattr(metadata, field.name))
|
| 81 |
+
|
| 82 |
+
return (_ident, tuple(out))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class NodeHashException(Exception):
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class InputPickler(pickle.Pickler):
|
| 90 |
+
def __init__(self) -> None:
|
| 91 |
+
from torch._inductor.codecache import _ident
|
| 92 |
+
|
| 93 |
+
stream = io.BytesIO()
|
| 94 |
+
self._stream = stream
|
| 95 |
+
super().__init__(stream)
|
| 96 |
+
self.dispatch_table = copyreg.dispatch_table.copy()
|
| 97 |
+
self.dispatch_table.update(
|
| 98 |
+
{
|
| 99 |
+
FakeTensor: _extract_tensor_metadata_for_node_hash,
|
| 100 |
+
torch.SymInt: lambda x: (_ident, (str(x),)),
|
| 101 |
+
torch.SymBool: lambda x: (_ident, (str(x),)),
|
| 102 |
+
torch.SymFloat: lambda x: (_ident, (str(x),)),
|
| 103 |
+
}
|
| 104 |
+
)
|
| 105 |
+
self.fast = True
|
| 106 |
+
|
| 107 |
+
def dumps(self, obj: Any) -> bytes:
|
| 108 |
+
"""
|
| 109 |
+
Pickle an object and return a byte string.
|
| 110 |
+
"""
|
| 111 |
+
try:
|
| 112 |
+
self.dump(obj)
|
| 113 |
+
return self._stream.getvalue()
|
| 114 |
+
except (TypeError, AttributeError) as e:
|
| 115 |
+
raise NodeHashException from e
|
| 116 |
+
finally:
|
| 117 |
+
self._stream.seek(0)
|
| 118 |
+
self._stream.truncate(0)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _extract_args(arg: Any) -> Any:
|
| 122 |
+
if isinstance(arg, Node):
|
| 123 |
+
return arg.meta.get("example_value")
|
| 124 |
+
elif isinstance(arg, (torch.Tensor, int)):
|
| 125 |
+
return arg
|
| 126 |
+
else:
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _normalize_args(
|
| 131 |
+
node: Node,
|
| 132 |
+
) -> tuple[tuple[str, ...], tuple[Optional[Any], ...]]:
|
| 133 |
+
flat_args, _ = tree_flatten(node.args)
|
| 134 |
+
sorted_kwargs = sorted(node.kwargs.items(), key=operator.itemgetter(0))
|
| 135 |
+
sorted_keys = tuple(sorted(node.kwargs.keys()))
|
| 136 |
+
flat_kwargs, _ = tree_flatten(sorted_kwargs)
|
| 137 |
+
all_args = flat_args + flat_kwargs
|
| 138 |
+
return (sorted_keys, tuple(_extract_args(arg) for arg in all_args))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _sort_with_ref_region(
|
| 142 |
+
index_to_rank: dict[int, int], regions: list[list[Any]]
|
| 143 |
+
) -> None:
|
| 144 |
+
# sort topologically
|
| 145 |
+
# we need to handle edge cases where some nodes have no dependencies
|
| 146 |
+
# so first we map each node to its ranking
|
| 147 |
+
ref_region = regions[0]
|
| 148 |
+
sorted_indices = sorted(range(len(ref_region)), key=lambda i: index_to_rank[i])
|
| 149 |
+
for region in regions:
|
| 150 |
+
region[:] = [region[i] for i in sorted_indices]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def get_global_state_key() -> GlobalStateKey:
|
| 154 |
+
return (
|
| 155 |
+
torch.is_grad_enabled(),
|
| 156 |
+
torch.is_inference_mode_enabled(),
|
| 157 |
+
torch.get_num_threads(),
|
| 158 |
+
torch._C._get_cublas_allow_fp16_reduced_precision_reduction(),
|
| 159 |
+
torch._C._get_cublas_allow_bf16_reduced_precision_reduction(),
|
| 160 |
+
torch.get_default_dtype(),
|
| 161 |
+
torch.are_deterministic_algorithms_enabled(),
|
| 162 |
+
torch._C._get_cublas_allow_tf32(),
|
| 163 |
+
torch.is_deterministic_algorithms_warn_only_enabled(),
|
| 164 |
+
torch._C._autograd._saved_tensors_hooks_is_enabled(), # type: ignore[attr-defined]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# This is typical BFS with the caveat
|
| 169 |
+
# that a node's children need to be explicitly
|
| 170 |
+
# added with the add_children() method
|
| 171 |
+
# The flow is yield a node and check if it's valid for all regions
|
| 172 |
+
# if not valid, discard and continue onto the next node
|
| 173 |
+
# Note: this iterates backward through the graph by looking at args/kwargs
|
| 174 |
+
# of a node
|
| 175 |
+
class BackwardBfsArgIter:
|
| 176 |
+
def __init__(self, origin: Node) -> None:
|
| 177 |
+
self._cur: Optional[Node] = origin
|
| 178 |
+
self._queue: deque[Optional[Node]] = deque()
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def create(origin: Node) -> BackwardBfsArgIter:
|
| 182 |
+
it = BackwardBfsArgIter(origin)
|
| 183 |
+
it.add_children(origin)
|
| 184 |
+
# pop the origin node, since it is the origin of
|
| 185 |
+
# the region and does not need to be considered for addition
|
| 186 |
+
assert it.next()
|
| 187 |
+
return it
|
| 188 |
+
|
| 189 |
+
def next(self) -> Optional[Node]:
|
| 190 |
+
ret = self._cur
|
| 191 |
+
if not self._queue:
|
| 192 |
+
self._cur = None
|
| 193 |
+
else:
|
| 194 |
+
self._cur = self._queue.popleft()
|
| 195 |
+
return ret
|
| 196 |
+
|
| 197 |
+
def peek(self) -> Optional[Node]:
|
| 198 |
+
return self._cur
|
| 199 |
+
|
| 200 |
+
def add_children(self, node: Node) -> None:
|
| 201 |
+
flat_args = _get_flat_args_unique(node, {})
|
| 202 |
+
for arg in flat_args:
|
| 203 |
+
if isinstance(arg, Node):
|
| 204 |
+
self._append(arg)
|
| 205 |
+
|
| 206 |
+
def _append(self, arg: Node) -> None:
|
| 207 |
+
if self._cur is None:
|
| 208 |
+
self._cur = arg
|
| 209 |
+
else:
|
| 210 |
+
self._queue.append(arg)
|
| 211 |
+
|
| 212 |
+
def __str__(self) -> str:
|
| 213 |
+
return f"BackwardBfsArgIter(cur={self._cur}, queue={self._queue})"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class GraphRegionTracker:
|
| 217 |
+
"""
|
| 218 |
+
GraphRegionTracker tracks each node added to the output graph and generates a key based on the source location,
|
| 219 |
+
instruction pointer, input shapes, and global state at the time the node is inserted into the graph. Nodes with
|
| 220 |
+
the same key are grouped together in a list of identical nodes (the value of node_to_duplicates).
|
| 221 |
+
|
| 222 |
+
hash_to_duplicates: Dict[str, IdenticalNodes] - A dictionary mapping the key to a list of identical nodes
|
| 223 |
+
node_to_duplicates: Dict[Node, IdenticalNodes] - A dictionary mapping a node to the list of identical nodes it belongs to
|
| 224 |
+
input_pickler: InputPickler - An instance of InputPickler used to generate a node hash
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
def __init__(self) -> None:
|
| 228 |
+
self.hash_to_duplicates: dict[str, IdenticalNodes] = defaultdict(list)
|
| 229 |
+
self.node_to_duplicates: dict[Node, IdenticalNodes] = {}
|
| 230 |
+
# Note: position is in flattened args/kwargs list
|
| 231 |
+
self.node_to_mutated_arg_positions: dict[Node, OrderedSet[int]] = {}
|
| 232 |
+
self.input_pickler = InputPickler()
|
| 233 |
+
|
| 234 |
+
def _hash_node(
|
| 235 |
+
self, filename: str, lineno: int, instruction_pointer: Optional[int], node: Node
|
| 236 |
+
) -> str:
|
| 237 |
+
from torch._inductor.codecache import sha256_hash
|
| 238 |
+
|
| 239 |
+
key = (
|
| 240 |
+
get_global_state_key(),
|
| 241 |
+
filename,
|
| 242 |
+
lineno,
|
| 243 |
+
instruction_pointer,
|
| 244 |
+
_normalize_args(node),
|
| 245 |
+
)
|
| 246 |
+
return sha256_hash(self.input_pickler.dumps(key))
|
| 247 |
+
|
| 248 |
+
def _is_identical(self, n0: Node, n1: Node) -> bool:
|
| 249 |
+
return (
|
| 250 |
+
n0 in self.node_to_duplicates
|
| 251 |
+
and n1 in self.node_to_duplicates
|
| 252 |
+
and self.node_to_duplicates[n0] is self.node_to_duplicates[n1]
|
| 253 |
+
and n0 is not n1
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def track_node(self, tx: InstructionTranslatorBase, node: Node) -> None:
|
| 257 |
+
"""
|
| 258 |
+
The main entry point for tracking a node. This function will hash the node argument and group
|
| 259 |
+
nodes with the same hash together. It updates the hash_to_duplicates and node_to_duplicates dictionaries
|
| 260 |
+
to track the new node.
|
| 261 |
+
"""
|
| 262 |
+
try:
|
| 263 |
+
if (
|
| 264 |
+
node not in self.node_to_duplicates
|
| 265 |
+
): # don't allow nodes to be added twice
|
| 266 |
+
duplicates = self.hash_to_duplicates[
|
| 267 |
+
self._hash_node(
|
| 268 |
+
tx.f_code.co_filename, tx.lineno, tx.instruction_pointer, node
|
| 269 |
+
)
|
| 270 |
+
]
|
| 271 |
+
duplicates.append(node)
|
| 272 |
+
self.node_to_duplicates[node] = duplicates
|
| 273 |
+
except NodeHashException as e:
|
| 274 |
+
log.debug("Unable to hash node %s with exception %s", node, e) # noqa: G200
|
| 275 |
+
|
| 276 |
+
def track_node_mutations(
|
| 277 |
+
self,
|
| 278 |
+
node: Node,
|
| 279 |
+
flat_args_kwargs: list[Any],
|
| 280 |
+
id_to_initial_version: dict[int, int],
|
| 281 |
+
) -> None:
|
| 282 |
+
"""
|
| 283 |
+
This function tracks which argument positions are mutated by the given node. Subgraph HOP does not support
|
| 284 |
+
input mutations today so we will skip regions which have inputs that are mutated.
|
| 285 |
+
"""
|
| 286 |
+
mutated_arg_positions = OrderedSet[int]()
|
| 287 |
+
for i, arg in enumerate(flat_args_kwargs):
|
| 288 |
+
val_id = id(arg)
|
| 289 |
+
if (
|
| 290 |
+
val_id in id_to_initial_version
|
| 291 |
+
and id_to_initial_version[val_id] != arg._version
|
| 292 |
+
):
|
| 293 |
+
mutated_arg_positions.add(i)
|
| 294 |
+
|
| 295 |
+
if mutated_arg_positions:
|
| 296 |
+
self.node_to_mutated_arg_positions[node] = mutated_arg_positions
|
| 297 |
+
|
| 298 |
+
def add_node_mutation(
|
| 299 |
+
self,
|
| 300 |
+
node: Node,
|
| 301 |
+
arg_pos: int,
|
| 302 |
+
) -> None:
|
| 303 |
+
if node in self.node_to_mutated_arg_positions:
|
| 304 |
+
self.node_to_mutated_arg_positions[node].add(arg_pos)
|
| 305 |
+
else:
|
| 306 |
+
self.node_to_mutated_arg_positions[node] = OrderedSet([arg_pos])
|
| 307 |
+
|
| 308 |
+
def get_identical_regions(self, graph: torch.fx.Graph) -> list[list[Region]]:
|
| 309 |
+
"""
|
| 310 |
+
This function is responsible for extracting the largest regions of identical nodes from the given graph.
|
| 311 |
+
**Note**: This function assumes the nodes that have been tracked with track_node are in the provided graph argument.
|
| 312 |
+
|
| 313 |
+
The algorithm proceeds as follows:
|
| 314 |
+
The nodes tracked via track_node above are organized into region groups. The initial region groups look like this:
|
| 315 |
+
[[IdenticalNode1], [IdenticalNode2], [IdenticalNode3]] and each sublist is called a region. For each region group
|
| 316 |
+
(starting at the topologically latest region group), the inner regions are gradually expanded one node at time from
|
| 317 |
+
the flattened args and kwargs of the node in each region provided that for all regions in the group, the nodes being
|
| 318 |
+
added are also identical (ie have the same key computed by track_node). This is checked by verifying that the two
|
| 319 |
+
nodes have the same identical node list in node_to_duplicates.
|
| 320 |
+
"""
|
| 321 |
+
topological_ranking = {node: i for i, node in enumerate(graph.nodes)}
|
| 322 |
+
region_groups_with_rank = []
|
| 323 |
+
# needed to detect if replacing a region will create cycles
|
| 324 |
+
node_to_recursive_ancestors = _populate_recursive_ancestor_map(graph)
|
| 325 |
+
|
| 326 |
+
# Create region groups; a region group is a group
|
| 327 |
+
# of regions that are all identical. In this initial state
|
| 328 |
+
# each region in the group is a single node, and we discard
|
| 329 |
+
# groups that are only a single region.
|
| 330 |
+
# We track the topological ranking to start with groups later in the graph
|
| 331 |
+
# the reason for this is that we will necessarily create the largest groups first.
|
| 332 |
+
for group in self.hash_to_duplicates.values():
|
| 333 |
+
if len(group) > 1:
|
| 334 |
+
region_group = []
|
| 335 |
+
min_rank = math.inf
|
| 336 |
+
# pyrefly: ignore [bad-assignment]
|
| 337 |
+
for node in group:
|
| 338 |
+
# some nodes aren't in the topo ranking?
|
| 339 |
+
if node in topological_ranking:
|
| 340 |
+
min_rank = min(min_rank, topological_ranking[node])
|
| 341 |
+
region_group.append([node])
|
| 342 |
+
|
| 343 |
+
if len(region_group) > 1:
|
| 344 |
+
region_groups_with_rank.append((region_group, min_rank))
|
| 345 |
+
|
| 346 |
+
region_groups_with_rank.sort(key=lambda rg: -rg[1])
|
| 347 |
+
region_groups = [rg for rg, _ in region_groups_with_rank]
|
| 348 |
+
|
| 349 |
+
# We start from regions later in the graph and expand them earlier
|
| 350 |
+
# as a result, we will create the largest regions first and they won't
|
| 351 |
+
# overlap.
|
| 352 |
+
seen_nodes: set[Node] = set()
|
| 353 |
+
for region_group in region_groups:
|
| 354 |
+
fully_expand_region_group(
|
| 355 |
+
region_group,
|
| 356 |
+
seen_nodes,
|
| 357 |
+
node_to_recursive_ancestors,
|
| 358 |
+
self._is_identical,
|
| 359 |
+
)
|
| 360 |
+
# sort topologically
|
| 361 |
+
# we need to handle edge cases where some nodes have no dependencies
|
| 362 |
+
# so first we map each node to its ranking,
|
| 363 |
+
ref_region = region_group[0]
|
| 364 |
+
index_to_rank = {
|
| 365 |
+
index: topological_ranking[n] for index, n in enumerate(ref_region)
|
| 366 |
+
}
|
| 367 |
+
_sort_with_ref_region(index_to_rank, region_group)
|
| 368 |
+
|
| 369 |
+
return [
|
| 370 |
+
region_group for region_group in region_groups if len(region_group[0]) > 1
|
| 371 |
+
]
|
| 372 |
+
|
| 373 |
+
def __str__(self) -> str:
|
| 374 |
+
return f"GraphRegionTracker(hash_to_duplicates={self.hash_to_duplicates}, node_to_duplicates={self.node_to_duplicates})"
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class RegionWrapper:
|
| 378 |
+
"""Holds state for regions e.g. ancestors and new candidate nodes for consideration"""
|
| 379 |
+
|
| 380 |
+
def __init__(
|
| 381 |
+
self, region: Region, node_to_recursive_ancestors: dict[Node, set[Node]]
|
| 382 |
+
) -> None:
|
| 383 |
+
assert len(region) == 1, "all regions should start with one node"
|
| 384 |
+
node = region[0]
|
| 385 |
+
self.node_to_recursive_ancestors = node_to_recursive_ancestors
|
| 386 |
+
self.iter = BackwardBfsArgIter.create(node)
|
| 387 |
+
self.nodes_unique = OrderedSet([node])
|
| 388 |
+
self.ancestors = set(node_to_recursive_ancestors[node])
|
| 389 |
+
self.region = region
|
| 390 |
+
|
| 391 |
+
def next_candidate(self) -> Optional[Node]:
|
| 392 |
+
return self.iter.next()
|
| 393 |
+
|
| 394 |
+
def will_inclusion_create_cycle(self, node: Node) -> bool:
|
| 395 |
+
external_users = [user for user in node.users if user not in self.nodes_unique]
|
| 396 |
+
for user in external_users:
|
| 397 |
+
if user in self.ancestors:
|
| 398 |
+
return True
|
| 399 |
+
|
| 400 |
+
return False
|
| 401 |
+
|
| 402 |
+
def add(self, node: Node) -> None:
|
| 403 |
+
self.nodes_unique.add(node)
|
| 404 |
+
self.region.append(node)
|
| 405 |
+
self.iter.add_children(node)
|
| 406 |
+
self.ancestors.update(self.node_to_recursive_ancestors[node])
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def fully_expand_region_group(
|
| 410 |
+
regions: list[Region],
|
| 411 |
+
seen_nodes: set[Node],
|
| 412 |
+
node_to_recursive_ancestors: dict[Node, set[Node]],
|
| 413 |
+
is_identical_fn: Callable[[Node, Node], bool],
|
| 414 |
+
) -> None:
|
| 415 |
+
debug_log("--------------------------------------------------")
|
| 416 |
+
debug_log("expanding new region group: %s", regions)
|
| 417 |
+
|
| 418 |
+
# All regions should start with 1 node
|
| 419 |
+
assert all(len(region) == 1 for region in regions)
|
| 420 |
+
region_wrappers = [
|
| 421 |
+
RegionWrapper(region, node_to_recursive_ancestors) for region in regions
|
| 422 |
+
]
|
| 423 |
+
|
| 424 |
+
nodes_to_add = OrderedSet[Node]()
|
| 425 |
+
current_node = region_wrappers[0].next_candidate()
|
| 426 |
+
|
| 427 |
+
# No children
|
| 428 |
+
if current_node is None:
|
| 429 |
+
return
|
| 430 |
+
|
| 431 |
+
# Loop incrementally adding new nodes to each region
|
| 432 |
+
# regions are only expanded if the node to add is valid
|
| 433 |
+
# for ALL regions
|
| 434 |
+
while current_node:
|
| 435 |
+
add_to_all_regions = not region_wrappers[0].will_inclusion_create_cycle(
|
| 436 |
+
current_node
|
| 437 |
+
)
|
| 438 |
+
nodes_to_add.clear()
|
| 439 |
+
nodes_to_add.add(current_node)
|
| 440 |
+
for region_wrapper in region_wrappers[1:]:
|
| 441 |
+
candidate = region_wrapper.next_candidate()
|
| 442 |
+
|
| 443 |
+
debug_log("--------------------")
|
| 444 |
+
debug_log(
|
| 445 |
+
"considering candidate: %s, cur_node: %s", candidate, current_node
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if not candidate or not add_to_all_regions:
|
| 449 |
+
add_to_all_regions = False
|
| 450 |
+
continue
|
| 451 |
+
|
| 452 |
+
debug_log(
|
| 453 |
+
"candidate in previously claimed nodes?: %s", candidate in seen_nodes
|
| 454 |
+
)
|
| 455 |
+
debug_log("is_identical: %s", is_identical_fn(candidate, current_node))
|
| 456 |
+
|
| 457 |
+
add_to_all_regions &= (
|
| 458 |
+
candidate not in seen_nodes
|
| 459 |
+
and candidate not in nodes_to_add
|
| 460 |
+
and candidate.op != "placeholder"
|
| 461 |
+
and candidate.op != "get_attr"
|
| 462 |
+
and is_identical_fn(candidate, current_node)
|
| 463 |
+
and not region_wrapper.will_inclusion_create_cycle(candidate)
|
| 464 |
+
)
|
| 465 |
+
nodes_to_add.add(candidate)
|
| 466 |
+
|
| 467 |
+
debug_log(f"add_to_all_regions: {add_to_all_regions}")
|
| 468 |
+
debug_log("--------------------")
|
| 469 |
+
|
| 470 |
+
if add_to_all_regions:
|
| 471 |
+
assert len(region_wrappers) == len(nodes_to_add), (
|
| 472 |
+
"Number of nodes to add must equal the number of regions"
|
| 473 |
+
)
|
| 474 |
+
for region_wrapper, node in zip(region_wrappers, nodes_to_add):
|
| 475 |
+
region_wrapper.add(node)
|
| 476 |
+
debug_log("adding %s's children", node)
|
| 477 |
+
debug_log("%s %s", node.args, list(node.kwargs.items()))
|
| 478 |
+
seen_nodes.add(node)
|
| 479 |
+
|
| 480 |
+
current_node = region_wrappers[0].next_candidate()
|
| 481 |
+
|
| 482 |
+
# Ensure regions are sorted in topological order
|
| 483 |
+
for region in regions:
|
| 484 |
+
region.reverse()
|
| 485 |
+
|
| 486 |
+
debug_log("end expand new region group: %s", regions)
|
| 487 |
+
debug_log("--------------------------------------------------")
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _populate_recursive_ancestor_map(graph: torch.fx.Graph) -> dict[Node, set[Node]]:
|
| 491 |
+
node_to_recursive_ancestors: dict[Node, set[Node]] = {}
|
| 492 |
+
for node in graph.nodes:
|
| 493 |
+
node_to_recursive_ancestors[node] = set()
|
| 494 |
+
for node in graph.nodes:
|
| 495 |
+
all_args = _get_flat_args_unique(node, {})
|
| 496 |
+
for arg in all_args:
|
| 497 |
+
if isinstance(arg, Node):
|
| 498 |
+
node_to_recursive_ancestors[node].update(
|
| 499 |
+
node_to_recursive_ancestors[arg]
|
| 500 |
+
)
|
| 501 |
+
node_to_recursive_ancestors[node].add(arg)
|
| 502 |
+
return node_to_recursive_ancestors
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/graph_utils.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import deque
|
| 2 |
+
from typing import Any, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.fx import Graph, map_arg, Node
|
| 6 |
+
from torch.utils._ordered_set import OrderedSet
|
| 7 |
+
from torch.utils._pytree import tree_flatten
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# flattens with support for slices
|
| 11 |
+
# Note: a better way to do this would
|
| 12 |
+
# be register/unregister slices as pytree nodes
|
| 13 |
+
# but there is no unregister API in the pytorch
|
| 14 |
+
# pytree impl
|
| 15 |
+
def _get_flat_args(
|
| 16 |
+
node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]]
|
| 17 |
+
) -> list[Node]:
|
| 18 |
+
args = list[Any]()
|
| 19 |
+
map_arg((node.args, node.kwargs), args.append)
|
| 20 |
+
if node in node_to_additional_deps:
|
| 21 |
+
args.extend(node_to_additional_deps[node])
|
| 22 |
+
return args
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _get_flat_args_unique(
|
| 26 |
+
node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]]
|
| 27 |
+
) -> OrderedSet[Node]:
|
| 28 |
+
args = OrderedSet[Node]()
|
| 29 |
+
map_arg((node.args, node.kwargs), args.add)
|
| 30 |
+
if node in node_to_additional_deps:
|
| 31 |
+
args.update(node_to_additional_deps[node])
|
| 32 |
+
return args
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _detect_cycles(
|
| 36 |
+
graph: Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]]
|
| 37 |
+
) -> str:
|
| 38 |
+
current_path: deque[Node] = deque()
|
| 39 |
+
current_path_set: set[Node] = set()
|
| 40 |
+
pending: deque[tuple[Node, Node]] = deque()
|
| 41 |
+
|
| 42 |
+
def add_to_current_path(node: Node) -> None:
|
| 43 |
+
current_path.append(node)
|
| 44 |
+
current_path_set.add(node)
|
| 45 |
+
|
| 46 |
+
def pop_current_path() -> None:
|
| 47 |
+
node = current_path.pop()
|
| 48 |
+
current_path_set.remove(node)
|
| 49 |
+
|
| 50 |
+
def current_path_head() -> Node:
|
| 51 |
+
return current_path[-1]
|
| 52 |
+
|
| 53 |
+
for origin in graph.find_nodes(op="output"):
|
| 54 |
+
current_path.clear()
|
| 55 |
+
current_path_set.clear()
|
| 56 |
+
add_to_current_path(origin)
|
| 57 |
+
for child in _get_flat_args_unique(origin, node_to_additional_deps):
|
| 58 |
+
pending.append((child, origin))
|
| 59 |
+
|
| 60 |
+
while pending:
|
| 61 |
+
cur_node, parent = pending.pop()
|
| 62 |
+
|
| 63 |
+
# handle backtracking
|
| 64 |
+
while current_path and current_path_head() != parent:
|
| 65 |
+
pop_current_path()
|
| 66 |
+
|
| 67 |
+
if not isinstance(cur_node, Node):
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
if cur_node in current_path_set:
|
| 71 |
+
current_path.append(cur_node)
|
| 72 |
+
return f"cycle detected in path: {current_path}"
|
| 73 |
+
|
| 74 |
+
add_to_current_path(cur_node)
|
| 75 |
+
|
| 76 |
+
for child in _get_flat_args_unique(cur_node, node_to_additional_deps):
|
| 77 |
+
pending.append((child, cur_node))
|
| 78 |
+
|
| 79 |
+
return "no cycle detected"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _graph_device_type(graph: Optional[Graph]) -> str:
|
| 83 |
+
if graph is None:
|
| 84 |
+
return "cpu"
|
| 85 |
+
|
| 86 |
+
def _device_type(x: Any) -> str:
|
| 87 |
+
if isinstance(x, torch.device):
|
| 88 |
+
return x.type
|
| 89 |
+
if isinstance(x, torch.Tensor):
|
| 90 |
+
return x.device.type
|
| 91 |
+
return "cpu"
|
| 92 |
+
|
| 93 |
+
def _flatten_meta(node: Node, key: str) -> list[Any]:
|
| 94 |
+
if key not in node.meta:
|
| 95 |
+
return []
|
| 96 |
+
flat, _ = tree_flatten(node.meta[key])
|
| 97 |
+
return flat
|
| 98 |
+
|
| 99 |
+
for node in graph.nodes:
|
| 100 |
+
for key in ("val", "example_value"):
|
| 101 |
+
for obj in _flatten_meta(node, key):
|
| 102 |
+
return _device_type(obj)
|
| 103 |
+
|
| 104 |
+
# Check for device conversions
|
| 105 |
+
if node.op == "call_method":
|
| 106 |
+
for gpu in ["cuda", "xpu"]:
|
| 107 |
+
if node.target == gpu:
|
| 108 |
+
return gpu
|
| 109 |
+
if node.target == "to" and gpu in node.args:
|
| 110 |
+
return gpu
|
| 111 |
+
|
| 112 |
+
# Check args/kwargs for non-CPU device specs
|
| 113 |
+
flat_args, _ = tree_flatten((node.args, node.kwargs))
|
| 114 |
+
for obj in flat_args:
|
| 115 |
+
return _device_type(obj)
|
| 116 |
+
return "cpu"
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/guards.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/hooks.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hook system for Dynamo's guard functionality.
|
| 2 |
+
|
| 3 |
+
This module provides a way to register callback functions that are triggered during
|
| 4 |
+
guard-related operations.
|
| 5 |
+
|
| 6 |
+
The Hooks class manages two types of hook functions:
|
| 7 |
+
- guard_export_fn: Called when guards need to be exported, taking a GuardsSet as input
|
| 8 |
+
- guard_fail_fn: Called when a guard check fails, taking a GuardFail object as input
|
| 9 |
+
These hooks enable customization of guard export and failure handling behaviors.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import dataclasses
|
| 13 |
+
from collections.abc import Callable
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from torch._guards import GuardsSet
|
| 17 |
+
|
| 18 |
+
from .types import GuardFail, GuardFilterEntry
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclasses.dataclass
|
| 22 |
+
class Hooks:
|
| 23 |
+
guard_export_fn: Optional[Callable[[GuardsSet], None]] = None
|
| 24 |
+
guard_fail_fn: Optional[Callable[[GuardFail], None]] = None
|
| 25 |
+
guard_filter_fn: Optional[Callable[[list[GuardFilterEntry]], list[bool]]] = None
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/logging.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logging utilities for Dynamo and Inductor.
|
| 2 |
+
|
| 3 |
+
This module provides specialized logging functionality including:
|
| 4 |
+
- Step-based logging that prepends step numbers to log messages
|
| 5 |
+
- Progress bar management for compilation phases
|
| 6 |
+
- Centralized logger management for Dynamo and Inductor components
|
| 7 |
+
|
| 8 |
+
The logging system helps track the progress of compilation phases and provides structured
|
| 9 |
+
logging output for debugging and monitoring.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import itertools
|
| 13 |
+
import logging
|
| 14 |
+
from collections.abc import Callable
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from torch.hub import _Faketqdm, tqdm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Disable progress bar by default, not in dynamo config because otherwise get a circular import
|
| 21 |
+
disable_progress = True
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Return all loggers that torchdynamo/torchinductor is responsible for
|
| 25 |
+
def get_loggers() -> list[logging.Logger]:
|
| 26 |
+
return [
|
| 27 |
+
logging.getLogger("torch.fx.experimental.symbolic_shapes"),
|
| 28 |
+
logging.getLogger("torch._dynamo"),
|
| 29 |
+
logging.getLogger("torch._inductor"),
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Creates a logging function that logs a message with a step # prepended.
|
| 34 |
+
# get_step_logger should be lazily called (i.e. at runtime, not at module-load time)
|
| 35 |
+
# so that step numbers are initialized properly. e.g.:
|
| 36 |
+
|
| 37 |
+
# @functools.cache
|
| 38 |
+
# def _step_logger():
|
| 39 |
+
# return get_step_logger(logging.getLogger(...))
|
| 40 |
+
|
| 41 |
+
# def fn():
|
| 42 |
+
# _step_logger()(logging.INFO, "msg")
|
| 43 |
+
|
| 44 |
+
_step_counter = itertools.count(1)
|
| 45 |
+
|
| 46 |
+
# Update num_steps if more phases are added: Dynamo, AOT, Backend
|
| 47 |
+
# This is very inductor centric
|
| 48 |
+
# _inductor.utils.has_triton() gives a circular import error here
|
| 49 |
+
|
| 50 |
+
if not disable_progress:
|
| 51 |
+
try:
|
| 52 |
+
import triton # noqa: F401
|
| 53 |
+
|
| 54 |
+
num_steps = 3
|
| 55 |
+
except ImportError:
|
| 56 |
+
num_steps = 2
|
| 57 |
+
pbar = tqdm(total=num_steps, desc="torch.compile()", delay=0)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_step_logger(logger: logging.Logger) -> Callable[..., None]:
|
| 61 |
+
if not disable_progress:
|
| 62 |
+
pbar.update(1)
|
| 63 |
+
if not isinstance(pbar, _Faketqdm):
|
| 64 |
+
pbar.set_postfix_str(f"{logger.name}")
|
| 65 |
+
|
| 66 |
+
step = next(_step_counter)
|
| 67 |
+
|
| 68 |
+
def log(level: int, msg: str, **kwargs: Any) -> None:
|
| 69 |
+
if "stacklevel" not in kwargs:
|
| 70 |
+
kwargs["stackl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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Metrics collection and management system for Dynamo.
|
| 2 |
+
|
| 3 |
+
This module provides context managers for gathering and reporting metrics during
|
| 4 |
+
compilation and runtime.
|
| 5 |
+
|
| 6 |
+
It includes two main components:
|
| 7 |
+
- MetricsContext: A context manager for collecting metrics during compilation, supporting
|
| 8 |
+
nested contexts and various metric types (counters, sets, key-value pairs)
|
| 9 |
+
- RuntimeMetricsContext: A specialized context for runtime metrics collection that doesn't
|
| 10 |
+
require explicit context management
|
| 11 |
+
|
| 12 |
+
The metrics system enables comprehensive monitoring and analysis of both compilation and
|
| 13 |
+
execution performance.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import heapq
|
| 19 |
+
import logging
|
| 20 |
+
import time
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from typing import Any, Optional, TYPE_CHECKING, TypeAlias
|
| 23 |
+
from typing_extensions import Self
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from collections.abc import Iterator
|
| 28 |
+
|
| 29 |
+
from torch.utils._traceback import CapturedTraceback
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TopN:
|
| 36 |
+
"""
|
| 37 |
+
Helper to record a list of metrics, keeping only the top N "most expensive" elements.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, at_most: int = 25):
|
| 41 |
+
self.at_most = at_most
|
| 42 |
+
self.heap: list[tuple[int, Any]] = []
|
| 43 |
+
|
| 44 |
+
def add(self, key: Any, val: int) -> None:
|
| 45 |
+
# Push if we haven't reached the max size, else push and pop the smallest
|
| 46 |
+
fn = heapq.heappush if len(self.heap) < self.at_most else heapq.heappushpop
|
| 47 |
+
fn(self.heap, (val, key))
|
| 48 |
+
|
| 49 |
+
def __len__(self) -> int:
|
| 50 |
+
return len(self.heap)
|
| 51 |
+
|
| 52 |
+
def __iter__(self) -> Iterator[tuple[Any, int]]:
|
| 53 |
+
return ((key, val) for val, key in sorted(self.heap, reverse=True))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
OnExitType: TypeAlias = Callable[
|
| 57 |
+
[int, int, dict[str, Any], Optional[type[BaseException]], Optional[BaseException]],
|
| 58 |
+
None,
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class MetricsContext:
|
| 63 |
+
def __init__(self, on_exit: OnExitType):
|
| 64 |
+
"""
|
| 65 |
+
Use this class as a contextmanager to create a context under which to accumulate
|
| 66 |
+
a set of metrics, e.g., metrics gathered during a compilation. On exit of the
|
| 67 |
+
contextmanager, call the provided 'on_exit' function and pass a dictionary of
|
| 68 |
+
all metrics set during the lifetime of the contextmanager.
|
| 69 |
+
"""
|
| 70 |
+
self._on_exit = on_exit
|
| 71 |
+
self._metrics: dict[str, Any] = {}
|
| 72 |
+
self._start_time_ns: int = 0
|
| 73 |
+
self._level: int = 0
|
| 74 |
+
self._edits: list[tuple[CapturedTraceback, set[str]]] = []
|
| 75 |
+
|
| 76 |
+
def __enter__(self) -> Self:
|
| 77 |
+
"""
|
| 78 |
+
Initialize metrics recording.
|
| 79 |
+
"""
|
| 80 |
+
if self._level == 0:
|
| 81 |
+
# In case of recursion, track at the outermost context.
|
| 82 |
+
self._metrics = {}
|
| 83 |
+
self._start_time_ns = time.time_ns()
|
| 84 |
+
|
| 85 |
+
self._level += 1
|
| 86 |
+
return self
|
| 87 |
+
|
| 88 |
+
def __exit__(
|
| 89 |
+
self,
|
| 90 |
+
exc_type: Optional[type[BaseException]],
|
| 91 |
+
exc_value: Optional[BaseException],
|
| 92 |
+
_traceback: Any,
|
| 93 |
+
) -> None:
|
| 94 |
+
"""
|
| 95 |
+
At exit, call the provided on_exit function.
|
| 96 |
+
"""
|
| 97 |
+
self._level -= 1
|
| 98 |
+
assert self._level >= 0
|
| 99 |
+
if self._level == 0:
|
| 100 |
+
try:
|
| 101 |
+
end_time_ns = time.time_ns()
|
| 102 |
+
self._on_exit(
|
| 103 |
+
self._start_time_ns, end_time_ns, self._metrics, exc_type, exc_value
|
| 104 |
+
)
|
| 105 |
+
except Exception:
|
| 106 |
+
log.exception("Unexpected exception logging compilation metrics")
|
| 107 |
+
|
| 108 |
+
def in_progress(self) -> bool:
|
| 109 |
+
"""
|
| 110 |
+
True if we've entered the context.
|
| 111 |
+
"""
|
| 112 |
+
return self._level > 0
|
| 113 |
+
|
| 114 |
+
def increment(self, metric: str, value: int) -> None:
|
| 115 |
+
"""
|
| 116 |
+
Increment a metric by a given amount.
|
| 117 |
+
"""
|
| 118 |
+
if self._level == 0:
|
| 119 |
+
raise RuntimeError(f"Cannot increment {metric} outside of a MetricsContext")
|
| 120 |
+
if metric not in self._metrics:
|
| 121 |
+
self._metrics[metric] = 0
|
| 122 |
+
self._metrics[metric] += value
|
| 123 |
+
|
| 124 |
+
def _render_edits(self, pred: set[str]) -> str:
|
| 125 |
+
return "\n\n" + "\n\n".join(
|
| 126 |
+
"Previous Traceback:\n" + "".join(e.format())
|
| 127 |
+
for e, k in self._edits
|
| 128 |
+
if k & pred
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def set(self, metric: str, value: Any, overwrite: bool = False) -> None:
|
| 132 |
+
"""
|
| 133 |
+
Set a metric to a given value. Raises if the metric has been assigned previously
|
| 134 |
+
in the current context.
|
| 135 |
+
"""
|
| 136 |
+
if self._level == 0:
|
| 137 |
+
raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext")
|
| 138 |
+
if metric in self._metrics and not overwrite:
|
| 139 |
+
raise RuntimeError(
|
| 140 |
+
self._render_edits({metric})
|
| 141 |
+
+ f"\n\nRuntimeError: Metric '{metric}' has already been set in the current context "
|
| 142 |
+
"(see above for current and previous traceback)."
|
| 143 |
+
)
|
| 144 |
+
self._edits.append((CapturedTraceback.extract(skip=1), {metric}))
|
| 145 |
+
self._metrics[metric] = value
|
| 146 |
+
|
| 147 |
+
def set_key_value(self, metric: str, key: str, value: Any) -> None:
|
| 148 |
+
"""
|
| 149 |
+
Treats a give metric as a dictionary and set the k and value within it.
|
| 150 |
+
Note that the metric must be a dictionary or not present.
|
| 151 |
+
|
| 152 |
+
We allow this to be called multiple times (i.e. for features, it's not uncommon
|
| 153 |
+
for them to be used multiple times within a single compilation).
|
| 154 |
+
"""
|
| 155 |
+
if self._level == 0:
|
| 156 |
+
raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext")
|
| 157 |
+
if metric not in self._metrics:
|
| 158 |
+
self._metrics[metric] = {}
|
| 159 |
+
self._metrics[metric][key] = value
|
| 160 |
+
|
| 161 |
+
def update(self, values: dict[str, Any], overwrite: bool = False) -> None:
|
| 162 |
+
"""
|
| 163 |
+
Set multiple metrics directly. This method does NOT increment. Raises if any
|
| 164 |
+
metric has been assigned previously in the current context and overwrite is
|
| 165 |
+
not set to True.
|
| 166 |
+
"""
|
| 167 |
+
if self._level == 0:
|
| 168 |
+
raise RuntimeError("Cannot update metrics outside of a MetricsContext")
|
| 169 |
+
existing = self._metrics.keys() & values.keys()
|
| 170 |
+
if existing and not overwrite:
|
| 171 |
+
raise RuntimeError(
|
| 172 |
+
self._render_edits(set(values.keys()))
|
| 173 |
+
+ f"\n\nRuntimeError: Metric(s) {existing} have already been set in the current context. "
|
| 174 |
+
"(see above for current and previous traceback)."
|
| 175 |
+
)
|
| 176 |
+
self._edits.append((CapturedTraceback.extract(skip=1), set(values.keys())))
|
| 177 |
+
self._metrics.update(values)
|
| 178 |
+
|
| 179 |
+
def update_outer(self, values: dict[str, Any]) -> None:
|
| 180 |
+
"""
|
| 181 |
+
Update, but only when at the outermost context.
|
| 182 |
+
"""
|
| 183 |
+
if self._level == 0:
|
| 184 |
+
raise RuntimeError("Cannot update metrics outside of a MetricsContext")
|
| 185 |
+
if self._level == 1:
|
| 186 |
+
self.update(values)
|
| 187 |
+
|
| 188 |
+
def add_to_set(self, metric: str, value: Any) -> None:
|
| 189 |
+
"""
|
| 190 |
+
Records a metric as a set() of values.
|
| 191 |
+
"""
|
| 192 |
+
if self._level == 0:
|
| 193 |
+
raise RuntimeError(f"Cannot add {metric} outside of a MetricsContext")
|
| 194 |
+
if metric not in self._metrics:
|
| 195 |
+
self._metrics[metric] = set()
|
| 196 |
+
self._metrics[metric].add(value)
|
| 197 |
+
|
| 198 |
+
def add_top_n(self, metric: str, key: Any, val: int) -> None:
|
| 199 |
+
"""
|
| 200 |
+
Records a metric as a TopN set of values.
|
| 201 |
+
"""
|
| 202 |
+
if self._level == 0:
|
| 203 |
+
return
|
| 204 |
+
if metric not in self._metrics:
|
| 205 |
+
self._metrics[metric] = TopN()
|
| 206 |
+
self._metrics[metric].add(key, val)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class RuntimeMetricsContext:
|
| 210 |
+
def __init__(self, on_exit: OnExitType):
|
| 211 |
+
"""
|
| 212 |
+
Similar to MetricsContext, but used to gather the runtime metrics that are
|
| 213 |
+
decoupled from compilation, where there's not a natural place to insert a
|
| 214 |
+
context manager.
|
| 215 |
+
"""
|
| 216 |
+
self._on_exit = on_exit
|
| 217 |
+
self._metrics: dict[str, Any] = {}
|
| 218 |
+
self._start_time_ns: int = 0
|
| 219 |
+
|
| 220 |
+
def increment(
|
| 221 |
+
self, metric: str, value: int, extra: Optional[dict[str, Any]] = None
|
| 222 |
+
) -> None:
|
| 223 |
+
"""
|
| 224 |
+
Increment a metric by a given amount.
|
| 225 |
+
"""
|
| 226 |
+
if not self._metrics:
|
| 227 |
+
# Start timing on the first entry
|
| 228 |
+
self._start_time_ns = time.time_ns()
|
| 229 |
+
if metric not in self._metrics:
|
| 230 |
+
self._metrics[metric] = 0
|
| 231 |
+
self._metrics[metric] += value
|
| 232 |
+
|
| 233 |
+
if extra:
|
| 234 |
+
for k, v in extra.items():
|
| 235 |
+
if k not in self._metrics and v is not None:
|
| 236 |
+
self._metrics[k] = v
|
| 237 |
+
|
| 238 |
+
def finish(self) -> None:
|
| 239 |
+
"""
|
| 240 |
+
Call the on_exit function with the metrics gathered so far and reset.
|
| 241 |
+
"""
|
| 242 |
+
if self._metrics:
|
| 243 |
+
try:
|
| 244 |
+
end_time_ns = time.time_ns()
|
| 245 |
+
self._on_exit(
|
| 246 |
+
self._start_time_ns, end_time_ns, self._metrics, None, None
|
| 247 |
+
)
|
| 248 |
+
except Exception:
|
| 249 |
+
log.exception("Unexpected exception logging runtime metrics")
|
| 250 |
+
finally:
|
| 251 |
+
self._metrics = {}
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/mutation_guard.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mutation tracking and dynamic module detection system for Dynamo.
|
| 2 |
+
|
| 3 |
+
This module provides mechanisms to track and respond to mutations in PyTorch modules
|
| 4 |
+
and detect dynamically created or modified modules.
|
| 5 |
+
|
| 6 |
+
Key components:
|
| 7 |
+
- MutationTracker: Tracks mutations to objects and invalidates associated cached code
|
| 8 |
+
- GenerationTracker: Tracks module creation timing to identify dynamic instances
|
| 9 |
+
- Patching system for nn.Module to detect mutations and dynamic creation
|
| 10 |
+
|
| 11 |
+
The system ensures that Dynamo's optimizations remain valid by detecting and responding
|
| 12 |
+
to runtime changes in module state and structure.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import functools
|
| 16 |
+
import weakref
|
| 17 |
+
from collections.abc import MutableMapping
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import torch.nn
|
| 21 |
+
from torch.nn import Module
|
| 22 |
+
|
| 23 |
+
from . import config
|
| 24 |
+
from .utils import ExactWeakKeyDictionary, nn_module_has_global_hooks
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
unpatched_nn_module_init = torch.nn.Module.__init__
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MutationTracker:
|
| 31 |
+
db: ExactWeakKeyDictionary = ExactWeakKeyDictionary()
|
| 32 |
+
|
| 33 |
+
def __init__(self) -> None:
|
| 34 |
+
self.mutation_count: int = 0
|
| 35 |
+
self.watchers: list[weakref.ReferenceType[Any]] = []
|
| 36 |
+
|
| 37 |
+
def on_mutation(self, name: str) -> None:
|
| 38 |
+
self.mutation_count += 1
|
| 39 |
+
tmp = self.watchers
|
| 40 |
+
self.watchers = []
|
| 41 |
+
for ref in tmp:
|
| 42 |
+
guarded = ref()
|
| 43 |
+
if guarded is not None:
|
| 44 |
+
guarded.invalidate(ref)
|
| 45 |
+
|
| 46 |
+
def track(self, guarded_code: Any) -> None:
|
| 47 |
+
self.watchers.append(weakref.ref(guarded_code))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def watch(obj: Any, guarded_code: Any) -> None:
|
| 51 |
+
"""invalidate guarded_code when obj is mutated"""
|
| 52 |
+
ensure_patched(type(obj))
|
| 53 |
+
|
| 54 |
+
if obj not in MutationTracker.db:
|
| 55 |
+
MutationTracker.db[obj] = MutationTracker()
|
| 56 |
+
tracker = MutationTracker.db[obj]
|
| 57 |
+
tracker.track(guarded_code)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def ensure_patched(cls: Any) -> None:
|
| 61 |
+
if getattr(cls, "___needs_mutation_patch", True):
|
| 62 |
+
cls.___needs_mutation_patch = False
|
| 63 |
+
original_setattr = cls.__setattr__
|
| 64 |
+
|
| 65 |
+
@functools.wraps(original_setattr)
|
| 66 |
+
def custom_setattr(self: Any, key: str, value: Any) -> None:
|
| 67 |
+
try:
|
| 68 |
+
MutationTracker.db[self].on_mutation(key)
|
| 69 |
+
except KeyError:
|
| 70 |
+
pass
|
| 71 |
+
return original_setattr(self, key, value)
|
| 72 |
+
|
| 73 |
+
cls.__setattr__ = custom_setattr
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class GenerationTracker:
|
| 77 |
+
generation: int = 0
|
| 78 |
+
dynamic_classes: ExactWeakKeyDictionary = ExactWeakKeyDictionary()
|
| 79 |
+
generation_values: ExactWeakKeyDictionary = ExactWeakKeyDictionary()
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def tag(cls, obj: Any) -> None:
|
| 83 |
+
cls.generation_values[obj] = cls.generation
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def mark_class_dynamic(cls: type[torch.nn.Module]) -> None:
|
| 87 |
+
assert issubclass(cls, torch.nn.Module)
|
| 88 |
+
GenerationTracker.dynamic_classes[cls] = True
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def get_generation_value(cls, obj: Any) -> int:
|
| 92 |
+
if obj not in cls.generation_values:
|
| 93 |
+
return -1
|
| 94 |
+
return cls.generation_values[obj]
|
| 95 |
+
|
| 96 |
+
@classmethod
|
| 97 |
+
def check(cls, obj: Any) -> bool:
|
| 98 |
+
return (
|
| 99 |
+
obj in cls.generation_values
|
| 100 |
+
and cls.generation_values[obj] == cls.generation
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def clear(cls) -> None:
|
| 105 |
+
cls.generation = 0
|
| 106 |
+
cls.dynamic_classes = ExactWeakKeyDictionary()
|
| 107 |
+
cls.generation_values = ExactWeakKeyDictionary()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def is_dynamic_nn_module(obj: Any, is_export: bool) -> bool:
|
| 111 |
+
"""Check for nn.Modules() created dynamically or mutated"""
|
| 112 |
+
if isinstance(obj, torch.nn.Module) and (
|
| 113 |
+
"forward" in obj.__dict__ or isinstance(obj, (dict, MutableMapping))
|
| 114 |
+
):
|
| 115 |
+
# A monkey patched `.forward` indicates something wacky is going on
|
| 116 |
+
# Similarly a nn module also subclassed as a dict is unusual.
|
| 117 |
+
return True
|
| 118 |
+
if hasattr(obj, "torchdynamo_force_dynamic"):
|
| 119 |
+
return obj.torchdynamo_force_dynamic
|
| 120 |
+
if (
|
| 121 |
+
isinstance(obj, torch.nn.Module)
|
| 122 |
+
and config.inline_inbuilt_nn_modules
|
| 123 |
+
and (not is_export or config.install_free_tensors)
|
| 124 |
+
):
|
| 125 |
+
return True
|
| 126 |
+
|
| 127 |
+
if isinstance(obj, torch.nn.Module) and nn_module_has_global_hooks():
|
| 128 |
+
return True
|
| 129 |
+
dyn = GenerationTracker.dynamic_classes.get(type(obj)) or GenerationTracker.check(
|
| 130 |
+
obj
|
| 131 |
+
)
|
| 132 |
+
return dyn
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def install_generation_tagging_init() -> None:
|
| 136 |
+
"""
|
| 137 |
+
Monkey patch torch.nn.Module.__init__ and torch.nn.Module.__setstate__
|
| 138 |
+
so we can detect nn.Module instances created dynamically inside forward methods.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
if getattr(Module, "___needs_generation_tag_patch", True):
|
| 142 |
+
init = Module.__init__
|
| 143 |
+
|
| 144 |
+
def patched_init(self: Module, *args: Any, **kwargs: Any) -> None:
|
| 145 |
+
init(self, *args, **kwargs)
|
| 146 |
+
GenerationTracker.tag(self)
|
| 147 |
+
|
| 148 |
+
Module.__init__ = patched_init # type: ignore[method-assign]
|
| 149 |
+
|
| 150 |
+
setstate = Module.__setstate__
|
| 151 |
+
|
| 152 |
+
def patched_setstate(self: Module, state: Any) -> None:
|
| 153 |
+
setstate(self, state)
|
| 154 |
+
GenerationTracker.tag(self)
|
| 155 |
+
|
| 156 |
+
Module.__setstate__ = patched_setstate # type: ignore[method-assign]
|
| 157 |
+
|
| 158 |
+
Module.___needs_generation_tag_patch = False # type: ignore[attr-defined]
|
| 159 |
+
|
| 160 |
+
GenerationTracker.generation += 1
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/output_graph.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/package.py
ADDED
|
@@ -0,0 +1,1157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module provides the infrastructure for creating and managing compile package
|
| 3 |
+
for torch.compile. We mainly have two abstractions here:
|
| 4 |
+
- CompilePackage: Overarching data structure for store and lookup a list of compiled codes.
|
| 5 |
+
- CodeCacheEntry: Data structure for a single code being compiled by torch.compile.
|
| 6 |
+
The caching behavior is always under user control explicitly so that a stronger guarantee can
|
| 7 |
+
be provided about cache hit for a specific compiled model. Users can load the compile package
|
| 8 |
+
from a different process or host.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import abc
|
| 12 |
+
import ast
|
| 13 |
+
import contextlib
|
| 14 |
+
import dataclasses
|
| 15 |
+
import functools
|
| 16 |
+
import hashlib
|
| 17 |
+
import importlib
|
| 18 |
+
import inspect
|
| 19 |
+
import json
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import pickle
|
| 23 |
+
import platform
|
| 24 |
+
import shutil
|
| 25 |
+
import sys
|
| 26 |
+
import types
|
| 27 |
+
from collections.abc import Callable, Generator, Iterator
|
| 28 |
+
from contextlib import nullcontext
|
| 29 |
+
from typing import Any, NewType, Optional, TYPE_CHECKING
|
| 30 |
+
from typing_extensions import Never
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
from torch._dynamo.exc import PackageError
|
| 34 |
+
from torch._dynamo.graph_utils import _graph_device_type
|
| 35 |
+
|
| 36 |
+
from .bytecode_transformation import get_code_keys
|
| 37 |
+
from .utils import counters, dynamo_timed, increment_frame
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.getLogger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING:
|
| 44 |
+
from .guards import GuardManagerWrapper, GuardsState
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclasses.dataclass(frozen=True)
|
| 48 |
+
class SerializedCode:
|
| 49 |
+
co_argcount: int
|
| 50 |
+
co_posonlyargcount: int
|
| 51 |
+
co_kwonlyargcount: int
|
| 52 |
+
co_nlocals: int
|
| 53 |
+
co_stacksize: int
|
| 54 |
+
co_flags: int
|
| 55 |
+
co_code: bytes
|
| 56 |
+
co_consts: tuple[Any, ...]
|
| 57 |
+
co_names: tuple[str, ...]
|
| 58 |
+
co_varnames: tuple[str, ...]
|
| 59 |
+
co_filename: str
|
| 60 |
+
co_name: str
|
| 61 |
+
co_firstlineno: int
|
| 62 |
+
co_cellvars: tuple[str, ...]
|
| 63 |
+
co_freevars: tuple[str, ...]
|
| 64 |
+
co_linetable: Optional[bytes] = None
|
| 65 |
+
co_qualname: Optional[str] = None
|
| 66 |
+
co_exceptiontable: Optional[bytes] = None
|
| 67 |
+
co_lnotab: Optional[str] = None
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
@functools.cache
|
| 71 |
+
def from_code_object(cls, code: types.CodeType) -> "SerializedCode":
|
| 72 |
+
kwargs = {key: getattr(code, key) for key in get_code_keys()}
|
| 73 |
+
kwargs["co_consts"] = tuple(
|
| 74 |
+
cls.from_code_object(c) if isinstance(c, types.CodeType) else c
|
| 75 |
+
for c in kwargs["co_consts"]
|
| 76 |
+
)
|
| 77 |
+
return cls(**kwargs)
|
| 78 |
+
|
| 79 |
+
@classmethod
|
| 80 |
+
@functools.cache
|
| 81 |
+
def to_code_object(cls, serialized_code: "SerializedCode") -> types.CodeType:
|
| 82 |
+
kwargs = {key: getattr(serialized_code, key) for key in get_code_keys()}
|
| 83 |
+
kwargs["co_consts"] = tuple(
|
| 84 |
+
cls.to_code_object(c) if isinstance(c, SerializedCode) else c
|
| 85 |
+
for c in kwargs["co_consts"]
|
| 86 |
+
)
|
| 87 |
+
return types.CodeType(
|
| 88 |
+
*kwargs.values(),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclasses.dataclass
|
| 93 |
+
class _GuardedCodeCacheEntry:
|
| 94 |
+
"""
|
| 95 |
+
Contains the serializable information associated with a single compilation in dynamo.
|
| 96 |
+
To restore an execution of compiled code, we will need to serialize the following data:
|
| 97 |
+
- Dynamo bytecode for mapping Python inputs/outputs.
|
| 98 |
+
- Dynamo guards.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
guards_state: bytes
|
| 102 |
+
dynamo_code: SerializedCode
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def load_guards_state(guards_state: bytes) -> Any:
|
| 106 |
+
try:
|
| 107 |
+
import torch.distributed.fsdp._fully_shard._fully_shard as _fully_shard
|
| 108 |
+
|
| 109 |
+
ctx = _fully_shard.disable_fsdp_module_new_init()
|
| 110 |
+
except ImportError:
|
| 111 |
+
ctx = nullcontext() # type: ignore[assignment]
|
| 112 |
+
with ctx:
|
| 113 |
+
return pickle.loads(guards_state)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def load_guard_manager(
|
| 117 |
+
guards_state: "GuardsState",
|
| 118 |
+
target_code: types.CodeType,
|
| 119 |
+
runtime_global_scope: Any,
|
| 120 |
+
) -> "GuardManagerWrapper":
|
| 121 |
+
from .output_graph import OutputGraphCommon
|
| 122 |
+
|
| 123 |
+
return torch._dynamo.guards.CheckFunctionManager(
|
| 124 |
+
target_code,
|
| 125 |
+
OutputGraphCommon(guards_state.output_graph),
|
| 126 |
+
shape_code_parts=guards_state.shape_code_parts,
|
| 127 |
+
runtime_global_scope=runtime_global_scope,
|
| 128 |
+
source_get_cache=guards_state.source_get_cache,
|
| 129 |
+
).guard_manager
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
_BackendId = NewType("_BackendId", str) # __compiled_fn
|
| 133 |
+
_FunctionId = NewType("_FunctionId", str) # __resume_at
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@dataclasses.dataclass(frozen=True)
|
| 137 |
+
class InlinedSource:
|
| 138 |
+
module: str
|
| 139 |
+
firstlineno: int
|
| 140 |
+
lastlineno: int
|
| 141 |
+
checksum: str
|
| 142 |
+
content: str
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@functools.cache
|
| 146 |
+
def _get_module_content(module: types.ModuleType) -> str:
|
| 147 |
+
return inspect.getsource(module)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@dataclasses.dataclass
|
| 151 |
+
class SourceInfo:
|
| 152 |
+
inlined_sources: set[InlinedSource]
|
| 153 |
+
|
| 154 |
+
def add_code(self, code: types.CodeType) -> None:
|
| 155 |
+
module = inspect.getmodule(code)
|
| 156 |
+
if module is None:
|
| 157 |
+
return
|
| 158 |
+
sourcelines, firstlineno = inspect.getsourcelines(code)
|
| 159 |
+
lastlineno = firstlineno + len(sourcelines)
|
| 160 |
+
source = "".join(sourcelines)
|
| 161 |
+
assert source == "".join(_get_sourcelines(module, firstlineno, lastlineno))
|
| 162 |
+
self.inlined_sources.add(
|
| 163 |
+
InlinedSource(
|
| 164 |
+
module=module.__name__,
|
| 165 |
+
firstlineno=firstlineno,
|
| 166 |
+
lastlineno=lastlineno,
|
| 167 |
+
checksum=_hash_source(source),
|
| 168 |
+
content=_get_module_content(module),
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@dataclasses.dataclass
|
| 174 |
+
class _DynamoCodeCacheEntry:
|
| 175 |
+
"""
|
| 176 |
+
Contains the serializable information associated with a single code object
|
| 177 |
+
in dynamo. To restore an execution of compiled code, we will need the following
|
| 178 |
+
ingredients:
|
| 179 |
+
1. The "original" code object, which serves as the entry point for eager
|
| 180 |
+
execution, i.e. the code only executed when there's no cache entry hit.
|
| 181 |
+
2. The python module name this code object belongs to, for identifying the
|
| 182 |
+
enclosing global scope to inject compiled and resume functions.
|
| 183 |
+
3. A list of function names that pointing to this code object. There could be
|
| 184 |
+
multiple function objects pointing to the same code such as recursive functions.
|
| 185 |
+
4. A list of guarded code that eval frame dispatches to.
|
| 186 |
+
5. A list of imported module objects unioned from all compiled branches.
|
| 187 |
+
6. A list of "backends" (compiled fx graph) unioned from all compield branches.
|
| 188 |
+
7. A string path used to access the original code object users defined.
|
| 189 |
+
A code object can be accessed by "{python_module}.{function_name}.{code_source}" .
|
| 190 |
+
8. A boolean flag indicating whether the function is installed to global scope.
|
| 191 |
+
9. A boolean flag indicating whether the function has a compile id.
|
| 192 |
+
10. Whether or not this code entry was bypassed
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
python_code: SerializedCode
|
| 196 |
+
python_module: str
|
| 197 |
+
function_names: list[_FunctionId]
|
| 198 |
+
guarded_codes: list[_GuardedCodeCacheEntry]
|
| 199 |
+
import_sources: dict[str, str]
|
| 200 |
+
backend_ids: list[_BackendId]
|
| 201 |
+
code_source: Optional[str]
|
| 202 |
+
install_to_global: bool
|
| 203 |
+
has_compile_id: bool = False
|
| 204 |
+
bypassed: bool = False
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _lookup_code(entry: _DynamoCodeCacheEntry) -> types.CodeType:
|
| 208 |
+
assert len(entry.function_names) == 1
|
| 209 |
+
fn: Any = sys.modules[entry.python_module]
|
| 210 |
+
parts = entry.function_names[0].split(".")
|
| 211 |
+
for part in parts:
|
| 212 |
+
fn = getattr(fn, part)
|
| 213 |
+
if entry.code_source:
|
| 214 |
+
parts = entry.code_source.split(".")
|
| 215 |
+
for part in parts:
|
| 216 |
+
if part.endswith("]"):
|
| 217 |
+
index_begin = part.rfind("[")
|
| 218 |
+
assert isinstance(index_begin, int) and index_begin >= 0
|
| 219 |
+
attr = getattr(fn, part[:index_begin], None)
|
| 220 |
+
if attr is None:
|
| 221 |
+
raise PackageError(f"Cannot find source for code entry {entry}")
|
| 222 |
+
fn = attr[ast.literal_eval(part[index_begin + 1 : -1])]
|
| 223 |
+
else:
|
| 224 |
+
fn = getattr(fn, part)
|
| 225 |
+
else:
|
| 226 |
+
raise PackageError(f"Cannot find source for code entry {entry}")
|
| 227 |
+
assert isinstance(fn, types.CodeType)
|
| 228 |
+
return fn
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _raise_resolution_error(code: types.CodeType, scope: Any) -> Never:
|
| 232 |
+
raise PackageError(
|
| 233 |
+
f"Cannot resolve a fully qualified name for {code}. Lookup scope: {scope}"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _get_code_source(code: types.CodeType) -> tuple[str, str]:
|
| 238 |
+
"""
|
| 239 |
+
Given a code object, return a fully qualified name which will be used as
|
| 240 |
+
a serialized handle to access the code object from the new process.
|
| 241 |
+
This is normally a straightforward process, but there are some corner cases:
|
| 242 |
+
1. When a function is defined with decorator, then this function will be captured
|
| 243 |
+
inside a closure with the wrapper object.
|
| 244 |
+
2. When a function is defined as a nested function, then the code object will be
|
| 245 |
+
stored on the co_consts field of the parent code object by Python compiler.
|
| 246 |
+
This function handles all of the corner cases above.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
module = inspect.getmodule(code)
|
| 250 |
+
if module is None:
|
| 251 |
+
raise PackageError(f"Cannot find module for code {code}")
|
| 252 |
+
|
| 253 |
+
toplevel: Any = module
|
| 254 |
+
if sys.version_info >= (3, 11):
|
| 255 |
+
parts = code.co_qualname.split(".")
|
| 256 |
+
|
| 257 |
+
for part in parts:
|
| 258 |
+
if not hasattr(toplevel, part):
|
| 259 |
+
_raise_resolution_error(code, toplevel)
|
| 260 |
+
toplevel = getattr(toplevel, part)
|
| 261 |
+
if inspect.isfunction(toplevel):
|
| 262 |
+
break
|
| 263 |
+
seen = set()
|
| 264 |
+
|
| 265 |
+
def _find_code_source(obj: Any) -> Optional[str]:
|
| 266 |
+
nonlocal toplevel
|
| 267 |
+
nonlocal seen
|
| 268 |
+
if obj in seen:
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
seen.add(obj)
|
| 272 |
+
|
| 273 |
+
if inspect.iscode(obj):
|
| 274 |
+
if obj is code:
|
| 275 |
+
return ""
|
| 276 |
+
|
| 277 |
+
for i, const in enumerate(obj.co_consts):
|
| 278 |
+
if (res := _find_code_source(const)) is not None:
|
| 279 |
+
return f".co_consts[{i}]{res}"
|
| 280 |
+
|
| 281 |
+
if inspect.isfunction(obj):
|
| 282 |
+
if (res := _find_code_source(obj.__code__)) is not None:
|
| 283 |
+
toplevel = obj
|
| 284 |
+
return f".__code__{res}"
|
| 285 |
+
if obj.__closure__ is not None:
|
| 286 |
+
for i, cell in enumerate(obj.__closure__):
|
| 287 |
+
try:
|
| 288 |
+
cell_contents = cell.cell_contents
|
| 289 |
+
except ValueError:
|
| 290 |
+
continue
|
| 291 |
+
if not (
|
| 292 |
+
inspect.isfunction(cell_contents)
|
| 293 |
+
or inspect.iscode(cell_contents)
|
| 294 |
+
):
|
| 295 |
+
continue
|
| 296 |
+
if (res := _find_code_source(cell_contents)) is not None:
|
| 297 |
+
toplevel = obj
|
| 298 |
+
return f".__closure__[{i}].cell_contents{res}"
|
| 299 |
+
|
| 300 |
+
if sys.version_info < (3, 11):
|
| 301 |
+
if inspect.ismodule(obj):
|
| 302 |
+
for value in obj.__dict__.values():
|
| 303 |
+
if not (inspect.isfunction(value) or inspect.isclass(value)):
|
| 304 |
+
continue
|
| 305 |
+
if (res := _find_code_source(value)) is not None:
|
| 306 |
+
return res
|
| 307 |
+
|
| 308 |
+
if inspect.isclass(obj):
|
| 309 |
+
for name, value in obj.__dict__.items():
|
| 310 |
+
value = getattr(obj, name)
|
| 311 |
+
if not (inspect.isfunction(value) or inspect.isclass(value)):
|
| 312 |
+
continue
|
| 313 |
+
if (res := _find_code_source(value)) is not None:
|
| 314 |
+
if value.__name__ != name:
|
| 315 |
+
_raise_resolution_error(code, toplevel)
|
| 316 |
+
return res
|
| 317 |
+
return None
|
| 318 |
+
|
| 319 |
+
code_source = _find_code_source(toplevel)
|
| 320 |
+
if code_source is None:
|
| 321 |
+
_raise_resolution_error(code, toplevel)
|
| 322 |
+
# pyrefly: ignore [missing-attribute]
|
| 323 |
+
return toplevel.__qualname__, code_source.strip(".")
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@dataclasses.dataclass(frozen=True)
|
| 327 |
+
class SystemInfo:
|
| 328 |
+
"""
|
| 329 |
+
System information including Python, PyTorch, and GPU details.
|
| 330 |
+
This information is used to ensure compiled artifacts can only be loaded
|
| 331 |
+
with compatible system configurations.
|
| 332 |
+
"""
|
| 333 |
+
|
| 334 |
+
python_version: str
|
| 335 |
+
torch_version: str
|
| 336 |
+
toolkit_version: Optional[str]
|
| 337 |
+
triton_version: Optional[tuple[int, int]]
|
| 338 |
+
gpu_name: Optional[str]
|
| 339 |
+
CHECK_GPUS = ("cuda", "xpu")
|
| 340 |
+
|
| 341 |
+
@classmethod
|
| 342 |
+
def current(cls) -> "SystemInfo":
|
| 343 |
+
"""Create a SystemInfo instance with current system information."""
|
| 344 |
+
# Get GPU name if CUDA or XPU is available
|
| 345 |
+
gpu_name = None
|
| 346 |
+
from torch.utils._triton import get_triton_version
|
| 347 |
+
|
| 348 |
+
gpu_name, toolkit_version = None, None
|
| 349 |
+
for device_type in cls.CHECK_GPUS:
|
| 350 |
+
if getattr(torch, device_type).is_available():
|
| 351 |
+
try:
|
| 352 |
+
gpu_name = getattr(torch, device_type).get_device_name()
|
| 353 |
+
toolkit_version = getattr(torch.version, device_type)
|
| 354 |
+
break
|
| 355 |
+
except Exception:
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
return cls(
|
| 359 |
+
python_version=platform.python_version(),
|
| 360 |
+
torch_version=torch.__version__,
|
| 361 |
+
toolkit_version=toolkit_version,
|
| 362 |
+
triton_version=get_triton_version((0, 0)),
|
| 363 |
+
gpu_name=gpu_name,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def check_compatibility(
|
| 367 |
+
self, other: "SystemInfo", device_type: str = "cpu"
|
| 368 |
+
) -> None:
|
| 369 |
+
"""
|
| 370 |
+
Check if this SystemInfo is compatible with another SystemInfo.
|
| 371 |
+
Raises RuntimeError if incompatible.
|
| 372 |
+
"""
|
| 373 |
+
if self.python_version != other.python_version:
|
| 374 |
+
raise RuntimeError(
|
| 375 |
+
f"Compile package was created with a different Python version: {self.python_version}"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
if self.torch_version != other.torch_version:
|
| 379 |
+
raise RuntimeError(
|
| 380 |
+
f"Compile package was created with a different PyTorch version: {self.torch_version}"
|
| 381 |
+
)
|
| 382 |
+
if device_type in self.CHECK_GPUS:
|
| 383 |
+
if not getattr(torch, device_type).is_available():
|
| 384 |
+
raise RuntimeError(f"{device_type} is not available")
|
| 385 |
+
|
| 386 |
+
if self.toolkit_version != other.toolkit_version:
|
| 387 |
+
raise RuntimeError(
|
| 388 |
+
f"Compile package was created with a different toolkit version: {self.toolkit_version}"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
if (
|
| 392 |
+
other.triton_version != (0, 0)
|
| 393 |
+
and self.triton_version != other.triton_version
|
| 394 |
+
):
|
| 395 |
+
raise RuntimeError(
|
| 396 |
+
f"Compile package was created with a different Triton version: {self.triton_version}"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# Check GPU name if CUDA/XPU was used
|
| 400 |
+
if other.gpu_name is not None and self.gpu_name != other.gpu_name:
|
| 401 |
+
raise RuntimeError(
|
| 402 |
+
f"Compile package was created with different GPU: "
|
| 403 |
+
f"cached={self.gpu_name}, current={other.gpu_name}"
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@dataclasses.dataclass
|
| 408 |
+
class _DynamoCacheEntry:
|
| 409 |
+
codes: list[_DynamoCodeCacheEntry]
|
| 410 |
+
source_info: SourceInfo
|
| 411 |
+
device_type: str
|
| 412 |
+
system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current)
|
| 413 |
+
fn_name: Optional[str] = None
|
| 414 |
+
fn_first_lineno: Optional[str] = None
|
| 415 |
+
|
| 416 |
+
@property
|
| 417 |
+
def backend_ids(self) -> set[_BackendId]:
|
| 418 |
+
return {backend_id for code in self.codes for backend_id in code.backend_ids}
|
| 419 |
+
|
| 420 |
+
def check_versions(self) -> None:
|
| 421 |
+
"""Check if the current system is compatible with the system used to create this cache entry."""
|
| 422 |
+
current_system_info = SystemInfo.current()
|
| 423 |
+
self.system_info.check_compatibility(current_system_info, self.device_type)
|
| 424 |
+
|
| 425 |
+
def debug_info(self) -> dict[str, Any]:
|
| 426 |
+
assert len(self.codes) > 0
|
| 427 |
+
return {
|
| 428 |
+
"num_codes": str(len(self.codes)),
|
| 429 |
+
"fn_name": self.fn_name,
|
| 430 |
+
"fn_first_lineno": self.fn_first_lineno,
|
| 431 |
+
"device_type": self.device_type,
|
| 432 |
+
"backend_ids": list(self.backend_ids),
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
from torch.compiler._cache import (
|
| 437 |
+
CacheArtifact,
|
| 438 |
+
CacheArtifactFactory,
|
| 439 |
+
CacheArtifactManager,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
@CacheArtifactFactory.register
|
| 444 |
+
class PrecompileCacheArtifact(CacheArtifact):
|
| 445 |
+
def populate_cache(self) -> None:
|
| 446 |
+
DynamoCache._write_to_local_cache(self.content, self.key)
|
| 447 |
+
|
| 448 |
+
@staticmethod
|
| 449 |
+
def type() -> str:
|
| 450 |
+
return "precompile"
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
@dataclasses.dataclass
|
| 454 |
+
class PrecompileCacheEntry:
|
| 455 |
+
"""
|
| 456 |
+
A full cache entry for caching precompile, for a toplevel torch.compile.
|
| 457 |
+
Consists of a _DynamoCacheEntry, which contains all the dynamo related contents,
|
| 458 |
+
and a set of backends content. In general, the backend content here will always
|
| 459 |
+
be of type precompile_context.BackendCacheArtifact
|
| 460 |
+
"""
|
| 461 |
+
|
| 462 |
+
dynamo: _DynamoCacheEntry
|
| 463 |
+
backends: dict[_BackendId, Any]
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
def from_cache_entry(
|
| 467 |
+
cache_entry: _DynamoCacheEntry, backends: dict[_BackendId, Any]
|
| 468 |
+
) -> Optional["PrecompileCacheEntry"]:
|
| 469 |
+
backend_content: dict[_BackendId, Any] = {}
|
| 470 |
+
|
| 471 |
+
for code in cache_entry.codes:
|
| 472 |
+
for backend_id in code.backend_ids:
|
| 473 |
+
if backend_id not in backends:
|
| 474 |
+
logger.warning("Backend not found")
|
| 475 |
+
debug_str = json.dumps(
|
| 476 |
+
{
|
| 477 |
+
"entry": cache_entry.debug_info(),
|
| 478 |
+
"missing_backend": backend_id,
|
| 479 |
+
}
|
| 480 |
+
)
|
| 481 |
+
torch._logging.trace_structured(
|
| 482 |
+
"artifact",
|
| 483 |
+
metadata_fn=lambda: {
|
| 484 |
+
"name": "dynamo_cache_bypass",
|
| 485 |
+
"encoding": "json",
|
| 486 |
+
},
|
| 487 |
+
payload_fn=lambda: debug_str,
|
| 488 |
+
expect_trace_id=False,
|
| 489 |
+
)
|
| 490 |
+
code.bypassed = True
|
| 491 |
+
break
|
| 492 |
+
else:
|
| 493 |
+
backend_content[backend_id] = backends[backend_id]
|
| 494 |
+
|
| 495 |
+
return PrecompileCacheEntry(dynamo=cache_entry, backends=backend_content)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def _hash_source(source: str) -> str:
|
| 499 |
+
sha256_hash = hashlib.sha256()
|
| 500 |
+
sha256_hash.update(source.encode())
|
| 501 |
+
return sha256_hash.hexdigest()
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _get_sourcelines(
|
| 505 |
+
m: types.ModuleType, firstlineno: int, lastlineno: int
|
| 506 |
+
) -> list[str]:
|
| 507 |
+
return inspect.getsourcelines(m)[0][firstlineno - 1 : lastlineno - 1]
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _hash_sourcelines(m: types.ModuleType, firstlineno: int, lastlineno: int) -> str:
|
| 511 |
+
return _hash_source("".join(_get_sourcelines(m, firstlineno, lastlineno)))
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _compile_frame_context(
|
| 515 |
+
code: types.CodeType,
|
| 516 |
+
) -> contextlib.AbstractContextManager[None]:
|
| 517 |
+
from torch._dynamo.convert_frame import get_compile_id, log_dynamo_start
|
| 518 |
+
from torch._guards import compile_context, CompileContext
|
| 519 |
+
|
| 520 |
+
# Each code represents a new compile frame
|
| 521 |
+
# recompiles on the same frame are all saved
|
| 522 |
+
# under the same cache entry, so we don't have recompile ids
|
| 523 |
+
# i.e. If cold start had 0/0, 0/1, 1/0, 1/1, these would be
|
| 524 |
+
# collapsed into 0/0, 1/0 on warm.
|
| 525 |
+
@contextlib.contextmanager
|
| 526 |
+
def _ctx() -> Iterator[None]:
|
| 527 |
+
increment_frame()
|
| 528 |
+
compile_id = get_compile_id(frame_state={})
|
| 529 |
+
with (
|
| 530 |
+
compile_context(CompileContext(compile_id)),
|
| 531 |
+
dynamo_timed(
|
| 532 |
+
"_compile.compile_inner",
|
| 533 |
+
phase_name="entire_frame_compile",
|
| 534 |
+
dynamo_compile_column_us="dynamo_cumulative_compile_time_us",
|
| 535 |
+
# TODO: save all relevant compilation metrics
|
| 536 |
+
metadata={
|
| 537 |
+
"frame_key": str(torch._dynamo.utils.curr_frame),
|
| 538 |
+
"co_name": code.co_name,
|
| 539 |
+
"co_filename": code.co_filename,
|
| 540 |
+
"co_firstlineno": code.co_firstlineno,
|
| 541 |
+
},
|
| 542 |
+
),
|
| 543 |
+
):
|
| 544 |
+
log_dynamo_start(code)
|
| 545 |
+
yield
|
| 546 |
+
|
| 547 |
+
return _ctx()
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class CompilePackage:
|
| 551 |
+
"""
|
| 552 |
+
CompilePackage is considered a low level component and should not be directly exposed to
|
| 553 |
+
end users. It has the following interface:
|
| 554 |
+
|
| 555 |
+
1. `CompilePackage.__init__()` which optionally takes previously serialized dynamo states.
|
| 556 |
+
a. when `dynamo` argument is None, it will construct a brand new CompilePackage object.
|
| 557 |
+
b. when `dynamo` argument is not None, it will load a pre-compiled dynamo state.
|
| 558 |
+
2. `package.save()` which dumps the dynamo and backend states to a DynamoCacheEntry object.
|
| 559 |
+
3. `package.install(backends) which will handle all the side-effectful global scope
|
| 560 |
+
updates with compiled functions and resume functions.
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
def __init__(
|
| 564 |
+
self,
|
| 565 |
+
fn: Optional[Callable[..., Any]],
|
| 566 |
+
dynamo: Optional[_DynamoCacheEntry] = None,
|
| 567 |
+
ignore_inlined_sources: bool = False,
|
| 568 |
+
) -> None:
|
| 569 |
+
self._innermost_fn = None
|
| 570 |
+
self._codes: dict[types.CodeType, _DynamoCodeCacheEntry] = {}
|
| 571 |
+
|
| 572 |
+
self._current_entry: Optional[_DynamoCodeCacheEntry] = None
|
| 573 |
+
self._installed_globals: dict[types.ModuleType, list[str]] = {}
|
| 574 |
+
# device_type that model compiled with.
|
| 575 |
+
self._device_type = "cpu"
|
| 576 |
+
|
| 577 |
+
# For debugging/testing purpose only.
|
| 578 |
+
self._cached_backends: dict[_BackendId, Any] = {}
|
| 579 |
+
self._source_info: SourceInfo = SourceInfo(inlined_sources=set())
|
| 580 |
+
self._resume_codes: set[types.CodeType] = set()
|
| 581 |
+
self._initialized = False
|
| 582 |
+
if fn is not None:
|
| 583 |
+
self.initialize(fn, dynamo, ignore_inlined_sources)
|
| 584 |
+
self.uninstall()
|
| 585 |
+
self.validate()
|
| 586 |
+
|
| 587 |
+
def is_initialized(self) -> bool:
|
| 588 |
+
return self._initialized
|
| 589 |
+
|
| 590 |
+
def initialize(
|
| 591 |
+
self,
|
| 592 |
+
fn: Any,
|
| 593 |
+
dynamo: Optional[_DynamoCacheEntry] = None,
|
| 594 |
+
ignore_inlined_sources: bool = False,
|
| 595 |
+
) -> None:
|
| 596 |
+
from .eval_frame import innermost_fn
|
| 597 |
+
|
| 598 |
+
assert not self._initialized
|
| 599 |
+
self._source_info = SourceInfo(inlined_sources=set())
|
| 600 |
+
self._innermost_fn = innermost_fn(fn) # type: ignore[assignment]
|
| 601 |
+
assert self._innermost_fn is not None
|
| 602 |
+
if dynamo is not None:
|
| 603 |
+
assert isinstance(dynamo, _DynamoCacheEntry)
|
| 604 |
+
dynamo.check_versions()
|
| 605 |
+
if not ignore_inlined_sources:
|
| 606 |
+
for code in dynamo.source_info.inlined_sources:
|
| 607 |
+
m = importlib.import_module(code.module)
|
| 608 |
+
checksum = _hash_sourcelines(m, code.firstlineno, code.lastlineno)
|
| 609 |
+
if checksum != code.checksum:
|
| 610 |
+
raise RuntimeError(
|
| 611 |
+
f"Source code changes detected for {code.module} (line {code.firstlineno} - line {code.lastlineno})"
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
# pyrefly: ignore [bad-assignment]
|
| 615 |
+
self._source_info = dynamo.source_info
|
| 616 |
+
|
| 617 |
+
main, *codes = dynamo.codes
|
| 618 |
+
# pyrefly: ignore [bad-assignment]
|
| 619 |
+
self._codes = {self._innermost_fn.__code__: main}
|
| 620 |
+
for code in codes:
|
| 621 |
+
self._codes[SerializedCode.to_code_object(code.python_code)] = code
|
| 622 |
+
else:
|
| 623 |
+
self._add_function(
|
| 624 |
+
self._innermost_fn.__code__, self._innermost_fn.__module__
|
| 625 |
+
)
|
| 626 |
+
# pyrefly: ignore [bad-assignment]
|
| 627 |
+
self._initialized = True
|
| 628 |
+
|
| 629 |
+
def _add_function(
|
| 630 |
+
self,
|
| 631 |
+
python_code: types.CodeType,
|
| 632 |
+
python_module: str,
|
| 633 |
+
function_name: Optional[_FunctionId] = None,
|
| 634 |
+
code_source: Optional[str] = None,
|
| 635 |
+
install_to_global: bool = False,
|
| 636 |
+
) -> None:
|
| 637 |
+
if python_code not in self._codes:
|
| 638 |
+
code = _DynamoCodeCacheEntry(
|
| 639 |
+
python_code=SerializedCode.from_code_object(python_code),
|
| 640 |
+
python_module=python_module,
|
| 641 |
+
function_names=[],
|
| 642 |
+
guarded_codes=[],
|
| 643 |
+
import_sources={},
|
| 644 |
+
backend_ids=[],
|
| 645 |
+
code_source=code_source,
|
| 646 |
+
install_to_global=install_to_global,
|
| 647 |
+
)
|
| 648 |
+
self._codes[python_code] = code
|
| 649 |
+
else:
|
| 650 |
+
code = self._codes[python_code]
|
| 651 |
+
assert code.python_module == python_module
|
| 652 |
+
assert code.install_to_global == install_to_global
|
| 653 |
+
assert code.code_source == code_source
|
| 654 |
+
|
| 655 |
+
if function_name is not None:
|
| 656 |
+
code.function_names.append(function_name)
|
| 657 |
+
|
| 658 |
+
@property
|
| 659 |
+
def cached_backends(self) -> dict[_BackendId, Any]:
|
| 660 |
+
return self._cached_backends
|
| 661 |
+
|
| 662 |
+
@functools.cached_property
|
| 663 |
+
def source_id(self) -> str:
|
| 664 |
+
assert self._innermost_fn is not None
|
| 665 |
+
return CompilePackage.source_id_from_fn(self._innermost_fn)
|
| 666 |
+
|
| 667 |
+
def _add_user_function(self, code: types.CodeType) -> None:
|
| 668 |
+
function_name, code_source = _get_code_source(code)
|
| 669 |
+
module = inspect.getmodule(code)
|
| 670 |
+
if module is None:
|
| 671 |
+
raise PackageError(f"Cannot find module for code {code}")
|
| 672 |
+
self._add_function(
|
| 673 |
+
code,
|
| 674 |
+
module.__name__,
|
| 675 |
+
function_name=_FunctionId(function_name),
|
| 676 |
+
code_source=code_source,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
@contextlib.contextmanager
|
| 680 |
+
def code_context(self, code: types.CodeType) -> Generator[None, None, None]:
|
| 681 |
+
assert self._current_entry is None
|
| 682 |
+
|
| 683 |
+
# Sometimes user code cannot be inlined in dynamo resulting in extra user code
|
| 684 |
+
# being compiled. We should record these as when they are actually invoked.
|
| 685 |
+
if code not in self._codes:
|
| 686 |
+
self._add_user_function(code)
|
| 687 |
+
|
| 688 |
+
entry = self._codes[code]
|
| 689 |
+
self._current_entry = entry
|
| 690 |
+
try:
|
| 691 |
+
yield
|
| 692 |
+
finally:
|
| 693 |
+
entry.has_compile_id = True
|
| 694 |
+
self._current_entry = None
|
| 695 |
+
|
| 696 |
+
def add_guarded_code(
|
| 697 |
+
self,
|
| 698 |
+
guards_state: bytes,
|
| 699 |
+
dynamo_code: types.CodeType,
|
| 700 |
+
) -> None:
|
| 701 |
+
assert self._current_entry is not None
|
| 702 |
+
if self._current_entry.bypassed:
|
| 703 |
+
return
|
| 704 |
+
guarded_code_entry = _GuardedCodeCacheEntry(
|
| 705 |
+
guards_state=guards_state,
|
| 706 |
+
dynamo_code=SerializedCode.from_code_object(dynamo_code),
|
| 707 |
+
)
|
| 708 |
+
self._current_entry.guarded_codes.append(guarded_code_entry)
|
| 709 |
+
|
| 710 |
+
def add_inlined_source(self, sources: list[types.CodeType]) -> None:
|
| 711 |
+
assert self._current_entry is not None
|
| 712 |
+
if self._current_entry.bypassed:
|
| 713 |
+
return
|
| 714 |
+
for code in sources:
|
| 715 |
+
if code in self._resume_codes:
|
| 716 |
+
continue
|
| 717 |
+
self._source_info.add_code(code)
|
| 718 |
+
|
| 719 |
+
def update_device_type(self, graph: Optional[torch.fx.Graph]) -> None:
|
| 720 |
+
self._device_type = _graph_device_type(graph)
|
| 721 |
+
|
| 722 |
+
def bypass_current_entry(self) -> None:
|
| 723 |
+
assert self._current_entry is not None
|
| 724 |
+
self._current_entry.bypassed = True
|
| 725 |
+
|
| 726 |
+
def add_resume_function(
|
| 727 |
+
self,
|
| 728 |
+
python_code: types.CodeType,
|
| 729 |
+
python_module: str,
|
| 730 |
+
function_name: Optional[str],
|
| 731 |
+
) -> None:
|
| 732 |
+
self._add_function(
|
| 733 |
+
python_code,
|
| 734 |
+
python_module,
|
| 735 |
+
function_name=_FunctionId(function_name) if function_name else None,
|
| 736 |
+
install_to_global=True,
|
| 737 |
+
)
|
| 738 |
+
self._resume_codes.add(python_code)
|
| 739 |
+
|
| 740 |
+
def add_import_source(self, alias: str, module_name: str) -> None:
|
| 741 |
+
assert self._current_entry is not None
|
| 742 |
+
self._current_entry.import_sources[alias] = module_name
|
| 743 |
+
|
| 744 |
+
def add_backend_id(self, backend_id: str, backend: Optional[Any] = None) -> None:
|
| 745 |
+
assert self._current_entry is not None
|
| 746 |
+
assert backend_id.startswith("__compiled_fn_") # sanity check
|
| 747 |
+
backend_id = _BackendId(backend_id)
|
| 748 |
+
self._current_entry.backend_ids.append(backend_id)
|
| 749 |
+
if backend is not None:
|
| 750 |
+
self._cached_backends[backend_id] = backend
|
| 751 |
+
|
| 752 |
+
def validate(self) -> None:
|
| 753 |
+
assert self._current_entry is None
|
| 754 |
+
assert self._innermost_fn is not None
|
| 755 |
+
assert self._initialized
|
| 756 |
+
assert next(iter(self._codes)) is self._innermost_fn.__code__
|
| 757 |
+
|
| 758 |
+
def _install_global(self, module: types.ModuleType, name: str, value: Any) -> None:
|
| 759 |
+
module.__dict__[name] = value
|
| 760 |
+
self._installed_globals.setdefault(module, []).append(name)
|
| 761 |
+
|
| 762 |
+
def uninstall(self) -> None:
|
| 763 |
+
from torch._C._dynamo.eval_frame import _reset_precompile_entries
|
| 764 |
+
|
| 765 |
+
assert self._innermost_fn is not None
|
| 766 |
+
for module, names in self._installed_globals.items():
|
| 767 |
+
for name in names:
|
| 768 |
+
module.__dict__.pop(name)
|
| 769 |
+
|
| 770 |
+
# pyrefly: ignore [bad-assignment]
|
| 771 |
+
self._installed_globals = {}
|
| 772 |
+
|
| 773 |
+
_reset_precompile_entries(self._innermost_fn.__code__)
|
| 774 |
+
|
| 775 |
+
def install(self, backends: dict[_BackendId, Any]) -> None:
|
| 776 |
+
"""
|
| 777 |
+
Sync the package states to the compiled function. This includes the following actions:
|
| 778 |
+
1. Clean up the previously installed states.
|
| 779 |
+
2. Install the compiled functions to global scopes.
|
| 780 |
+
3. Install the precompiled cache entries to ExtraStates on the code object.
|
| 781 |
+
"""
|
| 782 |
+
from torch._C._dynamo.eval_frame import _load_precompile_entry
|
| 783 |
+
|
| 784 |
+
from .output_graph import get_builtins_dict
|
| 785 |
+
|
| 786 |
+
self.uninstall()
|
| 787 |
+
for code, entry in self._codes.items():
|
| 788 |
+
context = (
|
| 789 |
+
_compile_frame_context(code)
|
| 790 |
+
if entry.has_compile_id
|
| 791 |
+
else contextlib.nullcontext()
|
| 792 |
+
)
|
| 793 |
+
with context:
|
| 794 |
+
module = sys.modules[entry.python_module]
|
| 795 |
+
for alias, module_name in entry.import_sources.items():
|
| 796 |
+
self._install_global(
|
| 797 |
+
module, alias, importlib.import_module(module_name)
|
| 798 |
+
)
|
| 799 |
+
target_code = code
|
| 800 |
+
if entry.install_to_global:
|
| 801 |
+
for function_name in entry.function_names:
|
| 802 |
+
fn = types.FunctionType(code, module.__dict__, function_name)
|
| 803 |
+
self._install_global(module, function_name, fn)
|
| 804 |
+
if entry.code_source:
|
| 805 |
+
target_code = _lookup_code(entry)
|
| 806 |
+
|
| 807 |
+
if entry.bypassed:
|
| 808 |
+
# If the entry is bypassed, do not install backends
|
| 809 |
+
# or guarded codes.
|
| 810 |
+
continue
|
| 811 |
+
|
| 812 |
+
for backend_id in entry.backend_ids:
|
| 813 |
+
if backend_id not in backends:
|
| 814 |
+
raise RuntimeError(
|
| 815 |
+
f"Backend {backend_id} is not found in the given backends"
|
| 816 |
+
)
|
| 817 |
+
with dynamo_timed(
|
| 818 |
+
"after_deserialization", phase_name="backend_compile"
|
| 819 |
+
):
|
| 820 |
+
backend = backends[backend_id].after_deserialization()
|
| 821 |
+
self._install_global(
|
| 822 |
+
module,
|
| 823 |
+
backend_id,
|
| 824 |
+
torch._dynamo.disable(backend),
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
if len(entry.guarded_codes) == 0:
|
| 828 |
+
# Dynamo generates empty graph for trivial functions, should just skip them
|
| 829 |
+
# in these cases.
|
| 830 |
+
torch._dynamo.eval_frame.skip_code(target_code)
|
| 831 |
+
|
| 832 |
+
for guarded_code in entry.guarded_codes:
|
| 833 |
+
with dynamo_timed("precompile_load_guards"):
|
| 834 |
+
guards_state = load_guards_state(guarded_code.guards_state)
|
| 835 |
+
runtime_global_scope = sys.modules[entry.python_module].__dict__
|
| 836 |
+
# The installed builtins dict might be absent from the runtime
|
| 837 |
+
# while loading guards. Populate it if it's missing.
|
| 838 |
+
if (
|
| 839 |
+
builtin_dict_name
|
| 840 |
+
:= guards_state.output_graph.name_of_builtins_dict_key_in_fglobals
|
| 841 |
+
):
|
| 842 |
+
builtins_dict = get_builtins_dict(runtime_global_scope)
|
| 843 |
+
if builtin_dict_name in runtime_global_scope:
|
| 844 |
+
assert (
|
| 845 |
+
runtime_global_scope[builtin_dict_name] is builtins_dict
|
| 846 |
+
)
|
| 847 |
+
else:
|
| 848 |
+
runtime_global_scope[builtin_dict_name] = builtins_dict
|
| 849 |
+
assert isinstance(guards_state, torch._dynamo.guards.GuardsState)
|
| 850 |
+
with dynamo_timed("precompile_build_guards"):
|
| 851 |
+
guard_manager = load_guard_manager(
|
| 852 |
+
guards_state, target_code, runtime_global_scope
|
| 853 |
+
)
|
| 854 |
+
_load_precompile_entry(
|
| 855 |
+
target_code,
|
| 856 |
+
guard_manager,
|
| 857 |
+
SerializedCode.to_code_object(guarded_code.dynamo_code),
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
def cache_entry(self) -> _DynamoCacheEntry:
|
| 861 |
+
self.validate()
|
| 862 |
+
assert self._innermost_fn is not None
|
| 863 |
+
return _DynamoCacheEntry(
|
| 864 |
+
codes=list(self._codes.values()),
|
| 865 |
+
source_info=self._source_info,
|
| 866 |
+
device_type=self._device_type,
|
| 867 |
+
fn_name=self._innermost_fn.__qualname__,
|
| 868 |
+
fn_first_lineno=self._innermost_fn.__code__.co_firstlineno,
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
@staticmethod
|
| 872 |
+
def source_id_from_fn(fn: Callable[..., Any]) -> str:
|
| 873 |
+
from .eval_frame import innermost_fn
|
| 874 |
+
|
| 875 |
+
innermost_fn_ = innermost_fn(fn)
|
| 876 |
+
|
| 877 |
+
sha256_hash = hashlib.sha256()
|
| 878 |
+
sha256_hash.update(innermost_fn_.__qualname__.encode())
|
| 879 |
+
sha256_hash.update(str(innermost_fn_.__code__.co_firstlineno).encode())
|
| 880 |
+
return sha256_hash.hexdigest()
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
_Backends = dict[_BackendId, Any]
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
class DynamoStore(abc.ABC):
|
| 887 |
+
"""
|
| 888 |
+
A DynamoStore tracks active CompilePackages, and provides methods to store and retrieve them.
|
| 889 |
+
|
| 890 |
+
This is an abstract base class for different storage implementations.
|
| 891 |
+
"""
|
| 892 |
+
|
| 893 |
+
def record_package(self, package: CompilePackage) -> None:
|
| 894 |
+
"""
|
| 895 |
+
Records a package to PrecompileContext, so that it can be serialized later.
|
| 896 |
+
"""
|
| 897 |
+
from torch._dynamo.precompile_context import PrecompileContext
|
| 898 |
+
|
| 899 |
+
cache_entry = package.cache_entry()
|
| 900 |
+
PrecompileContext.record_dynamo_cache_entry(
|
| 901 |
+
cache_entry=cache_entry, key=package.source_id
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
def record_eager_backend(self, backend_id: _BackendId, backend: Any) -> None:
|
| 905 |
+
"""
|
| 906 |
+
Records eager fx graphs to PrecompileContext for testing purposes.
|
| 907 |
+
"""
|
| 908 |
+
from torch._dynamo.precompile_context import (
|
| 909 |
+
EagerCacheArtifact,
|
| 910 |
+
PrecompileContext,
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
result = EagerCacheArtifact(key=backend_id, content=backend)
|
| 914 |
+
PrecompileContext.record_artifact(result)
|
| 915 |
+
|
| 916 |
+
@abc.abstractmethod
|
| 917 |
+
def clear(self) -> None: ...
|
| 918 |
+
|
| 919 |
+
@abc.abstractmethod
|
| 920 |
+
def write(
|
| 921 |
+
self,
|
| 922 |
+
cache_entry: PrecompileCacheEntry,
|
| 923 |
+
path: str,
|
| 924 |
+
) -> None:
|
| 925 |
+
"""
|
| 926 |
+
Abstract method to write dynamo cache entry and backends to storage.
|
| 927 |
+
|
| 928 |
+
Args:
|
| 929 |
+
dynamo: The dynamo cache entry to write
|
| 930 |
+
backends: Dictionary of backend content to write
|
| 931 |
+
path: Path or key to identify where to write the data
|
| 932 |
+
"""
|
| 933 |
+
...
|
| 934 |
+
|
| 935 |
+
def save_cache_entry(self, cache_entry: _DynamoCacheEntry, key: str) -> None:
|
| 936 |
+
"""
|
| 937 |
+
Saves a package to a given path. Grabs backends from PrecompileContext.
|
| 938 |
+
"""
|
| 939 |
+
from torch._dynamo.precompile_context import (
|
| 940 |
+
BackendCacheArtifact,
|
| 941 |
+
PrecompileContext,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
backend_content: _Backends = {}
|
| 945 |
+
for backend_id in cache_entry.backend_ids:
|
| 946 |
+
serialized_backend = PrecompileContext.serialize_artifact_by_key(backend_id)
|
| 947 |
+
if serialized_backend is None:
|
| 948 |
+
raise RuntimeError(
|
| 949 |
+
f"Backend {backend_id} is not found in the given backends"
|
| 950 |
+
)
|
| 951 |
+
assert isinstance(serialized_backend, BackendCacheArtifact)
|
| 952 |
+
backend_content[backend_id] = serialized_backend
|
| 953 |
+
|
| 954 |
+
entry = PrecompileCacheEntry(cache_entry, backend_content)
|
| 955 |
+
|
| 956 |
+
self.write(entry, key)
|
| 957 |
+
|
| 958 |
+
def save_package(self, package: CompilePackage, key: str) -> None:
|
| 959 |
+
"""
|
| 960 |
+
Saves a package to a given path. Grabs backends from PrecompileContext.
|
| 961 |
+
"""
|
| 962 |
+
self.record_package(package)
|
| 963 |
+
cache_entry = package.cache_entry()
|
| 964 |
+
self.save_cache_entry(cache_entry, key)
|
| 965 |
+
|
| 966 |
+
@abc.abstractmethod
|
| 967 |
+
def read(self, path: str) -> PrecompileCacheEntry:
|
| 968 |
+
"""
|
| 969 |
+
Abstract method to read dynamo cache entry and backends from storage.
|
| 970 |
+
|
| 971 |
+
Args:
|
| 972 |
+
path: Path or key to identify where to read the data from
|
| 973 |
+
|
| 974 |
+
Returns:
|
| 975 |
+
A tuple containing (dynamo_cache_entry, backend_content)
|
| 976 |
+
"""
|
| 977 |
+
...
|
| 978 |
+
|
| 979 |
+
def load_cache_entry(self, key: str) -> PrecompileCacheEntry:
|
| 980 |
+
from torch._dynamo.precompile_context import (
|
| 981 |
+
BackendCacheArtifact,
|
| 982 |
+
PrecompileContext,
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
precompile_entry = self.read(key)
|
| 986 |
+
for backend in precompile_entry.backends.values():
|
| 987 |
+
assert isinstance(backend, BackendCacheArtifact)
|
| 988 |
+
PrecompileContext.record_artifact(backend)
|
| 989 |
+
|
| 990 |
+
return precompile_entry
|
| 991 |
+
|
| 992 |
+
def load_package(
|
| 993 |
+
self, fn: Any, key: str
|
| 994 |
+
) -> tuple[CompilePackage, dict[_BackendId, Any]]:
|
| 995 |
+
"""
|
| 996 |
+
Loads a package from a given path and returns it plus a list of deserialized backends
|
| 997 |
+
"""
|
| 998 |
+
entry = self.load_cache_entry(key)
|
| 999 |
+
package = CompilePackage(fn, entry.dynamo)
|
| 1000 |
+
return package, entry.backends
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
class InMemoryDynamoStore(DynamoStore):
|
| 1004 |
+
"""
|
| 1005 |
+
A DynamoStore implementation that keeps state about CompilePackages in memory.
|
| 1006 |
+
"""
|
| 1007 |
+
|
| 1008 |
+
def __init__(self) -> None:
|
| 1009 |
+
self.packages: dict[str, PrecompileCacheEntry] = {}
|
| 1010 |
+
|
| 1011 |
+
def clear(self) -> None:
|
| 1012 |
+
self.packages.clear()
|
| 1013 |
+
|
| 1014 |
+
def write(
|
| 1015 |
+
self,
|
| 1016 |
+
entry: PrecompileCacheEntry,
|
| 1017 |
+
path: str,
|
| 1018 |
+
) -> None:
|
| 1019 |
+
"""
|
| 1020 |
+
Store the dynamo cache entry and backends in memory instead of writing to disk.
|
| 1021 |
+
"""
|
| 1022 |
+
self.packages[path] = entry
|
| 1023 |
+
|
| 1024 |
+
def read(self, path: str) -> PrecompileCacheEntry:
|
| 1025 |
+
"""
|
| 1026 |
+
Read dynamo cache entry and backends from memory.
|
| 1027 |
+
"""
|
| 1028 |
+
if path not in self.packages:
|
| 1029 |
+
raise RuntimeError(f"No package found with key {path}")
|
| 1030 |
+
|
| 1031 |
+
return self.packages[path]
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
class DiskDynamoStore(DynamoStore):
|
| 1035 |
+
"""
|
| 1036 |
+
A DynamoStore implementation that keeps state about CompilePackages on disk.
|
| 1037 |
+
"""
|
| 1038 |
+
|
| 1039 |
+
def __init__(self, path_prefix: str = ""):
|
| 1040 |
+
"""
|
| 1041 |
+
Initialize a DiskDynamoStore with a path prefix.
|
| 1042 |
+
|
| 1043 |
+
Args:
|
| 1044 |
+
path_prefix: Prefix directory for where to put CompilePackages on disk
|
| 1045 |
+
"""
|
| 1046 |
+
self._path_prefix = path_prefix
|
| 1047 |
+
|
| 1048 |
+
def path_prefix(self) -> str:
|
| 1049 |
+
return self._path_prefix
|
| 1050 |
+
|
| 1051 |
+
def clear(self) -> None:
|
| 1052 |
+
"""
|
| 1053 |
+
Clear all CompilePackages from disk.
|
| 1054 |
+
"""
|
| 1055 |
+
if self.path_prefix():
|
| 1056 |
+
shutil.rmtree(self.path_prefix(), ignore_errors=True)
|
| 1057 |
+
|
| 1058 |
+
def write(
|
| 1059 |
+
self,
|
| 1060 |
+
entry: PrecompileCacheEntry,
|
| 1061 |
+
path: str,
|
| 1062 |
+
) -> None:
|
| 1063 |
+
"""
|
| 1064 |
+
Write dynamo cache entry and backends to disk.
|
| 1065 |
+
"""
|
| 1066 |
+
try:
|
| 1067 |
+
pickled_content: bytes = pickle.dumps(entry)
|
| 1068 |
+
CacheArtifactManager.record_artifact(
|
| 1069 |
+
PrecompileCacheArtifact.type(), path, pickled_content
|
| 1070 |
+
)
|
| 1071 |
+
self._write_to_local_cache(pickled_content, path)
|
| 1072 |
+
except Exception as e:
|
| 1073 |
+
raise RuntimeError(f"Failed to save package to {path}: {e}") from e
|
| 1074 |
+
|
| 1075 |
+
def _write_to_local_cache(self, pickled_content: bytes, path: str) -> None:
|
| 1076 |
+
from torch._inductor.codecache import write_atomic
|
| 1077 |
+
|
| 1078 |
+
path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path
|
| 1079 |
+
try:
|
| 1080 |
+
os.makedirs(path, exist_ok=True)
|
| 1081 |
+
write_atomic(os.path.join(path, "entry"), pickled_content)
|
| 1082 |
+
except Exception as e:
|
| 1083 |
+
raise RuntimeError(f"Failed to save package to {path}: {e}") from e
|
| 1084 |
+
|
| 1085 |
+
def read(self, path: str) -> PrecompileCacheEntry:
|
| 1086 |
+
"""
|
| 1087 |
+
Read dynamo cache entry and backends from disk.
|
| 1088 |
+
"""
|
| 1089 |
+
path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path
|
| 1090 |
+
try:
|
| 1091 |
+
with open(os.path.join(path, "entry"), "rb") as f:
|
| 1092 |
+
pickled_content = f.read()
|
| 1093 |
+
entry = pickle.loads(pickled_content)
|
| 1094 |
+
return entry
|
| 1095 |
+
except Exception as e:
|
| 1096 |
+
raise RuntimeError(f"Failed to load package from path {path}: {e}") from e
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
class DiskDynamoCache(DiskDynamoStore):
|
| 1100 |
+
"""
|
| 1101 |
+
Special DiskDynamoStore which adds some helper functions for automatically
|
| 1102 |
+
tracking paths of packages
|
| 1103 |
+
"""
|
| 1104 |
+
|
| 1105 |
+
def save(self, package: CompilePackage) -> None:
|
| 1106 |
+
"""
|
| 1107 |
+
Saves a package to a given path. Grabs backends from PrecompileContext.
|
| 1108 |
+
"""
|
| 1109 |
+
key = package.source_id
|
| 1110 |
+
logger.info("Saving CompilePackage for %s", package.source_id)
|
| 1111 |
+
super().save_package(package, key)
|
| 1112 |
+
|
| 1113 |
+
def load(self, fn: Callable[..., Any]) -> Optional[PrecompileCacheEntry]:
|
| 1114 |
+
"""
|
| 1115 |
+
Loads a package from a given path and returns it plus a list of deserialized backends
|
| 1116 |
+
"""
|
| 1117 |
+
key = CompilePackage.source_id_from_fn(fn)
|
| 1118 |
+
logger.info("Loading CompilePackage for %s", key)
|
| 1119 |
+
path = os.path.join(self.path_prefix(), key)
|
| 1120 |
+
if os.path.exists(path):
|
| 1121 |
+
try:
|
| 1122 |
+
result = super().load_cache_entry(key)
|
| 1123 |
+
counters["dynamo_cache"]["dynamo_cache_hit"] += 1
|
| 1124 |
+
return result
|
| 1125 |
+
except Exception:
|
| 1126 |
+
counters["dynamo_cache"]["dynamo_cache_error"] += 1
|
| 1127 |
+
logger.warning("Failed to load package from path %s", exc_info=True)
|
| 1128 |
+
return None
|
| 1129 |
+
logger.info("No package found for %s", key)
|
| 1130 |
+
counters["dynamo_cache"]["dynamo_cache_miss"] += 1
|
| 1131 |
+
return None
|
| 1132 |
+
|
| 1133 |
+
def load_and_install_package(
|
| 1134 |
+
self, fn: Callable[..., Any]
|
| 1135 |
+
) -> Optional[CompilePackage]:
|
| 1136 |
+
"""
|
| 1137 |
+
Load directly into a package and install backends
|
| 1138 |
+
"""
|
| 1139 |
+
results = self.load(fn)
|
| 1140 |
+
if results is None:
|
| 1141 |
+
return None
|
| 1142 |
+
else:
|
| 1143 |
+
package = CompilePackage(fn, results.dynamo)
|
| 1144 |
+
package.install(results.backends)
|
| 1145 |
+
return package
|
| 1146 |
+
|
| 1147 |
+
def path_prefix(self) -> str:
|
| 1148 |
+
return os.path.join(cache_dir(), "dynamo")
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
def cache_dir() -> str:
|
| 1152 |
+
from torch._inductor.runtime.cache_dir_utils import cache_dir
|
| 1153 |
+
|
| 1154 |
+
return cache_dir()
|
| 1155 |
+
|
| 1156 |
+
|
| 1157 |
+
DynamoCache = DiskDynamo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+
Profile Guided Optimization (PGO) implementation for Dynamo.
|
| 3 |
+
|
| 4 |
+
This module provides functionality for caching and managing code state profiles
|
| 5 |
+
that guide optimization decisions in Dynamo. It implements both local and remote
|
| 6 |
+
caching mechanisms for storing profile information across runs, handles profile
|
| 7 |
+
merging across distributed ranks, and manages the lifecycle of profile data
|
| 8 |
+
during compilation. The profiles track dynamic vs static properties of tensors
|
| 9 |
+
and help Dynamo make better specialization decisions.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import base64
|
| 15 |
+
import copy
|
| 16 |
+
import dataclasses
|
| 17 |
+
import enum
|
| 18 |
+
import functools
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import pickle
|
| 22 |
+
import re
|
| 23 |
+
import zlib
|
| 24 |
+
from collections import defaultdict
|
| 25 |
+
from typing import Optional, TYPE_CHECKING, TypeVar, Union
|
| 26 |
+
from typing_extensions import override, Self
|
| 27 |
+
|
| 28 |
+
import torch._dynamo.config
|
| 29 |
+
import torch._utils_internal
|
| 30 |
+
import torch.compiler.config
|
| 31 |
+
import torch.distributed as dist
|
| 32 |
+
from torch._dynamo.utils import (
|
| 33 |
+
CompileEventLogger,
|
| 34 |
+
dynamo_timed,
|
| 35 |
+
set_feature_use,
|
| 36 |
+
warn_once,
|
| 37 |
+
)
|
| 38 |
+
from torch._environment import is_fbcode
|
| 39 |
+
from torch._logging._internal import trace_structured_artifact
|
| 40 |
+
from torch.compiler._cache import (
|
| 41 |
+
CacheArtifact,
|
| 42 |
+
CacheArtifactFactory,
|
| 43 |
+
CacheArtifactManager,
|
| 44 |
+
)
|
| 45 |
+
from torch.utils._ordered_set import OrderedSet
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if TYPE_CHECKING:
|
| 49 |
+
import types
|
| 50 |
+
|
| 51 |
+
from torch._dynamo.symbolic_convert import InstructionTranslator
|
| 52 |
+
from torch._inductor.remote_cache import JsonDataTy, RemoteCache
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ReservedWorkflowIdUserError(ValueError):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
log = logging.getLogger(__name__)
|
| 60 |
+
|
| 61 |
+
LOCK_TIMEOUT = 10
|
| 62 |
+
|
| 63 |
+
# How does in memory representation work? Concretely, this module is
|
| 64 |
+
# responsible for holding GLOBAL state representing the state it holds, no
|
| 65 |
+
# other copies permitted. So we retire frame_state entirely and store it
|
| 66 |
+
# here. This should be reset when Dynamo is reset. We never GC information
|
| 67 |
+
# (similar to how the filesystem doesn't get cleaned up except by tmp
|
| 68 |
+
# cleaner), so the expectation is the information is relatively cheap and we
|
| 69 |
+
# don't mind leaking it.
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# How exactly did we design the cache key? Here are some of the questions:
|
| 73 |
+
#
|
| 74 |
+
# - JOB_ID: Do we have a unique identifier for the "training run" (such that
|
| 75 |
+
# it stays the same if we're running the same code, and changes if we're
|
| 76 |
+
# running something different).
|
| 77 |
+
#
|
| 78 |
+
# - RANK: Are we sharing the cache across ranks, or does each rank get
|
| 79 |
+
# an individual cache?
|
| 80 |
+
#
|
| 81 |
+
# We choose to require job_id for PGO cache. This is to prevent
|
| 82 |
+
# situations where unrelated invocations of PyTorch unpredictably cause
|
| 83 |
+
# changes to each other's behavior. With a job_id, at least you know there
|
| 84 |
+
# is some "state" associated with it. (State dict might be another way to
|
| 85 |
+
# tell if a run is related or not.) You can opt-in to YOLO everything
|
| 86 |
+
# aliases everything by passing a shared job_id for all your invocations.
|
| 87 |
+
#
|
| 88 |
+
# We choose to NOT share PGO cache across ranks. With no RANK_SHARING, there
|
| 89 |
+
# is never contention between runs, so we can leisurely update a bundle with
|
| 90 |
+
# information we need. Because we are grouped by job_id, we can have a single
|
| 91 |
+
# consolidated bundle for everything (or not; maybe worry about O(n^2) IO if
|
| 92 |
+
# we updated every compile--let's just instrument this.) Can even take a
|
| 93 |
+
# filelock for extra safety (expect no contention); expect 50ns overhead from
|
| 94 |
+
# uncontended filelock.
|
| 95 |
+
#
|
| 96 |
+
# If we did share ranks, everyone is storming to modify the same cache files.
|
| 97 |
+
# We can do this by having folks atomic write to a CAS-store and then having
|
| 98 |
+
# readers do on-the-fly merging (this can be implemented in remote using
|
| 99 |
+
# prefix iteration). As an optional optimization, one rank can be elected to
|
| 100 |
+
# handling bundling post facto (ideally, this is done async, after quiescence,
|
| 101 |
+
# without compiler collective need to wait for everyone to finish writing
|
| 102 |
+
# their bits.) Not sure how you can avoid a listdir because if some rank shows
|
| 103 |
+
# up with some new entries we need to pull them in ASAP (unless you want to
|
| 104 |
+
# delay bundling).
|
| 105 |
+
#
|
| 106 |
+
# But compiler collectives fill a similar niche: compilers chat with each
|
| 107 |
+
# other so rank 0 has collected everything. So elect rank 0 only to write the
|
| 108 |
+
# bundle. Don't even need CAS-store atomic write; just one rank writing an
|
| 109 |
+
# updating bundles. The point is that use compiler collectives to share
|
| 110 |
+
# profiles across ranks, but use the PGO cache to persist profiles per rank
|
| 111 |
+
# across attempts. No need to have one mechanism to do everything.
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@functools.cache
|
| 115 |
+
def _hash_containing_file(filepath: str) -> str:
|
| 116 |
+
# if the file does not exists we consider filepath to be the hash.
|
| 117 |
+
if not os.path.exists(filepath):
|
| 118 |
+
return filepath
|
| 119 |
+
|
| 120 |
+
with open(filepath, "rb") as file:
|
| 121 |
+
content = file.read()
|
| 122 |
+
crc32_value = zlib.crc32(content)
|
| 123 |
+
hash = format(crc32_value & 0xFFFFFFFF, "08x")
|
| 124 |
+
return hash
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclasses.dataclass(frozen=True)
|
| 128 |
+
class CodeId:
|
| 129 |
+
filename: str
|
| 130 |
+
firstlineno: int
|
| 131 |
+
name: str
|
| 132 |
+
# When a job restart, the code can be copied to a different path than the previous attempt. In that case
|
| 133 |
+
# self.filename will have a different value, we do not want to consider those differences. Instead we
|
| 134 |
+
# hash the content of the file and use it as an identifier of the file.
|
| 135 |
+
#
|
| 136 |
+
# self.filename is kept in the object to give readable information/pointer to the actual file, in a local
|
| 137 |
+
# code state it will refer to the first seen file path.
|
| 138 |
+
file_hash: str
|
| 139 |
+
|
| 140 |
+
# Exclude file name.
|
| 141 |
+
def __eq__(self, other: object) -> bool:
|
| 142 |
+
if not isinstance(other, CodeId):
|
| 143 |
+
return False
|
| 144 |
+
return (
|
| 145 |
+
self.file_hash == other.file_hash
|
| 146 |
+
and self.firstlineno == other.firstlineno
|
| 147 |
+
and self.name == other.name
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Ensure if two CodeIds are the same, then they have the same hash by excluding filename.
|
| 151 |
+
def __hash__(self) -> int:
|
| 152 |
+
return hash((self.file_hash, self.name, self.firstlineno))
|
| 153 |
+
|
| 154 |
+
def __str__(self) -> str:
|
| 155 |
+
return f"hash({self.file_hash}){self.filename}:{self.firstlineno}:{self.name}"
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def make(code: types.CodeType) -> CodeId:
|
| 159 |
+
return CodeId(
|
| 160 |
+
code.co_filename,
|
| 161 |
+
code.co_firstlineno,
|
| 162 |
+
code.co_name,
|
| 163 |
+
_hash_containing_file(code.co_filename),
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dataclasses.dataclass
|
| 168 |
+
class CodeState:
|
| 169 |
+
automatic_dynamic: defaultdict[str, FrameStateSizeEntry] = dataclasses.field(
|
| 170 |
+
# pyrefly: ignore [unbound-name]
|
| 171 |
+
default_factory=lambda: defaultdict(FrameStateSizeEntry)
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
_INIT_CODE_STATE: Optional[defaultdict[CodeId, CodeState]] = None
|
| 176 |
+
_CODE_STATE: Optional[defaultdict[CodeId, CodeState]] = None
|
| 177 |
+
_LOGGED_DYNAMIC_ALLOWLIST: bool = False
|
| 178 |
+
_KNOWN_DYNAMIC_SOURCES: set[str] = set()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@dataclasses.dataclass(frozen=True)
|
| 182 |
+
class InferStride:
|
| 183 |
+
"""
|
| 184 |
+
Denotes the quantity stride[dim] * size[dim], which is what the stride would
|
| 185 |
+
be for the next physical dimension that results in a contiguous layout.
|
| 186 |
+
|
| 187 |
+
For example, given size = [2, 3], stride = [3, 1], we can replace this with
|
| 188 |
+
stride = [InferStride(1), 1], because InferStride(1) = stride[1] * size[1] = 1 * 3 = 3
|
| 189 |
+
|
| 190 |
+
Indirecting the representation in this way is important for the join operation
|
| 191 |
+
on strides as if we join [2, 3][3, 1] and [2, 4][4, 1],
|
| 192 |
+
we don't want [2, None][None, 1] which would get eventually symbolized into
|
| 193 |
+
[2, s0][s1, 1] (notice that the relationship between s0 and s1 is broken).
|
| 194 |
+
If we instead rewrite the expressions as InferStride so we have [2, 3][InferStride(1), 1]
|
| 195 |
+
and [2, 4][InferStride(1), 1] we now join to [2, None][InferStride(1), 1] will
|
| 196 |
+
result in [2, s0][s0, 1], as desired.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
dim: int
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
_T = TypeVar("_T")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class AutoUnset(enum.Enum):
|
| 206 |
+
"""
|
| 207 |
+
The identity element of our semilattice, a generic "don't know" element that
|
| 208 |
+
is always subsumed when we get more information.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
token = 0
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
auto_unset = AutoUnset.token
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class AutoDynamic(enum.Enum):
|
| 218 |
+
"""
|
| 219 |
+
The top element of our (bounded) semilattice, whenever you merge this with
|
| 220 |
+
any other element you always get it again
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
token = 0
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
auto_dynamic = AutoDynamic.token
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@dataclasses.dataclass
|
| 230 |
+
class FrameStateSizeEntry:
|
| 231 |
+
scalar: Union[int, AutoDynamic, AutoUnset] = dataclasses.field(default=auto_unset)
|
| 232 |
+
# NB: We don't have cases where we have a known dimensionality but
|
| 233 |
+
# we know NOTHING about the individual sizes
|
| 234 |
+
size: Union[AutoDynamic, AutoUnset, tuple[Union[int, AutoDynamic], ...]] = (
|
| 235 |
+
dataclasses.field(default=auto_unset)
|
| 236 |
+
)
|
| 237 |
+
stride: Union[
|
| 238 |
+
AutoDynamic, AutoUnset, tuple[Union[int, AutoDynamic, InferStride], ...]
|
| 239 |
+
] = dataclasses.field(default=auto_unset)
|
| 240 |
+
|
| 241 |
+
def render(self) -> str:
|
| 242 |
+
# Special cases
|
| 243 |
+
def render_single(s: Union[int, AutoDynamic, AutoUnset, InferStride]) -> str:
|
| 244 |
+
if s is auto_dynamic:
|
| 245 |
+
return "?"
|
| 246 |
+
elif s is auto_unset:
|
| 247 |
+
# This basically shouldn't happen, this is for debugging
|
| 248 |
+
return "auto unset"
|
| 249 |
+
elif isinstance(s, InferStride):
|
| 250 |
+
return f"S({s.dim})"
|
| 251 |
+
else:
|
| 252 |
+
return str(s)
|
| 253 |
+
|
| 254 |
+
def render_tuple(ss: tuple[Union[int, AutoDynamic, InferStride], ...]) -> str:
|
| 255 |
+
return "[" + ", ".join(render_single(s) for s in ss) + "]"
|
| 256 |
+
|
| 257 |
+
# Common cases
|
| 258 |
+
if self.size is auto_dynamic and self.stride is auto_dynamic:
|
| 259 |
+
if self.scalar is auto_dynamic:
|
| 260 |
+
return "fully dynamic scalar or tensor"
|
| 261 |
+
else:
|
| 262 |
+
return f"scalar {self.scalar}"
|
| 263 |
+
elif self.scalar is auto_dynamic:
|
| 264 |
+
if isinstance(self.size, tuple) and isinstance(self.stride, tuple):
|
| 265 |
+
return f"tensor size={render_tuple(self.size)} stride={render_tuple(self.stride)}"
|
| 266 |
+
|
| 267 |
+
# Fallback
|
| 268 |
+
return f"unusual {repr(self)}"
|
| 269 |
+
|
| 270 |
+
def __post_init__(self) -> None:
|
| 271 |
+
assert not isinstance(self.scalar, torch.SymInt), self.scalar
|
| 272 |
+
if isinstance(self.size, tuple):
|
| 273 |
+
for s in self.size:
|
| 274 |
+
assert not isinstance(s, torch.SymInt), s
|
| 275 |
+
if isinstance(self.stride, tuple):
|
| 276 |
+
for s1 in self.stride:
|
| 277 |
+
assert not isinstance(s1, torch.SymInt), s1
|
| 278 |
+
|
| 279 |
+
def is_size_dynamic(self, dim: int) -> bool:
|
| 280 |
+
if self.size is auto_dynamic:
|
| 281 |
+
return True
|
| 282 |
+
if self.size is auto_unset:
|
| 283 |
+
return False
|
| 284 |
+
return self.size[dim] is auto_dynamic
|
| 285 |
+
|
| 286 |
+
def is_stride_dynamic(self, dim: int) -> bool:
|
| 287 |
+
# At the moment, dynamic strides is a bit buggy. Good test case
|
| 288 |
+
# here is `PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py
|
| 289 |
+
# TestAutograd.test_gradcheck_jacobian_mismatch`
|
| 290 |
+
#
|
| 291 |
+
# This if statement preserves historical behavior, which is that we
|
| 292 |
+
# ONLY make strides dynamic if the size is exactly static everywhere.
|
| 293 |
+
# We could potentially relax this but in general we should be very
|
| 294 |
+
# careful about when to infer dynamic strides.
|
| 295 |
+
#
|
| 296 |
+
# Actually, the existing algorithm is already somewhat problematic.
|
| 297 |
+
# Suppose a tensor that is sometimes:
|
| 298 |
+
# f32[2, 3, 5][15, 5, 1] and other times
|
| 299 |
+
# f32[2, 3, 5][5, 10, 1] (specifically, dim 0 and 1 are physically transposed).
|
| 300 |
+
# If we infer strides should be (DYNAMIC, DYNAMIC, 1). But this is
|
| 301 |
+
# silly: we really should have just guarded on dim order.
|
| 302 |
+
if not (
|
| 303 |
+
isinstance(self.size, tuple) and all(type(s) is int for s in self.size)
|
| 304 |
+
):
|
| 305 |
+
return False
|
| 306 |
+
if self.stride is auto_dynamic:
|
| 307 |
+
return True
|
| 308 |
+
if self.stride is auto_unset:
|
| 309 |
+
return False
|
| 310 |
+
return self.stride[dim] is auto_dynamic
|
| 311 |
+
|
| 312 |
+
@staticmethod
|
| 313 |
+
def _munge_symint(xs: tuple[int, ...]) -> tuple[Union[AutoDynamic, int], ...]:
|
| 314 |
+
return tuple(auto_dynamic if isinstance(x, torch.SymInt) else x for x in xs)
|
| 315 |
+
|
| 316 |
+
@classmethod
|
| 317 |
+
def make_scalar(cls, x: int) -> FrameStateSizeEntry:
|
| 318 |
+
return FrameStateSizeEntry(scalar=x, size=auto_dynamic, stride=auto_dynamic)
|
| 319 |
+
|
| 320 |
+
@classmethod
|
| 321 |
+
def make_tensor(
|
| 322 |
+
cls, size: tuple[int, ...], stride: tuple[int, ...]
|
| 323 |
+
) -> FrameStateSizeEntry:
|
| 324 |
+
return FrameStateSizeEntry(
|
| 325 |
+
scalar=auto_dynamic,
|
| 326 |
+
size=cls._munge_symint(size),
|
| 327 |
+
stride=cls._munge_symint(stride),
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
@classmethod
|
| 331 |
+
def make_size(cls, size: tuple[int, ...]) -> FrameStateSizeEntry:
|
| 332 |
+
return FrameStateSizeEntry(
|
| 333 |
+
scalar=auto_unset,
|
| 334 |
+
size=cls._munge_symint(size),
|
| 335 |
+
stride=auto_unset,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
@staticmethod
|
| 339 |
+
def _merge_atom(x: _T, y: _T) -> Union[AutoDynamic, _T]:
|
| 340 |
+
if x is auto_unset:
|
| 341 |
+
return y
|
| 342 |
+
if y is auto_unset:
|
| 343 |
+
return x
|
| 344 |
+
if x is auto_dynamic or y is auto_dynamic or x != y:
|
| 345 |
+
return auto_dynamic
|
| 346 |
+
return x
|
| 347 |
+
|
| 348 |
+
@classmethod
|
| 349 |
+
def _merge_atom_tup(
|
| 350 |
+
cls,
|
| 351 |
+
xs: Union[AutoDynamic, AutoUnset, tuple[_T, ...]],
|
| 352 |
+
ys: Union[AutoDynamic, AutoUnset, tuple[_T, ...]],
|
| 353 |
+
) -> Union[AutoDynamic, AutoUnset, tuple[Union[AutoDynamic, _T], ...]]:
|
| 354 |
+
if xs is auto_unset:
|
| 355 |
+
return ys
|
| 356 |
+
if ys is auto_unset:
|
| 357 |
+
return xs
|
| 358 |
+
if xs is auto_dynamic or ys is auto_dynamic:
|
| 359 |
+
return auto_dynamic
|
| 360 |
+
if len(xs) != len(ys):
|
| 361 |
+
return auto_dynamic
|
| 362 |
+
return tuple(cls._merge_atom(x, y) for x, y in zip(xs, ys))
|
| 363 |
+
|
| 364 |
+
def __ior__(self, other: Self) -> Self:
|
| 365 |
+
self.scalar = self._merge_atom(self.scalar, other.scalar)
|
| 366 |
+
self.size = self._merge_atom_tup(self.size, other.size)
|
| 367 |
+
self.stride = self._merge_atom_tup(self.stride, other.stride)
|
| 368 |
+
return self
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def update_automatic_dynamic(
|
| 372 |
+
tx: InstructionTranslator,
|
| 373 |
+
name: str,
|
| 374 |
+
entry: FrameStateSizeEntry,
|
| 375 |
+
*,
|
| 376 |
+
is_unspecialized_nn_module: bool = False,
|
| 377 |
+
) -> FrameStateSizeEntry:
|
| 378 |
+
code_id = CodeId.make(tx.f_code)
|
| 379 |
+
frame_state = get_code_state()[code_id]
|
| 380 |
+
if torch._dynamo.config.automatic_dynamic_shapes:
|
| 381 |
+
is_update = name in frame_state.automatic_dynamic
|
| 382 |
+
mut_entry = frame_state.automatic_dynamic[name]
|
| 383 |
+
old_entry = copy.copy(mut_entry)
|
| 384 |
+
mut_entry |= entry
|
| 385 |
+
|
| 386 |
+
# Do some logs (damn, I spend more code logging than I do actually doing
|
| 387 |
+
# the updates lol)
|
| 388 |
+
if is_update and old_entry.scalar != mut_entry.scalar:
|
| 389 |
+
log.debug(
|
| 390 |
+
"automatic dynamic int %s val %s != %s",
|
| 391 |
+
name,
|
| 392 |
+
entry.scalar,
|
| 393 |
+
old_entry.scalar,
|
| 394 |
+
)
|
| 395 |
+
CompileEventLogger.instant(
|
| 396 |
+
"automatic_dynamic",
|
| 397 |
+
{
|
| 398 |
+
"name": name,
|
| 399 |
+
"dim_changed": "scalar",
|
| 400 |
+
"reason": "scalar change",
|
| 401 |
+
"cached": str(old_entry.scalar),
|
| 402 |
+
"new": str(entry.scalar),
|
| 403 |
+
},
|
| 404 |
+
)
|
| 405 |
+
if is_unspecialized_nn_module:
|
| 406 |
+
log.info(
|
| 407 |
+
"%s is converted to a symbolic integer. It is an attribute of a "
|
| 408 |
+
"user defined nn module class. If you wish to keep it static, you can "
|
| 409 |
+
"mark the nn module class as `torch._dynamo.mark_static`.",
|
| 410 |
+
name,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
def log_tup(
|
| 414 |
+
tup_name: str, short_reason: str, long_reason: str, i: Optional[int] = None
|
| 415 |
+
) -> None:
|
| 416 |
+
entry_tup = (
|
| 417 |
+
getattr(entry, tup_name) if i is None else getattr(entry, tup_name)[i]
|
| 418 |
+
)
|
| 419 |
+
old_entry_tup = (
|
| 420 |
+
getattr(old_entry, tup_name)
|
| 421 |
+
if i is None
|
| 422 |
+
else getattr(old_entry, tup_name)[i]
|
| 423 |
+
)
|
| 424 |
+
log.debug(
|
| 425 |
+
"automatic dynamic %s %s %s %s != %s",
|
| 426 |
+
tup_name,
|
| 427 |
+
name,
|
| 428 |
+
short_reason,
|
| 429 |
+
# NB: We used to only report len(...) here for dim mismatch
|
| 430 |
+
entry_tup,
|
| 431 |
+
old_entry_tup,
|
| 432 |
+
)
|
| 433 |
+
CompileEventLogger.instant(
|
| 434 |
+
"automatic_dynamic",
|
| 435 |
+
{
|
| 436 |
+
"name": name,
|
| 437 |
+
"dim_changed": "all" if i is None else i,
|
| 438 |
+
"reason": long_reason,
|
| 439 |
+
"cached": str(old_entry_tup),
|
| 440 |
+
"new": str(entry_tup),
|
| 441 |
+
},
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
if is_update and old_entry.size != mut_entry.size:
|
| 445 |
+
if isinstance(old_entry.size, tuple) and isinstance(entry.size, tuple):
|
| 446 |
+
if len(old_entry.size) != len(entry.size):
|
| 447 |
+
log_tup("size", "dim", "dimensionality change")
|
| 448 |
+
else:
|
| 449 |
+
for i in range(len(entry.size)):
|
| 450 |
+
if old_entry.size[i] != entry.size[i]:
|
| 451 |
+
log_tup("size", f"size({i})", "size change", i)
|
| 452 |
+
else:
|
| 453 |
+
log_tup("size", "other", "other")
|
| 454 |
+
|
| 455 |
+
if is_update and old_entry.stride != mut_entry.stride:
|
| 456 |
+
if isinstance(old_entry.stride, tuple) and isinstance(entry.stride, tuple):
|
| 457 |
+
if len(old_entry.stride) != len(entry.stride):
|
| 458 |
+
log_tup("stride", "dim", "dimensionality change")
|
| 459 |
+
else:
|
| 460 |
+
for i in range(len(entry.stride)):
|
| 461 |
+
if old_entry.stride[i] != entry.stride[i]:
|
| 462 |
+
log_tup("stride", f"stride({i})", "stride change", i)
|
| 463 |
+
else:
|
| 464 |
+
log_tup("stride", "other", "other")
|
| 465 |
+
else:
|
| 466 |
+
old_entry = frame_state.automatic_dynamic[name]
|
| 467 |
+
log.debug(
|
| 468 |
+
"automatic dynamic is off, overwriting int %s val %s -> %s",
|
| 469 |
+
name,
|
| 470 |
+
old_entry.scalar,
|
| 471 |
+
entry.scalar,
|
| 472 |
+
)
|
| 473 |
+
frame_state.automatic_dynamic[name] = entry
|
| 474 |
+
mut_entry = entry
|
| 475 |
+
|
| 476 |
+
return mut_entry
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def process_automatic_dynamic(
|
| 480 |
+
tx: InstructionTranslator,
|
| 481 |
+
name: str,
|
| 482 |
+
entry: FrameStateSizeEntry,
|
| 483 |
+
*,
|
| 484 |
+
is_unspecialized_nn_module: bool = False,
|
| 485 |
+
) -> FrameStateSizeEntry:
|
| 486 |
+
if (st := tx.distributed_state) is None:
|
| 487 |
+
return update_automatic_dynamic(
|
| 488 |
+
tx,
|
| 489 |
+
name,
|
| 490 |
+
entry,
|
| 491 |
+
is_unspecialized_nn_module=is_unspecialized_nn_module,
|
| 492 |
+
)
|
| 493 |
+
elif st.all_states is None:
|
| 494 |
+
# Preflight, always pretend as if it's static. The point here
|
| 495 |
+
# is we want to get through the preflight quickly, and static
|
| 496 |
+
# will run faster. The preexisting frame state will get
|
| 497 |
+
# applied anyway after we do compiler collectives.
|
| 498 |
+
# TODO: I'm not sure if we should just bong the entire pgo
|
| 499 |
+
# state here, it kind of depends if we're going to have other
|
| 500 |
+
# things that talk in compiler collective. Also, the PGO
|
| 501 |
+
# state, if we've already inferred something is automatic
|
| 502 |
+
# dynamic, will have lost the actual input sizes, which might
|
| 503 |
+
# be useful for debugging purposes (e.g., observing 0/1
|
| 504 |
+
# specialization). Bonging the entire PGO state here would
|
| 505 |
+
# let us delete this logic here; the compiler collective
|
| 506 |
+
# would just directly update_automatic_dynamic
|
| 507 |
+
st.local_state.automatic_dynamic[name] = entry
|
| 508 |
+
return entry
|
| 509 |
+
else:
|
| 510 |
+
# Apply the updates. NB: all_states includes the local state
|
| 511 |
+
# too.
|
| 512 |
+
res = None
|
| 513 |
+
for sub_state in st.all_states:
|
| 514 |
+
if name in sub_state.automatic_dynamic:
|
| 515 |
+
res = update_automatic_dynamic(
|
| 516 |
+
tx,
|
| 517 |
+
name,
|
| 518 |
+
sub_state.automatic_dynamic[name],
|
| 519 |
+
is_unspecialized_nn_module=is_unspecialized_nn_module,
|
| 520 |
+
)
|
| 521 |
+
assert res is not None
|
| 522 |
+
return res
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def format_cache_key(key: str) -> str:
|
| 526 |
+
# NB: We always use global rank for keys, even though they are overkill
|
| 527 |
+
# for local only cache
|
| 528 |
+
rank = None
|
| 529 |
+
if dist.is_available() and dist.is_initialized():
|
| 530 |
+
rank = dist.get_rank()
|
| 531 |
+
|
| 532 |
+
tag = torch.compiler.config.cache_key_tag
|
| 533 |
+
return f"{key}:{rank}:{tag}"
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def get_cache_key() -> Optional[str]:
|
| 537 |
+
# TODO: info versions of these logs that log only once
|
| 538 |
+
if torch.compiler.config.force_disable_caches:
|
| 539 |
+
warn_once(
|
| 540 |
+
"dynamo_pgo force disabled by torch.compiler.config.force_disable_caches"
|
| 541 |
+
)
|
| 542 |
+
return None
|
| 543 |
+
|
| 544 |
+
# NB: We namespace the cache keys so that only user-specified job id
|
| 545 |
+
# can alias with each other.
|
| 546 |
+
if (r := torch.compiler.config.job_id) is not None:
|
| 547 |
+
if r.startswith("mast:"):
|
| 548 |
+
raise ReservedWorkflowIdUserError(
|
| 549 |
+
"torch.compiler.config.job_id with prefix 'mast:' is reserved for "
|
| 550 |
+
"automatically generated job id associated with a specific MAST job "
|
| 551 |
+
"name and version."
|
| 552 |
+
)
|
| 553 |
+
return format_cache_key(r)
|
| 554 |
+
|
| 555 |
+
if (name_version := torch._utils_internal.get_mast_job_name_version()) is not None:
|
| 556 |
+
mast_job_name, mast_job_version = name_version
|
| 557 |
+
return format_cache_key(f"mast:{mast_job_name}:{mast_job_version}")
|
| 558 |
+
|
| 559 |
+
return None
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def get_extra_cache_key(sticky_key: str) -> Optional[str]:
|
| 563 |
+
if torch.compiler.config.force_disable_caches:
|
| 564 |
+
warn_once(
|
| 565 |
+
"dynamo_pgo force disabled by torch.compiler.config.force_disable_caches"
|
| 566 |
+
)
|
| 567 |
+
return None
|
| 568 |
+
|
| 569 |
+
return format_cache_key(sticky_key)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# This solely controls local PGO
|
| 573 |
+
def code_state_path(cache_key: str) -> Optional[str]:
|
| 574 |
+
if not torch._dynamo.config.automatic_dynamic_local_pgo:
|
| 575 |
+
log.debug("automatic_dynamic_local_pgo not enabled")
|
| 576 |
+
return None
|
| 577 |
+
|
| 578 |
+
from torch._inductor.runtime.runtime_utils import cache_dir
|
| 579 |
+
|
| 580 |
+
code_state_key = re.sub(r'[<>:"/\\|?*]', "_", f"code_state_{cache_key}.pkl")
|
| 581 |
+
return os.path.join(cache_dir(), "dynamo", code_state_key)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def should_use_remote_dynamo_pgo_cache() -> bool:
|
| 585 |
+
if torch.compiler.config.force_disable_caches:
|
| 586 |
+
return False
|
| 587 |
+
|
| 588 |
+
if (r := torch._dynamo.config.automatic_dynamic_remote_pgo) is not None:
|
| 589 |
+
return r
|
| 590 |
+
|
| 591 |
+
if not is_fbcode():
|
| 592 |
+
return False
|
| 593 |
+
|
| 594 |
+
if torch._utils_internal.is_fb_unit_test():
|
| 595 |
+
return False
|
| 596 |
+
|
| 597 |
+
try:
|
| 598 |
+
from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
|
| 599 |
+
except ModuleNotFoundError:
|
| 600 |
+
return False
|
| 601 |
+
|
| 602 |
+
return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(
|
| 603 |
+
"pytorch/remote_cache:dynamo_pgo_version"
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def get_remote_cache() -> Optional[RemoteCache[JsonDataTy]]:
|
| 608 |
+
from torch._inductor.remote_cache import create_cache
|
| 609 |
+
|
| 610 |
+
if not should_use_remote_dynamo_pgo_cache():
|
| 611 |
+
return None
|
| 612 |
+
|
| 613 |
+
return create_cache(
|
| 614 |
+
"dynamo-pgo",
|
| 615 |
+
is_fbcode(),
|
| 616 |
+
"FbRemoteDynamoPGOCache",
|
| 617 |
+
"RemoteDynamoPGOCache",
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def _collect_dynamic_sources(code_state: CodeState) -> OrderedSet[str]:
|
| 622 |
+
dynamic_sources: OrderedSet[str] = OrderedSet()
|
| 623 |
+
for src, fs in code_state.automatic_dynamic.items():
|
| 624 |
+
dynamic = False
|
| 625 |
+
if isinstance(fs.size, tuple):
|
| 626 |
+
dynamic = auto_dynamic in fs.size # type: ignore[operator]
|
| 627 |
+
elif fs.scalar == auto_dynamic:
|
| 628 |
+
dynamic = True
|
| 629 |
+
if dynamic:
|
| 630 |
+
dynamic_sources.add(src)
|
| 631 |
+
return dynamic_sources
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def _collect_missing_sources(all_sources: OrderedSet[str]) -> OrderedSet[str]:
|
| 635 |
+
from torch._dynamo.variables.builder import is_dynamic_source
|
| 636 |
+
|
| 637 |
+
global _KNOWN_DYNAMIC_SOURCES
|
| 638 |
+
missing_sources: OrderedSet[str] = OrderedSet()
|
| 639 |
+
for src in all_sources:
|
| 640 |
+
if src in _KNOWN_DYNAMIC_SOURCES:
|
| 641 |
+
continue
|
| 642 |
+
elif is_dynamic_source(src):
|
| 643 |
+
_KNOWN_DYNAMIC_SOURCES.add(src)
|
| 644 |
+
continue
|
| 645 |
+
missing_sources.add(src)
|
| 646 |
+
return missing_sources
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def log_frame_dynamic_whitelist(f_code: types.CodeType) -> None:
|
| 650 |
+
global _KNOWN_DYNAMIC_SOURCES
|
| 651 |
+
code_id = CodeId.make(f_code)
|
| 652 |
+
frame_state = get_code_state()[code_id]
|
| 653 |
+
all_dynamic_sources = _collect_dynamic_sources(frame_state)
|
| 654 |
+
frame_whitelist = ",".join(all_dynamic_sources)
|
| 655 |
+
missing_whitelist = ",".join(_collect_missing_sources(all_dynamic_sources))
|
| 656 |
+
if frame_whitelist:
|
| 657 |
+
with dynamo_timed(name := "pgo.dynamic_whitelist", log_pt2_compile_event=True):
|
| 658 |
+
CompileEventLogger.pt2_compile(
|
| 659 |
+
name,
|
| 660 |
+
recompile_dynamic_whitelist=frame_whitelist,
|
| 661 |
+
missing_dynamic_whitelist=missing_whitelist,
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _log_size_mismatch_recompile() -> None:
|
| 666 |
+
global _LOGGED_DYNAMIC_ALLOWLIST
|
| 667 |
+
if not _LOGGED_DYNAMIC_ALLOWLIST:
|
| 668 |
+
torch._utils_internal.add_mlhub_insight(
|
| 669 |
+
category="dynamic_shapes_analysis",
|
| 670 |
+
insight="Dynamic shape recompilation detected",
|
| 671 |
+
insight_description="PGO detected a recompilation due to dynamic shapes. \
|
| 672 |
+
Please follow the instruction from the action link to reduce \
|
| 673 |
+
recompilation overhead.",
|
| 674 |
+
)
|
| 675 |
+
# add mlhub insight only once per rank
|
| 676 |
+
_LOGGED_DYNAMIC_ALLOWLIST = True
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def render_code_state(cs: defaultdict[CodeId, CodeState]) -> str:
|
| 680 |
+
code_state_str = "\n".join(
|
| 681 |
+
f"{k}:\n"
|
| 682 |
+
+ "\n".join(
|
| 683 |
+
f" {src}: {fs.render()}" for src, fs in v.automatic_dynamic.items()
|
| 684 |
+
)
|
| 685 |
+
for k, v in cs.items()
|
| 686 |
+
)
|
| 687 |
+
dynamic_sources: OrderedSet[str] = OrderedSet()
|
| 688 |
+
for state in cs.values():
|
| 689 |
+
dynamic_sources.update(_collect_dynamic_sources(state))
|
| 690 |
+
if dynamic_sources:
|
| 691 |
+
code_state_str += (
|
| 692 |
+
"\n\nPGO detected a recompilation due to dynamic shapes. "
|
| 693 |
+
"To reduce shape recompilations by compiling dynamically to start, "
|
| 694 |
+
f'set environment variable TORCH_COMPILE_DYNAMIC_SOURCES="{",".join(dynamic_sources)}"'
|
| 695 |
+
)
|
| 696 |
+
return code_state_str
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
@CacheArtifactFactory.register
|
| 700 |
+
class PGOCacheArtifact(CacheArtifact):
|
| 701 |
+
@override
|
| 702 |
+
def populate_cache(self) -> None:
|
| 703 |
+
meta = write_local_impl(
|
| 704 |
+
self._rewrite_cache_key_for_mega_cache(self.key), self.content
|
| 705 |
+
)
|
| 706 |
+
assert meta is not None
|
| 707 |
+
|
| 708 |
+
@override
|
| 709 |
+
@staticmethod
|
| 710 |
+
def type() -> str:
|
| 711 |
+
return "pgo"
|
| 712 |
+
|
| 713 |
+
@staticmethod
|
| 714 |
+
def _rewrite_cache_key_for_mega_cache(original_key: str) -> str:
|
| 715 |
+
"""
|
| 716 |
+
The PGO cache artifact key for a MAST job contains the job name and the version.
|
| 717 |
+
When we want to use the cache artifact on a different MAST job, we need to
|
| 718 |
+
update the key to use the new MAST job's name and version.
|
| 719 |
+
"""
|
| 720 |
+
if not original_key.startswith("mast:"):
|
| 721 |
+
# if original_key is overridden, then dont change it
|
| 722 |
+
return original_key
|
| 723 |
+
if (new_key := get_cache_key()) is not None:
|
| 724 |
+
return new_key
|
| 725 |
+
return original_key
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def hit(key: str, ty: str) -> defaultdict[CodeId, CodeState]:
|
| 729 |
+
global _INIT_CODE_STATE
|
| 730 |
+
assert isinstance(_CODE_STATE, defaultdict)
|
| 731 |
+
log.info("get_code_state %s hit %s, %d entries", key, ty, len(_CODE_STATE))
|
| 732 |
+
trace_structured_artifact(
|
| 733 |
+
f"get_{ty}_code_state",
|
| 734 |
+
"string",
|
| 735 |
+
lambda: render_code_state(_CODE_STATE), # type: ignore[arg-type]
|
| 736 |
+
)
|
| 737 |
+
set_feature_use("pgo", True)
|
| 738 |
+
_INIT_CODE_STATE = copy.deepcopy(_CODE_STATE)
|
| 739 |
+
return _CODE_STATE
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def get_local_code_state(cache_key: str) -> Optional[defaultdict[CodeId, CodeState]]:
|
| 743 |
+
global _CODE_STATE
|
| 744 |
+
path = code_state_path(cache_key)
|
| 745 |
+
if path is not None and os.path.exists(path):
|
| 746 |
+
with dynamo_timed(
|
| 747 |
+
name := "pgo.get_local_code_state", log_pt2_compile_event=True
|
| 748 |
+
):
|
| 749 |
+
CompileEventLogger.pt2_compile(name, cache_key=cache_key)
|
| 750 |
+
# Read lock not necessary as we always write atomically write to
|
| 751 |
+
# the actual location
|
| 752 |
+
with open(path, "rb") as f:
|
| 753 |
+
try:
|
| 754 |
+
content = f.read()
|
| 755 |
+
_CODE_STATE = pickle.loads(content)
|
| 756 |
+
CompileEventLogger.pt2_compile(name, cache_size_bytes=f.tell())
|
| 757 |
+
except Exception:
|
| 758 |
+
log.warning(
|
| 759 |
+
"get_code_state failed while reading %s", path, exc_info=True
|
| 760 |
+
)
|
| 761 |
+
else:
|
| 762 |
+
CacheArtifactManager.record_artifact(
|
| 763 |
+
PGOCacheArtifact.type(), cache_key, content
|
| 764 |
+
)
|
| 765 |
+
return hit(path, "local")
|
| 766 |
+
return None
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def lookup_remote_cache_entry(
|
| 770 |
+
remote_cache: RemoteCache[JsonDataTy],
|
| 771 |
+
cache_key: str,
|
| 772 |
+
event_name: Optional[str] = None,
|
| 773 |
+
) -> Optional[defaultdict[CodeId, CodeState]]:
|
| 774 |
+
code_state = None
|
| 775 |
+
try:
|
| 776 |
+
cache_data = remote_cache.get(cache_key)
|
| 777 |
+
except Exception:
|
| 778 |
+
log.warning("get_code_state failed remote read on %s", cache_key, exc_info=True)
|
| 779 |
+
else:
|
| 780 |
+
if cache_data is not None:
|
| 781 |
+
try:
|
| 782 |
+
assert isinstance(cache_data, dict)
|
| 783 |
+
data = cache_data["data"]
|
| 784 |
+
assert isinstance(data, str)
|
| 785 |
+
payload = base64.b64decode(data)
|
| 786 |
+
if event_name is not None:
|
| 787 |
+
CompileEventLogger.pt2_compile(
|
| 788 |
+
event_name, cache_size_bytes=len(payload)
|
| 789 |
+
)
|
| 790 |
+
code_state = pickle.loads(payload)
|
| 791 |
+
except Exception:
|
| 792 |
+
log.warning(
|
| 793 |
+
"get_code_state failed parsing remote result on %s",
|
| 794 |
+
cache_key,
|
| 795 |
+
exc_info=True,
|
| 796 |
+
)
|
| 797 |
+
else:
|
| 798 |
+
CacheArtifactManager.record_artifact(
|
| 799 |
+
PGOCacheArtifact.type(), cache_key, payload
|
| 800 |
+
)
|
| 801 |
+
else:
|
| 802 |
+
log.info("get_code_state remote miss on %s", cache_key)
|
| 803 |
+
return code_state
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def get_remote_code_state(cache_key: str) -> Optional[defaultdict[CodeId, CodeState]]:
|
| 807 |
+
global _CODE_STATE
|
| 808 |
+
remote_cache = get_remote_cache()
|
| 809 |
+
if remote_cache is not None:
|
| 810 |
+
with dynamo_timed(
|
| 811 |
+
name := "pgo.get_remote_code_state",
|
| 812 |
+
log_pt2_compile_event=True,
|
| 813 |
+
dynamo_compile_column_us="pgo_get_remote_code_state_time_us",
|
| 814 |
+
):
|
| 815 |
+
CompileEventLogger.pt2_compile(name, cache_key=cache_key)
|
| 816 |
+
code_state = lookup_remote_cache_entry(remote_cache, cache_key, name)
|
| 817 |
+
if code_state is not None:
|
| 818 |
+
_CODE_STATE = code_state
|
| 819 |
+
return hit(cache_key, "remote")
|
| 820 |
+
return None
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def get_extra_remote_code_state(cache_key: str) -> None:
|
| 824 |
+
"""
|
| 825 |
+
Reads an additional PGO profile from the given cache key, and merges it with the default PGO profile.
|
| 826 |
+
"""
|
| 827 |
+
global _CODE_STATE
|
| 828 |
+
assert _CODE_STATE is not None
|
| 829 |
+
|
| 830 |
+
remote_cache = get_remote_cache()
|
| 831 |
+
if remote_cache is not None:
|
| 832 |
+
with dynamo_timed(
|
| 833 |
+
name := "pgo.get_extra_remote_code_state",
|
| 834 |
+
log_pt2_compile_event=True,
|
| 835 |
+
dynamo_compile_column_us="pgo_get_remote_code_state_time_us",
|
| 836 |
+
):
|
| 837 |
+
CompileEventLogger.pt2_compile(name, cache_key=cache_key)
|
| 838 |
+
code_state = lookup_remote_cache_entry(remote_cache, cache_key)
|
| 839 |
+
log.info(
|
| 840 |
+
"get_extra_code_state %s hit, %d entries",
|
| 841 |
+
cache_key,
|
| 842 |
+
len(code_state) if code_state is not None else 0,
|
| 843 |
+
)
|
| 844 |
+
if code_state is not None:
|
| 845 |
+
assert not _CODE_STATE
|
| 846 |
+
_CODE_STATE = code_state
|
| 847 |
+
# log to tlparse
|
| 848 |
+
trace_structured_artifact(
|
| 849 |
+
"get_extra_remote_code_state",
|
| 850 |
+
"string",
|
| 851 |
+
lambda: render_code_state(code_state),
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def get_code_state() -> defaultdict[CodeId, CodeState]:
|
| 856 |
+
global _CODE_STATE, _INIT_CODE_STATE
|
| 857 |
+
if _CODE_STATE is not None:
|
| 858 |
+
return _CODE_STATE
|
| 859 |
+
|
| 860 |
+
# Initialize it (even if we don't look up profile)
|
| 861 |
+
_CODE_STATE = defaultdict(CodeState)
|
| 862 |
+
|
| 863 |
+
cache_key = get_cache_key()
|
| 864 |
+
if cache_key is None:
|
| 865 |
+
return _CODE_STATE
|
| 866 |
+
|
| 867 |
+
# Attempt local
|
| 868 |
+
local_code_state = get_local_code_state(cache_key)
|
| 869 |
+
|
| 870 |
+
# Attempt remote
|
| 871 |
+
if local_code_state is None:
|
| 872 |
+
get_remote_code_state(cache_key)
|
| 873 |
+
|
| 874 |
+
# Attempt additional remote if neither local/default remote succeeded
|
| 875 |
+
if (
|
| 876 |
+
not _CODE_STATE
|
| 877 |
+
and (sticky_read := torch.compiler.config.pgo_extra_read_key) is not None
|
| 878 |
+
):
|
| 879 |
+
extra_read_key = get_extra_cache_key(sticky_read)
|
| 880 |
+
if extra_read_key is not None:
|
| 881 |
+
get_extra_remote_code_state(extra_read_key)
|
| 882 |
+
|
| 883 |
+
log.info("get_code_state using default")
|
| 884 |
+
|
| 885 |
+
assert _CODE_STATE is not None
|
| 886 |
+
return _CODE_STATE
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def put_code_state() -> None:
|
| 890 |
+
if _CODE_STATE is None:
|
| 891 |
+
log.info("put_code_state: never initialized, will not write")
|
| 892 |
+
return
|
| 893 |
+
|
| 894 |
+
if _CODE_STATE == _INIT_CODE_STATE:
|
| 895 |
+
log.info("put_code_state: no change, skipping")
|
| 896 |
+
return
|
| 897 |
+
|
| 898 |
+
cache_key = get_cache_key()
|
| 899 |
+
if cache_key is None:
|
| 900 |
+
log.info("put_code_state: no cache key, skipping")
|
| 901 |
+
return
|
| 902 |
+
|
| 903 |
+
put_local_code_state(cache_key)
|
| 904 |
+
put_remote_code_state(cache_key)
|
| 905 |
+
if (sticky_write := torch.compiler.config.pgo_extra_write_key) is not None:
|
| 906 |
+
extra_write_key = get_extra_cache_key(sticky_write)
|
| 907 |
+
if extra_write_key is not None:
|
| 908 |
+
put_remote_code_state(extra_write_key)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def write_local_impl(cache_key: str, pickled_code: bytes) -> Optional[tuple[str, int]]:
|
| 912 |
+
path = code_state_path(cache_key)
|
| 913 |
+
|
| 914 |
+
if path is None:
|
| 915 |
+
return None
|
| 916 |
+
|
| 917 |
+
# If the user isn't misusing our API, we should have exclusive access to
|
| 918 |
+
# this directory. But it's not too hard
|
| 919 |
+
|
| 920 |
+
tmp_path = path + ".tmp"
|
| 921 |
+
lock_path = path + ".lock"
|
| 922 |
+
# We /mostly/ don't need the lock but the tmp file could be clobbered
|
| 923 |
+
# TODO: use a safe tempfile create to eliminate lock
|
| 924 |
+
from torch.utils._filelock import FileLock
|
| 925 |
+
|
| 926 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 927 |
+
|
| 928 |
+
with FileLock(lock_path, timeout=LOCK_TIMEOUT):
|
| 929 |
+
with open(tmp_path, "wb") as f:
|
| 930 |
+
f.write(pickled_code)
|
| 931 |
+
size = f.tell()
|
| 932 |
+
os.replace(tmp_path, path)
|
| 933 |
+
return path, size
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def put_local_code_state(cache_key: str) -> None:
|
| 937 |
+
with dynamo_timed(name := "pgo.put_local_code_state", log_pt2_compile_event=True):
|
| 938 |
+
CompileEventLogger.pt2_compile(name, cache_key=cache_key)
|
| 939 |
+
assert _CODE_STATE is not None
|
| 940 |
+
|
| 941 |
+
pickled_code = pickle.dumps(_CODE_STATE)
|
| 942 |
+
|
| 943 |
+
CacheArtifactManager.record_artifact(
|
| 944 |
+
PGOCacheArtifact.type(), cache_key, pickled_code
|
| 945 |
+
)
|
| 946 |
+
|
| 947 |
+
meta = write_local_impl(cache_key, pickled_code)
|
| 948 |
+
if meta is None:
|
| 949 |
+
log.info("put_code_state: local cache disabled")
|
| 950 |
+
return
|
| 951 |
+
path, size = meta
|
| 952 |
+
|
| 953 |
+
CompileEventLogger.pt2_compile(name, cache_size_bytes=size)
|
| 954 |
+
log.info("put_code_state: wrote local %s, %d entries", path, len(_CODE_STATE))
|
| 955 |
+
trace_structured_artifact(
|
| 956 |
+
"put_local_code_state",
|
| 957 |
+
"string",
|
| 958 |
+
lambda: render_code_state(_CODE_STATE),
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def put_remote_code_state(cache_key: str, extra_code_state: bool = False) -> None:
|
| 963 |
+
event_name = (
|
| 964 |
+
"put_remote_code_state"
|
| 965 |
+
if not extra_code_state
|
| 966 |
+
else "put_extra_remote_code_state"
|
| 967 |
+
)
|
| 968 |
+
with dynamo_timed(
|
| 969 |
+
name := f"pgo.{event_name}",
|
| 970 |
+
log_pt2_compile_event=True,
|
| 971 |
+
dynamo_compile_column_us="pgo_put_remote_code_state_time_us",
|
| 972 |
+
):
|
| 973 |
+
CompileEventLogger.pt2_compile(name, cache_key=cache_key)
|
| 974 |
+
assert _CODE_STATE is not None
|
| 975 |
+
|
| 976 |
+
remote_cache = get_remote_cache()
|
| 977 |
+
|
| 978 |
+
if remote_cache is None:
|
| 979 |
+
log.info("%s: remote cache disabled", event_name)
|
| 980 |
+
return
|
| 981 |
+
|
| 982 |
+
content = pickle.dumps(_CODE_STATE)
|
| 983 |
+
CompileEventLogger.pt2_compile(name, cache_size_bytes=len(content))
|
| 984 |
+
cache_data: JsonDataTy = {
|
| 985 |
+
"data": base64.b64encode(content).decode("ascii"),
|
| 986 |
+
}
|
| 987 |
+
remote_cache.put(cache_key, cache_data)
|
| 988 |
+
log.info(
|
| 989 |
+
"%s: wrote remote %s, %d entries", event_name, cache_key, len(_CODE_STATE)
|
| 990 |
+
)
|
| 991 |
+
# TODO: don't log this multiple times
|
| 992 |
+
trace_structured_artifact(
|
| 993 |
+
event_name,
|
| 994 |
+
"string",
|
| 995 |
+
lambda: render_code_state(_CODE_STATE),
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
# NB: this does NOT reset the cached code state on disk
|
| 1000 |
+
def reset_code_state() -> None:
|
| 1001 |
+
global _CODE_STATE, _INIT_CODE_STATE, _LOGGED_DYNAMIC_ALLOWLIST
|
| 1002 |
+
_CODE_STATE = None
|
| 1003 |
+
_INIT_CODE_STATE = None
|
| 1004 |
+
_LOGGED_DYNAMIC_ALLOWLIST = False
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/__init__.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for common builtins.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# NOTE: 1. Please do not import any submodule in the directory here to avoid circular imports.
|
| 6 |
+
# 2. While adding a new polyfill module, also add it to POLYFILLED_MODULE_NAMES in loader.py.
|
| 7 |
+
# Add it in the TYPE_CHECKING block below as well.
|
| 8 |
+
|
| 9 |
+
# mypy: allow-untyped-defs
|
| 10 |
+
|
| 11 |
+
import types
|
| 12 |
+
from collections import OrderedDict
|
| 13 |
+
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
|
| 14 |
+
from itertools import repeat as _repeat
|
| 15 |
+
from operator import eq, ne
|
| 16 |
+
from typing import Any, TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from ..utils import dict_keys
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
# Load by torch._dynamo.polyfills.loader
|
| 25 |
+
# See also the POLYFILLED_MODULE_NAMES in torch/_dynamo/polyfills/loader.py
|
| 26 |
+
# Put the submodules here to avoid circular imports
|
| 27 |
+
from . import (
|
| 28 |
+
_collections as _collections,
|
| 29 |
+
builtins as builtins,
|
| 30 |
+
functools as functools,
|
| 31 |
+
itertools as itertools,
|
| 32 |
+
operator as operator,
|
| 33 |
+
os as os,
|
| 34 |
+
pytree as pytree,
|
| 35 |
+
struct as struct,
|
| 36 |
+
sys as sys,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from torch.overrides import BaseTorchFunctionMode
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# These classes handle support for TorchFunctionModes across
|
| 43 |
+
# graph breaks
|
| 44 |
+
# Today the TorchFunctionMode enter (for the classes we support)
|
| 45 |
+
# simply pushes the mode onto the stack. Since after this occurs
|
| 46 |
+
# the stack is mutated, and we replay these mutations, we don't need
|
| 47 |
+
# any cleanup logic to be run once the graph break occurs, we simply replay
|
| 48 |
+
# these mutations to ensure at the graph break the torch function mode stack is correct
|
| 49 |
+
# and reconstruct the torch function mode stack normally
|
| 50 |
+
# when we compile the resume function on the other side of the break.
|
| 51 |
+
# However, to ensure we exit properly
|
| 52 |
+
# in the resume function, we need to re-enter the contexts as we do other contexts.
|
| 53 |
+
# These contexts do nothing on enter, but provide the correct exit logic to ensure
|
| 54 |
+
# the stack state is correct.
|
| 55 |
+
class NoEnterTorchFunctionMode(BaseTorchFunctionMode):
|
| 56 |
+
def __enter__(self):
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def index(iterator, item, start=0, end=None):
|
| 61 |
+
from itertools import islice
|
| 62 |
+
|
| 63 |
+
for i, elem in islice(enumerate(iterator), start, end):
|
| 64 |
+
if item == elem:
|
| 65 |
+
return i
|
| 66 |
+
# This will not run in dynamo
|
| 67 |
+
raise ValueError(f"{item} is not in {type(iterator)}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def repeat(item, count):
|
| 71 |
+
for _ in range(count):
|
| 72 |
+
yield item
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def radians(x):
|
| 76 |
+
import math
|
| 77 |
+
|
| 78 |
+
return math.pi / 180.0 * x
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def impl_CONTAINS_OP_fallback(a, b):
|
| 82 |
+
# performs fallback "a in b"
|
| 83 |
+
if hasattr(b, "__iter__"):
|
| 84 |
+
# use __iter__ if __contains__ is not available
|
| 85 |
+
for x in b:
|
| 86 |
+
if x == a:
|
| 87 |
+
return True
|
| 88 |
+
return False
|
| 89 |
+
raise TypeError(f"argument of type {type(b)} is not iterable")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def accumulate_grad(x, new_grad):
|
| 93 |
+
# polyfills according to the Gradient Layout Contract
|
| 94 |
+
if new_grad is None:
|
| 95 |
+
return
|
| 96 |
+
new_grad_strided = torch.empty_like(x)
|
| 97 |
+
new_grad_strided.copy_(new_grad)
|
| 98 |
+
if x.grad is None:
|
| 99 |
+
x.grad = new_grad_strided
|
| 100 |
+
elif torch.is_grad_enabled():
|
| 101 |
+
x.grad = x.grad + new_grad_strided
|
| 102 |
+
else:
|
| 103 |
+
x.grad.add_(new_grad_strided)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# This mirrors
|
| 107 |
+
# https://github.com/python/cpython/blob/a1c52d1265c65bcf0d9edf87e143843ad54f9b8f/Objects/listobject.c#L3352-L3413
|
| 108 |
+
def list_cmp(op: Callable[[Any, Any], bool], left: Sequence[Any], right: Sequence[Any]):
|
| 109 |
+
"""emulate `(1,2,3) > (1,2)` etc"""
|
| 110 |
+
|
| 111 |
+
# Optimization: For equality, short-circuit if lengths differ
|
| 112 |
+
# This avoids iterating through elements and triggering guards on SymInts
|
| 113 |
+
left_len = len(left)
|
| 114 |
+
right_len = len(right)
|
| 115 |
+
|
| 116 |
+
if op is eq and left_len != right_len:
|
| 117 |
+
return False
|
| 118 |
+
if op is ne and left_len != right_len:
|
| 119 |
+
return True
|
| 120 |
+
|
| 121 |
+
# Apply `op` to the first pair that differ
|
| 122 |
+
for a, b in zip(left, right):
|
| 123 |
+
if a != b:
|
| 124 |
+
return op(a, b)
|
| 125 |
+
|
| 126 |
+
# No more pairs to compare, so compare sizes.
|
| 127 |
+
return op(left_len, right_len)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def dict___eq__(d, other):
|
| 131 |
+
if (len(d) != len(other)) or (d.keys() != other.keys()):
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
if all(isinstance(a, OrderedDict) for a in (d, other)):
|
| 135 |
+
return list(d.items()) == list(other.items())
|
| 136 |
+
|
| 137 |
+
for k, v in d.items():
|
| 138 |
+
if v != other[k]:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
return True
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def set_symmetric_difference(set1, set2):
|
| 145 |
+
symmetric_difference_set = set()
|
| 146 |
+
for x in set1:
|
| 147 |
+
if x not in set2:
|
| 148 |
+
symmetric_difference_set.add(x)
|
| 149 |
+
for x in set2:
|
| 150 |
+
if x not in set1:
|
| 151 |
+
symmetric_difference_set.add(x)
|
| 152 |
+
return symmetric_difference_set
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def set_symmetric_difference_update(set1, set2):
|
| 156 |
+
result = set1.symmetric_difference(set2)
|
| 157 |
+
set1.clear()
|
| 158 |
+
set1.update(result)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def set_isdisjoint(set1, set2):
|
| 162 |
+
if not isinstance(set2, Iterable):
|
| 163 |
+
raise TypeError(f"'{type(set2)}' object is not iterable")
|
| 164 |
+
|
| 165 |
+
for x in set1:
|
| 166 |
+
for y in set2:
|
| 167 |
+
if not isinstance(y, Hashable):
|
| 168 |
+
raise TypeError(f"unhashable type: '{type(y)}'")
|
| 169 |
+
if x == y:
|
| 170 |
+
return False
|
| 171 |
+
return True
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def set_intersection(set1, *others):
|
| 175 |
+
if len(others) == 0:
|
| 176 |
+
return set1.copy()
|
| 177 |
+
|
| 178 |
+
if not all(isinstance(s, Iterable) for s in others):
|
| 179 |
+
raise TypeError(f"set.difference expected an iterable, got {type(others)}")
|
| 180 |
+
|
| 181 |
+
for s in others:
|
| 182 |
+
if any(not isinstance(x, Hashable) for x in s):
|
| 183 |
+
raise TypeError("unhashable type")
|
| 184 |
+
|
| 185 |
+
# return a new set with elements common in all sets
|
| 186 |
+
intersection_set = set()
|
| 187 |
+
for x in set1:
|
| 188 |
+
for set2 in others:
|
| 189 |
+
if not any(x == y for y in set2):
|
| 190 |
+
break
|
| 191 |
+
else:
|
| 192 |
+
intersection_set.add(x)
|
| 193 |
+
return intersection_set
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def set_intersection_update(set1, *others):
|
| 197 |
+
result = set1.intersection(*others)
|
| 198 |
+
set1.clear()
|
| 199 |
+
set1.update(result)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def set_union(set1, *others):
|
| 203 |
+
# frozenset also uses this function
|
| 204 |
+
if len(others) == 0:
|
| 205 |
+
return set1.copy()
|
| 206 |
+
|
| 207 |
+
if not all(isinstance(s, Iterable) for s in others):
|
| 208 |
+
raise TypeError(f"set.union expected an iterable, got {type(others)}")
|
| 209 |
+
|
| 210 |
+
for s in others:
|
| 211 |
+
if any(not isinstance(x, Hashable) for x in s):
|
| 212 |
+
raise TypeError("unhashable type")
|
| 213 |
+
|
| 214 |
+
union_set = set(set1.copy())
|
| 215 |
+
for set2 in others:
|
| 216 |
+
set_update(union_set, set2)
|
| 217 |
+
|
| 218 |
+
# frozenset also uses this function
|
| 219 |
+
return type(set1)(union_set)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def set_update(set1, *others):
|
| 223 |
+
if len(others) == 0:
|
| 224 |
+
return set1
|
| 225 |
+
|
| 226 |
+
for set2 in others:
|
| 227 |
+
for x in set2:
|
| 228 |
+
if x not in set1:
|
| 229 |
+
set1.add(x)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def set_difference(set1, *others):
|
| 233 |
+
if len(others) == 0:
|
| 234 |
+
return set1.copy()
|
| 235 |
+
|
| 236 |
+
if not all(isinstance(s, Iterable) for s in others):
|
| 237 |
+
raise TypeError(f"set.difference expected an iterable, got {type(others)}")
|
| 238 |
+
|
| 239 |
+
for s in others:
|
| 240 |
+
if any(not isinstance(x, Hashable) for x in s):
|
| 241 |
+
raise TypeError("unhashable type")
|
| 242 |
+
|
| 243 |
+
difference_set = set()
|
| 244 |
+
for x in set1:
|
| 245 |
+
for set2 in others:
|
| 246 |
+
if x in set2:
|
| 247 |
+
break
|
| 248 |
+
else:
|
| 249 |
+
difference_set.add(x)
|
| 250 |
+
return difference_set
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def set_difference_update(set1, *others):
|
| 254 |
+
result = set1.difference(*others)
|
| 255 |
+
set1.clear()
|
| 256 |
+
set1.update(result)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def assert_dict_equal(self_, d1, d2, msg=None):
|
| 260 |
+
self_.assertTrue(d1 == d2, msg)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def assert_multi_line_equal(self_, first, second, msg=None):
|
| 264 |
+
return self_.assertTrue(first == second, msg)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# The original impl. uses difflib
|
| 268 |
+
def assert_sequence_equal(self_, seq1, seq2, msg=None, seq_type=None):
|
| 269 |
+
return self_.assertTrue(seq1 == seq2, msg)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def getattr_and_trace(*args, **kwargs):
|
| 273 |
+
wrapper_obj = args[0]
|
| 274 |
+
attr_name = args[1]
|
| 275 |
+
fn = getattr(wrapper_obj, attr_name)
|
| 276 |
+
return fn(*args[2:], **kwargs)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def mapping_get(obj, key, value=None, /):
|
| 280 |
+
try:
|
| 281 |
+
return obj.__getitem__(key)
|
| 282 |
+
except KeyError:
|
| 283 |
+
return value
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def instantiate_user_defined_class_object(cls, /, *args, **kwargs):
|
| 287 |
+
obj = cls.__new__(cls, *args, **kwargs)
|
| 288 |
+
|
| 289 |
+
# Only call __init__ if the object is an instance of the class
|
| 290 |
+
# Reference: https://github.com/python/cpython/blob/3.12/Objects/typeobject.c#L1670-L1673
|
| 291 |
+
if isinstance(obj, cls):
|
| 292 |
+
obj.__init__(*args, **kwargs)
|
| 293 |
+
return obj
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def mutable_mapping_update(self, data=(), /, **kwargs):
|
| 297 |
+
if isinstance(data, Mapping):
|
| 298 |
+
# Merge standard mapping with PyMapping_Items
|
| 299 |
+
for key, value in data.items():
|
| 300 |
+
self[key] = value
|
| 301 |
+
# FIXME: Enabling the `elif`-branch below needs too many `VariableClass.call_obj_hasattr` changes.
|
| 302 |
+
# >>> class Foo:
|
| 303 |
+
# ... def __init__(self):
|
| 304 |
+
# ... self.keys = lambda: ['a', 'b', 'c'] # not required to be a method
|
| 305 |
+
# ...
|
| 306 |
+
# ... def __getitem__(self, key):
|
| 307 |
+
# ... return 0
|
| 308 |
+
# ...
|
| 309 |
+
# >>> dict(Foo())
|
| 310 |
+
# {'a': 0, 'b': 0, 'c': 0}
|
| 311 |
+
#
|
| 312 |
+
# > This is a rare case, so we comment it out for now.
|
| 313 |
+
#
|
| 314 |
+
# elif hasattr(data, "keys"):
|
| 315 |
+
# # Merge mapping-like object with PyMapping_Keys + PyObject_GetItem
|
| 316 |
+
# for key in data.keys():
|
| 317 |
+
# self[key] = data[key]
|
| 318 |
+
else:
|
| 319 |
+
if not isinstance(data, Iterable):
|
| 320 |
+
raise TypeError(f"{type(data).__name__!r} object is not iterable")
|
| 321 |
+
# Likely a sequence of pairs
|
| 322 |
+
for key, value in data:
|
| 323 |
+
self[key] = value
|
| 324 |
+
|
| 325 |
+
if kwargs:
|
| 326 |
+
for key, value in kwargs.items():
|
| 327 |
+
self[key] = value
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# Used with something like dict(obj)
|
| 331 |
+
def construct_dict(cls, data=(), /, **kwargs):
|
| 332 |
+
self = cls.__new__(cls)
|
| 333 |
+
mutable_mapping_update(self, data, **kwargs)
|
| 334 |
+
return self
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def foreach_map_fn(*args):
|
| 338 |
+
op = args[0]
|
| 339 |
+
new_args: list[Any] = []
|
| 340 |
+
at_least_one_list = False
|
| 341 |
+
for arg in args[1:]:
|
| 342 |
+
if not isinstance(arg, (list, tuple)):
|
| 343 |
+
new_args.append(_repeat(arg))
|
| 344 |
+
else:
|
| 345 |
+
at_least_one_list = True
|
| 346 |
+
new_args.append(arg)
|
| 347 |
+
|
| 348 |
+
# Just apply op once to args if there are no lists
|
| 349 |
+
if not at_least_one_list:
|
| 350 |
+
return op(*args[1:])
|
| 351 |
+
|
| 352 |
+
out = []
|
| 353 |
+
for unpacked in zip(*new_args):
|
| 354 |
+
out.append(op(*unpacked))
|
| 355 |
+
|
| 356 |
+
return out
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def foreach_lerp_inplace(self, end, weight):
|
| 360 |
+
# decompose foreach lerp into constituent ops, prevents a graph break due to
|
| 361 |
+
# converting a value to a scalar when arg[2] is a single tensor
|
| 362 |
+
result = torch._foreach_sub(end, self)
|
| 363 |
+
result = torch._foreach_mul(result, weight)
|
| 364 |
+
return torch._foreach_add_(self, result)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def foreach_pow_scalar(scalar, exps):
|
| 368 |
+
return torch._foreach_pow([scalar for _ in exps], exps)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def addcmul_inplace(self, tensor1, tensor2, value):
|
| 372 |
+
return self.add_(tensor1 * tensor2 * value)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def predicate(obj: Any) -> bool:
|
| 376 |
+
# This will cause the rest of dynamo to handle the if statement correctly, so we don't have to rewrite it here.
|
| 377 |
+
# We can't just use bool() here since we can't trace into that in general.
|
| 378 |
+
if obj:
|
| 379 |
+
return True
|
| 380 |
+
return False
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def cmp_eq(a, b):
|
| 384 |
+
# Note that the commented `is` check should ideally be removed. This is a
|
| 385 |
+
# CPython optimization that skips the __eq__ checks it the obj id's are
|
| 386 |
+
# same. But, these lines adds many `is` nodes in the Fx graph for
|
| 387 |
+
# SymNodeVariable. For now, we can just skip this check. This is STILL
|
| 388 |
+
# correct because one of the __eq__ checks will pass later, just could be
|
| 389 |
+
# slow in some corner cases.
|
| 390 |
+
# if a is b:
|
| 391 |
+
# return True
|
| 392 |
+
result = a.__eq__(b)
|
| 393 |
+
if result is NotImplemented:
|
| 394 |
+
result = b.__eq__(a)
|
| 395 |
+
return result is not NotImplemented and result
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def cmp_ne(a, b):
|
| 399 |
+
# Check if __ne__ is overridden
|
| 400 |
+
if isinstance(type(a).__ne__, types.FunctionType):
|
| 401 |
+
return a.__ne__(b)
|
| 402 |
+
return not cmp_eq(a, b)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def cmp_lt(a, b):
|
| 406 |
+
result = a.__lt__(b)
|
| 407 |
+
if result is NotImplemented:
|
| 408 |
+
raise TypeError(f"{type(a)} does not support the < operator")
|
| 409 |
+
return result
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def cmp_le(a, b):
|
| 413 |
+
# Check if __le__ is overridden
|
| 414 |
+
if isinstance(type(a).__le__, types.FunctionType):
|
| 415 |
+
return a.__le__(b)
|
| 416 |
+
return cmp_eq(a, b) or cmp_lt(a, b)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def cmp_gt(a, b):
|
| 420 |
+
# Check if __gt__ is overridden
|
| 421 |
+
if isinstance(type(a).__gt__, types.FunctionType):
|
| 422 |
+
return a.__gt__(b)
|
| 423 |
+
# a > b is equivalent to b < a
|
| 424 |
+
return cmp_lt(b, a)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def cmp_ge(a, b):
|
| 428 |
+
# Check if __ge__ is overridden
|
| 429 |
+
if isinstance(type(a).__ge__, types.FunctionType):
|
| 430 |
+
return a.__ge__(b)
|
| 431 |
+
return cmp_eq(a, b) or cmp_gt(a, b)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/_collections.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for builtins
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections.abc import Iterable, MutableMapping
|
| 6 |
+
from typing import TypeVar
|
| 7 |
+
|
| 8 |
+
from ..decorators import substitute_in_graph
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = []
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
T = TypeVar("T")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import _collections # type: ignore[import-not-found]
|
| 19 |
+
|
| 20 |
+
@substitute_in_graph(_collections._count_elements)
|
| 21 |
+
def _count_elements(
|
| 22 |
+
mapping: MutableMapping[T, int],
|
| 23 |
+
iterable: Iterable[T],
|
| 24 |
+
) -> None:
|
| 25 |
+
"Tally elements from the iterable."
|
| 26 |
+
mapping_get = mapping.get
|
| 27 |
+
for elem in iterable:
|
| 28 |
+
mapping[elem] = mapping_get(elem, 0) + 1
|
| 29 |
+
|
| 30 |
+
__all__.append("_count_elements")
|
| 31 |
+
|
| 32 |
+
except ImportError:
|
| 33 |
+
pass
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/builtins.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for builtins
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import builtins
|
| 8 |
+
import functools
|
| 9 |
+
import operator
|
| 10 |
+
from collections.abc import Callable
|
| 11 |
+
from typing import TYPE_CHECKING, TypeVar
|
| 12 |
+
|
| 13 |
+
from ..decorators import substitute_in_graph
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from collections.abc import Iterable
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"all",
|
| 22 |
+
"any",
|
| 23 |
+
"enumerate",
|
| 24 |
+
"sum",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_T = TypeVar("_T")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@substitute_in_graph(builtins.all, can_constant_fold_through=True)
|
| 32 |
+
def all(iterable: Iterable[object], /) -> bool:
|
| 33 |
+
for elem in iterable:
|
| 34 |
+
if not elem:
|
| 35 |
+
return False
|
| 36 |
+
return True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@substitute_in_graph(builtins.any, can_constant_fold_through=True)
|
| 40 |
+
def any(iterable: Iterable[object], /) -> bool:
|
| 41 |
+
for elem in iterable:
|
| 42 |
+
if elem:
|
| 43 |
+
return True
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@substitute_in_graph(builtins.enumerate, is_embedded_type=True) # type: ignore[arg-type]
|
| 48 |
+
def enumerate(iterable: Iterable[_T], start: int = 0) -> Iterable[tuple[int, _T]]:
|
| 49 |
+
if not isinstance(start, int):
|
| 50 |
+
raise TypeError(
|
| 51 |
+
f"{type(start).__name__!r} object cannot be interpreted as an integer"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
for x in iterable:
|
| 55 |
+
yield start, x
|
| 56 |
+
start += 1
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@substitute_in_graph(builtins.sum, can_constant_fold_through=True) # type: ignore[arg-type]
|
| 60 |
+
def sum(iterable: Iterable[_T], /, start: _T = 0) -> _T: # type: ignore[assignment]
|
| 61 |
+
return functools.reduce(operator.add, iterable, start)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _CallableIterator:
|
| 65 |
+
def __init__(self, fn, sentinel): # type: ignore[no-untyped-def]
|
| 66 |
+
self.fn = fn
|
| 67 |
+
self.sentinel = sentinel
|
| 68 |
+
|
| 69 |
+
def __iter__(self): # type: ignore[no-untyped-def]
|
| 70 |
+
return self
|
| 71 |
+
|
| 72 |
+
def __next__(self): # type: ignore[no-untyped-def]
|
| 73 |
+
# The iterator created in this case will call object with no arguments
|
| 74 |
+
# for each call to its __next__() method;
|
| 75 |
+
r = self.fn()
|
| 76 |
+
|
| 77 |
+
# If the value returned is equal to sentinel, StopIteration will be raised
|
| 78 |
+
if r == self.sentinel:
|
| 79 |
+
raise StopIteration
|
| 80 |
+
|
| 81 |
+
# otherwise the value will be returned.
|
| 82 |
+
return r
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class _SENTINEL_MISSING:
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# TODO(guilhermeleobas): use substitute_in_graph for iter()
|
| 90 |
+
def iter_(fn_or_iterable, sentinel=_SENTINEL_MISSING, /): # type: ignore[no-untyped-def]
|
| 91 |
+
# Without a second argument, object must be a collection object which supports
|
| 92 |
+
# the iterable (__iter__) or the sequence protocol (__getitem__ with an integer
|
| 93 |
+
# starting at 0)
|
| 94 |
+
if sentinel is _SENTINEL_MISSING:
|
| 95 |
+
iterable = fn_or_iterable
|
| 96 |
+
if hasattr(iterable, "__iter__"):
|
| 97 |
+
iterator = iterable.__iter__()
|
| 98 |
+
if hasattr(iterator, "__next__"):
|
| 99 |
+
return iterator
|
| 100 |
+
else:
|
| 101 |
+
raise TypeError(f"'{type(iterator)}' object is not iterable")
|
| 102 |
+
if hasattr(iterable, "__getitem__"):
|
| 103 |
+
# Needs to be a new function to avoid iter becoming a generator
|
| 104 |
+
def sequence_protocol(iterable): # type: ignore[no-untyped-def]
|
| 105 |
+
i = 0
|
| 106 |
+
while True:
|
| 107 |
+
try:
|
| 108 |
+
yield iterable.__getitem__(i)
|
| 109 |
+
i += 1
|
| 110 |
+
except IndexError:
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
return sequence_protocol(iterable)
|
| 114 |
+
raise TypeError(f"'{type(iterable)}' object is not iterable")
|
| 115 |
+
else:
|
| 116 |
+
# If the second argument, sentinel, is given, then object must be a
|
| 117 |
+
# callable object.
|
| 118 |
+
fn = fn_or_iterable
|
| 119 |
+
|
| 120 |
+
if not isinstance(fn, Callable): # type: ignore[arg-type]
|
| 121 |
+
raise TypeError("iter(v, w): v must be a callable")
|
| 122 |
+
|
| 123 |
+
return _CallableIterator(fn, sentinel)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/functools.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for functools
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
from collections.abc import Callable, Iterable
|
| 7 |
+
from typing import TypeVar
|
| 8 |
+
|
| 9 |
+
from ..decorators import substitute_in_graph
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = ["reduce"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_T = TypeVar("_T")
|
| 16 |
+
_U = TypeVar("_U")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _INITIAL_MISSING:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# Reference: https://docs.python.org/3/library/functools.html#functools.reduce
|
| 24 |
+
@substitute_in_graph(functools.reduce)
|
| 25 |
+
def reduce(
|
| 26 |
+
function: Callable[[_U, _T], _U],
|
| 27 |
+
iterable: Iterable[_T],
|
| 28 |
+
initial: _U = _INITIAL_MISSING, # type: ignore[assignment]
|
| 29 |
+
/,
|
| 30 |
+
) -> _U:
|
| 31 |
+
it = iter(iterable)
|
| 32 |
+
|
| 33 |
+
value: _U
|
| 34 |
+
if initial is _INITIAL_MISSING:
|
| 35 |
+
try:
|
| 36 |
+
value = next(it) # type: ignore[assignment]
|
| 37 |
+
except StopIteration:
|
| 38 |
+
raise TypeError(
|
| 39 |
+
"reduce() of empty iterable with no initial value",
|
| 40 |
+
) from None
|
| 41 |
+
else:
|
| 42 |
+
value = initial
|
| 43 |
+
|
| 44 |
+
for element in it:
|
| 45 |
+
value = function(value, element)
|
| 46 |
+
|
| 47 |
+
return value
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/fx.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from torch._C import _fx_map_aggregate, _fx_map_arg
|
| 5 |
+
from torch.fx.immutable_collections import immutable_dict, immutable_list
|
| 6 |
+
from torch.fx.node import Node
|
| 7 |
+
|
| 8 |
+
from ..decorators import substitute_in_graph
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@substitute_in_graph(_fx_map_arg, can_constant_fold_through=True)
|
| 12 |
+
def map_arg(a: Any, fn: Callable[[Node], Any]) -> Any:
|
| 13 |
+
return map_aggregate(a, lambda x: fn(x) if isinstance(x, Node) else x)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@substitute_in_graph(_fx_map_aggregate, can_constant_fold_through=True)
|
| 17 |
+
def map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any:
|
| 18 |
+
result: Any
|
| 19 |
+
if isinstance(a, tuple):
|
| 20 |
+
it = (map_aggregate(elem, fn) for elem in a)
|
| 21 |
+
# Support NamedTuple (if it has `_fields`) by repacking into original type.
|
| 22 |
+
result = type(a)(*it) if hasattr(a, "_fields") else tuple(it)
|
| 23 |
+
elif isinstance(a, list):
|
| 24 |
+
result = immutable_list([map_aggregate(elem, fn) for elem in a])
|
| 25 |
+
elif isinstance(a, dict):
|
| 26 |
+
result = immutable_dict([(k, map_aggregate(v, fn)) for k, v in a.items()])
|
| 27 |
+
elif isinstance(a, slice):
|
| 28 |
+
result = slice(
|
| 29 |
+
map_aggregate(a.start, fn),
|
| 30 |
+
map_aggregate(a.stop, fn),
|
| 31 |
+
map_aggregate(a.step, fn),
|
| 32 |
+
)
|
| 33 |
+
else:
|
| 34 |
+
result = fn(a)
|
| 35 |
+
return result
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"map_arg",
|
| 40 |
+
"map_aggregate",
|
| 41 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/heapq.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for heapq
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import heapq
|
| 8 |
+
import importlib
|
| 9 |
+
import sys
|
| 10 |
+
from typing import TYPE_CHECKING, TypeVar
|
| 11 |
+
|
| 12 |
+
from ..decorators import substitute_in_graph
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from types import ModuleType
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_T = TypeVar("_T")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Partially copied from CPython test/support/import_helper.py
|
| 23 |
+
# https://github.com/python/cpython/blob/bb8791c0b75b5970d109e5557bfcca8a578a02af/Lib/test/support/import_helper.py
|
| 24 |
+
def _save_and_remove_modules(names: set[str]) -> dict[str, ModuleType]:
|
| 25 |
+
orig_modules = {}
|
| 26 |
+
prefixes = tuple(name + "." for name in names)
|
| 27 |
+
for modname in list(sys.modules):
|
| 28 |
+
if modname in names or modname.startswith(prefixes):
|
| 29 |
+
orig_modules[modname] = sys.modules.pop(modname)
|
| 30 |
+
return orig_modules
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def import_fresh_module(name: str, blocked: list[str]) -> ModuleType:
|
| 34 |
+
# Keep track of modules saved for later restoration as well
|
| 35 |
+
# as those which just need a blocking entry removed
|
| 36 |
+
names = {name, *blocked}
|
| 37 |
+
orig_modules = _save_and_remove_modules(names)
|
| 38 |
+
for modname in blocked:
|
| 39 |
+
sys.modules[modname] = None # type: ignore[assignment]
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
return importlib.import_module(name)
|
| 43 |
+
finally:
|
| 44 |
+
_save_and_remove_modules(names)
|
| 45 |
+
sys.modules.update(orig_modules)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Import the pure Python heapq module, blocking the C extension
|
| 49 |
+
py_heapq = import_fresh_module("heapq", blocked=["_heapq"])
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
__all__ = [
|
| 53 |
+
"_heapify_max",
|
| 54 |
+
"_heappop_max",
|
| 55 |
+
"_heapreplace_max",
|
| 56 |
+
"heapify",
|
| 57 |
+
"heappop",
|
| 58 |
+
"heappush",
|
| 59 |
+
"heappushpop",
|
| 60 |
+
"heapreplace",
|
| 61 |
+
"merge",
|
| 62 |
+
"nlargest",
|
| 63 |
+
"nsmallest",
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@substitute_in_graph(heapq._heapify_max)
|
| 68 |
+
def _heapify_max(heap: list[_T], /) -> None:
|
| 69 |
+
return py_heapq._heapify_max(heap)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@substitute_in_graph(heapq._heappop_max) # type: ignore[attr-defined]
|
| 73 |
+
def _heappop_max(heap: list[_T]) -> _T:
|
| 74 |
+
return py_heapq._heappop_max(heap)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@substitute_in_graph(heapq._heapreplace_max) # type: ignore[attr-defined]
|
| 78 |
+
def _heapreplace_max(heap: list[_T], item: _T) -> _T:
|
| 79 |
+
return py_heapq._heapreplace_max(heap, item)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@substitute_in_graph(heapq.heapify)
|
| 83 |
+
def heapify(heap: list[_T], /) -> None:
|
| 84 |
+
return py_heapq.heapify(heap)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@substitute_in_graph(heapq.heappop)
|
| 88 |
+
def heappop(heap: list[_T], /) -> _T:
|
| 89 |
+
return py_heapq.heappop(heap)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@substitute_in_graph(heapq.heappush)
|
| 93 |
+
def heappush(heap: list[_T], item: _T) -> None:
|
| 94 |
+
return py_heapq.heappush(heap, item)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@substitute_in_graph(heapq.heappushpop)
|
| 98 |
+
def heappushpop(heap: list[_T], item: _T) -> _T:
|
| 99 |
+
return py_heapq.heappushpop(heap, item)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@substitute_in_graph(heapq.heapreplace)
|
| 103 |
+
def heapreplace(heap: list[_T], item: _T) -> _T:
|
| 104 |
+
return py_heapq.heapreplace(heap, item)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@substitute_in_graph(heapq.merge) # type: ignore[arg-type]
|
| 108 |
+
def merge(*iterables, key=None, reverse=False): # type: ignore[no-untyped-def]
|
| 109 |
+
return py_heapq.merge(*iterables, key=key, reverse=reverse)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@substitute_in_graph(heapq.nlargest) # type: ignore[arg-type]
|
| 113 |
+
def nlargest(n, iterable, key=None): # type: ignore[no-untyped-def]
|
| 114 |
+
return py_heapq.nlargest(n, iterable, key=key)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@substitute_in_graph(heapq.nsmallest) # type: ignore[arg-type]
|
| 118 |
+
def nsmallest(n, iterable, key=None): # type: ignore[no-untyped-def]
|
| 119 |
+
return py_heapq.nsmallest(n, iterable, key=key)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/itertools.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for itertools
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import itertools
|
| 8 |
+
import operator
|
| 9 |
+
from collections.abc import Callable
|
| 10 |
+
from typing import Optional, overload, TYPE_CHECKING, TypeAlias, TypeVar
|
| 11 |
+
|
| 12 |
+
from ..decorators import substitute_in_graph
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from collections.abc import Iterable, Iterator
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"accumulate",
|
| 21 |
+
"chain",
|
| 22 |
+
"chain_from_iterable",
|
| 23 |
+
"compress",
|
| 24 |
+
"cycle",
|
| 25 |
+
"dropwhile",
|
| 26 |
+
"filterfalse",
|
| 27 |
+
"islice",
|
| 28 |
+
"tee",
|
| 29 |
+
"zip_longest",
|
| 30 |
+
"pairwise",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_T = TypeVar("_T")
|
| 35 |
+
_U = TypeVar("_U")
|
| 36 |
+
_Predicate: TypeAlias = Callable[[_T], object]
|
| 37 |
+
_T1 = TypeVar("_T1")
|
| 38 |
+
_T2 = TypeVar("_T2")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.chain
|
| 42 |
+
@substitute_in_graph(itertools.chain, is_embedded_type=True) # type: ignore[arg-type]
|
| 43 |
+
def chain(*iterables: Iterable[_T]) -> Iterator[_T]:
|
| 44 |
+
for iterable in iterables:
|
| 45 |
+
yield from iterable
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.accumulate
|
| 49 |
+
@substitute_in_graph(itertools.accumulate, is_embedded_type=True) # type: ignore[arg-type]
|
| 50 |
+
def accumulate(
|
| 51 |
+
iterable: Iterable[_T],
|
| 52 |
+
func: Optional[Callable[[_T, _T], _T]] = None,
|
| 53 |
+
*,
|
| 54 |
+
initial: Optional[_T] = None,
|
| 55 |
+
) -> Iterator[_T]:
|
| 56 |
+
# call iter outside of the generator to match cypthon behavior
|
| 57 |
+
iterator = iter(iterable)
|
| 58 |
+
if func is None:
|
| 59 |
+
func = operator.add
|
| 60 |
+
|
| 61 |
+
def _accumulate(iterator: Iterator[_T]) -> Iterator[_T]:
|
| 62 |
+
total = initial
|
| 63 |
+
if total is None:
|
| 64 |
+
try:
|
| 65 |
+
total = next(iterator)
|
| 66 |
+
except StopIteration:
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
yield total
|
| 70 |
+
for element in iterator:
|
| 71 |
+
total = func(total, element)
|
| 72 |
+
yield total
|
| 73 |
+
|
| 74 |
+
return _accumulate(iterator)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@substitute_in_graph(itertools.chain.from_iterable) # type: ignore[arg-type]
|
| 78 |
+
def chain_from_iterable(iterable: Iterable[Iterable[_T]], /) -> Iterator[_T]:
|
| 79 |
+
# previous version of this code was:
|
| 80 |
+
# return itertools.chain(*iterable)
|
| 81 |
+
# If iterable is an infinite generator, this will lead to infinite recursion
|
| 82 |
+
for it in iterable:
|
| 83 |
+
yield from it
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
chain.from_iterable = chain_from_iterable # type: ignore[attr-defined]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.compress
|
| 90 |
+
@substitute_in_graph(itertools.compress, is_embedded_type=True) # type: ignore[arg-type]
|
| 91 |
+
def compress(data: Iterable[_T], selectors: Iterable[_U], /) -> Iterator[_T]:
|
| 92 |
+
return (datum for datum, selector in zip(data, selectors) if selector)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.cycle
|
| 96 |
+
@substitute_in_graph(itertools.cycle, is_embedded_type=True) # type: ignore[arg-type]
|
| 97 |
+
def cycle(iterable: Iterable[_T]) -> Iterator[_T]:
|
| 98 |
+
iterator = iter(iterable)
|
| 99 |
+
|
| 100 |
+
def _cycle(iterator: Iterator[_T]) -> Iterator[_T]:
|
| 101 |
+
saved = []
|
| 102 |
+
for element in iterable:
|
| 103 |
+
yield element
|
| 104 |
+
saved.append(element)
|
| 105 |
+
|
| 106 |
+
while saved:
|
| 107 |
+
for element in saved:
|
| 108 |
+
yield element
|
| 109 |
+
|
| 110 |
+
return _cycle(iterator)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.dropwhile
|
| 114 |
+
@substitute_in_graph(itertools.dropwhile, is_embedded_type=True) # type: ignore[arg-type]
|
| 115 |
+
def dropwhile(predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]:
|
| 116 |
+
# dropwhile(lambda x: x < 5, [1, 4, 6, 3, 8]) -> 6 3 8
|
| 117 |
+
|
| 118 |
+
iterator = iter(iterable)
|
| 119 |
+
for x in iterator:
|
| 120 |
+
if not predicate(x):
|
| 121 |
+
yield x
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
yield from iterator
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@substitute_in_graph(itertools.filterfalse, is_embedded_type=True) # type: ignore[arg-type]
|
| 128 |
+
def filterfalse(function: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]:
|
| 129 |
+
it = iter(iterable)
|
| 130 |
+
if function is None:
|
| 131 |
+
return filter(operator.not_, it)
|
| 132 |
+
else:
|
| 133 |
+
return filter(lambda x: not function(x), it)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.islice
|
| 137 |
+
@substitute_in_graph(itertools.islice, is_embedded_type=True) # type: ignore[arg-type]
|
| 138 |
+
def islice(iterable: Iterable[_T], /, *args: int | None) -> Iterator[_T]:
|
| 139 |
+
s = slice(*args)
|
| 140 |
+
start = 0 if s.start is None else s.start
|
| 141 |
+
stop = s.stop
|
| 142 |
+
step = 1 if s.step is None else s.step
|
| 143 |
+
if start < 0 or (stop is not None and stop < 0) or step <= 0:
|
| 144 |
+
raise ValueError(
|
| 145 |
+
"Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.",
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
if stop is None:
|
| 149 |
+
# TODO: use indices = itertools.count() and merge implementation with the else branch
|
| 150 |
+
# when we support infinite iterators
|
| 151 |
+
next_i = start
|
| 152 |
+
for i, element in enumerate(iterable):
|
| 153 |
+
if i == next_i:
|
| 154 |
+
yield element
|
| 155 |
+
next_i += step
|
| 156 |
+
else:
|
| 157 |
+
indices = range(max(start, stop))
|
| 158 |
+
next_i = start
|
| 159 |
+
for i, element in zip(indices, iterable):
|
| 160 |
+
if i == next_i:
|
| 161 |
+
yield element
|
| 162 |
+
next_i += step
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.pairwise
|
| 166 |
+
@substitute_in_graph(itertools.pairwise, is_embedded_type=True) # type: ignore[arg-type]
|
| 167 |
+
def pairwise(iterable: Iterable[_T], /) -> Iterator[tuple[_T, _T]]:
|
| 168 |
+
a = None
|
| 169 |
+
first = True
|
| 170 |
+
for b in iterable:
|
| 171 |
+
if first:
|
| 172 |
+
first = False
|
| 173 |
+
else:
|
| 174 |
+
yield a, b # type: ignore[misc]
|
| 175 |
+
a = b
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.tee
|
| 179 |
+
@substitute_in_graph(itertools.tee)
|
| 180 |
+
def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]:
|
| 181 |
+
iterator = iter(iterable)
|
| 182 |
+
shared_link = [None, None]
|
| 183 |
+
|
| 184 |
+
def _tee(link) -> Iterator[_T]: # type: ignore[no-untyped-def]
|
| 185 |
+
try:
|
| 186 |
+
while True:
|
| 187 |
+
if link[1] is None:
|
| 188 |
+
link[0] = next(iterator)
|
| 189 |
+
link[1] = [None, None]
|
| 190 |
+
value, link = link
|
| 191 |
+
yield value
|
| 192 |
+
except StopIteration:
|
| 193 |
+
return
|
| 194 |
+
|
| 195 |
+
return tuple(_tee(shared_link) for _ in range(n))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@overload
|
| 199 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 200 |
+
def zip_longest(
|
| 201 |
+
iter1: Iterable[_T1],
|
| 202 |
+
/,
|
| 203 |
+
*,
|
| 204 |
+
fillvalue: _U = ...,
|
| 205 |
+
) -> Iterator[tuple[_T1]]: ...
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@overload
|
| 209 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 210 |
+
def zip_longest(
|
| 211 |
+
iter1: Iterable[_T1],
|
| 212 |
+
iter2: Iterable[_T2],
|
| 213 |
+
/,
|
| 214 |
+
) -> Iterator[tuple[_T1 | None, _T2 | None]]: ...
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@overload
|
| 218 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 219 |
+
def zip_longest(
|
| 220 |
+
iter1: Iterable[_T1],
|
| 221 |
+
iter2: Iterable[_T2],
|
| 222 |
+
/,
|
| 223 |
+
*,
|
| 224 |
+
fillvalue: _U = ...,
|
| 225 |
+
) -> Iterator[tuple[_T1 | _U, _T2 | _U]]: ...
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@overload
|
| 229 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 230 |
+
def zip_longest(
|
| 231 |
+
iter1: Iterable[_T],
|
| 232 |
+
iter2: Iterable[_T],
|
| 233 |
+
iter3: Iterable[_T],
|
| 234 |
+
/,
|
| 235 |
+
*iterables: Iterable[_T],
|
| 236 |
+
) -> Iterator[tuple[_T | None, ...]]: ...
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@overload
|
| 240 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 241 |
+
def zip_longest(
|
| 242 |
+
iter1: Iterable[_T],
|
| 243 |
+
iter2: Iterable[_T],
|
| 244 |
+
iter3: Iterable[_T],
|
| 245 |
+
/,
|
| 246 |
+
*iterables: Iterable[_T],
|
| 247 |
+
fillvalue: _U = ...,
|
| 248 |
+
) -> Iterator[tuple[_T | _U, ...]]: ...
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# Reference: https://docs.python.org/3/library/itertools.html#itertools.zip_longest
|
| 252 |
+
@substitute_in_graph(itertools.zip_longest, is_embedded_type=True) # type: ignore[arg-type,misc]
|
| 253 |
+
def zip_longest(
|
| 254 |
+
*iterables: Iterable[_T],
|
| 255 |
+
fillvalue: _U = None, # type: ignore[assignment]
|
| 256 |
+
) -> Iterator[tuple[_T | _U, ...]]:
|
| 257 |
+
# zip_longest('ABCD', 'xy', fillvalue='-') -> Ax By C- D-
|
| 258 |
+
|
| 259 |
+
iterators = list(map(iter, iterables))
|
| 260 |
+
num_active = len(iterators)
|
| 261 |
+
if not num_active:
|
| 262 |
+
return
|
| 263 |
+
|
| 264 |
+
while True:
|
| 265 |
+
values = []
|
| 266 |
+
for i, iterator in enumerate(iterators):
|
| 267 |
+
try:
|
| 268 |
+
value = next(iterator)
|
| 269 |
+
except StopIteration:
|
| 270 |
+
num_active -= 1
|
| 271 |
+
if not num_active:
|
| 272 |
+
return
|
| 273 |
+
iterators[i] = itertools.repeat(fillvalue) # type: ignore[arg-type]
|
| 274 |
+
value = fillvalue # type: ignore[assignment]
|
| 275 |
+
values.append(value)
|
| 276 |
+
yield tuple(values)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/loader.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Used to load and initialize polyfill handlers when importing torch._dynamo
|
| 2 |
+
# Please add a new import when adding a new polyfill module.
|
| 3 |
+
|
| 4 |
+
import importlib
|
| 5 |
+
from typing import TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
import torch.utils._pytree as python_pytree
|
| 8 |
+
|
| 9 |
+
from .. import polyfills, trace_rules
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from types import ModuleType
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# See also the TYPE_CHECKING block in torch/_dynamo/polyfills/__init__.py
|
| 17 |
+
POLYFILLED_MODULE_NAMES: tuple[str, ...] = (
|
| 18 |
+
"_collections",
|
| 19 |
+
"builtins",
|
| 20 |
+
"functools",
|
| 21 |
+
"itertools",
|
| 22 |
+
"operator",
|
| 23 |
+
"os",
|
| 24 |
+
"struct",
|
| 25 |
+
"sys",
|
| 26 |
+
"fx",
|
| 27 |
+
"tensor",
|
| 28 |
+
)
|
| 29 |
+
if python_pytree._cxx_pytree_dynamo_traceable:
|
| 30 |
+
POLYFILLED_MODULE_NAMES += ("pytree",)
|
| 31 |
+
|
| 32 |
+
POLYFILLED_MODULES: tuple["ModuleType", ...] = tuple(
|
| 33 |
+
importlib.import_module(f".{submodule}", package=polyfills.__name__)
|
| 34 |
+
for submodule in POLYFILLED_MODULE_NAMES
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Unregister the builtin functions from _builtin_function_ids to let them to be
|
| 39 |
+
# dispatched with the appropriate VariableTracker type. Otherwise, they will be
|
| 40 |
+
# dispatched with BuiltinVariable if present in _builtin_function_ids.
|
| 41 |
+
for polyfill_module in POLYFILLED_MODULES:
|
| 42 |
+
for polyfill_name in polyfill_module.__all__:
|
| 43 |
+
polyfill_handler = getattr(polyfill_module, polyfill_name)
|
| 44 |
+
original_fn = polyfill_handler.__torch_dynamo_original__
|
| 45 |
+
trace_rules._builtin_function_ids.remove(id(original_fn))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/operator.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for operator
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import operator
|
| 8 |
+
from typing import Any, overload, TYPE_CHECKING, TypeVar
|
| 9 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 10 |
+
|
| 11 |
+
from ..decorators import substitute_in_graph
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from collections.abc import Callable, Iterable
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Most unary and binary operators are handled by BuiltinVariable (e.g., `pos`, `add`)
|
| 19 |
+
__all__ = ["attrgetter", "itemgetter", "methodcaller", "countOf"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_T = TypeVar("_T")
|
| 23 |
+
_T1 = TypeVar("_T1")
|
| 24 |
+
_T2 = TypeVar("_T2")
|
| 25 |
+
_Ts = TypeVarTuple("_Ts")
|
| 26 |
+
_U = TypeVar("_U")
|
| 27 |
+
_U1 = TypeVar("_U1")
|
| 28 |
+
_U2 = TypeVar("_U2")
|
| 29 |
+
_Us = TypeVarTuple("_Us")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@overload
|
| 33 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 34 |
+
def attrgetter(attr: str, /) -> Callable[[Any], _U]: ...
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@overload
|
| 38 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 39 |
+
def attrgetter(
|
| 40 |
+
attr1: str, attr2: str, /, *attrs: str
|
| 41 |
+
) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ...
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Reference: https://docs.python.org/3/library/operator.html#operator.attrgetter
|
| 45 |
+
@substitute_in_graph(operator.attrgetter, is_embedded_type=True) # type: ignore[arg-type,misc]
|
| 46 |
+
def attrgetter(*attrs: str) -> Callable[[Any], Any | tuple[Any, ...]]:
|
| 47 |
+
if len(attrs) == 0:
|
| 48 |
+
raise TypeError("attrgetter expected 1 argument, got 0")
|
| 49 |
+
|
| 50 |
+
if any(not isinstance(attr, str) for attr in attrs):
|
| 51 |
+
raise TypeError("attribute name must be a string")
|
| 52 |
+
|
| 53 |
+
def resolve_attr(obj: Any, attr: str) -> Any:
|
| 54 |
+
for name in attr.split("."):
|
| 55 |
+
obj = getattr(obj, name)
|
| 56 |
+
return obj
|
| 57 |
+
|
| 58 |
+
if len(attrs) == 1:
|
| 59 |
+
attr = attrs[0]
|
| 60 |
+
|
| 61 |
+
def getter(obj: Any) -> Any:
|
| 62 |
+
return resolve_attr(obj, attr)
|
| 63 |
+
|
| 64 |
+
else:
|
| 65 |
+
|
| 66 |
+
def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc]
|
| 67 |
+
return tuple(resolve_attr(obj, attr) for attr in attrs)
|
| 68 |
+
|
| 69 |
+
return getter
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@overload
|
| 73 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 74 |
+
def itemgetter(item: _T, /) -> Callable[[Any], _U]: ...
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@overload
|
| 78 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 79 |
+
def itemgetter(
|
| 80 |
+
item1: _T1, item2: _T2, /, *items: Unpack[_Ts]
|
| 81 |
+
) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ...
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# Reference: https://docs.python.org/3/library/operator.html#operator.itemgetter
|
| 85 |
+
@substitute_in_graph(operator.itemgetter, is_embedded_type=True) # type: ignore[arg-type,misc]
|
| 86 |
+
def itemgetter(*items: Any) -> Callable[[Any], Any | tuple[Any, ...]]:
|
| 87 |
+
if len(items) == 0:
|
| 88 |
+
raise TypeError("itemgetter expected 1 argument, got 0")
|
| 89 |
+
|
| 90 |
+
if len(items) == 1:
|
| 91 |
+
item = items[0]
|
| 92 |
+
|
| 93 |
+
def getter(obj: Any) -> Any:
|
| 94 |
+
return obj[item]
|
| 95 |
+
|
| 96 |
+
else:
|
| 97 |
+
|
| 98 |
+
def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc]
|
| 99 |
+
return tuple(obj[item] for item in items)
|
| 100 |
+
|
| 101 |
+
return getter
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# Reference: https://docs.python.org/3/library/operator.html#operator.methodcaller
|
| 105 |
+
@substitute_in_graph(operator.methodcaller, is_embedded_type=True) # type: ignore[arg-type]
|
| 106 |
+
def methodcaller(name: str, /, *args: Any, **kwargs: Any) -> Callable[[Any], Any]:
|
| 107 |
+
if not isinstance(name, str):
|
| 108 |
+
raise TypeError("method name must be a string")
|
| 109 |
+
|
| 110 |
+
def caller(obj: Any) -> Any:
|
| 111 |
+
return getattr(obj, name)(*args, **kwargs)
|
| 112 |
+
|
| 113 |
+
return caller
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# Reference: https://docs.python.org/3/library/operator.html#operator.countOf
|
| 117 |
+
@substitute_in_graph(operator.countOf, can_constant_fold_through=True) # type: ignore[arg-type,misc]
|
| 118 |
+
def countOf(a: Iterable[_T], b: _T, /) -> int:
|
| 119 |
+
return sum(it is b or it == b for it in a)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/os.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for os
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
from typing import AnyStr
|
| 9 |
+
|
| 10 |
+
from ..decorators import substitute_in_graph
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ["fspath"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Copied from os.py in the standard library
|
| 17 |
+
@substitute_in_graph(os.fspath, can_constant_fold_through=True)
|
| 18 |
+
def fspath(path: AnyStr | os.PathLike[AnyStr]) -> AnyStr:
|
| 19 |
+
if isinstance(path, (str, bytes)):
|
| 20 |
+
# pyrefly: ignore [bad-return]
|
| 21 |
+
return path
|
| 22 |
+
|
| 23 |
+
path_type = type(path)
|
| 24 |
+
try:
|
| 25 |
+
path_repr = path_type.__fspath__(path) # type: ignore[arg-type]
|
| 26 |
+
except AttributeError:
|
| 27 |
+
if hasattr(path_type, "__fspath__"):
|
| 28 |
+
raise
|
| 29 |
+
raise TypeError(
|
| 30 |
+
f"expected str, bytes or os.PathLike object, not {path_type.__name__}",
|
| 31 |
+
) from None
|
| 32 |
+
if isinstance(path_repr, (str, bytes)):
|
| 33 |
+
return path_repr # type: ignore[return-value]
|
| 34 |
+
raise TypeError(
|
| 35 |
+
f"expected {path_type.__name__}.__fspath__() to return str or bytes, "
|
| 36 |
+
f"not {type(path_repr).__name__}",
|
| 37 |
+
)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/pytree.py
ADDED
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for torch.utils.pytree
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from collections import deque
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from typing import Any, TYPE_CHECKING, TypeVar
|
| 10 |
+
|
| 11 |
+
import optree
|
| 12 |
+
import optree._C
|
| 13 |
+
import optree.utils
|
| 14 |
+
from optree import (
|
| 15 |
+
is_namedtuple,
|
| 16 |
+
is_namedtuple_class,
|
| 17 |
+
is_namedtuple_instance,
|
| 18 |
+
is_structseq,
|
| 19 |
+
is_structseq_class,
|
| 20 |
+
is_structseq_instance,
|
| 21 |
+
namedtuple_fields,
|
| 22 |
+
structseq_fields,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
import torch.utils._cxx_pytree as cxx_pytree # noqa: F401
|
| 26 |
+
import torch.utils._pytree as python_pytree
|
| 27 |
+
from torch.utils._pytree import BUILTIN_TYPES, STANDARD_DICT_TYPES
|
| 28 |
+
|
| 29 |
+
from ..decorators import substitute_in_graph
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
import builtins
|
| 34 |
+
from collections.abc import Callable, Iterable, Mapping
|
| 35 |
+
from typing_extensions import Self, TypeIs
|
| 36 |
+
|
| 37 |
+
from torch.utils._cxx_pytree import PyTree
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
__all__ = [
|
| 41 |
+
"is_namedtuple",
|
| 42 |
+
"is_namedtuple_class",
|
| 43 |
+
"is_namedtuple_instance",
|
| 44 |
+
"is_structseq",
|
| 45 |
+
"is_structseq_class",
|
| 46 |
+
"is_structseq_instance",
|
| 47 |
+
"namedtuple_fields",
|
| 48 |
+
"structseq_fields",
|
| 49 |
+
"treespec_leaf",
|
| 50 |
+
"treespec_tuple",
|
| 51 |
+
"treespec_dict",
|
| 52 |
+
"tree_is_leaf",
|
| 53 |
+
"tree_iter",
|
| 54 |
+
"tree_leaves",
|
| 55 |
+
"tree_flatten",
|
| 56 |
+
"tree_flatten_with_path",
|
| 57 |
+
"tree_structure",
|
| 58 |
+
"tree_unflatten",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
_T = TypeVar("_T")
|
| 63 |
+
_KT = TypeVar("_KT")
|
| 64 |
+
_VT = TypeVar("_VT")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@substitute_in_graph(
|
| 68 |
+
optree._C.is_dict_insertion_ordered,
|
| 69 |
+
can_constant_fold_through=True,
|
| 70 |
+
)
|
| 71 |
+
def _(*args: Any, **kwargs: Any) -> bool:
|
| 72 |
+
# In namespace 'torch', the dictionary is always traversed in insertion order.
|
| 73 |
+
# This function returns True.
|
| 74 |
+
raise ValueError(
|
| 75 |
+
"Should not be called directly "
|
| 76 |
+
"because the original function will be called in the constant fold path."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
__name = ""
|
| 81 |
+
for __name, __func in (
|
| 82 |
+
("is_namedtuple", is_namedtuple),
|
| 83 |
+
("is_namedtuple_class", is_namedtuple_class),
|
| 84 |
+
("is_namedtuple_instance", is_namedtuple_instance),
|
| 85 |
+
("is_structseq", is_structseq),
|
| 86 |
+
("is_structseq_class", is_structseq_class),
|
| 87 |
+
("is_structseq_instance", is_structseq_instance),
|
| 88 |
+
("namedtuple_fields", namedtuple_fields),
|
| 89 |
+
("structseq_fields", structseq_fields),
|
| 90 |
+
):
|
| 91 |
+
globals()[__name] = substitute_in_graph(
|
| 92 |
+
__func, # type: ignore[arg-type]
|
| 93 |
+
can_constant_fold_through=True,
|
| 94 |
+
)(__func.__python_implementation__) # type: ignore[attr-defined]
|
| 95 |
+
del __func
|
| 96 |
+
del __name
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@substitute_in_graph(optree.tree_is_leaf, can_constant_fold_through=True) # type: ignore[arg-type]
|
| 100 |
+
def tree_is_leaf(
|
| 101 |
+
tree: PyTree,
|
| 102 |
+
/,
|
| 103 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 104 |
+
*,
|
| 105 |
+
none_is_leaf: bool = False,
|
| 106 |
+
namespace: str = "",
|
| 107 |
+
) -> bool:
|
| 108 |
+
if (tree is None and none_is_leaf) or (is_leaf is not None and is_leaf(tree)):
|
| 109 |
+
return True
|
| 110 |
+
if optree.register_pytree_node.get(type(tree), namespace=namespace) is None:
|
| 111 |
+
return True
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@substitute_in_graph(optree.tree_iter, can_constant_fold_through=False) # type: ignore[arg-type]
|
| 116 |
+
def tree_iter(
|
| 117 |
+
tree: PyTree,
|
| 118 |
+
/,
|
| 119 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 120 |
+
*,
|
| 121 |
+
none_is_leaf: bool = False,
|
| 122 |
+
namespace: str = "",
|
| 123 |
+
) -> Iterable[Any]:
|
| 124 |
+
stack = [tree]
|
| 125 |
+
while stack:
|
| 126 |
+
node = stack.pop()
|
| 127 |
+
if tree_is_leaf(
|
| 128 |
+
node,
|
| 129 |
+
is_leaf=is_leaf,
|
| 130 |
+
none_is_leaf=none_is_leaf,
|
| 131 |
+
namespace=namespace,
|
| 132 |
+
):
|
| 133 |
+
yield node
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
children, *_ = optree.tree_flatten_one_level(
|
| 137 |
+
node,
|
| 138 |
+
is_leaf=is_leaf,
|
| 139 |
+
none_is_leaf=none_is_leaf,
|
| 140 |
+
namespace=namespace,
|
| 141 |
+
)
|
| 142 |
+
stack.extend(reversed(children))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@substitute_in_graph(optree.tree_leaves, can_constant_fold_through=True) # type: ignore[arg-type]
|
| 146 |
+
def tree_leaves(
|
| 147 |
+
tree: PyTree,
|
| 148 |
+
/,
|
| 149 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 150 |
+
*,
|
| 151 |
+
none_is_leaf: bool = False,
|
| 152 |
+
namespace: str = "",
|
| 153 |
+
) -> list[Any]:
|
| 154 |
+
return list(
|
| 155 |
+
tree_iter(
|
| 156 |
+
tree,
|
| 157 |
+
is_leaf=is_leaf,
|
| 158 |
+
none_is_leaf=none_is_leaf,
|
| 159 |
+
namespace=namespace,
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class _Asterisk(str):
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
def __new__(cls) -> Self:
|
| 168 |
+
return super().__new__(cls, "*")
|
| 169 |
+
|
| 170 |
+
def __repr__(self) -> str:
|
| 171 |
+
return "*" # no quotes
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
_asterisk = _Asterisk()
|
| 175 |
+
del _Asterisk
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@dataclass(frozen=True)
|
| 179 |
+
class PyTreeSpec:
|
| 180 |
+
"""Analog for :class:`optree.PyTreeSpec` in Python."""
|
| 181 |
+
|
| 182 |
+
_children: tuple[PyTreeSpec, ...]
|
| 183 |
+
_type: builtins.type | None
|
| 184 |
+
_metadata: Any
|
| 185 |
+
_entries: tuple[Any, ...]
|
| 186 |
+
_unflatten_func: Callable[[Any | None, Iterable[PyTree]], PyTree] | None
|
| 187 |
+
none_is_leaf: bool
|
| 188 |
+
namespace: str
|
| 189 |
+
|
| 190 |
+
num_nodes: int = field(init=False)
|
| 191 |
+
num_leaves: int = field(init=False)
|
| 192 |
+
num_children: int = field(init=False)
|
| 193 |
+
|
| 194 |
+
def __post_init__(self, /) -> None:
|
| 195 |
+
if self._type is None:
|
| 196 |
+
assert len(self._children) == 0
|
| 197 |
+
assert self._metadata is None
|
| 198 |
+
assert self._entries == ()
|
| 199 |
+
assert self._unflatten_func is None
|
| 200 |
+
num_nodes = 1
|
| 201 |
+
num_leaves = 1
|
| 202 |
+
num_children = 0
|
| 203 |
+
else:
|
| 204 |
+
assert callable(self._unflatten_func)
|
| 205 |
+
num_nodes = 1
|
| 206 |
+
num_leaves = 0
|
| 207 |
+
for child in self._children:
|
| 208 |
+
num_nodes += child.num_nodes
|
| 209 |
+
num_leaves += child.num_leaves
|
| 210 |
+
num_children = len(self._children)
|
| 211 |
+
|
| 212 |
+
object.__setattr__(self, "num_nodes", num_nodes)
|
| 213 |
+
object.__setattr__(self, "num_leaves", num_leaves)
|
| 214 |
+
object.__setattr__(self, "num_children", num_children)
|
| 215 |
+
|
| 216 |
+
def __repr__(self, /) -> str:
|
| 217 |
+
def helper(treespec: PyTreeSpec) -> str:
|
| 218 |
+
if treespec.is_leaf():
|
| 219 |
+
assert treespec.type is None
|
| 220 |
+
return _asterisk
|
| 221 |
+
|
| 222 |
+
assert treespec.type is not None
|
| 223 |
+
assert callable(treespec._unflatten_func)
|
| 224 |
+
children_representations = [
|
| 225 |
+
helper(subspec) for subspec in treespec._children
|
| 226 |
+
]
|
| 227 |
+
if (
|
| 228 |
+
treespec.type in BUILTIN_TYPES
|
| 229 |
+
or (treespec.type is type(None) and not self.none_is_leaf)
|
| 230 |
+
or optree.is_namedtuple_class(treespec.type)
|
| 231 |
+
or optree.is_structseq_class(treespec.type)
|
| 232 |
+
):
|
| 233 |
+
# pyrefly: ignore [bad-return]
|
| 234 |
+
return treespec._unflatten_func(
|
| 235 |
+
treespec._metadata,
|
| 236 |
+
children_representations,
|
| 237 |
+
)
|
| 238 |
+
return (
|
| 239 |
+
f"CustomTreeNode({treespec.type.__name__}[{treespec._metadata!r}], "
|
| 240 |
+
f"[{', '.join(children_representations)}])"
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
inner = [
|
| 244 |
+
str(helper(self)),
|
| 245 |
+
*(["NoneIsLeaf"] if self.none_is_leaf else []),
|
| 246 |
+
f"namespace={self.namespace!r}",
|
| 247 |
+
]
|
| 248 |
+
return f"PyTreeSpec({', '.join(inner)})"
|
| 249 |
+
|
| 250 |
+
def __len__(self, /) -> int:
|
| 251 |
+
return self.num_leaves
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def type(self, /) -> builtins.type | None:
|
| 255 |
+
return self._type
|
| 256 |
+
|
| 257 |
+
def is_leaf(self, /) -> bool:
|
| 258 |
+
return self.num_nodes == 1 and self.num_leaves == 1
|
| 259 |
+
|
| 260 |
+
def paths(self, /) -> list[tuple[Any, ...]]:
|
| 261 |
+
def helper(treespec: PyTreeSpec, path_prefix: list[Any]) -> None:
|
| 262 |
+
if treespec.is_leaf():
|
| 263 |
+
paths.append(path_prefix)
|
| 264 |
+
return
|
| 265 |
+
|
| 266 |
+
for entry, subspec in zip(
|
| 267 |
+
treespec._entries,
|
| 268 |
+
treespec._children,
|
| 269 |
+
strict=True,
|
| 270 |
+
):
|
| 271 |
+
helper(subspec, path_prefix + [entry])
|
| 272 |
+
|
| 273 |
+
paths: list[list[Any]] = []
|
| 274 |
+
helper(self, [])
|
| 275 |
+
return [tuple(path) for path in paths]
|
| 276 |
+
|
| 277 |
+
def accessors(self, /) -> list[optree.PyTreeAccessor]:
|
| 278 |
+
def helper(
|
| 279 |
+
treespec: PyTreeSpec,
|
| 280 |
+
entry_path_prefix: list[optree.PyTreeEntry],
|
| 281 |
+
) -> None:
|
| 282 |
+
if treespec.is_leaf():
|
| 283 |
+
entry_paths.append(entry_path_prefix)
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
node_type = treespec.type
|
| 287 |
+
assert node_type is not None
|
| 288 |
+
handler = optree.register_pytree_node.get(
|
| 289 |
+
node_type, namespace=treespec.namespace
|
| 290 |
+
)
|
| 291 |
+
assert handler is not None
|
| 292 |
+
kind: optree.PyTreeKind = handler.kind
|
| 293 |
+
path_entry_type: type[optree.PyTreeEntry] = handler.path_entry_type
|
| 294 |
+
|
| 295 |
+
for entry, subspec in zip(
|
| 296 |
+
treespec._entries,
|
| 297 |
+
treespec._children,
|
| 298 |
+
strict=True,
|
| 299 |
+
):
|
| 300 |
+
helper(
|
| 301 |
+
subspec,
|
| 302 |
+
entry_path_prefix + [path_entry_type(entry, node_type, kind)],
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
entry_paths: list[list[optree.PyTreeEntry]] = []
|
| 306 |
+
helper(self, [])
|
| 307 |
+
return [optree.PyTreeAccessor(path) for path in entry_paths]
|
| 308 |
+
|
| 309 |
+
def children(self, /) -> list[PyTreeSpec]:
|
| 310 |
+
return list(self._children)
|
| 311 |
+
|
| 312 |
+
def child(self, index: int, /) -> PyTreeSpec:
|
| 313 |
+
return self._children[index]
|
| 314 |
+
|
| 315 |
+
def entries(self, /) -> list[Any]:
|
| 316 |
+
return list(self._entries)
|
| 317 |
+
|
| 318 |
+
def entry(self, index: int, /) -> Any:
|
| 319 |
+
return self._entries[index]
|
| 320 |
+
|
| 321 |
+
def flatten_up_to(self, tree: PyTree, /) -> list[PyTree]:
|
| 322 |
+
def helper(
|
| 323 |
+
treespec: PyTreeSpec,
|
| 324 |
+
node: PyTree,
|
| 325 |
+
subtrees: list[PyTree],
|
| 326 |
+
) -> None:
|
| 327 |
+
if treespec.is_leaf():
|
| 328 |
+
subtrees.append(node)
|
| 329 |
+
return
|
| 330 |
+
|
| 331 |
+
node_type = type(node)
|
| 332 |
+
if treespec.type not in BUILTIN_TYPES:
|
| 333 |
+
# Always require custom node types to match exactly
|
| 334 |
+
if node_type != treespec.type:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
f"Type mismatch; "
|
| 337 |
+
f"expected {treespec.type!r}, but got {node_type!r}.",
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
children, metadata, *_ = optree.tree_flatten_one_level(
|
| 341 |
+
node,
|
| 342 |
+
none_is_leaf=self.none_is_leaf,
|
| 343 |
+
namespace=self.namespace,
|
| 344 |
+
)
|
| 345 |
+
if len(children) != treespec.num_children:
|
| 346 |
+
raise ValueError(
|
| 347 |
+
f"Node arity mismatch; "
|
| 348 |
+
f"expected {treespec.num_children}, but got {len(children)}.",
|
| 349 |
+
)
|
| 350 |
+
if metadata != treespec._metadata:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
f"Node context mismatch for custom node type {treespec.type!r}.",
|
| 353 |
+
)
|
| 354 |
+
else:
|
| 355 |
+
# For builtin dictionary types, we allow some flexibility
|
| 356 |
+
# Otherwise, we require exact matches
|
| 357 |
+
both_standard_dict = (
|
| 358 |
+
treespec.type in STANDARD_DICT_TYPES
|
| 359 |
+
and node_type in STANDARD_DICT_TYPES
|
| 360 |
+
)
|
| 361 |
+
if not both_standard_dict and node_type != treespec.type:
|
| 362 |
+
raise ValueError(
|
| 363 |
+
f"Node type mismatch; "
|
| 364 |
+
f"expected {treespec.type!r}, but got {node_type!r}.",
|
| 365 |
+
)
|
| 366 |
+
if len(node) != treespec.num_children:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
f"Node arity mismatch; "
|
| 369 |
+
f"expected {treespec.num_children}, but got {len(node)}.",
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
if both_standard_dict:
|
| 373 |
+
# dictionary types are compatible with each other
|
| 374 |
+
expected_keys = treespec.entries()
|
| 375 |
+
got_key_set = set(node)
|
| 376 |
+
expected_key_set = set(expected_keys)
|
| 377 |
+
if got_key_set != expected_key_set:
|
| 378 |
+
missing_keys = expected_key_set.difference(got_key_set)
|
| 379 |
+
extra_keys = got_key_set.difference(expected_key_set)
|
| 380 |
+
message = ""
|
| 381 |
+
if missing_keys:
|
| 382 |
+
message += f"; missing key(s): {missing_keys}"
|
| 383 |
+
if extra_keys:
|
| 384 |
+
message += f"; extra key(s): {extra_keys}"
|
| 385 |
+
raise ValueError(f"Node keys mismatch{message}.")
|
| 386 |
+
children = [node[key] for key in expected_keys]
|
| 387 |
+
else:
|
| 388 |
+
# node_type is treespec.type
|
| 389 |
+
children, metadata, *_ = optree.tree_flatten_one_level(
|
| 390 |
+
node,
|
| 391 |
+
none_is_leaf=self.none_is_leaf,
|
| 392 |
+
namespace=self.namespace,
|
| 393 |
+
)
|
| 394 |
+
if (
|
| 395 |
+
node_type is not deque # ignore mismatch of `maxlen` for deque
|
| 396 |
+
) and metadata != treespec._metadata:
|
| 397 |
+
raise ValueError(
|
| 398 |
+
f"Node metadata mismatch for node type {treespec.type!r}; "
|
| 399 |
+
f"expected {treespec._metadata!r}, but got {metadata!r}.", # namedtuple type mismatch
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
for subtree, subspec in zip(children, treespec._children, strict=True):
|
| 403 |
+
helper(subspec, subtree, subtrees)
|
| 404 |
+
|
| 405 |
+
subtrees: list[PyTree] = []
|
| 406 |
+
helper(self, tree, subtrees)
|
| 407 |
+
return subtrees
|
| 408 |
+
|
| 409 |
+
def unflatten(self, leaves: Iterable[Any], /) -> PyTree:
|
| 410 |
+
if not isinstance(leaves, (list, tuple)):
|
| 411 |
+
leaves = list(leaves)
|
| 412 |
+
if len(leaves) != self.num_leaves:
|
| 413 |
+
raise ValueError(
|
| 414 |
+
f"treespec.unflatten(leaves): `leaves` has length {len(leaves)} "
|
| 415 |
+
f"but the spec refers to a pytree that holds {self.num_leaves} "
|
| 416 |
+
f"items ({self}).",
|
| 417 |
+
)
|
| 418 |
+
if self.is_leaf():
|
| 419 |
+
return leaves[0]
|
| 420 |
+
|
| 421 |
+
# Recursively unflatten the children
|
| 422 |
+
start = 0
|
| 423 |
+
end = 0
|
| 424 |
+
subtrees = []
|
| 425 |
+
for subspec in self._children:
|
| 426 |
+
end += subspec.num_leaves
|
| 427 |
+
subtrees.append(subspec.unflatten(leaves[start:end]))
|
| 428 |
+
start = end
|
| 429 |
+
|
| 430 |
+
assert callable(self._unflatten_func)
|
| 431 |
+
return self._unflatten_func(self._metadata, subtrees)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _is_pytreespec_instance(obj: Any, /) -> TypeIs[PyTreeSpec | python_pytree.TreeSpec]:
|
| 435 |
+
return isinstance(obj, (PyTreeSpec, python_pytree.TreeSpec))
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 439 |
+
optree.treespec_leaf,
|
| 440 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 441 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 442 |
+
can_constant_fold_through=False,
|
| 443 |
+
)
|
| 444 |
+
def treespec_leaf(
|
| 445 |
+
*,
|
| 446 |
+
none_is_leaf: bool = False,
|
| 447 |
+
namespace: str = "", # unused
|
| 448 |
+
) -> PyTreeSpec:
|
| 449 |
+
return PyTreeSpec(
|
| 450 |
+
(),
|
| 451 |
+
None,
|
| 452 |
+
None,
|
| 453 |
+
(),
|
| 454 |
+
None,
|
| 455 |
+
none_is_leaf=none_is_leaf,
|
| 456 |
+
namespace="",
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 461 |
+
optree.treespec_tuple,
|
| 462 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 463 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 464 |
+
can_constant_fold_through=False,
|
| 465 |
+
)
|
| 466 |
+
def treespec_tuple(
|
| 467 |
+
iterable: Iterable[PyTreeSpec] = (),
|
| 468 |
+
/,
|
| 469 |
+
*,
|
| 470 |
+
none_is_leaf: bool = False,
|
| 471 |
+
namespace: str = "",
|
| 472 |
+
) -> PyTreeSpec:
|
| 473 |
+
children = tuple(iterable)
|
| 474 |
+
if any(not _is_pytreespec_instance(child) for child in children):
|
| 475 |
+
raise ValueError(f"Expected a tuple of PyTreeSpecs, got: {children!r}.")
|
| 476 |
+
if any(child.none_is_leaf != none_is_leaf for child in children):
|
| 477 |
+
raise ValueError(
|
| 478 |
+
"All children PyTreeSpecs must have the same `none_is_leaf` value "
|
| 479 |
+
f"as the parent; expected {none_is_leaf}, got: {children!r}.",
|
| 480 |
+
)
|
| 481 |
+
if any(child.namespace not in (namespace, "") for child in children):
|
| 482 |
+
raise ValueError(
|
| 483 |
+
"All children PyTreeSpecs must have the same `namespace` value "
|
| 484 |
+
f"as the parent; expected {namespace!r}, got: {children!r}.",
|
| 485 |
+
)
|
| 486 |
+
handler = optree.register_pytree_node.get(tuple, namespace=namespace)
|
| 487 |
+
assert handler is not None
|
| 488 |
+
return PyTreeSpec(
|
| 489 |
+
tuple(children),
|
| 490 |
+
tuple,
|
| 491 |
+
None,
|
| 492 |
+
tuple(range(len(children))),
|
| 493 |
+
handler.unflatten_func,
|
| 494 |
+
none_is_leaf=none_is_leaf,
|
| 495 |
+
namespace=namespace,
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 500 |
+
optree.treespec_dict,
|
| 501 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 502 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 503 |
+
can_constant_fold_through=False,
|
| 504 |
+
)
|
| 505 |
+
def treespec_dict(
|
| 506 |
+
mapping: Mapping[Any, PyTreeSpec] | Iterable[tuple[Any, PyTreeSpec]] = (),
|
| 507 |
+
/,
|
| 508 |
+
*,
|
| 509 |
+
none_is_leaf: bool = False,
|
| 510 |
+
namespace: str = "",
|
| 511 |
+
**kwargs: PyTreeSpec,
|
| 512 |
+
) -> PyTreeSpec:
|
| 513 |
+
dct = dict(mapping, **kwargs)
|
| 514 |
+
if any(not _is_pytreespec_instance(child) for child in dct.values()):
|
| 515 |
+
raise ValueError(f"Expected a dictionary of TreeSpecs, got: {dct!r}.")
|
| 516 |
+
if any(child.none_is_leaf != none_is_leaf for child in dct.values()):
|
| 517 |
+
raise ValueError(
|
| 518 |
+
"All children PyTreeSpecs must have the same `none_is_leaf` value "
|
| 519 |
+
f"as the parent; expected {none_is_leaf}, got: {dct!r}.",
|
| 520 |
+
)
|
| 521 |
+
if any(child.namespace not in (namespace, "") for child in dct.values()):
|
| 522 |
+
raise ValueError(
|
| 523 |
+
"All children PyTreeSpecs must have the same `namespace` value "
|
| 524 |
+
f"as the parent; expected {namespace!r}, got: {dct!r}.",
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
(
|
| 528 |
+
children,
|
| 529 |
+
metadata,
|
| 530 |
+
entries,
|
| 531 |
+
unflatten_func,
|
| 532 |
+
) = optree.tree_flatten_one_level( # type: ignore[assignment,var-annotated]
|
| 533 |
+
dct, # type: ignore[arg-type]
|
| 534 |
+
none_is_leaf=none_is_leaf,
|
| 535 |
+
namespace=namespace,
|
| 536 |
+
)
|
| 537 |
+
return PyTreeSpec(
|
| 538 |
+
tuple(children), # type: ignore[arg-type]
|
| 539 |
+
dict,
|
| 540 |
+
metadata,
|
| 541 |
+
entries,
|
| 542 |
+
unflatten_func, # type: ignore[arg-type]
|
| 543 |
+
none_is_leaf=none_is_leaf,
|
| 544 |
+
namespace=namespace,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 549 |
+
optree.tree_flatten,
|
| 550 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 551 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 552 |
+
can_constant_fold_through=False,
|
| 553 |
+
)
|
| 554 |
+
def tree_flatten(
|
| 555 |
+
tree: PyTree,
|
| 556 |
+
/,
|
| 557 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 558 |
+
*,
|
| 559 |
+
none_is_leaf: bool = False,
|
| 560 |
+
namespace: str = "",
|
| 561 |
+
) -> tuple[list[Any], PyTreeSpec]:
|
| 562 |
+
def helper(node: PyTree, leaves: list[Any]) -> PyTreeSpec:
|
| 563 |
+
if tree_is_leaf(
|
| 564 |
+
node,
|
| 565 |
+
is_leaf=is_leaf,
|
| 566 |
+
none_is_leaf=none_is_leaf,
|
| 567 |
+
namespace=namespace,
|
| 568 |
+
):
|
| 569 |
+
leaves.append(node)
|
| 570 |
+
return PyTreeSpec(
|
| 571 |
+
(),
|
| 572 |
+
None,
|
| 573 |
+
None,
|
| 574 |
+
(),
|
| 575 |
+
None,
|
| 576 |
+
none_is_leaf=none_is_leaf,
|
| 577 |
+
namespace=namespace,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
(
|
| 581 |
+
children,
|
| 582 |
+
metadata,
|
| 583 |
+
entries,
|
| 584 |
+
unflatten_func,
|
| 585 |
+
) = optree.tree_flatten_one_level(
|
| 586 |
+
node,
|
| 587 |
+
is_leaf=is_leaf,
|
| 588 |
+
none_is_leaf=none_is_leaf,
|
| 589 |
+
namespace=namespace,
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
# Recursively flatten the children
|
| 593 |
+
subspecs = tuple(helper(child, leaves) for child in children)
|
| 594 |
+
return PyTreeSpec(
|
| 595 |
+
subspecs,
|
| 596 |
+
type(node),
|
| 597 |
+
metadata,
|
| 598 |
+
entries,
|
| 599 |
+
unflatten_func, # type: ignore[arg-type]
|
| 600 |
+
none_is_leaf=none_is_leaf,
|
| 601 |
+
namespace=namespace,
|
| 602 |
+
) # type: ignore[arg-type]
|
| 603 |
+
|
| 604 |
+
leaves: list[Any] = []
|
| 605 |
+
treespec = helper(tree, leaves)
|
| 606 |
+
return leaves, treespec
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 610 |
+
optree._C.flatten,
|
| 611 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 612 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 613 |
+
can_constant_fold_through=False,
|
| 614 |
+
)
|
| 615 |
+
def _C_flatten(
|
| 616 |
+
tree: PyTree,
|
| 617 |
+
/,
|
| 618 |
+
leaf_predicate: Callable[[PyTree], bool] | None = None,
|
| 619 |
+
none_is_leaf: bool = False,
|
| 620 |
+
namespace: str = "",
|
| 621 |
+
) -> tuple[list[Any], PyTreeSpec]:
|
| 622 |
+
return tree_flatten( # type: ignore[return-value]
|
| 623 |
+
tree,
|
| 624 |
+
is_leaf=leaf_predicate,
|
| 625 |
+
none_is_leaf=none_is_leaf,
|
| 626 |
+
namespace=namespace,
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 631 |
+
optree.tree_flatten_with_path,
|
| 632 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 633 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 634 |
+
can_constant_fold_through=False,
|
| 635 |
+
)
|
| 636 |
+
def tree_flatten_with_path(
|
| 637 |
+
tree: PyTree,
|
| 638 |
+
/,
|
| 639 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 640 |
+
*,
|
| 641 |
+
none_is_leaf: bool = False,
|
| 642 |
+
namespace: str = "",
|
| 643 |
+
) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]:
|
| 644 |
+
leaves, treespec = tree_flatten(
|
| 645 |
+
tree,
|
| 646 |
+
is_leaf=is_leaf,
|
| 647 |
+
none_is_leaf=none_is_leaf,
|
| 648 |
+
namespace=namespace,
|
| 649 |
+
)
|
| 650 |
+
return treespec.paths(), leaves, treespec # type: ignore[return-value]
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 654 |
+
optree._C.flatten_with_path,
|
| 655 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 656 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 657 |
+
can_constant_fold_through=False,
|
| 658 |
+
)
|
| 659 |
+
def _C_flatten_with_path(
|
| 660 |
+
tree: PyTree,
|
| 661 |
+
/,
|
| 662 |
+
leaf_predicate: Callable[[PyTree], bool] | None = None,
|
| 663 |
+
none_is_leaf: bool = False,
|
| 664 |
+
namespace: str = "",
|
| 665 |
+
) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]:
|
| 666 |
+
return tree_flatten_with_path( # type: ignore[return-value]
|
| 667 |
+
tree,
|
| 668 |
+
is_leaf=leaf_predicate,
|
| 669 |
+
none_is_leaf=none_is_leaf,
|
| 670 |
+
namespace=namespace,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 675 |
+
optree.tree_structure,
|
| 676 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 677 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 678 |
+
can_constant_fold_through=False,
|
| 679 |
+
)
|
| 680 |
+
def tree_structure(
|
| 681 |
+
tree: PyTree,
|
| 682 |
+
/,
|
| 683 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 684 |
+
*,
|
| 685 |
+
none_is_leaf: bool = False,
|
| 686 |
+
namespace: str = "",
|
| 687 |
+
) -> PyTreeSpec:
|
| 688 |
+
return tree_flatten( # type: ignore[return-value]
|
| 689 |
+
tree,
|
| 690 |
+
is_leaf=is_leaf,
|
| 691 |
+
none_is_leaf=none_is_leaf,
|
| 692 |
+
namespace=namespace,
|
| 693 |
+
)[1]
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 697 |
+
optree.tree_unflatten,
|
| 698 |
+
# We need to disable constant folding here because we want the function to reference the
|
| 699 |
+
# PyTreeSpec class defined above, not the one in the C++ module.
|
| 700 |
+
can_constant_fold_through=False,
|
| 701 |
+
)
|
| 702 |
+
def tree_unflatten(treespec: PyTreeSpec, leaves: Iterable[Any]) -> PyTree:
|
| 703 |
+
if not _is_pytreespec_instance(treespec):
|
| 704 |
+
raise TypeError(
|
| 705 |
+
f"Expected `treespec` to be an instance of "
|
| 706 |
+
f"PyTreeSpec but got item of type {type(treespec)}."
|
| 707 |
+
)
|
| 708 |
+
return treespec.unflatten(leaves)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
_none_registration = optree.register_pytree_node.get(type(None))
|
| 712 |
+
assert _none_registration is not None
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 716 |
+
_none_registration.unflatten_func,
|
| 717 |
+
can_constant_fold_through=True,
|
| 718 |
+
skip_signature_check=True,
|
| 719 |
+
)
|
| 720 |
+
def none_unflatten(_: None, children: Iterable[_T], /) -> None:
|
| 721 |
+
if len(list(children)) != 0:
|
| 722 |
+
raise ValueError("Expected no children.")
|
| 723 |
+
return None
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
with optree.dict_insertion_ordered(False, namespace="torch"):
|
| 727 |
+
_dict_registration = optree.register_pytree_node.get(dict)
|
| 728 |
+
assert _dict_registration is not None
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 732 |
+
_dict_registration.flatten_func,
|
| 733 |
+
can_constant_fold_through=True,
|
| 734 |
+
skip_signature_check=True,
|
| 735 |
+
)
|
| 736 |
+
def dict_flatten(
|
| 737 |
+
dct: dict[_KT, _VT], /
|
| 738 |
+
) -> tuple[list[_VT], tuple[list[_KT], list[_KT]], tuple[_KT, ...]]:
|
| 739 |
+
sorted_keys = optree.utils.total_order_sorted(dct)
|
| 740 |
+
values = [dct[key] for key in sorted_keys]
|
| 741 |
+
original_keys = list(dct)
|
| 742 |
+
return values, (original_keys, sorted_keys), tuple(sorted_keys)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 746 |
+
_dict_registration.unflatten_func,
|
| 747 |
+
can_constant_fold_through=True,
|
| 748 |
+
skip_signature_check=True,
|
| 749 |
+
)
|
| 750 |
+
def dict_unflatten(
|
| 751 |
+
metadata: tuple[list[_KT], list[_KT]],
|
| 752 |
+
values: Iterable[_VT],
|
| 753 |
+
/,
|
| 754 |
+
) -> dict[_KT, _VT]:
|
| 755 |
+
original_keys, sorted_keys = metadata
|
| 756 |
+
d = dict.fromkeys(original_keys)
|
| 757 |
+
d.update(zip(sorted_keys, values, strict=True))
|
| 758 |
+
return d # type: ignore[return-value]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/struct.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for struct
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import struct
|
| 8 |
+
from typing import Any
|
| 9 |
+
from typing_extensions import Buffer
|
| 10 |
+
|
| 11 |
+
from ..decorators import substitute_in_graph
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"pack",
|
| 16 |
+
"unpack",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@substitute_in_graph(struct.pack, can_constant_fold_through=True) # type: ignore[arg-type]
|
| 21 |
+
def pack(fmt: bytes | str, /, *v: Any) -> bytes:
|
| 22 |
+
return struct.pack(fmt, *v)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@substitute_in_graph(struct.unpack, can_constant_fold_through=True) # type: ignore[arg-type]
|
| 26 |
+
def unpack(format: bytes | str, buffer: Buffer, /) -> tuple[Any, ...]:
|
| 27 |
+
return struct.unpack(format, buffer)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/sys.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python polyfills for sys
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
from ..decorators import substitute_in_graph
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"intern",
|
| 14 |
+
"getrecursionlimit",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@substitute_in_graph(sys.intern, can_constant_fold_through=True)
|
| 19 |
+
def intern(string: str, /) -> str:
|
| 20 |
+
return string
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@substitute_in_graph(sys.getrecursionlimit, can_constant_fold_through=True)
|
| 24 |
+
def getrecursionlimit() -> int:
|
| 25 |
+
return sys.getrecursionlimit()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if hasattr(sys, "get_int_max_str_digits"):
|
| 29 |
+
|
| 30 |
+
@substitute_in_graph(sys.get_int_max_str_digits, can_constant_fold_through=True)
|
| 31 |
+
def get_int_max_str_digits() -> int:
|
| 32 |
+
return sys.get_int_max_str_digits()
|
| 33 |
+
|
| 34 |
+
__all__ += ["get_int_max_str_digits"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/polyfills/tensor.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from ..decorators import substitute_in_graph
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@substitute_in_graph( # type: ignore[arg-type]
|
| 9 |
+
torch.Tensor._make_subclass
|
| 10 |
+
)
|
| 11 |
+
def make_subclass(
|
| 12 |
+
cls: type[Any], data: torch.Tensor, requires_grad: bool = False, **kwargs: Any
|
| 13 |
+
) -> Any:
|
| 14 |
+
with torch._C.DisableTorchFunctionSubclass():
|
| 15 |
+
# This is a rough approximation of `THPVariable_make_subclass`. It should
|
| 16 |
+
# suffice for most of Dynamo tracing purposes.
|
| 17 |
+
# https://github.com/pytorch/pytorch/blob/ccfde4dadfa3c342076a1ee387017f84dd4ad2f7/torch/csrc/autograd/python_variable.cpp#L597-L650
|
| 18 |
+
assert len(kwargs) == 0, (
|
| 19 |
+
"_make_subclass only supports requires_grad as keyword arg"
|
| 20 |
+
)
|
| 21 |
+
data = data.detach()
|
| 22 |
+
|
| 23 |
+
# Avoid unnecessary `requires_grad` mutation, which isn't supported in Dynamo.
|
| 24 |
+
if data.requires_grad != requires_grad:
|
| 25 |
+
data.requires_grad = requires_grad
|
| 26 |
+
|
| 27 |
+
# Dynamo can't yet handle upcasting to base tensor type via `as_subclass`.
|
| 28 |
+
if cls is torch.Tensor:
|
| 29 |
+
return torch.Tensor(data)
|
| 30 |
+
|
| 31 |
+
# Calling `as_subclass` because
|
| 32 |
+
# 1. Dynamo knows how to handle it
|
| 33 |
+
# 2. the C impls match at this point -- both `THPVariable_make_subclass` and
|
| 34 |
+
# `THPVariable_as_subclass` calls `THPVariable_NewWithVar`.
|
| 35 |
+
return data.as_subclass(cls)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"make_subclass",
|
| 40 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/precompile_context.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from abc import abstractmethod
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Generic, Optional, TypeVar
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch._dynamo.package import (
|
| 12 |
+
_BackendId,
|
| 13 |
+
_DynamoCacheEntry,
|
| 14 |
+
DynamoCache,
|
| 15 |
+
PrecompileCacheEntry,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
Classes and implementations related to precompile
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
T = TypeVar("T")
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class BackendCacheArtifact(Generic[T]):
|
| 29 |
+
"""
|
| 30 |
+
Represents a single serializable backend artifact from a dynamo backend.
|
| 31 |
+
Each BackendCacheArtifact has a key associated with it along with some
|
| 32 |
+
serializable content.
|
| 33 |
+
|
| 34 |
+
Example implementation:
|
| 35 |
+
|
| 36 |
+
class MyPrecompileCacheArtifact(PrecompileCacheArtifact[MySerializableType]):
|
| 37 |
+
my_field: int
|
| 38 |
+
|
| 39 |
+
def after_deserialization(self) -> MySerializableType:
|
| 40 |
+
result = pickle.loads(self.content)
|
| 41 |
+
# Do some extra work post deserialization
|
| 42 |
+
result.my_post_deserialization_function(self.my_field)
|
| 43 |
+
return result
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
key: str
|
| 47 |
+
content: Any
|
| 48 |
+
|
| 49 |
+
@abstractmethod
|
| 50 |
+
def after_deserialization(self) -> T:
|
| 51 |
+
"""
|
| 52 |
+
Code to be run after reading raw byte contents from disk.
|
| 53 |
+
Generally converts self.content from raw bytes back into its original form.
|
| 54 |
+
"""
|
| 55 |
+
...
|
| 56 |
+
|
| 57 |
+
def edit_contents(self, edit_fn: Callable[..., Any]) -> None:
|
| 58 |
+
"""
|
| 59 |
+
Edit the contents of the artifact.
|
| 60 |
+
"""
|
| 61 |
+
self.content = edit_fn(self.content)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class EagerCacheArtifact(BackendCacheArtifact[Any]):
|
| 65 |
+
def after_deserialization(self) -> Any:
|
| 66 |
+
return self.content
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BypassDynamoCacheEntry(Exception):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PrecompileContext:
|
| 74 |
+
"""
|
| 75 |
+
PrecompileContext is a special CacheArtifactManager for handling precompilation
|
| 76 |
+
It uses the same interface as CacheArtifactManager, but handles deserialization differently: instead
|
| 77 |
+
of placing each artifact into respective caches, it will stitch all the cache artifacts for a single key
|
| 78 |
+
together and place it into a global Precompile Cache.
|
| 79 |
+
|
| 80 |
+
PrecompileContext has two main portions: dynamo_cache_entries and backend_cache_artifacts.
|
| 81 |
+
When saving, PrecompileContext.serialize() will serialize all dynamo cache entries along with any PrecompileCacheArtifacts that
|
| 82 |
+
are needed to save those dynamo cache entries.
|
| 83 |
+
|
| 84 |
+
The following artifact types are supported by PrecompileContext:
|
| 85 |
+
- BundledAOTAutogradCacheArtifact
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
# Protected by the compile_lock
|
| 90 |
+
# _backend_artifacts_by_key organizes results by the key of each artifact.
|
| 91 |
+
# Each object here must be serializable
|
| 92 |
+
_backend_artifacts_by_key: dict[_BackendId, BackendCacheArtifact[Any]] = {}
|
| 93 |
+
|
| 94 |
+
# On call to `serialize()`, all cache artifacts in _dynamo_cache_entries are converted
|
| 95 |
+
# into DynamoCacheArtifacts and added to _new_cache_artifacts for serialization
|
| 96 |
+
_dynamo_cache_entries: dict[str, _DynamoCacheEntry] = {}
|
| 97 |
+
|
| 98 |
+
@classmethod
|
| 99 |
+
def clear(cls) -> None:
|
| 100 |
+
cls._backend_artifacts_by_key.clear()
|
| 101 |
+
cls._dynamo_cache_entries.clear()
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def record_artifact(
|
| 105 |
+
cls,
|
| 106 |
+
artifact: BackendCacheArtifact[Any],
|
| 107 |
+
) -> None:
|
| 108 |
+
"""
|
| 109 |
+
Records a backend artifact to be used with dynamo cache entries
|
| 110 |
+
"""
|
| 111 |
+
# Temporarily disable all dispatch modes (including FakeTensorMode) during
|
| 112 |
+
# deepcopy to avoid issues with cloning fake tensors (e.g., device mesh
|
| 113 |
+
# with meta tensors that fail when cloning due to device mismatches)
|
| 114 |
+
from torch.utils._mode_utils import no_dispatch
|
| 115 |
+
|
| 116 |
+
with no_dispatch():
|
| 117 |
+
cls._backend_artifacts_by_key[_BackendId(artifact.key)] = copy.deepcopy(
|
| 118 |
+
artifact
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
@classmethod
|
| 122 |
+
def record_dynamo_cache_entry(
|
| 123 |
+
cls, cache_entry: _DynamoCacheEntry, key: str
|
| 124 |
+
) -> None:
|
| 125 |
+
cls._dynamo_cache_entries[key] = cache_entry
|
| 126 |
+
|
| 127 |
+
@classmethod
|
| 128 |
+
def edit_artifact(cls, key: str, edit_fn: Callable[..., Any]) -> None:
|
| 129 |
+
"""
|
| 130 |
+
Edit the content of an existing artifact
|
| 131 |
+
"""
|
| 132 |
+
assert key in cls._backend_artifacts_by_key, f"Key {key} not found in artifacts"
|
| 133 |
+
artifact = cls._backend_artifacts_by_key[_BackendId(key)]
|
| 134 |
+
artifact.edit_contents(edit_fn)
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def serialize_artifact_by_key(cls, key: str) -> Optional[BackendCacheArtifact[Any]]:
|
| 138 |
+
"""
|
| 139 |
+
Return the backend cache artifact with the associated key
|
| 140 |
+
"""
|
| 141 |
+
return cls._backend_artifacts_by_key.get(_BackendId(key), None)
|
| 142 |
+
|
| 143 |
+
@staticmethod
|
| 144 |
+
def dump_debug_info(
|
| 145 |
+
dynamo_entries: dict[str, _DynamoCacheEntry],
|
| 146 |
+
backend_artifacts: dict[_BackendId, BackendCacheArtifact[Any]],
|
| 147 |
+
) -> dict[str, Any]:
|
| 148 |
+
"""
|
| 149 |
+
Return a JSON serializable debug dump of all entries in the precompile context
|
| 150 |
+
Called in serialize before serialization, and in populate_caches after deserialization
|
| 151 |
+
"""
|
| 152 |
+
# Print debug information
|
| 153 |
+
debug_info: defaultdict[str, list[Any]] = defaultdict(list)
|
| 154 |
+
for key, cache_entry in dynamo_entries.items():
|
| 155 |
+
info = cache_entry.debug_info()
|
| 156 |
+
info["key"] = key
|
| 157 |
+
debug_info["dynamo"].append(info)
|
| 158 |
+
|
| 159 |
+
for artifact in backend_artifacts.values():
|
| 160 |
+
debug_info["backends"].append(artifact.key)
|
| 161 |
+
|
| 162 |
+
return debug_info
|
| 163 |
+
|
| 164 |
+
@classmethod
|
| 165 |
+
def save_to_dynamo_cache(cls) -> dict[str, Any]:
|
| 166 |
+
precompile_cache_entries, debug_info = cls.create_cache_entries()
|
| 167 |
+
for key, entry in precompile_cache_entries.items():
|
| 168 |
+
DynamoCache.write(entry, key)
|
| 169 |
+
return debug_info
|
| 170 |
+
|
| 171 |
+
@classmethod
|
| 172 |
+
def create_cache_entries(
|
| 173 |
+
cls,
|
| 174 |
+
) -> tuple[dict[str, PrecompileCacheEntry], dict[str, Any]]:
|
| 175 |
+
"""
|
| 176 |
+
Grabs all the cache entries in the precompile context and
|
| 177 |
+
stitches them together into full PrecompileCacheEntries.
|
| 178 |
+
"""
|
| 179 |
+
dynamo_entries = cls._dynamo_cache_entries
|
| 180 |
+
backend_artifacts = cls._backend_artifacts_by_key
|
| 181 |
+
|
| 182 |
+
num_artifacts = len(dynamo_entries)
|
| 183 |
+
|
| 184 |
+
debug_info = PrecompileContext.dump_debug_info(
|
| 185 |
+
dynamo_entries, backend_artifacts
|
| 186 |
+
)
|
| 187 |
+
debug_str = json.dumps(
|
| 188 |
+
{
|
| 189 |
+
"num_entries": num_artifacts,
|
| 190 |
+
"artifacts": debug_info,
|
| 191 |
+
},
|
| 192 |
+
)
|
| 193 |
+
torch._logging.trace_structured(
|
| 194 |
+
"artifact",
|
| 195 |
+
metadata_fn=lambda: {
|
| 196 |
+
"name": "dynamo_cache_entries",
|
| 197 |
+
"encoding": "json",
|
| 198 |
+
},
|
| 199 |
+
payload_fn=lambda: debug_str,
|
| 200 |
+
expect_trace_id=False,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
precompile_cache_entries = {}
|
| 204 |
+
|
| 205 |
+
for key, cache_entry in dynamo_entries.items():
|
| 206 |
+
try:
|
| 207 |
+
result = PrecompileCacheEntry.from_cache_entry(
|
| 208 |
+
cache_entry, backend_artifacts
|
| 209 |
+
)
|
| 210 |
+
if result is not None:
|
| 211 |
+
precompile_cache_entries[key] = result
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.warning("Failed to create cache entry %s", key, exc_info=True)
|
| 214 |
+
|
| 215 |
+
error = e
|
| 216 |
+
data = json.dumps(
|
| 217 |
+
{
|
| 218 |
+
"key": key,
|
| 219 |
+
"error": str(error),
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
torch._logging.trace_structured(
|
| 223 |
+
"artifact",
|
| 224 |
+
metadata_fn=lambda: {
|
| 225 |
+
"name": "dynamo_cache_exception",
|
| 226 |
+
"encoding": "json",
|
| 227 |
+
},
|
| 228 |
+
payload_fn=lambda: data,
|
| 229 |
+
)
|
| 230 |
+
continue
|
| 231 |
+
return precompile_cache_entries, debug_info
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/profiler.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dynamo profiling implementation.
|
| 3 |
+
|
| 4 |
+
This module provides profiling functionality for Dynamo, including:
|
| 5 |
+
- ProfileMetrics: Class for collecting and aggregating performance metrics like
|
| 6 |
+
execution time, operator counts, and fusion statistics
|
| 7 |
+
- ProfileResult: Class for analyzing and reporting profiling results
|
| 8 |
+
- Utilities for tracking missed/uncaptured operations
|
| 9 |
+
- Functions for instrumenting FX graphs with profiling capabilities
|
| 10 |
+
|
| 11 |
+
The profiler helps measure and optimize the performance of Dynamo-compiled code
|
| 12 |
+
by tracking both captured and total operations, timing, and graph statistics.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import dataclasses
|
| 18 |
+
import os
|
| 19 |
+
from typing import Any
|
| 20 |
+
from typing_extensions import Self
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from .utils import print_once
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclasses.dataclass
|
| 28 |
+
class ProfileMetrics:
|
| 29 |
+
microseconds: float = 0.0
|
| 30 |
+
operators: int = 0
|
| 31 |
+
fusions: int = 0
|
| 32 |
+
graphs: int = 0
|
| 33 |
+
|
| 34 |
+
def __iadd__(self, other: Self) -> Self:
|
| 35 |
+
self.microseconds += other.microseconds
|
| 36 |
+
self.operators += other.operators
|
| 37 |
+
self.fusions += other.fusions
|
| 38 |
+
return self
|
| 39 |
+
|
| 40 |
+
def __add__(self, other: ProfileMetrics) -> ProfileMetrics:
|
| 41 |
+
assert isinstance(other, ProfileMetrics)
|
| 42 |
+
return ProfileMetrics(
|
| 43 |
+
self.microseconds + other.microseconds,
|
| 44 |
+
self.operators + other.operators,
|
| 45 |
+
self.fusions + other.fusions,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def __truediv__(self, other: Any) -> ProfileMetrics:
|
| 49 |
+
if isinstance(other, int):
|
| 50 |
+
other = ProfileMetrics(other, other, other)
|
| 51 |
+
return ProfileMetrics(
|
| 52 |
+
# pyrefly: ignore [no-matching-overload]
|
| 53 |
+
self.microseconds / max(1, other.microseconds),
|
| 54 |
+
# pyrefly: ignore [bad-argument-type]
|
| 55 |
+
self.operators / max(1, other.operators),
|
| 56 |
+
# pyrefly: ignore [bad-argument-type]
|
| 57 |
+
self.fusions / max(1, other.fusions),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def __str__(self) -> str:
|
| 61 |
+
return f"{self.operators:4.0%} ops {self.microseconds:4.0%} time"
|
| 62 |
+
|
| 63 |
+
def tocsv(self) -> list[float]:
|
| 64 |
+
return [self.operators, self.microseconds]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ProfileResult:
|
| 68 |
+
def __init__(
|
| 69 |
+
self, captured: ProfileMetrics, total: ProfileMetrics, unique_graphs: int
|
| 70 |
+
) -> None:
|
| 71 |
+
self.captured: ProfileMetrics = captured or ProfileMetrics()
|
| 72 |
+
self.total: ProfileMetrics = total or ProfileMetrics()
|
| 73 |
+
self.unique_graphs: int = unique_graphs
|
| 74 |
+
|
| 75 |
+
def __iadd__(self, other: Self) -> Self:
|
| 76 |
+
self.captured += other.captured
|
| 77 |
+
self.total += other.total
|
| 78 |
+
self.unique_graphs += other.unique_graphs
|
| 79 |
+
return self
|
| 80 |
+
|
| 81 |
+
def percent(self) -> ProfileMetrics:
|
| 82 |
+
return self.captured / self.total
|
| 83 |
+
|
| 84 |
+
def __str__(self) -> str:
|
| 85 |
+
return (
|
| 86 |
+
f"{self.unique_graphs:2} graphs {self.captured.graphs:2} graph calls "
|
| 87 |
+
f"{self.captured.operators:4}/{self.total.operators:4} = "
|
| 88 |
+
+ str(self.percent())
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def tocsv(self) -> list[Any]:
|
| 92 |
+
return [
|
| 93 |
+
self.unique_graphs,
|
| 94 |
+
self.captured.graphs,
|
| 95 |
+
self.captured.operators,
|
| 96 |
+
self.total.operators,
|
| 97 |
+
] + self.percent().tocsv()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def should_print_missing() -> bool:
|
| 101 |
+
return os.environ.get("TORCHDYNAMO_PRINT_MISSING") == "1"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def print_missing(stack: list[str]) -> None:
|
| 105 |
+
if any("/torch/autograd/profiler.py" in x for x in stack):
|
| 106 |
+
return
|
| 107 |
+
stack = [
|
| 108 |
+
x for x in stack if ("<built-in" not in x and "site-packages/torch/" not in x)
|
| 109 |
+
]
|
| 110 |
+
print_once("MISSING", " >> ".join(stack[-3:]))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class Profiler:
|
| 114 |
+
unique_graphs: int = 0
|
| 115 |
+
|
| 116 |
+
def __init__(self) -> None:
|
| 117 |
+
self.prof = torch.profiler.profile(
|
| 118 |
+
activities=[torch.profiler.ProfilerActivity.CPU],
|
| 119 |
+
with_stack=should_print_missing(),
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def results(self) -> ProfileResult:
|
| 123 |
+
captured_regions = 0
|
| 124 |
+
captured_ops = 0
|
| 125 |
+
captured_microseconds = 0
|
| 126 |
+
total_ops = 0
|
| 127 |
+
total_microseconds = 0
|
| 128 |
+
|
| 129 |
+
last_op_end_time = -1
|
| 130 |
+
captured_region_end_time = -1
|
| 131 |
+
events = sorted(self.prof.events(), key=lambda x: x.time_range.start)
|
| 132 |
+
for e in events:
|
| 133 |
+
if e.name == "TORCHDYNAMO":
|
| 134 |
+
captured_region_end_time = e.time_range.end
|
| 135 |
+
captured_regions += 1
|
| 136 |
+
# ignore `handle = torch.zeros(1)` in record_function.__init__()
|
| 137 |
+
total_ops -= 1
|
| 138 |
+
elif e.time_range.start >= last_op_end_time:
|
| 139 |
+
last_op_end_time = e.time_range.end
|
| 140 |
+
if e.time_range.end <= captured_region_end_time:
|
| 141 |
+
captured_ops += 1
|
| 142 |
+
captured_microseconds += e.time_range.elapsed_us()
|
| 143 |
+
elif should_print_missing():
|
| 144 |
+
print_missing(e.stack)
|
| 145 |
+
total_ops += 1
|
| 146 |
+
total_microseconds += e.time_range.elapsed_us()
|
| 147 |
+
else:
|
| 148 |
+
pass # ops recursively called from other ops (ignored)
|
| 149 |
+
|
| 150 |
+
unique_graphs = Profiler.unique_graphs
|
| 151 |
+
Profiler.unique_graphs = 0
|
| 152 |
+
# we counted one extra op that is part of the profiler setup code
|
| 153 |
+
total_ops -= 1
|
| 154 |
+
|
| 155 |
+
return ProfileResult(
|
| 156 |
+
captured=ProfileMetrics(
|
| 157 |
+
microseconds=captured_microseconds,
|
| 158 |
+
operators=captured_ops,
|
| 159 |
+
fusions=captured_ops - captured_regions,
|
| 160 |
+
graphs=captured_regions,
|
| 161 |
+
),
|
| 162 |
+
total=ProfileMetrics(
|
| 163 |
+
microseconds=total_microseconds,
|
| 164 |
+
operators=total_ops,
|
| 165 |
+
fusions=total_ops - 1,
|
| 166 |
+
),
|
| 167 |
+
unique_graphs=unique_graphs,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def fx_insert_profiling(gm: torch.fx.GraphModule, example_inputs: list[Any]) -> Any:
|
| 172 |
+
def _wrapped(*args: Any) -> Any:
|
| 173 |
+
with torch.profiler.record_function("TORCHDYNAMO"):
|
| 174 |
+
return gm.forward(*args)
|
| 175 |
+
|
| 176 |
+
Profiler.unique_graphs += 1
|
| 177 |
+
return _wrapped
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/replay_record.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python execution state recording and replay functionality.
|
| 3 |
+
|
| 4 |
+
This module provides mechanisms for capturing and replaying Python execution state:
|
| 5 |
+
|
| 6 |
+
- ModuleRecord: Tracks module access patterns and attribute usage
|
| 7 |
+
- DummyModule: Lightweight module substitute for replay
|
| 8 |
+
- ExecutionRecord: Manages execution context including globals, locals and builtins
|
| 9 |
+
- ExecutionRecorder: Records variable states and module access during execution
|
| 10 |
+
|
| 11 |
+
The module enables serialization and reproduction of Python execution environments,
|
| 12 |
+
particularly useful for debugging and testing frameworks that need to capture
|
| 13 |
+
and recreate specific program states.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import dataclasses
|
| 17 |
+
from dataclasses import field
|
| 18 |
+
from io import BufferedReader, BufferedWriter
|
| 19 |
+
from types import CellType, CodeType, ModuleType
|
| 20 |
+
from typing import Any, IO, Union
|
| 21 |
+
from typing_extensions import Self
|
| 22 |
+
|
| 23 |
+
from torch.utils._import_utils import import_dill
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
dill = import_dill()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclasses.dataclass
|
| 30 |
+
class ModuleRecord:
|
| 31 |
+
module: ModuleType
|
| 32 |
+
accessed_attrs: dict[str, Any] = field(default_factory=dict)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclasses.dataclass
|
| 36 |
+
class DummyModule:
|
| 37 |
+
name: str
|
| 38 |
+
is_torch: bool = False
|
| 39 |
+
value: object = None
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def __name__(self) -> str:
|
| 43 |
+
return self.name
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclasses.dataclass
|
| 47 |
+
class ExecutionRecord:
|
| 48 |
+
code: CodeType
|
| 49 |
+
closure: tuple[CellType]
|
| 50 |
+
globals: dict[str, Any] = field(default_factory=dict)
|
| 51 |
+
locals: dict[str, Any] = field(default_factory=dict)
|
| 52 |
+
builtins: dict[str, Any] = field(default_factory=dict)
|
| 53 |
+
code_options: dict[str, Any] = field(default_factory=dict)
|
| 54 |
+
|
| 55 |
+
def dump(self, f: Union[IO[str], BufferedWriter]) -> None:
|
| 56 |
+
assert dill is not None, "replay_record requires `pip install dill`"
|
| 57 |
+
dill.dump(self, f)
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def load(cls, f: Union[IO[bytes], BufferedReader]) -> Self:
|
| 61 |
+
assert dill is not None, "replay_record requires `pip install dill`"
|
| 62 |
+
return dill.load(f)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclasses.dataclass
|
| 66 |
+
class ExecutionRecorder:
|
| 67 |
+
LOCAL_MOD_PREFIX = "___local_mod_"
|
| 68 |
+
|
| 69 |
+
code: CodeType
|
| 70 |
+
closure: tuple[CellType]
|
| 71 |
+
globals: dict[str, Any] = field(default_factory=dict)
|
| 72 |
+
locals: dict[str, Any] = field(default_factory=dict)
|
| 73 |
+
builtins: dict[str, Any] = field(default_factory=dict)
|
| 74 |
+
code_options: dict[str, Any] = field(default_factory=dict)
|
| 75 |
+
name_to_modrec: dict[str, ModuleRecord] = field(default_factory=dict)
|
| 76 |
+
|
| 77 |
+
def add_local_var(self, name: str, var: Any) -> None:
|
| 78 |
+
if isinstance(var, ModuleType):
|
| 79 |
+
self.locals[name] = self._add_mod(var)
|
| 80 |
+
else:
|
| 81 |
+
self.locals[name] = var
|
| 82 |
+
|
| 83 |
+
def add_global_var(self, name: str, var: Any) -> None:
|
| 84 |
+
if isinstance(var, ModuleType):
|
| 85 |
+
self.globals[name] = self._add_mod(var)
|
| 86 |
+
else:
|
| 87 |
+
self.globals[name] = var
|
| 88 |
+
|
| 89 |
+
def add_local_mod(self, name: str, mod: ModuleType) -> None:
|
| 90 |
+
assert isinstance(mod, ModuleType)
|
| 91 |
+
self.add_global_var(name, mod)
|
| 92 |
+
|
| 93 |
+
def record_module_access(self, mod: ModuleType, name: str, val: Any) -> None:
|
| 94 |
+
if isinstance(val, ModuleType):
|
| 95 |
+
self.name_to_modrec[mod.__name__].accessed_attrs[name] = self._add_mod(val)
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
if mod.__name__ in self.name_to_modrec:
|
| 99 |
+
self.name_to_modrec[mod.__name__].accessed_attrs[name] = val
|
| 100 |
+
|
| 101 |
+
def get_record(self) -> ExecutionRecord:
|
| 102 |
+
return ExecutionRecord(
|
| 103 |
+
self.code,
|
| 104 |
+
self.closure,
|
| 105 |
+
ExecutionRecorder._resolve_modules(self.globals),
|
| 106 |
+
ExecutionRecorder._resolve_modules(self.locals),
|
| 107 |
+
self.builtins.copy(),
|
| 108 |
+
self.code_options.copy(),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def _add_mod(self, mod: ModuleType) -> ModuleRecord:
|
| 112 |
+
if mod.__name__ not in self.name_to_modrec:
|
| 113 |
+
self.name_to_modrec[mod.__name__] = ModuleRecord(mod)
|
| 114 |
+
|
| 115 |
+
return self.name_to_modrec[mod.__name__]
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def _resolve_modules(cls, vars: dict[str, Any]) -> dict[str, Any]:
|
| 119 |
+
def resolve_module(var: Any) -> Any:
|
| 120 |
+
if not isinstance(var, ModuleRecord):
|
| 121 |
+
return var
|
| 122 |
+
|
| 123 |
+
dummy_mod = DummyModule(var.module.__name__)
|
| 124 |
+
for attr_name, attr_value in var.accessed_attrs.items():
|
| 125 |
+
attr_value = resolve_module(attr_value)
|
| 126 |
+
dummy_mod.__setattr__(attr_name, attr_value)
|
| 127 |
+
|
| 128 |
+
return dummy_mod
|
| 129 |
+
|
| 130 |
+
return {k: resolve_module(v) for k, v in vars.items()}
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/after_aot.py
ADDED
|
@@ -0,0 +1,1281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities for reproducing and debugging issues in PyTorch's Dynamo AOT compilation.
|
| 3 |
+
|
| 4 |
+
This module provides tools and infrastructure for:
|
| 5 |
+
1. Generating minimal reproducible test cases ("repros") from failing compilations
|
| 6 |
+
2. Analyzing accuracy issues between eager and compiled execution
|
| 7 |
+
3. Minifying large models/inputs to isolate problematic patterns
|
| 8 |
+
4. Debugging compiler errors and accuracy divergences
|
| 9 |
+
|
| 10 |
+
The main components include:
|
| 11 |
+
- Repro generation: Creates standalone Python files that reproduce compiler issues
|
| 12 |
+
- Minification: Reduces large graphs to minimal failing examples
|
| 13 |
+
- Accuracy analysis: Compares compiled vs eager execution, with fp64 reference
|
| 14 |
+
- Debug tools: Dumps graph state, tracks intermediates, analyzes divergences
|
| 15 |
+
|
| 16 |
+
This is primarily used by PyTorch developers and researchers to debug issues in
|
| 17 |
+
the Dynamo AOT compilation pipeline, particularly for the Inductor backend.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import copy
|
| 24 |
+
import functools
|
| 25 |
+
import io
|
| 26 |
+
import logging
|
| 27 |
+
import os
|
| 28 |
+
import shutil
|
| 29 |
+
import subprocess
|
| 30 |
+
import sys
|
| 31 |
+
import textwrap
|
| 32 |
+
import uuid
|
| 33 |
+
from importlib import import_module
|
| 34 |
+
from tempfile import TemporaryFile
|
| 35 |
+
from typing import Any, IO, Optional, TYPE_CHECKING, Union
|
| 36 |
+
from typing_extensions import Unpack
|
| 37 |
+
|
| 38 |
+
import sympy
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from triton.runtime.autotuner import Autotuner, Heuristics
|
| 43 |
+
from triton.runtime.jit import JITFunction
|
| 44 |
+
except ImportError:
|
| 45 |
+
|
| 46 |
+
class Autotuner: # type: ignore[no-redef]
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
class JITFunction: # type: ignore[no-redef]
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
class Heuristics: # type: ignore[no-redef]
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
import torch
|
| 57 |
+
import torch.fx as fx
|
| 58 |
+
import torch.nn as nn
|
| 59 |
+
from torch._dynamo.debug_utils import (
|
| 60 |
+
_cuda_system_info_comment,
|
| 61 |
+
AccuracyError,
|
| 62 |
+
backend_accuracy_fails,
|
| 63 |
+
BuckTargetWriter,
|
| 64 |
+
cast_to_fp64,
|
| 65 |
+
extra_deps,
|
| 66 |
+
extra_imports,
|
| 67 |
+
generate_config_string,
|
| 68 |
+
generate_env_vars_string,
|
| 69 |
+
helper_for_dump_minify,
|
| 70 |
+
InputReader,
|
| 71 |
+
InputWriter,
|
| 72 |
+
MAX_CONSTANT_NUMEL_INLINE,
|
| 73 |
+
minifier_dir,
|
| 74 |
+
NNModuleToString,
|
| 75 |
+
NopInputReader,
|
| 76 |
+
same_two_models,
|
| 77 |
+
)
|
| 78 |
+
from torch._dynamo.utils import clone_inputs, counters, same
|
| 79 |
+
from torch._environment import is_fbcode
|
| 80 |
+
from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table
|
| 81 |
+
from torch._inductor.cpp_builder import normalize_path_separator
|
| 82 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 83 |
+
from torch._ops import OpOverload
|
| 84 |
+
from torch.fx.experimental.proxy_tensor import make_fx
|
| 85 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 86 |
+
fx_placeholder_targets,
|
| 87 |
+
has_free_symbols,
|
| 88 |
+
)
|
| 89 |
+
from torch.hub import tqdm
|
| 90 |
+
|
| 91 |
+
from .. import config
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if TYPE_CHECKING:
|
| 95 |
+
from collections.abc import Callable, Sequence
|
| 96 |
+
|
| 97 |
+
from torch._inductor.compile_fx import _CompileFxCallable, _CompileFxKwargs
|
| 98 |
+
from torch._inductor.output_code import OutputCode
|
| 99 |
+
from torch._inductor.utils import InputType
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
log = logging.getLogger(__name__)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
inductor_config = import_module("torch._inductor.config")
|
| 106 |
+
use_buck = is_fbcode()
|
| 107 |
+
|
| 108 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 109 |
+
# MAIN ENTRY POINT
|
| 110 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def wrap_compiler_debug(
|
| 114 |
+
unconfigured_compiler_fn: _CompileFxCallable,
|
| 115 |
+
compiler_name: str,
|
| 116 |
+
) -> _CompileFxCallable:
|
| 117 |
+
"""
|
| 118 |
+
Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both
|
| 119 |
+
forward and backward call separately with the backend compiler_fn - like
|
| 120 |
+
inductor or nvfuser. Intercepting after Aot Autograd presents neat
|
| 121 |
+
abstraction, where all the params are lifted as graph inputs, making it easy
|
| 122 |
+
to save the graph as a string.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
@functools.wraps(unconfigured_compiler_fn)
|
| 126 |
+
def debug_wrapper(
|
| 127 |
+
gm: torch.fx.GraphModule,
|
| 128 |
+
example_inputs: Sequence[InputType],
|
| 129 |
+
**kwargs: Unpack[_CompileFxKwargs],
|
| 130 |
+
) -> OutputCode:
|
| 131 |
+
from torch._subclasses import FakeTensorMode
|
| 132 |
+
|
| 133 |
+
compiler_fn = functools.partial(unconfigured_compiler_fn, **kwargs)
|
| 134 |
+
|
| 135 |
+
from torch._functorch.aot_autograd import get_aot_graph_name
|
| 136 |
+
|
| 137 |
+
graph_name = get_aot_graph_name()
|
| 138 |
+
|
| 139 |
+
# TODO: why do we need to deepcopy the original graph?
|
| 140 |
+
orig_graph = copy.deepcopy(gm.graph)
|
| 141 |
+
assert config.repro_after in ("dynamo", "aot", None)
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
# Call the compiler_fn - which is either aot_autograd or inductor
|
| 145 |
+
# with fake inputs
|
| 146 |
+
inner_compiled_fn = compiler_fn(gm, example_inputs)
|
| 147 |
+
except Exception:
|
| 148 |
+
# TODO: Failures here are troublesome because no real inputs,
|
| 149 |
+
# need a different serialization strategy
|
| 150 |
+
if config.repro_after == "aot":
|
| 151 |
+
if config.repro_level == 1:
|
| 152 |
+
dump_compiler_graph_state(
|
| 153 |
+
fx.GraphModule(gm, orig_graph),
|
| 154 |
+
example_inputs,
|
| 155 |
+
compiler_name,
|
| 156 |
+
)
|
| 157 |
+
elif config.repro_level == 2:
|
| 158 |
+
dump_to_minify(
|
| 159 |
+
fx.GraphModule(gm, orig_graph),
|
| 160 |
+
example_inputs,
|
| 161 |
+
compiler_name,
|
| 162 |
+
)
|
| 163 |
+
log.error("CompilerError")
|
| 164 |
+
raise
|
| 165 |
+
|
| 166 |
+
# We may run regular PyTorch compute that may trigger Dynamo, do NOT
|
| 167 |
+
# recursively attempt to accuracy minify in that case!
|
| 168 |
+
def deferred_for_real_inputs(
|
| 169 |
+
real_inputs: Sequence[InputType], **_kwargs: object
|
| 170 |
+
) -> Any:
|
| 171 |
+
# This is a bit obscure: if we recursively try to accuracy minify
|
| 172 |
+
# the SAME function, this would trigger. But most of the time
|
| 173 |
+
# we should never hit this branch
|
| 174 |
+
assert not _kwargs
|
| 175 |
+
if config.repro_after != "aot":
|
| 176 |
+
assert not isinstance(inner_compiled_fn, str)
|
| 177 |
+
return inner_compiled_fn(real_inputs)
|
| 178 |
+
with config.patch(repro_after=None):
|
| 179 |
+
return inner_debug_fn(real_inputs)
|
| 180 |
+
|
| 181 |
+
def inner_debug_fn(real_inputs: Sequence[InputType]) -> Any:
|
| 182 |
+
"""
|
| 183 |
+
Aot Autograd fw_compiler and bw_compiler can have fake tensors. So,
|
| 184 |
+
example_inputs can be fake tensors. We can call compiler_fn (which is
|
| 185 |
+
inductor or nvfuser) with fake tensors but the actually compiled_fn
|
| 186 |
+
should be called with real tensors. Therefore, the actual invocation
|
| 187 |
+
is deferred.
|
| 188 |
+
"""
|
| 189 |
+
# Copy the tensor attrs like shape, stride etc by converting to Fake Tensor
|
| 190 |
+
# because inductor clears the tensor list in its codegen. And example_inputs
|
| 191 |
+
# are available only for the first invocation.
|
| 192 |
+
fake_mode = FakeTensorMode()
|
| 193 |
+
copy_tensor_attrs = [
|
| 194 |
+
fake_mode.from_tensor(x) if isinstance(x, torch.Tensor) else x
|
| 195 |
+
for x in real_inputs
|
| 196 |
+
]
|
| 197 |
+
if config.repro_level == 3:
|
| 198 |
+
# Always dump the original module in case we have segfaults
|
| 199 |
+
dump_to_minify(
|
| 200 |
+
fx.GraphModule(gm, orig_graph), real_inputs, compiler_name
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
if config.repro_level == 4:
|
| 204 |
+
if compiler_name != "inductor":
|
| 205 |
+
raise NotImplementedError(
|
| 206 |
+
"Accuracy minification is supported for inductor only"
|
| 207 |
+
)
|
| 208 |
+
failed = not same_two_models(
|
| 209 |
+
gm,
|
| 210 |
+
inner_compiled_fn, # type: ignore[arg-type]
|
| 211 |
+
real_inputs,
|
| 212 |
+
only_fwd=True,
|
| 213 |
+
ignore_non_fp=config.repro_ignore_non_fp,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if failed:
|
| 217 |
+
log.warning(
|
| 218 |
+
"Accuracy failed for the AOT Autograd graph %s", graph_name
|
| 219 |
+
)
|
| 220 |
+
dump_compiler_graph_state(
|
| 221 |
+
fx.GraphModule(gm, orig_graph),
|
| 222 |
+
real_inputs,
|
| 223 |
+
f"{compiler_name}_accuracy",
|
| 224 |
+
)
|
| 225 |
+
dump_to_minify(
|
| 226 |
+
fx.GraphModule(gm, orig_graph),
|
| 227 |
+
real_inputs,
|
| 228 |
+
f"{compiler_name}_accuracy",
|
| 229 |
+
)
|
| 230 |
+
raise AccuracyError("Bad accuracy detected")
|
| 231 |
+
else:
|
| 232 |
+
# Call the compiled function with real inputs
|
| 233 |
+
return inner_compiled_fn(real_inputs) # type: ignore[operator]
|
| 234 |
+
else:
|
| 235 |
+
try:
|
| 236 |
+
# Call the compiled function with real inputs
|
| 237 |
+
out = inner_compiled_fn(real_inputs) # type: ignore[operator]
|
| 238 |
+
# sync cuda kernels to ensure IMA detection
|
| 239 |
+
for arg in example_inputs:
|
| 240 |
+
if isinstance(arg, torch.Tensor) and arg.is_cuda:
|
| 241 |
+
torch.cuda.synchronize()
|
| 242 |
+
break
|
| 243 |
+
return out
|
| 244 |
+
except Exception:
|
| 245 |
+
if config.repro_level == 1:
|
| 246 |
+
dump_compiler_graph_state(
|
| 247 |
+
fx.GraphModule(gm, orig_graph),
|
| 248 |
+
copy_tensor_attrs,
|
| 249 |
+
compiler_name,
|
| 250 |
+
)
|
| 251 |
+
elif config.repro_level == 2:
|
| 252 |
+
dump_to_minify(
|
| 253 |
+
fx.GraphModule(gm, orig_graph),
|
| 254 |
+
copy_tensor_attrs,
|
| 255 |
+
compiler_name,
|
| 256 |
+
)
|
| 257 |
+
raise
|
| 258 |
+
|
| 259 |
+
if config.repro_after == "aot":
|
| 260 |
+
compiled_fn = deferred_for_real_inputs
|
| 261 |
+
compiled_fn._boxed_call = True # type: ignore[attr-defined]
|
| 262 |
+
return compiled_fn # type: ignore[return-value]
|
| 263 |
+
else:
|
| 264 |
+
return inner_compiled_fn
|
| 265 |
+
|
| 266 |
+
return debug_wrapper
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 270 |
+
# DUMP REPROS
|
| 271 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def maybe_fbcode_instructions() -> str:
|
| 275 |
+
if is_fbcode():
|
| 276 |
+
extra_deps_formatted = "\n".join([f' "{dep}",' for dep in extra_deps])
|
| 277 |
+
if len(extra_deps_formatted) > 0:
|
| 278 |
+
extra_deps_formatted = "\n" + extra_deps_formatted
|
| 279 |
+
return f"""\
|
| 280 |
+
\"\"\"
|
| 281 |
+
To run this script in fbcode:
|
| 282 |
+
- Create a directory (//scripts/{{your_unixname}}/repro)
|
| 283 |
+
- Put this file in scripts/{{your_unixname}}/repro/fx_graph_runnable.py
|
| 284 |
+
- Add a TARGETS file that looks like the following
|
| 285 |
+
- `buck2 run //scripts/{{your_unixname}}/repro:repro`
|
| 286 |
+
|
| 287 |
+
NOTE: you may need additional deps to actually be able to run the script.
|
| 288 |
+
```
|
| 289 |
+
# Contents of TARGETS file
|
| 290 |
+
load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary")
|
| 291 |
+
|
| 292 |
+
python_binary(
|
| 293 |
+
name = "repro",
|
| 294 |
+
main_src = "fx_graph_runnable.py",
|
| 295 |
+
deps = [
|
| 296 |
+
"//caffe2:torch",{extra_deps_formatted}
|
| 297 |
+
],
|
| 298 |
+
)
|
| 299 |
+
```
|
| 300 |
+
\"\"\"
|
| 301 |
+
"""
|
| 302 |
+
else:
|
| 303 |
+
return ""
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def generate_compiler_repro_string(
|
| 307 |
+
gm: torch.fx.GraphModule,
|
| 308 |
+
args: Sequence[Any],
|
| 309 |
+
*,
|
| 310 |
+
stable_output: bool = False,
|
| 311 |
+
save_dir: Optional[str] = None,
|
| 312 |
+
stable_hash: bool = False,
|
| 313 |
+
has_distributed_ops: bool = False,
|
| 314 |
+
) -> str:
|
| 315 |
+
if save_dir is not None:
|
| 316 |
+
save_dir = normalize_path_separator(save_dir)
|
| 317 |
+
# Add distributed imports if needed
|
| 318 |
+
distributed_imports = ""
|
| 319 |
+
if has_distributed_ops:
|
| 320 |
+
distributed_imports = textwrap.dedent(
|
| 321 |
+
"""
|
| 322 |
+
import torch.distributed as dist
|
| 323 |
+
from torch.testing._internal.distributed.fake_pg import FakeStore
|
| 324 |
+
"""
|
| 325 |
+
).strip()
|
| 326 |
+
|
| 327 |
+
triton_imports = ""
|
| 328 |
+
|
| 329 |
+
if len(kernel_side_table.id_to_kernel) > 0:
|
| 330 |
+
triton_imports = textwrap.dedent(
|
| 331 |
+
"""
|
| 332 |
+
import triton
|
| 333 |
+
import triton.language as tl
|
| 334 |
+
"""
|
| 335 |
+
).strip()
|
| 336 |
+
|
| 337 |
+
model_str = textwrap.dedent(
|
| 338 |
+
f"""
|
| 339 |
+
{generate_env_vars_string(stable_output=stable_output)}
|
| 340 |
+
import torch
|
| 341 |
+
from torch import tensor, device
|
| 342 |
+
import torch.fx as fx
|
| 343 |
+
from torch._dynamo.testing import rand_strided
|
| 344 |
+
from math import inf
|
| 345 |
+
import torch._inductor.inductor_prims
|
| 346 |
+
{distributed_imports}
|
| 347 |
+
{triton_imports}
|
| 348 |
+
|
| 349 |
+
{generate_config_string(stable_output=stable_output)}
|
| 350 |
+
|
| 351 |
+
isolate_fails_code_str = None
|
| 352 |
+
|
| 353 |
+
{extra_imports}
|
| 354 |
+
|
| 355 |
+
{maybe_fbcode_instructions()}
|
| 356 |
+
"""
|
| 357 |
+
)
|
| 358 |
+
model_str += textwrap.dedent(
|
| 359 |
+
"""
|
| 360 |
+
if "__compile_source__" in globals():
|
| 361 |
+
import inspect as __after_aot_inspect
|
| 362 |
+
import linecache as __after_aot_linecache
|
| 363 |
+
__after_aot_filename = __after_aot_inspect.currentframe().f_code.co_filename
|
| 364 |
+
__after_aot_linecache.cache[__after_aot_filename] = (
|
| 365 |
+
len(__compile_source__),
|
| 366 |
+
None,
|
| 367 |
+
__compile_source__.splitlines(True),
|
| 368 |
+
__after_aot_filename,
|
| 369 |
+
)
|
| 370 |
+
"""
|
| 371 |
+
)
|
| 372 |
+
if not stable_output:
|
| 373 |
+
model_str += f"# torch version: {torch.version.__version__}\n"
|
| 374 |
+
if hasattr(torch.version, "cuda"):
|
| 375 |
+
model_str += f"# torch cuda version: {torch.version.cuda}\n"
|
| 376 |
+
if hasattr(torch.version, "git_version"):
|
| 377 |
+
model_str += f"# torch git version: {torch.version.git_version}\n\n\n"
|
| 378 |
+
model_str += _cuda_system_info_comment()
|
| 379 |
+
|
| 380 |
+
kernel_side_table_prefix = (
|
| 381 |
+
"torch._higher_order_ops.triton_kernel_wrap.kernel_side_table"
|
| 382 |
+
)
|
| 383 |
+
# Track which grid entry corresponds to the best config
|
| 384 |
+
for id in kernel_side_table.id_to_kernel:
|
| 385 |
+
kernel = kernel_side_table.get_kernel(id)
|
| 386 |
+
|
| 387 |
+
try:
|
| 388 |
+
if isinstance(kernel, Autotuner):
|
| 389 |
+
# pyrefly: ignore [missing-attribute]
|
| 390 |
+
if isinstance(kernel.fn, Heuristics):
|
| 391 |
+
model_str += "ERROR: Repro will not work as intended, "
|
| 392 |
+
model_str += "triton.runtime.autotuner.Heuristics is not currently supported\n"
|
| 393 |
+
break
|
| 394 |
+
|
| 395 |
+
config_strs = []
|
| 396 |
+
# pyrefly: ignore [missing-attribute]
|
| 397 |
+
for kernel_config in kernel.configs:
|
| 398 |
+
# pyrefly: ignore [bad-argument-type]
|
| 399 |
+
config_strs.append(f"""triton.Config(
|
| 400 |
+
{str(kernel_config.kwargs)},
|
| 401 |
+
num_warps={kernel_config.num_warps},
|
| 402 |
+
num_stages={kernel_config.num_stages},
|
| 403 |
+
)""")
|
| 404 |
+
|
| 405 |
+
config_str = ",".join(config_strs)
|
| 406 |
+
model_str += textwrap.dedent(f"""
|
| 407 |
+
@triton.autotune(
|
| 408 |
+
configs=[
|
| 409 |
+
{config_str}
|
| 410 |
+
],
|
| 411 |
+
key=[]
|
| 412 |
+
)
|
| 413 |
+
""").strip()
|
| 414 |
+
|
| 415 |
+
model_str += "\n@triton.jit\n"
|
| 416 |
+
# pyrefly: ignore [missing-attribute]
|
| 417 |
+
src_code = kernel.src if isinstance(kernel, JITFunction) else kernel.fn.src
|
| 418 |
+
fn_name = (
|
| 419 |
+
# pyrefly: ignore [missing-attribute]
|
| 420 |
+
kernel._fn_name
|
| 421 |
+
if isinstance(kernel, JITFunction)
|
| 422 |
+
# pyrefly: ignore # missing-attribute
|
| 423 |
+
else kernel.fn._fn_name
|
| 424 |
+
)
|
| 425 |
+
fn_name = fn_name.split(".")[-1]
|
| 426 |
+
|
| 427 |
+
model_str += src_code
|
| 428 |
+
model_str += "\n"
|
| 429 |
+
model_str += f"{kernel_side_table_prefix}.add_kernel({fn_name})\n"
|
| 430 |
+
except AttributeError as e:
|
| 431 |
+
model_str += "ERROR: Repro will not work as intended, "
|
| 432 |
+
model_str += f"User defined triton kernel exception: {e}\n"
|
| 433 |
+
|
| 434 |
+
# pyrefly: ignore [unbound-name]
|
| 435 |
+
if len(kernel_side_table.constant_args) > 0:
|
| 436 |
+
# pyrefly: ignore [unbound-name]
|
| 437 |
+
model_str += f"{kernel_side_table_prefix}.constant_args={kernel_side_table.constant_args}\n"
|
| 438 |
+
|
| 439 |
+
model_str += NNModuleToString.convert(gm)
|
| 440 |
+
|
| 441 |
+
writer = InputWriter(save_dir, stable_hash=stable_hash)
|
| 442 |
+
used_syms = {}
|
| 443 |
+
|
| 444 |
+
# Extract from graph placeholders and their corresponding arguments
|
| 445 |
+
placeholder_targets = fx_placeholder_targets(gm)
|
| 446 |
+
for placeholder, arg in zip(placeholder_targets, args):
|
| 447 |
+
# pyrefly: ignore [unbound-name]
|
| 448 |
+
if isinstance(arg, (int, torch.SymInt)):
|
| 449 |
+
writer.symint(placeholder, arg)
|
| 450 |
+
# pyrefly: ignore [unbound-name]
|
| 451 |
+
elif isinstance(arg, torch.Tensor):
|
| 452 |
+
# TODO: improve these names with FQN
|
| 453 |
+
writer.tensor(placeholder, arg)
|
| 454 |
+
elif arg is None:
|
| 455 |
+
writer.const(placeholder)
|
| 456 |
+
else:
|
| 457 |
+
writer.unsupported(placeholder, arg)
|
| 458 |
+
|
| 459 |
+
# Extract symbolic variables from the same arguments
|
| 460 |
+
# pyrefly: ignore [unbound-name]
|
| 461 |
+
if (
|
| 462 |
+
# pyrefly: ignore [unbound-name]
|
| 463 |
+
isinstance(arg, torch.SymInt)
|
| 464 |
+
# By checking sympy.Symbol, we are excluding any symbolic expressions.
|
| 465 |
+
# TODO: we may need to solve expressions to extract symbol definitions.
|
| 466 |
+
and isinstance(arg.node.expr, sympy.Symbol)
|
| 467 |
+
and arg.node.hint is not None
|
| 468 |
+
):
|
| 469 |
+
used_syms[str(arg.node)] = arg.node.hint
|
| 470 |
+
# pyrefly: ignore [unbound-name]
|
| 471 |
+
elif isinstance(arg, torch.Tensor):
|
| 472 |
+
# Extract symbolic variables from tensor shapes and strides
|
| 473 |
+
for dim in arg.shape:
|
| 474 |
+
# pyrefly: ignore [unbound-name]
|
| 475 |
+
if (
|
| 476 |
+
# pyrefly: ignore [unbound-name]
|
| 477 |
+
isinstance(dim, torch.SymInt)
|
| 478 |
+
and isinstance(dim.node.expr, sympy.Symbol)
|
| 479 |
+
and dim.node.hint is not None
|
| 480 |
+
):
|
| 481 |
+
used_syms[str(dim.node)] = dim.node.hint
|
| 482 |
+
for stride in arg.stride():
|
| 483 |
+
# pyrefly: ignore [unbound-name]
|
| 484 |
+
if (
|
| 485 |
+
# pyrefly: ignore [unbound-name]
|
| 486 |
+
isinstance(stride, torch.SymInt)
|
| 487 |
+
and isinstance(stride.node.expr, sympy.Symbol)
|
| 488 |
+
and stride.node.hint is not None
|
| 489 |
+
):
|
| 490 |
+
used_syms[str(stride.node)] = stride.node.hint
|
| 491 |
+
# Add symbolic variable definitions to the top of the generated code
|
| 492 |
+
if used_syms:
|
| 493 |
+
hint_lines = "\n".join(
|
| 494 |
+
f"{name} = {hint}" for name, hint in sorted(used_syms.items())
|
| 495 |
+
)
|
| 496 |
+
model_str = f"{hint_lines}\n\n{model_str}"
|
| 497 |
+
|
| 498 |
+
load_args_lines = writer.lines()
|
| 499 |
+
load_args_code = "\n".join(load_args_lines)
|
| 500 |
+
model_str += load_args_code + "\n"
|
| 501 |
+
|
| 502 |
+
model_str += "mod = Repro()\n"
|
| 503 |
+
return model_str
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def save_graph_repro(
|
| 507 |
+
fd: IO[Any],
|
| 508 |
+
gm: torch.fx.GraphModule,
|
| 509 |
+
args: Sequence[Any],
|
| 510 |
+
compiler_name: str,
|
| 511 |
+
*,
|
| 512 |
+
stable_output: bool = False,
|
| 513 |
+
save_dir: Optional[str] = None,
|
| 514 |
+
command: str = "run",
|
| 515 |
+
accuracy: Optional[Union[str, bool]] = None,
|
| 516 |
+
tracing_mode: Optional[str] = None,
|
| 517 |
+
check_str: Optional[str] = None,
|
| 518 |
+
stable_hash: bool = False,
|
| 519 |
+
) -> None:
|
| 520 |
+
if any(
|
| 521 |
+
isinstance(arg, torch.fx.experimental._backward_state.BackwardState)
|
| 522 |
+
for arg in args
|
| 523 |
+
):
|
| 524 |
+
fd.write(
|
| 525 |
+
"Repro is not generated due to existence of BackwardState in graph input"
|
| 526 |
+
)
|
| 527 |
+
return
|
| 528 |
+
|
| 529 |
+
if save_dir is not None:
|
| 530 |
+
save_dir = normalize_path_separator(save_dir)
|
| 531 |
+
|
| 532 |
+
# Check if the graph contains distributed operations
|
| 533 |
+
has_distributed_ops = any(
|
| 534 |
+
node.op == "call_function"
|
| 535 |
+
and isinstance(node.target, OpOverload)
|
| 536 |
+
and node.target.namespace in {"_c10d_functional", "c10d_functional"}
|
| 537 |
+
for node in gm.graph.nodes
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
fd.write(
|
| 541 |
+
generate_compiler_repro_string(
|
| 542 |
+
gm,
|
| 543 |
+
args,
|
| 544 |
+
stable_output=stable_output,
|
| 545 |
+
save_dir=save_dir,
|
| 546 |
+
stable_hash=stable_hash,
|
| 547 |
+
has_distributed_ops=has_distributed_ops,
|
| 548 |
+
)
|
| 549 |
+
)
|
| 550 |
+
if accuracy is None:
|
| 551 |
+
accuracy = "_accuracy" in compiler_name
|
| 552 |
+
if tracing_mode is None:
|
| 553 |
+
tracing_mode = "real"
|
| 554 |
+
if any(
|
| 555 |
+
has_free_symbols(a) for a in args if not isinstance(a, FakeScriptObject)
|
| 556 |
+
):
|
| 557 |
+
tracing_mode = "symbolic"
|
| 558 |
+
fd.write("if __name__ == '__main__':\n")
|
| 559 |
+
fd.write(" from torch._dynamo.repro.after_aot import run_repro\n")
|
| 560 |
+
|
| 561 |
+
# Add distributed initialization before run_repro if needed
|
| 562 |
+
if has_distributed_ops:
|
| 563 |
+
fd.write(
|
| 564 |
+
" # Initialize FakeProcessGroup for distributed operations\n"
|
| 565 |
+
" store = FakeStore()\n"
|
| 566 |
+
" dist.init_process_group(\n"
|
| 567 |
+
' backend="fake",\n'
|
| 568 |
+
" rank=0,\n"
|
| 569 |
+
" world_size=2,\n"
|
| 570 |
+
" store=store\n"
|
| 571 |
+
" )\n"
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
fd.write(
|
| 575 |
+
f" with torch.no_grad():\n"
|
| 576 |
+
f" run_repro(mod, load_args, accuracy={accuracy!r}, command={command!r}, "
|
| 577 |
+
f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n"
|
| 578 |
+
f" # To run it separately, do \n"
|
| 579 |
+
f" # mod, args = run_repro(mod, load_args, accuracy={accuracy!r}, command='get_args', "
|
| 580 |
+
f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n"
|
| 581 |
+
f" # mod(*args)"
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
# Add distributed cleanup after run_repro
|
| 585 |
+
if has_distributed_ops:
|
| 586 |
+
fd.write("\n dist.destroy_process_group()\n")
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def dump_compiler_graph_state(
|
| 590 |
+
gm: torch.fx.GraphModule,
|
| 591 |
+
args: Sequence[Any],
|
| 592 |
+
compiler_name: str,
|
| 593 |
+
*,
|
| 594 |
+
accuracy: Optional[Union[str, bool]] = None,
|
| 595 |
+
) -> None:
|
| 596 |
+
subdir = os.path.join(minifier_dir(), "checkpoints")
|
| 597 |
+
if not os.path.exists(subdir):
|
| 598 |
+
os.makedirs(subdir, exist_ok=True)
|
| 599 |
+
file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py")
|
| 600 |
+
log.warning(
|
| 601 |
+
"Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name
|
| 602 |
+
)
|
| 603 |
+
with open(file_name, "w") as fd:
|
| 604 |
+
save_graph_repro(
|
| 605 |
+
fd, gm, args, compiler_name, save_dir=subdir, accuracy=accuracy
|
| 606 |
+
)
|
| 607 |
+
curdir = os.getcwd()
|
| 608 |
+
repro_path = os.path.join(curdir, "repro.py")
|
| 609 |
+
try:
|
| 610 |
+
shutil.copyfile(file_name, repro_path)
|
| 611 |
+
log.warning("Copying repro file for convenience to %s", repro_path)
|
| 612 |
+
if use_buck:
|
| 613 |
+
BuckTargetWriter(file_name).write()
|
| 614 |
+
except OSError:
|
| 615 |
+
log.warning("No write permissions for %s", repro_path)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 619 |
+
# DUMP MINIFIER
|
| 620 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def dump_to_minify(
|
| 624 |
+
gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: str
|
| 625 |
+
) -> None:
|
| 626 |
+
out = io.StringIO()
|
| 627 |
+
# TODO: factor this out
|
| 628 |
+
subdir = os.path.join(minifier_dir(), "checkpoints")
|
| 629 |
+
if not os.path.exists(subdir):
|
| 630 |
+
os.makedirs(subdir, exist_ok=True)
|
| 631 |
+
save_graph_repro(out, gm, args, compiler_name, save_dir=subdir, command="minify")
|
| 632 |
+
return helper_for_dump_minify(out.getvalue())
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def isolate_fails(
|
| 636 |
+
fx_g: torch.fx.GraphModule,
|
| 637 |
+
args: Sequence[Any],
|
| 638 |
+
compiler_name: str,
|
| 639 |
+
env: Optional[dict[str, Any]] = None,
|
| 640 |
+
save_dir: Optional[str] = None,
|
| 641 |
+
accuracy: Optional[Union[bool, str]] = None,
|
| 642 |
+
tracing_mode: Optional[str] = None,
|
| 643 |
+
check_str: Optional[str] = None,
|
| 644 |
+
) -> bool:
|
| 645 |
+
if env is None:
|
| 646 |
+
env = {}
|
| 647 |
+
subdir = os.path.join(os.getcwd(), "isolate")
|
| 648 |
+
if not os.path.exists(subdir):
|
| 649 |
+
os.makedirs(subdir, exist_ok=True)
|
| 650 |
+
file_name = os.path.join(subdir, f"{str(uuid.uuid4())[:5]}.py")
|
| 651 |
+
with open(file_name, "w") as fd:
|
| 652 |
+
save_graph_repro(
|
| 653 |
+
fd,
|
| 654 |
+
fx_g,
|
| 655 |
+
args,
|
| 656 |
+
compiler_name,
|
| 657 |
+
save_dir=save_dir,
|
| 658 |
+
command="minifier-query",
|
| 659 |
+
accuracy=accuracy,
|
| 660 |
+
tracing_mode=tracing_mode,
|
| 661 |
+
check_str=check_str,
|
| 662 |
+
)
|
| 663 |
+
# with open(file_name, "r") as fd:
|
| 664 |
+
# print(fd.read())
|
| 665 |
+
new_env = os.environ.copy()
|
| 666 |
+
new_env = {**new_env, **env}
|
| 667 |
+
if use_buck:
|
| 668 |
+
cmd = BuckTargetWriter(file_name).write(print_msg=False)
|
| 669 |
+
else:
|
| 670 |
+
cmd = [sys.executable, file_name]
|
| 671 |
+
with (
|
| 672 |
+
TemporaryFile() as stdout,
|
| 673 |
+
TemporaryFile() as stderr,
|
| 674 |
+
subprocess.Popen(
|
| 675 |
+
cmd,
|
| 676 |
+
cwd=subdir,
|
| 677 |
+
stdout=stdout,
|
| 678 |
+
stderr=stderr,
|
| 679 |
+
env=new_env,
|
| 680 |
+
) as p,
|
| 681 |
+
):
|
| 682 |
+
p.wait()
|
| 683 |
+
|
| 684 |
+
stdout.seek(0)
|
| 685 |
+
stderr.seek(0)
|
| 686 |
+
print(
|
| 687 |
+
textwrap.indent(stdout.read().decode("utf-8"), prefix=">> "),
|
| 688 |
+
file=sys.stdout,
|
| 689 |
+
)
|
| 690 |
+
print(
|
| 691 |
+
textwrap.indent(stderr.read().decode("utf-8"), prefix=">> "),
|
| 692 |
+
file=sys.stderr,
|
| 693 |
+
)
|
| 694 |
+
# print(f"Isolated test failed - {file_name}")
|
| 695 |
+
return p.returncode != 0
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 699 |
+
# MINIFIER TOOLS
|
| 700 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def inductor_fails(
|
| 704 |
+
fx_g: torch.fx.GraphModule, args: Sequence[Any], check_str: Optional[str] = None
|
| 705 |
+
) -> bool:
|
| 706 |
+
has_cuda = False
|
| 707 |
+
for arg in args:
|
| 708 |
+
if isinstance(arg, torch.Tensor) and arg.is_cuda:
|
| 709 |
+
has_cuda = True
|
| 710 |
+
break
|
| 711 |
+
|
| 712 |
+
def sync() -> None:
|
| 713 |
+
if has_cuda:
|
| 714 |
+
# Ensures that segfaults are surfaced
|
| 715 |
+
torch.cuda.synchronize()
|
| 716 |
+
|
| 717 |
+
from torch._inductor.compile_fx import compile_fx_inner
|
| 718 |
+
|
| 719 |
+
try:
|
| 720 |
+
result = fx_g(*args)
|
| 721 |
+
assert isinstance(result, (tuple, list))
|
| 722 |
+
assert not any(isinstance(x, (tuple, list)) for x in result)
|
| 723 |
+
except Exception:
|
| 724 |
+
return False
|
| 725 |
+
|
| 726 |
+
sync()
|
| 727 |
+
|
| 728 |
+
try:
|
| 729 |
+
compile_mod = compile_fx_inner(fx_g, args)
|
| 730 |
+
assert not isinstance(compile_mod, str)
|
| 731 |
+
compile_mod(args)
|
| 732 |
+
sync()
|
| 733 |
+
except Exception as e:
|
| 734 |
+
if check_str is not None and check_str not in repr(e):
|
| 735 |
+
return False
|
| 736 |
+
print(repr(e))
|
| 737 |
+
return True
|
| 738 |
+
return False
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def inductor_accuracy_fails(
|
| 742 |
+
fx_g: torch.fx.GraphModule,
|
| 743 |
+
args: Sequence[Any],
|
| 744 |
+
check_str: Optional[str] = None,
|
| 745 |
+
*,
|
| 746 |
+
require_fp64: bool = False,
|
| 747 |
+
ignore_non_fp: bool = False,
|
| 748 |
+
) -> bool:
|
| 749 |
+
from torch._inductor.compile_fx import compile_fx_inner
|
| 750 |
+
|
| 751 |
+
return backend_aot_accuracy_fails(
|
| 752 |
+
fx_g,
|
| 753 |
+
args, # type: ignore[arg-type]
|
| 754 |
+
compile_fx_inner, # type: ignore[arg-type]
|
| 755 |
+
require_fp64=require_fp64,
|
| 756 |
+
ignore_non_fp=ignore_non_fp,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
backend_aot_accuracy_fails = functools.partial(backend_accuracy_fails, only_fwd=True)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 764 |
+
# REPRO MAIN
|
| 765 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def repro_common(
|
| 769 |
+
options: Any, mod: nn.Module, load_args: Any
|
| 770 |
+
) -> tuple[torch.fx.GraphModule, Sequence[Any]]:
|
| 771 |
+
# Invariant for graphs we generate with the repro script
|
| 772 |
+
assert not any(mod.named_parameters())
|
| 773 |
+
for n, b in mod.named_buffers():
|
| 774 |
+
if b.numel() > MAX_CONSTANT_NUMEL_INLINE:
|
| 775 |
+
log.warning(
|
| 776 |
+
"Constant %s was not serialized, generated random data instead. "
|
| 777 |
+
"If you think this is affecting you, please comment on "
|
| 778 |
+
"https://github.com/pytorch/pytorch/issues/100468",
|
| 779 |
+
n,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
if not hasattr(load_args, "_version"):
|
| 783 |
+
log.warning(
|
| 784 |
+
"load_args does not have a _version attribute, please file a bug to PyTorch "
|
| 785 |
+
"and describe how you generate this repro script"
|
| 786 |
+
)
|
| 787 |
+
else:
|
| 788 |
+
if load_args._version > 0:
|
| 789 |
+
log.warning(
|
| 790 |
+
"load_args is version %s, but this version of PyTorch only supports "
|
| 791 |
+
"version 0. We will try to run it anyway but there may be an incompatibility; "
|
| 792 |
+
"if so, try upgrading your version of PyTorch.",
|
| 793 |
+
load_args._version,
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
nop_reader = NopInputReader()
|
| 797 |
+
load_args(nop_reader)
|
| 798 |
+
|
| 799 |
+
with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar:
|
| 800 |
+
input_reader = InputReader(save_dir=options.save_dir, pbar=pbar)
|
| 801 |
+
load_args(input_reader)
|
| 802 |
+
args = input_reader.args
|
| 803 |
+
|
| 804 |
+
# Turn mod into a GraphModule the slow way
|
| 805 |
+
# TODO: speed this up
|
| 806 |
+
mod = make_fx(mod, tracing_mode=options.tracing_mode)(*args)
|
| 807 |
+
|
| 808 |
+
# pyrefly: ignore [bad-assignment]
|
| 809 |
+
torch._inductor.config.generate_intermediate_hooks = True
|
| 810 |
+
|
| 811 |
+
return mod, args
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
ACCURACY_FAILS: dict[str, Callable[[torch.fx.GraphModule, Any], bool]] = {
|
| 815 |
+
"": inductor_fails,
|
| 816 |
+
# This might look inverted but it's not. strict_accuracy means "we will
|
| 817 |
+
# minify any time we see anything that diverges", whereas accuracy is more
|
| 818 |
+
# conservative, and will only minify if there is a meaningful fp64
|
| 819 |
+
# divergence
|
| 820 |
+
"accuracy": functools.partial(
|
| 821 |
+
inductor_accuracy_fails, require_fp64=True, ignore_non_fp=True
|
| 822 |
+
),
|
| 823 |
+
"strict_accuracy": inductor_accuracy_fails,
|
| 824 |
+
}
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def repro_minifier_query(options: Any, mod: nn.Module, load_args: Any) -> None:
|
| 828 |
+
mod, args = repro_common(options, mod, load_args)
|
| 829 |
+
fail_fn = functools.partial(
|
| 830 |
+
ACCURACY_FAILS[options.accuracy],
|
| 831 |
+
check_str=options.check_str, # type: ignore[call-arg]
|
| 832 |
+
)
|
| 833 |
+
if fail_fn(mod, args):
|
| 834 |
+
sys.exit(1)
|
| 835 |
+
else:
|
| 836 |
+
sys.exit(0)
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def repro_minify(options: Any, mod: nn.Module, load_args: Any) -> None:
|
| 840 |
+
from functorch.compile import minifier
|
| 841 |
+
|
| 842 |
+
mod, args = repro_common(options, mod, load_args)
|
| 843 |
+
compiler_name = "inductor_accuracy" if options.accuracy != "" else "inductor"
|
| 844 |
+
|
| 845 |
+
favored_device = 1 if torch.cuda.device_count() >= 2 else 0
|
| 846 |
+
env_variables = {"CUDA_VISIBLE_DEVICES": str(favored_device)}
|
| 847 |
+
|
| 848 |
+
module_fails: Any
|
| 849 |
+
if options.isolate:
|
| 850 |
+
module_fails = functools.partial(
|
| 851 |
+
isolate_fails,
|
| 852 |
+
env=env_variables,
|
| 853 |
+
compiler_name=compiler_name,
|
| 854 |
+
save_dir=options.save_dir,
|
| 855 |
+
accuracy=options.accuracy,
|
| 856 |
+
tracing_mode=options.tracing_mode,
|
| 857 |
+
)
|
| 858 |
+
else:
|
| 859 |
+
module_fails = ACCURACY_FAILS[options.accuracy]
|
| 860 |
+
|
| 861 |
+
minifier(
|
| 862 |
+
mod,
|
| 863 |
+
args,
|
| 864 |
+
module_fails=functools.partial(module_fails, check_str=options.check_str),
|
| 865 |
+
dump_state=functools.partial(
|
| 866 |
+
dump_compiler_graph_state, compiler_name=compiler_name
|
| 867 |
+
),
|
| 868 |
+
save_dir=options.save_dir,
|
| 869 |
+
offload_to_disk=options.offload_to_disk,
|
| 870 |
+
skip_offload=options.skip_saving_eager_intermediates,
|
| 871 |
+
skip_sanity=options.skip_sanity,
|
| 872 |
+
max_granularity=options.max_granularity,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def repro_analyze(options: Any, mod: nn.Module, load_args: Any) -> None:
|
| 877 |
+
from torch._inductor.compile_fx import compile_fx_inner
|
| 878 |
+
from torch._inductor.hooks import intermediate_hook
|
| 879 |
+
|
| 880 |
+
mod, args = repro_common(options, mod, load_args)
|
| 881 |
+
|
| 882 |
+
# TODO: The logic for cloning inputs/models here is intentionally
|
| 883 |
+
# modeled off of run_fwd_maybe_bwd, but arguably it is better not to
|
| 884 |
+
# clone inputs (as you are doubling your effective GPU memory usage).
|
| 885 |
+
# It is certainly faster though! It probably makes sense to let the
|
| 886 |
+
# user specify the offload strategy.
|
| 887 |
+
|
| 888 |
+
with tqdm(desc="Compiling"):
|
| 889 |
+
compiled = compile_fx_inner(mod, args)
|
| 890 |
+
total = counters["inductor"]["intermediate_hooks"]
|
| 891 |
+
|
| 892 |
+
known_names = set()
|
| 893 |
+
|
| 894 |
+
def save_hook(name: str, val: Any) -> None:
|
| 895 |
+
known_names.add(name)
|
| 896 |
+
if not options.skip_saving_inductor_intermediates:
|
| 897 |
+
writer.write_tensor(os.path.join("inductor", name), val)
|
| 898 |
+
pbar.update(1) # type: ignore[has-type]
|
| 899 |
+
|
| 900 |
+
writer = torch.utils._content_store.ContentStoreWriter(
|
| 901 |
+
options.save_dir, stable_hash=options.stable_hash
|
| 902 |
+
)
|
| 903 |
+
reader = torch.utils._content_store.ContentStoreReader(options.save_dir)
|
| 904 |
+
|
| 905 |
+
new_args = clone_inputs(args)
|
| 906 |
+
with (
|
| 907 |
+
intermediate_hook(save_hook),
|
| 908 |
+
tqdm(desc="Saving inductor intermediates", total=total) as pbar,
|
| 909 |
+
):
|
| 910 |
+
assert not isinstance(compiled, str)
|
| 911 |
+
compiled(new_args) # type: ignore[arg-type]
|
| 912 |
+
assert not new_args
|
| 913 |
+
|
| 914 |
+
def compare_tuples(tuple1: tuple[Any], tuple2: tuple[Any]) -> Optional[str]:
|
| 915 |
+
diff_indices = [i for i in range(len(tuple1)) if tuple1[i] != tuple2[i]]
|
| 916 |
+
diff_values = [(tuple1[i], tuple2[i]) for i in diff_indices]
|
| 917 |
+
|
| 918 |
+
if not diff_values:
|
| 919 |
+
return None
|
| 920 |
+
else:
|
| 921 |
+
return " and ".join(f"{a} != {b}" for a, b in diff_values)
|
| 922 |
+
|
| 923 |
+
def check_hook(name: str, val: Any) -> None:
|
| 924 |
+
meta = writer.compute_tensor_metadata(val)
|
| 925 |
+
meta2 = reader.read_tensor_metadata(os.path.join("inductor", name))
|
| 926 |
+
reason = compare_tuples(meta, meta2)
|
| 927 |
+
if reason is not None:
|
| 928 |
+
pbar.write(f"NONDETERMINISTIC INDUCTOR at {name} ({reason})")
|
| 929 |
+
pbar.update(1)
|
| 930 |
+
|
| 931 |
+
if not options.skip_check_deterministic:
|
| 932 |
+
new_args = clone_inputs(args)
|
| 933 |
+
with (
|
| 934 |
+
intermediate_hook(check_hook),
|
| 935 |
+
tqdm(desc="Checking inductor determinism", total=total) as pbar,
|
| 936 |
+
):
|
| 937 |
+
compiled(new_args) # type: ignore[arg-type]
|
| 938 |
+
assert not new_args
|
| 939 |
+
|
| 940 |
+
class WriterInterp(fx.Interpreter):
|
| 941 |
+
def __init__(self, mod: torch.nn.Module, subdir: str) -> None:
|
| 942 |
+
super().__init__(mod)
|
| 943 |
+
self.subdir = subdir
|
| 944 |
+
|
| 945 |
+
def run_node(self, n: torch.fx.Node) -> Any:
|
| 946 |
+
r = super().run_node(n)
|
| 947 |
+
name = n.name
|
| 948 |
+
if name in known_names:
|
| 949 |
+
pbar.update(1)
|
| 950 |
+
writer.write_tensor(os.path.join(self.subdir, name), r)
|
| 951 |
+
return r
|
| 952 |
+
|
| 953 |
+
# NB: the module cast doesn't actually do anything, since there are no
|
| 954 |
+
# parameters/buffers on the module
|
| 955 |
+
if not options.skip_saving_float64_intermediates:
|
| 956 |
+
new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type]
|
| 957 |
+
with tqdm(desc="Saving float64 intermediates", total=total) as pbar:
|
| 958 |
+
WriterInterp(new_mod, "float64").boxed_run(new_args)
|
| 959 |
+
assert not new_args
|
| 960 |
+
|
| 961 |
+
class ExactReaderInterp(fx.Interpreter):
|
| 962 |
+
def run_node(self, n: torch.fx.Node) -> Any:
|
| 963 |
+
r = super().run_node(n)
|
| 964 |
+
name = n.name
|
| 965 |
+
if name in known_names:
|
| 966 |
+
meta = writer.compute_tensor_metadata(r)
|
| 967 |
+
meta2 = reader.read_tensor_metadata(os.path.join("float64", name))
|
| 968 |
+
reason = compare_tuples(meta, meta2)
|
| 969 |
+
if reason is not None:
|
| 970 |
+
pbar.write(f"NONDETERMINISTIC FLOAT64 at {name} ({reason})")
|
| 971 |
+
pbar.update(1)
|
| 972 |
+
return r
|
| 973 |
+
|
| 974 |
+
# TODO: check eager determinism
|
| 975 |
+
|
| 976 |
+
if not options.skip_check_deterministic:
|
| 977 |
+
new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type]
|
| 978 |
+
with tqdm(desc="Checking float64 determinism", total=total) as pbar:
|
| 979 |
+
ExactReaderInterp(new_mod).boxed_run(new_args)
|
| 980 |
+
assert not new_args
|
| 981 |
+
|
| 982 |
+
# Now that we've saved everything, interp through the eager graph
|
| 983 |
+
# and do comparisons
|
| 984 |
+
class ReaderInterp(fx.Interpreter):
|
| 985 |
+
def run_node(self, n: torch.fx.Node) -> Any:
|
| 986 |
+
r = super().run_node(n)
|
| 987 |
+
name = n.name
|
| 988 |
+
if name in known_names:
|
| 989 |
+
inductor = reader.read_tensor(os.path.join("inductor", name))
|
| 990 |
+
float64 = reader.read_tensor(os.path.join("float64", name))
|
| 991 |
+
logged = False
|
| 992 |
+
|
| 993 |
+
def log_error(msg: str, *args: Any) -> None:
|
| 994 |
+
nonlocal logged
|
| 995 |
+
logged = True
|
| 996 |
+
pbar.write(f"DIVERGED at {name}: {msg % args}")
|
| 997 |
+
|
| 998 |
+
if not same(
|
| 999 |
+
r,
|
| 1000 |
+
inductor,
|
| 1001 |
+
float64,
|
| 1002 |
+
tol=torch._dynamo.config.repro_tolerance,
|
| 1003 |
+
equal_nan=True,
|
| 1004 |
+
log_error=log_error,
|
| 1005 |
+
):
|
| 1006 |
+
assert logged
|
| 1007 |
+
pbar.update(1)
|
| 1008 |
+
return r
|
| 1009 |
+
|
| 1010 |
+
with tqdm(desc="Checking divergence", total=total) as pbar:
|
| 1011 |
+
ReaderInterp(mod).boxed_run(args)
|
| 1012 |
+
assert not args
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def repro_get_args(
|
| 1016 |
+
options: Any, mod: nn.Module, load_args: Any
|
| 1017 |
+
) -> tuple[torch.fx.GraphModule, list[Any]]:
|
| 1018 |
+
mod, args = repro_common(options, mod, load_args)
|
| 1019 |
+
return mod, args # type: ignore[return-value]
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def repro_run(options: Any, mod: nn.Module, load_args: Any) -> None:
|
| 1023 |
+
from torch._inductor.compile_fx import compile_fx_inner
|
| 1024 |
+
|
| 1025 |
+
mod, args = repro_common(options, mod, load_args)
|
| 1026 |
+
|
| 1027 |
+
from torch.cuda import synchronize
|
| 1028 |
+
|
| 1029 |
+
compiled = compile_fx_inner(mod, args)
|
| 1030 |
+
assert not isinstance(compiled, str)
|
| 1031 |
+
|
| 1032 |
+
if options.accuracy != "":
|
| 1033 |
+
# We don't really respect --accuracy vs --strict-accuracy here, it
|
| 1034 |
+
# seems counterintuitive
|
| 1035 |
+
if not same_two_models(
|
| 1036 |
+
mod,
|
| 1037 |
+
compiled, # type: ignore[arg-type]
|
| 1038 |
+
args,
|
| 1039 |
+
only_fwd=True,
|
| 1040 |
+
ignore_non_fp=config.repro_ignore_non_fp,
|
| 1041 |
+
):
|
| 1042 |
+
raise AccuracyError("Bad accuracy detected")
|
| 1043 |
+
else:
|
| 1044 |
+
need_sync = False
|
| 1045 |
+
|
| 1046 |
+
for arg in args:
|
| 1047 |
+
if isinstance(arg, torch.Tensor) and arg.is_cuda:
|
| 1048 |
+
need_sync = True
|
| 1049 |
+
break
|
| 1050 |
+
|
| 1051 |
+
compiled(list(args))
|
| 1052 |
+
|
| 1053 |
+
if need_sync:
|
| 1054 |
+
synchronize() # ensure segfaults are surfaced
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
# TODO: lazily load the inputs or something, rather than cloning them
|
| 1058 |
+
def run_repro(
|
| 1059 |
+
mod: nn.Module,
|
| 1060 |
+
load_args: Any,
|
| 1061 |
+
*,
|
| 1062 |
+
command: str = "run",
|
| 1063 |
+
accuracy: Union[bool, str] = "",
|
| 1064 |
+
save_dir: Optional[str] = None,
|
| 1065 |
+
tracing_mode: Optional[str] = None,
|
| 1066 |
+
patch_code: Optional[str] = None,
|
| 1067 |
+
check_str: Optional[str] = None,
|
| 1068 |
+
**kwargs: Any,
|
| 1069 |
+
) -> Any:
|
| 1070 |
+
for k in kwargs:
|
| 1071 |
+
log.warning(
|
| 1072 |
+
"Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch",
|
| 1073 |
+
k,
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
if accuracy is True:
|
| 1077 |
+
accuracy = "accuracy"
|
| 1078 |
+
elif accuracy is False:
|
| 1079 |
+
accuracy = ""
|
| 1080 |
+
|
| 1081 |
+
if patch_code is not None:
|
| 1082 |
+
log.warning(
|
| 1083 |
+
"patch_code no longer works on this version of PyTorch, silently ignoring"
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
parser = argparse.ArgumentParser(
|
| 1087 |
+
description=f"""\
|
| 1088 |
+
An after_aot repro script, typically triggering a bug in PyTorch Inductor.
|
| 1089 |
+
When run with no arguments, this script defaults to running '{command}'.
|
| 1090 |
+
Extra flags may be available; to find out more, try '{command} --help'.
|
| 1091 |
+
There are also alternate subcommands available, see below.
|
| 1092 |
+
|
| 1093 |
+
default settings on this script:
|
| 1094 |
+
{accuracy=}
|
| 1095 |
+
{tracing_mode=}
|
| 1096 |
+
{save_dir=}
|
| 1097 |
+
{check_str=}
|
| 1098 |
+
""",
|
| 1099 |
+
formatter_class=argparse.RawTextHelpFormatter,
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
def common_flags(parser: argparse.ArgumentParser) -> None:
|
| 1103 |
+
accuracy_group = parser.add_mutually_exclusive_group()
|
| 1104 |
+
accuracy_group.add_argument(
|
| 1105 |
+
"--no-accuracy",
|
| 1106 |
+
dest="accuracy",
|
| 1107 |
+
action="store_const",
|
| 1108 |
+
const="",
|
| 1109 |
+
default=accuracy,
|
| 1110 |
+
help="do not test accuracy, just run the module and see if it errors",
|
| 1111 |
+
)
|
| 1112 |
+
accuracy_group.add_argument(
|
| 1113 |
+
"--accuracy",
|
| 1114 |
+
action="store_const",
|
| 1115 |
+
const="accuracy",
|
| 1116 |
+
default=accuracy,
|
| 1117 |
+
help="""\
|
| 1118 |
+
test if the RMSE between the compiled module and the fp64 reference is greater
|
| 1119 |
+
than eager and the fp64 reference. This is usually more reliable than the
|
| 1120 |
+
standard allclose test, as we expect numeric differences from compiling, often
|
| 1121 |
+
improving accuracy over eager. RMSE test allows for compiled module to
|
| 1122 |
+
diverge greatly from eager, as long as this divergence moves it closer to the
|
| 1123 |
+
'true' mathematical value of the network. Caveats: (1) double precision can
|
| 1124 |
+
still suffer from rounding error, so it is not a perfect reference (see for
|
| 1125 |
+
example 'Herbie: Automatically Improving Floating Point Accuracy') for
|
| 1126 |
+
approaches that detect the necessary working precision and compute it in
|
| 1127 |
+
arbitrary precision floating point; unfortunately, this is not practical for
|
| 1128 |
+
tensor computation; (2) if there are not enough samples in the output being
|
| 1129 |
+
compared, we may get unlucky and have an unlucky greater RMSE than eager; this
|
| 1130 |
+
could be overcome by applying a more rigorous statistical test at some
|
| 1131 |
+
p-value, which we leave for future work.
|
| 1132 |
+
""",
|
| 1133 |
+
)
|
| 1134 |
+
accuracy_group.add_argument(
|
| 1135 |
+
"--strict-accuracy",
|
| 1136 |
+
dest="accuracy",
|
| 1137 |
+
action="store_const",
|
| 1138 |
+
const="strict_accuracy",
|
| 1139 |
+
default=accuracy,
|
| 1140 |
+
help="""\
|
| 1141 |
+
by default, when doing accuracy minification we will reject reductions which
|
| 1142 |
+
change the divergence from a floating point divergence to a integral/boolean
|
| 1143 |
+
divergence. This is because some operations like ReLU involve temporarily
|
| 1144 |
+
sharp boundaries that smooth out again afterwards; without requiring
|
| 1145 |
+
divergence on floating point, the minifier will often fixate on divergent
|
| 1146 |
+
boolean tensor even though this is not the true source of the divergence.
|
| 1147 |
+
However, rejecting these reductions makes it more difficult for the minifier
|
| 1148 |
+
to make process. Using this option will let the minifier progress for ALL
|
| 1149 |
+
divergences--you just might not end up with a useful repro in the end.""",
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
parser.add_argument(
|
| 1153 |
+
"--save-dir",
|
| 1154 |
+
type=str,
|
| 1155 |
+
default=save_dir,
|
| 1156 |
+
metavar="DIR",
|
| 1157 |
+
help="directory where saved inputs live",
|
| 1158 |
+
)
|
| 1159 |
+
parser.add_argument(
|
| 1160 |
+
"--no-save-dir",
|
| 1161 |
+
dest="save_dir",
|
| 1162 |
+
action="store_const",
|
| 1163 |
+
const=None,
|
| 1164 |
+
help="don't use any directory for saved inputs",
|
| 1165 |
+
)
|
| 1166 |
+
parser.add_argument(
|
| 1167 |
+
"--tracing-mode",
|
| 1168 |
+
type=str,
|
| 1169 |
+
metavar="{real,fake,symbolic}",
|
| 1170 |
+
default=tracing_mode,
|
| 1171 |
+
help="how to trace the repro module into a GraphModule with metadata",
|
| 1172 |
+
)
|
| 1173 |
+
|
| 1174 |
+
subparsers = parser.add_subparsers(
|
| 1175 |
+
dest="command", metavar="{run,minify,analyze}", required=True
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
parser_run = subparsers.add_parser(
|
| 1179 |
+
"run",
|
| 1180 |
+
help="just run the repro",
|
| 1181 |
+
)
|
| 1182 |
+
common_flags(parser_run)
|
| 1183 |
+
|
| 1184 |
+
parser_minify = subparsers.add_parser(
|
| 1185 |
+
"minify", help="run the minifier on the repro"
|
| 1186 |
+
)
|
| 1187 |
+
common_flags(parser_minify)
|
| 1188 |
+
parser_get_args = subparsers.add_parser("get_args", help="get the args")
|
| 1189 |
+
common_flags(parser_get_args)
|
| 1190 |
+
parser_minify_isolate = parser_minify.add_mutually_exclusive_group()
|
| 1191 |
+
parser_minify_isolate.add_argument(
|
| 1192 |
+
"--isolate",
|
| 1193 |
+
action="store_true",
|
| 1194 |
+
default=True,
|
| 1195 |
+
help="run in separate processes to avoid interference (default)",
|
| 1196 |
+
)
|
| 1197 |
+
parser_minify_isolate.add_argument(
|
| 1198 |
+
"--no-isolate",
|
| 1199 |
+
dest="isolate",
|
| 1200 |
+
action="store_false",
|
| 1201 |
+
help="speed up by running all compilation in same process",
|
| 1202 |
+
)
|
| 1203 |
+
parser_minify.add_argument(
|
| 1204 |
+
"--skip-saving-eager-intermediates",
|
| 1205 |
+
action="store_true",
|
| 1206 |
+
help="skip saving eager intermediates on --minify",
|
| 1207 |
+
)
|
| 1208 |
+
# TODO: make this an option for --analyze too
|
| 1209 |
+
parser_minify.add_argument(
|
| 1210 |
+
"--offload-to-disk",
|
| 1211 |
+
action="store_true",
|
| 1212 |
+
help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing",
|
| 1213 |
+
)
|
| 1214 |
+
parser_minify.add_argument(
|
| 1215 |
+
"--skip-sanity",
|
| 1216 |
+
action="store_true",
|
| 1217 |
+
help="skip sanity check at beginning of minification on original graph",
|
| 1218 |
+
)
|
| 1219 |
+
parser_minify.add_argument(
|
| 1220 |
+
"--max-granularity",
|
| 1221 |
+
type=int,
|
| 1222 |
+
default=None,
|
| 1223 |
+
help="start at this granularity and work down; must be power of 2",
|
| 1224 |
+
)
|
| 1225 |
+
parser_minify.add_argument(
|
| 1226 |
+
"--check-str",
|
| 1227 |
+
type=str,
|
| 1228 |
+
default=check_str,
|
| 1229 |
+
help="require minified program to fail with error containing this string",
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
parser_analyze = subparsers.add_parser(
|
| 1233 |
+
"analyze", help="run the accuracy analyzer on the repro"
|
| 1234 |
+
)
|
| 1235 |
+
common_flags(parser_analyze)
|
| 1236 |
+
parser_analyze.add_argument(
|
| 1237 |
+
"--skip-saving-inductor-intermediates",
|
| 1238 |
+
action="store_true",
|
| 1239 |
+
help="skip saving inductor intermediates on --analyze",
|
| 1240 |
+
)
|
| 1241 |
+
parser_analyze.add_argument(
|
| 1242 |
+
"--skip-saving-float64-intermediates",
|
| 1243 |
+
action="store_true",
|
| 1244 |
+
help="skip saving float64 intermediates",
|
| 1245 |
+
)
|
| 1246 |
+
parser_analyze.add_argument(
|
| 1247 |
+
"--skip-check-deterministic",
|
| 1248 |
+
action="store_true",
|
| 1249 |
+
help="skip checking that the network is deterministic",
|
| 1250 |
+
)
|
| 1251 |
+
parser_analyze.add_argument(
|
| 1252 |
+
"--stable-hash",
|
| 1253 |
+
action="store_true",
|
| 1254 |
+
help="use SHA-1 checksum instead of fast (but possibly unsound) hash",
|
| 1255 |
+
)
|
| 1256 |
+
|
| 1257 |
+
# Run the repro in the context of minification, inverting exit code meaning
|
| 1258 |
+
parser_minifier_query = subparsers.add_parser(
|
| 1259 |
+
"minifier-query",
|
| 1260 |
+
)
|
| 1261 |
+
common_flags(parser_minifier_query)
|
| 1262 |
+
parser_minifier_query.add_argument(
|
| 1263 |
+
"--check-str",
|
| 1264 |
+
type=str,
|
| 1265 |
+
default=check_str,
|
| 1266 |
+
help="require minified program to fail with error containing this string",
|
| 1267 |
+
)
|
| 1268 |
+
|
| 1269 |
+
args = None
|
| 1270 |
+
if len(sys.argv) <= 1:
|
| 1271 |
+
args = [command, *sys.argv[1:]]
|
| 1272 |
+
|
| 1273 |
+
options = parser.parse_args(args)
|
| 1274 |
+
COMMAND_FNS = {
|
| 1275 |
+
"minify": repro_minify,
|
| 1276 |
+
"analyze": repro_analyze,
|
| 1277 |
+
"minifier-query": repro_minifier_query,
|
| 1278 |
+
"run": repro_run,
|
| 1279 |
+
"get_args": repro_get_args,
|
| 1280 |
+
}
|
| 1281 |
+
return COMMAND_FNS[options.command](options, mod, load_args)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/after_dynamo.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities for reproducing and debugging issues in Dynamo after graph capture.
|
| 3 |
+
|
| 4 |
+
This file provides tools and infrastructure for debugging problems that occur
|
| 5 |
+
after Dynamo has captured the graph but before/during backend compilation.
|
| 6 |
+
Key components include:
|
| 7 |
+
|
| 8 |
+
- Minification tools to reduce large graphs to minimal failing examples
|
| 9 |
+
- Accuracy testing to validate compiled graph outputs match eager mode
|
| 10 |
+
- Repro generation to create standalone reproduction scripts
|
| 11 |
+
- Debug backends for capturing and analyzing failures
|
| 12 |
+
- Utilities for saving/loading graph states and inputs
|
| 13 |
+
|
| 14 |
+
The tools here focus specifically on the post-graph-capture stage, making them
|
| 15 |
+
useful for debugging backend compilation issues, AOTAutograd problems, and
|
| 16 |
+
accuracy discrepancies between compiled and eager execution.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import copy
|
| 21 |
+
import functools
|
| 22 |
+
import logging
|
| 23 |
+
import os
|
| 24 |
+
import shutil
|
| 25 |
+
import sys
|
| 26 |
+
import textwrap
|
| 27 |
+
from collections.abc import Callable, Sequence
|
| 28 |
+
from importlib import import_module
|
| 29 |
+
from typing import Any, Optional, Union
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
import torch.fx as fx
|
| 33 |
+
from torch._dynamo.debug_utils import (
|
| 34 |
+
AccuracyError,
|
| 35 |
+
backend_accuracy_fails,
|
| 36 |
+
BUCK_CMD_PREFIX,
|
| 37 |
+
BuckTargetWriter,
|
| 38 |
+
extra_imports,
|
| 39 |
+
generate_config_string,
|
| 40 |
+
generate_env_vars_string,
|
| 41 |
+
helper_for_dump_minify,
|
| 42 |
+
InputReader,
|
| 43 |
+
InputWriter,
|
| 44 |
+
minifier_dir,
|
| 45 |
+
NNModuleToString,
|
| 46 |
+
NopInputReader,
|
| 47 |
+
run_fwd_maybe_bwd,
|
| 48 |
+
same_two_models,
|
| 49 |
+
)
|
| 50 |
+
from torch.fx.experimental.symbolic_shapes import fx_placeholder_targets
|
| 51 |
+
from torch.hub import tqdm
|
| 52 |
+
|
| 53 |
+
from .. import config
|
| 54 |
+
from ..backends.registry import CompilerFn, lookup_backend, register_debug_backend
|
| 55 |
+
from ..debug_utils import clone_inputs_retaining_gradness
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
log = logging.getLogger(__name__)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
inductor_config = import_module("torch._inductor.config")
|
| 62 |
+
use_buck = inductor_config.is_fbcode()
|
| 63 |
+
|
| 64 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 65 |
+
# MAIN ENTRY POINT
|
| 66 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _accuracy_fails(
|
| 70 |
+
gm: torch.fx.GraphModule,
|
| 71 |
+
example_inputs: Sequence[Any],
|
| 72 |
+
compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule],
|
| 73 |
+
) -> bool:
|
| 74 |
+
return backend_accuracy_fails(
|
| 75 |
+
gm,
|
| 76 |
+
example_inputs,
|
| 77 |
+
compiler_fn,
|
| 78 |
+
only_fwd=config.repro_forward_only,
|
| 79 |
+
ignore_non_fp=config.repro_ignore_non_fp,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class WrapBackendDebug:
|
| 84 |
+
def __init__(
|
| 85 |
+
self, unconfigured_compiler_fn: CompilerFn, compiler_name: Optional[str]
|
| 86 |
+
) -> None:
|
| 87 |
+
functools.wraps(unconfigured_compiler_fn)(self)
|
| 88 |
+
self._torchdynamo_orig_backend = unconfigured_compiler_fn
|
| 89 |
+
self._compiler_name = compiler_name
|
| 90 |
+
if hasattr(unconfigured_compiler_fn, "__name__"):
|
| 91 |
+
self.__name__ = unconfigured_compiler_fn.__name__
|
| 92 |
+
if hasattr(unconfigured_compiler_fn, "compiler_name"):
|
| 93 |
+
self.__name__ = unconfigured_compiler_fn.compiler_name # type: ignore[attr-defined]
|
| 94 |
+
if hasattr(unconfigured_compiler_fn, "get_compiler_config"):
|
| 95 |
+
self.get_compiler_config = unconfigured_compiler_fn.get_compiler_config # type: ignore[attr-defined]
|
| 96 |
+
|
| 97 |
+
def __call__(
|
| 98 |
+
self, gm: torch.fx.GraphModule, example_inputs: list[Any], **kwargs: Any
|
| 99 |
+
) -> torch.fx.GraphModule:
|
| 100 |
+
compiler_fn = functools.partial(self._torchdynamo_orig_backend, **kwargs)
|
| 101 |
+
assert config.repro_after in ("dynamo", "aot", None)
|
| 102 |
+
|
| 103 |
+
if config.repro_after == "dynamo":
|
| 104 |
+
|
| 105 |
+
def add_paths(exc: Exception) -> None:
|
| 106 |
+
exc.minifier_path = os.path.join(minifier_dir(), "minifier_launcher.py") # type: ignore[attr-defined]
|
| 107 |
+
if use_buck:
|
| 108 |
+
exc.buck_command = " ".join( # type: ignore[attr-defined]
|
| 109 |
+
BUCK_CMD_PREFIX
|
| 110 |
+
+ [BuckTargetWriter(exc.minifier_path).cmd_line_path] # type: ignore[attr-defined]
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
if config.repro_level == 3:
|
| 114 |
+
dump_to_minify_after_dynamo(gm, example_inputs, self._compiler_name)
|
| 115 |
+
|
| 116 |
+
# Check for either accuracy (level 4) or other type of failures.
|
| 117 |
+
if config.repro_level == 4:
|
| 118 |
+
# Check Accuracy
|
| 119 |
+
compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs)
|
| 120 |
+
if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type]
|
| 121 |
+
log.warning(
|
| 122 |
+
"Accuracy failed for the TorchDynamo produced graph. Creating script to minify the error."
|
| 123 |
+
)
|
| 124 |
+
dump_to_minify_after_dynamo(
|
| 125 |
+
fx.GraphModule(gm, copy.deepcopy(gm.graph)),
|
| 126 |
+
example_inputs,
|
| 127 |
+
self._compiler_name,
|
| 128 |
+
)
|
| 129 |
+
exc = AccuracyError("Bad accuracy detected.")
|
| 130 |
+
add_paths(exc)
|
| 131 |
+
raise exc
|
| 132 |
+
else:
|
| 133 |
+
try:
|
| 134 |
+
compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs)
|
| 135 |
+
run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type]
|
| 136 |
+
except Exception as exc:
|
| 137 |
+
log.warning(
|
| 138 |
+
"Compiled Fx GraphModule failed. Creating script to minify the error."
|
| 139 |
+
)
|
| 140 |
+
if config.repro_level == 1:
|
| 141 |
+
dump_state_fn = functools.partial(
|
| 142 |
+
dump_backend_state, compiler_name=self._compiler_name
|
| 143 |
+
)
|
| 144 |
+
dump_state_fn(
|
| 145 |
+
fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs
|
| 146 |
+
)
|
| 147 |
+
elif config.repro_level == 2:
|
| 148 |
+
dump_to_minify_after_dynamo(
|
| 149 |
+
fx.GraphModule(gm, copy.deepcopy(gm.graph)),
|
| 150 |
+
example_inputs,
|
| 151 |
+
self._compiler_name,
|
| 152 |
+
)
|
| 153 |
+
add_paths(exc)
|
| 154 |
+
raise
|
| 155 |
+
else:
|
| 156 |
+
compiled_gm = compiler_fn(gm, example_inputs)
|
| 157 |
+
|
| 158 |
+
return compiled_gm # type: ignore[return-value]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def wrap_backend_debug(
|
| 162 |
+
unconfigured_compiler_fn: CompilerFn, compiler_name: Optional[str]
|
| 163 |
+
) -> WrapBackendDebug:
|
| 164 |
+
"""
|
| 165 |
+
A minifier decorator that wraps the TorchDynamo produced Fx graph modules.
|
| 166 |
+
As opposed to wrap_compiler_debug, this wrapper intercepts at the
|
| 167 |
+
TorchDynamo produced Fx Graph Module. This makes it backend-agnostic to some
|
| 168 |
+
level, e.g., it is useful for minifying issues related to Aot Autograd
|
| 169 |
+
tracing. If an error is found, we minify and save the minified repro in
|
| 170 |
+
repro.tar.gz.
|
| 171 |
+
"""
|
| 172 |
+
return WrapBackendDebug(unconfigured_compiler_fn, compiler_name)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 176 |
+
# REPRO DUMPERS
|
| 177 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def generate_dynamo_fx_repro_string(
|
| 181 |
+
gm: torch.fx.GraphModule,
|
| 182 |
+
args: Sequence[Any],
|
| 183 |
+
compiler_name: Optional[str],
|
| 184 |
+
check_accuracy: bool = False,
|
| 185 |
+
*,
|
| 186 |
+
stable_output: bool = False,
|
| 187 |
+
save_dir: Optional[str] = None,
|
| 188 |
+
command: str = "run",
|
| 189 |
+
) -> str:
|
| 190 |
+
"""
|
| 191 |
+
Generate a repro string for backend-agnostic minified version.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
model_str = NNModuleToString.convert(gm)
|
| 195 |
+
|
| 196 |
+
# TODO: Figure out why torch.compile'd hash isn't work on this codepath
|
| 197 |
+
writer = InputWriter(save_dir, stable_hash=True)
|
| 198 |
+
for placeholder, arg in zip(fx_placeholder_targets(gm), args):
|
| 199 |
+
if isinstance(arg, (int, torch.SymInt)):
|
| 200 |
+
writer.symint(placeholder, arg)
|
| 201 |
+
elif isinstance(arg, torch.Tensor):
|
| 202 |
+
# TODO: improve these names with FQN
|
| 203 |
+
writer.tensor(placeholder, arg)
|
| 204 |
+
else:
|
| 205 |
+
raise TypeError(f"arg is neither SymInt/int nor torch.Tensor, {arg}")
|
| 206 |
+
load_args = "\n".join(writer.lines())
|
| 207 |
+
|
| 208 |
+
return textwrap.dedent(
|
| 209 |
+
f"""
|
| 210 |
+
{generate_env_vars_string(stable_output=stable_output)}
|
| 211 |
+
from math import inf
|
| 212 |
+
import torch
|
| 213 |
+
from torch import tensor, device
|
| 214 |
+
import torch.fx as fx
|
| 215 |
+
import torch._dynamo
|
| 216 |
+
from torch._dynamo.testing import rand_strided
|
| 217 |
+
from torch._dynamo.debug_utils import run_fwd_maybe_bwd
|
| 218 |
+
|
| 219 |
+
{generate_config_string(stable_output=stable_output)}
|
| 220 |
+
|
| 221 |
+
{extra_imports}
|
| 222 |
+
|
| 223 |
+
{model_str}
|
| 224 |
+
mod = Repro()
|
| 225 |
+
|
| 226 |
+
{load_args}
|
| 227 |
+
|
| 228 |
+
if __name__ == '__main__':
|
| 229 |
+
from torch._dynamo.repro.after_dynamo import run_repro
|
| 230 |
+
run_repro(mod, load_args, accuracy={check_accuracy!r}, command={command!r},
|
| 231 |
+
save_dir={save_dir!r}, autocast={torch.is_autocast_enabled()!r}, backend={compiler_name!r})
|
| 232 |
+
"""
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def dump_backend_repro_as_file(
|
| 237 |
+
gm: torch.fx.GraphModule,
|
| 238 |
+
args: Sequence[Any],
|
| 239 |
+
compiler_name: Optional[str],
|
| 240 |
+
check_accuracy: bool = False,
|
| 241 |
+
) -> None:
|
| 242 |
+
"""
|
| 243 |
+
Saves the repro to a repro.py file
|
| 244 |
+
"""
|
| 245 |
+
curdir = os.getcwd()
|
| 246 |
+
subdir = os.path.join(os.getcwd(), "checkpoints")
|
| 247 |
+
if not os.path.exists(subdir):
|
| 248 |
+
os.makedirs(subdir, exist_ok=True)
|
| 249 |
+
file_name = os.path.join(subdir, f"minified_{len(gm.graph.nodes)}_nodes.py")
|
| 250 |
+
log.warning(
|
| 251 |
+
"Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
with open(file_name, "w") as fd:
|
| 255 |
+
fd.write(
|
| 256 |
+
generate_dynamo_fx_repro_string(
|
| 257 |
+
gm, args, compiler_name, check_accuracy, save_dir=subdir
|
| 258 |
+
)
|
| 259 |
+
)
|
| 260 |
+
latest_repro = os.path.join(curdir, "repro.py")
|
| 261 |
+
log.warning("Copying %s to %s for convenience", file_name, latest_repro)
|
| 262 |
+
|
| 263 |
+
if use_buck:
|
| 264 |
+
BuckTargetWriter(latest_repro).write()
|
| 265 |
+
|
| 266 |
+
shutil.copyfile(file_name, latest_repro)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def dump_backend_state(
|
| 270 |
+
gm: torch.fx.GraphModule,
|
| 271 |
+
args: Sequence[Any],
|
| 272 |
+
compiler_name: Optional[str],
|
| 273 |
+
check_accuracy: bool = False,
|
| 274 |
+
) -> None:
|
| 275 |
+
"""
|
| 276 |
+
Dumps the dynamo graph to repro the issue.
|
| 277 |
+
1) It tries to convert Fx GraphModule to a string. If we can, it writes to a
|
| 278 |
+
repro.py file.
|
| 279 |
+
2) If we can't convert Fx GraphModule to a string, we use to_folder to save
|
| 280 |
+
the module and save a tar file.
|
| 281 |
+
"""
|
| 282 |
+
assert NNModuleToString.can_convert_to_string(gm)
|
| 283 |
+
return dump_backend_repro_as_file(gm, args, compiler_name, check_accuracy)
|
| 284 |
+
# return dump_backend_repro_as_tarfile(gm, args, compiler_name)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 288 |
+
# MINIFIER DUMPER
|
| 289 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def dump_to_minify_after_dynamo(
|
| 293 |
+
gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: Optional[str]
|
| 294 |
+
) -> None:
|
| 295 |
+
# TODO: factor this out
|
| 296 |
+
subdir = os.path.join(minifier_dir(), "checkpoints")
|
| 297 |
+
if not os.path.exists(subdir):
|
| 298 |
+
os.makedirs(subdir, exist_ok=True)
|
| 299 |
+
helper_for_dump_minify(
|
| 300 |
+
generate_dynamo_fx_repro_string(
|
| 301 |
+
gm,
|
| 302 |
+
args,
|
| 303 |
+
compiler_name,
|
| 304 |
+
check_accuracy=config.repro_level == 4,
|
| 305 |
+
save_dir=subdir,
|
| 306 |
+
command="minify",
|
| 307 |
+
)
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 312 |
+
# MINIFIER BACKENDS
|
| 313 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
@register_debug_backend # type: ignore[arg-type]
|
| 317 |
+
def dynamo_minifier_backend(
|
| 318 |
+
gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: Optional[str]
|
| 319 |
+
) -> fx.GraphModule:
|
| 320 |
+
from functorch.compile import minifier
|
| 321 |
+
|
| 322 |
+
compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type]
|
| 323 |
+
|
| 324 |
+
# TODO: It's inconsistent to pass SymInt inputs but REAL tensors.
|
| 325 |
+
# We should pass ints and look at the GraphModule placeholders
|
| 326 |
+
# to resolve them to SymInt (if necessary)
|
| 327 |
+
example_inputs = [
|
| 328 |
+
i.node.hint if isinstance(i, torch.SymInt) else i for i in example_inputs
|
| 329 |
+
]
|
| 330 |
+
|
| 331 |
+
try:
|
| 332 |
+
compiled_gm = compiler_fn(gm, example_inputs)
|
| 333 |
+
run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type]
|
| 334 |
+
raise ValueError("No issue was detected")
|
| 335 |
+
except Exception as exc:
|
| 336 |
+
orig_failure = str(exc)
|
| 337 |
+
log.warning(
|
| 338 |
+
"Compiled Fx GraphModule failed. Creating script to minify the error."
|
| 339 |
+
)
|
| 340 |
+
dump_state_fn = functools.partial(
|
| 341 |
+
dump_backend_state, compiler_name=compiler_name
|
| 342 |
+
)
|
| 343 |
+
dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs)
|
| 344 |
+
fails_fn = functools.partial(
|
| 345 |
+
backend_fails,
|
| 346 |
+
compiler_fn=compiler_fn,
|
| 347 |
+
orig_failure=orig_failure,
|
| 348 |
+
)
|
| 349 |
+
minifier(
|
| 350 |
+
gm,
|
| 351 |
+
example_inputs,
|
| 352 |
+
module_fails=fails_fn,
|
| 353 |
+
dump_state=dump_state_fn,
|
| 354 |
+
)
|
| 355 |
+
return gm
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@register_debug_backend # type: ignore[arg-type]
|
| 359 |
+
def dynamo_accuracy_minifier_backend(
|
| 360 |
+
gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: Optional[str]
|
| 361 |
+
) -> fx.GraphModule:
|
| 362 |
+
from functorch.compile import minifier
|
| 363 |
+
|
| 364 |
+
compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type]
|
| 365 |
+
|
| 366 |
+
# Set the eval mode to remove randomness.
|
| 367 |
+
gm.eval()
|
| 368 |
+
|
| 369 |
+
# Check Accuracy
|
| 370 |
+
if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type]
|
| 371 |
+
log.warning("Accuracy failed for the TorchDynamo produced graph")
|
| 372 |
+
dump_state_fn = functools.partial(
|
| 373 |
+
dump_backend_state, compiler_name=compiler_name, check_accuracy=True
|
| 374 |
+
)
|
| 375 |
+
fails_fn = functools.partial(
|
| 376 |
+
_accuracy_fails,
|
| 377 |
+
compiler_fn=compiler_fn, # type: ignore[arg-type]
|
| 378 |
+
)
|
| 379 |
+
dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs)
|
| 380 |
+
minifier(
|
| 381 |
+
gm,
|
| 382 |
+
example_inputs,
|
| 383 |
+
module_fails=fails_fn,
|
| 384 |
+
dump_state=dump_state_fn,
|
| 385 |
+
)
|
| 386 |
+
else:
|
| 387 |
+
log.error("Input graph does not fail accuracy testing")
|
| 388 |
+
return gm
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def backend_fails(
|
| 392 |
+
gm: fx.GraphModule,
|
| 393 |
+
example_inputs: Sequence[Any],
|
| 394 |
+
compiler_fn: CompilerFn,
|
| 395 |
+
orig_failure: Sequence[Any],
|
| 396 |
+
) -> bool:
|
| 397 |
+
"""
|
| 398 |
+
Minifier uses this function to identify if the minified graph module fails
|
| 399 |
+
with the same error.
|
| 400 |
+
|
| 401 |
+
One caveat is that minifier can potentially go into a wrong direction when
|
| 402 |
+
the resulting graph module fails for a different reason. To avoid this, we
|
| 403 |
+
save the string for the original exception and check similarity between new
|
| 404 |
+
and old exception. They can be somewhat different in some cases, when the
|
| 405 |
+
exception string depends on the failing node information. So, we have a
|
| 406 |
+
loose similarity metric to guide the minifier path.
|
| 407 |
+
"""
|
| 408 |
+
from difflib import SequenceMatcher
|
| 409 |
+
|
| 410 |
+
try:
|
| 411 |
+
# Run the original gm to check eager validity
|
| 412 |
+
run_fwd_maybe_bwd(gm, clone_inputs_retaining_gradness(example_inputs))
|
| 413 |
+
compiled_gm = compiler_fn(gm, example_inputs) # type: ignore[arg-type]
|
| 414 |
+
run_fwd_maybe_bwd(compiled_gm, clone_inputs_retaining_gradness(example_inputs)) # type: ignore[arg-type]
|
| 415 |
+
except Exception as e:
|
| 416 |
+
new_failure = str(e)
|
| 417 |
+
if SequenceMatcher(None, orig_failure, new_failure).ratio() > 0.5:
|
| 418 |
+
return True
|
| 419 |
+
return False
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 423 |
+
# REPRO MAIN
|
| 424 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def run_load_args(options: Any, mod: torch.nn.Module, load_args: Any) -> list[Any]:
|
| 428 |
+
if not hasattr(load_args, "_version"):
|
| 429 |
+
log.warning(
|
| 430 |
+
"load_args does not have a _version attribute, please file a bug to PyTorch "
|
| 431 |
+
"and describe how you generate this repro script"
|
| 432 |
+
)
|
| 433 |
+
else:
|
| 434 |
+
if load_args._version > 0:
|
| 435 |
+
log.warning(
|
| 436 |
+
"load_args is version %s, but this version of PyTorch only supports "
|
| 437 |
+
"version 0. We will try to run it anyway but there may be an incompatibility; "
|
| 438 |
+
"if so, try upgrading your version of PyTorch.",
|
| 439 |
+
load_args._version,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
nop_reader = NopInputReader()
|
| 443 |
+
load_args(nop_reader)
|
| 444 |
+
|
| 445 |
+
with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar:
|
| 446 |
+
input_reader = InputReader(save_dir=options.save_dir, pbar=pbar)
|
| 447 |
+
load_args(input_reader)
|
| 448 |
+
args = input_reader.args
|
| 449 |
+
|
| 450 |
+
return args
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def repro_minify(options: Any, mod: torch.nn.Module, load_args: Any) -> None:
|
| 454 |
+
args = run_load_args(options, mod, load_args)
|
| 455 |
+
|
| 456 |
+
# Setup debug minifier compiler
|
| 457 |
+
if not options.accuracy:
|
| 458 |
+
compiler_fn = lookup_backend("dynamo_minifier_backend")
|
| 459 |
+
else:
|
| 460 |
+
compiler_fn = lookup_backend("dynamo_accuracy_minifier_backend")
|
| 461 |
+
|
| 462 |
+
if options.backend is None:
|
| 463 |
+
raise RuntimeError(
|
| 464 |
+
"Compiler name is None - this likely means that a custom compiler "
|
| 465 |
+
"was called by torchdynamo. Please remove this error, import your "
|
| 466 |
+
"custom compiler function, and replace the backend=None "
|
| 467 |
+
"line in run_repro to backend=<my_imported_custom_function>"
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
dynamo_minifier_backend = functools.partial(
|
| 471 |
+
compiler_fn,
|
| 472 |
+
compiler_name=options.backend, # type: ignore[call-arg]
|
| 473 |
+
)
|
| 474 |
+
opt_mod = torch._dynamo.optimize(dynamo_minifier_backend)(mod)
|
| 475 |
+
|
| 476 |
+
with torch.amp.autocast("cuda", enabled=options.autocast):
|
| 477 |
+
opt_mod(*args)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def repro_run(options: Any, mod: torch.nn.Module, load_args: Any) -> None:
|
| 481 |
+
opt_mod = torch._dynamo.optimize(options.backend)(mod)
|
| 482 |
+
|
| 483 |
+
if options.accuracy != "":
|
| 484 |
+
mod.eval()
|
| 485 |
+
opt_mod.eval() # type: ignore[union-attr]
|
| 486 |
+
|
| 487 |
+
with torch.amp.autocast("cuda", enabled=options.autocast):
|
| 488 |
+
# TODO: disable clone
|
| 489 |
+
args = run_load_args(options, mod, load_args)
|
| 490 |
+
assert same_two_models(mod, mod, args), "Eager itself failed" # type: ignore[arg-type]
|
| 491 |
+
if not same_two_models(
|
| 492 |
+
mod, # type: ignore[arg-type]
|
| 493 |
+
opt_mod, # type: ignore[arg-type]
|
| 494 |
+
args,
|
| 495 |
+
only_fwd=config.repro_forward_only,
|
| 496 |
+
ignore_non_fp=config.repro_ignore_non_fp,
|
| 497 |
+
):
|
| 498 |
+
raise AccuracyError("Dynamo failed")
|
| 499 |
+
else:
|
| 500 |
+
with torch.amp.autocast("cuda", enabled=options.autocast):
|
| 501 |
+
args = run_load_args(options, mod, load_args)
|
| 502 |
+
run_fwd_maybe_bwd(mod, args, only_fwd=options.only_fwd, disable_clone=True) # type: ignore[arg-type]
|
| 503 |
+
del args
|
| 504 |
+
|
| 505 |
+
args = run_load_args(options, mod, load_args)
|
| 506 |
+
run_fwd_maybe_bwd(
|
| 507 |
+
opt_mod, # type: ignore[arg-type]
|
| 508 |
+
args,
|
| 509 |
+
only_fwd=options.only_fwd,
|
| 510 |
+
disable_clone=True, # type: ignore[arg-type]
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def run_repro(
|
| 515 |
+
mod: torch.nn.Module,
|
| 516 |
+
load_args: Any,
|
| 517 |
+
*,
|
| 518 |
+
command: str = "run",
|
| 519 |
+
accuracy: Union[bool, str] = "",
|
| 520 |
+
save_dir: Optional[str] = None,
|
| 521 |
+
autocast: bool = False,
|
| 522 |
+
backend: str = "inductor",
|
| 523 |
+
**kwargs: Any,
|
| 524 |
+
) -> None:
|
| 525 |
+
for k in kwargs:
|
| 526 |
+
log.warning(
|
| 527 |
+
"Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch",
|
| 528 |
+
k,
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
if accuracy is True:
|
| 532 |
+
accuracy = "accuracy"
|
| 533 |
+
elif accuracy is False:
|
| 534 |
+
accuracy = ""
|
| 535 |
+
|
| 536 |
+
parser = argparse.ArgumentParser(
|
| 537 |
+
description=f"""\
|
| 538 |
+
An after_dynamo repro script, typically triggering a bug in Dynamo or
|
| 539 |
+
AOTAutograd. When run with no arguments, this script defaults to running
|
| 540 |
+
'{command}'. Extra flags may be available; to find out more, try '{command}
|
| 541 |
+
--help'. There are also alternate subcommands available, see below.
|
| 542 |
+
|
| 543 |
+
default settings on this script:
|
| 544 |
+
{accuracy=}
|
| 545 |
+
{save_dir=}
|
| 546 |
+
""",
|
| 547 |
+
formatter_class=argparse.RawTextHelpFormatter,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
def common_flags(parser: argparse.ArgumentParser) -> None:
|
| 551 |
+
accuracy_group = parser.add_mutually_exclusive_group()
|
| 552 |
+
accuracy_group.add_argument(
|
| 553 |
+
"--no-accuracy",
|
| 554 |
+
dest="accuracy",
|
| 555 |
+
action="store_const",
|
| 556 |
+
const="",
|
| 557 |
+
default=accuracy,
|
| 558 |
+
help="do not test accuracy, just run the module and see if it errors",
|
| 559 |
+
)
|
| 560 |
+
accuracy_group.add_argument(
|
| 561 |
+
"--accuracy",
|
| 562 |
+
action="store_const",
|
| 563 |
+
const="accuracy",
|
| 564 |
+
default=accuracy,
|
| 565 |
+
help="test accuracy",
|
| 566 |
+
)
|
| 567 |
+
parser.add_argument(
|
| 568 |
+
"--save-dir",
|
| 569 |
+
type=str,
|
| 570 |
+
default=save_dir,
|
| 571 |
+
metavar="DIR",
|
| 572 |
+
help="directory where saved inputs live",
|
| 573 |
+
)
|
| 574 |
+
parser.add_argument(
|
| 575 |
+
"--no-save-dir",
|
| 576 |
+
dest="save_dir",
|
| 577 |
+
action="store_const",
|
| 578 |
+
const=None,
|
| 579 |
+
help="don't use any directory for saved inputs",
|
| 580 |
+
)
|
| 581 |
+
parser.add_argument(
|
| 582 |
+
"--no-isolate",
|
| 583 |
+
dest="isolate",
|
| 584 |
+
action="store_false",
|
| 585 |
+
default=False,
|
| 586 |
+
help="no isolate (doesn't do anything for after_dynamo)",
|
| 587 |
+
)
|
| 588 |
+
parser.add_argument(
|
| 589 |
+
"--autocast",
|
| 590 |
+
default=autocast,
|
| 591 |
+
action="store_true",
|
| 592 |
+
help="use torch.cuda.amp.autocast",
|
| 593 |
+
)
|
| 594 |
+
parser.add_argument(
|
| 595 |
+
"--no-autocast",
|
| 596 |
+
dest="autocast",
|
| 597 |
+
action="store_false",
|
| 598 |
+
help="don't use torch.cuda.amp.autocast",
|
| 599 |
+
)
|
| 600 |
+
parser.add_argument(
|
| 601 |
+
"--backend",
|
| 602 |
+
type=str,
|
| 603 |
+
default=backend,
|
| 604 |
+
metavar="BACKEND",
|
| 605 |
+
help="torch.compile backend to use",
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
subparsers = parser.add_subparsers(
|
| 609 |
+
dest="command", metavar="{run,minify}", required=True
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
parser_run = subparsers.add_parser(
|
| 613 |
+
"run",
|
| 614 |
+
help="just run the repro",
|
| 615 |
+
)
|
| 616 |
+
common_flags(parser_run)
|
| 617 |
+
parser_run.add_argument(
|
| 618 |
+
"--only-fwd",
|
| 619 |
+
action="store_true",
|
| 620 |
+
help="don't run backwards compilation for testing",
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
parser_minify = subparsers.add_parser(
|
| 624 |
+
"minify", help="run the minifier on the repro"
|
| 625 |
+
)
|
| 626 |
+
common_flags(parser_minify)
|
| 627 |
+
|
| 628 |
+
args = None
|
| 629 |
+
if len(sys.argv) <= 1:
|
| 630 |
+
args = [command, *sys.argv[1:]]
|
| 631 |
+
|
| 632 |
+
options = parser.parse_args(args)
|
| 633 |
+
COMMAND_FNS = {
|
| 634 |
+
"minify": repro_minify,
|
| 635 |
+
"run": repro_run,
|
| 636 |
+
}
|
| 637 |
+
COMMAND_FNS[options.command](options, mod, load_args)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/repro/aoti.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities for debugging and reproducing issues in Ahead of Time with Inductor (AOTI) compilation.
|
| 3 |
+
|
| 4 |
+
This file provides tools and utilities for:
|
| 5 |
+
- Generating minimal reproducible test cases (minification)
|
| 6 |
+
- Handling exported programs and graph modules
|
| 7 |
+
- Creating debug repros for AOTI compilation issues
|
| 8 |
+
- Supporting both accuracy testing and error reproduction
|
| 9 |
+
- Managing configuration and environment for repro cases
|
| 10 |
+
|
| 11 |
+
The main components include:
|
| 12 |
+
- Minification tools to reduce test cases while preserving errors
|
| 13 |
+
- Repro generation utilities for exported programs
|
| 14 |
+
- Error handling specific to AOTI compilation
|
| 15 |
+
- Command-line interface for running and managing repros
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import functools
|
| 20 |
+
import io
|
| 21 |
+
import logging
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import shutil
|
| 25 |
+
import sys
|
| 26 |
+
import textwrap
|
| 27 |
+
from collections.abc import Sequence
|
| 28 |
+
from importlib import import_module
|
| 29 |
+
from typing import Any, IO, Optional, Union
|
| 30 |
+
|
| 31 |
+
import torch
|
| 32 |
+
from torch._dynamo.debug_utils import (
|
| 33 |
+
_cuda_system_info_comment,
|
| 34 |
+
BuckTargetWriter,
|
| 35 |
+
extra_imports,
|
| 36 |
+
generate_config_string,
|
| 37 |
+
generate_env_vars_string,
|
| 38 |
+
helper_for_dump_minify,
|
| 39 |
+
InputReader,
|
| 40 |
+
minifier_dir,
|
| 41 |
+
NNModuleToString,
|
| 42 |
+
NopInputReader,
|
| 43 |
+
)
|
| 44 |
+
from torch.export import ExportedProgram
|
| 45 |
+
from torch.hub import tqdm
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
log = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
inductor_config = import_module("torch._inductor.config")
|
| 52 |
+
use_buck = inductor_config.is_fbcode()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class AOTIMinifierError(Exception):
|
| 56 |
+
def __init__(self, original_exception: Union[str, Exception]) -> None:
|
| 57 |
+
additional_message = "This error is caused by a bug in the AOTI minifier, please report a bug to PyTorch"
|
| 58 |
+
full_message = f"{additional_message}: {str(original_exception)}"
|
| 59 |
+
super().__init__(full_message)
|
| 60 |
+
self.original_exception = original_exception
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def dump_to_minify(
|
| 64 |
+
exported_program: ExportedProgram,
|
| 65 |
+
compiler_name: str,
|
| 66 |
+
command: str = "minify",
|
| 67 |
+
options: Optional[dict[str, Any]] = None,
|
| 68 |
+
) -> None:
|
| 69 |
+
"""
|
| 70 |
+
If command is "minify":
|
| 71 |
+
Dump exported_program to `debug_dir/minifier/minifier_launcher.py`, with minify command.
|
| 72 |
+
If command is "run":
|
| 73 |
+
Dump exported_program to `cwd/repro.py`, with run command.
|
| 74 |
+
"""
|
| 75 |
+
assert command in ["minify", "run"]
|
| 76 |
+
|
| 77 |
+
subdir = os.path.join(minifier_dir(), "checkpoints")
|
| 78 |
+
if not os.path.exists(subdir):
|
| 79 |
+
os.makedirs(subdir, exist_ok=True)
|
| 80 |
+
|
| 81 |
+
if command == "minify":
|
| 82 |
+
out = io.StringIO()
|
| 83 |
+
save_graph_repro_ep(
|
| 84 |
+
out,
|
| 85 |
+
compiler_name,
|
| 86 |
+
exported_program=exported_program,
|
| 87 |
+
save_dir=subdir,
|
| 88 |
+
command="minify",
|
| 89 |
+
config_patches=options,
|
| 90 |
+
)
|
| 91 |
+
return helper_for_dump_minify(out.getvalue())
|
| 92 |
+
else:
|
| 93 |
+
curdir = os.getcwd()
|
| 94 |
+
file_name = os.path.join(curdir, "repro.py")
|
| 95 |
+
try:
|
| 96 |
+
with open(file_name, "w") as fd:
|
| 97 |
+
save_graph_repro_ep(
|
| 98 |
+
fd,
|
| 99 |
+
compiler_name,
|
| 100 |
+
exported_program=exported_program,
|
| 101 |
+
config_patches=options,
|
| 102 |
+
save_dir=subdir,
|
| 103 |
+
command="run",
|
| 104 |
+
module_in_comment=True,
|
| 105 |
+
)
|
| 106 |
+
log.warning("Writing repro file to %s", file_name)
|
| 107 |
+
if use_buck:
|
| 108 |
+
BuckTargetWriter(file_name).write()
|
| 109 |
+
except OSError:
|
| 110 |
+
log.warning("No write permissions for %s", file_name)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def get_module_string(gm: torch.fx.GraphModule) -> str:
|
| 114 |
+
def _convert_to_comment(s_: str) -> str:
|
| 115 |
+
s = s_.split("\n")
|
| 116 |
+
if len(s) == 1:
|
| 117 |
+
return "# " + s_
|
| 118 |
+
first = s.pop(0)
|
| 119 |
+
for i in range(len(s)):
|
| 120 |
+
line = s[i]
|
| 121 |
+
if line.strip() != "":
|
| 122 |
+
s[i] = "# " + line
|
| 123 |
+
else:
|
| 124 |
+
s[i] = ""
|
| 125 |
+
s = "\n".join(s)
|
| 126 |
+
s = first + "\n" + s
|
| 127 |
+
return s
|
| 128 |
+
|
| 129 |
+
module_string = NNModuleToString.convert(gm)
|
| 130 |
+
return _convert_to_comment(module_string)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def save_graph_repro_ep(
|
| 134 |
+
fd: IO[Any],
|
| 135 |
+
compiler_name: str,
|
| 136 |
+
*,
|
| 137 |
+
exported_program: Optional[ExportedProgram] = None,
|
| 138 |
+
gm: Optional[torch.nn.Module] = None,
|
| 139 |
+
args: Optional[tuple[Any]] = None,
|
| 140 |
+
config_patches: Optional[dict[str, str]] = None,
|
| 141 |
+
stable_output: bool = False,
|
| 142 |
+
save_dir: Optional[str] = None,
|
| 143 |
+
command: str = "run",
|
| 144 |
+
accuracy: Optional[Union[str, bool]] = None,
|
| 145 |
+
check_str: Optional[str] = None,
|
| 146 |
+
module_in_comment: bool = False,
|
| 147 |
+
strict: bool = False,
|
| 148 |
+
) -> None:
|
| 149 |
+
# Save graph for reproducing the error.
|
| 150 |
+
# Either exported_program or gm will be saved, depending on which one is defined.
|
| 151 |
+
# Only one of exported_program and gm should be defined.
|
| 152 |
+
|
| 153 |
+
if exported_program is None and gm is None:
|
| 154 |
+
raise AOTIMinifierError("One of exported_program and gm must be defined")
|
| 155 |
+
if exported_program is not None and gm is not None:
|
| 156 |
+
raise AOTIMinifierError("Only one of exported_program and gm can be defined")
|
| 157 |
+
if gm is not None and args is None:
|
| 158 |
+
raise AOTIMinifierError("If gm is defined, args should also be defined")
|
| 159 |
+
|
| 160 |
+
if exported_program is None:
|
| 161 |
+
assert gm is not None
|
| 162 |
+
assert args is not None
|
| 163 |
+
exported_program = torch.export.export(gm, args, strict=strict)
|
| 164 |
+
elif gm is None:
|
| 165 |
+
gm = exported_program.module(check_guards=False)
|
| 166 |
+
|
| 167 |
+
# save a graph preview using gm
|
| 168 |
+
module_string = get_module_string(gm) # type: ignore[arg-type]
|
| 169 |
+
fd.write(module_string)
|
| 170 |
+
|
| 171 |
+
# save a graph repro using exported_program
|
| 172 |
+
fd.write(
|
| 173 |
+
generate_compiler_repro_exported_program(
|
| 174 |
+
exported_program,
|
| 175 |
+
options=config_patches,
|
| 176 |
+
stable_output=stable_output,
|
| 177 |
+
save_dir=save_dir,
|
| 178 |
+
)
|
| 179 |
+
)
|
| 180 |
+
if accuracy is None:
|
| 181 |
+
accuracy = "_accuracy" in compiler_name
|
| 182 |
+
fd.write("if __name__ == '__main__':\n")
|
| 183 |
+
fd.write(" from torch._dynamo.repro.aoti import run_repro\n")
|
| 184 |
+
fd.write(
|
| 185 |
+
f" with torch.no_grad():\n"
|
| 186 |
+
f" run_repro(exported_program, config_patches=config_patches, accuracy={accuracy!r}, command={command!r}, "
|
| 187 |
+
f"save_dir={save_dir!r}, check_str={check_str!r})\n"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def dump_compiler_graph_state(
|
| 192 |
+
gm: torch.fx.GraphModule,
|
| 193 |
+
args: Sequence[Any],
|
| 194 |
+
compiler_name: str,
|
| 195 |
+
*,
|
| 196 |
+
config_patches: Optional[dict[str, str]] = None,
|
| 197 |
+
accuracy: Optional[Union[str, bool]] = None,
|
| 198 |
+
strict: bool = False,
|
| 199 |
+
) -> None:
|
| 200 |
+
subdir = os.path.join(minifier_dir(), "checkpoints")
|
| 201 |
+
if not os.path.exists(subdir):
|
| 202 |
+
os.makedirs(subdir, exist_ok=True)
|
| 203 |
+
file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py")
|
| 204 |
+
log.warning(
|
| 205 |
+
"Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name
|
| 206 |
+
)
|
| 207 |
+
with open(file_name, "w") as fd:
|
| 208 |
+
save_graph_repro_ep(
|
| 209 |
+
fd,
|
| 210 |
+
compiler_name,
|
| 211 |
+
gm=gm,
|
| 212 |
+
args=tuple(args),
|
| 213 |
+
config_patches=config_patches,
|
| 214 |
+
save_dir=subdir,
|
| 215 |
+
accuracy=accuracy,
|
| 216 |
+
module_in_comment=True,
|
| 217 |
+
strict=strict,
|
| 218 |
+
)
|
| 219 |
+
curdir = os.getcwd()
|
| 220 |
+
repro_path = os.path.join(curdir, "repro.py")
|
| 221 |
+
try:
|
| 222 |
+
shutil.copyfile(file_name, repro_path)
|
| 223 |
+
log.warning("Copying repro file for convenience to %s", repro_path)
|
| 224 |
+
if use_buck:
|
| 225 |
+
BuckTargetWriter(file_name).write()
|
| 226 |
+
except OSError:
|
| 227 |
+
log.warning("No write permissions for %s", repro_path)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 231 |
+
# DUMP REPROS
|
| 232 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def generate_compiler_repro_exported_program(
|
| 236 |
+
exported_program: ExportedProgram,
|
| 237 |
+
*,
|
| 238 |
+
options: Optional[dict[str, str]] = None,
|
| 239 |
+
stable_output: bool = False,
|
| 240 |
+
save_dir: Optional[str] = None,
|
| 241 |
+
) -> str:
|
| 242 |
+
model_str = textwrap.dedent(
|
| 243 |
+
f"""
|
| 244 |
+
{generate_env_vars_string(stable_output=stable_output)}
|
| 245 |
+
import torch
|
| 246 |
+
import torch._inductor.inductor_prims
|
| 247 |
+
|
| 248 |
+
{generate_config_string(stable_output=stable_output)}
|
| 249 |
+
|
| 250 |
+
isolate_fails_code_str = None
|
| 251 |
+
|
| 252 |
+
{extra_imports}
|
| 253 |
+
|
| 254 |
+
"""
|
| 255 |
+
)
|
| 256 |
+
if not stable_output:
|
| 257 |
+
model_str += f"# torch version: {torch.version.__version__}\n"
|
| 258 |
+
if hasattr(torch.version, "cuda"):
|
| 259 |
+
model_str += f"# torch cuda version: {torch.version.cuda}\n"
|
| 260 |
+
if hasattr(torch.version, "git_version"):
|
| 261 |
+
model_str += f"# torch git version: {torch.version.git_version}\n\n\n"
|
| 262 |
+
model_str += _cuda_system_info_comment()
|
| 263 |
+
if save_dir:
|
| 264 |
+
ep_path = os.path.join(save_dir, "exported_program.pt2")
|
| 265 |
+
else:
|
| 266 |
+
ep_path = "exported_program.pt2"
|
| 267 |
+
torch.export.save(exported_program, ep_path)
|
| 268 |
+
|
| 269 |
+
model_str += f"exported_program = torch.export.load('{ep_path}')\n"
|
| 270 |
+
model_str += "# print(exported_program.graph)\n"
|
| 271 |
+
model_str += f"config_patches={options}\n"
|
| 272 |
+
return model_str
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def repro_load_args(load_args: Any, save_dir: Optional[str]) -> tuple[Any]:
|
| 276 |
+
if not hasattr(load_args, "_version"):
|
| 277 |
+
log.warning(
|
| 278 |
+
"load_args does not have a _version attribute, please file a bug to PyTorch "
|
| 279 |
+
"and describe how you generate this repro script"
|
| 280 |
+
)
|
| 281 |
+
else:
|
| 282 |
+
if load_args._version > 0:
|
| 283 |
+
log.warning(
|
| 284 |
+
"load_args is version %s, but this version of PyTorch only supports "
|
| 285 |
+
"version 0. We will try to run it anyway but there may be an incompatibility; "
|
| 286 |
+
"if so, try upgrading your version of PyTorch.",
|
| 287 |
+
load_args._version,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
nop_reader = NopInputReader()
|
| 291 |
+
load_args(nop_reader)
|
| 292 |
+
|
| 293 |
+
with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar:
|
| 294 |
+
input_reader = InputReader(save_dir=save_dir, pbar=pbar)
|
| 295 |
+
load_args(input_reader)
|
| 296 |
+
args = input_reader.args
|
| 297 |
+
|
| 298 |
+
return tuple(args)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def repro_common(
|
| 302 |
+
options: Any, exported_program: ExportedProgram
|
| 303 |
+
) -> tuple[torch.fx.GraphModule, Any, Any]:
|
| 304 |
+
# pyrefly: ignore [bad-assignment]
|
| 305 |
+
torch._inductor.config.generate_intermediate_hooks = True
|
| 306 |
+
mod = exported_program.module(check_guards=False)
|
| 307 |
+
args, kwargs = exported_program.example_inputs
|
| 308 |
+
return mod, args, kwargs # type: ignore[return-value]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def repro_get_args(
|
| 312 |
+
options: Any,
|
| 313 |
+
exported_program: ExportedProgram,
|
| 314 |
+
config_patches: Optional[dict[str, Any]],
|
| 315 |
+
) -> tuple[torch.fx.GraphModule, Any, Any]:
|
| 316 |
+
mod, args, kwargs = repro_common(options, exported_program)
|
| 317 |
+
return mod, args, kwargs
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def repro_run(
|
| 321 |
+
options: Any,
|
| 322 |
+
exported_program: ExportedProgram,
|
| 323 |
+
config_patches: Optional[dict[str, Any]],
|
| 324 |
+
) -> None:
|
| 325 |
+
from torch._inductor import _aoti_compile_and_package_inner
|
| 326 |
+
|
| 327 |
+
gm, args, kwargs = repro_common(options, exported_program)
|
| 328 |
+
|
| 329 |
+
from torch.cuda import synchronize
|
| 330 |
+
|
| 331 |
+
_aoti_compile_and_package_inner(
|
| 332 |
+
gm,
|
| 333 |
+
args,
|
| 334 |
+
kwargs,
|
| 335 |
+
load_and_run=True,
|
| 336 |
+
check_accuracy=options.accuracy,
|
| 337 |
+
inductor_configs=config_patches,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
need_sync = False
|
| 341 |
+
|
| 342 |
+
for arg in args:
|
| 343 |
+
if isinstance(arg, torch.Tensor) and arg.is_cuda:
|
| 344 |
+
need_sync = True
|
| 345 |
+
break
|
| 346 |
+
|
| 347 |
+
if need_sync:
|
| 348 |
+
synchronize() # ensure segfaults are surfaced
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def export_for_aoti_minifier(
|
| 352 |
+
gm: torch.nn.Module,
|
| 353 |
+
tuple_inputs: tuple[Any],
|
| 354 |
+
strict: bool = False,
|
| 355 |
+
skip_export_error: bool = True,
|
| 356 |
+
) -> Optional[torch.nn.Module]:
|
| 357 |
+
# Some graphs cannot be used for AOTI/export (illegal graphs), these should be
|
| 358 |
+
# considered as graphs that don't fail in the minifier, so the minifier keeps searching.
|
| 359 |
+
# In these case, we return None. Otherwise, we return the exported graph module.
|
| 360 |
+
# This won't affect the minifier result because the minifier is only responsible for catching
|
| 361 |
+
# errors in AOTI, not export.
|
| 362 |
+
#
|
| 363 |
+
# Please add to this list of illegal graphs if you change the implementation here.
|
| 364 |
+
# - graph output is not allowed by export
|
| 365 |
+
#
|
| 366 |
+
# If skip_export_error=True, then the errors in export will not be raised, and the minifier
|
| 367 |
+
# will keep exploring and ignore this graph.
|
| 368 |
+
from torch._dynamo.exc import UserError, UserErrorType
|
| 369 |
+
|
| 370 |
+
try:
|
| 371 |
+
ep = torch.export.export(gm, tuple_inputs, strict=strict)
|
| 372 |
+
gm = ep.module(check_guards=False)
|
| 373 |
+
return gm
|
| 374 |
+
except Exception as e:
|
| 375 |
+
if skip_export_error:
|
| 376 |
+
return None
|
| 377 |
+
if isinstance(e, UserError) and e.error_type == UserErrorType.INVALID_OUTPUT:
|
| 378 |
+
# graph output is not allowed by export when strict=True
|
| 379 |
+
return None
|
| 380 |
+
if isinstance(e, RuntimeError):
|
| 381 |
+
# graph output is not allowed by export when strict=False
|
| 382 |
+
pattern = r"Found .* in output, which is not a known type\."
|
| 383 |
+
if re.search(pattern, str(e)) is not None:
|
| 384 |
+
return None
|
| 385 |
+
raise AOTIMinifierError(e) from e
|
| 386 |
+
# we should never reach here
|
| 387 |
+
return None
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def repro_minify(
|
| 391 |
+
options: Any,
|
| 392 |
+
exported_program: ExportedProgram,
|
| 393 |
+
config_patches: Optional[dict[str, Any]],
|
| 394 |
+
) -> None:
|
| 395 |
+
from functorch.compile import minifier
|
| 396 |
+
from torch._inductor import _aoti_compile_and_package_inner
|
| 397 |
+
from torch._inductor.compile_fx import _aoti_flatten_inputs
|
| 398 |
+
|
| 399 |
+
mod, args, kwargs = repro_common(options, exported_program)
|
| 400 |
+
|
| 401 |
+
# update serialized_in_spec and serialized_out_spec
|
| 402 |
+
flat_example_inputs, inductor_configs = _aoti_flatten_inputs(
|
| 403 |
+
mod, args, kwargs, options=config_patches
|
| 404 |
+
)
|
| 405 |
+
compiler_name = "aot_inductor"
|
| 406 |
+
assert options.minifier_export_mode in ["dynamo", "python"]
|
| 407 |
+
strict = options.minifier_export_mode == "dynamo"
|
| 408 |
+
skip_export_error = options.skip_export_error
|
| 409 |
+
|
| 410 |
+
from torch.cuda import synchronize
|
| 411 |
+
|
| 412 |
+
need_sync = False
|
| 413 |
+
|
| 414 |
+
for arg in args:
|
| 415 |
+
if isinstance(arg, torch.Tensor) and arg.is_cuda:
|
| 416 |
+
need_sync = True
|
| 417 |
+
break
|
| 418 |
+
|
| 419 |
+
def module_fails(
|
| 420 |
+
gm: torch.fx.GraphModule,
|
| 421 |
+
flat_example_inputs: list[Any],
|
| 422 |
+
check_str: Optional[str] = None,
|
| 423 |
+
) -> bool:
|
| 424 |
+
# Need to export first so the in_spec and out_spec are populated
|
| 425 |
+
tuple_inputs = tuple(flat_example_inputs)
|
| 426 |
+
# pyrefly: ignore [bad-assignment]
|
| 427 |
+
gm = export_for_aoti_minifier(
|
| 428 |
+
gm, tuple_inputs, strict=strict, skip_export_error=skip_export_error
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
# Some graphs cannot be used for AOTI/export (illegal graphs), these should be
|
| 432 |
+
# considered as graphs that don't fail in the minifier, so the minifier keeps searching.
|
| 433 |
+
if gm is None:
|
| 434 |
+
return False
|
| 435 |
+
|
| 436 |
+
assert isinstance(gm, torch.fx.GraphModule)
|
| 437 |
+
|
| 438 |
+
try:
|
| 439 |
+
_aoti_compile_and_package_inner(
|
| 440 |
+
gm,
|
| 441 |
+
tuple_inputs,
|
| 442 |
+
load_and_run=True,
|
| 443 |
+
check_accuracy=options.accuracy,
|
| 444 |
+
inductor_configs=inductor_configs,
|
| 445 |
+
)
|
| 446 |
+
if need_sync:
|
| 447 |
+
synchronize() # ensure segfaults are surfaced
|
| 448 |
+
return False
|
| 449 |
+
except Exception as e:
|
| 450 |
+
if check_str is not None and check_str not in repr(e):
|
| 451 |
+
return False
|
| 452 |
+
return True
|
| 453 |
+
|
| 454 |
+
minifier(
|
| 455 |
+
mod,
|
| 456 |
+
flat_example_inputs,
|
| 457 |
+
module_fails=functools.partial(module_fails, check_str=options.check_str),
|
| 458 |
+
dump_state=functools.partial(
|
| 459 |
+
dump_compiler_graph_state,
|
| 460 |
+
compiler_name=compiler_name,
|
| 461 |
+
config_patches=config_patches,
|
| 462 |
+
accuracy=options.accuracy,
|
| 463 |
+
strict=strict,
|
| 464 |
+
),
|
| 465 |
+
save_dir=options.save_dir,
|
| 466 |
+
offload_to_disk=options.offload_to_disk,
|
| 467 |
+
skip_offload=options.skip_saving_eager_intermediates,
|
| 468 |
+
skip_sanity=options.skip_sanity,
|
| 469 |
+
max_granularity=options.max_granularity,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def run_repro(
|
| 474 |
+
exported_program: ExportedProgram,
|
| 475 |
+
*,
|
| 476 |
+
config_patches: Optional[dict[str, str]] = None,
|
| 477 |
+
command: str = "run",
|
| 478 |
+
accuracy: Union[bool, str] = "",
|
| 479 |
+
save_dir: Optional[str] = None,
|
| 480 |
+
tracing_mode: Optional[str] = None,
|
| 481 |
+
check_str: Optional[str] = None,
|
| 482 |
+
minifier_export_mode: str = "python",
|
| 483 |
+
skip_export_error: bool = True,
|
| 484 |
+
**more_kwargs: Any,
|
| 485 |
+
) -> Any:
|
| 486 |
+
for k in more_kwargs:
|
| 487 |
+
log.warning(
|
| 488 |
+
"Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch",
|
| 489 |
+
k,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
if accuracy is True:
|
| 493 |
+
accuracy = "accuracy"
|
| 494 |
+
elif accuracy is False:
|
| 495 |
+
accuracy = ""
|
| 496 |
+
|
| 497 |
+
parser = argparse.ArgumentParser(
|
| 498 |
+
description=f"""\
|
| 499 |
+
An AOTI repro script, typically triggering a bug in PyTorch AOTInductor.
|
| 500 |
+
When run with no arguments, this script defaults to running '{command}'.
|
| 501 |
+
Extra flags may be available; to find out more, try '{command} --help'.
|
| 502 |
+
There are also alternate subcommands available, see below.
|
| 503 |
+
|
| 504 |
+
default settings on this script:
|
| 505 |
+
{accuracy=}
|
| 506 |
+
{tracing_mode=}
|
| 507 |
+
{save_dir=}
|
| 508 |
+
{check_str=}
|
| 509 |
+
""",
|
| 510 |
+
formatter_class=argparse.RawTextHelpFormatter,
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
def common_flags(parser: argparse.ArgumentParser) -> None:
|
| 514 |
+
accuracy_group = parser.add_mutually_exclusive_group()
|
| 515 |
+
accuracy_group.add_argument(
|
| 516 |
+
"--no-accuracy",
|
| 517 |
+
dest="accuracy",
|
| 518 |
+
action="store_const",
|
| 519 |
+
const="",
|
| 520 |
+
default=accuracy,
|
| 521 |
+
help="do not test accuracy, just run the module and see if it errors",
|
| 522 |
+
)
|
| 523 |
+
accuracy_group.add_argument(
|
| 524 |
+
"--accuracy",
|
| 525 |
+
action="store_const",
|
| 526 |
+
const="accuracy",
|
| 527 |
+
default=accuracy,
|
| 528 |
+
help="""\
|
| 529 |
+
test if the RMSE between the compiled module and the fp64 reference is greater
|
| 530 |
+
than eager and the fp64 reference. This is usually more reliable than the
|
| 531 |
+
standard allclose test, as we expect numeric differences from compiling, often
|
| 532 |
+
improving accuracy over eager. RMSE test allows for compiled module to
|
| 533 |
+
diverge greatly from eager, as long as this divergence moves it closer to the
|
| 534 |
+
'true' mathematical value of the network. Caveats: (1) double precision can
|
| 535 |
+
still suffer from rounding error, so it is not a perfect reference (see for
|
| 536 |
+
example 'Herbie: Automatically Improving Floating Point Accuracy') for
|
| 537 |
+
approaches that detect the necessary working precision and compute it in
|
| 538 |
+
arbitrary precision floating point; unfortunately, this is not practical for
|
| 539 |
+
tensor computation; (2) if there are not enough samples in the output being
|
| 540 |
+
compared, we may get unlucky and have an unlucky greater RMSE than eager; this
|
| 541 |
+
could be overcome by applying a more rigorous statistical test at some
|
| 542 |
+
p-value, which we leave for future work.
|
| 543 |
+
""",
|
| 544 |
+
)
|
| 545 |
+
accuracy_group.add_argument(
|
| 546 |
+
"--strict-accuracy",
|
| 547 |
+
dest="accuracy",
|
| 548 |
+
action="store_const",
|
| 549 |
+
const="strict_accuracy",
|
| 550 |
+
default=accuracy,
|
| 551 |
+
help="""\
|
| 552 |
+
by default, when doing accuracy minification we will reject reductions which
|
| 553 |
+
change the divergence from a floating point divergence to a integral/boolean
|
| 554 |
+
divergence. This is because some operations like ReLU involve temporarily
|
| 555 |
+
sharp boundaries that smooth out again afterwards; without requiring
|
| 556 |
+
divergence on floating point, the minifier will often fixate on divergent
|
| 557 |
+
boolean tensor even though this is not the true source of the divergence.
|
| 558 |
+
However, rejecting these reductions makes it more difficult for the minifier
|
| 559 |
+
to make process. Using this option will let the minifier progress for ALL
|
| 560 |
+
divergences--you just might not end up with a useful repro in the end.""",
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
parser.add_argument(
|
| 564 |
+
"--save-dir",
|
| 565 |
+
type=str,
|
| 566 |
+
default=save_dir,
|
| 567 |
+
metavar="DIR",
|
| 568 |
+
help="directory where saved inputs live",
|
| 569 |
+
)
|
| 570 |
+
parser.add_argument(
|
| 571 |
+
"--no-save-dir",
|
| 572 |
+
dest="save_dir",
|
| 573 |
+
action="store_const",
|
| 574 |
+
const=None,
|
| 575 |
+
help="don't use any directory for saved inputs",
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
subparsers = parser.add_subparsers(
|
| 579 |
+
dest="command", metavar="{run,minify}", required=True
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
parser_run = subparsers.add_parser(
|
| 583 |
+
"run",
|
| 584 |
+
help="just run the repro",
|
| 585 |
+
)
|
| 586 |
+
common_flags(parser_run)
|
| 587 |
+
|
| 588 |
+
parser_minify = subparsers.add_parser(
|
| 589 |
+
"minify", help="run the minifier on the repro"
|
| 590 |
+
)
|
| 591 |
+
common_flags(parser_minify)
|
| 592 |
+
parser_get_args = subparsers.add_parser("get_args", help="get the args")
|
| 593 |
+
common_flags(parser_get_args)
|
| 594 |
+
parser_minify.add_argument(
|
| 595 |
+
"--skip-saving-eager-intermediates",
|
| 596 |
+
action="store_true",
|
| 597 |
+
help="skip saving eager intermediates on --minify",
|
| 598 |
+
)
|
| 599 |
+
parser_minify.add_argument(
|
| 600 |
+
"--offload-to-disk",
|
| 601 |
+
action="store_true",
|
| 602 |
+
help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing",
|
| 603 |
+
)
|
| 604 |
+
parser_minify.add_argument(
|
| 605 |
+
"--skip-sanity",
|
| 606 |
+
action="store_true",
|
| 607 |
+
help="skip sanity check at beginning of minification on original graph",
|
| 608 |
+
)
|
| 609 |
+
parser_minify.add_argument(
|
| 610 |
+
"--max-granularity",
|
| 611 |
+
type=int,
|
| 612 |
+
default=None,
|
| 613 |
+
help="start at this granularity and work down; must be power of 2",
|
| 614 |
+
)
|
| 615 |
+
parser_minify.add_argument(
|
| 616 |
+
"--check-str",
|
| 617 |
+
type=str,
|
| 618 |
+
default=check_str,
|
| 619 |
+
help="require minified program to fail with error containing this string",
|
| 620 |
+
)
|
| 621 |
+
parser_minify.add_argument(
|
| 622 |
+
"--minifier-export-mode",
|
| 623 |
+
type=str,
|
| 624 |
+
default=minifier_export_mode,
|
| 625 |
+
help=(
|
| 626 |
+
"The export mode used in minifier, either dynamo or python."
|
| 627 |
+
"`dynamo` corresponds to strict=True, and `python` corresponds to strict=False."
|
| 628 |
+
),
|
| 629 |
+
)
|
| 630 |
+
parser_minify.add_argument(
|
| 631 |
+
"--skip-export-error",
|
| 632 |
+
type=bool,
|
| 633 |
+
default=skip_export_error,
|
| 634 |
+
help="Skip intermediate graphs that cannot be exported.",
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# Run the repro in the context of minification, inverting exit code meaning
|
| 638 |
+
parser_minifier_query = subparsers.add_parser(
|
| 639 |
+
"minifier-query",
|
| 640 |
+
)
|
| 641 |
+
common_flags(parser_minifier_query)
|
| 642 |
+
parser_minifier_query.add_argument(
|
| 643 |
+
"--check-str",
|
| 644 |
+
type=str,
|
| 645 |
+
default=check_str,
|
| 646 |
+
help="require minified program to fail with error containing this string",
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
args = None
|
| 650 |
+
if len(sys.argv) <= 1:
|
| 651 |
+
args = [command, *sys.argv[1:]]
|
| 652 |
+
|
| 653 |
+
options = parser.parse_args(args)
|
| 654 |
+
COMMAND_FNS = {
|
| 655 |
+
"minify": repro_minify,
|
| 656 |
+
"run": repro_run,
|
| 657 |
+
"get_args": repro_get_args,
|
| 658 |
+
}
|
| 659 |
+
return COMMAND_FNS[options.command](
|
| 660 |
+
options, exported_program, config_patches=config_patches
|
| 661 |
+
)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/resume_execution.py
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ynamo for control flow handling and optimization. It implements
|
| 4 |
+
bytecode transformation and execution state management to enable:
|
| 5 |
+
|
| 6 |
+
- Resuming execution at arbitrary points in Python bytecode
|
| 7 |
+
- Managing context managers and their state across execution boundaries
|
| 8 |
+
- Transforming and generating new code objects with preserved execution state
|
| 9 |
+
- Supporting Python 3.11+ exception handling and block management
|
| 10 |
+
- Restoring torch function mode stacks and other execution context
|
| 11 |
+
|
| 12 |
+
The module is critical for PyTorch Dynamo's ability to optimize code while preserving
|
| 13 |
+
Python semantics and execution state.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import dataclasses
|
| 18 |
+
import sys
|
| 19 |
+
import types
|
| 20 |
+
from collections.abc import Callable, Iterable
|
| 21 |
+
from contextlib import AbstractContextManager
|
| 22 |
+
from typing import Any, cast, Optional
|
| 23 |
+
|
| 24 |
+
from .bytecode_transformation import (
|
| 25 |
+
add_push_null,
|
| 26 |
+
bytecode_from_template,
|
| 27 |
+
create_binary_subscr,
|
| 28 |
+
create_call_function,
|
| 29 |
+
create_call_function_ex,
|
| 30 |
+
create_instruction,
|
| 31 |
+
create_jump_absolute,
|
| 32 |
+
create_load_const,
|
| 33 |
+
Instruction,
|
| 34 |
+
overwrite_instruction,
|
| 35 |
+
transform_code_object,
|
| 36 |
+
unique_id,
|
| 37 |
+
)
|
| 38 |
+
from .utils import ExactWeakKeyDictionary
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# taken from code.h in cpython
|
| 42 |
+
CO_OPTIMIZED = 0x0001
|
| 43 |
+
CO_NEWLOCALS = 0x0002
|
| 44 |
+
CO_VARARGS = 0x0004
|
| 45 |
+
CO_VARKEYWORDS = 0x0008
|
| 46 |
+
CO_NESTED = 0x0010
|
| 47 |
+
CO_GENERATOR = 0x0020
|
| 48 |
+
CO_NOFREE = 0x0040
|
| 49 |
+
CO_COROUTINE = 0x0080
|
| 50 |
+
CO_ITERABLE_COROUTINE = 0x0100
|
| 51 |
+
CO_ASYNC_GENERATOR = 0x0200
|
| 52 |
+
|
| 53 |
+
# trace_rules.py import this constant for consistency
|
| 54 |
+
TORCH_DYNAMO_RESUME_IN_PREFIX = "torch_dynamo_resume_in"
|
| 55 |
+
IS_TRACING_RESUME_PROLOGUE_VARNAME = "__is_tracing_resume_prologue"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# If is_resume - this codegen is for a resume function
|
| 59 |
+
def _initial_push_null(insts: list[Instruction]) -> None:
|
| 60 |
+
if sys.version_info >= (3, 11):
|
| 61 |
+
insts.append(create_instruction("PUSH_NULL"))
|
| 62 |
+
if sys.version_info < (3, 13):
|
| 63 |
+
insts.append(create_instruction("SWAP", arg=2))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# Generates bytecode from template and splits the code where LOAD_FAST dummy is present.
|
| 67 |
+
def _bytecode_from_template_with_split(
|
| 68 |
+
template: Callable[..., Any],
|
| 69 |
+
stack_index: int,
|
| 70 |
+
varname_map: Optional[dict[str, Any]] = None,
|
| 71 |
+
) -> tuple[list[Instruction], list[Instruction]]:
|
| 72 |
+
template_code = bytecode_from_template(template, varname_map=varname_map)
|
| 73 |
+
template_code.append(create_instruction("POP_TOP"))
|
| 74 |
+
|
| 75 |
+
# adjust exception table entry depth
|
| 76 |
+
for inst in template_code:
|
| 77 |
+
if inst.exn_tab_entry:
|
| 78 |
+
inst.exn_tab_entry.depth += stack_index
|
| 79 |
+
|
| 80 |
+
# search for LOAD_FAST dummy and replace it with 2 NOPs (we can break up the bytecode between them)
|
| 81 |
+
dummy_idx, dummy_inst = next(
|
| 82 |
+
(
|
| 83 |
+
(i, inst)
|
| 84 |
+
for i, inst in enumerate(template_code)
|
| 85 |
+
if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW")
|
| 86 |
+
and inst.argval == "dummy"
|
| 87 |
+
),
|
| 88 |
+
(None, None),
|
| 89 |
+
)
|
| 90 |
+
assert dummy_idx is not None and dummy_inst is not None
|
| 91 |
+
|
| 92 |
+
# replace LOAD_FAST dummy with first NOP marking exception area
|
| 93 |
+
overwrite_instruction(dummy_inst, [create_instruction("NOP")])
|
| 94 |
+
|
| 95 |
+
# POP_TOP follows LOAD_FAST dummy - replace with NOP marking end of exception area
|
| 96 |
+
assert template_code[dummy_idx + 1].opname == "POP_TOP"
|
| 97 |
+
overwrite_instruction(template_code[dummy_idx + 1], [create_instruction("NOP")])
|
| 98 |
+
|
| 99 |
+
return template_code[: dummy_idx + 1], template_code[dummy_idx + 1 :]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _try_except_tf_mode_template(dummy: Any, stack_var_name: Any) -> None:
|
| 103 |
+
# NOTE: Make sure this name matches what is generated by symbolic_convert:import_source
|
| 104 |
+
# on torch._dynamo.utils.
|
| 105 |
+
# pyrefly: ignore [unknown-name]
|
| 106 |
+
global __import_torch_dot__dynamo_dot_utils
|
| 107 |
+
try:
|
| 108 |
+
dummy
|
| 109 |
+
except: # noqa: E722, B001
|
| 110 |
+
__import_torch_dot__dynamo_dot_utils.set_torch_function_mode_stack( # type: ignore[name-defined]
|
| 111 |
+
stack_var_name
|
| 112 |
+
)
|
| 113 |
+
raise
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@dataclasses.dataclass(frozen=True)
|
| 117 |
+
class ReenterWith:
|
| 118 |
+
stack_index: int
|
| 119 |
+
target_values: Optional[tuple[Any, ...]] = None
|
| 120 |
+
|
| 121 |
+
def try_except_torch_function_mode(
|
| 122 |
+
self, code_options: dict[str, Any], cleanup: list[Instruction]
|
| 123 |
+
) -> list[Instruction]:
|
| 124 |
+
"""
|
| 125 |
+
Codegen based off of:
|
| 126 |
+
try:
|
| 127 |
+
(rest)
|
| 128 |
+
except:
|
| 129 |
+
(restore previous tf mode stack)
|
| 130 |
+
raise
|
| 131 |
+
"""
|
| 132 |
+
from .variables.torch_function import get_prev_stack_var_name
|
| 133 |
+
|
| 134 |
+
setup_try_except, epilogue = _bytecode_from_template_with_split(
|
| 135 |
+
_try_except_tf_mode_template,
|
| 136 |
+
self.stack_index,
|
| 137 |
+
varname_map={"stack_var_name": get_prev_stack_var_name()},
|
| 138 |
+
)
|
| 139 |
+
cleanup[:] = epilogue + cleanup
|
| 140 |
+
|
| 141 |
+
return setup_try_except
|
| 142 |
+
|
| 143 |
+
# If we do not want to destroy the stack, we can do the same thing as a
|
| 144 |
+
# `SETUP_WITH` block, only that we store the context manager in a local_symbol
|
| 145 |
+
def try_finally(
|
| 146 |
+
self, code_options: dict[str, Any], cleanup: list[Instruction]
|
| 147 |
+
) -> list[Instruction]:
|
| 148 |
+
"""
|
| 149 |
+
Codegen based off of:
|
| 150 |
+
load args
|
| 151 |
+
enter context
|
| 152 |
+
try:
|
| 153 |
+
(rest)
|
| 154 |
+
finally:
|
| 155 |
+
exit context
|
| 156 |
+
"""
|
| 157 |
+
# NOTE: we assume that TOS is a context manager CLASS!
|
| 158 |
+
load_args = []
|
| 159 |
+
if self.target_values:
|
| 160 |
+
load_args = [create_load_const(val) for val in self.target_values]
|
| 161 |
+
ctx_name = unique_id(f"___context_manager_{self.stack_index}")
|
| 162 |
+
if ctx_name not in code_options["co_varnames"]:
|
| 163 |
+
code_options["co_varnames"] += (ctx_name,)
|
| 164 |
+
for name in ["__enter__", "__exit__"]:
|
| 165 |
+
if name not in code_options["co_names"]:
|
| 166 |
+
code_options["co_names"] += (name,)
|
| 167 |
+
|
| 168 |
+
create_ctx: list[Instruction] = []
|
| 169 |
+
_initial_push_null(create_ctx)
|
| 170 |
+
create_ctx.extend(
|
| 171 |
+
[
|
| 172 |
+
*load_args,
|
| 173 |
+
*create_call_function(len(load_args), False),
|
| 174 |
+
create_instruction("STORE_FAST", argval=ctx_name),
|
| 175 |
+
]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None:
|
| 179 |
+
ctx.__enter__()
|
| 180 |
+
try:
|
| 181 |
+
dummy
|
| 182 |
+
finally:
|
| 183 |
+
ctx.__exit__(None, None, None)
|
| 184 |
+
|
| 185 |
+
setup_try_finally, epilogue = _bytecode_from_template_with_split(
|
| 186 |
+
_template, self.stack_index, varname_map={"ctx": ctx_name}
|
| 187 |
+
)
|
| 188 |
+
cleanup[:] = epilogue + cleanup
|
| 189 |
+
return create_ctx + setup_try_finally
|
| 190 |
+
|
| 191 |
+
def __call__(
|
| 192 |
+
self, code_options: dict[str, Any], cleanup: list[Instruction]
|
| 193 |
+
) -> tuple[list[Instruction], Optional[Instruction]]:
|
| 194 |
+
"""
|
| 195 |
+
Codegen based off of:
|
| 196 |
+
with ctx(args):
|
| 197 |
+
(rest)
|
| 198 |
+
"""
|
| 199 |
+
# NOTE: we assume that TOS is a context manager CLASS!
|
| 200 |
+
load_args = []
|
| 201 |
+
if self.target_values:
|
| 202 |
+
load_args = [create_load_const(val) for val in self.target_values]
|
| 203 |
+
|
| 204 |
+
create_ctx: list[Instruction] = []
|
| 205 |
+
# Do not push NULL in Python 3.14+ since the NULL should be on the symbolic stack.
|
| 206 |
+
if sys.version_info < (3, 14):
|
| 207 |
+
_initial_push_null(create_ctx)
|
| 208 |
+
create_ctx.extend(
|
| 209 |
+
[
|
| 210 |
+
*load_args,
|
| 211 |
+
*create_call_function(len(load_args), False),
|
| 212 |
+
]
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None:
|
| 216 |
+
with ctx:
|
| 217 |
+
dummy
|
| 218 |
+
|
| 219 |
+
setup_with, epilogue = _bytecode_from_template_with_split(
|
| 220 |
+
_template, self.stack_index
|
| 221 |
+
)
|
| 222 |
+
cleanup[:] = epilogue + cleanup
|
| 223 |
+
|
| 224 |
+
load_fast_ctx_inst = next(
|
| 225 |
+
(
|
| 226 |
+
inst
|
| 227 |
+
for inst in setup_with
|
| 228 |
+
if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW")
|
| 229 |
+
and inst.argval == "ctx"
|
| 230 |
+
),
|
| 231 |
+
None,
|
| 232 |
+
)
|
| 233 |
+
assert load_fast_ctx_inst is not None
|
| 234 |
+
# ctx already loaded on stack before the template - no need to LOAD_FAST
|
| 235 |
+
overwrite_instruction(load_fast_ctx_inst, [create_instruction("NOP")])
|
| 236 |
+
|
| 237 |
+
# 3.11+ only
|
| 238 |
+
push_exc_info_gen = (
|
| 239 |
+
inst for inst in epilogue if inst.opname == "PUSH_EXC_INFO"
|
| 240 |
+
)
|
| 241 |
+
push_exc_info_inst = next(push_exc_info_gen, None)
|
| 242 |
+
# expect only 1 PUSH_EXC_INFO in epilogue
|
| 243 |
+
assert next(push_exc_info_gen, None) is None
|
| 244 |
+
|
| 245 |
+
return create_ctx + setup_with, push_exc_info_inst
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@dataclasses.dataclass
|
| 249 |
+
class ResumeFunctionMetadata:
|
| 250 |
+
code: types.CodeType
|
| 251 |
+
instructions: list[Instruction] = dataclasses.field(default_factory=list)
|
| 252 |
+
# Python 3.11+ fields
|
| 253 |
+
# NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists
|
| 254 |
+
# of instructions of all exception table entries that have the same target.
|
| 255 |
+
|
| 256 |
+
# map from PUSH_EXC_INFO's in the prefix to original block target offset
|
| 257 |
+
prefix_block_target_offset_remap: list[int] = dataclasses.field(
|
| 258 |
+
default_factory=list
|
| 259 |
+
)
|
| 260 |
+
# per-offset map from new block target offsets to original block target offsets
|
| 261 |
+
block_target_offset_remap: dict[tuple[int, int], dict[int, int]] = (
|
| 262 |
+
dataclasses.field(default_factory=dict)
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _filter_iter(
|
| 267 |
+
l1: Iterable[Any],
|
| 268 |
+
l2: Iterable[Any],
|
| 269 |
+
cond: Callable[[Any, Any], bool],
|
| 270 |
+
) -> list[Any]:
|
| 271 |
+
"""
|
| 272 |
+
Two-pointer conditional filter.
|
| 273 |
+
e.g. _filter_iter(insts, sorted_offsets, lambda i, o: i.offset == o)
|
| 274 |
+
returns the instructions with offsets in sorted_offsets
|
| 275 |
+
"""
|
| 276 |
+
it = iter(l2)
|
| 277 |
+
res: list[Instruction] = []
|
| 278 |
+
try:
|
| 279 |
+
cur = next(it)
|
| 280 |
+
for val in l1:
|
| 281 |
+
if cond(val, cur):
|
| 282 |
+
res.append(val)
|
| 283 |
+
cur = next(it)
|
| 284 |
+
except StopIteration:
|
| 285 |
+
pass
|
| 286 |
+
return res
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _load_tuple_and_call(tup: tuple[Any, ...]) -> list[Instruction]:
|
| 290 |
+
insts: list[Instruction] = []
|
| 291 |
+
_initial_push_null(insts)
|
| 292 |
+
insts.extend(create_load_const(val) for val in tup)
|
| 293 |
+
insts.extend(create_call_function(len(tup), False))
|
| 294 |
+
return insts
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class ContinueExecutionCache:
|
| 298 |
+
cache = ExactWeakKeyDictionary()
|
| 299 |
+
generated_code_metadata = ExactWeakKeyDictionary()
|
| 300 |
+
|
| 301 |
+
@classmethod
|
| 302 |
+
def lookup(
|
| 303 |
+
cls, code: types.CodeType, lineno: int, init_offset: int, *key: Any
|
| 304 |
+
) -> types.CodeType:
|
| 305 |
+
if code not in cls.cache:
|
| 306 |
+
cls.cache[code] = {}
|
| 307 |
+
key = tuple(key)
|
| 308 |
+
if key not in cls.cache[code]:
|
| 309 |
+
cls.cache[code][key] = cls.generate(code, lineno, init_offset, *key)
|
| 310 |
+
return cls.cache[code][key]
|
| 311 |
+
|
| 312 |
+
@classmethod
|
| 313 |
+
def generate(
|
| 314 |
+
cls,
|
| 315 |
+
code: types.CodeType,
|
| 316 |
+
lineno: int,
|
| 317 |
+
init_offset: int,
|
| 318 |
+
resume_offset: int,
|
| 319 |
+
setup_fn_target_offsets: tuple[int, ...], # only used in Python 3.11+
|
| 320 |
+
nstack: int,
|
| 321 |
+
argnames: tuple[str, ...],
|
| 322 |
+
argnames_null: tuple[str, ...],
|
| 323 |
+
setup_fns: tuple[ReenterWith, ...],
|
| 324 |
+
handle_inactive_ctx: bool,
|
| 325 |
+
stack_ctx_vars: tuple[tuple[int, tuple[Any, ...]], ...],
|
| 326 |
+
argnames_ctx_vars: tuple[tuple[str, tuple[Any, ...]], ...],
|
| 327 |
+
null_idxes: tuple[int, ...],
|
| 328 |
+
# mainly used to ensure distinct code objects per stack trace,
|
| 329 |
+
# which prevents excessive recompilation of inner frames
|
| 330 |
+
nested_code_objs: tuple[types.CodeType],
|
| 331 |
+
# Are we currently graph breaking on an instruction that doesn't push
|
| 332 |
+
# its result to the stack? If so, and we are not the leaf resume, then we need to pop
|
| 333 |
+
# the result of calling the next resume function.
|
| 334 |
+
pop_nested_resume_result: bool,
|
| 335 |
+
) -> types.CodeType:
|
| 336 |
+
assert resume_offset is not None
|
| 337 |
+
assert not (
|
| 338 |
+
code.co_flags
|
| 339 |
+
& (CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR)
|
| 340 |
+
)
|
| 341 |
+
assert code.co_flags & CO_OPTIMIZED
|
| 342 |
+
if code in ContinueExecutionCache.generated_code_metadata:
|
| 343 |
+
return cls.generate_based_on_original_code_object(
|
| 344 |
+
code,
|
| 345 |
+
lineno,
|
| 346 |
+
init_offset,
|
| 347 |
+
resume_offset,
|
| 348 |
+
setup_fn_target_offsets,
|
| 349 |
+
nstack,
|
| 350 |
+
argnames,
|
| 351 |
+
argnames_null,
|
| 352 |
+
setup_fns,
|
| 353 |
+
handle_inactive_ctx,
|
| 354 |
+
stack_ctx_vars,
|
| 355 |
+
argnames_ctx_vars,
|
| 356 |
+
null_idxes,
|
| 357 |
+
nested_code_objs,
|
| 358 |
+
pop_nested_resume_result,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
is_py311_plus = sys.version_info >= (3, 11)
|
| 362 |
+
meta = ResumeFunctionMetadata(code)
|
| 363 |
+
|
| 364 |
+
def update(
|
| 365 |
+
instructions: list[Instruction], code_options: dict[str, Any]
|
| 366 |
+
) -> None:
|
| 367 |
+
meta.instructions = copy.deepcopy(instructions)
|
| 368 |
+
|
| 369 |
+
args = ["__nested_resume_fns", "__nested_frame_values"]
|
| 370 |
+
args += [f"___stack{i}" for i in range(nstack)]
|
| 371 |
+
args.extend(v for v in argnames if v not in args)
|
| 372 |
+
freevars = tuple(code_options["co_cellvars"] or []) + tuple(
|
| 373 |
+
code_options["co_freevars"] or []
|
| 374 |
+
)
|
| 375 |
+
freevars = tuple(sorted(freevars))
|
| 376 |
+
code_options["co_name"] = (
|
| 377 |
+
f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_{code_options['co_name']}_at_{lineno}"
|
| 378 |
+
)
|
| 379 |
+
if is_py311_plus:
|
| 380 |
+
qualified_path = code_options["co_qualname"].rsplit(".", maxsplit=1)
|
| 381 |
+
if len(qualified_path) == 1:
|
| 382 |
+
code_options["co_qualname"] = code_options["co_name"]
|
| 383 |
+
else:
|
| 384 |
+
assert len(qualified_path) == 2
|
| 385 |
+
module_name, co_name = qualified_path
|
| 386 |
+
code_options["co_qualname"] = (
|
| 387 |
+
f"{module_name}.{TORCH_DYNAMO_RESUME_IN_PREFIX}_{co_name}_at_{lineno}"
|
| 388 |
+
)
|
| 389 |
+
code_options["co_firstlineno"] = lineno
|
| 390 |
+
code_options["co_cellvars"] = ()
|
| 391 |
+
code_options["co_freevars"] = freevars
|
| 392 |
+
code_options["co_argcount"] = len(args)
|
| 393 |
+
code_options["co_posonlyargcount"] = 0
|
| 394 |
+
code_options["co_kwonlyargcount"] = 0
|
| 395 |
+
code_options["co_varnames"] = tuple(
|
| 396 |
+
args
|
| 397 |
+
+ [v for v in argnames_null if v not in args]
|
| 398 |
+
+ [v for v in code_options["co_varnames"] if v not in args]
|
| 399 |
+
+ [IS_TRACING_RESUME_PROLOGUE_VARNAME]
|
| 400 |
+
)
|
| 401 |
+
code_options["co_flags"] = code_options["co_flags"] & ~(
|
| 402 |
+
CO_VARARGS | CO_VARKEYWORDS
|
| 403 |
+
)
|
| 404 |
+
target = next(i for i in instructions if i.offset == resume_offset)
|
| 405 |
+
|
| 406 |
+
prefix = []
|
| 407 |
+
if is_py311_plus:
|
| 408 |
+
if freevars:
|
| 409 |
+
prefix.append(
|
| 410 |
+
create_instruction("COPY_FREE_VARS", arg=len(freevars))
|
| 411 |
+
)
|
| 412 |
+
prefix.append(create_instruction("RESUME", arg=0))
|
| 413 |
+
|
| 414 |
+
# Set is_tracing_resume_prologue to prevent graph breaks.
|
| 415 |
+
# This doesn't really do anything at runtime, but dynamo will trace this
|
| 416 |
+
# and will know that we're in a resume function prologue.
|
| 417 |
+
prefix.extend(
|
| 418 |
+
[
|
| 419 |
+
create_instruction("LOAD_CONST", argval=True),
|
| 420 |
+
create_instruction(
|
| 421 |
+
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
|
| 422 |
+
),
|
| 423 |
+
]
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
cleanup: list[Instruction] = []
|
| 427 |
+
hooks = {fn.stack_index: fn for fn in setup_fns}
|
| 428 |
+
hook_target_offsets = {
|
| 429 |
+
fn.stack_index: setup_fn_target_offsets[i]
|
| 430 |
+
for i, fn in enumerate(setup_fns)
|
| 431 |
+
}
|
| 432 |
+
offset_to_inst = {inst.offset: inst for inst in instructions}
|
| 433 |
+
# map old hook targets to new targets generated by the hook
|
| 434 |
+
old_hook_target_remap = {}
|
| 435 |
+
stack_i = 0
|
| 436 |
+
null_i = 0
|
| 437 |
+
stack_ctx_vars_d = dict(stack_ctx_vars) # type: ignore[var-annotated,arg-type]
|
| 438 |
+
for i in range(nstack + len(null_idxes)):
|
| 439 |
+
if null_i < len(null_idxes) and null_idxes[null_i] == i:
|
| 440 |
+
prefix.append(create_instruction("PUSH_NULL"))
|
| 441 |
+
null_i += 1
|
| 442 |
+
else:
|
| 443 |
+
prefix.append(
|
| 444 |
+
create_instruction("LOAD_FAST", argval=f"___stack{stack_i}")
|
| 445 |
+
)
|
| 446 |
+
if handle_inactive_ctx and stack_i in stack_ctx_vars_d:
|
| 447 |
+
# NOTE: we assume that current stack var is a context manager CLASS!
|
| 448 |
+
# Load args for context variable and construct it
|
| 449 |
+
prefix.extend(_load_tuple_and_call(stack_ctx_vars_d[stack_i]))
|
| 450 |
+
stack_i += 1
|
| 451 |
+
|
| 452 |
+
if i in hooks:
|
| 453 |
+
hook = hooks.pop(i)
|
| 454 |
+
hook_insts, exn_target = hook(code_options, cleanup)
|
| 455 |
+
prefix.extend(hook_insts)
|
| 456 |
+
if is_py311_plus:
|
| 457 |
+
hook_target_offset = hook_target_offsets.pop(i)
|
| 458 |
+
old_hook_target = offset_to_inst[hook_target_offset]
|
| 459 |
+
meta.prefix_block_target_offset_remap.append(hook_target_offset)
|
| 460 |
+
old_hook_target_remap[old_hook_target] = exn_target
|
| 461 |
+
|
| 462 |
+
if is_py311_plus:
|
| 463 |
+
# reverse the mapping since targets of later/nested contexts are inserted
|
| 464 |
+
# into the mapping later, but show up earlier in the prefix.
|
| 465 |
+
meta.prefix_block_target_offset_remap = list(
|
| 466 |
+
reversed(meta.prefix_block_target_offset_remap)
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
assert not hooks
|
| 470 |
+
|
| 471 |
+
# NOTE: we assume that local var is a context manager CLASS!
|
| 472 |
+
# initialize inactive context vars in argnames
|
| 473 |
+
if handle_inactive_ctx:
|
| 474 |
+
for name, vals in argnames_ctx_vars:
|
| 475 |
+
prefix.append(create_instruction("LOAD_FAST", argval=name))
|
| 476 |
+
prefix.extend(_load_tuple_and_call(vals))
|
| 477 |
+
prefix.append(create_instruction("STORE_FAST", argval=name))
|
| 478 |
+
|
| 479 |
+
# 3.12+: store NULL into variables that were NULL
|
| 480 |
+
if argnames_null:
|
| 481 |
+
assert sys.version_info >= (3, 12)
|
| 482 |
+
for v in argnames_null:
|
| 483 |
+
assert v not in args
|
| 484 |
+
prefix.extend(
|
| 485 |
+
[
|
| 486 |
+
create_instruction("PUSH_NULL"),
|
| 487 |
+
create_instruction("STORE_FAST", argval=v),
|
| 488 |
+
]
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
# Call nested resume function
|
| 492 |
+
if nested_code_objs:
|
| 493 |
+
prefix.extend(
|
| 494 |
+
[
|
| 495 |
+
# set up __nested_resume_fns[-1] call
|
| 496 |
+
*add_push_null(
|
| 497 |
+
[
|
| 498 |
+
create_instruction(
|
| 499 |
+
"LOAD_FAST", argval="__nested_resume_fns"
|
| 500 |
+
),
|
| 501 |
+
create_instruction("LOAD_CONST", argval=-1),
|
| 502 |
+
create_binary_subscr(),
|
| 503 |
+
]
|
| 504 |
+
),
|
| 505 |
+
# del __nested_resume_fns[-1]
|
| 506 |
+
create_instruction("LOAD_FAST", argval="__nested_resume_fns"),
|
| 507 |
+
create_instruction("LOAD_CONST", argval=-1),
|
| 508 |
+
create_instruction("DELETE_SUBSCR"),
|
| 509 |
+
# load [__nested_resume_fns, __nested_frame_values]
|
| 510 |
+
create_instruction("LOAD_FAST", argval="__nested_resume_fns"),
|
| 511 |
+
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
|
| 512 |
+
create_instruction("BUILD_LIST", arg=2),
|
| 513 |
+
# load __nested_frame_values[-1]
|
| 514 |
+
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
|
| 515 |
+
create_instruction("LOAD_CONST", argval=-1),
|
| 516 |
+
create_binary_subscr(),
|
| 517 |
+
# create [
|
| 518 |
+
# __nested_resume_fns,
|
| 519 |
+
# __nested_frame_values,
|
| 520 |
+
# *__nested_frame_values[-1],
|
| 521 |
+
# ]
|
| 522 |
+
create_instruction("LIST_EXTEND", arg=1),
|
| 523 |
+
# del __nested_frame_values[-1]
|
| 524 |
+
create_instruction("LOAD_FAST", argval="__nested_frame_values"),
|
| 525 |
+
create_instruction("LOAD_CONST", argval=-1),
|
| 526 |
+
create_instruction("DELETE_SUBSCR"),
|
| 527 |
+
# delete __nested values
|
| 528 |
+
create_instruction("DELETE_FAST", argval="__nested_resume_fns"),
|
| 529 |
+
create_instruction(
|
| 530 |
+
"DELETE_FAST", argval="__nested_frame_values"
|
| 531 |
+
),
|
| 532 |
+
# Set is_tracing_resume_prologue back to allow graph breaks
|
| 533 |
+
# in the nested resume
|
| 534 |
+
create_instruction("LOAD_CONST", argval=False),
|
| 535 |
+
create_instruction(
|
| 536 |
+
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
|
| 537 |
+
),
|
| 538 |
+
# finish the call
|
| 539 |
+
*create_call_function_ex(False, False),
|
| 540 |
+
]
|
| 541 |
+
)
|
| 542 |
+
if pop_nested_resume_result:
|
| 543 |
+
# pop the result of calling the nested resume function
|
| 544 |
+
prefix.append(create_instruction("POP_TOP"))
|
| 545 |
+
else:
|
| 546 |
+
# Set is_tracing_resume_prologue back to allow graph breaks after the jump
|
| 547 |
+
prefix.extend(
|
| 548 |
+
[
|
| 549 |
+
create_instruction("LOAD_CONST", argval=False),
|
| 550 |
+
create_instruction(
|
| 551 |
+
"STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME
|
| 552 |
+
),
|
| 553 |
+
]
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
prefix.append(create_jump_absolute(target))
|
| 557 |
+
|
| 558 |
+
# because the line number table monotonically increases from co_firstlineno
|
| 559 |
+
# remove starts_line for any instructions before the graph break instruction
|
| 560 |
+
# this will ensure the instructions after the break have the correct line numbers
|
| 561 |
+
for inst in instructions:
|
| 562 |
+
if inst.offset == target.offset:
|
| 563 |
+
break
|
| 564 |
+
inst.starts_line = None
|
| 565 |
+
if sys.version_info >= (3, 11):
|
| 566 |
+
inst.positions = None
|
| 567 |
+
|
| 568 |
+
if cleanup:
|
| 569 |
+
prefix.extend(cleanup)
|
| 570 |
+
prefix.extend(cls.unreachable_codes(code_options))
|
| 571 |
+
|
| 572 |
+
# remap original instructions' exception table entries
|
| 573 |
+
if old_hook_target_remap:
|
| 574 |
+
# pyrefly: ignore [unbound-name]
|
| 575 |
+
assert is_py311_plus
|
| 576 |
+
for inst in instructions:
|
| 577 |
+
if (
|
| 578 |
+
inst.exn_tab_entry
|
| 579 |
+
and inst.exn_tab_entry.target in old_hook_target_remap
|
| 580 |
+
):
|
| 581 |
+
inst.exn_tab_entry.target = old_hook_target_remap[ # type: ignore[assignment]
|
| 582 |
+
inst.exn_tab_entry.target
|
| 583 |
+
]
|
| 584 |
+
|
| 585 |
+
# TODO(jansel): add dead code elimination here
|
| 586 |
+
instructions[:] = prefix + instructions
|
| 587 |
+
|
| 588 |
+
new_code, _ = transform_code_object(code, update)
|
| 589 |
+
ContinueExecutionCache.generated_code_metadata[new_code] = meta
|
| 590 |
+
return new_code
|
| 591 |
+
|
| 592 |
+
@staticmethod
|
| 593 |
+
def unreachable_codes(code_options: dict[str, Any]) -> list[Instruction]:
|
| 594 |
+
"""Codegen a `raise None` to make analysis work for unreachable code"""
|
| 595 |
+
return [
|
| 596 |
+
create_load_const(None),
|
| 597 |
+
create_instruction("RAISE_VARARGS", arg=1),
|
| 598 |
+
]
|
| 599 |
+
|
| 600 |
+
@classmethod
|
| 601 |
+
def generate_based_on_original_code_object(
|
| 602 |
+
cls,
|
| 603 |
+
code: types.CodeType,
|
| 604 |
+
lineno: int,
|
| 605 |
+
init_offset: int,
|
| 606 |
+
resume_offset: int,
|
| 607 |
+
setup_fn_target_offsets: tuple[int, ...],
|
| 608 |
+
*args: Any,
|
| 609 |
+
) -> types.CodeType:
|
| 610 |
+
"""
|
| 611 |
+
This handles the case of generating a resume into code generated
|
| 612 |
+
to resume something else. We want to always generate starting
|
| 613 |
+
from the original code object so that if control flow paths
|
| 614 |
+
converge we only generated 1 resume function (rather than 2^n
|
| 615 |
+
resume functions).
|
| 616 |
+
"""
|
| 617 |
+
|
| 618 |
+
meta: ResumeFunctionMetadata = ContinueExecutionCache.generated_code_metadata[
|
| 619 |
+
code
|
| 620 |
+
]
|
| 621 |
+
|
| 622 |
+
def find_orig_offset(cur_offset: int) -> int:
|
| 623 |
+
orig_offset = -1
|
| 624 |
+
|
| 625 |
+
def find_orig_offset_transform(
|
| 626 |
+
instructions: list[Instruction], code_options: dict[str, Any]
|
| 627 |
+
) -> None:
|
| 628 |
+
nonlocal orig_offset
|
| 629 |
+
(target,) = (i for i in instructions if i.offset == cur_offset)
|
| 630 |
+
# match the functions starting at the last instruction as we have added a prefix
|
| 631 |
+
new_target_tuple = tuple(
|
| 632 |
+
i2
|
| 633 |
+
for i1, i2 in zip(
|
| 634 |
+
reversed(instructions), reversed(meta.instructions)
|
| 635 |
+
)
|
| 636 |
+
if i1 is target
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
if not new_target_tuple:
|
| 640 |
+
# Instruction with cur_offset in instructions was not found
|
| 641 |
+
# in the original code - orig_offset left as -1.
|
| 642 |
+
# Caller expected to handle this case.
|
| 643 |
+
return
|
| 644 |
+
|
| 645 |
+
assert len(new_target_tuple) == 1
|
| 646 |
+
new_target = new_target_tuple[0]
|
| 647 |
+
|
| 648 |
+
assert target.opcode == new_target.opcode
|
| 649 |
+
assert new_target.offset is not None
|
| 650 |
+
orig_offset = new_target.offset
|
| 651 |
+
|
| 652 |
+
transform_code_object(code, find_orig_offset_transform)
|
| 653 |
+
return orig_offset
|
| 654 |
+
|
| 655 |
+
orig_init_offset = find_orig_offset(init_offset)
|
| 656 |
+
# It is fine if the initial instruction is not found in the original code;
|
| 657 |
+
# this means we graph broke in the prefix, which only happens with nested graph breaks.
|
| 658 |
+
# We should not be running into ambiguous graph break issues here.
|
| 659 |
+
orig_resume_offset = find_orig_offset(resume_offset)
|
| 660 |
+
assert orig_resume_offset > -1, (
|
| 661 |
+
"resume instruction not found in original code - this is a bug."
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
if sys.version_info >= (3, 11):
|
| 665 |
+
# setup_fn_target_offsets currently contains the target offset of
|
| 666 |
+
# each setup_fn, based on `code`. When we codegen the resume function
|
| 667 |
+
# based on the original code object, `meta.code`, the offsets in
|
| 668 |
+
# setup_fn_target_offsets must be based on `meta.code` instead.
|
| 669 |
+
offset_key = (orig_init_offset, orig_resume_offset)
|
| 670 |
+
# NOTE: we key by offset_key since the same resume function may graph
|
| 671 |
+
# break in multiple places and we need different block_target_offset_remap's
|
| 672 |
+
# for each graph break location. Keying by orig_resume_offset may not be enough
|
| 673 |
+
# if 2 graph breaks on different initial offsets resume on the same instruction
|
| 674 |
+
# (although this is rare and not tested anywhere).
|
| 675 |
+
if offset_key not in meta.block_target_offset_remap:
|
| 676 |
+
block_target_offset_remap = meta.block_target_offset_remap[
|
| 677 |
+
offset_key
|
| 678 |
+
] = {}
|
| 679 |
+
|
| 680 |
+
def remap_block_offsets(
|
| 681 |
+
instructions: list[Instruction], code_options: dict[str, Any]
|
| 682 |
+
) -> None:
|
| 683 |
+
# NOTE: each prefix block generates exactly one PUSH_EXC_INFO,
|
| 684 |
+
# so we can tell which block a prefix PUSH_EXC_INFO belongs to,
|
| 685 |
+
# by counting. Then we can use meta.prefix_block_target_offset_remap
|
| 686 |
+
# to determine where in the original code the PUSH_EXC_INFO offset
|
| 687 |
+
# replaced.
|
| 688 |
+
prefix_blocks: list[Instruction] = []
|
| 689 |
+
for inst in instructions:
|
| 690 |
+
# NOTE meta.prefix_block_target_offset_remap is based off of how we codegen'd
|
| 691 |
+
# context managers at the prefix/prologue of the resume function. It is the same for
|
| 692 |
+
# every graph break in the same resume function, so we do not need to recompute
|
| 693 |
+
# for each graph break (unlike for meta.block_target_offset_remap)
|
| 694 |
+
if len(prefix_blocks) == len(
|
| 695 |
+
meta.prefix_block_target_offset_remap
|
| 696 |
+
):
|
| 697 |
+
break
|
| 698 |
+
if inst.opname == "PUSH_EXC_INFO":
|
| 699 |
+
prefix_blocks.append(inst)
|
| 700 |
+
|
| 701 |
+
# remap block target offsets for blocks generated in the resume prefix
|
| 702 |
+
for inst, o in zip(
|
| 703 |
+
prefix_blocks, meta.prefix_block_target_offset_remap
|
| 704 |
+
):
|
| 705 |
+
block_target_offset_remap[cast(int, inst.offset)] = o
|
| 706 |
+
|
| 707 |
+
# current bytecode targets are after the prefix PUSH_EXC_INFO's
|
| 708 |
+
cur_start_offset = (
|
| 709 |
+
cast(int, prefix_blocks[-1].offset) if prefix_blocks else -1
|
| 710 |
+
)
|
| 711 |
+
# get the remaining block target offsets of the current bytecode
|
| 712 |
+
cur_inst_offsets = sorted(
|
| 713 |
+
n for n in setup_fn_target_offsets if n > cur_start_offset
|
| 714 |
+
)
|
| 715 |
+
targets = _filter_iter(
|
| 716 |
+
instructions, cur_inst_offsets, lambda inst, o: inst.offset == o
|
| 717 |
+
)
|
| 718 |
+
# The original code and resume code should have matching suffixes.
|
| 719 |
+
# Match the post-prefix block target offsets of the current resume code
|
| 720 |
+
# and the original code.
|
| 721 |
+
orig_targets = reversed(
|
| 722 |
+
_filter_iter(
|
| 723 |
+
zip(reversed(instructions), reversed(meta.instructions)),
|
| 724 |
+
reversed(targets),
|
| 725 |
+
lambda v1, v2: v1[0] is v2,
|
| 726 |
+
)
|
| 727 |
+
)
|
| 728 |
+
for orig, cur in zip(orig_targets, targets):
|
| 729 |
+
block_target_offset_remap[cur.offset] = orig[1].offset
|
| 730 |
+
|
| 731 |
+
transform_code_object(code, remap_block_offsets)
|
| 732 |
+
|
| 733 |
+
# if offset_key or offset is not in setup_fn_target_offsets, it is an error
|
| 734 |
+
# that needs to be fixed
|
| 735 |
+
setup_fn_target_offsets = tuple(
|
| 736 |
+
meta.block_target_offset_remap[offset_key][n]
|
| 737 |
+
for n in setup_fn_target_offsets
|
| 738 |
+
)
|
| 739 |
+
return ContinueExecutionCache.lookup(
|
| 740 |
+
meta.code,
|
| 741 |
+
lineno,
|
| 742 |
+
orig_init_offset,
|
| 743 |
+
orig_resume_offset,
|
| 744 |
+
setup_fn_target_offsets,
|
| 745 |
+
*args,
|
| 746 |
+
)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/_dynamo/side_effects.py
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Side effect tracking and management for TorchDynamo's compilation system.
|
| 3 |
+
|
| 4 |
+
This module provides infrastructure for tracking and managing side effects that occur
|
| 5 |
+
during symbolic execution, including:
|
| 6 |
+
|
| 7 |
+
- Tracking mutations to objects, attributes, and variables
|
| 8 |
+
- Managing context changes (cell variables, global namespace modifications)
|
| 9 |
+
- Handling aliasing and object identity preservation
|
| 10 |
+
- Managing stack frame state and local variable changes
|
| 11 |
+
- Tracking function calls with side effects
|
| 12 |
+
|
| 13 |
+
Key classes:
|
| 14 |
+
- SideEffects: Main container for tracking all side effects during execution
|
| 15 |
+
- MutableSideEffects: Specialization for mutable object tracking
|
| 16 |
+
- AttributeMutation/ValueMutation: Track specific types of mutations
|
| 17 |
+
- Various specialized side effect classes for different scenarios
|
| 18 |
+
|
| 19 |
+
The side effect system ensures that mutations performed during symbolic execution
|
| 20 |
+
are properly replayed during runtime, maintaining the correctness of compiled code
|
| 21 |
+
while enabling optimizations where safe.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import collections
|
| 25 |
+
import contextlib
|
| 26 |
+
import inspect
|
| 27 |
+
import warnings
|
| 28 |
+
import weakref
|
| 29 |
+
from collections.abc import Generator, MutableMapping
|
| 30 |
+
from types import CellType
|
| 31 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 32 |
+
|
| 33 |
+
import torch.nn
|
| 34 |
+
from torch._dynamo.variables.misc import AutogradFunctionContextVariable
|
| 35 |
+
|
| 36 |
+
from . import graph_break_hints, utils, variables
|
| 37 |
+
from .bytecode_transformation import (
|
| 38 |
+
bytecode_from_template,
|
| 39 |
+
create_call_function,
|
| 40 |
+
create_call_method,
|
| 41 |
+
create_instruction,
|
| 42 |
+
)
|
| 43 |
+
from .codegen import PyCodegen
|
| 44 |
+
from .exc import SideEffectsError, unimplemented
|
| 45 |
+
from .source import GlobalSource, LocalCellSource, Source, TempLocalSource
|
| 46 |
+
from .utils import is_frozen_dataclass, nn_module_new, object_new
|
| 47 |
+
from .variables.base import (
|
| 48 |
+
AttributeMutation,
|
| 49 |
+
AttributeMutationExisting,
|
| 50 |
+
AttributeMutationNew,
|
| 51 |
+
is_side_effect_safe,
|
| 52 |
+
ValueMutationExisting,
|
| 53 |
+
ValueMutationNew,
|
| 54 |
+
VariableTracker,
|
| 55 |
+
)
|
| 56 |
+
from .variables.user_defined import FrozenDataClassVariable
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if TYPE_CHECKING:
|
| 60 |
+
from torch._dynamo.output_graph import OutputGraph
|
| 61 |
+
from torch._dynamo.symbolic_convert import InstructionTranslatorBase
|
| 62 |
+
from torch._dynamo.variables.lists import ListVariable
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _manual_dict_setitem(
|
| 66 |
+
dict_from: dict[Any, Any], dict_to: dict[Any, Any], mro_index: int
|
| 67 |
+
) -> None:
|
| 68 |
+
# Carefully calls the dict or OrderedDict `clear` or `__setitem__`. We have
|
| 69 |
+
# to be careful because we don't want to trigger the user defined object
|
| 70 |
+
# setitem or clear. The mro_index is used to find the dict/OrderedDict from
|
| 71 |
+
# the class mro.
|
| 72 |
+
dict_class = type(dict_to).__mro__[mro_index]
|
| 73 |
+
dict_class.clear(dict_to) # type: ignore[attr-defined]
|
| 74 |
+
for k, v in dict_from.items():
|
| 75 |
+
dict_class.__setitem__(dict_to, k, v) # type: ignore[index]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _manual_list_update(list_from: list[Any], list_to: list[Any]) -> None:
|
| 79 |
+
list.clear(list_to)
|
| 80 |
+
list.extend(list_to, list_from)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class SideEffects:
|
| 84 |
+
"""
|
| 85 |
+
Maintain records of mutations and provide methods to apply them during code generation.
|
| 86 |
+
|
| 87 |
+
Handles tracking and applying side effects during PyTorch Dynamo compilation,
|
| 88 |
+
maintaining Python semantics by managing mutations, attribute modifications,
|
| 89 |
+
and other side effects that occur during program execution.
|
| 90 |
+
|
| 91 |
+
Key responsibilities:
|
| 92 |
+
- Tracks mutations to Python objects, lists, and dictionaries that need to be
|
| 93 |
+
applied after an FX graph is run.
|
| 94 |
+
- Manages attribute modifications and deletions
|
| 95 |
+
- Handles tensor hooks and backward pass state
|
| 96 |
+
- Tracks cell variable mutations and global variable changes
|
| 97 |
+
- Ensures correct ordering and application of side effects after graph execution
|
| 98 |
+
|
| 99 |
+
This ensures that optimized code behaves identically to the original Python code with
|
| 100 |
+
respect to object mutations and other side effects.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
id_to_variable: dict[int, VariableTracker]
|
| 104 |
+
store_attr_mutations: dict[VariableTracker, dict[str, VariableTracker]]
|
| 105 |
+
keepalive: list[Any]
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
output_graph: "OutputGraph",
|
| 110 |
+
id_to_variable: Optional[dict[int, VariableTracker]] = None,
|
| 111 |
+
store_attr_mutations: Optional[
|
| 112 |
+
dict[VariableTracker, dict[str, VariableTracker]]
|
| 113 |
+
] = None,
|
| 114 |
+
keepalive: Optional[list[Any]] = None,
|
| 115 |
+
save_for_backward: Optional[
|
| 116 |
+
list[tuple[AutogradFunctionContextVariable, list[VariableTracker]]]
|
| 117 |
+
] = None,
|
| 118 |
+
tensor_hooks: Optional[
|
| 119 |
+
dict[
|
| 120 |
+
int,
|
| 121 |
+
tuple[
|
| 122 |
+
"variables.TensorVariable",
|
| 123 |
+
VariableTracker,
|
| 124 |
+
"variables.RemovableHandleVariable",
|
| 125 |
+
str,
|
| 126 |
+
],
|
| 127 |
+
]
|
| 128 |
+
] = None,
|
| 129 |
+
) -> None:
|
| 130 |
+
super().__init__()
|
| 131 |
+
self.output_graph_weakref = weakref.ref(output_graph)
|
| 132 |
+
self.id_to_variable = id_to_variable or {}
|
| 133 |
+
self.store_attr_mutations = store_attr_mutations or {}
|
| 134 |
+
self.keepalive = keepalive or []
|
| 135 |
+
self.save_for_backward = save_for_backward or []
|
| 136 |
+
self.tensor_hooks = tensor_hooks or {}
|
| 137 |
+
# Used by MappingProxyVariable to graph break in case of any mutated
|
| 138 |
+
# dict
|
| 139 |
+
self._has_existing_dict_mutation = False
|
| 140 |
+
# Track Compiled Autograd final callbacks that must be called at the end of Compiled Autograd backward graph.
|
| 141 |
+
# Only applicable if this graph is created from Dynamo tracing in Compiled Autograd.
|
| 142 |
+
self.ca_final_callbacks_var: Optional[ListVariable] = None
|
| 143 |
+
|
| 144 |
+
# Tracks VariableTracker objects whose mutations can be skipped.
|
| 145 |
+
# For normal mutated variables, Dynamo generates code to replay/reconstruct
|
| 146 |
+
# the mutations after graph execution. However, variables in this set have
|
| 147 |
+
# their mutations ignored - the mutations happen during
|
| 148 |
+
# execution but don't need to be replayed in the generated code.
|
| 149 |
+
# Used for temporary mutations in contexts like torch.func.functional_call,
|
| 150 |
+
# where module parameters/buffers are modified but later restored.
|
| 151 |
+
self.ignore_mutation_on_these_variables: set[VariableTracker] = set()
|
| 152 |
+
|
| 153 |
+
def ignore_mutations_on(self, var: VariableTracker) -> None:
|
| 154 |
+
"""Mutations to this variable will be executed but not not tracked,
|
| 155 |
+
typically used for temporary mutations that are later restored."""
|
| 156 |
+
self.ignore_mutation_on_these_variables.add(var)
|
| 157 |
+
|
| 158 |
+
def stop_ignoring_mutations_on(self, var: VariableTracker) -> None:
|
| 159 |
+
"""Remove a variable from the skip mutation set, restoring normal mutation tracking."""
|
| 160 |
+
if var in self.ignore_mutation_on_these_variables:
|
| 161 |
+
self.ignore_mutation_on_these_variables.remove(var)
|
| 162 |
+
|
| 163 |
+
def __eq__(self, other: object) -> bool:
|
| 164 |
+
assert isinstance(other, SideEffects)
|
| 165 |
+
# NB: do NOT test keepalive
|
| 166 |
+
return (
|
| 167 |
+
self.id_to_variable == other.id_to_variable
|
| 168 |
+
and self.store_attr_mutations == other.store_attr_mutations
|
| 169 |
+
and self.save_for_backward == other.save_for_backward
|
| 170 |
+
and self.tensor_hooks == other.tensor_hooks
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def diff(self, other: "SideEffects") -> Optional[str]:
|
| 174 |
+
if self.id_to_variable != other.id_to_variable:
|
| 175 |
+
sk_itv = self.id_to_variable.keys()
|
| 176 |
+
ok_itv = other.id_to_variable.keys()
|
| 177 |
+
if sk_itv != ok_itv:
|
| 178 |
+
return f"id_to_variable keys: {sk_itv} != {ok_itv}"
|
| 179 |
+
# Feel free to augment this with more fancy diffing logic
|
| 180 |
+
# if needed for debugging
|
| 181 |
+
return "id_to_variable: unknown diff"
|
| 182 |
+
elif self.store_attr_mutations != other.store_attr_mutations:
|
| 183 |
+
sk_sam = self.store_attr_mutations.keys()
|
| 184 |
+
ok_sam = other.store_attr_mutations.keys()
|
| 185 |
+
if sk_sam != ok_sam:
|
| 186 |
+
return f"store_attr_mutations keys: {sk_sam} != {ok_sam}"
|
| 187 |
+
return "store_attr_mutations: unknown diff"
|
| 188 |
+
elif self.save_for_backward != other.save_for_backward:
|
| 189 |
+
return "save_for_backward"
|
| 190 |
+
elif self.tensor_hooks != other.tensor_hooks:
|
| 191 |
+
return "tensor_hooks"
|
| 192 |
+
else:
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
def clone(self) -> "SideEffects":
|
| 196 |
+
"""Create a shallow copy"""
|
| 197 |
+
ref = self.output_graph_weakref()
|
| 198 |
+
assert ref is not None
|
| 199 |
+
return self.__class__(
|
| 200 |
+
output_graph=ref,
|
| 201 |
+
id_to_variable=dict(self.id_to_variable),
|
| 202 |
+
store_attr_mutations={
|
| 203 |
+
k: dict(v) for k, v in self.store_attr_mutations.items()
|
| 204 |
+
},
|
| 205 |
+
keepalive=list(self.keepalive),
|
| 206 |
+
save_for_backward=self.save_for_backward,
|
| 207 |
+
tensor_hooks=self.tensor_hooks,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def __contains__(self, item: Any) -> bool:
|
| 211 |
+
return id(item) in self.id_to_variable
|
| 212 |
+
|
| 213 |
+
def __getitem__(self, item: Any) -> VariableTracker:
|
| 214 |
+
return self.id_to_variable[id(item)]
|
| 215 |
+
|
| 216 |
+
def should_allow_externally_visible_side_effects_in_subtracer(self) -> bool:
|
| 217 |
+
output_graph = self.output_graph_weakref()
|
| 218 |
+
return bool(
|
| 219 |
+
output_graph
|
| 220 |
+
and output_graph.current_tx.output.current_tracer.unsafe_allow_externally_visible_side_effects
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
def should_allow_side_effects_in_hop(self) -> bool:
|
| 224 |
+
output_graph = self.output_graph_weakref()
|
| 225 |
+
return bool(
|
| 226 |
+
output_graph
|
| 227 |
+
and output_graph.current_tx.output.current_tracer.allow_side_effects_in_hop
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
def is_reconstructing_generator(self) -> bool:
|
| 231 |
+
output_graph = self.output_graph_weakref()
|
| 232 |
+
|
| 233 |
+
return bool(
|
| 234 |
+
output_graph
|
| 235 |
+
and output_graph.current_tx.output.current_tracer.is_reconstructing_generator
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def check_allowed_side_effect(self, item: VariableTracker) -> bool:
|
| 239 |
+
from torch._dynamo.variables.misc import AutogradFunctionContextVariable
|
| 240 |
+
|
| 241 |
+
# People do things like self.dim = dim inside autograd.Function.
|
| 242 |
+
# These are benign.
|
| 243 |
+
if isinstance(item, AutogradFunctionContextVariable):
|
| 244 |
+
return True
|
| 245 |
+
if self.should_allow_externally_visible_side_effects_in_subtracer():
|
| 246 |
+
return True
|
| 247 |
+
if self.should_allow_side_effects_in_hop():
|
| 248 |
+
return True
|
| 249 |
+
if self.is_reconstructing_generator():
|
| 250 |
+
# This is missing the case where one mutates a tensor. See
|
| 251 |
+
# test_generator.py::test_reconstruct_generator_tensor_mutation
|
| 252 |
+
raise SideEffectsError(
|
| 253 |
+
"Cannot reconstruct a generator with variable mutations. "
|
| 254 |
+
"Dynamo needs to fully exhaust the generator, which may cause "
|
| 255 |
+
"unintended variable modifications."
|
| 256 |
+
)
|
| 257 |
+
assert item.mutation_type is not None
|
| 258 |
+
if not is_side_effect_safe(item.mutation_type):
|
| 259 |
+
# TODO plumb HOP information here
|
| 260 |
+
unimplemented(
|
| 261 |
+
gb_type="HigherOrderOperator: Mutating a variable not in the current scope (SideEffects)",
|
| 262 |
+
context="",
|
| 263 |
+
explanation="This is not supported.",
|
| 264 |
+
hints=[],
|
| 265 |
+
)
|
| 266 |
+
return False
|
| 267 |
+
|
| 268 |
+
def store_attr(
|
| 269 |
+
self, item: VariableTracker, name: str, value: VariableTracker
|
| 270 |
+
) -> None:
|
| 271 |
+
assert self.is_attribute_mutation(item)
|
| 272 |
+
self.check_allowed_side_effect(item)
|
| 273 |
+
if item not in self.store_attr_mutations:
|
| 274 |
+
self.store_attr_mutations[item] = {}
|
| 275 |
+
self.store_attr_mutations[item][name] = value
|
| 276 |
+
|
| 277 |
+
def load_attr(
|
| 278 |
+
self,
|
| 279 |
+
item: VariableTracker,
|
| 280 |
+
name: str,
|
| 281 |
+
deleted_ok: bool = False,
|
| 282 |
+
check: bool = False,
|
| 283 |
+
) -> VariableTracker:
|
| 284 |
+
if check:
|
| 285 |
+
assert self.is_attribute_mutation(item)
|
| 286 |
+
result = self.store_attr_mutations[item][name]
|
| 287 |
+
if not deleted_ok and isinstance(result, variables.DeletedVariable):
|
| 288 |
+
unimplemented(
|
| 289 |
+
gb_type="Attempted to read a deleted variable",
|
| 290 |
+
context=f"item: {item}, name: {name}",
|
| 291 |
+
explanation="",
|
| 292 |
+
hints=[*graph_break_hints.USER_ERROR],
|
| 293 |
+
)
|
| 294 |
+
return result
|
| 295 |
+
|
| 296 |
+
def store_cell(self, cellvar: VariableTracker, value: VariableTracker) -> None:
|
| 297 |
+
if cellvar.is_immutable():
|
| 298 |
+
unimplemented(
|
| 299 |
+
gb_type="Write to immutable cell",
|
| 300 |
+
context=f"cellvar: {cellvar}, value: {value}",
|
| 301 |
+
explanation="Dynamo doesn't support writing to immutable/sourceless cell variables.",
|
| 302 |
+
hints=[*graph_break_hints.DIFFICULT],
|
| 303 |
+
)
|
| 304 |
+
assert isinstance(cellvar, variables.CellVariable)
|
| 305 |
+
assert isinstance(value, variables.VariableTracker)
|
| 306 |
+
self.store_attr(cellvar, "cell_contents", value)
|
| 307 |
+
|
| 308 |
+
def load_cell(self, cellvar: VariableTracker) -> VariableTracker:
|
| 309 |
+
assert isinstance(cellvar, variables.CellVariable)
|
| 310 |
+
if self.has_pending_mutation_of_attr(cellvar, "cell_contents"):
|
| 311 |
+
return self.load_attr(cellvar, "cell_contents", check=False)
|
| 312 |
+
if cellvar.pre_existing_contents:
|
| 313 |
+
return cellvar.pre_existing_contents
|
| 314 |
+
unimplemented(
|
| 315 |
+
gb_type="Read uninitialized cell",
|
| 316 |
+
context=str(cellvar),
|
| 317 |
+
explanation="Attempted to read a cell variable that has not been populated yet.",
|
| 318 |
+
hints=[*graph_break_hints.USER_ERROR],
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def load_global(self, gvar: VariableTracker, name: str) -> VariableTracker:
|
| 322 |
+
assert isinstance(gvar, variables.VariableTracker)
|
| 323 |
+
return self.load_attr(gvar, name)
|
| 324 |
+
|
| 325 |
+
def store_global(
|
| 326 |
+
self, gvar: VariableTracker, name: str, value: VariableTracker
|
| 327 |
+
) -> None:
|
| 328 |
+
assert isinstance(gvar, variables.VariableTracker)
|
| 329 |
+
assert isinstance(value, variables.VariableTracker)
|
| 330 |
+
self.store_attr(gvar, name, value)
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def cls_supports_mutation_side_effects(cls: type) -> bool:
|
| 334 |
+
return inspect.getattr_static(cls, "__getattribute__", None) in (
|
| 335 |
+
object.__getattribute__,
|
| 336 |
+
dict.__getattribute__,
|
| 337 |
+
set.__getattribute__,
|
| 338 |
+
frozenset.__getattribute__,
|
| 339 |
+
int.__getattribute__,
|
| 340 |
+
str.__getattribute__,
|
| 341 |
+
list.__getattribute__,
|
| 342 |
+
tuple.__getattribute__,
|
| 343 |
+
BaseException.__getattribute__,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
def is_attribute_mutation(self, item: VariableTracker) -> bool:
|
| 347 |
+
return isinstance(item.mutation_type, AttributeMutation)
|
| 348 |
+
|
| 349 |
+
def has_pending_mutation(self, item: VariableTracker) -> bool:
|
| 350 |
+
return self.is_attribute_mutation(item) and bool(
|
| 351 |
+
self.store_attr_mutations.get(item)
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
def has_pending_mutation_of_attr(self, item: VariableTracker, name: str) -> bool:
|
| 355 |
+
return self.is_attribute_mutation(
|
| 356 |
+
item
|
| 357 |
+
) and name in self.store_attr_mutations.get(item, ())
|
| 358 |
+
|
| 359 |
+
def is_modified(self, item: VariableTracker) -> bool:
|
| 360 |
+
if item.is_immutable():
|
| 361 |
+
return False
|
| 362 |
+
if isinstance(item.mutation_type, (AttributeMutationNew, ValueMutationNew)):
|
| 363 |
+
return True
|
| 364 |
+
|
| 365 |
+
if isinstance(item, variables.UserDefinedObjectVariable):
|
| 366 |
+
# Checks if the underlying dict or tuple vt has been modified
|
| 367 |
+
return item in self.store_attr_mutations or item.is_underlying_vt_modified(
|
| 368 |
+
self
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
if self.is_attribute_mutation(item):
|
| 372 |
+
return item in self.store_attr_mutations
|
| 373 |
+
assert item.mutation_type is not None
|
| 374 |
+
return item.mutation_type.is_modified # type: ignore[attr-defined]
|
| 375 |
+
|
| 376 |
+
def _track_obj(
|
| 377 |
+
self,
|
| 378 |
+
item: Any,
|
| 379 |
+
variable: VariableTracker,
|
| 380 |
+
mutation_type_cls: type = ValueMutationExisting,
|
| 381 |
+
) -> VariableTracker:
|
| 382 |
+
"""Start tracking an existing or new variable for mutation"""
|
| 383 |
+
if id(item) in self.id_to_variable:
|
| 384 |
+
raise AssertionError(
|
| 385 |
+
f"{variable} is already tracked for mutation. This could be "
|
| 386 |
+
"because you are not using VariableBuilder to construct "
|
| 387 |
+
"the variable tracker. "
|
| 388 |
+
f"Source of new object: {variable.source}. "
|
| 389 |
+
f"Source of previously tracked object: {self.id_to_variable[id(item)].source}."
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
variable.mutation_type = mutation_type_cls()
|
| 393 |
+
self.id_to_variable[id(item)] = variable
|
| 394 |
+
self.keepalive.append(item)
|
| 395 |
+
return variable
|
| 396 |
+
|
| 397 |
+
track_mutable = _track_obj
|
| 398 |
+
|
| 399 |
+
def track_object_existing(
|
| 400 |
+
self,
|
| 401 |
+
item: Any,
|
| 402 |
+
variable: VariableTracker,
|
| 403 |
+
) -> VariableTracker:
|
| 404 |
+
return self._track_obj(
|
| 405 |
+
item,
|
| 406 |
+
variable,
|
| 407 |
+
mutation_type_cls=AttributeMutationExisting,
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
def track_object_new(
|
| 411 |
+
self,
|
| 412 |
+
cls_source: Source,
|
| 413 |
+
user_cls: Any,
|
| 414 |
+
variable_cls: Any,
|
| 415 |
+
options: dict[str, Any],
|
| 416 |
+
) -> VariableTracker:
|
| 417 |
+
if user_cls is torch.autograd.function.FunctionCtx:
|
| 418 |
+
with warnings.catch_warnings(record=True):
|
| 419 |
+
obj = torch.autograd.Function()
|
| 420 |
+
else:
|
| 421 |
+
obj = object_new(user_cls)
|
| 422 |
+
variable = variable_cls(
|
| 423 |
+
obj,
|
| 424 |
+
mutation_type=AttributeMutationNew(cls_source),
|
| 425 |
+
**options,
|
| 426 |
+
)
|
| 427 |
+
self.id_to_variable[id(obj)] = variable
|
| 428 |
+
self.keepalive.append(obj)
|
| 429 |
+
return variable
|
| 430 |
+
|
| 431 |
+
def get_variable_cls(self, user_cls: type) -> type:
|
| 432 |
+
from torch.overrides import TorchFunctionMode
|
| 433 |
+
|
| 434 |
+
from .variables.ctx_manager import GenericContextWrappingVariable
|
| 435 |
+
from .variables.torch_function import TorchFunctionModeVariable
|
| 436 |
+
from .variables.user_defined import is_forbidden_context_manager
|
| 437 |
+
|
| 438 |
+
variable_cls: type[variables.UserDefinedObjectVariable] = (
|
| 439 |
+
variables.UserDefinedObjectVariable
|
| 440 |
+
)
|
| 441 |
+
if issubclass(
|
| 442 |
+
user_cls, TorchFunctionMode
|
| 443 |
+
) and TorchFunctionModeVariable.is_supported_torch_function_mode(user_cls):
|
| 444 |
+
variable_cls = TorchFunctionModeVariable
|
| 445 |
+
elif (
|
| 446 |
+
hasattr(user_cls, "__enter__")
|
| 447 |
+
and hasattr(user_cls, "__exit__")
|
| 448 |
+
and not is_forbidden_context_manager(user_cls)
|
| 449 |
+
):
|
| 450 |
+
variable_cls = GenericContextWrappingVariable
|
| 451 |
+
elif issubclass(user_cls, torch.nn.Module):
|
| 452 |
+
variable_cls = variables.UnspecializedNNModuleVariable
|
| 453 |
+
elif issubclass(user_cls, (dict, collections.OrderedDict)):
|
| 454 |
+
variable_cls = variables.UserDefinedDictVariable
|
| 455 |
+
elif issubclass(user_cls, (set, frozenset)):
|
| 456 |
+
variable_cls = variables.UserDefinedSetVariable
|
| 457 |
+
elif issubclass(user_cls, tuple):
|
| 458 |
+
variable_cls = variables.UserDefinedTupleVariable
|
| 459 |
+
elif issubclass(user_cls, list):
|
| 460 |
+
variable_cls = variables.UserDefinedListVariable
|
| 461 |
+
elif issubclass(user_cls, MutableMapping):
|
| 462 |
+
variable_cls = variables.MutableMappingVariable
|
| 463 |
+
elif is_frozen_dataclass(user_cls):
|
| 464 |
+
variable_cls = FrozenDataClassVariable
|
| 465 |
+
elif issubclass(user_cls, BaseException):
|
| 466 |
+
variable_cls = variables.UserDefinedExceptionObjectVariable
|
| 467 |
+
assert issubclass(variable_cls, variables.UserDefinedObjectVariable)
|
| 468 |
+
return variable_cls
|
| 469 |
+
|
| 470 |
+
def get_example_value(
|
| 471 |
+
self,
|
| 472 |
+
base_cls_vt: VariableTracker,
|
| 473 |
+
cls_vt: VariableTracker,
|
| 474 |
+
init_args: list[VariableTracker],
|
| 475 |
+
) -> Any:
|
| 476 |
+
user_cls = cls_vt.value # type: ignore[attr-defined]
|
| 477 |
+
if issubclass(user_cls, torch.nn.Module):
|
| 478 |
+
# TODO(anijain2305) - Is it possible to remove this specialization?
|
| 479 |
+
obj = nn_module_new(user_cls)
|
| 480 |
+
else:
|
| 481 |
+
if isinstance(base_cls_vt, variables.BuiltinVariable):
|
| 482 |
+
base_cls = base_cls_vt.fn
|
| 483 |
+
elif isinstance(base_cls_vt, variables.UserDefinedClassVariable):
|
| 484 |
+
base_cls = base_cls_vt.value
|
| 485 |
+
else:
|
| 486 |
+
raise RuntimeError(f"Unexpected base_cls_vt {base_cls_vt}")
|
| 487 |
+
|
| 488 |
+
assert variables.UserDefinedClassVariable.is_supported_new_method(
|
| 489 |
+
base_cls.__new__
|
| 490 |
+
)
|
| 491 |
+
# TODO(anijain2305) - Consider adding get_example_value method to
|
| 492 |
+
# each VT to get an example value for all args. As we expand the
|
| 493 |
+
# scope to other __new__ methods, we might need to call __new__ with
|
| 494 |
+
# init_args (like functools.partial)
|
| 495 |
+
# init_args = [arg.get_example_value() for arg in init_args]
|
| 496 |
+
# obj = base_cls.__new__(user_cls, *init_args)
|
| 497 |
+
|
| 498 |
+
obj = base_cls.__new__(user_cls)
|
| 499 |
+
return obj
|
| 500 |
+
|
| 501 |
+
def track_new_user_defined_object(
|
| 502 |
+
self,
|
| 503 |
+
base_cls_vt: VariableTracker,
|
| 504 |
+
cls_vt: VariableTracker,
|
| 505 |
+
init_args: list[VariableTracker],
|
| 506 |
+
) -> VariableTracker:
|
| 507 |
+
"""
|
| 508 |
+
Creates a UserDefinedObjectVariable (or its subclass) variable tracker
|
| 509 |
+
and mark it for attribute mutation tracking.
|
| 510 |
+
|
| 511 |
+
Also records the variable trackers to call __new__ method on
|
| 512 |
+
reconstruction. Roughly, the reconstruction looks like this
|
| 513 |
+
base_cls_vt.__new__(user_cls, *init_args)
|
| 514 |
+
"""
|
| 515 |
+
cls_source = cls_vt.source
|
| 516 |
+
user_cls = cls_vt.value # type: ignore[attr-defined]
|
| 517 |
+
variable_cls = self.get_variable_cls(user_cls)
|
| 518 |
+
obj = self.get_example_value(base_cls_vt, cls_vt, init_args)
|
| 519 |
+
|
| 520 |
+
variable = variable_cls(
|
| 521 |
+
obj,
|
| 522 |
+
cls_source=cls_vt.source,
|
| 523 |
+
base_cls_vt=base_cls_vt,
|
| 524 |
+
init_args=init_args,
|
| 525 |
+
mutation_type=AttributeMutationNew(cls_source),
|
| 526 |
+
)
|
| 527 |
+
self.id_to_variable[id(obj)] = variable
|
| 528 |
+
self.keepalive.append(obj)
|
| 529 |
+
return variable
|
| 530 |
+
|
| 531 |
+
def track_cell_new(
|
| 532 |
+
self,
|
| 533 |
+
) -> VariableTracker:
|
| 534 |
+
obj = object()
|
| 535 |
+
variable = variables.CellVariable(
|
| 536 |
+
mutation_type=AttributeMutationNew(),
|
| 537 |
+
)
|
| 538 |
+
self.id_to_variable[id(obj)] = variable
|
| 539 |
+
self.keepalive.append(obj)
|
| 540 |
+
return variable
|
| 541 |
+
|
| 542 |
+
def track_cell_existing(
|
| 543 |
+
self, source: Optional[Source], cell: CellType, contents: VariableTracker
|
| 544 |
+
) -> VariableTracker:
|
| 545 |
+
variable = variables.CellVariable(
|
| 546 |
+
# We don't support mutation to cell without source because we need
|
| 547 |
+
# source to properly codegen the mutations.
|
| 548 |
+
mutation_type=None if source is None else AttributeMutationExisting(),
|
| 549 |
+
pre_existing_contents=contents,
|
| 550 |
+
source=source,
|
| 551 |
+
)
|
| 552 |
+
self.id_to_variable[id(cell)] = variable
|
| 553 |
+
self.keepalive.append(cell)
|
| 554 |
+
return variable
|
| 555 |
+
|
| 556 |
+
def track_global_existing(self, source: Source, item: Any) -> VariableTracker:
|
| 557 |
+
variable = variables.NewGlobalVariable(
|
| 558 |
+
mutation_type=AttributeMutationExisting(),
|
| 559 |
+
source=source,
|
| 560 |
+
)
|
| 561 |
+
self.id_to_variable[id(item)] = variable
|
| 562 |
+
self.keepalive.append(item)
|
| 563 |
+
return variable
|
| 564 |
+
|
| 565 |
+
def track_save_for_backward(
|
| 566 |
+
self, ctx: VariableTracker, args: list[VariableTracker]
|
| 567 |
+
) -> None:
|
| 568 |
+
assert isinstance(ctx, variables.AutogradFunctionContextVariable)
|
| 569 |
+
self.save_for_backward.append((ctx, args))
|
| 570 |
+
|
| 571 |
+
def track_runahead_tensor_and_symvar_side_effects(
|
| 572 |
+
self, other: "SideEffects"
|
| 573 |
+
) -> None:
|
| 574 |
+
# In higher order ops we want to keep track of tensors seen in the
|
| 575 |
+
# speculate_subgraph so that we don't lift them again as a new input in
|
| 576 |
+
# other speculate_subgraph or in the root tracer.
|
| 577 |
+
for other_item in other.keepalive:
|
| 578 |
+
other_id = id(other_item)
|
| 579 |
+
other_variable = other.id_to_variable[other_id]
|
| 580 |
+
if other_id not in self.id_to_variable and isinstance(
|
| 581 |
+
other_variable, (variables.TensorVariable, variables.SymNodeVariable)
|
| 582 |
+
):
|
| 583 |
+
self.track_object_existing(other_item, other_variable)
|
| 584 |
+
|
| 585 |
+
def prune_dead_object_new(self, tx: "InstructionTranslatorBase") -> None:
|
| 586 |
+
# Avoid VT cycles from e.g., recursive function.
|
| 587 |
+
visited: set[VariableTracker] = set()
|
| 588 |
+
live_new_objects: set[VariableTracker] = set()
|
| 589 |
+
|
| 590 |
+
def visit(var: VariableTracker) -> None:
|
| 591 |
+
if var in visited:
|
| 592 |
+
return
|
| 593 |
+
visited.add(var)
|
| 594 |
+
# Object may have been mutated, store this mutation.
|
| 595 |
+
if isinstance(var.mutation_type, AttributeMutationNew):
|
| 596 |
+
live_new_objects.add(var)
|
| 597 |
+
# It's possible that we have mutated the value of this variable
|
| 598 |
+
# to be another one. The new value is in store_attr_mutations.
|
| 599 |
+
# Also recurse through the new value to detect alive AttributeMutationNew.
|
| 600 |
+
if var in self.store_attr_mutations:
|
| 601 |
+
VariableTracker.visit(
|
| 602 |
+
visit, # noqa: F821
|
| 603 |
+
self.store_attr_mutations[var],
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
def is_live(var: VariableTracker) -> bool:
|
| 607 |
+
if isinstance(var.mutation_type, AttributeMutationNew):
|
| 608 |
+
return var in live_new_objects
|
| 609 |
+
return True
|
| 610 |
+
|
| 611 |
+
pre_existing_vars = [
|
| 612 |
+
var
|
| 613 |
+
for var in self.id_to_variable.values()
|
| 614 |
+
if not isinstance(var.mutation_type, AttributeMutationNew)
|
| 615 |
+
]
|
| 616 |
+
|
| 617 |
+
# The only live side effects come from returns (tx.stack), any intermediates
|
| 618 |
+
# during a graph break (tx.symbolic_locals), and mutation on pre-existing variables.
|
| 619 |
+
# Recursively visit Variables and see if any of them have been mutated.
|
| 620 |
+
init_live_vars = []
|
| 621 |
+
# gather stack/symbolic_locals for all tx's up the chain
|
| 622 |
+
cur_tx: Optional[InstructionTranslatorBase] = tx
|
| 623 |
+
while cur_tx is not None:
|
| 624 |
+
init_live_vars.extend([cur_tx.stack, cur_tx.symbolic_locals])
|
| 625 |
+
if cur_tx.parent is not None:
|
| 626 |
+
# for non-root tx'es, also keep the cells/freevars alive so they get codegen'd properly
|
| 627 |
+
# TODO see if we could prune dead cells - cell pruning information needs to be forwarded
|
| 628 |
+
# to the resume function creation as well.
|
| 629 |
+
assert cur_tx.post_prune_cell_and_freevars is not None
|
| 630 |
+
init_live_vars.append(cur_tx.post_prune_cell_and_freevars)
|
| 631 |
+
cur_tx = cur_tx.parent
|
| 632 |
+
VariableTracker.visit(
|
| 633 |
+
visit,
|
| 634 |
+
# TODO track from all possible sources.
|
| 635 |
+
init_live_vars
|
| 636 |
+
+ [
|
| 637 |
+
pre_existing_vars,
|
| 638 |
+
tx.output.backward_state,
|
| 639 |
+
self.tensor_hooks,
|
| 640 |
+
],
|
| 641 |
+
)
|
| 642 |
+
# Manually release the self-referential function, which indirectly
|
| 643 |
+
# captures certain `VariableTracker` and affects parts of PT test/logic
|
| 644 |
+
# that are sensitive to when certain objects get released.
|
| 645 |
+
del visit
|
| 646 |
+
|
| 647 |
+
# NB: cell variable handling.is tricky.
|
| 648 |
+
# cell variables must stay alive if any NestedUserFunctionVariable
|
| 649 |
+
# are live. "visit"-ing the NestedUserFunctionVariable visits
|
| 650 |
+
# the .closures field, from which we will see if we need to keep
|
| 651 |
+
# any mutations to cell variables alive.
|
| 652 |
+
|
| 653 |
+
self.id_to_variable = {
|
| 654 |
+
k: v for k, v in self.id_to_variable.items() if is_live(v)
|
| 655 |
+
}
|
| 656 |
+
self.store_attr_mutations = {
|
| 657 |
+
k: v for k, v in self.store_attr_mutations.items() if is_live(k)
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
def mutation(self, var: VariableTracker) -> None:
|
| 661 |
+
if var in self.ignore_mutation_on_these_variables:
|
| 662 |
+
return
|
| 663 |
+
|
| 664 |
+
self.check_allowed_side_effect(var)
|
| 665 |
+
if isinstance(var.mutation_type, ValueMutationExisting):
|
| 666 |
+
var.mutation_type.is_modified = True
|
| 667 |
+
if (
|
| 668 |
+
var.source
|
| 669 |
+
and isinstance(var, variables.ConstDictVariable)
|
| 670 |
+
and not isinstance(var, variables.SetVariable)
|
| 671 |
+
):
|
| 672 |
+
self._has_existing_dict_mutation = True
|
| 673 |
+
|
| 674 |
+
def has_existing_dict_mutation(self) -> bool:
|
| 675 |
+
return self._has_existing_dict_mutation
|
| 676 |
+
|
| 677 |
+
def _get_modified_vars(self) -> list[VariableTracker]:
|
| 678 |
+
return [var for var in self.id_to_variable.values() if self.is_modified(var)]
|
| 679 |
+
|
| 680 |
+
def codegen_save_tempvars(self, cg: PyCodegen) -> None:
|
| 681 |
+
# We must codegen modified VT to their source by default, so that
|
| 682 |
+
# mutation and aliasing are properly accounted for.
|
| 683 |
+
#
|
| 684 |
+
# Since newly constructed objects don't have a source, we manually
|
| 685 |
+
# codegen their construction and store them to a newly assigned local
|
| 686 |
+
# source. Note that `ValueMutationNew` isn't tracked by SideEffects.
|
| 687 |
+
for var in self._get_modified_vars():
|
| 688 |
+
if not isinstance(var.mutation_type, AttributeMutationNew):
|
| 689 |
+
assert var.source is not None
|
| 690 |
+
continue
|
| 691 |
+
|
| 692 |
+
if isinstance(var, variables.CellVariable):
|
| 693 |
+
# Cells created in the root frame are created either by
|
| 694 |
+
# `MAKE_CELL` or by them being in `co_cellvars`, so we only emit
|
| 695 |
+
# `make_cell` for the non-root-frame cells here.
|
| 696 |
+
# TODO generalize this so we never need to call `make_cell`.
|
| 697 |
+
if var.local_name is None:
|
| 698 |
+
cg.add_push_null(
|
| 699 |
+
lambda: cg.load_import_from(utils.__name__, "make_cell")
|
| 700 |
+
)
|
| 701 |
+
cg.extend_output(create_call_function(0, False))
|
| 702 |
+
cg.add_cache(var)
|
| 703 |
+
var.source = TempLocalSource(cg.tempvars[var]) # type: ignore[attr-defined]
|
| 704 |
+
elif var.source is None:
|
| 705 |
+
# pyrefly: ignore [bad-assignment]
|
| 706 |
+
var.source = LocalCellSource(var.local_name)
|
| 707 |
+
elif var.is_tensor():
|
| 708 |
+
# NOTE: for historical reasons we never assigned local sources
|
| 709 |
+
# to newly constructed tensor object, so we keep it that way.
|
| 710 |
+
# They are always loaded from output of the fx graph, so one can
|
| 711 |
+
# think of it as having a "OutputGraphSource" for codegen
|
| 712 |
+
# purposes.
|
| 713 |
+
#
|
| 714 |
+
# However, tensor subclass objects are different, because the
|
| 715 |
+
# reconstruction logic in `PyCodegen` loads the data tensor from
|
| 716 |
+
# graph output and then calls `as_subclass`, meaning we must
|
| 717 |
+
# assign a source to it to ensure we only reconstruct one
|
| 718 |
+
# subclass instance.
|
| 719 |
+
if isinstance(
|
| 720 |
+
var, variables.torch_function.TensorWithTFOverrideVariable
|
| 721 |
+
):
|
| 722 |
+
# Don't codegen from temp source assigned from the 1st pass.
|
| 723 |
+
cg(var, allow_cache=False)
|
| 724 |
+
cg.add_cache(var)
|
| 725 |
+
# `add_cache` generates STORE and consumes TOS, but we never
|
| 726 |
+
# cleared it. TODO move this call into `add_cache`
|
| 727 |
+
cg.clear_tos()
|
| 728 |
+
var.source = TempLocalSource(cg.tempvars[var])
|
| 729 |
+
elif isinstance(var, variables.AutogradFunctionContextVariable):
|
| 730 |
+
unimplemented(
|
| 731 |
+
gb_type="AutogradFunctionContextVariable escaped Dynamo-traced region",
|
| 732 |
+
context="",
|
| 733 |
+
explanation="We cannot reconstruct a torch.autograd.Function's context object.",
|
| 734 |
+
hints=[],
|
| 735 |
+
)
|
| 736 |
+
else:
|
| 737 |
+
# Reconstruct the bytecode for
|
| 738 |
+
# base_cls.__new__(user_cls, *args)
|
| 739 |
+
if isinstance(var, variables.UserDefinedObjectVariable):
|
| 740 |
+
|
| 741 |
+
def load_new_method() -> None:
|
| 742 |
+
# pyrefly: ignore [missing-attribute]
|
| 743 |
+
assert var.base_cls_vt is not None
|
| 744 |
+
cg(var.base_cls_vt) # type: ignore[attr-defined]
|
| 745 |
+
cg.extend_output([cg.create_load_attr("__new__")])
|
| 746 |
+
|
| 747 |
+
cg.add_push_null(load_new_method)
|
| 748 |
+
else:
|
| 749 |
+
cg.add_push_null(
|
| 750 |
+
lambda: cg.load_import_from(utils.__name__, "object_new")
|
| 751 |
+
)
|
| 752 |
+
assert var.mutation_type.cls_source is not None
|
| 753 |
+
cg(var.mutation_type.cls_source)
|
| 754 |
+
|
| 755 |
+
# Generate the args to the __new__ method
|
| 756 |
+
for arg in var.init_args: # type: ignore[attr-defined]
|
| 757 |
+
cg(arg)
|
| 758 |
+
|
| 759 |
+
# Call the __new__ method
|
| 760 |
+
cg.extend_output(create_call_function(1 + len(var.init_args), False)) # type: ignore[attr-defined]
|
| 761 |
+
|
| 762 |
+
cg.add_cache(var)
|
| 763 |
+
var.source = TempLocalSource(cg.tempvars[var])
|
| 764 |
+
|
| 765 |
+
for ctx, args in self.save_for_backward:
|
| 766 |
+
cg(ctx.source)
|
| 767 |
+
cg.load_method("save_for_backward")
|
| 768 |
+
for arg in args:
|
| 769 |
+
cg(arg)
|
| 770 |
+
cg.extend_output(
|
| 771 |
+
[
|
| 772 |
+
*create_call_method(len(args)),
|
| 773 |
+
create_instruction("POP_TOP"),
|
| 774 |
+
]
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
def register_hook(
|
| 778 |
+
self,
|
| 779 |
+
tensor: "variables.TensorVariable",
|
| 780 |
+
hook: VariableTracker,
|
| 781 |
+
handle: "variables.RemovableHandleVariable",
|
| 782 |
+
name: str,
|
| 783 |
+
) -> None:
|
| 784 |
+
assert tensor.is_tensor()
|
| 785 |
+
assert isinstance(hook, variables.VariableTracker)
|
| 786 |
+
assert (
|
| 787 |
+
isinstance(handle, variables.RemovableHandleVariable)
|
| 788 |
+
and handle.is_mutable()
|
| 789 |
+
)
|
| 790 |
+
assert hasattr(torch.Tensor, name)
|
| 791 |
+
idx = len(self.tensor_hooks.keys())
|
| 792 |
+
# duplicate index possible because of self.remove_hook()
|
| 793 |
+
while idx in self.tensor_hooks:
|
| 794 |
+
idx += 1
|
| 795 |
+
self.tensor_hooks[idx] = (tensor, hook, handle, name)
|
| 796 |
+
assert not handle.idx
|
| 797 |
+
handle.idx = idx
|
| 798 |
+
|
| 799 |
+
def remove_hook(self, idx: int) -> None:
|
| 800 |
+
del self.tensor_hooks[idx]
|
| 801 |
+
|
| 802 |
+
def codegen_hooks(self, cg: PyCodegen) -> None:
|
| 803 |
+
for (
|
| 804 |
+
tensor,
|
| 805 |
+
hook,
|
| 806 |
+
handle,
|
| 807 |
+
name,
|
| 808 |
+
) in self.tensor_hooks.values():
|
| 809 |
+
# Note: [On tensor.register_hook]
|
| 810 |
+
#
|
| 811 |
+
# register_hook on a tensor, AKA backward hooks, have slightly nuanced differences in how they are implemented
|
| 812 |
+
# when it comes to hooks on objects with sources (inputs, params) vs objects without sources (intermediaries).
|
| 813 |
+
#
|
| 814 |
+
# For tensors with a source, we bypass direct inclusion of register_hook calls in the graph.
|
| 815 |
+
# Instead, these are tracked and stashed as a global variable, enabling their association with tensors in
|
| 816 |
+
# the residuals. During dynamo's frame creation, these hooks are invoked seamlessly on known reconstructible/fetch-able
|
| 817 |
+
# tensors. Because a source indicates knowledge of this object outside the torch compile region, and
|
| 818 |
+
# because we are running residuals firmly before .backward() can be run, it is sound to invoke
|
| 819 |
+
# `register_hook` on a known tensor.
|
| 820 |
+
#
|
| 821 |
+
# For tensors without a source, we support a limited subset of hooks. Global functions only, and
|
| 822 |
+
# compiled_autograd must be enabled or we will graph break.
|
| 823 |
+
#
|
| 824 |
+
# Handling the Handle: When a user retains the register_hook result in a handle, we intercept the
|
| 825 |
+
# STORE_FAST operation to record the user-designated local variable name. This ensures the reconstructed
|
| 826 |
+
# bytecode retains this name. If no handle is defined, we simply pop the generated value to keep the
|
| 827 |
+
# stack intact.
|
| 828 |
+
#
|
| 829 |
+
# Dynamo Tensor Hooks Workflow:
|
| 830 |
+
# - Functions passed to register_hook are lifted globally.
|
| 831 |
+
# - For tensors with sources:
|
| 832 |
+
# - In the "side_effects" phase of codegen, we iterate over tensors with hooks to:
|
| 833 |
+
# - Generate the tensor.
|
| 834 |
+
# - Issue a register_hook call on the tensor, linking to the globally stored function.
|
| 835 |
+
# - Incorporate a handle if one was established in the eager phase.
|
| 836 |
+
# - For tensors without sources:
|
| 837 |
+
# - We don't generate any instructions for registering a hook.
|
| 838 |
+
# - Handles from intermediary hooks are NYI.
|
| 839 |
+
# - We produce a call function that utilizes the trace_wrapped higher order op, closing over it.
|
| 840 |
+
# - We then manually insert the call function above into the graph.
|
| 841 |
+
# - The handle's exact user-specified name, "user_code_variable_name", is discerned and associated during STORE_FAST.
|
| 842 |
+
assert tensor.source, "Hooks on non input tensors NYI - should not get here"
|
| 843 |
+
|
| 844 |
+
def gen_fn() -> None:
|
| 845 |
+
cg(tensor)
|
| 846 |
+
cg.extend_output([cg.create_load_attr(name)])
|
| 847 |
+
|
| 848 |
+
cg.add_push_null(gen_fn)
|
| 849 |
+
cg(hook)
|
| 850 |
+
cg.extend_output(create_call_function(1, False))
|
| 851 |
+
|
| 852 |
+
# Adding the handle to the cache means RemovableHandleVariable().reconstruct() will
|
| 853 |
+
# be associated with the return value of register_hook(). This consumes the top of stack.
|
| 854 |
+
cg.add_cache(handle)
|
| 855 |
+
|
| 856 |
+
def get_ca_final_callbacks_var(self) -> "variables.ListVariable":
|
| 857 |
+
from .variables.base import ValueMutationNew
|
| 858 |
+
|
| 859 |
+
if self.ca_final_callbacks_var is None:
|
| 860 |
+
self.ca_final_callbacks_var = variables.ListVariable(
|
| 861 |
+
[], mutation_type=ValueMutationNew()
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
return self.ca_final_callbacks_var
|
| 865 |
+
|
| 866 |
+
def codegen_update_mutated(self, cg: PyCodegen) -> None:
|
| 867 |
+
suffixes = []
|
| 868 |
+
for var in self._get_modified_vars():
|
| 869 |
+
if isinstance(var, variables.ListVariable):
|
| 870 |
+
# old[:] = new
|
| 871 |
+
cg(var, allow_cache=False) # Don't codegen via source
|
| 872 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 873 |
+
cg.extend_output(
|
| 874 |
+
[
|
| 875 |
+
cg.create_load_const(None),
|
| 876 |
+
cg.create_load_const(None),
|
| 877 |
+
create_instruction("BUILD_SLICE", arg=2),
|
| 878 |
+
]
|
| 879 |
+
)
|
| 880 |
+
suffixes.append([create_instruction("STORE_SUBSCR")])
|
| 881 |
+
elif isinstance(var, variables.lists.DequeVariable):
|
| 882 |
+
# For limited maxlen, the order of operations matter for side
|
| 883 |
+
# effect, but we currently don't track the order, so no support.
|
| 884 |
+
if not var.maxlen.is_constant_none():
|
| 885 |
+
unimplemented(
|
| 886 |
+
gb_type="Side effect on existing deque with limited maxlen",
|
| 887 |
+
context="",
|
| 888 |
+
explanation="This is not supported.",
|
| 889 |
+
hints=[
|
| 890 |
+
"Don't use a deque with `maxlen` specified.",
|
| 891 |
+
],
|
| 892 |
+
)
|
| 893 |
+
|
| 894 |
+
# old.extend(new), this runs last
|
| 895 |
+
cg(var.source)
|
| 896 |
+
cg.load_method("extend")
|
| 897 |
+
cg(var, allow_cache=False) # Don't codegen via source
|
| 898 |
+
suffixes.append(
|
| 899 |
+
[
|
| 900 |
+
*create_call_method(1),
|
| 901 |
+
create_instruction("POP_TOP"),
|
| 902 |
+
]
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
# old.clear(), this runs first
|
| 906 |
+
cg(var.source)
|
| 907 |
+
cg.load_method("clear")
|
| 908 |
+
suffixes.append(
|
| 909 |
+
[
|
| 910 |
+
*create_call_method(0),
|
| 911 |
+
create_instruction("POP_TOP"),
|
| 912 |
+
]
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
elif isinstance(var, variables.ConstDictVariable):
|
| 916 |
+
# Reconstruct works as follow:
|
| 917 |
+
# (1) Skip codegen if there are no new items
|
| 918 |
+
# (2) codegen(...) each pair of key/value
|
| 919 |
+
# (3) create a new dictionary with the pairs of key/values above
|
| 920 |
+
# (4) clear the original dictionary
|
| 921 |
+
# + only if a key was removed from the input dict
|
| 922 |
+
# (5) update the original dictionary with the dict created in (2)
|
| 923 |
+
|
| 924 |
+
if var.has_new_items():
|
| 925 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 926 |
+
cg.load_method("update")
|
| 927 |
+
cg(var, allow_cache=False) # Don't codegen via source
|
| 928 |
+
|
| 929 |
+
if var.should_reconstruct_all:
|
| 930 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 931 |
+
cg.load_method("clear")
|
| 932 |
+
|
| 933 |
+
suffixes.append(
|
| 934 |
+
[
|
| 935 |
+
*create_call_method(1), # update
|
| 936 |
+
create_instruction("POP_TOP"),
|
| 937 |
+
]
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
if var.should_reconstruct_all:
|
| 941 |
+
# clear will appear before "update" as the suffixes are
|
| 942 |
+
# applied in reverse order.
|
| 943 |
+
suffixes.append(
|
| 944 |
+
[
|
| 945 |
+
*create_call_method(0), # clear
|
| 946 |
+
create_instruction("POP_TOP"),
|
| 947 |
+
]
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
elif isinstance(
|
| 951 |
+
var, variables.torch_function.TorchFunctionModeStackVariable
|
| 952 |
+
):
|
| 953 |
+
# Needed in the finally block for stack restoration
|
| 954 |
+
cg.add_push_null(
|
| 955 |
+
lambda: cg.load_import_from(
|
| 956 |
+
utils.__name__, "get_torch_function_mode_stack"
|
| 957 |
+
)
|
| 958 |
+
)
|
| 959 |
+
cg.call_function(0, False)
|
| 960 |
+
name = variables.torch_function.get_prev_stack_var_name()
|
| 961 |
+
cg.code_options["co_varnames"] += (name,)
|
| 962 |
+
cg.append_output(create_instruction("STORE_FAST", argval=name))
|
| 963 |
+
cg.add_push_null(
|
| 964 |
+
lambda: cg.load_import_from(
|
| 965 |
+
utils.__name__, "set_torch_function_mode_stack"
|
| 966 |
+
)
|
| 967 |
+
)
|
| 968 |
+
|
| 969 |
+
cg.foreach(var.symbolic_stack)
|
| 970 |
+
cg.append_output(
|
| 971 |
+
create_instruction("BUILD_LIST", arg=len(var.symbolic_stack))
|
| 972 |
+
)
|
| 973 |
+
cg.call_function(1, False)
|
| 974 |
+
cg.append_output(create_instruction("POP_TOP"))
|
| 975 |
+
|
| 976 |
+
elif isinstance(var, variables.CellVariable) and var.local_name is not None:
|
| 977 |
+
# Emit more readable and performant bytecode.
|
| 978 |
+
# TODO generalize this for cells created during inlining.
|
| 979 |
+
if var in self.store_attr_mutations:
|
| 980 |
+
contents_var = self.load_cell(var)
|
| 981 |
+
cg(contents_var)
|
| 982 |
+
suffixes.append([cg.create_store_deref(var.local_name)])
|
| 983 |
+
|
| 984 |
+
elif self.is_attribute_mutation(var):
|
| 985 |
+
if isinstance(
|
| 986 |
+
var,
|
| 987 |
+
variables.UserDefinedDictVariable,
|
| 988 |
+
# pyrefly: ignore [bad-argument-type]
|
| 989 |
+
) and self.is_modified(var._dict_vt):
|
| 990 |
+
# Do dict related update manually here. The store_attr
|
| 991 |
+
# mutations will be applied later.
|
| 992 |
+
varname_map = {}
|
| 993 |
+
for name in _manual_dict_setitem.__code__.co_varnames:
|
| 994 |
+
varname_map[name] = cg.tx.output.new_var()
|
| 995 |
+
|
| 996 |
+
try:
|
| 997 |
+
mro_index = type(var.value).__mro__.index(
|
| 998 |
+
collections.OrderedDict
|
| 999 |
+
)
|
| 1000 |
+
except ValueError:
|
| 1001 |
+
mro_index = type(var.value).__mro__.index(dict)
|
| 1002 |
+
|
| 1003 |
+
cg.extend_output(
|
| 1004 |
+
[
|
| 1005 |
+
create_instruction("LOAD_CONST", argval=mro_index),
|
| 1006 |
+
create_instruction(
|
| 1007 |
+
"STORE_FAST", argval=varname_map["mro_index"]
|
| 1008 |
+
),
|
| 1009 |
+
]
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1013 |
+
cg.extend_output(
|
| 1014 |
+
[
|
| 1015 |
+
create_instruction(
|
| 1016 |
+
"STORE_FAST", argval=varname_map["dict_to"]
|
| 1017 |
+
)
|
| 1018 |
+
]
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1022 |
+
cg(var._dict_vt, allow_cache=False) # Don't codegen via source
|
| 1023 |
+
cg.extend_output(
|
| 1024 |
+
[
|
| 1025 |
+
create_instruction(
|
| 1026 |
+
"STORE_FAST", argval=varname_map["dict_from"]
|
| 1027 |
+
)
|
| 1028 |
+
]
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
dict_update_insts = bytecode_from_template(
|
| 1032 |
+
_manual_dict_setitem, varname_map=varname_map
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
suffixes.append(
|
| 1036 |
+
[
|
| 1037 |
+
*dict_update_insts,
|
| 1038 |
+
create_instruction("POP_TOP"),
|
| 1039 |
+
]
|
| 1040 |
+
)
|
| 1041 |
+
elif isinstance(
|
| 1042 |
+
var,
|
| 1043 |
+
variables.UserDefinedListVariable,
|
| 1044 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1045 |
+
) and self.is_modified(var._list_vt):
|
| 1046 |
+
# Update the list to the updated items. Be careful in
|
| 1047 |
+
# calling the list methods and not the overridden methods.
|
| 1048 |
+
varname_map = {}
|
| 1049 |
+
for name in _manual_list_update.__code__.co_varnames:
|
| 1050 |
+
varname_map[name] = cg.tx.output.new_var()
|
| 1051 |
+
|
| 1052 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1053 |
+
cg.extend_output(
|
| 1054 |
+
[
|
| 1055 |
+
create_instruction(
|
| 1056 |
+
"STORE_FAST", argval=varname_map["list_to"]
|
| 1057 |
+
)
|
| 1058 |
+
]
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1062 |
+
cg(var._list_vt, allow_cache=False) # Don't codegen via source
|
| 1063 |
+
cg.extend_output(
|
| 1064 |
+
[
|
| 1065 |
+
create_instruction(
|
| 1066 |
+
"STORE_FAST", argval=varname_map["list_from"]
|
| 1067 |
+
)
|
| 1068 |
+
]
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
list_update_insts = bytecode_from_template(
|
| 1072 |
+
_manual_list_update, varname_map=varname_map
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
suffixes.append(
|
| 1076 |
+
[
|
| 1077 |
+
*list_update_insts,
|
| 1078 |
+
create_instruction("POP_TOP"),
|
| 1079 |
+
]
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
# Applying mutations involves two steps: 1) Push all
|
| 1083 |
+
# reconstructed objects onto the stack. 2) Call STORE_ATTR to
|
| 1084 |
+
# apply the mutations.
|
| 1085 |
+
#
|
| 1086 |
+
# Dynamo must ensure that mutations are applied in the same
|
| 1087 |
+
# order as in the original program. Therefore, two reverse
|
| 1088 |
+
# operations occur below.
|
| 1089 |
+
#
|
| 1090 |
+
# The first reverse operation concerns `suffixes`. We apply
|
| 1091 |
+
# suffixes in reverse order due to the way Python handles the
|
| 1092 |
+
# stack. In Step 1, we push all reconstructed objects onto the
|
| 1093 |
+
# stack, but the item at the top of the stack refers to the last
|
| 1094 |
+
# attribute in the mutation order. If not fixed, this will apply
|
| 1095 |
+
# the mutations of attributes in the reverse order. To account
|
| 1096 |
+
# for this reversal, we iterate through the mutable attributes
|
| 1097 |
+
# in reverse order.
|
| 1098 |
+
for name, value in reversed(
|
| 1099 |
+
self.store_attr_mutations.get(var, {}).items()
|
| 1100 |
+
):
|
| 1101 |
+
if isinstance(var, variables.NewGlobalVariable):
|
| 1102 |
+
cg.tx.output.update_co_names(name)
|
| 1103 |
+
cg(value)
|
| 1104 |
+
assert isinstance(var.source, GlobalSource) # type: ignore[attr-defined]
|
| 1105 |
+
suffixes.append(
|
| 1106 |
+
[create_instruction("STORE_GLOBAL", argval=name)]
|
| 1107 |
+
)
|
| 1108 |
+
elif isinstance(value, variables.DeletedVariable):
|
| 1109 |
+
if isinstance(
|
| 1110 |
+
var.mutation_type, AttributeMutationExisting
|
| 1111 |
+
) and hasattr(getattr(var, "value", None), name):
|
| 1112 |
+
cg.tx.output.update_co_names(name)
|
| 1113 |
+
cg(var.source)
|
| 1114 |
+
suffixes.append(
|
| 1115 |
+
[create_instruction("DELETE_ATTR", argval=name)]
|
| 1116 |
+
)
|
| 1117 |
+
elif isinstance(
|
| 1118 |
+
var, variables.UserDefinedObjectVariable
|
| 1119 |
+
) and var.should_skip_descriptor_setter(name):
|
| 1120 |
+
cg.add_push_null(
|
| 1121 |
+
lambda: cg.load_import_from(
|
| 1122 |
+
utils.__name__, "object_setattr_ignore_descriptor"
|
| 1123 |
+
)
|
| 1124 |
+
)
|
| 1125 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1126 |
+
cg(variables.ConstantVariable(name))
|
| 1127 |
+
cg(value)
|
| 1128 |
+
suffixes.append(
|
| 1129 |
+
[
|
| 1130 |
+
*create_call_function(3, False),
|
| 1131 |
+
create_instruction("POP_TOP"),
|
| 1132 |
+
]
|
| 1133 |
+
)
|
| 1134 |
+
elif (
|
| 1135 |
+
isinstance(var, variables.UserDefinedObjectVariable)
|
| 1136 |
+
and var.needs_slow_setattr()
|
| 1137 |
+
):
|
| 1138 |
+
# __setattr__ is defined on this object, so call object.__setattr__ directly
|
| 1139 |
+
cg.load_import_from("builtins", "object")
|
| 1140 |
+
cg.load_method("__setattr__")
|
| 1141 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1142 |
+
cg(variables.ConstantVariable(name))
|
| 1143 |
+
cg(value)
|
| 1144 |
+
suffixes.append(
|
| 1145 |
+
[*create_call_method(3), create_instruction("POP_TOP")]
|
| 1146 |
+
)
|
| 1147 |
+
else:
|
| 1148 |
+
cg.tx.output.update_co_names(name)
|
| 1149 |
+
cg(value)
|
| 1150 |
+
cg(var)
|
| 1151 |
+
suffixes.append([create_instruction("STORE_ATTR", argval=name)])
|
| 1152 |
+
elif isinstance(var, variables.ListIteratorVariable):
|
| 1153 |
+
for _ in range(var.index):
|
| 1154 |
+
cg.add_push_null(
|
| 1155 |
+
lambda: cg.load_import_from(utils.__name__, "iter_next")
|
| 1156 |
+
)
|
| 1157 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1158 |
+
cg.call_function(1, False)
|
| 1159 |
+
cg.pop_top()
|
| 1160 |
+
elif isinstance(var, variables.RandomVariable):
|
| 1161 |
+
# set correct random seed state
|
| 1162 |
+
def gen_fn() -> None:
|
| 1163 |
+
cg(var.source) # type: ignore[attr-defined]
|
| 1164 |
+
cg.load_attr("setstate")
|
| 1165 |
+
|
| 1166 |
+
cg.add_push_null(gen_fn)
|
| 1167 |
+
cg(var.wrap_state(var.random.getstate()))
|
| 1168 |
+
|
| 1169 |
+
suffixes.append(
|
| 1170 |
+
[
|
| 1171 |
+
*create_call_function(1, False), # setstate
|
| 1172 |
+
create_instruction("POP_TOP"),
|
| 1173 |
+
]
|
| 1174 |
+
)
|
| 1175 |
+
else:
|
| 1176 |
+
raise AssertionError(type(var))
|
| 1177 |
+
|
| 1178 |
+
# do all the actual mutations at the very end to handle dependencies
|
| 1179 |
+
for suffix in reversed(suffixes):
|
| 1180 |
+
cg.extend_output(suffix)
|
| 1181 |
+
|
| 1182 |
+
def is_empty(self) -> bool:
|
| 1183 |
+
return not (
|
| 1184 |
+
any(map(self.is_modified, self.id_to_variable.values()))
|
| 1185 |
+
or self.tensor_hooks
|
| 1186 |
+
or self.save_for_backward
|
| 1187 |
+
or self.tensor_hooks
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
def clear(self) -> None:
|
| 1191 |
+
self.keepalive.clear()
|
| 1192 |
+
self.id_to_variable.clear()
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@contextlib.contextmanager
|
| 1196 |
+
def allow_side_effects_in_hop(
|
| 1197 |
+
tx: "InstructionTranslatorBase",
|
| 1198 |
+
) -> Generator[None, None, None]:
|
| 1199 |
+
"""Context manager to temporarily allow side effects with extra outputs.
|
| 1200 |
+
|
| 1201 |
+
This is used for special cases (like FSDP functions) that need to perform
|
| 1202 |
+
side effects even when the general policy is to disallow them.
|
| 1203 |
+
"""
|
| 1204 |
+
orig_val = tx.output.current_tracer.allow_side_effects_in_hop
|
| 1205 |
+
try:
|
| 1206 |
+
tx.output.current_tracer.allow_side_effects_in_hop = True
|
| 1207 |
+
yield
|
| 1208 |
+
finally:
|
| 1209 |
+
tx.output.current_tracer.allow_side_effects_in_hop = orig_val
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
@contextlib.contextmanager
|
| 1213 |
+
def allow_externally_visible_side_effects_in_subtracer(
|
| 1214 |
+
tx: "InstructionTranslatorBase",
|
| 1215 |
+
) -> Generator[None, None, None]:
|
| 1216 |
+
orig_val = tx.output.current_tracer.unsafe_allow_externally_visible_side_effects
|
| 1217 |
+
try:
|
| 1218 |
+
tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = True
|
| 1219 |
+
tx.output.current_tracer.traced_with_externally_visible_side_effects = True
|
| 1220 |
+
yield
|
| 1221 |
+
finally:
|
| 1222 |
+
tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = orig_val
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
@contextlib.contextmanager
|
| 1226 |
+
def disallow_side_effects_in_generator(
|
| 1227 |
+
tx: "InstructionTranslatorBase",
|
| 1228 |
+
) -> Generator[None, None, None]:
|
| 1229 |
+
orig_val = tx.output.current_tracer.is_reconstructing_generator
|
| 1230 |
+
try:
|
| 1231 |
+
tx.output.current_tracer.is_reconstructing_generator = True
|
| 1232 |
+
yield
|
| 1233 |
+
finally:
|
| 1234 |
+
tx.output.current_tracer.is_reconstructing_generator = orig_val
|