Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_cpp_scheduling.py +114 -0
- vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_template.py +258 -0
- vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_utils.py +363 -0
- vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py +19 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/accelerator_partitioner.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/debug.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/graph_gradual_typechecker.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/meta_tracer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/optimization.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/partitioner_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/proxy_tensor.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/refinement_types.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/rewriter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/schema_type_annotation.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/_backward_state.py +27 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/_config.py +88 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/accelerator_partitioner.py +1079 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/const_fold.py +292 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/debug.py +32 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/graph_gradual_typechecker.py +916 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/merge_matmul.py +172 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/meta_tracer.py +269 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/constraint_generator.py +1281 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/operation.py +14 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/transform_to_z3.py +349 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/util.py +53 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/z3_types.py +29 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/normalize.py +163 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/optimization.py +409 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/partitioner_utils.py +318 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py +2215 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/recording.py +512 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/refinement_types.py +17 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/rewriter.py +128 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/schema_type_annotation.py +112 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/sym_node.py +1554 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/symbolic_shapes.py +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__init__.py +4 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/core.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/dispatch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/match.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/more.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/unification_tools.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/variable.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_cpp_scheduling.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
from typing import cast, Sequence
|
| 4 |
+
|
| 5 |
+
from ...._dynamo.utils import counters
|
| 6 |
+
from ... import config
|
| 7 |
+
from ...codecache import code_hash, get_path
|
| 8 |
+
from ...ir import CUDATemplateBuffer
|
| 9 |
+
from ...scheduler import BaseSchedulerNode, BaseScheduling, Scheduler, SchedulerNode
|
| 10 |
+
from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product
|
| 11 |
+
from ...virtualized import V
|
| 12 |
+
from ..common import IndentedBuffer
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class CUDACPPScheduling(BaseScheduling):
|
| 19 |
+
"""
|
| 20 |
+
Partial Scheduling implementation for CUDA C++ Kernels.
|
| 21 |
+
This class is intended to be used in combination with TritonScheduling,
|
| 22 |
+
and delegated to by CUDACombinedScheduling.
|
| 23 |
+
|
| 24 |
+
It handles fusion decisions and CUDA C++ specific template code generation.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, scheduler: Scheduler) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.scheduler = scheduler
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def get_backend_features(cls, device):
|
| 33 |
+
return {}
|
| 34 |
+
|
| 35 |
+
def group_fn(self, sizes):
|
| 36 |
+
return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def is_cuda_cpp_template(node: BaseSchedulerNode) -> bool:
|
| 40 |
+
return isinstance(node, SchedulerNode) and isinstance(
|
| 41 |
+
node.node, CUDATemplateBuffer
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def can_fuse_vertical(
|
| 45 |
+
self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
|
| 46 |
+
) -> bool:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
def define_kernel(self, src_code: str, node_schedule) -> str:
|
| 50 |
+
wrapper = V.graph.wrapper_code
|
| 51 |
+
if src_code in wrapper.src_to_kernel:
|
| 52 |
+
kernel_name = wrapper.src_to_kernel[src_code]
|
| 53 |
+
else:
|
| 54 |
+
fused_name = (
|
| 55 |
+
get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
|
| 56 |
+
if config.triton.descriptive_names
|
| 57 |
+
else ""
|
| 58 |
+
)
|
| 59 |
+
kernel_name = "_".join(["cuda", fused_name, wrapper.next_kernel_suffix()])
|
| 60 |
+
# use the original src_code as the key
|
| 61 |
+
wrapper.src_to_kernel[src_code] = kernel_name
|
| 62 |
+
src_code = src_code.replace("KERNEL_NAME", kernel_name)
|
| 63 |
+
|
| 64 |
+
_, _, kernel_path = get_path(code_hash(src_code), "py")
|
| 65 |
+
|
| 66 |
+
compile_wrapper = IndentedBuffer()
|
| 67 |
+
compile_wrapper.writeline("async_compile.cuda(r'''")
|
| 68 |
+
compile_wrapper.splice(src_code, strip=True)
|
| 69 |
+
compile_wrapper.writeline("''', 'so')")
|
| 70 |
+
|
| 71 |
+
metadata_comment = f"# kernel path: {kernel_path}"
|
| 72 |
+
origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
|
| 73 |
+
metadata_comment += "\n" + origins + "\n" + detailed_origins
|
| 74 |
+
wrapper.define_kernel(
|
| 75 |
+
kernel_name, compile_wrapper.getvalue(), metadata_comment
|
| 76 |
+
)
|
| 77 |
+
return kernel_name
|
| 78 |
+
|
| 79 |
+
def codegen_template(
|
| 80 |
+
self,
|
| 81 |
+
template_node: BaseSchedulerNode,
|
| 82 |
+
epilogue_nodes: Sequence[BaseSchedulerNode],
|
| 83 |
+
):
|
| 84 |
+
"""
|
| 85 |
+
Codegen a CUDA template, possibly with fused epilogues
|
| 86 |
+
"""
|
| 87 |
+
counters["inductor"]["cuda_epilogue_fusion_counter"] += len(epilogue_nodes)
|
| 88 |
+
assert self.is_cuda_cpp_template(
|
| 89 |
+
template_node
|
| 90 |
+
), "Template node passed to CUDAScheduler.codegen_template must be a SchedulerNode that wraps a CUDATemplateBuffer"
|
| 91 |
+
template_node = cast(SchedulerNode, template_node)
|
| 92 |
+
_, (numel, rnumel) = template_node.group
|
| 93 |
+
assert rnumel == 1
|
| 94 |
+
ctb: CUDATemplateBuffer = cast(CUDATemplateBuffer, template_node.node)
|
| 95 |
+
kernel, render = ctb.make_kernel_render(ctb)
|
| 96 |
+
with kernel:
|
| 97 |
+
template_node.mark_run()
|
| 98 |
+
src_code = render()
|
| 99 |
+
|
| 100 |
+
with V.set_kernel_handler(kernel):
|
| 101 |
+
node_schedule = [template_node]
|
| 102 |
+
kernel_name = self.define_kernel(src_code, node_schedule)
|
| 103 |
+
|
| 104 |
+
# debug printing values of intermediate tensors
|
| 105 |
+
_, call_args, arg_signatures, _ = kernel.args.python_argdefs()
|
| 106 |
+
debug_printer_manager = V.graph.wrapper_code.debug_printer
|
| 107 |
+
debug_printer_manager.set_printer_args(
|
| 108 |
+
call_args, kernel_name, arg_signatures, kernel
|
| 109 |
+
)
|
| 110 |
+
with debug_printer_manager:
|
| 111 |
+
kernel.call_kernel(kernel_name, ctb)
|
| 112 |
+
|
| 113 |
+
V.graph.removed_buffers |= kernel.removed_buffers
|
| 114 |
+
self.scheduler.free_buffers()
|
vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_template.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
import sympy
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from ...autotune_process import CUDABenchmarkRequest, TensorMeta
|
| 13 |
+
from ...ir import Buffer, CUDATemplateBuffer, IRNode, Layout
|
| 14 |
+
from ...utils import IndentedBuffer, unique
|
| 15 |
+
from ...virtualized import V
|
| 16 |
+
from ..common import KernelTemplate
|
| 17 |
+
from .cuda_kernel import CUDATemplateCaller, CUDATemplateKernel
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CUDATemplate(KernelTemplate):
|
| 24 |
+
index_counter = itertools.count()
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
name: str,
|
| 29 |
+
input_nodes: List[Buffer],
|
| 30 |
+
layout: Layout,
|
| 31 |
+
input_reorder: Optional[List[int]] = None,
|
| 32 |
+
) -> None:
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
Baseclass for CUDA C++ Templates, derived from KernelTemplate. Not to be instantiated directly.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
name (str): The name of the CUDATemplate object.
|
| 39 |
+
input_nodes (List[IRNode]): A list of input IRNodes.
|
| 40 |
+
layout (Layout): The layout of the output buffer / tensor.
|
| 41 |
+
input_reorder (Optional[List[int]]): An optional list that specifies the order of the input nodes.
|
| 42 |
+
|
| 43 |
+
"""
|
| 44 |
+
super().__init__(name)
|
| 45 |
+
self.input_nodes = input_nodes
|
| 46 |
+
self.output_node: Buffer = Buffer("buf_out", layout)
|
| 47 |
+
self.input_reorder = input_reorder
|
| 48 |
+
self.layout = layout
|
| 49 |
+
|
| 50 |
+
def generate( # type: ignore[override]
|
| 51 |
+
self,
|
| 52 |
+
**kwargs,
|
| 53 |
+
) -> CUDATemplateCaller:
|
| 54 |
+
"""
|
| 55 |
+
Generates the CUDA template caller object for the given GEMM template and operation. This CUDATemplateCaller
|
| 56 |
+
may be used to call and benchmark the generated CUDA kernel in a standalone manner to enable Autotuning.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
kwargs: Additional keyword arguments.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
A CUDATemplateCaller object representing the generated CUDA template caller.
|
| 63 |
+
"""
|
| 64 |
+
kernel_name = f"cuda_{self.name}"
|
| 65 |
+
with patch.object(
|
| 66 |
+
V.graph, "get_dtype", self._fake_get_dtype(self.output_node)
|
| 67 |
+
), CUDATemplateKernel(
|
| 68 |
+
kernel_name=kernel_name,
|
| 69 |
+
) as kernel:
|
| 70 |
+
code = self.render(kernel=kernel, **kwargs)
|
| 71 |
+
_, call_args, _, _ = kernel.args.python_argdefs()
|
| 72 |
+
log.debug("Generated Code:\n%s", code)
|
| 73 |
+
log.debug(
|
| 74 |
+
"Args: cpp_argdefs: %s, python_argdefs: %s",
|
| 75 |
+
kernel.args.cpp_argdefs(),
|
| 76 |
+
kernel.args.python_argdefs(),
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
input_reorder = (
|
| 80 |
+
self.input_reorder
|
| 81 |
+
if self.input_reorder is not None
|
| 82 |
+
else list(range(len(self.input_nodes)))
|
| 83 |
+
)
|
| 84 |
+
expected_args = list(
|
| 85 |
+
unique(self.input_nodes[idx].get_name() for idx in input_reorder)
|
| 86 |
+
)
|
| 87 |
+
expected_args.extend([self.output_node.get_name()])
|
| 88 |
+
assert list(call_args)[: len(expected_args)] == expected_args, (
|
| 89 |
+
call_args,
|
| 90 |
+
expected_args,
|
| 91 |
+
)
|
| 92 |
+
extra_args = V.graph.sizevars.size_hints(
|
| 93 |
+
map(sympy.expand, call_args[len(expected_args) :])
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
kernel_hash_name = f"cuda_{self.name}_{next(self.index_counter)}"
|
| 97 |
+
|
| 98 |
+
# create the BenchmarkRequest
|
| 99 |
+
bmreq = CUDABenchmarkRequest(
|
| 100 |
+
kernel_name=kernel_name,
|
| 101 |
+
input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
|
| 102 |
+
output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
|
| 103 |
+
extra_args=extra_args,
|
| 104 |
+
source_code=code,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def make_kernel_render(
|
| 108 |
+
template_node: CUDATemplateBuffer,
|
| 109 |
+
epilogue_nodes: Optional[List[IRNode]] = None,
|
| 110 |
+
):
|
| 111 |
+
kernel = CUDATemplateKernel(
|
| 112 |
+
kernel_name="KERNEL_NAME",
|
| 113 |
+
)
|
| 114 |
+
render = functools.partial(
|
| 115 |
+
self.render,
|
| 116 |
+
kernel=kernel,
|
| 117 |
+
template_buffer_node=template_node,
|
| 118 |
+
epilogue_nodes=epilogue_nodes,
|
| 119 |
+
**kwargs, # includes "op" argument in case of CUTLASSGemmTemplate
|
| 120 |
+
)
|
| 121 |
+
return kernel, render
|
| 122 |
+
|
| 123 |
+
return CUDATemplateCaller(
|
| 124 |
+
kernel_hash_name,
|
| 125 |
+
self.name,
|
| 126 |
+
self.input_nodes,
|
| 127 |
+
self.output_node.get_layout(),
|
| 128 |
+
make_kernel_render,
|
| 129 |
+
bmreq,
|
| 130 |
+
self,
|
| 131 |
+
kwargs,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def header(self) -> IndentedBuffer:
|
| 135 |
+
res = IndentedBuffer()
|
| 136 |
+
res.splice(
|
| 137 |
+
"""
|
| 138 |
+
#include <exception>
|
| 139 |
+
#include <iostream>
|
| 140 |
+
#include <memory>
|
| 141 |
+
#include <random>
|
| 142 |
+
#include <vector>
|
| 143 |
+
"""
|
| 144 |
+
)
|
| 145 |
+
return res
|
| 146 |
+
|
| 147 |
+
def globals(self) -> IndentedBuffer:
|
| 148 |
+
res = IndentedBuffer()
|
| 149 |
+
res.splice(
|
| 150 |
+
"""
|
| 151 |
+
// We compile all models with -fvisibility=hidden. Any symbols that need to be
|
| 152 |
+
// exposed in the final shared library must be declared with PT_EXPORT to make
|
| 153 |
+
// them visible.
|
| 154 |
+
#ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++)
|
| 155 |
+
#define PT_EXPORT __attribute__((__visibility__("default")))
|
| 156 |
+
#else
|
| 157 |
+
#ifdef _WIN32
|
| 158 |
+
#define PT_EXPORT __declspec(dllexport)
|
| 159 |
+
#else
|
| 160 |
+
#define PT_EXPORT
|
| 161 |
+
#endif
|
| 162 |
+
#endif
|
| 163 |
+
using bfloat16 = nv_bfloat16;
|
| 164 |
+
"""
|
| 165 |
+
)
|
| 166 |
+
return res
|
| 167 |
+
|
| 168 |
+
def render(self, **kwargs) -> str:
|
| 169 |
+
raise NotImplementedError
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class CUTLASSTemplate(CUDATemplate):
|
| 173 |
+
"""
|
| 174 |
+
CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the
|
| 175 |
+
CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def header(self) -> IndentedBuffer:
|
| 179 |
+
res = super().header()
|
| 180 |
+
res.splice(
|
| 181 |
+
"""
|
| 182 |
+
#include "cute/tensor.hpp"
|
| 183 |
+
#include "cutlass/cutlass.h"
|
| 184 |
+
#include "cutlass/numeric_types.h"
|
| 185 |
+
#include "cutlass/tensor_ref.h"
|
| 186 |
+
#include "cutlass/util/host_tensor.h"
|
| 187 |
+
#include "cutlass/util/reference/host/tensor_fill.h"
|
| 188 |
+
#include "cutlass/util/reference/device/tensor_fill.h"
|
| 189 |
+
#include "cutlass/util/device_memory.h"
|
| 190 |
+
"""
|
| 191 |
+
)
|
| 192 |
+
return res
|
| 193 |
+
|
| 194 |
+
def globals(self) -> IndentedBuffer:
|
| 195 |
+
res = super().globals()
|
| 196 |
+
res.splice(
|
| 197 |
+
"""
|
| 198 |
+
using namespace cute;
|
| 199 |
+
#define CUTLASS_CHECK(status) \\
|
| 200 |
+
{ \\
|
| 201 |
+
cutlass::Status error = status; \\
|
| 202 |
+
if (error != cutlass::Status::kSuccess) { \\
|
| 203 |
+
auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\
|
| 204 |
+
cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\
|
| 205 |
+
throw std::runtime_error(msg); \\
|
| 206 |
+
} \\
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// Used as pass-through functor in EVT just for type casting / rounding
|
| 210 |
+
template <typename T>
|
| 211 |
+
struct identity_op {
|
| 212 |
+
CUTLASS_HOST_DEVICE
|
| 213 |
+
T operator()(T val) const { return val; }
|
| 214 |
+
};
|
| 215 |
+
|
| 216 |
+
"""
|
| 217 |
+
)
|
| 218 |
+
return res
|
| 219 |
+
|
| 220 |
+
def cute_int(self, int_str: str, var_name: str) -> str:
|
| 221 |
+
res = ""
|
| 222 |
+
if int_str in {"1", "1L"}:
|
| 223 |
+
res = "cute::Int<1>{}"
|
| 224 |
+
else:
|
| 225 |
+
res = int_str
|
| 226 |
+
|
| 227 |
+
return f"{res} /* {var_name} */"
|
| 228 |
+
|
| 229 |
+
_DTYPE_TO_CUTLASS = {
|
| 230 |
+
torch.float32: "float",
|
| 231 |
+
torch.float64: "double",
|
| 232 |
+
torch.float16: "cutlass::half_t",
|
| 233 |
+
torch.int32: "int32_t",
|
| 234 |
+
torch.int16: "int16_t",
|
| 235 |
+
torch.int8: "int8_t",
|
| 236 |
+
torch.uint8: "uint8_t",
|
| 237 |
+
torch.bool: "bool",
|
| 238 |
+
torch.bfloat16: "cutlass::bfloat16_t",
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
_DTYPE_TO_CUTLASS_SPARSE_META = {
|
| 242 |
+
torch.int32: "uint32_t",
|
| 243 |
+
torch.int16: "uint16_t",
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
def cutlass_type_cast(self, node: IRNode, ptr: str) -> str:
|
| 247 |
+
if node is None:
|
| 248 |
+
return ptr
|
| 249 |
+
else:
|
| 250 |
+
return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})"
|
| 251 |
+
|
| 252 |
+
def cutlass_sparse_meta_type_cast(self, node: IRNode, ptr: str) -> str:
|
| 253 |
+
if node is None:
|
| 254 |
+
return ptr
|
| 255 |
+
else:
|
| 256 |
+
return (
|
| 257 |
+
f"({self._DTYPE_TO_CUTLASS_SPARSE_META.get(node.get_dtype())}*)({ptr})"
|
| 258 |
+
)
|
vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_utils.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, List, Optional
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from ... import config
|
| 15 |
+
from ...ir import Layout
|
| 16 |
+
from ...runtime.runtime_utils import cache_dir
|
| 17 |
+
from .cuda_env import get_cuda_arch, get_cuda_version
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _rename_cutlass_import(content: str, cutlass_modules: List[str]) -> str:
|
| 24 |
+
for cutlass_module in cutlass_modules:
|
| 25 |
+
content = content.replace(
|
| 26 |
+
f"from {cutlass_module} import ",
|
| 27 |
+
f"from cutlass_library.{cutlass_module} import ",
|
| 28 |
+
)
|
| 29 |
+
return content
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _gen_cutlass_file(
|
| 33 |
+
file_name: str, cutlass_modules: List[str], src_dir: str, dst_dir: str
|
| 34 |
+
) -> None:
|
| 35 |
+
orig_full_path = os.path.abspath(os.path.join(src_dir, file_name))
|
| 36 |
+
text = ""
|
| 37 |
+
with open(orig_full_path) as f:
|
| 38 |
+
text = f.read()
|
| 39 |
+
text = _rename_cutlass_import(text, cutlass_modules)
|
| 40 |
+
dst_full_path = os.path.abspath(
|
| 41 |
+
os.path.join(
|
| 42 |
+
dst_dir,
|
| 43 |
+
file_name,
|
| 44 |
+
)
|
| 45 |
+
)
|
| 46 |
+
with open(dst_full_path, "w") as f:
|
| 47 |
+
f.write(text)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@functools.lru_cache(None)
|
| 51 |
+
def try_import_cutlass() -> bool:
|
| 52 |
+
if config.is_fbcode():
|
| 53 |
+
return True
|
| 54 |
+
|
| 55 |
+
# Copy CUTLASS python scripts to a temp dir and add the temp dir to Python search path.
|
| 56 |
+
# This is a temporary hack to avoid CUTLASS module naming conflicts.
|
| 57 |
+
# TODO(ipiszy): remove this hack when CUTLASS solves Python scripts packaging structure issues.
|
| 58 |
+
|
| 59 |
+
cutlass_py_full_path = os.path.abspath(
|
| 60 |
+
os.path.join(config.cuda.cutlass_dir, "python/cutlass_library")
|
| 61 |
+
)
|
| 62 |
+
tmp_cutlass_py_full_path = os.path.abspath(
|
| 63 |
+
os.path.join(cache_dir(), "torch_cutlass_library")
|
| 64 |
+
)
|
| 65 |
+
dst_link = os.path.join(tmp_cutlass_py_full_path, "cutlass_library")
|
| 66 |
+
|
| 67 |
+
if os.path.isdir(cutlass_py_full_path):
|
| 68 |
+
if tmp_cutlass_py_full_path not in sys.path:
|
| 69 |
+
if os.path.exists(dst_link):
|
| 70 |
+
assert os.path.islink(
|
| 71 |
+
dst_link
|
| 72 |
+
), f"{dst_link} is not a symlink. Try to remove {dst_link} manually and try again."
|
| 73 |
+
assert os.path.realpath(os.readlink(dst_link)) == os.path.realpath(
|
| 74 |
+
cutlass_py_full_path
|
| 75 |
+
), f"Symlink at {dst_link} does not point to {cutlass_py_full_path}"
|
| 76 |
+
else:
|
| 77 |
+
os.makedirs(tmp_cutlass_py_full_path, exist_ok=True)
|
| 78 |
+
os.symlink(cutlass_py_full_path, dst_link)
|
| 79 |
+
sys.path.append(tmp_cutlass_py_full_path)
|
| 80 |
+
try:
|
| 81 |
+
import cutlass_library.generator # noqa: F401
|
| 82 |
+
import cutlass_library.library # noqa: F401
|
| 83 |
+
import cutlass_library.manifest # noqa: F401
|
| 84 |
+
|
| 85 |
+
return True
|
| 86 |
+
|
| 87 |
+
except ImportError as e:
|
| 88 |
+
log.debug(
|
| 89 |
+
"Failed to import CUTLASS packages: %s, ignoring the CUTLASS backend.",
|
| 90 |
+
str(e),
|
| 91 |
+
)
|
| 92 |
+
else:
|
| 93 |
+
log.debug(
|
| 94 |
+
"Failed to import CUTLASS packages: CUTLASS repo does not exist: %s",
|
| 95 |
+
cutlass_py_full_path,
|
| 96 |
+
)
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _normalize_cuda_arch(arch: str) -> str:
|
| 101 |
+
if int(arch) >= 90:
|
| 102 |
+
return "90"
|
| 103 |
+
elif int(arch) >= 80:
|
| 104 |
+
return "80"
|
| 105 |
+
elif int(arch) >= 75:
|
| 106 |
+
return "75"
|
| 107 |
+
elif int(arch) >= 70:
|
| 108 |
+
return "70"
|
| 109 |
+
else:
|
| 110 |
+
raise NotImplementedError(f"Unsupported cuda arch: {arch}")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@dataclass
|
| 114 |
+
class CUTLASSArgs:
|
| 115 |
+
"""
|
| 116 |
+
CUTLASS args used to initialize a CUTLASS Manifest.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
architectures: Optional[str] = None
|
| 120 |
+
cuda_version: Optional[str] = None
|
| 121 |
+
|
| 122 |
+
operations = "all"
|
| 123 |
+
build_dir = ""
|
| 124 |
+
curr_build_dir = ""
|
| 125 |
+
generator_target = ""
|
| 126 |
+
kernels = "all"
|
| 127 |
+
ignore_kernels = ""
|
| 128 |
+
# TODO: these three look dead?
|
| 129 |
+
kernel_filter_file: None = None
|
| 130 |
+
selected_kernel_list: None = None
|
| 131 |
+
interface_dir: None = None
|
| 132 |
+
filter_by_cc = True
|
| 133 |
+
disable_full_archs_compilation = False
|
| 134 |
+
|
| 135 |
+
def __post_init__(self):
|
| 136 |
+
if self.architectures is None or self.cuda_version is None:
|
| 137 |
+
raise RuntimeError(
|
| 138 |
+
f"{self.architectures=} or {self.cuda_version=} is None!"
|
| 139 |
+
)
|
| 140 |
+
self.architectures = _normalize_cuda_arch(self.architectures)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@functools.lru_cache(None)
|
| 144 |
+
def _gen_ops_cached(arch, version) -> List[Any]:
|
| 145 |
+
# Note: Cache needs to be specific for cuda architecture and version
|
| 146 |
+
|
| 147 |
+
# Import cutlass python scripts.
|
| 148 |
+
assert try_import_cutlass()
|
| 149 |
+
import cutlass_library.generator as cutlass_generator
|
| 150 |
+
import cutlass_library.manifest as cutlass_manifest
|
| 151 |
+
|
| 152 |
+
if arch is None or version is None:
|
| 153 |
+
log.error(
|
| 154 |
+
"Cannot detect cuda arch %s or cuda version %s. "
|
| 155 |
+
"Will discard all cutlass ops. "
|
| 156 |
+
"Please consider setting _inductor.cuda.arch and _inductor.cuda.version configs.",
|
| 157 |
+
arch,
|
| 158 |
+
version,
|
| 159 |
+
)
|
| 160 |
+
return []
|
| 161 |
+
arch = _normalize_cuda_arch(arch)
|
| 162 |
+
args = CUTLASSArgs(architectures=arch, cuda_version=version)
|
| 163 |
+
manifest = cutlass_manifest.Manifest(args)
|
| 164 |
+
|
| 165 |
+
if arch == "90":
|
| 166 |
+
cutlass_generator.GenerateSM90(manifest, args.cuda_version)
|
| 167 |
+
cutlass_generator.GenerateSM80(manifest, args.cuda_version)
|
| 168 |
+
else:
|
| 169 |
+
try:
|
| 170 |
+
func = getattr(cutlass_generator, "GenerateSM" + arch)
|
| 171 |
+
func(manifest, args.cuda_version)
|
| 172 |
+
except AttributeError as e:
|
| 173 |
+
raise NotImplementedError(
|
| 174 |
+
"Arch " + arch + " is not supported by current cutlass lib."
|
| 175 |
+
) from e
|
| 176 |
+
return manifest.operations
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def gen_ops() -> List[Any]:
|
| 180 |
+
"""
|
| 181 |
+
Generates all supported CUTLASS operations.
|
| 182 |
+
"""
|
| 183 |
+
arch = get_cuda_arch()
|
| 184 |
+
version = get_cuda_version()
|
| 185 |
+
return _gen_ops_cached(arch, version)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def torch_dtype_to_cutlass_type(
|
| 189 |
+
torch_dtype: torch.dtype,
|
| 190 |
+
) -> "cutlass_library.library.DataType": # type: ignore[name-defined] # noqa: F821
|
| 191 |
+
# Import cutlass python scripts.
|
| 192 |
+
assert try_import_cutlass()
|
| 193 |
+
import cutlass_library # type: ignore[import]
|
| 194 |
+
|
| 195 |
+
if torch_dtype == torch.float:
|
| 196 |
+
return cutlass_library.library.DataType.f32
|
| 197 |
+
elif torch_dtype == torch.half:
|
| 198 |
+
return cutlass_library.library.DataType.f16
|
| 199 |
+
elif torch_dtype == torch.bfloat16:
|
| 200 |
+
return cutlass_library.library.DataType.bf16
|
| 201 |
+
else:
|
| 202 |
+
raise NotImplementedError(f"Unsupported data type: {torch_dtype=}")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def dtype_match(
|
| 206 |
+
torch_dtype: Optional[torch.dtype],
|
| 207 |
+
cutlass_dtype: "cutlass_library.library.DataType", # type: ignore[name-defined] # noqa: F821
|
| 208 |
+
) -> bool:
|
| 209 |
+
# Import cutlass python scripts.
|
| 210 |
+
assert try_import_cutlass()
|
| 211 |
+
import cutlass_library
|
| 212 |
+
|
| 213 |
+
if torch_dtype == torch.float:
|
| 214 |
+
return (
|
| 215 |
+
cutlass_dtype == cutlass_library.library.DataType.f32
|
| 216 |
+
or cutlass_dtype == cutlass_library.library.DataType.tf32
|
| 217 |
+
)
|
| 218 |
+
elif torch_dtype == torch.half:
|
| 219 |
+
return cutlass_dtype == cutlass_library.library.DataType.f16
|
| 220 |
+
elif torch_dtype == torch.bfloat16:
|
| 221 |
+
return cutlass_dtype == cutlass_library.library.DataType.bf16
|
| 222 |
+
elif torch_dtype == torch.int8:
|
| 223 |
+
return cutlass_dtype == cutlass_library.library.DataType.s8
|
| 224 |
+
elif torch_dtype == torch.uint8:
|
| 225 |
+
return cutlass_dtype == cutlass_library.library.DataType.u8
|
| 226 |
+
elif torch_dtype == torch.int32:
|
| 227 |
+
return cutlass_dtype == cutlass_library.library.DataType.s32
|
| 228 |
+
else:
|
| 229 |
+
return False
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def get_accumulator_dtype(
|
| 233 |
+
input_torch_dtypes: List[torch.dtype],
|
| 234 |
+
) -> Optional[torch.dtype]:
|
| 235 |
+
"""
|
| 236 |
+
Given a pair of input torch dtypes, returns the inferred accumulator torch dtype.
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
if len(input_torch_dtypes) != 2:
|
| 240 |
+
return None
|
| 241 |
+
|
| 242 |
+
torch_dtype = None
|
| 243 |
+
if input_torch_dtypes[0] == input_torch_dtypes[1]:
|
| 244 |
+
torch_dtype = input_torch_dtypes[0]
|
| 245 |
+
else:
|
| 246 |
+
size0 = torch.tensor([], dtype=input_torch_dtypes[0]).element_size()
|
| 247 |
+
size1 = torch.tensor([], dtype=input_torch_dtypes[1]).element_size()
|
| 248 |
+
if size0 > size1:
|
| 249 |
+
dtype0, dtype1 = input_torch_dtypes
|
| 250 |
+
else:
|
| 251 |
+
dtype1, dtype0 = input_torch_dtypes
|
| 252 |
+
if dtype0 in [torch.half, torch.bfloat16] and dtype1 in [
|
| 253 |
+
torch.int8,
|
| 254 |
+
torch.uint8,
|
| 255 |
+
]:
|
| 256 |
+
torch_dtype = dtype0
|
| 257 |
+
|
| 258 |
+
if torch_dtype == torch.half:
|
| 259 |
+
if torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction:
|
| 260 |
+
return torch_dtype
|
| 261 |
+
else:
|
| 262 |
+
return torch.float
|
| 263 |
+
if torch_dtype in {torch.bfloat16, torch.float}:
|
| 264 |
+
return torch.float
|
| 265 |
+
if torch_dtype == torch.int8:
|
| 266 |
+
return torch.int32
|
| 267 |
+
raise NotImplementedError(f"Unsupported data types: {input_torch_dtypes=}")
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def get_alignments(torch_dtype: torch.dtype) -> List[int]:
|
| 271 |
+
"""
|
| 272 |
+
Returns all possible valid CUTLASS alignments in terms of the number of elements for a given dtype.
|
| 273 |
+
CUTLASS gemm / conv SM80 APIs support 16 bytes max alignment, and 2 bytes min alignment.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
if torch_dtype in (torch.half, torch.bfloat16):
|
| 277 |
+
return [8, 4, 2, 1]
|
| 278 |
+
elif torch_dtype == torch.float:
|
| 279 |
+
return [4, 2, 1]
|
| 280 |
+
elif torch_dtype in (torch.uint8, torch.int8):
|
| 281 |
+
return [16, 8, 4, 2]
|
| 282 |
+
elif torch_dtype == torch.int32:
|
| 283 |
+
return [4, 2, 1]
|
| 284 |
+
else:
|
| 285 |
+
raise NotImplementedError(f"unsupported {torch_dtype=} for alignments")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def get_max_alignment(inductor_layout: Layout) -> int:
|
| 289 |
+
"""
|
| 290 |
+
Returns the max alignment (in terms of number of elements) for a given Inductor Layout.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
dtype = inductor_layout.dtype
|
| 294 |
+
size = inductor_layout.size
|
| 295 |
+
offset = inductor_layout.offset
|
| 296 |
+
|
| 297 |
+
def is_static_int(number):
|
| 298 |
+
return isinstance(number, (int, sympy.Integer))
|
| 299 |
+
|
| 300 |
+
try:
|
| 301 |
+
contiguous_dim = inductor_layout.stride.index(1)
|
| 302 |
+
except ValueError:
|
| 303 |
+
# No dim with stride 1 found, return 1
|
| 304 |
+
return 1
|
| 305 |
+
if (
|
| 306 |
+
is_static_int(size[contiguous_dim])
|
| 307 |
+
and is_static_int(offset)
|
| 308 |
+
and all(is_static_int(s) for s in inductor_layout.stride)
|
| 309 |
+
):
|
| 310 |
+
alignments = get_alignments(dtype)
|
| 311 |
+
for alignment in alignments:
|
| 312 |
+
if (
|
| 313 |
+
int(size[contiguous_dim]) % alignment != 0
|
| 314 |
+
or int(offset) % alignment != 0
|
| 315 |
+
):
|
| 316 |
+
continue
|
| 317 |
+
if all(
|
| 318 |
+
(dim == contiguous_dim)
|
| 319 |
+
or (inductor_layout.stride[dim] % alignment == 0)
|
| 320 |
+
for dim in range(len(size))
|
| 321 |
+
):
|
| 322 |
+
return alignment
|
| 323 |
+
return 1
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class CUDACompileSourceCapturingContext:
|
| 327 |
+
# Helper class for Benchmarking and Testing CUTLASS Kernels in isolation.
|
| 328 |
+
# Can be used to capture the sourcecode passed to CUDACodeCache.compile
|
| 329 |
+
|
| 330 |
+
def __init__(self):
|
| 331 |
+
self.sources = []
|
| 332 |
+
self._compile_patch = None
|
| 333 |
+
|
| 334 |
+
def __enter__(self, *args, **kwargs):
|
| 335 |
+
import unittest.mock as mock
|
| 336 |
+
|
| 337 |
+
import torch._inductor.codecache
|
| 338 |
+
|
| 339 |
+
_compile_method_orig = torch._inductor.codecache.CUDACodeCache.compile
|
| 340 |
+
|
| 341 |
+
def my_compile(source_code, dst_file_ext):
|
| 342 |
+
self.sources.append(source_code)
|
| 343 |
+
return _compile_method_orig(source_code, dst_file_ext)
|
| 344 |
+
|
| 345 |
+
self._compile_patch = mock.patch(
|
| 346 |
+
"torch._inductor.codecache.CUDACodeCache.compile", my_compile
|
| 347 |
+
)
|
| 348 |
+
return self._compile_patch.__enter__(*args, **kwargs) # type: ignore[union-attr]
|
| 349 |
+
|
| 350 |
+
def __exit__(self, *args, **kwargs):
|
| 351 |
+
return self._compile_patch.__exit__(*args, **kwargs) # type: ignore[union-attr]
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def cuda_standalone_runner_compile_command(srcpath: Path, exepath: Path):
|
| 355 |
+
# returns command string to compile a (captured) CUDA GEMM Kernel source to a standalone executable that's ready to run
|
| 356 |
+
# Passes the correct preprocessor define to nvcc to ensure the standalone runner is enabled.
|
| 357 |
+
from torch._inductor.codecache import cuda_compile_command
|
| 358 |
+
|
| 359 |
+
extra_args = ["-DGENERATE_STANDALONE_RUNNER=1", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]
|
| 360 |
+
compile_command = cuda_compile_command(
|
| 361 |
+
[str(srcpath)], str(exepath), "exe", extra_args=extra_args
|
| 362 |
+
)
|
| 363 |
+
return compile_command
|
vllm/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from ..common import DeviceOpOverrides, register_device_op_overrides
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class CUDADeviceOpOverrides(DeviceOpOverrides):
|
| 6 |
+
def import_get_raw_stream_as(self, name):
|
| 7 |
+
return f"from torch._C import _cuda_getCurrentRawStream as {name}"
|
| 8 |
+
|
| 9 |
+
def set_device(self, device_idx):
|
| 10 |
+
return f"torch.cuda.set_device({device_idx})"
|
| 11 |
+
|
| 12 |
+
def synchronize(self):
|
| 13 |
+
return "torch.cuda.synchronize()"
|
| 14 |
+
|
| 15 |
+
def device_guard(self, device_idx):
|
| 16 |
+
return f"torch.cuda._DeviceGuard({device_idx})"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
register_device_op_overrides("cuda", CUDADeviceOpOverrides())
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (171 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/accelerator_partitioner.cpython-310.pyc
ADDED
|
Binary file (28.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/debug.cpython-310.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/graph_gradual_typechecker.cpython-310.pyc
ADDED
|
Binary file (25.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/meta_tracer.cpython-310.pyc
ADDED
|
Binary file (9.17 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/optimization.cpython-310.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/partitioner_utils.cpython-310.pyc
ADDED
|
Binary file (8.32 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/proxy_tensor.cpython-310.pyc
ADDED
|
Binary file (58.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/refinement_types.cpython-310.pyc
ADDED
|
Binary file (912 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/rewriter.cpython-310.pyc
ADDED
|
Binary file (4.88 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/schema_type_annotation.cpython-310.pyc
ADDED
|
Binary file (4.06 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/_backward_state.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.fx
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BackwardState:
|
| 5 |
+
"""
|
| 6 |
+
BackwardState is used to pass Python hooks from the forwards pass
|
| 7 |
+
into the backwards pass in Dynamo+Compiled Autograd.
|
| 8 |
+
|
| 9 |
+
It is created by TorchDynamo and has special handling there.
|
| 10 |
+
Dynamo will pass an empty BackwardState to the forwards, then populate
|
| 11 |
+
members on it (via setattr) only after the forwards graph is finished.
|
| 12 |
+
Later on, in CompileAutograd we will inline and add the needed guards
|
| 13 |
+
on the BackwardState.
|
| 14 |
+
|
| 15 |
+
BackwardState is identified and has special handling in AOTAutograd.
|
| 16 |
+
During AOTAutograd:
|
| 17 |
+
1) BackwardState is an input to the forwards graph
|
| 18 |
+
2) It must only be used in the backwards
|
| 19 |
+
3) It will be empty in the forwards
|
| 20 |
+
4) In the forwards we add a wrapper to save it
|
| 21 |
+
5) In the backwards it becomes an input
|
| 22 |
+
6) There can only be one per graph
|
| 23 |
+
|
| 24 |
+
BackwardState requires CompiledAutograd.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
proxy: torch.fx.Proxy
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/_config.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# [@compile_ignored: debug] Uses z3 for validating the guard optimizations transformations.
|
| 7 |
+
translation_validation = (
|
| 8 |
+
os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION", "0") == "1"
|
| 9 |
+
)
|
| 10 |
+
# Timeout (in milliseconds) for z3 finding a solution.
|
| 11 |
+
# [@compile_ignored: debug]
|
| 12 |
+
translation_validation_timeout = int(
|
| 13 |
+
os.environ.get("TORCHDYNAMO_TRANSLATION_VALIDATION_TIMEOUT", "600000")
|
| 14 |
+
)
|
| 15 |
+
# Disables bisection for translation validation.
|
| 16 |
+
#
|
| 17 |
+
# Translation validation bisection is enabled by default, if translation validation
|
| 18 |
+
# is also enabled. This should help finding guard simplification issues. However,
|
| 19 |
+
# since validation uses Z3 for bisecting, it might take a lot of time.
|
| 20 |
+
#
|
| 21 |
+
# Set this configuration option so as to avoid bisecting.
|
| 22 |
+
# [@compile_ignored: debug]
|
| 23 |
+
translation_validation_no_bisect = (
|
| 24 |
+
os.environ.get("TORCHDYNAMO_TRANSLATION_NO_BISECT", "0") == "1"
|
| 25 |
+
)
|
| 26 |
+
# Checks whether replaying ShapeEnv events on a freshly constructed one yields
|
| 27 |
+
# the a ShapeEnv with the same state. This should be used only in testing.
|
| 28 |
+
check_shape_env_recorded_events = False
|
| 29 |
+
|
| 30 |
+
# TODO: Perhaps consider allowing unions for the configs below (so you can hit
|
| 31 |
+
# multiple reps at the same time)
|
| 32 |
+
|
| 33 |
+
# Give extended debug information if the string representation of a guard
|
| 34 |
+
# matches this. For example, set this to "Ne(s0, 10)" and whenever we issue
|
| 35 |
+
# this guard, we will generate full Python and C++ backtrace
|
| 36 |
+
# [@compile_ignored: debug]
|
| 37 |
+
extended_debug_guard_added = os.environ.get(
|
| 38 |
+
"TORCHDYNAMO_EXTENDED_DEBUG_GUARD_ADDED", None
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Give extended debug information when a particular symbol is allocated. For
|
| 42 |
+
# example, set this to "u2" and whenever we create this symbol, we will
|
| 43 |
+
# generate full Python and C++ backtrace
|
| 44 |
+
# [@compile_ignored: debug]
|
| 45 |
+
extended_debug_create_symbol = os.environ.get(
|
| 46 |
+
"TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL", None
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Give extended debug information (C++ backtrace) for all extended debug
|
| 50 |
+
# settings as well as errors. The C++ backtrace is slow and very spammy so we
|
| 51 |
+
# don't include it by default even when you're requesting extended debug.
|
| 52 |
+
# [@compile_ignored: debug]
|
| 53 |
+
extended_debug_cpp = os.environ.get("TORCHDYNAMO_EXTENDED_DEBUG_CPP", "") != ""
|
| 54 |
+
|
| 55 |
+
# Give extended debug information (line of code) when a torch function
|
| 56 |
+
# is called during export. This is useful for showing progress and detecting
|
| 57 |
+
# where export might be stuck. Currently only works for strict=False.
|
| 58 |
+
# [@compile_ignored: debug]
|
| 59 |
+
extended_debug_current_loc = (
|
| 60 |
+
os.environ.get("TORCHEXPORT_EXTENDED_DEBUG_CURRENT_LOC", "0") == "1"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# [@compile_ignored: debug] Show a warning for every specialization
|
| 64 |
+
print_specializations = False
|
| 65 |
+
|
| 66 |
+
# wraps (un)equalities with 'Not' class after recording the correct expression
|
| 67 |
+
# in the FX graph. This should incorrectly construct the divisible and replacement
|
| 68 |
+
# lists, and incorrectly issue guards.
|
| 69 |
+
inject_EVALUATE_EXPR_flip_equality_TESTING_ONLY = False
|
| 70 |
+
|
| 71 |
+
# [@compile_ignored: debug] Validate that ShapeEnv's version key is updated correctly
|
| 72 |
+
validate_shape_env_version_key = False
|
| 73 |
+
|
| 74 |
+
# If we produce more than this many guards on a symbol, force the symbol to
|
| 75 |
+
# get specialized and bail out if this many guards mention this particular
|
| 76 |
+
# symbol. This may be slightly more aggressive than the true number of guards
|
| 77 |
+
# issued (as we test if we've hit the limit on-the-fly, whereas we may
|
| 78 |
+
# do further simplifications at final guard issuance time that make guards
|
| 79 |
+
# irrelevant.)
|
| 80 |
+
symbol_guard_limit_before_specialize: Optional[int] = None
|
| 81 |
+
|
| 82 |
+
# This flag changes whether we should use the same symbolic variable to represent input sizes that are the same.
|
| 83 |
+
use_duck_shape = True
|
| 84 |
+
|
| 85 |
+
from torch.utils._config_module import install_config_module
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
install_config_module(sys.modules[__name__])
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/accelerator_partitioner.py
ADDED
|
@@ -0,0 +1,1079 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from collections import deque
|
| 4 |
+
from typing import Dict, List, Set, NamedTuple, Tuple, Deque
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.fx.passes.graph_manipulation import get_size_of_all_nodes
|
| 8 |
+
from torch.fx.experimental.partitioner_utils import (
|
| 9 |
+
Partition,
|
| 10 |
+
Device,
|
| 11 |
+
PartitionerConfig,
|
| 12 |
+
get_partition_to_latency_mapping,
|
| 13 |
+
get_latency_of_partitioned_graph,
|
| 14 |
+
NodeLatency,
|
| 15 |
+
get_extra_size_of,
|
| 16 |
+
PartitionMode,
|
| 17 |
+
)
|
| 18 |
+
from torch.fx.graph_module import GraphModule
|
| 19 |
+
from torch.fx.node import Node, map_arg
|
| 20 |
+
from torch.fx.passes.split_module import split_module
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DAGNode:
|
| 24 |
+
"""DAGNode class maintains useful information for a partition (submodule),
|
| 25 |
+
and its input submodules and output submodules.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
submodule_node: Node,
|
| 31 |
+
input_nodes: List[Node],
|
| 32 |
+
output_nodes: List[Node],
|
| 33 |
+
logical_device_ids: List[int],
|
| 34 |
+
size_bytes: int,
|
| 35 |
+
) -> None:
|
| 36 |
+
self.submodule_node: Node = submodule_node
|
| 37 |
+
self.input_nodes: List[Node] = input_nodes
|
| 38 |
+
self.output_nodes: List[Node] = output_nodes
|
| 39 |
+
self.logical_device_ids: List[int] = logical_device_ids
|
| 40 |
+
self.size_bytes = size_bytes
|
| 41 |
+
|
| 42 |
+
def __str__(self) -> str:
|
| 43 |
+
return str(self.submodule_node)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class DAG:
|
| 47 |
+
"""DAG class contains all the DAG nodes"""
|
| 48 |
+
|
| 49 |
+
def __init__(self) -> None:
|
| 50 |
+
self.nodes: List[DAGNode] = []
|
| 51 |
+
|
| 52 |
+
def create_node(
|
| 53 |
+
self,
|
| 54 |
+
submodule_node: Node,
|
| 55 |
+
input_nodes: List[Node],
|
| 56 |
+
output_nodes: List[Node],
|
| 57 |
+
logical_devices: List[int],
|
| 58 |
+
size_bytes: int,
|
| 59 |
+
) -> None:
|
| 60 |
+
node = DAGNode(
|
| 61 |
+
submodule_node, input_nodes, output_nodes, logical_devices, size_bytes
|
| 62 |
+
)
|
| 63 |
+
self.nodes.append(node)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class PartitionResult(NamedTuple):
|
| 67 |
+
"""NameTuple used for returning DAG and a new fx module"""
|
| 68 |
+
|
| 69 |
+
dag: DAG
|
| 70 |
+
module_with_submodules: GraphModule
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
"""Followings are some helper functions for partition manipulation"""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def reset_partition_device(partitions):
|
| 77 |
+
for partition in partitions:
|
| 78 |
+
partition.logical_device_ids = []
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def combine_two_partitions(
|
| 82 |
+
partition_0: Partition, partition_1: Partition, partitions: List[Partition]
|
| 83 |
+
) -> None:
|
| 84 |
+
"""Given a list of partitions and its two partitions,
|
| 85 |
+
combine these two partitions into a new one appending to the partitions
|
| 86 |
+
and remove the previous two partitions from the list of partitions
|
| 87 |
+
"""
|
| 88 |
+
partition = Partition(len(partitions))
|
| 89 |
+
partition.nodes = partition_0.nodes.union(partition_1.nodes)
|
| 90 |
+
partition.recalculate_mem_size()
|
| 91 |
+
partitions.append(partition)
|
| 92 |
+
partitions.remove(partition_0)
|
| 93 |
+
partitions.remove(partition_1)
|
| 94 |
+
reorganize_partitions(partitions)
|
| 95 |
+
return
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def set_parents_and_children(partitions: List[Partition]) -> None:
|
| 99 |
+
"""Given a list of partitions, mark parents and children for each partition"""
|
| 100 |
+
# Go through all nodes in a partition.
|
| 101 |
+
# If a node's user is in other partition,
|
| 102 |
+
# then the other partition is this partition's children.
|
| 103 |
+
# This partition is the other partition's parent
|
| 104 |
+
for partition in partitions:
|
| 105 |
+
partition.children = set()
|
| 106 |
+
partition.parents = set()
|
| 107 |
+
for partition in partitions:
|
| 108 |
+
for node in partition.nodes:
|
| 109 |
+
# For each node in the current partition, find its users
|
| 110 |
+
users = node.users
|
| 111 |
+
for n in users:
|
| 112 |
+
# Find which the partition the user node belongs to.
|
| 113 |
+
# Note that if the node itself is also belongs to that partition,
|
| 114 |
+
# that partition is not the child of the current partition
|
| 115 |
+
for p in partitions:
|
| 116 |
+
if p != partition and n in p.nodes and node not in p.nodes:
|
| 117 |
+
partition.children.add(p)
|
| 118 |
+
p.parents.add(partition)
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def reorganize_partitions(partitions: List[Partition]) -> None:
|
| 123 |
+
"""Given a list of partitions, reorganize partition id,
|
| 124 |
+
its parents and its children for each partition
|
| 125 |
+
"""
|
| 126 |
+
# Rearrange partition ids
|
| 127 |
+
for i, partition in enumerate(partitions):
|
| 128 |
+
partition.partition_id = i
|
| 129 |
+
set_parents_and_children(partitions)
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def get_bfs_level_partition(partitions: List[Partition]) -> None:
|
| 134 |
+
"""Given a list of partitions,
|
| 135 |
+
mark the bfs level for each partition
|
| 136 |
+
"""
|
| 137 |
+
current_level: Set[Partition] = set()
|
| 138 |
+
visited: Set[Partition] = set()
|
| 139 |
+
for partition in partitions:
|
| 140 |
+
# If a partition has no parent, it should be in root level
|
| 141 |
+
if len(partition.parents) == 0:
|
| 142 |
+
current_level.add(partition)
|
| 143 |
+
next_level: Set[Partition] = set()
|
| 144 |
+
level = 0
|
| 145 |
+
# bfs
|
| 146 |
+
while current_level:
|
| 147 |
+
partition = current_level.pop()
|
| 148 |
+
partition.bfs_level = level
|
| 149 |
+
visited.add(partition)
|
| 150 |
+
children = partition.children
|
| 151 |
+
for child in children:
|
| 152 |
+
if child not in next_level:
|
| 153 |
+
next_level.add(child)
|
| 154 |
+
if not current_level:
|
| 155 |
+
current_level = next_level.copy()
|
| 156 |
+
next_level = set()
|
| 157 |
+
level += 1
|
| 158 |
+
return
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def get_node_to_partition_mapping(partitions: List[Partition]) -> Dict[Node, int]:
|
| 162 |
+
"""Given a list of partitions,return node to partition mapping"""
|
| 163 |
+
node_to_partition: Dict[Node, int] = {}
|
| 164 |
+
for partition in partitions:
|
| 165 |
+
for node in partition.nodes:
|
| 166 |
+
node_to_partition[node] = partition.partition_id
|
| 167 |
+
return node_to_partition
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def get_logical_id_to_device(devices: List[Device]) -> Dict[int, Device]:
|
| 171 |
+
"""Get a mapping from device logical ID to Device object."""
|
| 172 |
+
logical_id_to_device: Dict[int, Device] = {}
|
| 173 |
+
for d in devices:
|
| 174 |
+
logical_id_to_device[d.logical_id] = d
|
| 175 |
+
return logical_id_to_device
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def get_device_partition_stats(
|
| 179 |
+
partitions: List[Partition], devices: List[Device]
|
| 180 |
+
) -> Tuple[Dict[Device, List[Partition]], Dict[Device, int], List[Partition]]:
|
| 181 |
+
"""Given a list of partitions and a list of devices, returns:
|
| 182 |
+
1. A mapping from device to partitions on it;
|
| 183 |
+
2. A mapping from device to its remaining memory size;
|
| 184 |
+
3. A list of partitions that do not have a device.
|
| 185 |
+
"""
|
| 186 |
+
# logical id to device
|
| 187 |
+
logical_id_to_device = get_logical_id_to_device(devices)
|
| 188 |
+
# Track partitions on device
|
| 189 |
+
device_to_partitions: Dict[Device, List[Partition]] = {}
|
| 190 |
+
# Track device's left mem size
|
| 191 |
+
device_to_left_mem_bytes: Dict[Device, int] = {}
|
| 192 |
+
for d in devices:
|
| 193 |
+
device_to_partitions[d] = []
|
| 194 |
+
device_to_left_mem_bytes[d] = d.available_mem_bytes
|
| 195 |
+
|
| 196 |
+
# Deal with the partitions that already have a device
|
| 197 |
+
# and also collect all partitions without a device (no_device_partitions)
|
| 198 |
+
no_device_partitions = []
|
| 199 |
+
for partition in partitions:
|
| 200 |
+
if partition.logical_device_ids != []:
|
| 201 |
+
for logical_id in partition.logical_device_ids:
|
| 202 |
+
device = logical_id_to_device[logical_id]
|
| 203 |
+
device_to_partitions[device].append(partition)
|
| 204 |
+
device_to_left_mem_bytes[device] -= partition.used_mem_bytes
|
| 205 |
+
else:
|
| 206 |
+
no_device_partitions.append(partition)
|
| 207 |
+
|
| 208 |
+
return (
|
| 209 |
+
device_to_partitions,
|
| 210 |
+
device_to_left_mem_bytes,
|
| 211 |
+
no_device_partitions,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def get_device_to_partitions_mapping(
|
| 216 |
+
partitions: List[Partition], devices: List[Device]
|
| 217 |
+
):
|
| 218 |
+
"""Given a list of partitions and a list of devices,
|
| 219 |
+
map each partition into a device.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
def calculate_extra_mem_bytes_needed_for(
|
| 223 |
+
partition: Partition, partitions: List[Partition]
|
| 224 |
+
):
|
| 225 |
+
all_nodes: Set[Node] = set()
|
| 226 |
+
for p in partitions:
|
| 227 |
+
all_nodes = all_nodes.union(p.nodes)
|
| 228 |
+
if len(all_nodes) == 0:
|
| 229 |
+
return partition.used_mem_bytes
|
| 230 |
+
all_nodes = all_nodes.union(partition.nodes)
|
| 231 |
+
extra_size_needed = 0
|
| 232 |
+
for node in partition.nodes:
|
| 233 |
+
extra_size_needed += get_extra_size_of(node, all_nodes)
|
| 234 |
+
return extra_size_needed
|
| 235 |
+
|
| 236 |
+
def find_device_for(partition: Partition):
|
| 237 |
+
"""Given a partition, find a logical device for the partition
|
| 238 |
+
The algorithm is to put the partition on the device
|
| 239 |
+
that has just enough mem left for that partition.
|
| 240 |
+
device_to_left_mem_bytes is a dictionary between device and its left mem size
|
| 241 |
+
sorted by its left mem size
|
| 242 |
+
"""
|
| 243 |
+
for d in device_to_left_mem_bytes:
|
| 244 |
+
extra_size_needed = calculate_extra_mem_bytes_needed_for(
|
| 245 |
+
partition, device_to_partitions[d]
|
| 246 |
+
)
|
| 247 |
+
if extra_size_needed < device_to_left_mem_bytes[d]:
|
| 248 |
+
device_to_partitions[d].append(partition)
|
| 249 |
+
partition.logical_device_ids.append(d.logical_id)
|
| 250 |
+
device_to_left_mem_bytes[d] -= extra_size_needed
|
| 251 |
+
return True
|
| 252 |
+
return False
|
| 253 |
+
|
| 254 |
+
(
|
| 255 |
+
device_to_partitions,
|
| 256 |
+
device_to_left_mem_bytes,
|
| 257 |
+
no_device_partitions,
|
| 258 |
+
) = get_device_partition_stats(partitions, devices)
|
| 259 |
+
|
| 260 |
+
# Find devices for all the partitions without a device
|
| 261 |
+
found_device = True
|
| 262 |
+
for partition in no_device_partitions:
|
| 263 |
+
device_to_left_mem_bytes = dict(sorted(device_to_left_mem_bytes.items(), key=operator.itemgetter(1)))
|
| 264 |
+
found_device = find_device_for(partition)
|
| 265 |
+
if not found_device:
|
| 266 |
+
break
|
| 267 |
+
return found_device
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def check_dependency(partition):
|
| 271 |
+
"""Given a partition,check if there is a circular dependency on
|
| 272 |
+
this partition using bfs
|
| 273 |
+
"""
|
| 274 |
+
visited: Set[Partition] = {partition}
|
| 275 |
+
queue: Deque[Partition] = deque([partition])
|
| 276 |
+
while queue:
|
| 277 |
+
p = queue.popleft()
|
| 278 |
+
for child in p.children:
|
| 279 |
+
if child == partition:
|
| 280 |
+
return True
|
| 281 |
+
else:
|
| 282 |
+
if child not in visited:
|
| 283 |
+
visited.add(child)
|
| 284 |
+
queue.append(child)
|
| 285 |
+
return False
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class Partitioner:
|
| 289 |
+
"""A fx module may not fit into one device.
|
| 290 |
+
Partitioner class helps partition one fx module into submodules (partitions),
|
| 291 |
+
so that the submodules can be executed crossing different accelerators.
|
| 292 |
+
The main function of this class is self.partition_graph.
|
| 293 |
+
It partitions the fx module based on the scheme specified in partition_config
|
| 294 |
+
A DAG structure is returned
|
| 295 |
+
along with a new fx module with submodule nodes.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(self) -> None:
|
| 299 |
+
self.partitions: List[Partition] = []
|
| 300 |
+
self.node_to_partition: Dict[Node, int] = {}
|
| 301 |
+
self.devices: List[Device] = []
|
| 302 |
+
|
| 303 |
+
def partition_graph(
|
| 304 |
+
self,
|
| 305 |
+
fx_module: GraphModule,
|
| 306 |
+
torch_module: torch.nn.Module,
|
| 307 |
+
partitioner_config: PartitionerConfig,
|
| 308 |
+
) -> PartitionResult:
|
| 309 |
+
"""Given the fx module, torch module and partitioner_config,
|
| 310 |
+
find the partitions, do the partitions,
|
| 311 |
+
and then return a DAG and a new fx module with submodule nodes (partitions)
|
| 312 |
+
"""
|
| 313 |
+
self.graph_module = fx_module
|
| 314 |
+
self.torch_module = torch_module
|
| 315 |
+
self.devices = partitioner_config.devices
|
| 316 |
+
if len(self.devices) == 0:
|
| 317 |
+
raise RuntimeError("No devices")
|
| 318 |
+
# Tag the size in bytes to all nodes in the graph_module.
|
| 319 |
+
get_size_of_all_nodes(self.graph_module)
|
| 320 |
+
# Check if there are op nodes in the fx module
|
| 321 |
+
nodes = self.graph_module.graph.nodes
|
| 322 |
+
if all(node.op in {"placeholder", "get_attr", "output"} for node in nodes):
|
| 323 |
+
raise RuntimeError("No Partition since no operations in the module")
|
| 324 |
+
# Calculate total size of the fx module
|
| 325 |
+
total_size_of_graph = 0
|
| 326 |
+
for node in nodes:
|
| 327 |
+
if node.op == "output":
|
| 328 |
+
break
|
| 329 |
+
total_size_of_graph += node.size_bytes.total_size
|
| 330 |
+
# Find the device with the max mem size
|
| 331 |
+
device_with_max_mem = max(self.devices, key=lambda d: d.available_mem_bytes)
|
| 332 |
+
# AOT based partition
|
| 333 |
+
if partitioner_config.mode == PartitionMode.aot_based:
|
| 334 |
+
self.aot_based_partition(
|
| 335 |
+
partitioner_config.node_to_partition_mapping,
|
| 336 |
+
partitioner_config.partition_to_logical_device_mapping,
|
| 337 |
+
)
|
| 338 |
+
# Single partition if the whole module can be fit into one device
|
| 339 |
+
elif total_size_of_graph <= device_with_max_mem.available_mem_bytes:
|
| 340 |
+
self.find_single_partition(
|
| 341 |
+
total_size_of_graph, logical_device_id=device_with_max_mem.logical_id
|
| 342 |
+
)
|
| 343 |
+
elif total_size_of_graph > sum(d.available_mem_bytes for d in self.devices):
|
| 344 |
+
raise RuntimeError("Devices have no enough memory for the module")
|
| 345 |
+
else:
|
| 346 |
+
# Sparse nn based partition
|
| 347 |
+
if partitioner_config.mode == PartitionMode.sparse_nn:
|
| 348 |
+
available_mem_bytes = self.devices[0].available_mem_bytes
|
| 349 |
+
if not all(
|
| 350 |
+
device.available_mem_bytes == available_mem_bytes
|
| 351 |
+
for device in self.devices
|
| 352 |
+
):
|
| 353 |
+
raise RuntimeError("All devices must have same memory size!")
|
| 354 |
+
# sparse_nn_partition only support same memory size
|
| 355 |
+
# TODO: add different size support for sparse_nn_partition
|
| 356 |
+
self.sparse_nn_partition(available_mem_bytes)
|
| 357 |
+
# Cost aware partition
|
| 358 |
+
elif partitioner_config.mode == PartitionMode.cost_aware:
|
| 359 |
+
self.cost_aware_partition(
|
| 360 |
+
partitioner_config.transfer_rate_bytes_per_sec,
|
| 361 |
+
partitioner_config.node_to_latency_mapping,
|
| 362 |
+
)
|
| 363 |
+
# KL based partition
|
| 364 |
+
elif partitioner_config.mode == PartitionMode.kl_based:
|
| 365 |
+
self.kl_based_partition(
|
| 366 |
+
partitioner_config.transfer_rate_bytes_per_sec,
|
| 367 |
+
partitioner_config.node_to_latency_mapping,
|
| 368 |
+
)
|
| 369 |
+
else:
|
| 370 |
+
self.size_based_partition()
|
| 371 |
+
|
| 372 |
+
# Saturate host if possible.
|
| 373 |
+
if partitioner_config.saturate_host:
|
| 374 |
+
self.saturate_host()
|
| 375 |
+
|
| 376 |
+
# Partition the graph module based on the partition assignment.
|
| 377 |
+
module_with_submodules = self.do_partition()
|
| 378 |
+
|
| 379 |
+
# The DAG contains DAGNodes with info of each partition's input nodes, output nodes
|
| 380 |
+
# and how partitions are connected.
|
| 381 |
+
dag = self.dump_dag(module_with_submodules)
|
| 382 |
+
ret = PartitionResult(dag, module_with_submodules)
|
| 383 |
+
return ret
|
| 384 |
+
|
| 385 |
+
def find_single_partition(
|
| 386 |
+
self, total_size_of_graph, logical_device_id: int = 0
|
| 387 |
+
) -> None:
|
| 388 |
+
"""Fit the whole fx module into one device"""
|
| 389 |
+
partition_0 = self.create_partition()
|
| 390 |
+
for node in self.graph_module.graph.nodes:
|
| 391 |
+
if node.op == "output":
|
| 392 |
+
# Skip the output node, but there can
|
| 393 |
+
# be nodes after the output in certain cases.
|
| 394 |
+
continue
|
| 395 |
+
partition_0.nodes.add(node)
|
| 396 |
+
partition_0.used_mem_bytes = total_size_of_graph
|
| 397 |
+
partition_0.logical_device_ids = [logical_device_id]
|
| 398 |
+
# Get the node to partition mapping
|
| 399 |
+
self.node_to_partition = get_node_to_partition_mapping(self.partitions)
|
| 400 |
+
return
|
| 401 |
+
|
| 402 |
+
def size_based_partition(self) -> None:
|
| 403 |
+
"""This method is to partition the fx module based on memory size.
|
| 404 |
+
It uses greedy approach. The result may not be the best.
|
| 405 |
+
The basic idea is:
|
| 406 |
+
Step 1:
|
| 407 |
+
Find a device which has enough memory to fit the current node, create a empty partition
|
| 408 |
+
with the size of that device.
|
| 409 |
+
Then keep adding the following nodes into the partition until the partition is full.
|
| 410 |
+
Step 2:
|
| 411 |
+
Repeat Step 1 until no device left
|
| 412 |
+
Step 3:
|
| 413 |
+
If some nodes are left, create a partition for each left node (single node partition).
|
| 414 |
+
and then try to map those partitions into logical devices with enough mem left.
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
def find_device_based_on_size(node) -> Device:
|
| 418 |
+
"""Given a node, this function is to find a logical device
|
| 419 |
+
that could fit the node.
|
| 420 |
+
"""
|
| 421 |
+
mem_size_needed = get_extra_size_of(node, set())
|
| 422 |
+
device = Device("", -1, -1)
|
| 423 |
+
for d in self.devices:
|
| 424 |
+
if (
|
| 425 |
+
d not in occupied_devices
|
| 426 |
+
and d.available_mem_bytes >= mem_size_needed
|
| 427 |
+
):
|
| 428 |
+
device = d
|
| 429 |
+
break
|
| 430 |
+
if device.available_mem_bytes < 0:
|
| 431 |
+
raise RuntimeError(str(node) + "is too large to fit any device")
|
| 432 |
+
occupied_devices.append(device)
|
| 433 |
+
return device
|
| 434 |
+
|
| 435 |
+
# Track partition and its left mem size
|
| 436 |
+
partition_to_left_mem_bytes: Dict[Partition, int] = {}
|
| 437 |
+
# Track all the devices that have been used
|
| 438 |
+
occupied_devices: List[Device] = []
|
| 439 |
+
partition = self.create_partition()
|
| 440 |
+
for node in self.graph_module.graph.nodes:
|
| 441 |
+
if node.op in {"call_module", "call_method", "call_function"}:
|
| 442 |
+
# Check if there are devices left
|
| 443 |
+
if len(self.partitions) <= len(self.devices):
|
| 444 |
+
total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
|
| 445 |
+
# Check if the current partition is the very first partition
|
| 446 |
+
if partition.used_mem_bytes == 0:
|
| 447 |
+
# Find a device to fit the first node, return available mem size
|
| 448 |
+
device = find_device_based_on_size(node)
|
| 449 |
+
occupied_devices.append(device)
|
| 450 |
+
# Update partition and its left mem size
|
| 451 |
+
partition_to_left_mem_bytes[
|
| 452 |
+
partition
|
| 453 |
+
] = device.available_mem_bytes
|
| 454 |
+
# Update available mem for the current partition
|
| 455 |
+
partition.logical_device_ids.append(device.logical_id)
|
| 456 |
+
else:
|
| 457 |
+
# The current partition is not the first partition
|
| 458 |
+
# Check if the current node can fit into current partition
|
| 459 |
+
if (
|
| 460 |
+
partition_to_left_mem_bytes[partition]
|
| 461 |
+
< total_size_of_input_nodes
|
| 462 |
+
):
|
| 463 |
+
# Check if no device is left
|
| 464 |
+
if len(self.partitions) == len(self.devices):
|
| 465 |
+
# No device is left
|
| 466 |
+
# Put the previous partitions into a list (non_single_node_partitions)
|
| 467 |
+
non_single_node_partitions = self.partitions[:]
|
| 468 |
+
# Create the first single node partition for the current node
|
| 469 |
+
self.create_single_node_partition(node)
|
| 470 |
+
continue
|
| 471 |
+
# Some devices are still left
|
| 472 |
+
# Create a new partition with a mem size that is enough for the current node
|
| 473 |
+
device = find_device_based_on_size(node)
|
| 474 |
+
partition = self.create_partition()
|
| 475 |
+
total_size_of_input_nodes = get_extra_size_of(
|
| 476 |
+
node, partition.nodes
|
| 477 |
+
)
|
| 478 |
+
partition_to_left_mem_bytes[
|
| 479 |
+
partition
|
| 480 |
+
] = device.available_mem_bytes
|
| 481 |
+
partition.logical_device_ids.append(device.logical_id)
|
| 482 |
+
partition.add_node(node)
|
| 483 |
+
partition_to_left_mem_bytes[partition] -= total_size_of_input_nodes
|
| 484 |
+
# Create single node partitions if no device is left
|
| 485 |
+
else:
|
| 486 |
+
self.create_single_node_partition(node)
|
| 487 |
+
reorganize_partitions(self.partitions)
|
| 488 |
+
# Get the node to partition mapping
|
| 489 |
+
self.node_to_partition = get_node_to_partition_mapping(self.partitions)
|
| 490 |
+
# Mapping all partitions into device
|
| 491 |
+
found_partition_to_device_mapping = get_device_to_partitions_mapping(
|
| 492 |
+
self.partitions, self.devices
|
| 493 |
+
)
|
| 494 |
+
if not found_partition_to_device_mapping:
|
| 495 |
+
raise RuntimeError("Cannot Get a Valid Partition to Logical Device Mapping")
|
| 496 |
+
return
|
| 497 |
+
|
| 498 |
+
def saturate_host(self) -> None:
|
| 499 |
+
"""Saturate host by assigning replicates to unused devices with enough memory.
|
| 500 |
+
It uses a greedy approach to find a next available set of devices to place all split
|
| 501 |
+
partitions: For each used device, it searches for an idle device with minimal memory
|
| 502 |
+
size that can hold all the partition located on that device; If the search is successful
|
| 503 |
+
for all used devices, it then assigns the new devices' logical ID to the corresponding
|
| 504 |
+
partition.
|
| 505 |
+
"""
|
| 506 |
+
(
|
| 507 |
+
device_to_partitions,
|
| 508 |
+
device_to_left_mem_bytes,
|
| 509 |
+
no_device_partitions,
|
| 510 |
+
) = get_device_partition_stats(self.partitions, self.devices)
|
| 511 |
+
|
| 512 |
+
assert (
|
| 513 |
+
len(no_device_partitions) == 0
|
| 514 |
+
), f"Expect no_device_partitions has 0 device, but get {len(no_device_partitions)}"
|
| 515 |
+
|
| 516 |
+
# Devices that hold partitions
|
| 517 |
+
used_devices = [d for d in self.devices if len(device_to_partitions[d]) > 0]
|
| 518 |
+
# Track replicates of the assigned devices
|
| 519 |
+
replicated_device_to_used_device: Dict[Device, Device] = {}
|
| 520 |
+
|
| 521 |
+
while len(used_devices) * 2 + len(replicated_device_to_used_device) <= len(
|
| 522 |
+
self.devices
|
| 523 |
+
):
|
| 524 |
+
# Success flag for this round
|
| 525 |
+
success = True
|
| 526 |
+
# Devices that have not been assigned
|
| 527 |
+
idle_devices = [
|
| 528 |
+
d
|
| 529 |
+
for d in self.devices
|
| 530 |
+
if d not in used_devices and d not in replicated_device_to_used_device
|
| 531 |
+
]
|
| 532 |
+
# Temporary mapping from replicated device to original device
|
| 533 |
+
temp_replicate_mapping = {}
|
| 534 |
+
|
| 535 |
+
# Find a new device to replicate all partitions on an used device
|
| 536 |
+
for used_device in used_devices:
|
| 537 |
+
# Idle devices that have enough memory
|
| 538 |
+
available_devices = [
|
| 539 |
+
d
|
| 540 |
+
for d in idle_devices
|
| 541 |
+
if d.available_mem_bytes
|
| 542 |
+
>= used_device.available_mem_bytes
|
| 543 |
+
- device_to_left_mem_bytes[used_device]
|
| 544 |
+
]
|
| 545 |
+
if len(available_devices) == 0:
|
| 546 |
+
success = False
|
| 547 |
+
break
|
| 548 |
+
new_device = min(available_devices, key=lambda d: d.available_mem_bytes)
|
| 549 |
+
idle_devices.remove(new_device)
|
| 550 |
+
temp_replicate_mapping[new_device] = used_device
|
| 551 |
+
|
| 552 |
+
if not success:
|
| 553 |
+
break
|
| 554 |
+
replicated_device_to_used_device.update(temp_replicate_mapping)
|
| 555 |
+
|
| 556 |
+
# Update logical device IDs assigned to the partitions
|
| 557 |
+
for (
|
| 558 |
+
replicate_device,
|
| 559 |
+
original_device,
|
| 560 |
+
) in replicated_device_to_used_device.items():
|
| 561 |
+
logical_id = replicate_device.logical_id
|
| 562 |
+
for partition in device_to_partitions[original_device]:
|
| 563 |
+
partition.logical_device_ids.append(logical_id)
|
| 564 |
+
for p in self.partitions:
|
| 565 |
+
print(p.logical_device_ids)
|
| 566 |
+
|
| 567 |
+
def do_partition(self) -> GraphModule:
|
| 568 |
+
"""Return a new fx module with submodule nodes (partitions)."""
|
| 569 |
+
module_with_submodules = split_module(
|
| 570 |
+
self.graph_module,
|
| 571 |
+
self.torch_module,
|
| 572 |
+
lambda node: self.node_to_partition[node],
|
| 573 |
+
)
|
| 574 |
+
return module_with_submodules
|
| 575 |
+
|
| 576 |
+
def dump_dag(self, module_with_submodules: GraphModule) -> DAG:
|
| 577 |
+
"""Return the dag structure and the new fx module with submodules."""
|
| 578 |
+
dag = DAG()
|
| 579 |
+
for node in module_with_submodules.graph.nodes:
|
| 580 |
+
if node.op == "output":
|
| 581 |
+
break
|
| 582 |
+
if node.op in {"placeholder", "get_attr"}:
|
| 583 |
+
continue
|
| 584 |
+
if node.target == operator.__getitem__:
|
| 585 |
+
continue
|
| 586 |
+
input_nodes: Dict[Node, None] = {}
|
| 587 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 588 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 589 |
+
# When a node has two or more output nodes,
|
| 590 |
+
# it outputs its result to 'getitem' nodes.
|
| 591 |
+
# Those 'getitem' nodes are the output node for this node.
|
| 592 |
+
# Otherwise, the output node is this node itself.
|
| 593 |
+
if len(node.users) > 1:
|
| 594 |
+
output_nodes = list(node.users)
|
| 595 |
+
else:
|
| 596 |
+
output_nodes = [node]
|
| 597 |
+
partition_id = int(node.name.rsplit("_", 1)[-1])
|
| 598 |
+
device_ids = self.partitions[partition_id].logical_device_ids
|
| 599 |
+
size_bytes = self.partitions[partition_id].used_mem_bytes
|
| 600 |
+
dag.create_node(
|
| 601 |
+
node, list(input_nodes), output_nodes, device_ids, size_bytes
|
| 602 |
+
)
|
| 603 |
+
return dag
|
| 604 |
+
|
| 605 |
+
def create_partition(self) -> Partition:
|
| 606 |
+
"""Create a partition and append it to self.partitions."""
|
| 607 |
+
partition_id = len(self.partitions)
|
| 608 |
+
partition = Partition(partition_id)
|
| 609 |
+
self.partitions.append(partition)
|
| 610 |
+
return partition
|
| 611 |
+
|
| 612 |
+
def create_single_node_partition(self, node):
|
| 613 |
+
"""Create a partition for a single node"""
|
| 614 |
+
partition = self.create_partition()
|
| 615 |
+
partition.add_node(node)
|
| 616 |
+
return
|
| 617 |
+
|
| 618 |
+
def sparse_nn_partition(self, available_mem_bytes: int) -> None:
|
| 619 |
+
"""This method partition a sparse nn module.
|
| 620 |
+
It is size based partition but different from size_based_partition,
|
| 621 |
+
it only works when all the devices have same memory size (available_mem_bytes).
|
| 622 |
+
In the future, devices with different mem sizes will be supported like size_based_partition.
|
| 623 |
+
It first traverse all the nodes and do the partitions based on the same memory size.
|
| 624 |
+
If the current partition has no enough memory left for a new op node
|
| 625 |
+
(call_module, call_method, call_function), a new partition is created.
|
| 626 |
+
When crossing the boundary between non-embedding nodes and embedding nodes,
|
| 627 |
+
a new partition is created regardlessly.
|
| 628 |
+
For example, if the current node is a non-embedding node but the next node is an
|
| 629 |
+
embedding node, a new partition is created for the next node.
|
| 630 |
+
After the partition, the partitions are combined as much as possible.
|
| 631 |
+
The rule is that a non-embedding partition only
|
| 632 |
+
combines with another non-embedding one.
|
| 633 |
+
So as the embedding partitions.
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
def combine_partitions_based_on_size(
|
| 637 |
+
partitions: List[Partition], available_mem_bytes: int
|
| 638 |
+
) -> None:
|
| 639 |
+
"""Combining small partitions together to keep as less partitions as possible.
|
| 640 |
+
Here is an example of the algorithm to do this:
|
| 641 |
+
Assume some partitions, we first sort them based on partition used memory size.
|
| 642 |
+
[(partition_4, 1), (partition_3, 1), (partition_2, 2), (partition_1, 7), (partition_0, 9)]
|
| 643 |
+
The available memory is 10.
|
| 644 |
+
step 1: self.find_partition_to_combine_based_on_size()
|
| 645 |
+
First, mark bfs level for each partition
|
| 646 |
+
Second, look the smallest partition, partition_4: 10 - 1 = 9
|
| 647 |
+
It means any partition has a used memory equal or less than 9 could combine this partition
|
| 648 |
+
We go from the largest and selection partition_0.
|
| 649 |
+
Check the bfs level for two partitions, if the level difference is less than 2,
|
| 650 |
+
it can be combined.
|
| 651 |
+
step 2: repeat step 1 until no partitions can be combined
|
| 652 |
+
"""
|
| 653 |
+
find_combination = True
|
| 654 |
+
while find_combination:
|
| 655 |
+
# Sort partitions based on memory size
|
| 656 |
+
sorted_partitions = sorted(partitions, key=lambda p: p.used_mem_bytes)
|
| 657 |
+
# Mark bfs level
|
| 658 |
+
get_bfs_level_partition(self.partitions)
|
| 659 |
+
find_combination, partitions = find_partition_to_combine_based_on_size(
|
| 660 |
+
sorted_partitions, available_mem_bytes, partitions
|
| 661 |
+
)
|
| 662 |
+
return
|
| 663 |
+
|
| 664 |
+
def calculate_mem_bytes_needed(p1, p2):
|
| 665 |
+
"""Given two partitions, calculate how many mem bytes
|
| 666 |
+
are needed if two partitions are combined
|
| 667 |
+
"""
|
| 668 |
+
nodes = p1.nodes.union(p2.nodes)
|
| 669 |
+
mem_bytes_needed = 0
|
| 670 |
+
for node in nodes:
|
| 671 |
+
mem_bytes_needed += get_extra_size_of(node, nodes)
|
| 672 |
+
return mem_bytes_needed
|
| 673 |
+
|
| 674 |
+
def find_partition_to_combine_based_on_size(
|
| 675 |
+
sorted_partitions: List[Partition],
|
| 676 |
+
available_mem_bytes: int,
|
| 677 |
+
partitions: List[Partition],
|
| 678 |
+
) -> Tuple[bool, List[Partition]]:
|
| 679 |
+
"""step 1 in combine_partition_based_on_size()"""
|
| 680 |
+
find_combination = False
|
| 681 |
+
smallest_partition = sorted_partitions.pop(0)
|
| 682 |
+
for p in sorted_partitions[::-1]:
|
| 683 |
+
if abs(smallest_partition.bfs_level - p.bfs_level) <= 1:
|
| 684 |
+
# Calculate how many bytes needed if combined
|
| 685 |
+
mem_bytes_needed = calculate_mem_bytes_needed(p, smallest_partition)
|
| 686 |
+
if mem_bytes_needed <= available_mem_bytes:
|
| 687 |
+
combine_two_partitions(p, smallest_partition, self.partitions)
|
| 688 |
+
partitions.remove(smallest_partition)
|
| 689 |
+
partitions.remove(p)
|
| 690 |
+
partitions.append(self.partitions[-1])
|
| 691 |
+
find_combination = True
|
| 692 |
+
break
|
| 693 |
+
return find_combination, partitions
|
| 694 |
+
|
| 695 |
+
def reset_partition_in_sparse_nn(partition, new_partition=True):
|
| 696 |
+
"""If crossing the boundary between non-embedding nodes and
|
| 697 |
+
embedding nodes, create a new partition
|
| 698 |
+
"""
|
| 699 |
+
if in_embedding_region:
|
| 700 |
+
embedding_partitions.append(partition)
|
| 701 |
+
else:
|
| 702 |
+
non_embedding_partitions.append(partition)
|
| 703 |
+
if new_partition:
|
| 704 |
+
partition = self.create_partition()
|
| 705 |
+
partition.left_mem_bytes = available_mem_bytes
|
| 706 |
+
return partition
|
| 707 |
+
return None
|
| 708 |
+
|
| 709 |
+
def is_embedding_node(node: Node) -> bool:
|
| 710 |
+
"""Check if a node is an embedding node"""
|
| 711 |
+
if node.op == "call_module":
|
| 712 |
+
submodule = self.graph_module
|
| 713 |
+
for atom in str(node.target).split("."):
|
| 714 |
+
if not hasattr(submodule, atom):
|
| 715 |
+
raise RuntimeError(
|
| 716 |
+
f"Module {submodule} has no attribute {atom}"
|
| 717 |
+
)
|
| 718 |
+
submodule = getattr(submodule, atom)
|
| 719 |
+
if "Embedding" in str(submodule):
|
| 720 |
+
return True
|
| 721 |
+
return False
|
| 722 |
+
|
| 723 |
+
# Track embedding partitions and non-embedding partitions separately
|
| 724 |
+
embedding_partitions: List[Partition] = []
|
| 725 |
+
non_embedding_partitions: List[Partition] = []
|
| 726 |
+
# A Flag to check the boundary
|
| 727 |
+
in_embedding_region: bool = False
|
| 728 |
+
partition = self.create_partition()
|
| 729 |
+
for node in self.graph_module.graph.nodes:
|
| 730 |
+
if node.op in {"call_module", "call_method", "call_function"}:
|
| 731 |
+
# Check if crossing the boundary between embedding nodes and non embedding nodes
|
| 732 |
+
if is_embedding_node(node) != in_embedding_region:
|
| 733 |
+
# Crossing the boundary
|
| 734 |
+
# Check if the current partition is an empty partition
|
| 735 |
+
if partition.used_mem_bytes != 0:
|
| 736 |
+
# The current partition isn't an empty partition. Create a new one.
|
| 737 |
+
partition = reset_partition_in_sparse_nn(partition)
|
| 738 |
+
in_embedding_region = not in_embedding_region
|
| 739 |
+
total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
|
| 740 |
+
if (
|
| 741 |
+
total_size_of_input_nodes + partition.used_mem_bytes
|
| 742 |
+
> available_mem_bytes
|
| 743 |
+
):
|
| 744 |
+
partition = reset_partition_in_sparse_nn(partition)
|
| 745 |
+
total_size_of_input_nodes = get_extra_size_of(node, partition.nodes)
|
| 746 |
+
if total_size_of_input_nodes > available_mem_bytes:
|
| 747 |
+
raise RuntimeError(
|
| 748 |
+
node.target + "is too large to fit into a device"
|
| 749 |
+
)
|
| 750 |
+
partition.add_node(node)
|
| 751 |
+
reset_partition_in_sparse_nn(partition, new_partition=False)
|
| 752 |
+
# Set parents and children for partitions
|
| 753 |
+
set_parents_and_children(self.partitions)
|
| 754 |
+
# Combining non-embedding partitions
|
| 755 |
+
combine_partitions_based_on_size(non_embedding_partitions, available_mem_bytes)
|
| 756 |
+
# Combining embedding partitions
|
| 757 |
+
combine_partitions_based_on_size(embedding_partitions, available_mem_bytes)
|
| 758 |
+
total_size_of_non_embedding_partitions = 0
|
| 759 |
+
for partition in non_embedding_partitions:
|
| 760 |
+
total_size_of_non_embedding_partitions += partition.used_mem_bytes
|
| 761 |
+
# Check if devices are enough for all partitions
|
| 762 |
+
if len(embedding_partitions) > len(self.devices):
|
| 763 |
+
msg = (
|
| 764 |
+
"Need "
|
| 765 |
+
+ str(len(embedding_partitions))
|
| 766 |
+
+ " devices, but only "
|
| 767 |
+
+ str(len(self.devices))
|
| 768 |
+
+ " provided"
|
| 769 |
+
)
|
| 770 |
+
raise RuntimeError(msg)
|
| 771 |
+
occupied_devices = []
|
| 772 |
+
for i, partition in enumerate(embedding_partitions):
|
| 773 |
+
# Check if all non-embedding partitions can fit into embedding partition devices
|
| 774 |
+
if (
|
| 775 |
+
total_size_of_non_embedding_partitions + partition.used_mem_bytes
|
| 776 |
+
> available_mem_bytes
|
| 777 |
+
):
|
| 778 |
+
raise RuntimeError(
|
| 779 |
+
"partition_"
|
| 780 |
+
+ str(partition.partition_id)
|
| 781 |
+
+ "(embedding partition) and non embedding partitions can not fit into one device"
|
| 782 |
+
)
|
| 783 |
+
else:
|
| 784 |
+
# Add logical device to the partition
|
| 785 |
+
partition.logical_device_ids = [self.devices[i].logical_id]
|
| 786 |
+
occupied_devices.append(self.devices[i].logical_id)
|
| 787 |
+
# Add logical devices to the non_embedding_partitions
|
| 788 |
+
for partition in non_embedding_partitions:
|
| 789 |
+
partition.logical_device_ids = occupied_devices
|
| 790 |
+
# Get the node to partition mapping
|
| 791 |
+
self.node_to_partition = get_node_to_partition_mapping(self.partitions)
|
| 792 |
+
return
|
| 793 |
+
|
| 794 |
+
def cost_aware_partition(
|
| 795 |
+
self,
|
| 796 |
+
transfer_rate_bytes_per_sec: float,
|
| 797 |
+
node_to_latency_mapping: Dict[Node, NodeLatency],
|
| 798 |
+
) -> None:
|
| 799 |
+
"""This method is to partition the fx module based on the cost.
|
| 800 |
+
The cost is the total latency of running the whole fx module.
|
| 801 |
+
In partitioner_utils.py, the cost model is built.
|
| 802 |
+
The cost aware partition algorithm is:
|
| 803 |
+
#1. At every beginning, each node is a partition.
|
| 804 |
+
Then we map all the partitions to the devices
|
| 805 |
+
and calculate the cost
|
| 806 |
+
#2. Then try to pre-combine any two of the partitions if the two
|
| 807 |
+
partitions can be combined.
|
| 808 |
+
(the bfs level is less than 2 or two partitions are connected and
|
| 809 |
+
can find partition to device mapping)
|
| 810 |
+
See if any partition pair could reduce the current cost.
|
| 811 |
+
Choose the pair that shows the minimum cost and then combine them
|
| 812 |
+
#3. Repeat #2 until the cost cannot be reduced.
|
| 813 |
+
"""
|
| 814 |
+
|
| 815 |
+
def try_combining_partitions(p0_index, p1_index, partitions) -> float:
|
| 816 |
+
"""Given two partitions and a list of partitions, combine these two partitions
|
| 817 |
+
and see what is the cost of the modified partition list
|
| 818 |
+
"""
|
| 819 |
+
p0 = partitions[p0_index]
|
| 820 |
+
p1 = partitions[p1_index]
|
| 821 |
+
"""If two partitions' bfs level are less than 2 or two partitions are connected to each other,
|
| 822 |
+
then they can be combined
|
| 823 |
+
"""
|
| 824 |
+
if (
|
| 825 |
+
(abs(p0.bfs_level - p1.bfs_level) <= 1)
|
| 826 |
+
or (p0 in p1.parents)
|
| 827 |
+
or p0 in (p1.children)
|
| 828 |
+
):
|
| 829 |
+
combine_two_partitions(p0, p1, partitions)
|
| 830 |
+
# Check if a circular dependency exists after combining
|
| 831 |
+
if check_dependency(partitions[-1]):
|
| 832 |
+
return float("inf")
|
| 833 |
+
# Check if the modified partition list can be mapped to devices after combination
|
| 834 |
+
reset_partition_device(partitions)
|
| 835 |
+
found_deivce = get_device_to_partitions_mapping(
|
| 836 |
+
partitions, self.devices
|
| 837 |
+
)
|
| 838 |
+
if not found_deivce:
|
| 839 |
+
return float("inf")
|
| 840 |
+
# Calculate the new cost
|
| 841 |
+
partition_to_latency_mapping = get_partition_to_latency_mapping(
|
| 842 |
+
partitions, node_to_latency_mapping
|
| 843 |
+
)
|
| 844 |
+
cost = get_latency_of_partitioned_graph(
|
| 845 |
+
partitions,
|
| 846 |
+
partition_to_latency_mapping,
|
| 847 |
+
transfer_rate_bytes_per_sec,
|
| 848 |
+
)
|
| 849 |
+
return cost
|
| 850 |
+
# If two partition can not be combined, the cost is inf
|
| 851 |
+
return float("inf")
|
| 852 |
+
|
| 853 |
+
def search_combination(
|
| 854 |
+
transfer_rate_bytes_per_sec, node_to_latency_mapping
|
| 855 |
+
) -> bool:
|
| 856 |
+
"""Given transfer rate between partitions and each node's latency,
|
| 857 |
+
find two partitions to combine so the cost of the partitions can
|
| 858 |
+
be reduced.
|
| 859 |
+
The algorithm is :
|
| 860 |
+
1. Go through all the partition pairs and see
|
| 861 |
+
if any pair of partitions can be combined.
|
| 862 |
+
2. Calculate the cost after the combination.
|
| 863 |
+
3. Select the minimum cost and combine its corresponding partition pair.
|
| 864 |
+
"""
|
| 865 |
+
partition_to_latency_mapping = get_partition_to_latency_mapping(
|
| 866 |
+
self.partitions, node_to_latency_mapping
|
| 867 |
+
)
|
| 868 |
+
cost = get_latency_of_partitioned_graph(
|
| 869 |
+
self.partitions,
|
| 870 |
+
partition_to_latency_mapping,
|
| 871 |
+
transfer_rate_bytes_per_sec,
|
| 872 |
+
)
|
| 873 |
+
if len(self.partitions) == 1:
|
| 874 |
+
return False
|
| 875 |
+
partition_pair: List[int] = []
|
| 876 |
+
for i in range(len(self.partitions) - 1):
|
| 877 |
+
for j in range(i + 1, len(self.partitions)):
|
| 878 |
+
# Try to combine the partition pair
|
| 879 |
+
# and see the new cost after combination
|
| 880 |
+
new_cost = try_combining_partitions(i, j, self.partitions[:])
|
| 881 |
+
if new_cost <= cost:
|
| 882 |
+
partition_pair = [i, j]
|
| 883 |
+
cost = new_cost
|
| 884 |
+
reorganize_partitions(self.partitions)
|
| 885 |
+
# If a partition pair is found, combine them
|
| 886 |
+
if len(partition_pair) != 0:
|
| 887 |
+
p0 = self.partitions[partition_pair[0]]
|
| 888 |
+
p1 = self.partitions[partition_pair[1]]
|
| 889 |
+
combine_two_partitions(p0, p1, self.partitions)
|
| 890 |
+
get_bfs_level_partition(self.partitions)
|
| 891 |
+
reset_partition_device(self.partitions)
|
| 892 |
+
get_device_to_partitions_mapping(self.partitions, self.devices)
|
| 893 |
+
return len(partition_pair) != 0
|
| 894 |
+
|
| 895 |
+
for node in self.graph_module.graph.nodes:
|
| 896 |
+
if node.op not in {"placeholder", "get_attr", "output"}:
|
| 897 |
+
self.create_single_node_partition(node)
|
| 898 |
+
# Set up parent partitions and children partitions for each partition
|
| 899 |
+
set_parents_and_children(self.partitions)
|
| 900 |
+
# Get bfs level for each partition
|
| 901 |
+
get_bfs_level_partition(self.partitions)
|
| 902 |
+
find_combination = True
|
| 903 |
+
while find_combination:
|
| 904 |
+
# Search for a pair partition to generate the minimum new cost,
|
| 905 |
+
# then combine them
|
| 906 |
+
find_combination = search_combination(
|
| 907 |
+
transfer_rate_bytes_per_sec, node_to_latency_mapping
|
| 908 |
+
)
|
| 909 |
+
# Make sure all partitions are set up correctly
|
| 910 |
+
reorganize_partitions(self.partitions)
|
| 911 |
+
# Set up node to partition mapping
|
| 912 |
+
self.node_to_partition = get_node_to_partition_mapping(self.partitions)
|
| 913 |
+
return
|
| 914 |
+
|
| 915 |
+
def kl_based_partition(
|
| 916 |
+
self,
|
| 917 |
+
transfer_rate_bytes_per_sec: float,
|
| 918 |
+
node_to_latency_mapping: Dict[Node, NodeLatency],
|
| 919 |
+
) -> None:
|
| 920 |
+
"""This function is a cost aware partition based
|
| 921 |
+
on Kernighan-Lin algorithm.
|
| 922 |
+
First, the graph is partitioned using size_based_partition.
|
| 923 |
+
Then, each node is swapped with any other node in a different
|
| 924 |
+
partition, and at the same time, the cost is estimated after
|
| 925 |
+
the swapping.
|
| 926 |
+
For example, we have nodes n0, n1, n2, n3 and n4.
|
| 927 |
+
Using size_based_partition, n0 and n1 are in Partition p0.
|
| 928 |
+
n2, n3 and n4 in Partition p1. The current cost is estimated.
|
| 929 |
+
We first tried using n0 to swap with n2 from the other partition.
|
| 930 |
+
Then we see that swapping n0 and n2 shows a lower cost
|
| 931 |
+
than the current cost and it is the minimum among other pairs like
|
| 932 |
+
(n0, None)(This means moving n0 to Partition without swapping other nodes),
|
| 933 |
+
(n0, n3) and (n0, n4). We swap n0 and n2 and set the new cost
|
| 934 |
+
as the current cost.
|
| 935 |
+
Then We repeat this process for all the other nodes until all swapping pairs
|
| 936 |
+
are tried.
|
| 937 |
+
"""
|
| 938 |
+
|
| 939 |
+
def swap_nodes(n0, n1, p0, p1):
|
| 940 |
+
# Either n0 or n1 could be None
|
| 941 |
+
# That means we simply move the node
|
| 942 |
+
# to another partition
|
| 943 |
+
if n0 is not None:
|
| 944 |
+
p0.remove_node(n0)
|
| 945 |
+
p1.add_node(n0)
|
| 946 |
+
if n1 is not None:
|
| 947 |
+
p0.add_node(n1)
|
| 948 |
+
p1.remove_node(n1)
|
| 949 |
+
|
| 950 |
+
def try_swap_nodes(
|
| 951 |
+
n0, n1, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
|
| 952 |
+
):
|
| 953 |
+
cost = float("inf")
|
| 954 |
+
swap_nodes(n0, n1, p0, p1)
|
| 955 |
+
# Reorganize partitions after swapping
|
| 956 |
+
reorganize_partitions(self.partitions)
|
| 957 |
+
# Check if there is a circular dependency after swapping
|
| 958 |
+
if (not check_dependency(p0)) and (not check_dependency(p1)):
|
| 959 |
+
reset_partition_device(self.partitions)
|
| 960 |
+
partition_to_latency_mapping = get_partition_to_latency_mapping(
|
| 961 |
+
self.partitions, node_to_latency_mapping
|
| 962 |
+
)
|
| 963 |
+
# Check if all partitions can be mapped to logical devices after swapping
|
| 964 |
+
found_device = get_device_to_partitions_mapping(
|
| 965 |
+
self.partitions, self.devices
|
| 966 |
+
)
|
| 967 |
+
if not found_device:
|
| 968 |
+
cost = float("inf")
|
| 969 |
+
else:
|
| 970 |
+
cost = get_latency_of_partitioned_graph(
|
| 971 |
+
self.partitions,
|
| 972 |
+
partition_to_latency_mapping,
|
| 973 |
+
transfer_rate_bytes_per_sec,
|
| 974 |
+
)
|
| 975 |
+
# Swap back and reset all partitions back to original
|
| 976 |
+
swap_nodes(n1, n0, p0, p1)
|
| 977 |
+
reorganize_partitions(self.partitions)
|
| 978 |
+
reset_partition_device(self.partitions)
|
| 979 |
+
get_device_to_partitions_mapping(self.partitions, self.devices)
|
| 980 |
+
return cost
|
| 981 |
+
|
| 982 |
+
def swap_node_to_partition(
|
| 983 |
+
node, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
|
| 984 |
+
):
|
| 985 |
+
"""This function helps to swap one node from partition p0
|
| 986 |
+
with all the nodes in another partition p1
|
| 987 |
+
"""
|
| 988 |
+
p1_nodes = list(p1.nodes) + [None]
|
| 989 |
+
min_cost = float("inf")
|
| 990 |
+
node_pair: List[Node] = []
|
| 991 |
+
for n1 in p1_nodes:
|
| 992 |
+
# Ignore the node if it is not a op node
|
| 993 |
+
if n1 is not None and n1.op in {"placeholder", "get_attr"}:
|
| 994 |
+
continue
|
| 995 |
+
# Try swapping node in p0 with n1 in p1
|
| 996 |
+
cost = try_swap_nodes(
|
| 997 |
+
node, n1, p0, p1, node_to_latency_mapping, transfer_rate_per_sec
|
| 998 |
+
)
|
| 999 |
+
if cost < min_cost:
|
| 1000 |
+
node_pair = [node, n1]
|
| 1001 |
+
min_cost = cost
|
| 1002 |
+
return cost, node_pair # type: ignore[possibly-undefined]
|
| 1003 |
+
|
| 1004 |
+
# First use size_base_partition
|
| 1005 |
+
self.size_based_partition()
|
| 1006 |
+
partition_to_latency_mapping = get_partition_to_latency_mapping(
|
| 1007 |
+
self.partitions, node_to_latency_mapping
|
| 1008 |
+
)
|
| 1009 |
+
# Calculate the cost of the partitions
|
| 1010 |
+
cost = get_latency_of_partitioned_graph(
|
| 1011 |
+
self.partitions, partition_to_latency_mapping, transfer_rate_bytes_per_sec
|
| 1012 |
+
)
|
| 1013 |
+
# Keep tracking the node pair that shows the better cost
|
| 1014 |
+
node_pair: List[Node] = []
|
| 1015 |
+
# Keep tracking the partition pair of node pair
|
| 1016 |
+
partition_pair: List[Partition] = []
|
| 1017 |
+
# Collect all the op nodes from the graph
|
| 1018 |
+
op_nodes = []
|
| 1019 |
+
for n in self.graph_module.graph.nodes:
|
| 1020 |
+
if n.op not in {"placeholder", "get_attr", "output"}:
|
| 1021 |
+
op_nodes.append(n)
|
| 1022 |
+
for node in op_nodes:
|
| 1023 |
+
# Find which partition the current node belongs
|
| 1024 |
+
p0_index = self.node_to_partition[node]
|
| 1025 |
+
p0 = self.partitions[p0_index]
|
| 1026 |
+
# Go through all the other partitions to swap
|
| 1027 |
+
# with other nodes from those partitions
|
| 1028 |
+
for p1_index, _ in enumerate(self.partitions):
|
| 1029 |
+
if p0_index != p1_index:
|
| 1030 |
+
p1 = self.partitions[p1_index]
|
| 1031 |
+
new_cost, new_node_pair = swap_node_to_partition(
|
| 1032 |
+
node,
|
| 1033 |
+
p0,
|
| 1034 |
+
p1,
|
| 1035 |
+
node_to_latency_mapping,
|
| 1036 |
+
transfer_rate_bytes_per_sec,
|
| 1037 |
+
)
|
| 1038 |
+
# Update the cost
|
| 1039 |
+
# Track the swapped node pair and their partitions
|
| 1040 |
+
if new_cost < cost:
|
| 1041 |
+
cost = new_cost
|
| 1042 |
+
node_pair = new_node_pair
|
| 1043 |
+
partition_pair = [p0, p1]
|
| 1044 |
+
# Do the swapping after trying all the nodes from a partition
|
| 1045 |
+
if len(node_pair) != 0:
|
| 1046 |
+
swap_nodes(
|
| 1047 |
+
node_pair[0], node_pair[1], partition_pair[0], partition_pair[1]
|
| 1048 |
+
)
|
| 1049 |
+
reorganize_partitions(self.partitions)
|
| 1050 |
+
get_device_to_partitions_mapping(self.partitions, self.devices)
|
| 1051 |
+
reorganize_partitions(self.partitions)
|
| 1052 |
+
# Mapping the device to the partition
|
| 1053 |
+
get_device_to_partitions_mapping(self.partitions, self.devices)
|
| 1054 |
+
return
|
| 1055 |
+
|
| 1056 |
+
def aot_based_partition(
|
| 1057 |
+
self, node_to_partition_mapping, partition_to_logical_device_mapping
|
| 1058 |
+
):
|
| 1059 |
+
"""This function helps to rebuild the partitions given the nodes and its
|
| 1060 |
+
corresponding partition id
|
| 1061 |
+
"""
|
| 1062 |
+
partition_id_to_partition_mapping: Dict[int, Partition] = {}
|
| 1063 |
+
self.node_to_partition = node_to_partition_mapping
|
| 1064 |
+
for node in self.node_to_partition:
|
| 1065 |
+
partition_id = self.node_to_partition[node]
|
| 1066 |
+
# If the requested partition has not been created, create the partition
|
| 1067 |
+
if partition_id not in partition_id_to_partition_mapping:
|
| 1068 |
+
partition = Partition(partition_id)
|
| 1069 |
+
self.partitions.append(partition)
|
| 1070 |
+
partition_id_to_partition_mapping[partition_id] = partition
|
| 1071 |
+
partition.logical_device_ids = partition_to_logical_device_mapping[
|
| 1072 |
+
partition_id
|
| 1073 |
+
]
|
| 1074 |
+
else:
|
| 1075 |
+
partition = partition_id_to_partition_mapping[
|
| 1076 |
+
self.node_to_partition[node]
|
| 1077 |
+
]
|
| 1078 |
+
# Add the current node into the partition
|
| 1079 |
+
partition.add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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import re
|
| 3 |
+
from typing import Callable, Dict, Optional, Set, Union
|
| 4 |
+
|
| 5 |
+
import torch.fx
|
| 6 |
+
from torch.fx.node import map_arg
|
| 7 |
+
from torch.fx.passes.split_module import split_module
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ['FoldedGraphModule', 'get_unique_attr_name_in_module', 'split_const_subgraphs']
|
| 11 |
+
|
| 12 |
+
class FoldedGraphModule(torch.fx.GraphModule):
|
| 13 |
+
"""
|
| 14 |
+
FoldedGraphModule is a GraphModule which also contains another
|
| 15 |
+
`const_subgraph_module` representing a subgraph which has all const attr
|
| 16 |
+
inputs and which can be run once before running the main standard
|
| 17 |
+
`graph`. The `const_output_names` are the ordered list names of attrs which
|
| 18 |
+
represent what each respective output from the const_subgraph should be set
|
| 19 |
+
on which attrs.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
root: torch.nn.Module,
|
| 25 |
+
graph: torch.fx.Graph,
|
| 26 |
+
const_subgraph: Optional[torch.fx.Graph] = None,
|
| 27 |
+
fx_const_folded_attrs_name: Optional[str] = None,
|
| 28 |
+
device_for_folded_attrs: str = "cuda",
|
| 29 |
+
):
|
| 30 |
+
super().__init__(root, graph)
|
| 31 |
+
self.const_subgraph_module = (
|
| 32 |
+
None
|
| 33 |
+
if const_subgraph is None
|
| 34 |
+
else torch.fx.GraphModule(root, const_subgraph)
|
| 35 |
+
)
|
| 36 |
+
self.has_folding_been_run = False
|
| 37 |
+
self.fx_const_folded_attrs_name = fx_const_folded_attrs_name
|
| 38 |
+
self.device_for_folded_attrs = device_for_folded_attrs
|
| 39 |
+
|
| 40 |
+
def __call__(self, *args, **kwargs):
|
| 41 |
+
if not self.has_folding_been_run:
|
| 42 |
+
self.run_folding()
|
| 43 |
+
return super().__call__(*args)
|
| 44 |
+
|
| 45 |
+
def run_folding(self):
|
| 46 |
+
# If there's no const subgraph module or attr output names to use, return
|
| 47 |
+
# early as there is no const folding to perform.
|
| 48 |
+
if (
|
| 49 |
+
self.const_subgraph_module is None
|
| 50 |
+
or self.fx_const_folded_attrs_name is None
|
| 51 |
+
):
|
| 52 |
+
return
|
| 53 |
+
|
| 54 |
+
assert not self.has_folding_been_run
|
| 55 |
+
self.has_folding_been_run = True
|
| 56 |
+
|
| 57 |
+
# Actually run const folding subgraph. Note that single attr const fold
|
| 58 |
+
# subgraphs output a single Tensor while multiple outputs are returned as
|
| 59 |
+
# Tuple[Tensor,].
|
| 60 |
+
folded_attrs = self.const_subgraph_module()
|
| 61 |
+
|
| 62 |
+
def _create_param(i):
|
| 63 |
+
return torch.nn.Parameter(
|
| 64 |
+
i.detach().clone()
|
| 65 |
+
if not isinstance(i, int)
|
| 66 |
+
else torch.Tensor([i]).to(device=self.device_for_folded_attrs),
|
| 67 |
+
requires_grad=i.requires_grad if isinstance(i, torch.Tensor) else False,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
params = (
|
| 71 |
+
torch.nn.ParameterList([_create_param(i) for i in folded_attrs])
|
| 72 |
+
if isinstance(folded_attrs, tuple)
|
| 73 |
+
else _create_param(folded_attrs)
|
| 74 |
+
)
|
| 75 |
+
setattr(self, self.fx_const_folded_attrs_name, params)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _inline_module(gm: torch.fx.GraphModule, inline_mod_name: str):
|
| 79 |
+
"""
|
| 80 |
+
Given `gm` and some graph module which is called with target name `inline_mod_name`,
|
| 81 |
+
this helper will inline all of the nodes from that called graph module into `gm`.
|
| 82 |
+
"""
|
| 83 |
+
# Fetch the inner graph module that we want to inline inside `gm`.
|
| 84 |
+
inline_mod = dict(gm.named_modules())[inline_mod_name]
|
| 85 |
+
assert isinstance(inline_mod, torch.fx.GraphModule)
|
| 86 |
+
call_mod_node_to_replace = None
|
| 87 |
+
for node in gm.graph.nodes:
|
| 88 |
+
if node.op == "call_module" and node.target == inline_mod_name:
|
| 89 |
+
call_mod_node_to_replace = node
|
| 90 |
+
break
|
| 91 |
+
assert call_mod_node_to_replace is not None
|
| 92 |
+
|
| 93 |
+
# Now actually do the swap. Note that we have to keep track of new nodes that are
|
| 94 |
+
# copied into `gm` -- we do this via replacement_mapping.
|
| 95 |
+
call_mod_args = call_mod_node_to_replace.args
|
| 96 |
+
replacement_mapping: Dict[torch.fx.Node, torch.fx.Node] = {}
|
| 97 |
+
ph_count = 0
|
| 98 |
+
|
| 99 |
+
def replacement_fn(node):
|
| 100 |
+
new_node = replacement_mapping[node]
|
| 101 |
+
new_node.meta = node.meta.copy()
|
| 102 |
+
return new_node
|
| 103 |
+
|
| 104 |
+
for inline_node in inline_mod.graph.nodes:
|
| 105 |
+
if inline_node.op == "placeholder":
|
| 106 |
+
replacement_mapping[inline_node] = call_mod_args[ph_count]
|
| 107 |
+
ph_count += 1
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
if inline_node.op == "output":
|
| 111 |
+
outputs = inline_node.args[0]
|
| 112 |
+
output_replacements = map_arg(outputs, replacement_fn)
|
| 113 |
+
call_mod_node_to_replace.replace_all_uses_with(output_replacements)
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
with gm.graph.inserting_before(call_mod_node_to_replace):
|
| 117 |
+
new_node = gm.graph.node_copy(inline_node, replacement_fn)
|
| 118 |
+
replacement_mapping[inline_node] = new_node
|
| 119 |
+
|
| 120 |
+
gm.graph.eliminate_dead_code()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_unique_attr_name_in_module(mod_traced: torch.fx.GraphModule, name: str) -> str:
|
| 124 |
+
"""
|
| 125 |
+
Make sure the name is unique (in a module) and can represents an attr.
|
| 126 |
+
"""
|
| 127 |
+
# Delete all characters that are illegal in a Python identifier.
|
| 128 |
+
name = re.sub("[^0-9a-zA-Z_]+", "_", name)
|
| 129 |
+
if name[0].isdigit():
|
| 130 |
+
name = f"_{name}"
|
| 131 |
+
# Now make sure it is in fact unique to the module by incrementing suffix value.
|
| 132 |
+
while hasattr(mod_traced, name):
|
| 133 |
+
match = re.match(r"(.*)_(\d+)$", name)
|
| 134 |
+
if match is None:
|
| 135 |
+
name = name + "_1"
|
| 136 |
+
else:
|
| 137 |
+
base, num = match.group(1, 2)
|
| 138 |
+
name = f"{base}_{int(num) + 1}"
|
| 139 |
+
|
| 140 |
+
return name
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def split_const_subgraphs(
|
| 144 |
+
module: Union[torch.nn.Module, torch.fx.GraphModule],
|
| 145 |
+
skip_folding_node_fn: Optional[Callable[[torch.fx.Node], bool]] = None,
|
| 146 |
+
device_for_folded_attrs: str = "cpu",
|
| 147 |
+
) -> FoldedGraphModule:
|
| 148 |
+
"""
|
| 149 |
+
Looks through `module` for any nodes that have all constant attribute inputs
|
| 150 |
+
and separates them out into their own constant subgraph, and returns a
|
| 151 |
+
FoldedGraphModule which runs that constant subgraph on the first run to set
|
| 152 |
+
attributes on the module prior to running the non-constant portion of the
|
| 153 |
+
graph.
|
| 154 |
+
"""
|
| 155 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 156 |
+
mod_traced = torch.fx.symbolic_trace(module)
|
| 157 |
+
else:
|
| 158 |
+
mod_traced = module
|
| 159 |
+
|
| 160 |
+
# Build up a list of const_nodes, defined as nodes that are themselves
|
| 161 |
+
# get_attrs, or have all get_attr or other constant node inputs.
|
| 162 |
+
const_nodes: Set[torch.fx.Node] = set()
|
| 163 |
+
found_const_folding = False
|
| 164 |
+
for node in mod_traced.graph.nodes:
|
| 165 |
+
# Skip over placeholders/outputs because they can't be const folded and
|
| 166 |
+
# we don't want to add tags to them.
|
| 167 |
+
if node.op in {"placeholder", "output"}:
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
# If the node itself is constant, or all of its inputs are constant,
|
| 171 |
+
# then tag it as constant.
|
| 172 |
+
if node.op != "get_attr" and not set(node.all_input_nodes).issubset(
|
| 173 |
+
const_nodes
|
| 174 |
+
):
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
# If provided skip folding function says to skip, then skip.
|
| 178 |
+
if skip_folding_node_fn and skip_folding_node_fn(node):
|
| 179 |
+
continue
|
| 180 |
+
|
| 181 |
+
# Skip folding side-effectful functions
|
| 182 |
+
if node.is_impure():
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
# Must be a constant foldable node at this point.
|
| 186 |
+
const_nodes.add(node)
|
| 187 |
+
if node.op != "get_attr":
|
| 188 |
+
found_const_folding = True
|
| 189 |
+
|
| 190 |
+
# If we did not find any const folding then return early without a const fold subgraph.
|
| 191 |
+
if not found_const_folding:
|
| 192 |
+
return FoldedGraphModule(mod_traced, mod_traced.graph)
|
| 193 |
+
|
| 194 |
+
# Partition the module into two: submod_0 for constant folding subgraph, and
|
| 195 |
+
# submod_1 for the rest.
|
| 196 |
+
def mod_partition(node: torch.fx.Node):
|
| 197 |
+
return 0 if node in const_nodes else 1
|
| 198 |
+
|
| 199 |
+
split = split_module(mod_traced, module, mod_partition)
|
| 200 |
+
|
| 201 |
+
const_mod_name, non_const_mod_name = "submod_0", "submod_1"
|
| 202 |
+
# Safely get submod_1 in case there are no non-const nodes
|
| 203 |
+
const_gm, non_const_gm = split.submod_0, getattr(split, non_const_mod_name, None)
|
| 204 |
+
|
| 205 |
+
# The module that a call_module node refers to gets copied to submodules during split.
|
| 206 |
+
# The path to the module also gets inlined, i.e. mod.a.b -> mod_a_b. Here we need to
|
| 207 |
+
# attach inlined modules to `split` as it's the owning module now.
|
| 208 |
+
for node in non_const_gm.graph.nodes if non_const_gm else []:
|
| 209 |
+
if node.op == "call_module":
|
| 210 |
+
setattr(split, node.target, getattr(non_const_gm, node.target))
|
| 211 |
+
for node in const_gm.graph.nodes:
|
| 212 |
+
if node.op == "call_module":
|
| 213 |
+
setattr(split, node.target, getattr(const_gm, node.target))
|
| 214 |
+
|
| 215 |
+
# split_module currently does not use get_attrs for attrs. Instead it passes
|
| 216 |
+
# them in as args from the parent module, which used get_attrs. Here we set
|
| 217 |
+
# them as get_attrs inside const_gm, allowing for running folding without
|
| 218 |
+
# somehow a priori knowing the attrs that should be passed as args. We can
|
| 219 |
+
# unconditionally do this for all placeholders because we know all
|
| 220 |
+
# placeholders to const_gm must be constants accessible via get_attr.
|
| 221 |
+
call_const_gm_args = None
|
| 222 |
+
for node in split.graph.nodes:
|
| 223 |
+
if node.op == "call_module":
|
| 224 |
+
if node.target == const_mod_name:
|
| 225 |
+
call_const_gm_args = node.args
|
| 226 |
+
break
|
| 227 |
+
assert call_const_gm_args is not None
|
| 228 |
+
|
| 229 |
+
# Here we do the actual replacement of placeholders to get_attrs. Note that here we
|
| 230 |
+
# set the const_gm.graph into a new root_const_gm with split as the root module,
|
| 231 |
+
# because we are fetching attributes directly from the root module, instead of
|
| 232 |
+
# fetching them from const_gm. Example: The const_gm must have some format like:
|
| 233 |
+
# graph():
|
| 234 |
+
# %inp : [num_users=1] = placeholder[target=const_inp]
|
| 235 |
+
# %add : [num_users=1] = call_function[target=operator.add](args = (%inp, %inp), kwargs = {})
|
| 236 |
+
# return add
|
| 237 |
+
# We replace that with the following, which does not have any placeholders:
|
| 238 |
+
# graph():
|
| 239 |
+
# %inp_1 : [num_users=1] = get_attr[target=const_inp]
|
| 240 |
+
# %add : [num_users=1] = call_function[target=operator.add](args = (%inp_1, %inp_1), kwargs = {})
|
| 241 |
+
# return add
|
| 242 |
+
root_const_gm = torch.fx.GraphModule(split, const_gm.graph)
|
| 243 |
+
for node in root_const_gm.graph.nodes:
|
| 244 |
+
if node.op == "output":
|
| 245 |
+
multiple_outputs = isinstance(node.args[0], tuple)
|
| 246 |
+
continue
|
| 247 |
+
if node.op != "placeholder":
|
| 248 |
+
continue
|
| 249 |
+
in_node = next(n for n in call_const_gm_args if n.name == node.target)
|
| 250 |
+
assert in_node.op == "get_attr"
|
| 251 |
+
with root_const_gm.graph.inserting_before(node):
|
| 252 |
+
new_node = root_const_gm.graph.get_attr(in_node.target)
|
| 253 |
+
new_node.meta = node.meta.copy()
|
| 254 |
+
node.replace_all_uses_with(new_node)
|
| 255 |
+
root_const_gm.graph.erase_node(node)
|
| 256 |
+
assert "multiple_outputs" in locals()
|
| 257 |
+
|
| 258 |
+
# Now find the call to const_gm inside split, and replace it with a getattr to the
|
| 259 |
+
# folded tensor(s) that result from constant folding. Note that we don't need to
|
| 260 |
+
# worry about whether this is one or more tensors because the original graph
|
| 261 |
+
# correctly uses getitem to extract individual tensors if there are multiple folded.
|
| 262 |
+
fx_const_folded_attrs_name = get_unique_attr_name_in_module(
|
| 263 |
+
mod_traced, "_FX_CONST_FOLDED_ATTRS"
|
| 264 |
+
)
|
| 265 |
+
setattr(
|
| 266 |
+
split,
|
| 267 |
+
fx_const_folded_attrs_name,
|
| 268 |
+
torch.nn.ParameterList() if multiple_outputs else torch.nn.Parameter(), # type: ignore[possibly-undefined]
|
| 269 |
+
)
|
| 270 |
+
for node in split.graph.nodes:
|
| 271 |
+
if node.op == "call_module" and node.target == const_mod_name:
|
| 272 |
+
with node.graph.inserting_before(node):
|
| 273 |
+
folded_attrs = node.graph.get_attr(fx_const_folded_attrs_name)
|
| 274 |
+
folded_attrs.meta = node.meta.copy()
|
| 275 |
+
node.replace_all_uses_with(folded_attrs)
|
| 276 |
+
break
|
| 277 |
+
|
| 278 |
+
# Finally, inline the non-constant submod (if it exists) into the split submod.
|
| 279 |
+
# This is so that the original caller who may have passed in a graph module will
|
| 280 |
+
# get back out a graph module whose graph is traced to the same granularity.
|
| 281 |
+
if hasattr(split, non_const_mod_name):
|
| 282 |
+
_inline_module(split, non_const_mod_name)
|
| 283 |
+
|
| 284 |
+
split.graph.eliminate_dead_code()
|
| 285 |
+
|
| 286 |
+
return FoldedGraphModule(
|
| 287 |
+
split,
|
| 288 |
+
split.graph,
|
| 289 |
+
root_const_gm.graph,
|
| 290 |
+
fx_const_folded_attrs_name,
|
| 291 |
+
device_for_folded_attrs,
|
| 292 |
+
)
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/debug.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch.fx as fx
|
| 3 |
+
|
| 4 |
+
def set_trace(gm: fx.GraphModule) -> fx.GraphModule:
|
| 5 |
+
"""
|
| 6 |
+
Sets a breakpoint in `gm`'s generated python code. It drops into pdb when
|
| 7 |
+
`gm` gets run.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
gm: graph module to insert breakpoint. It is then recompiled for it to
|
| 11 |
+
take effect.
|
| 12 |
+
|
| 13 |
+
Returns:
|
| 14 |
+
the `gm` with breakpoint inserted.
|
| 15 |
+
"""
|
| 16 |
+
def insert_pdb(body):
|
| 17 |
+
return ["import pdb; pdb.set_trace()\n", *body]
|
| 18 |
+
|
| 19 |
+
with gm.graph.on_generate_code(
|
| 20 |
+
make_transformer=lambda cur_transform: (
|
| 21 |
+
# new code transformer to register
|
| 22 |
+
lambda body: (
|
| 23 |
+
insert_pdb(
|
| 24 |
+
cur_transform(body) if cur_transform
|
| 25 |
+
else body
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
)
|
| 29 |
+
):
|
| 30 |
+
gm.recompile()
|
| 31 |
+
|
| 32 |
+
return gm
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/graph_gradual_typechecker.py
ADDED
|
@@ -0,0 +1,916 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
from functools import reduce
|
| 4 |
+
import torch
|
| 5 |
+
import operator
|
| 6 |
+
from torch.fx.tensor_type import Dyn, is_consistent, TensorType, is_more_precise
|
| 7 |
+
from typing import Callable, Dict
|
| 8 |
+
from torch.fx.node import Target, Node
|
| 9 |
+
from torch.nn.modules.batchnorm import BatchNorm2d
|
| 10 |
+
from torch.nn.modules.conv import Conv2d
|
| 11 |
+
from torch.fx.experimental.refinement_types import Equality
|
| 12 |
+
import itertools
|
| 13 |
+
|
| 14 |
+
from torch.fx.experimental.unification import Var # type: ignore[attr-defined]
|
| 15 |
+
|
| 16 |
+
import sympy
|
| 17 |
+
|
| 18 |
+
_INFERENCE_RULES: Dict[Target, Callable] = {}
|
| 19 |
+
_REFINEMENT_RULES: Dict[Target, Callable] = {}
|
| 20 |
+
_RULES: Dict[Target, Callable] = {}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def expand_to_tensor_dim(t, n):
|
| 24 |
+
"""
|
| 25 |
+
Expand a type to the desired tensor dimension if possible
|
| 26 |
+
Raise an error otherwise.
|
| 27 |
+
- t is the given type
|
| 28 |
+
- n is a number of dimensions to expand to
|
| 29 |
+
"""
|
| 30 |
+
if t == Dyn:
|
| 31 |
+
dims = [Dyn] * n
|
| 32 |
+
return TensorType(tuple(dims))
|
| 33 |
+
elif isinstance(t, TensorType):
|
| 34 |
+
if len(t.__args__) != n:
|
| 35 |
+
raise TypeError(f'Cannot extend tensor. Tensor {t} has rank {len(t.__args__)}. It should have rank {n}')
|
| 36 |
+
return t
|
| 37 |
+
else:
|
| 38 |
+
raise TypeError(f'Cannot match the type {t}')
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def broadcast_types(t1, t2):
|
| 42 |
+
"""
|
| 43 |
+
Applies broadcasting to both given types such that they
|
| 44 |
+
become consistent with eachother and returns two new
|
| 45 |
+
resulting types
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
# if either type is Dyn, do nothing since the types are already consistent
|
| 49 |
+
if t1 == Dyn or t2 == Dyn or isinstance(t1, Var) or isinstance(t2, Var):
|
| 50 |
+
return t1, t2
|
| 51 |
+
|
| 52 |
+
if isinstance(t1, TensorType) and isinstance(t2, TensorType):
|
| 53 |
+
s1 = len(t1.__args__)
|
| 54 |
+
s2 = len(t2.__args__)
|
| 55 |
+
|
| 56 |
+
new_t1 = list(t1.__args__)
|
| 57 |
+
new_t2 = list(t2.__args__)
|
| 58 |
+
|
| 59 |
+
# We make the types the same length which is the first requirement
|
| 60 |
+
# for consistency
|
| 61 |
+
if s1 > s2:
|
| 62 |
+
for i in range(s1 - s2):
|
| 63 |
+
new_t2.insert(0, 1)
|
| 64 |
+
|
| 65 |
+
elif s2 > s1:
|
| 66 |
+
for i in range(s2 - s1):
|
| 67 |
+
new_t1.insert(0, 1)
|
| 68 |
+
|
| 69 |
+
# we replace occurrences of "1" with each tensor with
|
| 70 |
+
# the corresponding type from the other tensor
|
| 71 |
+
for i, (x, y) in enumerate(zip(new_t1, new_t2)):
|
| 72 |
+
if x == 1:
|
| 73 |
+
new_t1[i] = y
|
| 74 |
+
elif y == 1:
|
| 75 |
+
new_t2[i] = x
|
| 76 |
+
|
| 77 |
+
# at this point our tensors should be consistent
|
| 78 |
+
# and we can apply the element-wise operation and find the right dimension
|
| 79 |
+
# for the output of the operation
|
| 80 |
+
(t1, t2) = TensorType(tuple(new_t1)), TensorType(tuple(new_t2))
|
| 81 |
+
return (t1, t2)
|
| 82 |
+
else:
|
| 83 |
+
raise TypeError(f'Cannot broadcast types {t1} and {t2}')
|
| 84 |
+
|
| 85 |
+
def register_inference_rule(call_target):
|
| 86 |
+
def register(fn):
|
| 87 |
+
if call_target in _INFERENCE_RULES:
|
| 88 |
+
raise RuntimeError(f'Inference rule already registered for {call_target}!')
|
| 89 |
+
_INFERENCE_RULES[call_target] = fn
|
| 90 |
+
return fn
|
| 91 |
+
return register
|
| 92 |
+
|
| 93 |
+
def register_refinement_rule(call_target):
|
| 94 |
+
def register(fn):
|
| 95 |
+
if call_target in _REFINEMENT_RULES:
|
| 96 |
+
raise RuntimeError(f'Refinement rule already registered for {call_target}!')
|
| 97 |
+
_REFINEMENT_RULES[call_target] = fn
|
| 98 |
+
return fn
|
| 99 |
+
return register
|
| 100 |
+
|
| 101 |
+
def register_algebraic_expressions_inference_rule(call_target):
|
| 102 |
+
def register(fn):
|
| 103 |
+
if call_target in _RULES:
|
| 104 |
+
raise RuntimeError(f'Rule already registered for {call_target}!')
|
| 105 |
+
_RULES[call_target] = fn
|
| 106 |
+
return fn
|
| 107 |
+
return register
|
| 108 |
+
|
| 109 |
+
@register_inference_rule(torch.add)
|
| 110 |
+
@register_inference_rule(operator.add)
|
| 111 |
+
def add_inference_rule(n: Node):
|
| 112 |
+
"""
|
| 113 |
+
Apply the addition inference rule. This includes:
|
| 114 |
+
- scalar addition
|
| 115 |
+
- broadcasting semantics
|
| 116 |
+
|
| 117 |
+
Note that we always return the least precise type between
|
| 118 |
+
the operands (after applying broadcasting) to be the final type of the operation
|
| 119 |
+
|
| 120 |
+
Note that we do not modify the operand types themselves after applying broadcasting
|
| 121 |
+
to them. We only use them to calculate the final type
|
| 122 |
+
"""
|
| 123 |
+
assert isinstance(n.args[0], Node)
|
| 124 |
+
assert isinstance(n.args[1], Node)
|
| 125 |
+
t1 = n.args[0].type
|
| 126 |
+
t2 = n.args[1].type
|
| 127 |
+
|
| 128 |
+
# handle scalar addition
|
| 129 |
+
if t1 == int and isinstance(t2, TensorType):
|
| 130 |
+
n.type = t2
|
| 131 |
+
return n.type
|
| 132 |
+
|
| 133 |
+
# handle scalar addition
|
| 134 |
+
elif t2 == int and isinstance(t1, TensorType):
|
| 135 |
+
n.type = t1
|
| 136 |
+
return n.type
|
| 137 |
+
|
| 138 |
+
# we bring the new types to the point where
|
| 139 |
+
# we can check for consistency
|
| 140 |
+
# any inconsistency would not have been caused
|
| 141 |
+
# by broadcasting at this point
|
| 142 |
+
(new_t1, new_t2) = broadcast_types(t1, t2)
|
| 143 |
+
|
| 144 |
+
if new_t1 != t1 or new_t2 != t2:
|
| 145 |
+
n.meta['broadcast'] = True
|
| 146 |
+
n.meta[str(n.args[0])] = new_t1
|
| 147 |
+
n.meta[str(n.args[1])] = new_t2
|
| 148 |
+
|
| 149 |
+
else:
|
| 150 |
+
n.meta['broadcast'] = False
|
| 151 |
+
|
| 152 |
+
new_t1 = t1 if not n.meta['broadcast'] else new_t1
|
| 153 |
+
new_t2 = t2 if not n.meta['broadcast'] else new_t2
|
| 154 |
+
|
| 155 |
+
# we check for consistency between the new types
|
| 156 |
+
if is_consistent(new_t1, new_t2):
|
| 157 |
+
# we return the less precise type because
|
| 158 |
+
# broadcasting may have happened
|
| 159 |
+
# for operands with shape [1,2,Dyn] and [1,2,1]
|
| 160 |
+
# we have to assign the node [1,2,Dyn]
|
| 161 |
+
if is_more_precise(new_t1, new_t2):
|
| 162 |
+
n.type = new_t2
|
| 163 |
+
else:
|
| 164 |
+
n.type = new_t1
|
| 165 |
+
return n.type
|
| 166 |
+
else:
|
| 167 |
+
raise TypeError(f'Cannot add arguments {n.args[0]} ({ n.args[0].type}) and {n.args[1]} ({ n.args[1].type}) in node {n}.'
|
| 168 |
+
f' Types should match ')
|
| 169 |
+
|
| 170 |
+
@register_inference_rule(getattr)
|
| 171 |
+
def get_attr_inference_rule(n: Node, traced):
|
| 172 |
+
"""
|
| 173 |
+
The current getattr rule only handles the shape attribute
|
| 174 |
+
Can be extended to other attributes
|
| 175 |
+
The most representitive type we have is "Dyn" but the system
|
| 176 |
+
can be extended with more types, such as a type to represent shapes
|
| 177 |
+
"""
|
| 178 |
+
attr_node = n.args[0]
|
| 179 |
+
attr_name = n.args[1]
|
| 180 |
+
|
| 181 |
+
if attr_name == "shape":
|
| 182 |
+
n.type = Dyn
|
| 183 |
+
else:
|
| 184 |
+
raise TypeError("Not yet implemented")
|
| 185 |
+
|
| 186 |
+
# TODO. We leave it like this till we add a type to represent tensor sizes
|
| 187 |
+
return n.type
|
| 188 |
+
|
| 189 |
+
@register_inference_rule(torch.transpose)
|
| 190 |
+
def transpose_inference_rule(n: Node):
|
| 191 |
+
"""
|
| 192 |
+
We check that dimensions for the transpose operations
|
| 193 |
+
are within range of the tensor type of the node
|
| 194 |
+
"""
|
| 195 |
+
if n.target == torch.transpose:
|
| 196 |
+
assert isinstance(n.args[0], Node)
|
| 197 |
+
t = n.args[0].type
|
| 198 |
+
|
| 199 |
+
assert isinstance(n.args[1], int)
|
| 200 |
+
assert isinstance(n.args[2], int)
|
| 201 |
+
dim1, dim2 = n.args[1], n.args[2]
|
| 202 |
+
|
| 203 |
+
if t == Dyn:
|
| 204 |
+
n.type = Dyn
|
| 205 |
+
return n.type
|
| 206 |
+
|
| 207 |
+
elif isinstance(t, TensorType):
|
| 208 |
+
if 0 <= dim1 < len(t.__args__) and 0 <= dim2 < len(t.__args__):
|
| 209 |
+
new_type = list(t.__args__)
|
| 210 |
+
new_type[dim1], new_type[dim2] = new_type[dim2], new_type[dim1]
|
| 211 |
+
final = TensorType(new_type)
|
| 212 |
+
n.type = get_greatest_upper_bound(n.type, final)
|
| 213 |
+
return n.type
|
| 214 |
+
else:
|
| 215 |
+
raise TypeError(f'Cannot transpose {dim1} and {dim2} in type {t} for node {n}')
|
| 216 |
+
else:
|
| 217 |
+
raise TypeError(f'Cannot transpose {dim1} and {dim2} in type {t} for node {n}')
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@register_inference_rule(torch.reshape)
|
| 221 |
+
def reshape_inference_rule(n: Node):
|
| 222 |
+
"""
|
| 223 |
+
Without dynamism, the rule checks that the
|
| 224 |
+
product of the elements of the argument tensor
|
| 225 |
+
type is equal to the product of the elements
|
| 226 |
+
of the required shape. We gradualize this rule
|
| 227 |
+
by adding a case to handle fully dynamic input
|
| 228 |
+
as well as input where some of the tensor dimensions
|
| 229 |
+
are unknown. In this case we check for divisibility
|
| 230 |
+
"""
|
| 231 |
+
assert isinstance(n.args[0], Node)
|
| 232 |
+
t1 = n.args[0].type
|
| 233 |
+
|
| 234 |
+
assert isinstance(n.args[1], list)
|
| 235 |
+
t2 = n.args[1]
|
| 236 |
+
t2_type = TensorType([Dyn if elem == -1 else elem for elem in t2])
|
| 237 |
+
|
| 238 |
+
# if we do not know the original tensor dimension,
|
| 239 |
+
# we return the required dimension
|
| 240 |
+
if t1 == Dyn:
|
| 241 |
+
n.type = t2_type
|
| 242 |
+
return t2_type
|
| 243 |
+
|
| 244 |
+
# if any of the dimensions are unknown,
|
| 245 |
+
# we check for divisibility
|
| 246 |
+
elif isinstance(t1, TensorType):
|
| 247 |
+
assert isinstance(t1, TensorType)
|
| 248 |
+
a = [e if e != Dyn else 1 for e in t1.__args__]
|
| 249 |
+
p1 = reduce(operator.mul, a)
|
| 250 |
+
p2 = reduce(operator.mul, t2)
|
| 251 |
+
if p1 % p2 == 0 or p2 % p1 == 0:
|
| 252 |
+
n.type = t2_type
|
| 253 |
+
return t2_type
|
| 254 |
+
else:
|
| 255 |
+
raise TypeError(f'Cannot reshape in node {n} from {t1} to {t2_type}')
|
| 256 |
+
else:
|
| 257 |
+
raise TypeError(f'Cannot reshape in node {n} from {t1} to {t2_type}')
|
| 258 |
+
|
| 259 |
+
@register_inference_rule(BatchNorm2d)
|
| 260 |
+
def bn2d_inference_rule(n: Node, module_instance):
|
| 261 |
+
"""
|
| 262 |
+
Given a BatchNorm2D instance and a node check the following conditions:
|
| 263 |
+
- the input type can be expanded to a size 4 tensor: t = (x_1, x_2, x_3, x_4)
|
| 264 |
+
- the current node type can be expanded to a size 4 tensor: t' = (x_1', x_2', x_3', x_4')
|
| 265 |
+
- t is consistent with t'
|
| 266 |
+
- x_2 is consistent with the module's num_features
|
| 267 |
+
- x_2' is consistent with the module's num_features
|
| 268 |
+
output type: the more precise type of t and t'
|
| 269 |
+
"""
|
| 270 |
+
assert isinstance(n.args[0], Node)
|
| 271 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, 4)
|
| 272 |
+
arg_type = n.args[0].type
|
| 273 |
+
n.type = expand_to_tensor_dim(n.type, 4)
|
| 274 |
+
|
| 275 |
+
# we check the conditions on the incoming argument
|
| 276 |
+
# and any existing annotation
|
| 277 |
+
# we also check for consistency between both annotations
|
| 278 |
+
if is_consistent(arg_type.__args__[1], module_instance.num_features) and \
|
| 279 |
+
is_consistent(n.type.__args__[1], module_instance.num_features) and \
|
| 280 |
+
is_consistent(arg_type, n.type):
|
| 281 |
+
|
| 282 |
+
# we choose the more precise type
|
| 283 |
+
# to be the node type
|
| 284 |
+
# so if an incoming argument has more type information
|
| 285 |
+
# we set this node's type to be the argument type
|
| 286 |
+
n.type = get_greatest_upper_bound(arg_type, n.type)
|
| 287 |
+
return n.type
|
| 288 |
+
else:
|
| 289 |
+
raise TypeError(f'Cannot apply {module_instance} with input type {arg_type} and existing type {n.type} on {n}')
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def calculate_out_dimension(d_in, module_instance, index):
|
| 293 |
+
"""
|
| 294 |
+
For calculating h_in and w_out according to the conv2D documentation
|
| 295 |
+
"""
|
| 296 |
+
padding = (module_instance.padding, module_instance.padding) \
|
| 297 |
+
if isinstance(module_instance.padding, int) else module_instance.padding
|
| 298 |
+
kernel_size = (module_instance.kernel_size, module_instance.kernel_size) \
|
| 299 |
+
if isinstance(module_instance.kernel_size, int) else module_instance.kernel_size
|
| 300 |
+
stride = (module_instance.stride, module_instance.stride) \
|
| 301 |
+
if isinstance(module_instance.stride, int) else module_instance.stride
|
| 302 |
+
dilation = (module_instance.dilation, module_instance.dilation) \
|
| 303 |
+
if isinstance(module_instance.dilation, int) else module_instance.dilation
|
| 304 |
+
|
| 305 |
+
DIMENSION_TYPES = (int, sympy.Symbol)
|
| 306 |
+
|
| 307 |
+
if d_in == Dyn:
|
| 308 |
+
return Dyn
|
| 309 |
+
|
| 310 |
+
elif isinstance(d_in, DIMENSION_TYPES):
|
| 311 |
+
n = d_in + 2 * padding[index] - \
|
| 312 |
+
dilation[index] * \
|
| 313 |
+
(kernel_size[index] - 1) - 1
|
| 314 |
+
|
| 315 |
+
return (n // stride[0]) + 1
|
| 316 |
+
|
| 317 |
+
else:
|
| 318 |
+
raise TypeError(f'{d_in} in {module_instance} must be a number or Dyn. Received {type(d_in)}')
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def get_greatest_upper_bound(type1, type2):
|
| 322 |
+
"""
|
| 323 |
+
Get the most precise type that's consistent with the given types
|
| 324 |
+
"""
|
| 325 |
+
if type1 == Dyn:
|
| 326 |
+
return type2
|
| 327 |
+
elif type2 == Dyn:
|
| 328 |
+
return type1
|
| 329 |
+
elif isinstance(type1, TensorType) and isinstance(type2, TensorType):
|
| 330 |
+
if not is_consistent(type1, type2):
|
| 331 |
+
raise TypeError(f'Inconsistent types {type1}, {type2}')
|
| 332 |
+
gub = [t1 if is_more_precise(t1, t2) else t2 for (t1, t2) in zip(type1.__args__, type2.__args__)]
|
| 333 |
+
return TensorType(tuple(gub))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@register_inference_rule(Conv2d)
|
| 337 |
+
def conv2d_inference_rule(n: Node, module_instance):
|
| 338 |
+
"""
|
| 339 |
+
Given a Conv2D instance and a node check the following conditions:
|
| 340 |
+
- the input type can be expanded to a size 4 tensor: t = (x_1, x_2, H, W)
|
| 341 |
+
- the current node type can be expanded to a size 4 tensor: t' = (x_1', x_2', x_3', x_4')
|
| 342 |
+
- x_2 is consistent with the module's in_channels
|
| 343 |
+
- let o = (x_1, out_channels, H_out, W_out)
|
| 344 |
+
then the output is the greatest upper bound of o and the existing node type t'.
|
| 345 |
+
"""
|
| 346 |
+
assert isinstance(n.args[0], Node)
|
| 347 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, 4)
|
| 348 |
+
arg_type = n.args[0].type
|
| 349 |
+
curr_node_type = expand_to_tensor_dim(n.type, 4)
|
| 350 |
+
|
| 351 |
+
if is_consistent(arg_type.__args__[1], module_instance.in_channels):
|
| 352 |
+
w_in = arg_type.__args__[3]
|
| 353 |
+
h_in = arg_type.__args__[2]
|
| 354 |
+
h_out = calculate_out_dimension(h_in, module_instance, 0)
|
| 355 |
+
w_out = calculate_out_dimension(w_in, module_instance, 1)
|
| 356 |
+
new_type = TensorType((arg_type.__args__[0], module_instance.out_channels, h_out, w_out))
|
| 357 |
+
gub = get_greatest_upper_bound(new_type, curr_node_type)
|
| 358 |
+
n.type = gub
|
| 359 |
+
return n.type
|
| 360 |
+
else:
|
| 361 |
+
raise TypeError(f'Cannot apply {module_instance} with input type { arg_type} and existing type {n.type} on {n}')
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@register_inference_rule(torch.nn.ReLU)
|
| 365 |
+
def relu_inference_rule(n: Node, module_instance):
|
| 366 |
+
"""
|
| 367 |
+
Input and output shapes should be equal.
|
| 368 |
+
"""
|
| 369 |
+
assert isinstance(n.args[0], Node)
|
| 370 |
+
|
| 371 |
+
if n.args[0].type == Dyn and isinstance(n.type, TensorType):
|
| 372 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, len(n.type.__args__))
|
| 373 |
+
|
| 374 |
+
if isinstance(n.args[0].type, TensorType):
|
| 375 |
+
n.type = get_greatest_upper_bound(n.args[0].type, n.type)
|
| 376 |
+
return n.type
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def maxpool2d_check(typ, module_instance):
|
| 380 |
+
"""
|
| 381 |
+
Applies the maxpool2d shape information to the input
|
| 382 |
+
this affects the last two dimensions
|
| 383 |
+
"""
|
| 384 |
+
new_type_list = list(typ.__args__)
|
| 385 |
+
if len(new_type_list) == 4 or len(new_type_list) == 3:
|
| 386 |
+
w_in = new_type_list[-1]
|
| 387 |
+
h_in = new_type_list[-2]
|
| 388 |
+
|
| 389 |
+
h_out = calculate_out_dimension(h_in, module_instance, 0)
|
| 390 |
+
w_out = calculate_out_dimension(w_in, module_instance, 1)
|
| 391 |
+
|
| 392 |
+
new_type_list[-1] = w_out
|
| 393 |
+
new_type_list[-2] = h_out
|
| 394 |
+
return TensorType(tuple(new_type_list))
|
| 395 |
+
|
| 396 |
+
else:
|
| 397 |
+
raise TypeError(f'Wrong size {typ} for {module_instance}')
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@register_inference_rule(torch.nn.MaxPool2d)
|
| 401 |
+
def maxpool2d_inference_rule(n: Node, module_instance):
|
| 402 |
+
"""
|
| 403 |
+
Given a MaxPool2D instance and a node check the following conditions:
|
| 404 |
+
- Input size matches size 3 or 4
|
| 405 |
+
- Current node type is consistent with the output type we will calculate
|
| 406 |
+
- Input size matches output size and the last two dimensions of the output
|
| 407 |
+
are w_out and h_out. The remaining dimensions are the same as the input
|
| 408 |
+
- Our final result is the greatest upper bound of the output we calculate
|
| 409 |
+
and the current node type.
|
| 410 |
+
"""
|
| 411 |
+
assert isinstance(n.args[0], Node)
|
| 412 |
+
|
| 413 |
+
if n.args[0].type == Dyn and isinstance(n.type, TensorType):
|
| 414 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, len(n.type.__args__))
|
| 415 |
+
if isinstance(n.args[0].type, TensorType):
|
| 416 |
+
output = maxpool2d_check(n.args[0].type, module_instance)
|
| 417 |
+
n.type = get_greatest_upper_bound(output, n.type)
|
| 418 |
+
return n.type
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def linear_check(tensor_type, module_instance):
|
| 423 |
+
"""
|
| 424 |
+
Checks that an input tensor type satisfies the conditions for linear operation
|
| 425 |
+
and returns the output type based on in and out features given by module_instance
|
| 426 |
+
"""
|
| 427 |
+
if len(tensor_type.__args__) >= 2:
|
| 428 |
+
if is_consistent(module_instance.in_features, tensor_type.__args__[-1]):
|
| 429 |
+
new_type_args = list(tensor_type.__args__)
|
| 430 |
+
new_type_args[-1] = module_instance.out_features
|
| 431 |
+
return TensorType(tuple(new_type_args))
|
| 432 |
+
else:
|
| 433 |
+
raise TypeError(f'Inconsistent {module_instance.in_features} and {tensor_type.__args__[-1]} in {module_instance}')
|
| 434 |
+
else:
|
| 435 |
+
raise TypeError(f'Type {tensor_type} must have rank 2 or more.')
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@register_inference_rule(torch.nn.Linear)
|
| 439 |
+
def linear_inference_rule(n: Node, module_instance):
|
| 440 |
+
"""
|
| 441 |
+
Applies the shape information to the input then gets the greatest upper bound
|
| 442 |
+
of the resulting type and the existing type
|
| 443 |
+
"""
|
| 444 |
+
assert isinstance(n.args[0], Node)
|
| 445 |
+
if n.args[0].type == Dyn and isinstance(n.type, TensorType):
|
| 446 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, len(n.type.__args__))
|
| 447 |
+
if isinstance(n.args[0].type, TensorType):
|
| 448 |
+
output_type = linear_check(n.args[0].type, module_instance)
|
| 449 |
+
n.type = get_greatest_upper_bound(output_type, n.type)
|
| 450 |
+
return n.type
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def adaptiveavgpool2d_check(tensor_type, module_instance):
|
| 454 |
+
output_size = module_instance.output_size
|
| 455 |
+
if isinstance(output_size, int):
|
| 456 |
+
output_size = [output_size, output_size]
|
| 457 |
+
elif isinstance(output_size, tuple):
|
| 458 |
+
output_size = list(output_size)
|
| 459 |
+
if output_size[0] is None:
|
| 460 |
+
output_size[0] = output_size[1]
|
| 461 |
+
if output_size[1] is None:
|
| 462 |
+
output_size[1] = output_size[0]
|
| 463 |
+
|
| 464 |
+
new_type_list = list(tensor_type.__args__)
|
| 465 |
+
|
| 466 |
+
if len(tensor_type.__args__) == 4 or len(tensor_type.__args__) == 3:
|
| 467 |
+
new_type_list[-1] = output_size[1]
|
| 468 |
+
new_type_list[-2] = output_size[0]
|
| 469 |
+
|
| 470 |
+
return TensorType(tuple(new_type_list))
|
| 471 |
+
|
| 472 |
+
else:
|
| 473 |
+
raise TypeError(f'Tensor ranks must be 3 or 4. Got {tensor_type}')
|
| 474 |
+
|
| 475 |
+
@register_inference_rule(torch.nn.AdaptiveAvgPool2d)
|
| 476 |
+
def adaptiveavgpool2d_inference_rule(n: Node, module_instance):
|
| 477 |
+
"""
|
| 478 |
+
The input and output sizes should be the same except for the last
|
| 479 |
+
two dimensions taken from the input, which represent width and height
|
| 480 |
+
"""
|
| 481 |
+
assert isinstance(n.args[0], Node)
|
| 482 |
+
if n.args[0].type == Dyn and isinstance(n.type, TensorType):
|
| 483 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, len(n.type.__args__))
|
| 484 |
+
if isinstance(n.args[0].type, TensorType):
|
| 485 |
+
output_type = adaptiveavgpool2d_check(n.args[0].type, module_instance)
|
| 486 |
+
n.type = get_greatest_upper_bound(n.type, output_type)
|
| 487 |
+
return n.type
|
| 488 |
+
|
| 489 |
+
def flatten_check(tensor_type, start_dim, end_dim):
|
| 490 |
+
l = len(tensor_type.__args__)
|
| 491 |
+
|
| 492 |
+
start_dim = l if start_dim == -1 else abs(start_dim)
|
| 493 |
+
end_dim = l + end_dim + 1 if end_dim < 0 else end_dim + 1
|
| 494 |
+
|
| 495 |
+
if 0 <= start_dim <= (l - 1) and 0 <= end_dim <= l and start_dim < end_dim:
|
| 496 |
+
my_args = list(tensor_type.__args__)
|
| 497 |
+
lhs = my_args[0:start_dim]
|
| 498 |
+
rhs = my_args[end_dim:]
|
| 499 |
+
mid = my_args[start_dim:end_dim]
|
| 500 |
+
if Dyn in mid:
|
| 501 |
+
mid = [Dyn]
|
| 502 |
+
else:
|
| 503 |
+
mid = [reduce(operator.mul, my_args[start_dim:end_dim])]
|
| 504 |
+
new_type_list = lhs + mid + rhs
|
| 505 |
+
return TensorType(tuple(new_type_list))
|
| 506 |
+
else:
|
| 507 |
+
raise TypeError(f'Incompatible dimensions {start_dim}, {end_dim - 1} in type {tensor_type}')
|
| 508 |
+
|
| 509 |
+
@register_inference_rule(torch.flatten)
|
| 510 |
+
def flatten_inference_rule(n: Node):
|
| 511 |
+
"""
|
| 512 |
+
Applies the flatten shape information to the input then gets the
|
| 513 |
+
greatest upper bound of the resulting type and the existing type
|
| 514 |
+
"""
|
| 515 |
+
assert isinstance(n.args[0], Node)
|
| 516 |
+
|
| 517 |
+
# set the default start and end dims
|
| 518 |
+
start_dim = 1
|
| 519 |
+
end_dim = -1
|
| 520 |
+
|
| 521 |
+
if len(n.args) > 1:
|
| 522 |
+
assert isinstance(n.args[1], int)
|
| 523 |
+
start_dim = n.args[1]
|
| 524 |
+
|
| 525 |
+
if len(n.args) > 2:
|
| 526 |
+
assert isinstance(n.args[2], int)
|
| 527 |
+
end_dim = n.args[2]
|
| 528 |
+
|
| 529 |
+
if n.args[0].type == Dyn and isinstance(n.type, TensorType):
|
| 530 |
+
n.args[0].type = expand_to_tensor_dim(n.args[0].type, len(n.type.__args__))
|
| 531 |
+
|
| 532 |
+
if isinstance(n.args[0].type, TensorType):
|
| 533 |
+
output_type = flatten_check(n.args[0].type, start_dim, end_dim)
|
| 534 |
+
n.type = get_greatest_upper_bound(output_type , n.type)
|
| 535 |
+
|
| 536 |
+
return n.type
|
| 537 |
+
|
| 538 |
+
class GraphTypeChecker:
|
| 539 |
+
def __init__(self, env, traced):
|
| 540 |
+
self.env = env
|
| 541 |
+
self.traced = traced
|
| 542 |
+
|
| 543 |
+
def type_check(self):
|
| 544 |
+
"""
|
| 545 |
+
A gradual type checker for graphs
|
| 546 |
+
Effect: every node's field type will be
|
| 547 |
+
populated with a type after type-checking is done
|
| 548 |
+
"""
|
| 549 |
+
graph = self.traced.graph
|
| 550 |
+
|
| 551 |
+
# type check every node with gradual type rules
|
| 552 |
+
# if any node does not type check return false
|
| 553 |
+
for n in graph.nodes:
|
| 554 |
+
self.type_check_node(n)
|
| 555 |
+
return True
|
| 556 |
+
|
| 557 |
+
def type_check_node(self, n: Node):
|
| 558 |
+
"""
|
| 559 |
+
Type check a given fx node.
|
| 560 |
+
Current operations:
|
| 561 |
+
- Reshape
|
| 562 |
+
- Transpose
|
| 563 |
+
- Add
|
| 564 |
+
- Relu
|
| 565 |
+
- conv2d
|
| 566 |
+
- batchnorm2d
|
| 567 |
+
- flatten
|
| 568 |
+
- maxpool2d
|
| 569 |
+
- adaptiveavgpool2d
|
| 570 |
+
- linear
|
| 571 |
+
"""
|
| 572 |
+
if n.type is None:
|
| 573 |
+
n.type = Dyn
|
| 574 |
+
|
| 575 |
+
if n.op == 'placeholder':
|
| 576 |
+
return n.type
|
| 577 |
+
|
| 578 |
+
elif n.op == 'get_attr':
|
| 579 |
+
t = get_parameter(self.traced, n.target) # type: ignore[arg-type]
|
| 580 |
+
if isinstance(t.data, torch.Tensor):
|
| 581 |
+
n.type = TensorType(t.data.shape)
|
| 582 |
+
return n.type
|
| 583 |
+
|
| 584 |
+
elif n.op == 'call_function':
|
| 585 |
+
if n.target == getattr:
|
| 586 |
+
assert getattr in _INFERENCE_RULES
|
| 587 |
+
return _INFERENCE_RULES[n.target](n, self.traced)
|
| 588 |
+
|
| 589 |
+
elif n.target in _INFERENCE_RULES:
|
| 590 |
+
return _INFERENCE_RULES[n.target](n)
|
| 591 |
+
else:
|
| 592 |
+
raise RuntimeError(f'No inference rule registered for target {n.target}!')
|
| 593 |
+
|
| 594 |
+
elif n.op == 'call_module':
|
| 595 |
+
module_instance = self.traced.get_submodule(n.target)
|
| 596 |
+
if type(module_instance) in _INFERENCE_RULES:
|
| 597 |
+
return _INFERENCE_RULES[type(module_instance)](n, module_instance)
|
| 598 |
+
else:
|
| 599 |
+
raise RuntimeError(f'No inference rule registered for class {type(module_instance)}!')
|
| 600 |
+
|
| 601 |
+
elif n.op == 'output':
|
| 602 |
+
def get_node_type(a):
|
| 603 |
+
return a.type
|
| 604 |
+
n.type = torch.fx.node.map_arg(n.args[0], get_node_type)
|
| 605 |
+
return n.type
|
| 606 |
+
|
| 607 |
+
else:
|
| 608 |
+
raise NotImplementedError(f"Method {n.op} not yet implemented")
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
@register_refinement_rule(Conv2d)
|
| 612 |
+
def conv_refinement_rule(n: Node):
|
| 613 |
+
"""
|
| 614 |
+
The equality constraints are between the first dimension of
|
| 615 |
+
the input and output
|
| 616 |
+
"""
|
| 617 |
+
res = []
|
| 618 |
+
assert isinstance(n.args[0], Node)
|
| 619 |
+
arg_type = n.args[0].type
|
| 620 |
+
if isinstance(arg_type, TensorType) and isinstance(n.type, TensorType):
|
| 621 |
+
res = [Equality(arg_type.__args__[0], n.type.__args__[0])]
|
| 622 |
+
return res
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
@register_refinement_rule(torch.nn.Linear)
|
| 626 |
+
def linear_refinement_rule(n: Node):
|
| 627 |
+
"""
|
| 628 |
+
The equality constraints are between the first dimension of
|
| 629 |
+
the input and output
|
| 630 |
+
"""
|
| 631 |
+
res = []
|
| 632 |
+
assert isinstance(n.args[0], Node)
|
| 633 |
+
arg_type = n.args[0].type
|
| 634 |
+
if isinstance(arg_type, TensorType) and isinstance(n.type, TensorType):
|
| 635 |
+
res = [Equality(arg_type.__args__[0], n.type.__args__[0])]
|
| 636 |
+
return res
|
| 637 |
+
|
| 638 |
+
@register_refinement_rule(BatchNorm2d)
|
| 639 |
+
@register_refinement_rule(torch.nn.ReLU)
|
| 640 |
+
def all_eq(n: Node):
|
| 641 |
+
"""
|
| 642 |
+
For operations where the input shape is equal to the output shape
|
| 643 |
+
"""
|
| 644 |
+
res = []
|
| 645 |
+
assert isinstance(n.args[0], Node)
|
| 646 |
+
arg_type = n.args[0].type
|
| 647 |
+
if isinstance(arg_type, TensorType) and isinstance(n.type, TensorType):
|
| 648 |
+
args1 = arg_type.__args__
|
| 649 |
+
args2 = n.type.__args__
|
| 650 |
+
res = [Equality(args1[i], args2[i]) for i in range(len(args1))]
|
| 651 |
+
return res
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
@register_refinement_rule(torch.nn.AdaptiveAvgPool2d)
|
| 655 |
+
@register_refinement_rule(torch.nn.MaxPool2d)
|
| 656 |
+
def first_two_eq(n: Node):
|
| 657 |
+
"""
|
| 658 |
+
For operations where the first two dimensions of the input and output shape
|
| 659 |
+
are equal
|
| 660 |
+
"""
|
| 661 |
+
res = []
|
| 662 |
+
assert isinstance(n.args[0], Node)
|
| 663 |
+
arg_type = n.args[0].type
|
| 664 |
+
if isinstance(arg_type, TensorType) and isinstance(n.type, TensorType):
|
| 665 |
+
args1 = arg_type.__args__
|
| 666 |
+
args2 = n.type.__args__
|
| 667 |
+
res = [Equality(args1[0], args2[0]), Equality(args1[1], args2[1])]
|
| 668 |
+
return res
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
@register_refinement_rule(torch.add)
|
| 672 |
+
@register_refinement_rule(operator.add)
|
| 673 |
+
def element_wise_eq(n: Node):
|
| 674 |
+
"""
|
| 675 |
+
For element-wise operations and handles broadcasting.
|
| 676 |
+
Note that after applying broadcasting to the arguments
|
| 677 |
+
we are able to determine if certain dimensions have not been broadcast
|
| 678 |
+
if they are symbolicallu equal.
|
| 679 |
+
|
| 680 |
+
in this case, we can establish equality between those dimensions and the
|
| 681 |
+
corresponding output dimensions.
|
| 682 |
+
|
| 683 |
+
Note that it takes two iterations for this result. One iteration to establish
|
| 684 |
+
equality between certain dimensions of the operands (requiring the whole solver
|
| 685 |
+
including unification) and another iteration to establish equality between the operands
|
| 686 |
+
and the resulting type, requiring another round of constraint generation and unificaiton.
|
| 687 |
+
"""
|
| 688 |
+
res = []
|
| 689 |
+
if isinstance(n.args[0], Node) and isinstance(n.args[1], Node):
|
| 690 |
+
arg_type1 = n.args[0].type
|
| 691 |
+
arg_type2 = n.args[1].type
|
| 692 |
+
if isinstance(arg_type1, TensorType) and isinstance(arg_type2, TensorType) and isinstance(n.type, TensorType):
|
| 693 |
+
args1, args2 = broadcast_types(arg_type1, arg_type2)
|
| 694 |
+
# by this point, we know that args1 and args2 are the same size.
|
| 695 |
+
a1 = args1.__args__
|
| 696 |
+
a2 = args2.__args__
|
| 697 |
+
a3 = n.type.__args__
|
| 698 |
+
|
| 699 |
+
# we would be here in the second iteration where we establish equality
|
| 700 |
+
# between operand type dimensions and the resulting type dimensions
|
| 701 |
+
r = []
|
| 702 |
+
for x, y, z in zip(a1, a2, a3):
|
| 703 |
+
if x == y:
|
| 704 |
+
r.append(Equality(x, z))
|
| 705 |
+
res = r
|
| 706 |
+
return res
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
@register_refinement_rule(torch.flatten)
|
| 710 |
+
def flatten_refinement_rule(n: Node):
|
| 711 |
+
"""
|
| 712 |
+
Generates equality constraints between the dimensions of the input and output
|
| 713 |
+
that will not be involved in the flatten operation
|
| 714 |
+
"""
|
| 715 |
+
assert isinstance(n.args[0], Node)
|
| 716 |
+
|
| 717 |
+
eq_const = []
|
| 718 |
+
|
| 719 |
+
start_dim = 1
|
| 720 |
+
end_dim = -1
|
| 721 |
+
|
| 722 |
+
if len(n.args) > 1:
|
| 723 |
+
assert isinstance(n.args[1], int)
|
| 724 |
+
start_dim = n.args[1]
|
| 725 |
+
|
| 726 |
+
if len(n.args) > 2:
|
| 727 |
+
assert isinstance(n.args[2], int)
|
| 728 |
+
end_dim = n.args[2]
|
| 729 |
+
|
| 730 |
+
if isinstance(n.type, TensorType) and isinstance(n.args[0].type, TensorType):
|
| 731 |
+
l = len(n.type.__args__)
|
| 732 |
+
arg_type = n.args[0].type
|
| 733 |
+
start_dim = l if start_dim == -1 else start_dim
|
| 734 |
+
end_dim = l + end_dim + 1 if end_dim < 0 else end_dim + 1
|
| 735 |
+
|
| 736 |
+
for t1, t2 in zip(n.type.__args__[0:start_dim], arg_type.__args__[0:start_dim]):
|
| 737 |
+
eq_const.append(Equality(t1, t2))
|
| 738 |
+
|
| 739 |
+
for t1, t2 in zip(n.type.__args__[end_dim:], arg_type.__args__[end_dim:]):
|
| 740 |
+
eq_const.append(Equality(t1, t2))
|
| 741 |
+
return eq_const
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
@register_algebraic_expressions_inference_rule(Conv2d)
|
| 745 |
+
def conv_rule(n: Node, module_instance):
|
| 746 |
+
"""
|
| 747 |
+
Represents the outout in terms of an algrbraic expression w.r.t
|
| 748 |
+
the input when possible
|
| 749 |
+
"""
|
| 750 |
+
assert isinstance(n.args[0], Node)
|
| 751 |
+
arg_type = n.args[0].type
|
| 752 |
+
if isinstance(arg_type, TensorType) and isinstance(n.type, TensorType):
|
| 753 |
+
w_in = arg_type.__args__[3]
|
| 754 |
+
h_in = arg_type.__args__[2]
|
| 755 |
+
h_out = calculate_out_dimension(h_in, module_instance, 0)
|
| 756 |
+
w_out = calculate_out_dimension(w_in, module_instance, 1)
|
| 757 |
+
new_type = TensorType((n.type.__args__[0], n.type.__args__[1], h_out, w_out))
|
| 758 |
+
n.type = new_type
|
| 759 |
+
return new_type
|
| 760 |
+
|
| 761 |
+
class Refine:
|
| 762 |
+
"""
|
| 763 |
+
Symbolic shape inference.
|
| 764 |
+
Generates constraints over type variables.
|
| 765 |
+
Currently all constraints are equality constraints.
|
| 766 |
+
"""
|
| 767 |
+
def __init__(self, traced):
|
| 768 |
+
self.constraints = []
|
| 769 |
+
self.traced = traced
|
| 770 |
+
self.symbol_iter = itertools.count(start=0, step=1)
|
| 771 |
+
|
| 772 |
+
def refine(self):
|
| 773 |
+
"""
|
| 774 |
+
Generates constraints for
|
| 775 |
+
every node in the graph based on
|
| 776 |
+
the operation.
|
| 777 |
+
"""
|
| 778 |
+
graph = self.traced.graph
|
| 779 |
+
for n in graph.nodes:
|
| 780 |
+
self.refine_node(n)
|
| 781 |
+
return True
|
| 782 |
+
|
| 783 |
+
def symbolic_relations(self):
|
| 784 |
+
"""
|
| 785 |
+
Infers algebraic relations
|
| 786 |
+
"""
|
| 787 |
+
graph = self.traced.graph
|
| 788 |
+
for n in graph.nodes:
|
| 789 |
+
self.infer_symbolic_relations(n)
|
| 790 |
+
return True
|
| 791 |
+
|
| 792 |
+
def replace_dyn_with_fresh_var(self, typ):
|
| 793 |
+
"""
|
| 794 |
+
Replace all unknown types with fresh type variables.
|
| 795 |
+
"""
|
| 796 |
+
if typ == Dyn:
|
| 797 |
+
new_symbol = Var(next(self.symbol_iter))
|
| 798 |
+
return new_symbol
|
| 799 |
+
elif isinstance(typ, TensorType):
|
| 800 |
+
new_args = [self.replace_dyn_with_fresh_var(a) for a in typ.__args__]
|
| 801 |
+
return TensorType(tuple(new_args))
|
| 802 |
+
elif isinstance(typ, list):
|
| 803 |
+
return [self.replace_dyn_with_fresh_var(t) for t in typ]
|
| 804 |
+
elif isinstance(typ, tuple):
|
| 805 |
+
return (self.replace_dyn_with_fresh_var(t) for t in typ)
|
| 806 |
+
else:
|
| 807 |
+
return typ
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def convert_to_sympy_symbols(self, typ):
|
| 811 |
+
"""
|
| 812 |
+
Replace all unknown types with fresh type variables.
|
| 813 |
+
"""
|
| 814 |
+
if isinstance(typ, Var):
|
| 815 |
+
return sympy.symbols(str(typ))
|
| 816 |
+
elif isinstance(typ, TensorType):
|
| 817 |
+
new_args = [self.convert_to_sympy_symbols(a) for a in typ.__args__]
|
| 818 |
+
return TensorType(tuple(new_args))
|
| 819 |
+
elif isinstance(typ, list):
|
| 820 |
+
return [self.convert_to_sympy_symbols(t) for t in typ]
|
| 821 |
+
elif isinstance(typ, tuple):
|
| 822 |
+
return (self.convert_to_sympy_symbols(t) for t in typ)
|
| 823 |
+
else:
|
| 824 |
+
return typ
|
| 825 |
+
|
| 826 |
+
def refine_node(self, n: Node):
|
| 827 |
+
"""
|
| 828 |
+
Returns a list of equality constraints for
|
| 829 |
+
call_module and call_function nodes.
|
| 830 |
+
Models the relation between input and output dimensions
|
| 831 |
+
using constraints in case they are both tensors.
|
| 832 |
+
All operations used in resnet50 are defined.
|
| 833 |
+
"""
|
| 834 |
+
if n.type is None:
|
| 835 |
+
n.type = Dyn
|
| 836 |
+
|
| 837 |
+
n.type = self.replace_dyn_with_fresh_var(n.type)
|
| 838 |
+
|
| 839 |
+
if n.op == 'call_function':
|
| 840 |
+
if n.target in _REFINEMENT_RULES:
|
| 841 |
+
self.constraints += _REFINEMENT_RULES[n.target](n)
|
| 842 |
+
else:
|
| 843 |
+
pass
|
| 844 |
+
|
| 845 |
+
if n.op == 'call_module':
|
| 846 |
+
module_instance = self.traced.get_submodule(n.target)
|
| 847 |
+
if type(module_instance) in _REFINEMENT_RULES:
|
| 848 |
+
self.constraints += _REFINEMENT_RULES[type(module_instance)](n)
|
| 849 |
+
else:
|
| 850 |
+
pass
|
| 851 |
+
|
| 852 |
+
if n.op == 'output':
|
| 853 |
+
def get_node_type(a):
|
| 854 |
+
return a.type
|
| 855 |
+
n.type = torch.fx.node.map_arg(n.args[0], get_node_type)
|
| 856 |
+
return n.type
|
| 857 |
+
|
| 858 |
+
else:
|
| 859 |
+
pass
|
| 860 |
+
|
| 861 |
+
def infer_symbolic_relations(self, n: Node):
|
| 862 |
+
n.type = self.convert_to_sympy_symbols(n.type)
|
| 863 |
+
if n.op == 'call_function':
|
| 864 |
+
if n.target in _RULES:
|
| 865 |
+
return _RULES[n.target](n)
|
| 866 |
+
else:
|
| 867 |
+
pass
|
| 868 |
+
|
| 869 |
+
if n.op == 'call_module':
|
| 870 |
+
module_instance = self.traced.get_submodule(n.target)
|
| 871 |
+
if type(module_instance) in _RULES:
|
| 872 |
+
return _RULES[type(module_instance)](n, module_instance)
|
| 873 |
+
else:
|
| 874 |
+
pass
|
| 875 |
+
|
| 876 |
+
if n.op == 'output':
|
| 877 |
+
def get_node_type(a):
|
| 878 |
+
return a.type
|
| 879 |
+
n.type = torch.fx.node.map_arg(n.args[0], get_node_type)
|
| 880 |
+
return n.type
|
| 881 |
+
|
| 882 |
+
else:
|
| 883 |
+
pass
|
| 884 |
+
|
| 885 |
+
def get_parameter(traced, target: str):
|
| 886 |
+
"""
|
| 887 |
+
Returns the parameter given by ``target`` if it exists,
|
| 888 |
+
otherwise throws an error.
|
| 889 |
+
|
| 890 |
+
See the docstring for ``get_submodule`` for a more detailed
|
| 891 |
+
explanation of this method's functionality as well as how to
|
| 892 |
+
correctly specify ``target``.
|
| 893 |
+
|
| 894 |
+
Args:
|
| 895 |
+
target: The fully-qualified string name of the Parameter
|
| 896 |
+
to look for. (See ``get_submodule`` for how to specify a
|
| 897 |
+
fully-qualified string.)
|
| 898 |
+
|
| 899 |
+
Returns:
|
| 900 |
+
torch.nn.Parameter: The Parameter referenced by ``target``
|
| 901 |
+
|
| 902 |
+
Raises:
|
| 903 |
+
AttributeError: If the target string references an invalid
|
| 904 |
+
path or resolves to something that is not an
|
| 905 |
+
``nn.Parameter``
|
| 906 |
+
"""
|
| 907 |
+
module_path, _, param_name = target.rpartition(".")
|
| 908 |
+
|
| 909 |
+
mod: torch.nn.Module = traced.get_submodule(module_path)
|
| 910 |
+
|
| 911 |
+
if not hasattr(mod, param_name):
|
| 912 |
+
raise AttributeError(mod._get_name() + " has no attribute `" + param_name + "`")
|
| 913 |
+
|
| 914 |
+
param: torch.nn.Parameter = getattr(mod, param_name)
|
| 915 |
+
|
| 916 |
+
return param
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/merge_matmul.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch.fx.node import Node
|
| 5 |
+
from torch.fx._symbolic_trace import symbolic_trace
|
| 6 |
+
from torch.fx.passes.tools_common import legalize_graph
|
| 7 |
+
import itertools
|
| 8 |
+
import operator
|
| 9 |
+
|
| 10 |
+
from typing import Dict, List, Tuple
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def split_result_tensors(
|
| 14 |
+
result: torch.Tensor, inputs: List[torch.Tensor]
|
| 15 |
+
) -> Tuple[torch.Tensor, ...]:
|
| 16 |
+
"""
|
| 17 |
+
A free function for use in the merge_matmul graph transformation below that
|
| 18 |
+
splits the output from a merged matmul into the individual results for each
|
| 19 |
+
input tensor.
|
| 20 |
+
|
| 21 |
+
Arguments:
|
| 22 |
+
result: The merged matmul result tensor.
|
| 23 |
+
inputs: The list of inputs that were merged into one for the matmul.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
List of matmul results for each input tensor.
|
| 27 |
+
"""
|
| 28 |
+
# When fx tracer is running, x.shape[0] will be torch.fx.Attribute but we
|
| 29 |
+
# need an int even when tracing
|
| 30 |
+
if isinstance(result, torch.fx.Proxy):
|
| 31 |
+
splits = [0] * len(inputs)
|
| 32 |
+
else:
|
| 33 |
+
splits = [x.shape[0] for x in inputs]
|
| 34 |
+
|
| 35 |
+
return torch.split(result, splits)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def may_depend_on(a: Node, b: Node, search_depth: int = 6):
|
| 39 |
+
"""
|
| 40 |
+
Determine if one node depends on another in a torch.fx.Graph.
|
| 41 |
+
|
| 42 |
+
Arguments:
|
| 43 |
+
a: The node that may have a dependency on b.
|
| 44 |
+
b: The node that a may have a dependency on.
|
| 45 |
+
search_depth: In the case of an indirect dependency, this function
|
| 46 |
+
searches upto this many nodes away in search of a
|
| 47 |
+
data dependency. If none is found, the function
|
| 48 |
+
makes the conservative assumption that there is a
|
| 49 |
+
dependency.
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
True if a may depend on b, False if it definitely does not.
|
| 53 |
+
"""
|
| 54 |
+
# Equivalence is defined as dependence.
|
| 55 |
+
if a == b:
|
| 56 |
+
return True
|
| 57 |
+
|
| 58 |
+
# If a has no inputs, it cannot depend on b.
|
| 59 |
+
if len(a.all_input_nodes) == 0:
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
# If the search depth has been exhausted and no conclusion has been
|
| 63 |
+
# reached, assume that there is a data dependency.
|
| 64 |
+
if search_depth == 0:
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
# Recursively check all inputs of a.
|
| 68 |
+
for inp in a.all_input_nodes:
|
| 69 |
+
if may_depend_on(inp, b, search_depth - 1):
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
return False
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def are_nodes_independent(nodes: List[Node]):
|
| 76 |
+
"""
|
| 77 |
+
Check if all of the given nodes are pairwise-data independent.
|
| 78 |
+
|
| 79 |
+
Arguments:
|
| 80 |
+
nodes: The nodes to check for data dependencies.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
True if any pair in nodes has a data dependency.
|
| 84 |
+
"""
|
| 85 |
+
# For each pair in nodes:
|
| 86 |
+
for i, j in itertools.combinations(nodes, 2):
|
| 87 |
+
if may_depend_on(i, j) or may_depend_on(j, i):
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
return True
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def merge_matmul(in_mod: torch.nn.Module):
|
| 94 |
+
"""
|
| 95 |
+
A graph transformation that merges matrix multiplication operations that share the same right-hand
|
| 96 |
+
side operand into one large matrix multiplication.
|
| 97 |
+
____ _________ _________
|
| 98 |
+
---- | | | | M| A * C |
|
| 99 |
+
M| A | T| B | * K| C | = |---------|
|
| 100 |
+
---- , | | | | T| B * C |
|
| 101 |
+
K ---- --------- ---------
|
| 102 |
+
K R R
|
| 103 |
+
"""
|
| 104 |
+
gm = symbolic_trace(in_mod)
|
| 105 |
+
|
| 106 |
+
rhs_users: Dict[Node, List[Node]] = {}
|
| 107 |
+
lhs_users: Dict[Node, List[Node]] = {}
|
| 108 |
+
|
| 109 |
+
# Populate rhs_users and lhs_users - maps from LHS/RHS matrix multiply operands to
|
| 110 |
+
# the matmul of which they are the LHS/RHS.
|
| 111 |
+
for node in gm.graph.nodes:
|
| 112 |
+
if node.op != "call_function" or node.target is not torch.matmul:
|
| 113 |
+
continue
|
| 114 |
+
|
| 115 |
+
lhs, rhs = node.args
|
| 116 |
+
|
| 117 |
+
# TODO: Properly handle aliasing caused by get_attr. For now,
|
| 118 |
+
# use the attribute name as the operand if the node is a
|
| 119 |
+
# get_attr.
|
| 120 |
+
lhs = lhs.target if lhs.op == "get_attr" else lhs
|
| 121 |
+
rhs = rhs.target if rhs.op == "get_attr" else rhs
|
| 122 |
+
|
| 123 |
+
lhs_users.setdefault(lhs, []).append(node)
|
| 124 |
+
rhs_users.setdefault(rhs, []).append(node)
|
| 125 |
+
|
| 126 |
+
for rhs, mms in rhs_users.items():
|
| 127 |
+
# There must be at least matmuls for a merge to make sense.
|
| 128 |
+
if len(mms) < 2:
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
# All matmuls must not depend on each other directly or indirectly
|
| 132 |
+
# in order for the merge to be possible.
|
| 133 |
+
if not are_nodes_independent(mms):
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
lhs_vals = [mm.args[0] for mm in mms]
|
| 137 |
+
|
| 138 |
+
# Merge the matmul.
|
| 139 |
+
# Collect a list of LHS operands and the single RHS operand.
|
| 140 |
+
lhs = [gm.graph.get_attr(l) if isinstance(l, str) else l for l in lhs_vals]
|
| 141 |
+
rhs = gm.graph.get_attr(rhs) if isinstance(rhs, str) else rhs
|
| 142 |
+
|
| 143 |
+
# Concatenate all the LHS operands.
|
| 144 |
+
merge_mm_cat = gm.graph.call_function(torch.cat, (lhs,), {})
|
| 145 |
+
|
| 146 |
+
# Multiply the concatenated LHS operands with the one RHS. This will produce
|
| 147 |
+
# the same results as all the individual matmuls involving rhs in the original graph,
|
| 148 |
+
# but they will all be concatenated together.
|
| 149 |
+
merge_mm = gm.graph.call_function(torch.matmul, (merge_mm_cat, rhs,), {})
|
| 150 |
+
|
| 151 |
+
# Split the result of the merged matmul using the shapes of the LHS operands
|
| 152 |
+
# to ascertain how large each chunk should be.
|
| 153 |
+
merge_mm_split = gm.graph.call_function(
|
| 154 |
+
split_result_tensors, (merge_mm, lhs), {}
|
| 155 |
+
)
|
| 156 |
+
merge_mm_res = [
|
| 157 |
+
gm.graph.call_function(operator.getitem, (merge_mm_split, out), {})
|
| 158 |
+
for out in range(len(lhs))
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
# Replace all uses of the original, unmerged matmuls with the equivalent split chunk from the merged matmul.
|
| 162 |
+
for old, new in zip(mms, merge_mm_res):
|
| 163 |
+
old.replace_all_uses_with(new)
|
| 164 |
+
gm.graph.erase_node(old)
|
| 165 |
+
|
| 166 |
+
# All of the new nodes created above were inserted at the end, so we need to sort
|
| 167 |
+
# the nodes topologically to make sure all definitions precede uses.
|
| 168 |
+
legalize_graph(gm)
|
| 169 |
+
|
| 170 |
+
gm.recompile()
|
| 171 |
+
gm.graph.lint()
|
| 172 |
+
return gm
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/meta_tracer.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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optional, Union
|
| 9 |
+
|
| 10 |
+
def embedding_override(self, input):
|
| 11 |
+
return torch.empty(*input.shape, self.weight.shape[-1], device='meta')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def nn_layernorm_override(self, input):
|
| 15 |
+
return input
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def torch_relu_override(x):
|
| 19 |
+
return x
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def torch_nn_relu_override(self, x):
|
| 23 |
+
return x
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def functional_relu_override(x, inplace=False):
|
| 27 |
+
assert not inplace, 'dont support inplace functional.relu for metatensor analysis'
|
| 28 |
+
return x
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def torch_where_override(condition, x, y):
|
| 32 |
+
# torch.where returns the broadcasted tensor of condition, x, and y,
|
| 33 |
+
# so hack it by using addition
|
| 34 |
+
return condition.to(device='meta') + x.to(device='meta') + y.to(device='meta')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def torch_abs_override(input, *, out=None):
|
| 38 |
+
assert out is None, 'Dont support in-place abs for MetaTensor analysis'
|
| 39 |
+
return input
|
| 40 |
+
|
| 41 |
+
manual_meta_overrides : Dict[Callable, Callable] = {
|
| 42 |
+
torch.nn.Embedding: embedding_override,
|
| 43 |
+
torch.nn.LayerNorm: nn_layernorm_override,
|
| 44 |
+
torch.relu: torch_relu_override,
|
| 45 |
+
torch.nn.functional.relu: functional_relu_override,
|
| 46 |
+
torch.nn.ReLU: torch_nn_relu_override,
|
| 47 |
+
torch.where: torch_where_override,
|
| 48 |
+
torch.abs: torch_abs_override,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
def gen_constructor_wrapper(target):
|
| 52 |
+
@functools.wraps(target)
|
| 53 |
+
def wrapper(*args, **kwargs):
|
| 54 |
+
proxy = None
|
| 55 |
+
|
| 56 |
+
def check_has_proxy(v):
|
| 57 |
+
if isinstance(v, torch.fx.Proxy):
|
| 58 |
+
nonlocal proxy
|
| 59 |
+
proxy = v
|
| 60 |
+
torch.fx.node.map_aggregate(args, check_has_proxy)
|
| 61 |
+
torch.fx.node.map_aggregate(kwargs, check_has_proxy)
|
| 62 |
+
|
| 63 |
+
if proxy is not None:
|
| 64 |
+
return proxy.tracer.create_proxy('call_function', target, args, kwargs)
|
| 65 |
+
else:
|
| 66 |
+
return target(*args, **kwargs)
|
| 67 |
+
return wrapper, target
|
| 68 |
+
|
| 69 |
+
class MetaProxy(torch.fx.Proxy):
|
| 70 |
+
def install_tensor_meta(self, tensor_meta):
|
| 71 |
+
self._tensor_meta = tensor_meta
|
| 72 |
+
|
| 73 |
+
def size(self, dim=None):
|
| 74 |
+
if hasattr(self, '_tensor_meta') and self._tensor_meta is not None:
|
| 75 |
+
return self._tensor_meta.size(*[dim] if dim else [])
|
| 76 |
+
return self.tracer.create_proxy('call_method', 'size', (self, dim) if dim else (self,), {})
|
| 77 |
+
|
| 78 |
+
def dim(self):
|
| 79 |
+
if hasattr(self, '_tensor_meta') and self._tensor_meta is not None:
|
| 80 |
+
return self._tensor_meta.dim()
|
| 81 |
+
return self.tracer.create_proxy('call_method', 'dim', (self,), {})
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def shape(self):
|
| 85 |
+
if hasattr(self, '_tensor_meta') and self._tensor_meta is not None:
|
| 86 |
+
return self._tensor_meta.shape
|
| 87 |
+
return self.tracer.create_proxy('call_function', builtins.getattr, (self, 'shape'), {})
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def dtype(self):
|
| 91 |
+
if hasattr(self, '_tensor_meta') and self._tensor_meta is not None:
|
| 92 |
+
return self._tensor_meta.dtype
|
| 93 |
+
return self.tracer.create_proxy('call_function', builtins.getattr, (self, 'dtype'), {})
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def device(self):
|
| 97 |
+
# Hack so we can track when devices are used. During meta-tensor propagation,
|
| 98 |
+
# replace these values with a constant 'meta'
|
| 99 |
+
return MetaDeviceAttribute(self, 'device')
|
| 100 |
+
|
| 101 |
+
def __getattr__(self, k):
|
| 102 |
+
if k == '_tensor_meta':
|
| 103 |
+
return self.__getattribute__(k)
|
| 104 |
+
# note: not added to the graph yet, if this is a method call
|
| 105 |
+
# we peephole optimize to the method invocation
|
| 106 |
+
return MetaAttribute(self, k)
|
| 107 |
+
|
| 108 |
+
class MetaAttribute(MetaProxy):
|
| 109 |
+
def __init__(self, root, attr: str):
|
| 110 |
+
|
| 111 |
+
self.root = root
|
| 112 |
+
self.attr = attr
|
| 113 |
+
self.tracer = root.tracer
|
| 114 |
+
self._node = None
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def node(self):
|
| 118 |
+
# the node for attributes is added lazily, since most will just be method calls
|
| 119 |
+
# which do not rely on the getitem call
|
| 120 |
+
if self._node is None:
|
| 121 |
+
self._node = self.tracer.create_proxy('call_function', getattr, (self.root, self.attr), {}).node
|
| 122 |
+
return self._node
|
| 123 |
+
|
| 124 |
+
def __call__(self, *args, **kwargs):
|
| 125 |
+
return self.tracer.create_proxy('call_method', self.attr, (self.root,) + args, kwargs)
|
| 126 |
+
|
| 127 |
+
class MetaDeviceAttribute(MetaAttribute):
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
def proxys_to_metas(v):
|
| 131 |
+
if isinstance(v, MetaDeviceAttribute):
|
| 132 |
+
return 'meta'
|
| 133 |
+
if isinstance(v, torch.fx.Proxy):
|
| 134 |
+
assert isinstance(v, MetaProxy), f'Expected MetaProxy but got {type(v)}'
|
| 135 |
+
assert hasattr(v, '_tensor_meta'), 'MetaProxy does not have an associated meta'
|
| 136 |
+
return v._tensor_meta
|
| 137 |
+
return v
|
| 138 |
+
|
| 139 |
+
class MetaTracer(torch.fx.Tracer):
|
| 140 |
+
allow_insert_stateless_mods : bool = True
|
| 141 |
+
|
| 142 |
+
_TORCH_METHODS_TO_PATCH = ['arange', 'zeros', 'ones', 'full_like', 'eye']
|
| 143 |
+
|
| 144 |
+
def create_proxy(self, kind, target, args, kwargs, name=None, type_expr=None, proxy_factory_fn=None):
|
| 145 |
+
rv = super().create_proxy(kind, target, args, kwargs, name, type_expr, proxy_factory_fn)
|
| 146 |
+
|
| 147 |
+
if kind == 'placeholder' and target in self.meta_args:
|
| 148 |
+
rv.install_tensor_meta(self.meta_args[target])
|
| 149 |
+
return rv
|
| 150 |
+
|
| 151 |
+
if target in self.orig_fns:
|
| 152 |
+
# NOTE: tensor constructors in PyTorch define the `device` argument as
|
| 153 |
+
# *kwargs-only*. That is why this works. If you add methods to
|
| 154 |
+
# _TORCH_METHODS_TO_PATCH that do not define `device` as kwarg-only,
|
| 155 |
+
# this will break and you will likely see issues where we cannot infer
|
| 156 |
+
# the size of the output.
|
| 157 |
+
if 'device' in kwargs:
|
| 158 |
+
kwargs['device'] = 'meta'
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
args_metas = torch.fx.node.map_aggregate(args, proxys_to_metas)
|
| 162 |
+
kwargs_metas = torch.fx.node.map_aggregate(kwargs, proxys_to_metas)
|
| 163 |
+
|
| 164 |
+
if kind == 'call_function':
|
| 165 |
+
meta_target = manual_meta_overrides.get(target, target)
|
| 166 |
+
meta_out = meta_target(*args_metas, **kwargs_metas)
|
| 167 |
+
elif kind == 'call_method':
|
| 168 |
+
meta_out = getattr(args_metas[0], target)(*args_metas[1:], **kwargs_metas) # type: ignore[index]
|
| 169 |
+
elif kind == 'call_module':
|
| 170 |
+
assert hasattr(self, 'orig_forward')
|
| 171 |
+
self._disable_module_getattr = True
|
| 172 |
+
try:
|
| 173 |
+
mod = self.root.get_submodule(target)
|
| 174 |
+
mod_type = type(mod)
|
| 175 |
+
if mod_type in manual_meta_overrides:
|
| 176 |
+
meta_out = manual_meta_overrides[mod_type](mod, *args_metas, **kwargs_metas) # type: ignore[misc, arg-type]
|
| 177 |
+
else:
|
| 178 |
+
meta_out = self.orig_forward(*args_metas, **kwargs_metas)
|
| 179 |
+
finally:
|
| 180 |
+
self._disable_module_getattr = False
|
| 181 |
+
elif kind == 'get_attr':
|
| 182 |
+
self._disable_module_getattr = True
|
| 183 |
+
try:
|
| 184 |
+
attr_itr = self.root
|
| 185 |
+
atoms = target.split('.')
|
| 186 |
+
for atom in atoms:
|
| 187 |
+
attr_itr = getattr(attr_itr, atom)
|
| 188 |
+
assert isinstance(attr_itr, torch.Tensor)
|
| 189 |
+
meta_out = attr_itr.to(device='meta')
|
| 190 |
+
finally:
|
| 191 |
+
self._disable_module_getattr = False
|
| 192 |
+
else:
|
| 193 |
+
return rv
|
| 194 |
+
|
| 195 |
+
# TODO
|
| 196 |
+
assert isinstance(rv, torch.fx.Proxy), 'Dont support composite output yet'
|
| 197 |
+
rv.install_tensor_meta(meta_out)
|
| 198 |
+
except Exception as e:
|
| 199 |
+
warnings.warn(f'Could not compute metadata for {kind} target {target}: {e}')
|
| 200 |
+
|
| 201 |
+
return rv
|
| 202 |
+
|
| 203 |
+
def getattr(self, attr, attr_val, parameter_proxy_cache):
|
| 204 |
+
if getattr(self, '_disable_module_getattr', False):
|
| 205 |
+
return attr_val
|
| 206 |
+
else:
|
| 207 |
+
return super().getattr(attr, attr_val, parameter_proxy_cache)
|
| 208 |
+
|
| 209 |
+
def call_module(self, m, forward, args, kwargs):
|
| 210 |
+
self.orig_forward = forward
|
| 211 |
+
return super().call_module(m, forward, args, kwargs)
|
| 212 |
+
|
| 213 |
+
def _insert_module_as_submodule(self, mod: torch.nn.Module) -> str:
|
| 214 |
+
"""
|
| 215 |
+
Helper method which tries to insert a module that was not declared as submodule.
|
| 216 |
+
"""
|
| 217 |
+
idx = 0
|
| 218 |
+
mod_name = mod.__class__.__name__.lower()
|
| 219 |
+
path = f"{mod_name}_{idx}"
|
| 220 |
+
while hasattr(self.root, path):
|
| 221 |
+
path = f"{mod_name}_{idx}"
|
| 222 |
+
idx += 1
|
| 223 |
+
|
| 224 |
+
self.root.add_module(path, mod)
|
| 225 |
+
return path
|
| 226 |
+
|
| 227 |
+
def path_of_module(self, mod: torch.nn.Module) -> str:
|
| 228 |
+
try:
|
| 229 |
+
return super().path_of_module(mod)
|
| 230 |
+
except NameError as e:
|
| 231 |
+
if self.allow_insert_stateless_mods and len(list(mod.parameters())) == 0 and len(list(mod.buffers())) == 0:
|
| 232 |
+
path = self._insert_module_as_submodule(mod)
|
| 233 |
+
self.prev_module = path
|
| 234 |
+
return path
|
| 235 |
+
raise
|
| 236 |
+
|
| 237 |
+
def proxy(self, node):
|
| 238 |
+
return MetaProxy(node, self)
|
| 239 |
+
|
| 240 |
+
def trace(self, root, meta_args : Dict[str, torch.Tensor], concrete_args=None): # type: ignore[override]
|
| 241 |
+
assert isinstance(meta_args, dict)
|
| 242 |
+
self.meta_args = meta_args
|
| 243 |
+
|
| 244 |
+
self.patched_torch_methods = {
|
| 245 |
+
target: gen_constructor_wrapper(getattr(torch, target)) for target in self._TORCH_METHODS_TO_PATCH
|
| 246 |
+
}
|
| 247 |
+
self.orig_fns = set()
|
| 248 |
+
|
| 249 |
+
for name, (wrapper, orig) in self.patched_torch_methods.items():
|
| 250 |
+
setattr(torch, name, wrapper)
|
| 251 |
+
self.orig_fns.add(orig)
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
graph = super().trace(root, concrete_args)
|
| 255 |
+
graph._tracer_extras = {'meta_args': meta_args}
|
| 256 |
+
return graph
|
| 257 |
+
finally:
|
| 258 |
+
for name, (_, orig) in self.patched_torch_methods.items():
|
| 259 |
+
setattr(torch, name, orig)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def symbolic_trace(root : Union[torch.nn.Module, Callable[..., Any]],
|
| 263 |
+
meta_args : Optional[Dict[str, torch.Tensor]] = None,
|
| 264 |
+
concrete_args: Optional[Dict[str, Any]] = None) -> torch.fx.GraphModule:
|
| 265 |
+
tracer = MetaTracer()
|
| 266 |
+
graph = tracer.trace(root, meta_args, concrete_args) # type: ignore[arg-type]
|
| 267 |
+
name = root.__class__.__name__ if isinstance(root, torch.nn.Module) else root.__name__
|
| 268 |
+
gm = torch.fx.GraphModule(tracer.root, graph, name)
|
| 269 |
+
return gm
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/constraint_generator.py
ADDED
|
@@ -0,0 +1,1281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import torch
|
| 4 |
+
import operator
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Callable, Dict, Iterable
|
| 7 |
+
|
| 8 |
+
from torch.fx._symbolic_trace import _assert_is_none
|
| 9 |
+
from torch.fx.experimental.migrate_gradual_types.constraint import ApplyBroadcasting, CalcProduct, \
|
| 10 |
+
Disj, TGreatestUpperBound, CalcMaxPool, CalcConv, Conj, BinConstraintT, CanReshape, BinConstraintD, GetItem, T, F, \
|
| 11 |
+
TVar, DVar, GetItemTensor, IndexSelect, Transpose, DGreatestUpperBound
|
| 12 |
+
from torch.fx.experimental.migrate_gradual_types.operation import \
|
| 13 |
+
op_eq, op_matching, op_consistency, op_leq, op_precision, op_gt, op_div, op_sub, op_neq, op_lt, op_add, op_mul
|
| 14 |
+
from torch.fx.node import Target, Node
|
| 15 |
+
from torch.fx.experimental.migrate_gradual_types.util import gen_tensor_dims, gen_nat_constraints, gen_dvar, gen_tvar, \
|
| 16 |
+
gen_bvar
|
| 17 |
+
|
| 18 |
+
from torch.fx.tensor_type import Dyn, TensorType
|
| 19 |
+
from torch.nn.modules.conv import Conv2d
|
| 20 |
+
from torch.nn.modules.batchnorm import BatchNorm2d
|
| 21 |
+
|
| 22 |
+
_INFERENCE_RULES: Dict[Target, Callable] = {}
|
| 23 |
+
|
| 24 |
+
MAX_TENSOR_RANK = 4
|
| 25 |
+
|
| 26 |
+
def register_inference_rule(call_target):
|
| 27 |
+
def register(fn):
|
| 28 |
+
if call_target in _INFERENCE_RULES:
|
| 29 |
+
raise RuntimeError(f'Inference rule already registered for {call_target}!')
|
| 30 |
+
_INFERENCE_RULES[call_target] = fn
|
| 31 |
+
return fn
|
| 32 |
+
return register
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def generate_flatten_constraints(start_dim, end_dim, input, flattened, n, counter):
|
| 36 |
+
d, counter = gen_tensor_dims(n, counter)
|
| 37 |
+
c1 = BinConstraintT(input, TensorType(d), op_eq)
|
| 38 |
+
start_dim = n if start_dim == -1 else abs(start_dim)
|
| 39 |
+
end_dim = n + end_dim + 1 if end_dim < 0 else end_dim + 1
|
| 40 |
+
c2 = CalcProduct(start_dim, end_dim, flattened, d)
|
| 41 |
+
nat_constraints = gen_nat_constraints(d)
|
| 42 |
+
return Conj([c1, c2, *nat_constraints]), counter
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@register_inference_rule(getattr)
|
| 46 |
+
def get_attr_inference_rule(n: Node, symbols, constraints, counter):
|
| 47 |
+
"""
|
| 48 |
+
If the attribute is "device" then the tensor shape is preserved
|
| 49 |
+
"""
|
| 50 |
+
assert isinstance(n.args[0], Node)
|
| 51 |
+
assert isinstance(n.args[1], str)
|
| 52 |
+
output, counter = gen_tvar(counter)
|
| 53 |
+
symbols[n] = output
|
| 54 |
+
|
| 55 |
+
input = symbols[n.args[0]]
|
| 56 |
+
attr = n.args[1]
|
| 57 |
+
|
| 58 |
+
if attr == 'device':
|
| 59 |
+
return [BinConstraintT(input, output, op_eq)], counter
|
| 60 |
+
else:
|
| 61 |
+
raise NotImplementedError('Not yet implemented')
|
| 62 |
+
|
| 63 |
+
@register_inference_rule(torch.bmm)
|
| 64 |
+
def bmm_inference_rule(n: Node, symbols, constraints, counter):
|
| 65 |
+
"""
|
| 66 |
+
Constraints that match the input to a size 3 tensor
|
| 67 |
+
and switch the dimensions according to the rules
|
| 68 |
+
of batch multiplication
|
| 69 |
+
"""
|
| 70 |
+
assert isinstance(n.args[0], Node)
|
| 71 |
+
assert isinstance(n.args[1], Node)
|
| 72 |
+
|
| 73 |
+
bmm_output, counter = gen_tvar(counter)
|
| 74 |
+
symbols[n] = bmm_output
|
| 75 |
+
|
| 76 |
+
bmm_input1 = symbols[n.args[0]]
|
| 77 |
+
bmm_input2 = symbols[n.args[1]]
|
| 78 |
+
|
| 79 |
+
dims_input1, counter = gen_tensor_dims(3, counter)
|
| 80 |
+
dims_input2, counter = gen_tensor_dims(3, counter)
|
| 81 |
+
|
| 82 |
+
inputs_dyn = Conj([BinConstraintT(bmm_input1, Dyn, op_eq),
|
| 83 |
+
BinConstraintT(bmm_input2, Dyn, op_eq),
|
| 84 |
+
BinConstraintT(bmm_output, Dyn, op_eq)])
|
| 85 |
+
|
| 86 |
+
input1_dyn = Conj([BinConstraintT(bmm_input1, Dyn, op_eq),
|
| 87 |
+
BinConstraintT(bmm_input2, TensorType(dims_input2), op_eq),
|
| 88 |
+
BinConstraintT(bmm_output, TensorType([dims_input2[0], Dyn, dims_input2[2]]), op_eq)])
|
| 89 |
+
|
| 90 |
+
input2_dyn = Conj([BinConstraintT(bmm_input2, Dyn, op_eq),
|
| 91 |
+
BinConstraintT(bmm_input1, TensorType(dims_input1), op_eq),
|
| 92 |
+
BinConstraintT(bmm_output, TensorType([dims_input1[0], dims_input1[1], Dyn]), op_eq)])
|
| 93 |
+
|
| 94 |
+
consistency_constraints = [BinConstraintD(dims_input1[0], dims_input2[0], op_consistency)]
|
| 95 |
+
|
| 96 |
+
batch_size, counter = gen_dvar(counter)
|
| 97 |
+
|
| 98 |
+
inputs_are_tensors = Conj([BinConstraintT(bmm_input1, TensorType(dims_input1), op_eq),
|
| 99 |
+
BinConstraintT(bmm_input2, TensorType(dims_input2), op_eq),
|
| 100 |
+
BinConstraintT(bmm_output, TensorType([batch_size, dims_input1[1], dims_input2[2]]), op_eq),
|
| 101 |
+
*consistency_constraints, DGreatestUpperBound(batch_size, dims_input1[0], dims_input2[0])])
|
| 102 |
+
|
| 103 |
+
return [Disj([inputs_dyn, input1_dyn, input2_dyn, inputs_are_tensors])], counter
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@register_inference_rule("index_select")
|
| 107 |
+
def index_select_inference_rule(n: Node, symbols, constraints, counter):
|
| 108 |
+
"""
|
| 109 |
+
We constrain the second argument to a vector or Dyn.
|
| 110 |
+
The output replaces the input with the shape of the vector
|
| 111 |
+
at the position given by the index (first argument)
|
| 112 |
+
"""
|
| 113 |
+
# print(n.args)
|
| 114 |
+
assert isinstance(n.args[0], Node)
|
| 115 |
+
assert isinstance(n.args[1], int)
|
| 116 |
+
assert isinstance(n.args[2], Node)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
index_select, counter = gen_tvar(counter)
|
| 121 |
+
symbols[n] = index_select
|
| 122 |
+
|
| 123 |
+
dims, counter = gen_tensor_dims(1, counter)
|
| 124 |
+
|
| 125 |
+
# equality constraint
|
| 126 |
+
is_size_1 = BinConstraintT(symbols[n.args[2]], TensorType(dims), op_eq)
|
| 127 |
+
is_dyn = BinConstraintT(symbols[n.args[2]], Dyn, op_eq)
|
| 128 |
+
|
| 129 |
+
c2 = Conj([is_size_1, Disj([IndexSelect(i + 1, symbols[n.args[0]], dims[0], n.args[1], index_select)
|
| 130 |
+
for i in range(MAX_TENSOR_RANK)])])
|
| 131 |
+
c3 = Conj([is_dyn, Disj([IndexSelect(i + 1, symbols[n.args[0]], Dyn, n.args[1], index_select)
|
| 132 |
+
for i in range(MAX_TENSOR_RANK)])])
|
| 133 |
+
|
| 134 |
+
return [Disj([c2, c3])], counter
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@register_inference_rule("expand")
|
| 138 |
+
def expand_inference_rule(n: Node, symbols, constraints, counter):
|
| 139 |
+
"""
|
| 140 |
+
We generate the exact constraints as we do for tensor additions but we constraint
|
| 141 |
+
the rank of this expression to be equal to len(n.args[1:]) so that only
|
| 142 |
+
those cases get considered for the output
|
| 143 |
+
"""
|
| 144 |
+
assert isinstance(n.args[0], Node)
|
| 145 |
+
|
| 146 |
+
# define the output for expand
|
| 147 |
+
expand, counter = gen_tvar(counter)
|
| 148 |
+
symbols[n] = expand
|
| 149 |
+
|
| 150 |
+
# since we do not have two nodes here, we will construct an argument variable
|
| 151 |
+
e1 = symbols[n.args[0]]
|
| 152 |
+
e2, counter = gen_tvar(counter)
|
| 153 |
+
|
| 154 |
+
e2_nat_constraints = []
|
| 155 |
+
for arg in n.args[1:]:
|
| 156 |
+
assert isinstance(arg, (Node, int))
|
| 157 |
+
if isinstance(arg, Node):
|
| 158 |
+
assert isinstance(symbols[arg], DVar)
|
| 159 |
+
e2_nat_constraints.append(BinConstraintD(0, symbols[arg], op_leq))
|
| 160 |
+
|
| 161 |
+
e2_constraint = BinConstraintT(e2, TensorType([arg if isinstance(arg, int) else symbols[arg] for arg in n.args[1:]]), op_eq)
|
| 162 |
+
|
| 163 |
+
constraints, counter = gen_broadcasting_constraints(e1, e2, symbols, counter, expand)
|
| 164 |
+
|
| 165 |
+
# constraint the output size
|
| 166 |
+
dims, counter = gen_tensor_dims(len(n.args[1:]), counter)
|
| 167 |
+
nat_constraints = gen_nat_constraints(dims)
|
| 168 |
+
c = [BinConstraintT(expand, TensorType(dims), op_eq), *nat_constraints, e2_constraint, *e2_nat_constraints]
|
| 169 |
+
constraints += c
|
| 170 |
+
|
| 171 |
+
return constraints, counter
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@register_inference_rule(torch.nn.functional.gelu)
|
| 175 |
+
@register_inference_rule(torch.nn.functional.dropout)
|
| 176 |
+
@register_inference_rule(torch.nn.functional.softmax)
|
| 177 |
+
@register_inference_rule("detach")
|
| 178 |
+
@register_inference_rule("to")
|
| 179 |
+
@register_inference_rule("int")
|
| 180 |
+
@register_inference_rule("long")
|
| 181 |
+
@register_inference_rule("contiguous")
|
| 182 |
+
@register_inference_rule(torch.ones)
|
| 183 |
+
@register_inference_rule(torch.zeros)
|
| 184 |
+
def equality_inference_rule(n: Node, symbols, constraints, counter):
|
| 185 |
+
"""
|
| 186 |
+
We generate the constraint: input = output
|
| 187 |
+
"""
|
| 188 |
+
output, counter = gen_tvar(counter)
|
| 189 |
+
symbols[n] = output
|
| 190 |
+
|
| 191 |
+
if isinstance(n.args[0], Node):
|
| 192 |
+
input = symbols[n.args[0]]
|
| 193 |
+
if isinstance(input, TVar):
|
| 194 |
+
return [BinConstraintT(input, output, op_eq)], counter
|
| 195 |
+
|
| 196 |
+
# then we have dimension variables
|
| 197 |
+
else:
|
| 198 |
+
for arg in n.args:
|
| 199 |
+
assert isinstance(symbols[arg], DVar)
|
| 200 |
+
my_size = [symbols[arg] for arg in n.args]
|
| 201 |
+
return [BinConstraintT(output, TensorType(my_size), op_eq)], counter
|
| 202 |
+
|
| 203 |
+
elif isinstance(n.args[0], tuple):
|
| 204 |
+
# then the tuple is the size
|
| 205 |
+
assert len(n.args[0]) <= 4
|
| 206 |
+
my_size = [symbols[arg] for arg in n.args[0]]
|
| 207 |
+
return [BinConstraintT(output, TensorType(my_size), op_eq)], counter
|
| 208 |
+
else:
|
| 209 |
+
raise NotImplementedError('Method not yet implemented')
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@register_inference_rule("transpose")
|
| 213 |
+
def transpose_inference_rule(n: Node, symbols, constraints, counter):
|
| 214 |
+
"""
|
| 215 |
+
Can be considered as a sequence of two index selects, so we generate constraints accordingly
|
| 216 |
+
"""
|
| 217 |
+
assert isinstance(n.args[0], Node)
|
| 218 |
+
assert isinstance(n.args[1], int)
|
| 219 |
+
assert isinstance(n.args[2], int)
|
| 220 |
+
|
| 221 |
+
output, counter = gen_tvar(counter)
|
| 222 |
+
symbols[n] = output
|
| 223 |
+
|
| 224 |
+
from_arg = symbols[n.args[0]]
|
| 225 |
+
assert isinstance(from_arg, TVar)
|
| 226 |
+
|
| 227 |
+
# input and output are dyn
|
| 228 |
+
is_dyn = Conj([BinConstraintT(from_arg, Dyn, op_eq), BinConstraintT(output, Dyn, op_eq)])
|
| 229 |
+
|
| 230 |
+
# or input is a tensor and we actually do the replacement
|
| 231 |
+
c3 = Disj([Transpose(i + 1, from_arg, n.args[1], n.args[2], output) for i in range(MAX_TENSOR_RANK)])
|
| 232 |
+
|
| 233 |
+
return [Disj([is_dyn, c3])], counter
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@register_inference_rule("type_as")
|
| 237 |
+
def type_inference_rule(n: Node, symbols, constraints, counter):
|
| 238 |
+
"""
|
| 239 |
+
We generate the constraint: input = output
|
| 240 |
+
"""
|
| 241 |
+
assert isinstance(n.args[0], Node)
|
| 242 |
+
assert isinstance(n.args[1], Node)
|
| 243 |
+
|
| 244 |
+
output, counter = gen_tvar(counter)
|
| 245 |
+
symbols[n] = output
|
| 246 |
+
|
| 247 |
+
from_arg = symbols[n.args[0]]
|
| 248 |
+
to_arg = symbols[n.args[1]]
|
| 249 |
+
|
| 250 |
+
assert isinstance(from_arg, TVar)
|
| 251 |
+
assert isinstance(to_arg, TVar)
|
| 252 |
+
|
| 253 |
+
return [BinConstraintT(from_arg, to_arg, op_consistency),
|
| 254 |
+
BinConstraintT(output, to_arg, op_eq)], counter
|
| 255 |
+
|
| 256 |
+
@register_inference_rule("masked_fill_")
|
| 257 |
+
def masked_fill_inference_rule(n: Node, symbols, constraints, counter):
|
| 258 |
+
"""
|
| 259 |
+
Similar to addition. For now we implement the constraints when
|
| 260 |
+
the argument is a boolean tensor. There is also a case for when
|
| 261 |
+
it is a condition. We will leave this out for now.
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
assert isinstance(n.args[0], Node)
|
| 265 |
+
assert isinstance(n.args[1], Node)
|
| 266 |
+
|
| 267 |
+
# We will retrieve the type variables from the symbol table
|
| 268 |
+
# and confirm they are tensor variables
|
| 269 |
+
|
| 270 |
+
e1 = symbols[n.args[0]]
|
| 271 |
+
e2 = symbols[n.args[1]]
|
| 272 |
+
|
| 273 |
+
if isinstance(e1, TVar) and isinstance(e2, TVar):
|
| 274 |
+
masked_fill_tensor, counter = gen_tvar(counter)
|
| 275 |
+
symbols[n] = masked_fill_tensor
|
| 276 |
+
return gen_broadcasting_constraints(e1, e2, symbols, counter, masked_fill_tensor)
|
| 277 |
+
else:
|
| 278 |
+
raise NotImplementedError('Not yet implemented')
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@register_inference_rule(torch.nn.functional.embedding)
|
| 282 |
+
def embedding_inference_rule_functional(n: Node, symbols, constraints, counter):
|
| 283 |
+
assert isinstance(n.args[0], Node)
|
| 284 |
+
|
| 285 |
+
embedding_dim_weights = symbols[n.args[1]]
|
| 286 |
+
|
| 287 |
+
# will treat this as a static shape. So we will not use matching.
|
| 288 |
+
weight_dims, counter = gen_tensor_dims(2, counter)
|
| 289 |
+
equality_constraint = BinConstraintT(embedding_dim_weights, TensorType(weight_dims), op_eq)
|
| 290 |
+
embedding_dim = weight_dims[1]
|
| 291 |
+
constraints, counter = gen_embedding_rules(n, symbols, embedding_dim, counter)
|
| 292 |
+
return [equality_constraint] + constraints, counter
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@register_inference_rule(torch.nn.modules.sparse.Embedding)
|
| 296 |
+
def embedding_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 297 |
+
"""
|
| 298 |
+
The output shape differs from the input shape in the last dimension
|
| 299 |
+
"""
|
| 300 |
+
assert isinstance(n.args[0], Node)
|
| 301 |
+
return gen_embedding_rules(n, symbols, module_instance.embedding_dim, counter)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def gen_embedding_rules(n: Node, symbols, embedding_dim, counter):
|
| 305 |
+
|
| 306 |
+
embedding_output, counter = gen_tvar(counter)
|
| 307 |
+
symbols[n] = embedding_output
|
| 308 |
+
embedding_input = symbols[n.args[0]]
|
| 309 |
+
|
| 310 |
+
input_dyn = BinConstraintT(embedding_input, Dyn, op_eq)
|
| 311 |
+
output_dyn = BinConstraintT(embedding_output, Dyn, op_eq)
|
| 312 |
+
|
| 313 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 314 |
+
c2 = []
|
| 315 |
+
|
| 316 |
+
for i in range(1, MAX_TENSOR_RANK):
|
| 317 |
+
new_dims, counter = gen_tensor_dims(i, counter)
|
| 318 |
+
nat_constraints = gen_nat_constraints(new_dims)
|
| 319 |
+
|
| 320 |
+
# we consider all tensor sizes and append embedding_dim to the end of the output dimension in all cases
|
| 321 |
+
c_tensor_i = Conj([BinConstraintT(embedding_input, TensorType(new_dims), op_eq),
|
| 322 |
+
BinConstraintT(embedding_output, TensorType(new_dims + [embedding_dim]), op_eq)] +
|
| 323 |
+
nat_constraints)
|
| 324 |
+
c2.append(c_tensor_i)
|
| 325 |
+
|
| 326 |
+
return [Disj([c1, Disj(c2)])], counter
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@register_inference_rule(torch.tensor)
|
| 330 |
+
def tensor_inference_rule(n: Node, symbols, constraints, counter):
|
| 331 |
+
"""
|
| 332 |
+
If the tensor is a scalar, we will skip it since we
|
| 333 |
+
do not support scalars yet. We will add support in the future
|
| 334 |
+
if it's needed. For our examples so far, scalars are not needed.
|
| 335 |
+
"""
|
| 336 |
+
return [], counter
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@register_inference_rule("reshape")
|
| 340 |
+
@register_inference_rule("view")
|
| 341 |
+
def view_inference_rule(n: Node, symbols, constraints, counter):
|
| 342 |
+
"""
|
| 343 |
+
Similar to reshape but with an extra condition on the strides
|
| 344 |
+
"""
|
| 345 |
+
assert isinstance(n.args[0], Node)
|
| 346 |
+
|
| 347 |
+
# generate the new variable
|
| 348 |
+
my_view, counter = gen_tvar(counter)
|
| 349 |
+
symbols[n] = my_view
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
src_var = symbols[n.args[0]]
|
| 353 |
+
t2 = [symbols[elem] if isinstance(elem, Node) else elem for elem in n.args[1:]] # target shape
|
| 354 |
+
t2_type = []
|
| 355 |
+
num_constraints = []
|
| 356 |
+
|
| 357 |
+
for t in t2:
|
| 358 |
+
if t == -1:
|
| 359 |
+
var, counter = gen_dvar(counter)
|
| 360 |
+
t2_type.append(var)
|
| 361 |
+
num_constraints.append(BinConstraintD(var, Dyn, op_neq))
|
| 362 |
+
|
| 363 |
+
else:
|
| 364 |
+
num_constraints.append(BinConstraintD(t, Dyn, op_neq))
|
| 365 |
+
t2_type.append(t)
|
| 366 |
+
|
| 367 |
+
t2_type = TensorType(t2_type) # type: ignore[assignment]
|
| 368 |
+
|
| 369 |
+
c1 = BinConstraintT(my_view, t2_type, op_eq)
|
| 370 |
+
c2 = CanReshape(src_var, t2_type)
|
| 371 |
+
|
| 372 |
+
# TODO: add the extra check mentioned here:
|
| 373 |
+
# https://pytorch.org/docs/stable/generated/torch.Tensor.view.html#torch.Tensor.view
|
| 374 |
+
|
| 375 |
+
return [c1, c2] + num_constraints, counter # type: ignore[operator]
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
@register_inference_rule("size")
|
| 379 |
+
def size_inference_rule(n: Node, symbols, constraints, counter):
|
| 380 |
+
"""
|
| 381 |
+
The constraint is just lhs = rhs.
|
| 382 |
+
Ex: size = input_ids.size()
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
if len(n.args) == 1:
|
| 387 |
+
# generate the new variable
|
| 388 |
+
size, counter = gen_tvar(counter)
|
| 389 |
+
symbols[n] = size
|
| 390 |
+
input = symbols[n.args[0]]
|
| 391 |
+
c = BinConstraintT(input, size, op_eq)
|
| 392 |
+
return [c], counter
|
| 393 |
+
|
| 394 |
+
elif len(n.args) == 2:
|
| 395 |
+
# TODO: review this rule; should input = dyn; output = dyn be included here?
|
| 396 |
+
if isinstance(n.args[1], int):
|
| 397 |
+
# generate the new variable
|
| 398 |
+
size_index, counter = gen_dvar(counter)
|
| 399 |
+
symbols[n] = size_index
|
| 400 |
+
input = symbols[n.args[0]]
|
| 401 |
+
c2 = [GetItem(i + 1, n.args[1], size_index, input) for i in range(MAX_TENSOR_RANK)]
|
| 402 |
+
c3 = BinConstraintD(0, size_index, op_leq)
|
| 403 |
+
|
| 404 |
+
input_dyn = BinConstraintT(input, Dyn, op_eq)
|
| 405 |
+
output_dyn = BinConstraintD(size_index, Dyn, op_eq)
|
| 406 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 407 |
+
|
| 408 |
+
return [Disj([c1, Conj([Disj(c2), c3])])], counter
|
| 409 |
+
|
| 410 |
+
else:
|
| 411 |
+
raise NotImplementedError
|
| 412 |
+
|
| 413 |
+
else:
|
| 414 |
+
raise NotImplementedError
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def range_check(i, n):
|
| 418 |
+
"""
|
| 419 |
+
Checks if an index i is within range of a size n list
|
| 420 |
+
Args:
|
| 421 |
+
i: index
|
| 422 |
+
n: list size
|
| 423 |
+
|
| 424 |
+
Returns: Boolean
|
| 425 |
+
"""
|
| 426 |
+
if i >= 0:
|
| 427 |
+
return T() if i < n else F()
|
| 428 |
+
else:
|
| 429 |
+
return T() if i >= n else F()
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
@register_inference_rule(torch.cumsum)
|
| 433 |
+
def cumsum_inference_rule(n: Node, symbols, constraints, counter):
|
| 434 |
+
"""
|
| 435 |
+
Input and output shapes should be equal
|
| 436 |
+
We should verify that the index is valid
|
| 437 |
+
"""
|
| 438 |
+
assert isinstance(n.args[0], Node)
|
| 439 |
+
arg_1 = n.args[1] if len(n.args) > 1 else n.kwargs["dim"]
|
| 440 |
+
assert isinstance(arg_1, int)
|
| 441 |
+
|
| 442 |
+
output, counter = gen_tvar(counter)
|
| 443 |
+
symbols[n] = output
|
| 444 |
+
input = symbols[n.args[0]]
|
| 445 |
+
|
| 446 |
+
input_dyn = BinConstraintT(input, Dyn, op_eq)
|
| 447 |
+
output_dyn = BinConstraintT(output, Dyn, op_eq)
|
| 448 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 449 |
+
c2 = []
|
| 450 |
+
for i in range(1, MAX_TENSOR_RANK + 1):
|
| 451 |
+
new_dims, counter = gen_tensor_dims(i, counter)
|
| 452 |
+
|
| 453 |
+
nat_constraints = gen_nat_constraints(new_dims)
|
| 454 |
+
|
| 455 |
+
c_tensor_i = Conj([BinConstraintT(input, TensorType(new_dims), op_eq),
|
| 456 |
+
BinConstraintT(output, TensorType(new_dims), op_eq)] +
|
| 457 |
+
[range_check(arg_1, i)] + nat_constraints)
|
| 458 |
+
|
| 459 |
+
c2.append(c_tensor_i)
|
| 460 |
+
dyn_or_tensor = Disj([c1, Disj(c2)])
|
| 461 |
+
return [dyn_or_tensor], counter
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@register_inference_rule(_assert_is_none)
|
| 465 |
+
def assert_inference_rule(n: Node, symbols, constraints, counter):
|
| 466 |
+
assert len(n.users) == 0
|
| 467 |
+
return [], counter
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
@register_inference_rule(operator.getitem)
|
| 471 |
+
def getitem_inference_rule(n: Node, symbols, constraints, counter):
|
| 472 |
+
assert isinstance(n.args[0], Node)
|
| 473 |
+
|
| 474 |
+
# dimension output case
|
| 475 |
+
if isinstance(n.args[1], int):
|
| 476 |
+
# create and store the new dimension variable
|
| 477 |
+
get_item_output, counter = gen_dvar(counter)
|
| 478 |
+
symbols[n] = get_item_output
|
| 479 |
+
|
| 480 |
+
# retrieve arg variables
|
| 481 |
+
get_item_arg = symbols[n.args[0]]
|
| 482 |
+
assert isinstance(get_item_arg, TVar)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# if the input is dynamic, we accept any index and return
|
| 486 |
+
# a dynamic dimension as output
|
| 487 |
+
input_dyn = BinConstraintT(get_item_arg, Dyn, op_eq)
|
| 488 |
+
output_dyn = BinConstraintD(get_item_output, Dyn, op_eq)
|
| 489 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 490 |
+
|
| 491 |
+
# if the input is a tensor,
|
| 492 |
+
# generate a getItem constraint which will be expanded based on the
|
| 493 |
+
# tensor dimension.
|
| 494 |
+
|
| 495 |
+
c2 = [GetItem(i + 1, n.args[1], get_item_output, get_item_arg) for i in range(MAX_TENSOR_RANK)]
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
# since the output is a dimension, we make sure it's a natural number
|
| 499 |
+
# added as a conjunction to the disjunction of c2
|
| 500 |
+
c3 = BinConstraintD(0, get_item_output, op_leq)
|
| 501 |
+
return [Disj([c1, Conj([Disj(c2), c3])])], counter
|
| 502 |
+
|
| 503 |
+
# tensor output case
|
| 504 |
+
elif isinstance(n.args[1], tuple):
|
| 505 |
+
# create and store the new tensor variable
|
| 506 |
+
get_item_output, counter = gen_tvar(counter)
|
| 507 |
+
symbols[n] = get_item_output
|
| 508 |
+
|
| 509 |
+
# retrieve arg variables
|
| 510 |
+
if n.args[0] in symbols:
|
| 511 |
+
get_item_arg = symbols[n.args[0]]
|
| 512 |
+
assert isinstance(get_item_arg, TVar)
|
| 513 |
+
|
| 514 |
+
input_dyn = BinConstraintT(get_item_arg, Dyn, op_eq)
|
| 515 |
+
output_dyn = BinConstraintT(get_item_output, Dyn, op_eq) # type: ignore[assignment]
|
| 516 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 517 |
+
|
| 518 |
+
c2 = [GetItemTensor(i + 1, n.args[1], get_item_output, get_item_arg) # type: ignore[misc]
|
| 519 |
+
for i in range(MAX_TENSOR_RANK)]
|
| 520 |
+
else:
|
| 521 |
+
# TODO: we should figure out why there is a key-error here.
|
| 522 |
+
return [], counter
|
| 523 |
+
|
| 524 |
+
return [Disj([c1, *c2])], counter
|
| 525 |
+
|
| 526 |
+
else:
|
| 527 |
+
raise RuntimeError('Method not yet implemented')
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
@register_inference_rule(operator.gt)
|
| 531 |
+
def gt_inference_rule(n: Node, symbols, constraints, counter):
|
| 532 |
+
assert isinstance(n.args[0], (Node, int))
|
| 533 |
+
assert isinstance(n.args[1], (Node, int))
|
| 534 |
+
|
| 535 |
+
# We make sure this node will not be used again. We do not
|
| 536 |
+
# generate a constraint about that node. Only about the operands.
|
| 537 |
+
|
| 538 |
+
e1 = symbols[n.args[0]] if isinstance(n.args[0], Node) else n.args[0]
|
| 539 |
+
e2 = symbols[n.args[1]] if isinstance(n.args[1], Node) else n.args[1]
|
| 540 |
+
|
| 541 |
+
if isinstance(n.args[0], Node) and isinstance(n.args[1], Node):
|
| 542 |
+
if isinstance(e1, TVar) and isinstance(e2, TVar):
|
| 543 |
+
gt_tensor, counter = gen_tvar(counter)
|
| 544 |
+
symbols[n] = gt_tensor
|
| 545 |
+
return gen_broadcasting_constraints(e1, e2, symbols, counter, gt_tensor)
|
| 546 |
+
|
| 547 |
+
elif isinstance(e1, DVar) and isinstance(e2, DVar):
|
| 548 |
+
# This is meant to be used for flow analysis only
|
| 549 |
+
gt_constraint = BinConstraintD(e1, e2, op_gt)
|
| 550 |
+
|
| 551 |
+
my_gt, counter = gen_bvar(counter)
|
| 552 |
+
equality_constraint = BinConstraintD(my_gt, gt_constraint, op_eq)
|
| 553 |
+
return [equality_constraint], counter
|
| 554 |
+
|
| 555 |
+
else:
|
| 556 |
+
raise RuntimeError('Sort Mismatch')
|
| 557 |
+
|
| 558 |
+
elif isinstance(n.args[0], Node) and not isinstance(n.args[1], Node):
|
| 559 |
+
if isinstance(e1, DVar):
|
| 560 |
+
# This is meant to be used for flow analysis only
|
| 561 |
+
gt_constraint = BinConstraintD(e1, e2, op_gt)
|
| 562 |
+
|
| 563 |
+
my_gt, counter = gen_bvar(counter)
|
| 564 |
+
equality_constraint = BinConstraintD(my_gt, gt_constraint, op_eq)
|
| 565 |
+
return [equality_constraint], counter
|
| 566 |
+
|
| 567 |
+
elif isinstance(e1, TVar) and isinstance(e2, int):
|
| 568 |
+
# then we made the wrong assumption about the argument being a tensor
|
| 569 |
+
# so we should fix the assumption
|
| 570 |
+
warnings.warn(f'Made the wrong assumption for node {n}. Correctness not guaranteed.')
|
| 571 |
+
|
| 572 |
+
new_e1, counter = gen_dvar(counter)
|
| 573 |
+
symbols[n.args[0]] = new_e1
|
| 574 |
+
symbols[n.args[0]]
|
| 575 |
+
|
| 576 |
+
gt_constraint = BinConstraintD(new_e1, e2, op_gt)
|
| 577 |
+
|
| 578 |
+
my_gt, counter = gen_bvar(counter)
|
| 579 |
+
equality_constraint = BinConstraintD(my_gt, gt_constraint, op_eq)
|
| 580 |
+
return [equality_constraint], counter
|
| 581 |
+
|
| 582 |
+
else:
|
| 583 |
+
raise NotImplementedError('Method not yet implemented')
|
| 584 |
+
|
| 585 |
+
else:
|
| 586 |
+
raise NotImplementedError('Method not yet implemented')
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
@register_inference_rule(operator.eq)
|
| 590 |
+
def eq_inference_rule(n: Node, symbols, constraints, counter):
|
| 591 |
+
assert isinstance(n.args[0], (Node, int))
|
| 592 |
+
assert isinstance(n.args[1], (Node, int))
|
| 593 |
+
|
| 594 |
+
e1 = symbols[n.args[0]] if isinstance(n.args[0], Node) else n.args[0]
|
| 595 |
+
e2 = symbols[n.args[1]] if isinstance(n.args[1], Node) else n.args[1]
|
| 596 |
+
|
| 597 |
+
if isinstance(n.args[0], Node) and isinstance(n.args[1], Node):
|
| 598 |
+
if isinstance(e1, TVar) and isinstance(e2, TVar):
|
| 599 |
+
eq_tensor, counter = gen_tvar(counter)
|
| 600 |
+
symbols[n] = eq_tensor
|
| 601 |
+
return gen_broadcasting_constraints(e1, e2, symbols, counter, eq_tensor)
|
| 602 |
+
|
| 603 |
+
elif isinstance(e1, DVar) and isinstance(e2, DVar):
|
| 604 |
+
# This is meant to be used for flow analysis only
|
| 605 |
+
eq_constraint = BinConstraintD(e1, e2, op_eq)
|
| 606 |
+
|
| 607 |
+
my_eq, counter = gen_bvar(counter)
|
| 608 |
+
equality_constraint = BinConstraintD(my_eq, eq_constraint, op_eq)
|
| 609 |
+
return [equality_constraint], counter
|
| 610 |
+
|
| 611 |
+
else:
|
| 612 |
+
raise RuntimeError('Sort Mismatch')
|
| 613 |
+
|
| 614 |
+
elif isinstance(n.args[0], Node) and not isinstance(n.args[1], Node):
|
| 615 |
+
if isinstance(e1, DVar):
|
| 616 |
+
# This is meant to be used for flow analysis only
|
| 617 |
+
eq_constraint = BinConstraintD(e1, e2, op_eq)
|
| 618 |
+
|
| 619 |
+
my_eq, counter = gen_bvar(counter)
|
| 620 |
+
equality_constraint = BinConstraintD(my_eq, eq_constraint, op_eq)
|
| 621 |
+
return [equality_constraint], counter
|
| 622 |
+
else:
|
| 623 |
+
raise NotImplementedError('Method not yet implemented')
|
| 624 |
+
else:
|
| 625 |
+
raise NotImplementedError('Method not yet implemented')
|
| 626 |
+
|
| 627 |
+
@register_inference_rule(operator.ne)
|
| 628 |
+
def neq_inference_rule(n: Node, symbols, constraints, counter):
|
| 629 |
+
"""
|
| 630 |
+
Translates to inconsistent in gradual types.
|
| 631 |
+
To prove inequality, we should prove that
|
| 632 |
+
tensors are either different sizes or
|
| 633 |
+
disagree on at least one dimension
|
| 634 |
+
|
| 635 |
+
This is a WIP (works when the condition
|
| 636 |
+
is false. We are working on making this operation work
|
| 637 |
+
when the condition is true as well)
|
| 638 |
+
"""
|
| 639 |
+
assert isinstance(n.args[0], Node)
|
| 640 |
+
assert isinstance(n.args[1], tuple)
|
| 641 |
+
|
| 642 |
+
# implementing for size 3 and 4
|
| 643 |
+
if len(n.args[1]) == 3:
|
| 644 |
+
|
| 645 |
+
assert isinstance(n.args[1][0], (Node, int))
|
| 646 |
+
assert isinstance(n.args[1][1], (Node, int))
|
| 647 |
+
assert isinstance(n.args[1][2], (Node, int))
|
| 648 |
+
|
| 649 |
+
lhs = symbols[n.args[0]]
|
| 650 |
+
|
| 651 |
+
b, counter = gen_tensor_dims(4, counter)
|
| 652 |
+
input_is_size3 = BinConstraintT(lhs, TensorType([b[0], b[1], b[2]]), op_eq)
|
| 653 |
+
|
| 654 |
+
d1 = n.args[1][0] if isinstance(n.args[1][0], int) else symbols[n.args[1][0]]
|
| 655 |
+
d2 = n.args[1][1] if isinstance(n.args[1][1], int) else symbols[n.args[1][1]]
|
| 656 |
+
d3 = n.args[1][2] if isinstance(n.args[1][2], int) else symbols[n.args[1][2]]
|
| 657 |
+
|
| 658 |
+
# dimensions not equal
|
| 659 |
+
my_ne, counter = gen_bvar(counter)
|
| 660 |
+
neq_1 = BinConstraintD(d1, b[0], op_neq)
|
| 661 |
+
neq_2 = BinConstraintD(d2, b[1], op_neq)
|
| 662 |
+
neq_3 = BinConstraintD(d3, b[2], op_neq)
|
| 663 |
+
|
| 664 |
+
# dimensions inconsistent
|
| 665 |
+
dims_inconsistent1 = Conj([BinConstraintD(d1, Dyn, op_neq), BinConstraintD(b[0], Dyn, op_neq), neq_1])
|
| 666 |
+
dims_inconsistent2 = Conj([BinConstraintD(d2, Dyn, op_neq), BinConstraintD(b[1], Dyn, op_neq), neq_2])
|
| 667 |
+
dims_inconsistent3 = Conj([BinConstraintD(d3, Dyn, op_neq), BinConstraintD(b[2], Dyn, op_neq), neq_3])
|
| 668 |
+
|
| 669 |
+
dims_inconsistent = Disj([dims_inconsistent1, dims_inconsistent2, dims_inconsistent3])
|
| 670 |
+
|
| 671 |
+
# we are covering size 3 and 4 only for now
|
| 672 |
+
ne_constraint = Conj([input_is_size3, dims_inconsistent])
|
| 673 |
+
|
| 674 |
+
my_ne, counter = gen_bvar(counter)
|
| 675 |
+
equality_constraint = BinConstraintD(my_ne, ne_constraint, op_eq)
|
| 676 |
+
|
| 677 |
+
elif len(n.args[1]) == 4:
|
| 678 |
+
|
| 679 |
+
assert isinstance(n.args[1][0], (Node, int))
|
| 680 |
+
assert isinstance(n.args[1][1], (Node, int))
|
| 681 |
+
assert isinstance(n.args[1][2], (Node, int))
|
| 682 |
+
assert isinstance(n.args[1][3], (Node, int))
|
| 683 |
+
|
| 684 |
+
lhs = symbols[n.args[0]]
|
| 685 |
+
|
| 686 |
+
b1, counter = gen_dvar(counter)
|
| 687 |
+
b2, counter = gen_dvar(counter)
|
| 688 |
+
b3, counter = gen_dvar(counter)
|
| 689 |
+
b4, counter = gen_dvar(counter)
|
| 690 |
+
|
| 691 |
+
input_is_size4 = BinConstraintT(lhs, TensorType([b1, b2, b3, b4]), op_eq)
|
| 692 |
+
|
| 693 |
+
d1 = n.args[1][0] if isinstance(n.args[1][0], int) else symbols[n.args[1][0]]
|
| 694 |
+
d2 = n.args[1][1] if isinstance(n.args[1][1], int) else symbols[n.args[1][1]]
|
| 695 |
+
d3 = n.args[1][2] if isinstance(n.args[1][2], int) else symbols[n.args[1][2]]
|
| 696 |
+
d4 = n.args[1][3] if isinstance(n.args[1][3], int) else symbols[n.args[1][3]]
|
| 697 |
+
|
| 698 |
+
# dimensions not equal
|
| 699 |
+
my_ne, counter = gen_bvar(counter)
|
| 700 |
+
neq_1 = BinConstraintD(d1, b1, op_neq)
|
| 701 |
+
neq_2 = BinConstraintD(d2, b2, op_neq)
|
| 702 |
+
neq_3 = BinConstraintD(d3, b3, op_neq)
|
| 703 |
+
neq_4 = BinConstraintD(d4, b4, op_neq)
|
| 704 |
+
|
| 705 |
+
# dimensions to inconsistent
|
| 706 |
+
dims_inconsistent1 = Conj([BinConstraintD(d1, Dyn, op_neq), BinConstraintD(b1, Dyn, op_neq), neq_1])
|
| 707 |
+
dims_inconsistent2 = Conj([BinConstraintD(d2, Dyn, op_neq), BinConstraintD(b2, Dyn, op_neq), neq_2])
|
| 708 |
+
dims_inconsistent3 = Conj([BinConstraintD(d3, Dyn, op_neq), BinConstraintD(b3, Dyn, op_neq), neq_3])
|
| 709 |
+
dims_inconsistent4 = Conj([BinConstraintD(d4, Dyn, op_neq), BinConstraintD(b3, Dyn, op_neq), neq_4])
|
| 710 |
+
|
| 711 |
+
dims_inconsistent = Disj([dims_inconsistent1, dims_inconsistent2, dims_inconsistent3, dims_inconsistent4])
|
| 712 |
+
|
| 713 |
+
ne_constraint = Conj([input_is_size4, dims_inconsistent])
|
| 714 |
+
|
| 715 |
+
my_ne, counter = gen_bvar(counter)
|
| 716 |
+
|
| 717 |
+
equality_constraint = BinConstraintD(my_ne, ne_constraint, op_eq)
|
| 718 |
+
|
| 719 |
+
else:
|
| 720 |
+
raise NotImplementedError('Method not yet implemented')
|
| 721 |
+
|
| 722 |
+
return [equality_constraint], counter
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
@register_inference_rule(operator.lt)
|
| 726 |
+
def lt_inference_rule(n: Node, symbols, constraints, counter):
|
| 727 |
+
assert isinstance(n.args[0], (Node, int))
|
| 728 |
+
assert isinstance(n.args[1], (Node, int))
|
| 729 |
+
|
| 730 |
+
# We make sure this node will not be used again. We do not
|
| 731 |
+
# generate a constraint about that node. Only about the operands.
|
| 732 |
+
|
| 733 |
+
e1 = symbols[n.args[0]] if isinstance(n.args[0], Node) else n.args[0]
|
| 734 |
+
e2 = symbols[n.args[1]] if isinstance(n.args[1], Node) else n.args[1]
|
| 735 |
+
|
| 736 |
+
if isinstance(n.args[0], Node) and isinstance(n.args[1], Node):
|
| 737 |
+
if isinstance(e1, TVar) and isinstance(e2, TVar):
|
| 738 |
+
lt_tensor, counter = gen_tvar(counter)
|
| 739 |
+
symbols[n] = lt_tensor
|
| 740 |
+
return gen_broadcasting_constraints(e1, e2, symbols, counter, lt_tensor)
|
| 741 |
+
|
| 742 |
+
elif isinstance(e1, DVar) and isinstance(e2, DVar):
|
| 743 |
+
# This is meant to be used for flow analysis only
|
| 744 |
+
lt_constraint = BinConstraintD(e1, e2, op_lt)
|
| 745 |
+
|
| 746 |
+
my_lt, counter = gen_bvar(counter)
|
| 747 |
+
equality_constraint = BinConstraintD(my_lt, lt_constraint, op_eq)
|
| 748 |
+
return [equality_constraint], counter
|
| 749 |
+
|
| 750 |
+
else:
|
| 751 |
+
raise RuntimeError('Sort Mismatch')
|
| 752 |
+
|
| 753 |
+
elif isinstance(n.args[0], Node) and not isinstance(n.args[1], Node):
|
| 754 |
+
if isinstance(e1, DVar):
|
| 755 |
+
# This is meant to be used for flow analysis only
|
| 756 |
+
lt_constraint = BinConstraintD(e1, e2, op_lt)
|
| 757 |
+
|
| 758 |
+
my_lt, counter = gen_bvar(counter)
|
| 759 |
+
equality_constraint = BinConstraintD(my_lt, lt_constraint, op_eq)
|
| 760 |
+
return [equality_constraint], counter
|
| 761 |
+
else:
|
| 762 |
+
raise NotImplementedError('Method not yet implemented')
|
| 763 |
+
|
| 764 |
+
else:
|
| 765 |
+
raise NotImplementedError('Method not yet implemented')
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
@register_inference_rule(torch.full)
|
| 769 |
+
def full_inference_rule(n: Node, symbols, constraints, counter):
|
| 770 |
+
full, counter = gen_tvar(counter)
|
| 771 |
+
symbols[n] = full
|
| 772 |
+
res = []
|
| 773 |
+
|
| 774 |
+
assert isinstance(n.args[0], Iterable)
|
| 775 |
+
for arg in n.args[0]:
|
| 776 |
+
dim = arg if isinstance(arg, int) else symbols[arg]
|
| 777 |
+
res.append(dim)
|
| 778 |
+
c = BinConstraintT(full, TensorType(list(res)), op_eq) # type: ignore[arg-type]
|
| 779 |
+
return [c], counter
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
# TODO normalize index
|
| 783 |
+
@register_inference_rule(torch.arange)
|
| 784 |
+
def arange_inference_rule(n: Node, symbols, constraints, counter):
|
| 785 |
+
start = 0
|
| 786 |
+
step = 1
|
| 787 |
+
|
| 788 |
+
if len(n.args) == 1:
|
| 789 |
+
end = symbols[n.args[0]]
|
| 790 |
+
else:
|
| 791 |
+
raise NotImplementedError('Not yet implemented')
|
| 792 |
+
|
| 793 |
+
# int((end - start) / step)
|
| 794 |
+
d1, counter = gen_dvar(counter)
|
| 795 |
+
size_constraint = BinConstraintD(d1, BinConstraintD(BinConstraintD(end, start, op_sub), step, op_div), op_eq)
|
| 796 |
+
arange, counter = gen_tvar(counter)
|
| 797 |
+
symbols[n] = arange
|
| 798 |
+
|
| 799 |
+
# either the a parameter is a number or it is Dyn
|
| 800 |
+
c1 = Disj([BinConstraintD(end, Dyn, op_eq),
|
| 801 |
+
BinConstraintD(start, Dyn, op_eq),
|
| 802 |
+
BinConstraintD(step, Dyn, op_eq)])
|
| 803 |
+
c2 = BinConstraintD(d1, Dyn, op_eq)
|
| 804 |
+
both_dyn = Conj([c1, c2])
|
| 805 |
+
|
| 806 |
+
c11 = Conj([BinConstraintD(end, Dyn, op_neq),
|
| 807 |
+
BinConstraintD(start, Dyn, op_neq),
|
| 808 |
+
BinConstraintD(step, Dyn, op_neq)])
|
| 809 |
+
c22 = BinConstraintD(d1, Dyn, op_neq)
|
| 810 |
+
both_numbers = Conj([c11, c22, size_constraint])
|
| 811 |
+
|
| 812 |
+
return [BinConstraintT(arange, TensorType([d1]), op_eq), Disj([both_dyn, both_numbers])], counter
|
| 813 |
+
|
| 814 |
+
def gen_broadcasting_constraints(e1, e2, symbols, counter, output_var):
|
| 815 |
+
# additional vars that don't correspond to expressions
|
| 816 |
+
e11, counter = gen_tvar(counter)
|
| 817 |
+
e22, counter = gen_tvar(counter)
|
| 818 |
+
|
| 819 |
+
# generate constraints
|
| 820 |
+
c1 = TGreatestUpperBound(output_var, e11, e22)
|
| 821 |
+
c2 = ApplyBroadcasting(e11, e22, e1, e2)
|
| 822 |
+
c3 = BinConstraintT(e11, e22, op_consistency)
|
| 823 |
+
return [c1, c2, c3], counter
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
@register_inference_rule(operator.mul)
|
| 827 |
+
@register_inference_rule(torch.ne)
|
| 828 |
+
@register_inference_rule("ne")
|
| 829 |
+
@register_inference_rule(torch.add)
|
| 830 |
+
@register_inference_rule(operator.add)
|
| 831 |
+
def broadcasting_inference_rule(n: Node, symbols, constraints, counter):
|
| 832 |
+
|
| 833 |
+
op_code = None
|
| 834 |
+
if n.target == operator.add or n.target == torch.add:
|
| 835 |
+
op_code = op_add
|
| 836 |
+
elif n.target == operator.mul:
|
| 837 |
+
op_code = op_mul
|
| 838 |
+
|
| 839 |
+
if isinstance(n.args[0], Node) and isinstance(n.args[1], Node):
|
| 840 |
+
if isinstance(symbols[n.args[0]], TVar) and isinstance(symbols[n.args[1]], TVar):
|
| 841 |
+
my_output, counter = gen_tvar(counter)
|
| 842 |
+
symbols[n] = my_output
|
| 843 |
+
e1 = symbols[n.args[0]]
|
| 844 |
+
e2 = symbols[n.args[1]]
|
| 845 |
+
|
| 846 |
+
return gen_broadcasting_constraints(e1, e2, symbols, counter, my_output)
|
| 847 |
+
else:
|
| 848 |
+
raise NotImplementedError('Method not yet implemented')
|
| 849 |
+
|
| 850 |
+
elif isinstance(n.args[0], Node) and isinstance(n.args[1], (int, float)):
|
| 851 |
+
if isinstance(symbols[n.args[0]], TVar):
|
| 852 |
+
my_output, counter = gen_tvar(counter)
|
| 853 |
+
symbols[n] = my_output
|
| 854 |
+
e1 = symbols[n.args[0]]
|
| 855 |
+
return [BinConstraintT(my_output, e1, op_eq)], counter
|
| 856 |
+
elif isinstance(symbols[n.args[0]], DVar):
|
| 857 |
+
my_output, counter = gen_dvar(counter)
|
| 858 |
+
symbols[n] = my_output
|
| 859 |
+
e1 = symbols[n.args[0]]
|
| 860 |
+
|
| 861 |
+
# we will propagate the runtime value here since this is regular addition
|
| 862 |
+
c = Conj([BinConstraintD(my_output, BinConstraintD(e1, n.args[1], op_code), op_eq),
|
| 863 |
+
BinConstraintD(0, my_output, op_leq)])
|
| 864 |
+
return [c], counter
|
| 865 |
+
|
| 866 |
+
elif isinstance(n.args[1], Node) and isinstance(n.args[0], (int, float)):
|
| 867 |
+
if isinstance(symbols[n.args[1]], TVar):
|
| 868 |
+
my_output, counter = gen_tvar(counter)
|
| 869 |
+
symbols[n] = my_output
|
| 870 |
+
e2 = symbols[n.args[1]]
|
| 871 |
+
return [BinConstraintT(my_output, e2, op_eq)], counter
|
| 872 |
+
elif isinstance(symbols[n.args[1]], DVar):
|
| 873 |
+
my_output, counter = gen_dvar(counter)
|
| 874 |
+
symbols[n] = my_output
|
| 875 |
+
e2 = symbols[n.args[1]]
|
| 876 |
+
|
| 877 |
+
# we will propagate the runtime value here since this is regular addition
|
| 878 |
+
c = Conj([BinConstraintD(my_output, BinConstraintD(e2, n.args[0], op_code), op_eq),
|
| 879 |
+
BinConstraintD(0, my_output, op_leq)])
|
| 880 |
+
return [c], counter
|
| 881 |
+
|
| 882 |
+
else:
|
| 883 |
+
raise NotImplementedError('Method not yet implemented')
|
| 884 |
+
|
| 885 |
+
else:
|
| 886 |
+
# TODO generate add constraints for scalar addition
|
| 887 |
+
raise NotImplementedError('Addition not yet implemented')
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
@register_inference_rule(torch.flatten)
|
| 891 |
+
def flatten_inference_rule(n: Node, symbols, constraints, counter):
|
| 892 |
+
assert isinstance(n.args[0], Node)
|
| 893 |
+
|
| 894 |
+
# generate the new variable
|
| 895 |
+
flattened, counter = gen_tvar(counter)
|
| 896 |
+
symbols[n] = flattened
|
| 897 |
+
|
| 898 |
+
input = symbols[n.args[0]]
|
| 899 |
+
|
| 900 |
+
# set the default start and end dims
|
| 901 |
+
start_dim = 1
|
| 902 |
+
end_dim = -1
|
| 903 |
+
|
| 904 |
+
if len(n.args) > 1:
|
| 905 |
+
assert isinstance(n.args[1], int)
|
| 906 |
+
start_dim = n.args[1]
|
| 907 |
+
|
| 908 |
+
if len(n.args) > 2:
|
| 909 |
+
assert isinstance(n.args[2], int)
|
| 910 |
+
end_dim = n.args[2]
|
| 911 |
+
|
| 912 |
+
c1 = BinConstraintT(input, Dyn, op_eq)
|
| 913 |
+
c2 = BinConstraintT(flattened, Dyn, op_eq)
|
| 914 |
+
both_dyn = Conj([c1, c2])
|
| 915 |
+
|
| 916 |
+
const = []
|
| 917 |
+
for i in range(1, MAX_TENSOR_RANK + 1):
|
| 918 |
+
c, counter = generate_flatten_constraints(start_dim, end_dim, input, flattened, i, counter)
|
| 919 |
+
const.append(c)
|
| 920 |
+
|
| 921 |
+
return [Disj([both_dyn, *const])], counter
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
@register_inference_rule(torch.nn.functional.layer_norm)
|
| 925 |
+
def layer_norm_functional(n: Node, symbols, constraints, counter):
|
| 926 |
+
"""
|
| 927 |
+
We generate the constraint: input = output
|
| 928 |
+
"""
|
| 929 |
+
assert isinstance(n.args[0], Node)
|
| 930 |
+
return gen_layer_norm_constraints(n, n.args[1], symbols, counter)
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
@register_inference_rule(torch.nn.LayerNorm)
|
| 934 |
+
def layer_norm_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 935 |
+
"""
|
| 936 |
+
Input and output shapes should be equal.
|
| 937 |
+
Input should be consistent with the normalized_shape
|
| 938 |
+
"""
|
| 939 |
+
assert isinstance(n.args[0], Node)
|
| 940 |
+
return gen_layer_norm_constraints(n, module_instance.normalized_shape, symbols, counter)
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
def gen_layer_norm_constraints(n: Node, normalized_shape, symbols, counter):
|
| 944 |
+
output, counter = gen_tvar(counter)
|
| 945 |
+
symbols[n] = output
|
| 946 |
+
input = symbols[n.args[0]]
|
| 947 |
+
|
| 948 |
+
input_dyn = BinConstraintT(input, Dyn, op_eq)
|
| 949 |
+
output_dyn = BinConstraintT(output, Dyn, op_eq)
|
| 950 |
+
|
| 951 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 952 |
+
|
| 953 |
+
c2 = []
|
| 954 |
+
for i in range(1, MAX_TENSOR_RANK + 1):
|
| 955 |
+
new_dims_rhs, counter = gen_tensor_dims(i, counter)
|
| 956 |
+
nat_constraints = gen_nat_constraints(new_dims_rhs)
|
| 957 |
+
|
| 958 |
+
c_tensor_i = Conj([BinConstraintT(input, TensorType(new_dims_rhs), op_eq),
|
| 959 |
+
BinConstraintT(output, TensorType(new_dims_rhs), op_eq)] +
|
| 960 |
+
add_layer_norm_constraints(new_dims_rhs, list(normalized_shape)) +
|
| 961 |
+
nat_constraints)
|
| 962 |
+
c2.append(c_tensor_i)
|
| 963 |
+
return [Disj([c1, Disj(c2)])], counter
|
| 964 |
+
|
| 965 |
+
@register_inference_rule(torch.nn.Dropout)
|
| 966 |
+
@register_inference_rule(torch.nn.ReLU)
|
| 967 |
+
def relu_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 968 |
+
"""
|
| 969 |
+
Input and output shapes should be equal.
|
| 970 |
+
"""
|
| 971 |
+
assert isinstance(n.args[0], Node)
|
| 972 |
+
output, counter = gen_tvar(counter)
|
| 973 |
+
symbols[n] = output
|
| 974 |
+
input = symbols[n.args[0]]
|
| 975 |
+
assert isinstance(input, TVar)
|
| 976 |
+
return [BinConstraintT(input, output, op_eq)], counter
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
@register_inference_rule(torch.nn.Linear)
|
| 980 |
+
def linear_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 981 |
+
"""
|
| 982 |
+
Input and output sizes should be the same except for the last dimension
|
| 983 |
+
If the input is Dyn, then so should the output
|
| 984 |
+
"""
|
| 985 |
+
assert isinstance(n.args[0], Node)
|
| 986 |
+
return linear_constraints(n, module_instance.in_features, module_instance.out_features, symbols, counter)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
@register_inference_rule("dim") # type: ignore[attr-defined]
|
| 990 |
+
def torch_dim_inference_rule(n: Node, symbols, constraints, counter):
|
| 991 |
+
assert isinstance(n.args[0], Node)
|
| 992 |
+
my_dim, counter = gen_dvar(counter)
|
| 993 |
+
symbols[n] = my_dim
|
| 994 |
+
input = symbols[n.args[0]]
|
| 995 |
+
|
| 996 |
+
input_dyn = BinConstraintT(input, Dyn, op_eq)
|
| 997 |
+
output_dyn = BinConstraintD(my_dim, Dyn, op_eq)
|
| 998 |
+
|
| 999 |
+
c1 = []
|
| 1000 |
+
|
| 1001 |
+
for i in range(1, MAX_TENSOR_RANK + 1):
|
| 1002 |
+
new_dims_rhs_1, counter = gen_tensor_dims(i, counter)
|
| 1003 |
+
|
| 1004 |
+
c_tensor_i = Conj([BinConstraintT(input, TensorType(new_dims_rhs_1), op_eq),
|
| 1005 |
+
BinConstraintD(my_dim, i, op_eq)])
|
| 1006 |
+
c1.append(c_tensor_i)
|
| 1007 |
+
|
| 1008 |
+
return [Disj([Conj([input_dyn, output_dyn]), Disj(c1)])], counter
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
@register_inference_rule(torch._C._nn.linear) # type: ignore[attr-defined]
|
| 1012 |
+
def torch_linear_inference_rule(n: Node, symbols, constraints, counter):
|
| 1013 |
+
assert isinstance(n.args[0], Node)
|
| 1014 |
+
weight_dims, counter = gen_tensor_dims(2, counter)
|
| 1015 |
+
equality_constraint = BinConstraintT(symbols[n.args[1]], TensorType(weight_dims), op_eq)
|
| 1016 |
+
constraints, counter = linear_constraints(n, weight_dims[1], weight_dims[0], symbols, counter)
|
| 1017 |
+
return [equality_constraint] + constraints, counter
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def linear_constraints(n: Node, in_features, out_features, symbols, counter):
|
| 1021 |
+
linear_output, counter = gen_tvar(counter)
|
| 1022 |
+
symbols[n] = linear_output
|
| 1023 |
+
linear_input = symbols[n.args[0]]
|
| 1024 |
+
|
| 1025 |
+
input_dyn = BinConstraintT(linear_input, Dyn, op_eq)
|
| 1026 |
+
output_dyn = BinConstraintT(linear_output, Dyn, op_eq)
|
| 1027 |
+
|
| 1028 |
+
c1 = Conj([input_dyn, output_dyn])
|
| 1029 |
+
|
| 1030 |
+
c2 = []
|
| 1031 |
+
for i in range(1, MAX_TENSOR_RANK + 1):
|
| 1032 |
+
new_dims_rhs_1, counter = gen_tensor_dims(i, counter)
|
| 1033 |
+
new_dims_rhs_2, counter = gen_tensor_dims(i, counter)
|
| 1034 |
+
|
| 1035 |
+
nat_constraints = gen_nat_constraints(new_dims_rhs_1 + new_dims_rhs_2)
|
| 1036 |
+
|
| 1037 |
+
c_tensor_i = Conj([BinConstraintT(linear_input, TensorType(new_dims_rhs_1), op_eq),
|
| 1038 |
+
BinConstraintT(linear_output, TensorType(new_dims_rhs_2), op_eq)] +
|
| 1039 |
+
add_linear_constraints(new_dims_rhs_1, new_dims_rhs_2, in_features, out_features) +
|
| 1040 |
+
nat_constraints)
|
| 1041 |
+
c2.append(c_tensor_i)
|
| 1042 |
+
return [Disj([c1, Disj(c2)])], counter
|
| 1043 |
+
|
| 1044 |
+
def add_layer_norm_constraints(input_dim, normalized_dim):
|
| 1045 |
+
"""
|
| 1046 |
+
The constraints say that the type has te form: [*, 1024, 1024]
|
| 1047 |
+
while the normalized_dim have the form [1024, 1024]
|
| 1048 |
+
Args:
|
| 1049 |
+
input_dim: Input shape of layer norm
|
| 1050 |
+
normalized_dim: normalized_dim parameter of the module instance
|
| 1051 |
+
|
| 1052 |
+
"""
|
| 1053 |
+
|
| 1054 |
+
# in this case we return false since there's a pattern mismatch
|
| 1055 |
+
if len(normalized_dim) > len(input_dim):
|
| 1056 |
+
return [F()]
|
| 1057 |
+
|
| 1058 |
+
else:
|
| 1059 |
+
constraints = []
|
| 1060 |
+
for i, n in zip(reversed(input_dim), reversed(normalized_dim)):
|
| 1061 |
+
constraints.append(BinConstraintD(i, n, op_consistency))
|
| 1062 |
+
return constraints
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def add_linear_constraints(dims1, dims2, in_features, out_features):
|
| 1066 |
+
assert len(dims1) == len(dims2)
|
| 1067 |
+
constraints = []
|
| 1068 |
+
for i in range(len(dims1)):
|
| 1069 |
+
if i == len(dims1) - 1:
|
| 1070 |
+
constraints.append(BinConstraintD(dims1[i], in_features, op_consistency))
|
| 1071 |
+
constraints.append(BinConstraintD(dims2[i], out_features, op_eq))
|
| 1072 |
+
else:
|
| 1073 |
+
constraints.append(BinConstraintD(dims1[i], dims2[i], op_eq))
|
| 1074 |
+
|
| 1075 |
+
return constraints
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
@register_inference_rule(torch.reshape)
|
| 1079 |
+
def reshape_inference_rule(n: Node, symbols, constraints, counter):
|
| 1080 |
+
assert isinstance(n.args[0], Node)
|
| 1081 |
+
|
| 1082 |
+
# generate the new variable
|
| 1083 |
+
my_reshape, counter = gen_tvar(counter)
|
| 1084 |
+
symbols[n] = my_reshape
|
| 1085 |
+
|
| 1086 |
+
src_var = symbols[n.args[0]]
|
| 1087 |
+
t2 = n.args[1]
|
| 1088 |
+
t2_type = TensorType([Dyn if elem == -1 else elem for elem in t2]) # type: ignore[union-attr]
|
| 1089 |
+
c1 = BinConstraintT(my_reshape, t2_type, op_eq) # type: ignore[union-attr]
|
| 1090 |
+
c2 = CanReshape(src_var, t2_type)
|
| 1091 |
+
|
| 1092 |
+
return [c1, c2], counter
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
@register_inference_rule(BatchNorm2d)
|
| 1096 |
+
def batchnorm_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 1097 |
+
assert isinstance(n.args[0], Node)
|
| 1098 |
+
|
| 1099 |
+
# generate the new variable
|
| 1100 |
+
batchnorm_output, counter = gen_tvar(counter)
|
| 1101 |
+
symbols[n] = batchnorm_output
|
| 1102 |
+
batchnorm_input = symbols[n.args[0]]
|
| 1103 |
+
|
| 1104 |
+
# dim vars
|
| 1105 |
+
d1, counter = gen_dvar(counter)
|
| 1106 |
+
d2, counter = gen_dvar(counter)
|
| 1107 |
+
d3, counter = gen_dvar(counter)
|
| 1108 |
+
d4, counter = gen_dvar(counter)
|
| 1109 |
+
|
| 1110 |
+
nat_constraints = gen_nat_constraints([d1, d2, d3, d4])
|
| 1111 |
+
|
| 1112 |
+
c1 = BinConstraintT(batchnorm_input, TensorType([d1, d2, d3, d4]), op_matching)
|
| 1113 |
+
c2 = BinConstraintT(batchnorm_input, batchnorm_output, op_eq)
|
| 1114 |
+
return [c1, c2, *nat_constraints], counter
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
@register_inference_rule(torch.nn.AdaptiveAvgPool2d)
|
| 1118 |
+
def adaptive_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 1119 |
+
assert isinstance(n.args[0], Node)
|
| 1120 |
+
|
| 1121 |
+
avg_pool, counter = gen_tvar(counter)
|
| 1122 |
+
|
| 1123 |
+
symbols[n] = avg_pool
|
| 1124 |
+
input_var = symbols[n.args[0]]
|
| 1125 |
+
|
| 1126 |
+
# dim vars
|
| 1127 |
+
d1, counter = gen_dvar(counter)
|
| 1128 |
+
d2, counter = gen_dvar(counter)
|
| 1129 |
+
d3, counter = gen_dvar(counter)
|
| 1130 |
+
d4, counter = gen_dvar(counter)
|
| 1131 |
+
nat_constraints = gen_nat_constraints([d1, d2, d3, d4])
|
| 1132 |
+
c1 = BinConstraintT(input_var, TensorType([d1, d2, d3, d4]), op_matching)
|
| 1133 |
+
c2 = BinConstraintT(avg_pool, TensorType([d1, d2, module_instance.output_size[0], module_instance.output_size[1]]), op_eq)
|
| 1134 |
+
|
| 1135 |
+
return [c1, c2, *nat_constraints], counter
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
@register_inference_rule(Conv2d)
|
| 1139 |
+
def conv2d_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 1140 |
+
assert isinstance(n.args[0], Node)
|
| 1141 |
+
|
| 1142 |
+
my_conv, counter = gen_tvar(counter)
|
| 1143 |
+
symbols[n] = my_conv
|
| 1144 |
+
input_var = symbols[n.args[0]]
|
| 1145 |
+
|
| 1146 |
+
# dim vars
|
| 1147 |
+
[d1, d2, d3, d4], counter = gen_tensor_dims(MAX_TENSOR_RANK, counter)
|
| 1148 |
+
|
| 1149 |
+
# c1 = Matching(input_var, TensorType([d1, d2, d3, d4]))
|
| 1150 |
+
c1 = BinConstraintT(input_var, TensorType([d1, d2, d3, d4]), op_matching)
|
| 1151 |
+
|
| 1152 |
+
# c2 = DConsistency(module_instance.in_channels, d2)
|
| 1153 |
+
c2 = BinConstraintD(module_instance.in_channels, d2, op_consistency)
|
| 1154 |
+
|
| 1155 |
+
c3 = CalcConv(my_conv, input_var,
|
| 1156 |
+
module_instance.out_channels,
|
| 1157 |
+
module_instance.kernel_size,
|
| 1158 |
+
module_instance.padding,
|
| 1159 |
+
module_instance.stride,
|
| 1160 |
+
module_instance.dilation, [d1, d2, d3, d4])
|
| 1161 |
+
|
| 1162 |
+
nat_constraints = gen_nat_constraints([d1, d2, d3, d4])
|
| 1163 |
+
|
| 1164 |
+
return [c1, c2, c3, *nat_constraints], counter
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
@register_inference_rule(torch.nn.MaxPool2d)
|
| 1168 |
+
def maxpool_inference_rule(n: Node, module_instance, symbols, constraints, counter):
|
| 1169 |
+
assert isinstance(n.args[0], Node)
|
| 1170 |
+
maxpool, counter = gen_tvar(counter)
|
| 1171 |
+
symbols[n] = maxpool
|
| 1172 |
+
input_var = symbols[n.args[0]]
|
| 1173 |
+
|
| 1174 |
+
# dim vars
|
| 1175 |
+
[d1, d2, d3, d4], counter = gen_tensor_dims(MAX_TENSOR_RANK, counter)
|
| 1176 |
+
|
| 1177 |
+
c1 = BinConstraintT(input_var, TensorType([d1, d2, d3, d4]), op_matching)
|
| 1178 |
+
|
| 1179 |
+
c2 = CalcMaxPool(maxpool, input_var, module_instance.kernel_size, module_instance.padding,
|
| 1180 |
+
module_instance.stride, module_instance.dilation, [d1, d2, d3, d4])
|
| 1181 |
+
|
| 1182 |
+
nat_constraints = gen_nat_constraints([d1, d2, d3, d4])
|
| 1183 |
+
|
| 1184 |
+
return [c1, c2, *nat_constraints], counter
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
class ConstraintGenerator:
|
| 1188 |
+
def __init__(self, traced, graph=None):
|
| 1189 |
+
self.traced = traced # traced or tracer.root
|
| 1190 |
+
self.traced_params = dict(self.traced.named_parameters())
|
| 1191 |
+
self.constraints = []
|
| 1192 |
+
self.symbol_dict = {}
|
| 1193 |
+
self.graph = traced.graph if hasattr(traced, 'graph') else graph
|
| 1194 |
+
|
| 1195 |
+
|
| 1196 |
+
def generate_constraints(self, counter=0):
|
| 1197 |
+
"""
|
| 1198 |
+
Iterate through every node and generate constraints
|
| 1199 |
+
Effect: self.constraints will be populated with the final constraints
|
| 1200 |
+
"""
|
| 1201 |
+
graph = self.graph
|
| 1202 |
+
|
| 1203 |
+
all_constraints = []
|
| 1204 |
+
|
| 1205 |
+
for n in graph.nodes:
|
| 1206 |
+
(constraints, counter) = self.generate_constraints_node(n, counter)
|
| 1207 |
+
all_constraints += constraints
|
| 1208 |
+
|
| 1209 |
+
return Conj(all_constraints), counter
|
| 1210 |
+
|
| 1211 |
+
def generate_constraints_node(self, n: Node, counter):
|
| 1212 |
+
"""
|
| 1213 |
+
Generate constraints the given node:
|
| 1214 |
+
Currently supported operations:
|
| 1215 |
+
- Reshape
|
| 1216 |
+
- Add
|
| 1217 |
+
- conv2d
|
| 1218 |
+
"""
|
| 1219 |
+
|
| 1220 |
+
if n.op == 'placeholder':
|
| 1221 |
+
x, counter = gen_tvar(counter)
|
| 1222 |
+
self.symbol_dict[n] = x
|
| 1223 |
+
|
| 1224 |
+
my_type = n.type
|
| 1225 |
+
|
| 1226 |
+
if n.type != Dyn and (not isinstance(n.type, TensorType)):
|
| 1227 |
+
if n.type == torch.nn.parameter.Parameter:
|
| 1228 |
+
# since we have a parameter, the shape must be static
|
| 1229 |
+
assert 'example_value' in n.meta
|
| 1230 |
+
my_type = TensorType(n.meta['example_value'].size())
|
| 1231 |
+
else:
|
| 1232 |
+
my_type = Dyn
|
| 1233 |
+
|
| 1234 |
+
c1 = BinConstraintT(my_type, x, op_precision)
|
| 1235 |
+
c2 = BinConstraintT(x, MAX_TENSOR_RANK, op_leq)
|
| 1236 |
+
return [c1, c2], counter
|
| 1237 |
+
|
| 1238 |
+
elif n.op == 'call_function':
|
| 1239 |
+
if n.target in _INFERENCE_RULES:
|
| 1240 |
+
return _INFERENCE_RULES[n.target](n, self.symbol_dict, self.constraints, counter)
|
| 1241 |
+
else:
|
| 1242 |
+
raise RuntimeError(f'No inference rule registered for target {n.target}!')
|
| 1243 |
+
|
| 1244 |
+
elif n.op == 'call_module':
|
| 1245 |
+
|
| 1246 |
+
module_instance = self.traced.get_submodule(n.target)
|
| 1247 |
+
if type(module_instance) in _INFERENCE_RULES:
|
| 1248 |
+
return _INFERENCE_RULES[type(module_instance)](n,
|
| 1249 |
+
module_instance,
|
| 1250 |
+
self.symbol_dict,
|
| 1251 |
+
self.constraints, counter)
|
| 1252 |
+
else:
|
| 1253 |
+
raise RuntimeError(f'No inference rule registered for class {type(module_instance)}!')
|
| 1254 |
+
|
| 1255 |
+
elif n.op == 'call_method':
|
| 1256 |
+
if n.target in _INFERENCE_RULES:
|
| 1257 |
+
return _INFERENCE_RULES[n.target](n, self.symbol_dict, self.constraints, counter)
|
| 1258 |
+
else:
|
| 1259 |
+
raise RuntimeError(f'No inference rule registered for target {n.target}!')
|
| 1260 |
+
|
| 1261 |
+
elif n.op == 'get_attr':
|
| 1262 |
+
t = self.traced_params.get(n.target, None)
|
| 1263 |
+
|
| 1264 |
+
if isinstance(t, torch.Tensor):
|
| 1265 |
+
if len(t.shape) > 0:
|
| 1266 |
+
res = list(t.shape)
|
| 1267 |
+
attr_type = TensorType(res)
|
| 1268 |
+
output, counter = gen_tvar(counter)
|
| 1269 |
+
self.symbol_dict[n] = output
|
| 1270 |
+
return [BinConstraintT(output, attr_type, op_eq)], counter
|
| 1271 |
+
else:
|
| 1272 |
+
# scalar?
|
| 1273 |
+
return [], counter
|
| 1274 |
+
else:
|
| 1275 |
+
return [], counter
|
| 1276 |
+
|
| 1277 |
+
elif n.op == 'output':
|
| 1278 |
+
return [], counter
|
| 1279 |
+
|
| 1280 |
+
else:
|
| 1281 |
+
raise NotImplementedError(f"Method {n.op} not yet implemented")
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/operation.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
op_add = '+'
|
| 2 |
+
op_sub = '-'
|
| 3 |
+
op_mul = '*'
|
| 4 |
+
op_div = '/'
|
| 5 |
+
op_eq = '='
|
| 6 |
+
op_neq = '!='
|
| 7 |
+
op_imp = '=>'
|
| 8 |
+
op_matching = '\u22b3' # (contains)
|
| 9 |
+
op_consistency = '~'
|
| 10 |
+
op_precision = '\u2291' # (square image of or equal to)
|
| 11 |
+
op_leq = '\u2264' # less-than or equal to
|
| 12 |
+
op_lt = '<'
|
| 13 |
+
op_gt = '>'
|
| 14 |
+
op_mod = '%'
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/transform_to_z3.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from torch.fx.experimental.migrate_gradual_types.constraint import Conj, Disj, T, F, BinConstraintT, BVar, is_bool_expr
|
| 3 |
+
from torch.fx.experimental.migrate_gradual_types.constraint import BinConstraintD, TVar, DVar
|
| 4 |
+
from torch.fx.experimental.migrate_gradual_types.constraint import Prod, is_algebraic_expression, is_dim
|
| 5 |
+
from torch.fx.experimental.migrate_gradual_types.constraint_generator import ConstraintGenerator
|
| 6 |
+
from torch.fx.experimental.migrate_gradual_types.constraint_transformation import transform_constraint
|
| 7 |
+
from torch.fx.experimental.migrate_gradual_types.operation import op_add, op_eq, op_neq, op_gt, op_lt
|
| 8 |
+
from torch.fx.experimental.migrate_gradual_types.operation import op_leq, op_sub, op_div, op_mul, op_mod
|
| 9 |
+
from torch.fx.tensor_type import TensorType, Dyn
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import z3 # type: ignore[import]
|
| 13 |
+
from torch.fx.experimental.migrate_gradual_types.z3_types import tensor_type, z3_dyn, D
|
| 14 |
+
HAS_Z3 = True
|
| 15 |
+
|
| 16 |
+
def transform_to_z3(constraint, counter, dimension_dict):
|
| 17 |
+
if isinstance(constraint, Conj):
|
| 18 |
+
conjuncts = []
|
| 19 |
+
for c in constraint.conjucts:
|
| 20 |
+
new_c, counter = transform_to_z3(c, counter, dimension_dict)
|
| 21 |
+
conjuncts.append(new_c)
|
| 22 |
+
return z3.And(conjuncts), counter
|
| 23 |
+
|
| 24 |
+
elif isinstance(constraint, Disj):
|
| 25 |
+
disjuncts = []
|
| 26 |
+
for c in constraint.disjuncts:
|
| 27 |
+
new_c, counter = transform_to_z3(c, counter, dimension_dict)
|
| 28 |
+
disjuncts.append(new_c)
|
| 29 |
+
return z3.Or(disjuncts), counter
|
| 30 |
+
|
| 31 |
+
elif isinstance(constraint, T):
|
| 32 |
+
return True, counter
|
| 33 |
+
|
| 34 |
+
elif isinstance(constraint, F):
|
| 35 |
+
return False, counter
|
| 36 |
+
|
| 37 |
+
elif isinstance(constraint, BinConstraintT):
|
| 38 |
+
if constraint.op == op_eq:
|
| 39 |
+
lhs, counter = transform_var(constraint.lhs, counter, dimension_dict)
|
| 40 |
+
rhs, counter = transform_var(constraint.rhs, counter, dimension_dict)
|
| 41 |
+
return (lhs == rhs), counter
|
| 42 |
+
|
| 43 |
+
else:
|
| 44 |
+
raise NotImplementedError('Method not yet implemented')
|
| 45 |
+
|
| 46 |
+
elif isinstance(constraint, BinConstraintD):
|
| 47 |
+
if constraint.op == op_eq:
|
| 48 |
+
|
| 49 |
+
if isinstance(constraint.lhs, BVar) and is_bool_expr(constraint.rhs):
|
| 50 |
+
transformed_rhs, counter = transform_to_z3(constraint.rhs, counter, dimension_dict)
|
| 51 |
+
transformed_lhs = z3.Bool(constraint.lhs.c)
|
| 52 |
+
return transformed_lhs == transformed_rhs, counter
|
| 53 |
+
|
| 54 |
+
elif is_dim(constraint.lhs) and is_dim(constraint.rhs):
|
| 55 |
+
# with dimension transformations we consider the encoding
|
| 56 |
+
lhs, counter = transform_dimension(constraint.lhs, counter, dimension_dict)
|
| 57 |
+
rhs, counter = transform_dimension(constraint.rhs, counter, dimension_dict)
|
| 58 |
+
return lhs == rhs, counter
|
| 59 |
+
|
| 60 |
+
else:
|
| 61 |
+
# then we have an algebraic expression which means that we disregard the
|
| 62 |
+
# first element of the encoding
|
| 63 |
+
lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict)
|
| 64 |
+
rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict)
|
| 65 |
+
return lhs == rhs, counter
|
| 66 |
+
|
| 67 |
+
# The assumption here is that the LHS and RHS must be dimensions
|
| 68 |
+
elif constraint.op == op_neq:
|
| 69 |
+
assert is_dim(constraint.lhs)
|
| 70 |
+
assert is_dim(constraint.rhs)
|
| 71 |
+
lhs, counter = transform_dimension(constraint.lhs, counter, dimension_dict)
|
| 72 |
+
rhs, counter = transform_dimension(constraint.rhs, counter, dimension_dict)
|
| 73 |
+
if constraint.rhs == Dyn or constraint.lhs == Dyn:
|
| 74 |
+
if constraint.rhs == Dyn:
|
| 75 |
+
return lhs.arg(0) == 1, counter
|
| 76 |
+
elif constraint.lhs == Dyn:
|
| 77 |
+
return rhs.arg(0) == 1, counter
|
| 78 |
+
|
| 79 |
+
# if one of the instances is a number
|
| 80 |
+
elif isinstance(constraint.lhs, int) or isinstance(constraint.rhs, int):
|
| 81 |
+
if isinstance(constraint.lhs, int):
|
| 82 |
+
return z3.Or([rhs.arg(0) == 0, z3.And([rhs.arg(0) == 1, lhs.arg(1) != rhs.arg(1)])]), counter
|
| 83 |
+
|
| 84 |
+
elif isinstance(constraint.rhs, int):
|
| 85 |
+
return z3.Or([lhs.arg(0) == 0, z3.And([lhs.arg(0) == 1, lhs.arg(1) != rhs.arg(1)])]), counter
|
| 86 |
+
|
| 87 |
+
else:
|
| 88 |
+
return z3.Or([z3.And([lhs.arg(0) == 0, rhs.arg(0) != 0]),
|
| 89 |
+
z3.And([lhs.arg(0) != 0, rhs.arg(0) == 0]),
|
| 90 |
+
z3.And([lhs.arg(0) != 0, rhs.arg(0) != 0, lhs.arg(1) != rhs.arg(1)])]), counter
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
elif constraint.op == op_leq:
|
| 94 |
+
# if the dimensions are not dyn, this will come into effect
|
| 95 |
+
# there would have been another constraint specifying if a given dimension
|
| 96 |
+
# is dyn or not
|
| 97 |
+
assert is_dim(constraint.lhs) and is_dim(constraint.rhs)
|
| 98 |
+
lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict)
|
| 99 |
+
rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict)
|
| 100 |
+
return lhs <= rhs, counter
|
| 101 |
+
|
| 102 |
+
elif constraint.op == op_gt:
|
| 103 |
+
assert is_dim(constraint.lhs) and is_dim(constraint.rhs)
|
| 104 |
+
lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict)
|
| 105 |
+
rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict)
|
| 106 |
+
return lhs > rhs, counter
|
| 107 |
+
|
| 108 |
+
elif constraint.op == op_lt:
|
| 109 |
+
assert is_dim(constraint.lhs) and is_dim(constraint.rhs)
|
| 110 |
+
lhs, counter = transform_algebraic_expression(constraint.lhs, counter, dimension_dict)
|
| 111 |
+
rhs, counter = transform_algebraic_expression(constraint.rhs, counter, dimension_dict)
|
| 112 |
+
return lhs < rhs, counter
|
| 113 |
+
|
| 114 |
+
else:
|
| 115 |
+
raise NotImplementedError('operation not yet implemented')
|
| 116 |
+
|
| 117 |
+
else:
|
| 118 |
+
raise NotImplementedError('Operation not yet implemented')
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def transform_var(tensor, counter, dimension_dict):
|
| 122 |
+
"""
|
| 123 |
+
Transforms tensor variables to a format understood by z3
|
| 124 |
+
Args:
|
| 125 |
+
tensor: Tensor variable or a tensor type potentially with variable dimensions
|
| 126 |
+
Returns: Transformed variable to a z3 format
|
| 127 |
+
|
| 128 |
+
"""
|
| 129 |
+
if isinstance(tensor, TensorType):
|
| 130 |
+
res = []
|
| 131 |
+
for t in tensor.__args__:
|
| 132 |
+
transformed, counter = transform_dimension(t, counter, dimension_dict)
|
| 133 |
+
res.append(transformed)
|
| 134 |
+
|
| 135 |
+
assert len(res) <= 4
|
| 136 |
+
if len(tensor.__args__) == 1:
|
| 137 |
+
return tensor_type.tensor1(res[0]), counter
|
| 138 |
+
elif len(tensor.__args__) == 2:
|
| 139 |
+
return tensor_type.tensor2(res[0], res[1]), counter
|
| 140 |
+
elif len(tensor.__args__) == 3:
|
| 141 |
+
return tensor_type.tensor3(res[0], res[1], res[2]), counter
|
| 142 |
+
elif len(tensor.__args__) == 4:
|
| 143 |
+
return tensor_type.tensor4(res[0], res[1], res[2], res[3]), counter
|
| 144 |
+
|
| 145 |
+
elif tensor == Dyn:
|
| 146 |
+
return z3_dyn, counter
|
| 147 |
+
|
| 148 |
+
elif isinstance(tensor, TVar):
|
| 149 |
+
return z3.Const(tensor.tvar, tensor_type), counter
|
| 150 |
+
|
| 151 |
+
def transform_dimension(dimension, counter, dimension_dict):
|
| 152 |
+
"""
|
| 153 |
+
Takes a dimension variable or a number and transforms it to a tuple
|
| 154 |
+
according to our scheme
|
| 155 |
+
Args:
|
| 156 |
+
dimension: The dimension to be transformed
|
| 157 |
+
counter: variable tracking
|
| 158 |
+
|
| 159 |
+
Returns: tuple and the current counter
|
| 160 |
+
|
| 161 |
+
"""
|
| 162 |
+
if dimension == Dyn:
|
| 163 |
+
counter += 1
|
| 164 |
+
return D(0, z3.Int(counter)), counter
|
| 165 |
+
elif isinstance(dimension, int):
|
| 166 |
+
return D(1, dimension), counter
|
| 167 |
+
elif isinstance(dimension, DVar):
|
| 168 |
+
if dimension.c in dimension_dict:
|
| 169 |
+
return D(z3.Int(dimension_dict[dimension.c]), z3.Int(dimension.c)), counter
|
| 170 |
+
else:
|
| 171 |
+
counter += 1
|
| 172 |
+
dimension_dict[dimension.c] = counter
|
| 173 |
+
return D(z3.Int(counter), z3.Int(dimension.c)), counter
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def transform_algebraic_expression(expr, counter, dimension_dict):
|
| 177 |
+
"""
|
| 178 |
+
Transforms an algebraic expression to z3 format
|
| 179 |
+
Args:
|
| 180 |
+
expr: An expression is either a dimension variable or an algebraic-expression
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
Returns: the transformed expression
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
assert is_algebraic_expression(expr) or is_dim(expr)
|
| 187 |
+
|
| 188 |
+
if is_dim(expr):
|
| 189 |
+
transformed, counter = transform_dimension(expr, counter, dimension_dict)
|
| 190 |
+
return transformed.arg(1), counter
|
| 191 |
+
|
| 192 |
+
elif isinstance(expr, Prod):
|
| 193 |
+
|
| 194 |
+
dims = []
|
| 195 |
+
for dim in expr.products:
|
| 196 |
+
assert is_dim(dim)
|
| 197 |
+
d, counter = transform_dimension(dim, counter, dimension_dict)
|
| 198 |
+
dims.append(d.arg(1))
|
| 199 |
+
return z3.Product(dims), counter
|
| 200 |
+
|
| 201 |
+
elif is_algebraic_expression(expr):
|
| 202 |
+
|
| 203 |
+
lhs, counter = transform_algebraic_expression(expr.lhs, counter, dimension_dict)
|
| 204 |
+
rhs, counter = transform_algebraic_expression(expr.rhs, counter, dimension_dict)
|
| 205 |
+
|
| 206 |
+
if expr.op == op_sub:
|
| 207 |
+
c = lhs - rhs
|
| 208 |
+
|
| 209 |
+
elif expr.op == op_add:
|
| 210 |
+
c = lhs + rhs
|
| 211 |
+
|
| 212 |
+
elif expr.op == op_div:
|
| 213 |
+
c = lhs / rhs
|
| 214 |
+
|
| 215 |
+
elif expr.op == op_mul:
|
| 216 |
+
c = lhs * rhs
|
| 217 |
+
|
| 218 |
+
elif expr.op == op_mod:
|
| 219 |
+
c = lhs % rhs
|
| 220 |
+
|
| 221 |
+
else:
|
| 222 |
+
raise NotImplementedError('operation not yet implemented')
|
| 223 |
+
|
| 224 |
+
return c, counter
|
| 225 |
+
|
| 226 |
+
else:
|
| 227 |
+
raise RuntimeError
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def transform_all_constraints(traced, counter=0):
|
| 231 |
+
"""
|
| 232 |
+
Given a trace, generates constraints and transforms them to z3 format
|
| 233 |
+
|
| 234 |
+
"""
|
| 235 |
+
dimension_dict = {} # type: ignore[var-annotated]
|
| 236 |
+
|
| 237 |
+
generator = ConstraintGenerator(traced)
|
| 238 |
+
new_constraints, counter = generator.generate_constraints(counter)
|
| 239 |
+
|
| 240 |
+
# print(new_constraints.conjucts[0])
|
| 241 |
+
# print(*new_constraints.conjucts, sep='\n')
|
| 242 |
+
|
| 243 |
+
# transform precision, matching, consistency till obtaining a fixed point
|
| 244 |
+
new_constraints, counter = iterate_till_fixed_point(new_constraints, counter)
|
| 245 |
+
# print(new_constraints)
|
| 246 |
+
# print(new_constraints.conjucts)
|
| 247 |
+
# new_constraints.conjucts = new_constraints.conjucts[:-1]
|
| 248 |
+
# print(*new_constraints.conjucts, sep='\n')
|
| 249 |
+
|
| 250 |
+
transformed, counter = transform_to_z3(new_constraints, counter, dimension_dict)
|
| 251 |
+
# print(transformed)
|
| 252 |
+
return transformed
|
| 253 |
+
|
| 254 |
+
def iterate_till_fixed_point(constraints, counter):
|
| 255 |
+
"""
|
| 256 |
+
Transform constraints till reaching a fixed point
|
| 257 |
+
"""
|
| 258 |
+
old_c = None
|
| 259 |
+
while old_c != constraints:
|
| 260 |
+
old_c = constraints
|
| 261 |
+
constraints, counter = transform_constraint(constraints, counter)
|
| 262 |
+
return constraints, counter
|
| 263 |
+
|
| 264 |
+
def transform_all_constraints_trace_time(tracer_root, graph, node, counter=0):
|
| 265 |
+
"""
|
| 266 |
+
Takes a node and a graph and generates two sets of constraints.
|
| 267 |
+
One set constraints the node's constraints and another set
|
| 268 |
+
constraints the negation of the node's constraints
|
| 269 |
+
Args:
|
| 270 |
+
tracer_root: the root for getting the module instances
|
| 271 |
+
graph: the graph so far in the tracing process
|
| 272 |
+
node: node that represents a conditional
|
| 273 |
+
counter: variable tracking
|
| 274 |
+
|
| 275 |
+
Returns: Two sets of constraints. One with a conjunction with the
|
| 276 |
+
the conditional constraint and the other with a conjunction with
|
| 277 |
+
its negation.
|
| 278 |
+
|
| 279 |
+
"""
|
| 280 |
+
dimension_dict = {} # type: ignore[var-annotated]
|
| 281 |
+
|
| 282 |
+
generator = ConstraintGenerator(tracer_root, graph)
|
| 283 |
+
new_constraints, counter = generator.generate_constraints(counter)
|
| 284 |
+
|
| 285 |
+
condition_constraint = new_constraints.conjucts[-1]
|
| 286 |
+
|
| 287 |
+
# we know the constraint is a conjunction where the last constraint is about the conditional
|
| 288 |
+
# so remove the last constraint
|
| 289 |
+
new_constraints.conjucts = new_constraints.conjucts[:-1]
|
| 290 |
+
|
| 291 |
+
# transform precision, matching, consistency till obtaining a fixed point
|
| 292 |
+
new_constraints, counter = iterate_till_fixed_point(new_constraints, counter)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# since the function returns a list of one element, we get the first element
|
| 296 |
+
# we are only interested in the RHS in this case because the LHS just stores
|
| 297 |
+
# the result
|
| 298 |
+
|
| 299 |
+
# we make sure the constraint is of the form:
|
| 300 |
+
# c = b where b is a boolean expression
|
| 301 |
+
# and we consider b (constraint.rhs) for transformation
|
| 302 |
+
assert isinstance(condition_constraint.lhs, BVar)
|
| 303 |
+
assert is_bool_expr(condition_constraint.rhs)
|
| 304 |
+
condition_constraint_rhs = condition_constraint.rhs
|
| 305 |
+
|
| 306 |
+
# transform the condition constraint
|
| 307 |
+
condition_constraint_rhs, counter = iterate_till_fixed_point(condition_constraint_rhs, counter)
|
| 308 |
+
|
| 309 |
+
transformed, counter = transform_to_z3(new_constraints, counter, dimension_dict)
|
| 310 |
+
|
| 311 |
+
transformed_condition_constraint, counter = transform_to_z3(condition_constraint_rhs, counter, dimension_dict)
|
| 312 |
+
|
| 313 |
+
negation_transformed_condition_constraint = z3.Not(transformed_condition_constraint)
|
| 314 |
+
|
| 315 |
+
return z3.And([transformed, transformed_condition_constraint]), \
|
| 316 |
+
z3.And([transformed, negation_transformed_condition_constraint])
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def evaluate_conditional_with_constraints(tracer_root, graph, node, counter=0, user_constraints=None):
|
| 320 |
+
"""
|
| 321 |
+
Given an IR and a node representing a conditional, evaluate the conditional
|
| 322 |
+
and its negation
|
| 323 |
+
Args:
|
| 324 |
+
tracer_root: Tracer root for module instances
|
| 325 |
+
node: The node to be evaluated
|
| 326 |
+
|
| 327 |
+
Returns: the results of evaluating the condition and the negation with
|
| 328 |
+
the rest of the constraints
|
| 329 |
+
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
transformed_positive, transformed_negative = \
|
| 333 |
+
transform_all_constraints_trace_time(tracer_root, graph, node, counter)
|
| 334 |
+
|
| 335 |
+
s = z3.Solver()
|
| 336 |
+
s.add(transformed_positive)
|
| 337 |
+
if user_constraints is not None:
|
| 338 |
+
s.add(user_constraints)
|
| 339 |
+
condition = s.check()
|
| 340 |
+
|
| 341 |
+
s = z3.Solver()
|
| 342 |
+
s.add(transformed_negative)
|
| 343 |
+
if user_constraints is not None:
|
| 344 |
+
s.add(user_constraints)
|
| 345 |
+
negation = s.check()
|
| 346 |
+
return condition, negation
|
| 347 |
+
|
| 348 |
+
except ImportError:
|
| 349 |
+
HAS_Z3 = False
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/util.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from torch.fx.experimental.migrate_gradual_types.constraint import TVar, DVar, BinConstraintD, \
|
| 3 |
+
BVar
|
| 4 |
+
from torch.fx.experimental.migrate_gradual_types.operation import op_leq
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def gen_tvar(curr):
|
| 8 |
+
"""
|
| 9 |
+
Generate a tensor variable
|
| 10 |
+
:param curr: The current counter
|
| 11 |
+
:return: a tensor variable and the updated counter
|
| 12 |
+
"""
|
| 13 |
+
curr += 1
|
| 14 |
+
return TVar(curr), curr
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def gen_dvar(curr):
|
| 18 |
+
"""
|
| 19 |
+
Generate a dimension variable
|
| 20 |
+
:param curr: the current counter
|
| 21 |
+
:return: a dimension variable and an updated counter
|
| 22 |
+
"""
|
| 23 |
+
curr += 1
|
| 24 |
+
return DVar(curr), curr
|
| 25 |
+
|
| 26 |
+
def gen_bvar(curr):
|
| 27 |
+
"""
|
| 28 |
+
Generate a boolean variable
|
| 29 |
+
:param curr: the current counter
|
| 30 |
+
:return: a boolean variable and an updated counter
|
| 31 |
+
"""
|
| 32 |
+
curr += 1
|
| 33 |
+
return BVar(curr), curr
|
| 34 |
+
|
| 35 |
+
def gen_tensor_dims(n, curr):
|
| 36 |
+
"""
|
| 37 |
+
Generate a list of tensor dimensions
|
| 38 |
+
:param n: the number of dimensions
|
| 39 |
+
:param curr: the current counter
|
| 40 |
+
:return: a list of dimension variables and an updated counter
|
| 41 |
+
"""
|
| 42 |
+
dims = []
|
| 43 |
+
for _ in range(n):
|
| 44 |
+
dvar, curr = gen_dvar(curr)
|
| 45 |
+
dims.append(dvar)
|
| 46 |
+
return dims, curr
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def gen_nat_constraints(list_of_dims):
|
| 50 |
+
"""
|
| 51 |
+
Generate natural number constraints for dimensions
|
| 52 |
+
"""
|
| 53 |
+
return [BinConstraintD(0, d, op_leq) for d in list_of_dims]
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/migrate_gradual_types/z3_types.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import z3 # type: ignore[import]
|
| 3 |
+
HAS_Z3 = True
|
| 4 |
+
# dynamic type
|
| 5 |
+
dyn = z3.DeclareSort('Dyn')
|
| 6 |
+
dyn_type = z3.Const('dyn', dyn)
|
| 7 |
+
|
| 8 |
+
# dimension
|
| 9 |
+
dim = z3.Datatype('dim')
|
| 10 |
+
dim.declare('dim', ('0', z3.IntSort()), ('1', z3.IntSort()))
|
| 11 |
+
dim = dim.create()
|
| 12 |
+
|
| 13 |
+
# tensors
|
| 14 |
+
tensor_type = z3.Datatype('TensorType')
|
| 15 |
+
tensor_type.declare('Dyn', ('dyn', dyn))
|
| 16 |
+
tensor_type.declare('tensor1', ('0', dim))
|
| 17 |
+
tensor_type.declare('tensor2', ('0', dim), ('1', dim))
|
| 18 |
+
tensor_type.declare('tensor3', ('0', dim), ('1', dim), ('2', dim))
|
| 19 |
+
tensor_type.declare('tensor4', ('0', dim), ('1', dim), ('2', dim), ('3', dim))
|
| 20 |
+
tensor_type = tensor_type.create()
|
| 21 |
+
|
| 22 |
+
# create dimension
|
| 23 |
+
D = dim.dim
|
| 24 |
+
|
| 25 |
+
z3_dyn = tensor_type.Dyn(dyn_type)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
except ImportError:
|
| 29 |
+
HAS_Z3 = False
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/normalize.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from typing import Any, Callable, Dict, Tuple, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.fx
|
| 7 |
+
import torch.fx as fx
|
| 8 |
+
from torch.fx import Transformer, Proxy
|
| 9 |
+
from torch.fx.node import Argument, Target, Node, map_aggregate
|
| 10 |
+
from torch.fx.operator_schemas import (
|
| 11 |
+
normalize_module,
|
| 12 |
+
normalize_function,
|
| 13 |
+
create_type_hint,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from .schema_type_annotation import AnnotateTypesWithSchema
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class NormalizeArgs(Transformer):
|
| 20 |
+
"""
|
| 21 |
+
Normalize arguments to Python targets. This means that
|
| 22 |
+
`args/kwargs` will be matched up to the module/functional's
|
| 23 |
+
signature and rewritten to exclusively kwargs in positional order
|
| 24 |
+
if `normalize_to_only_use_kwargs` is true. Also populates default
|
| 25 |
+
values. Does not support positional-only parameters or varargs
|
| 26 |
+
parameters (*args, **kwargs).
|
| 27 |
+
|
| 28 |
+
If the nodes have 'type' metadata, it will use it to disambiguate
|
| 29 |
+
overloads. Otherwise, it will throw an error.
|
| 30 |
+
|
| 31 |
+
Example usage:
|
| 32 |
+
m = torchvision.models.resnet18()
|
| 33 |
+
traced = torch.fx.symbolic_trace(m)
|
| 34 |
+
traced = NormalizeArgs(traced).transform()
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self, module: torch.fx.GraphModule, normalize_to_only_use_kwargs: bool = True
|
| 39 |
+
):
|
| 40 |
+
super().__init__(module)
|
| 41 |
+
self.node_map: Dict[Proxy, Node] = {}
|
| 42 |
+
self.normalize_to_only_use_kwargs = normalize_to_only_use_kwargs
|
| 43 |
+
|
| 44 |
+
def run_node(self, n: Node) -> Any:
|
| 45 |
+
args, kwargs = self.fetch_args_kwargs_from_env(n)
|
| 46 |
+
|
| 47 |
+
def get_type(arg):
|
| 48 |
+
if isinstance(arg, fx.Node):
|
| 49 |
+
return n.meta["type"] if "type" in n.meta else None
|
| 50 |
+
return type(arg)
|
| 51 |
+
|
| 52 |
+
arg_types = map_aggregate(n.args, get_type)
|
| 53 |
+
assert isinstance(arg_types, tuple)
|
| 54 |
+
arg_types = tuple([create_type_hint(i) for i in arg_types])
|
| 55 |
+
kwarg_types = {k: get_type(v) for k, v in kwargs.items()}
|
| 56 |
+
if n.op == "call_function":
|
| 57 |
+
out = self.call_function(n.target, args, kwargs, arg_types, kwarg_types)
|
| 58 |
+
else:
|
| 59 |
+
out = super().run_node(n)
|
| 60 |
+
if n.op != "output":
|
| 61 |
+
self.node_map[out] = n
|
| 62 |
+
out.node.meta = n.meta
|
| 63 |
+
out.node.type = n.type
|
| 64 |
+
return out
|
| 65 |
+
|
| 66 |
+
def call_function(
|
| 67 |
+
self,
|
| 68 |
+
target: Target,
|
| 69 |
+
args: Tuple[Argument, ...],
|
| 70 |
+
kwargs: Dict[str, Any],
|
| 71 |
+
arg_types: Optional[Tuple[Any, ...]] = None,
|
| 72 |
+
kwarg_types: Optional[Dict[str, Any]] = None,
|
| 73 |
+
):
|
| 74 |
+
assert callable(target)
|
| 75 |
+
new_args_and_kwargs = normalize_function(
|
| 76 |
+
target,
|
| 77 |
+
args, # type: ignore[arg-type]
|
| 78 |
+
kwargs,
|
| 79 |
+
arg_types, # type: ignore[arg-type]
|
| 80 |
+
kwarg_types,
|
| 81 |
+
self.normalize_to_only_use_kwargs,
|
| 82 |
+
)
|
| 83 |
+
if new_args_and_kwargs:
|
| 84 |
+
new_args, new_kwargs = new_args_and_kwargs
|
| 85 |
+
return self.tracer.create_proxy(
|
| 86 |
+
"call_function", target, new_args, new_kwargs
|
| 87 |
+
)
|
| 88 |
+
else:
|
| 89 |
+
return super().call_function(target, args, kwargs)
|
| 90 |
+
|
| 91 |
+
def call_module(
|
| 92 |
+
self, target: Target, args: Tuple[Argument, ...], kwargs: Dict[str, Any]
|
| 93 |
+
):
|
| 94 |
+
assert isinstance(target, str)
|
| 95 |
+
new_args_and_kwargs = normalize_module(
|
| 96 |
+
self.module,
|
| 97 |
+
target,
|
| 98 |
+
args, # type: ignore[arg-type]
|
| 99 |
+
kwargs,
|
| 100 |
+
self.normalize_to_only_use_kwargs,
|
| 101 |
+
)
|
| 102 |
+
if new_args_and_kwargs:
|
| 103 |
+
new_args, new_kwargs = new_args_and_kwargs
|
| 104 |
+
return super().call_module(target, new_args, new_kwargs)
|
| 105 |
+
else:
|
| 106 |
+
return super().call_module(target, args, kwargs)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class NormalizeOperators(AnnotateTypesWithSchema):
|
| 110 |
+
"""
|
| 111 |
+
Normalize callsites that are different ways of "spelling" the same
|
| 112 |
+
invocation into a single, canonical call. Currently supports:
|
| 113 |
+
|
| 114 |
+
1. Normalize operators (e.g. operator.add) to the `torch` ops they
|
| 115 |
+
ultimately invoke (e.g. torch.add) when it is possible to statically
|
| 116 |
+
reason that
|
| 117 |
+
|
| 118 |
+
Example usage:
|
| 119 |
+
|
| 120 |
+
m = torchvision.models.resnet18()
|
| 121 |
+
|
| 122 |
+
traced = torch.fx.symbolic_trace(m)
|
| 123 |
+
|
| 124 |
+
traced = NormalizeOperators(traced).transform()
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
binary_magic_method_remap: Dict[
|
| 128 |
+
Callable[[Any, Any], Any], Callable[[Any, Any], Any]
|
| 129 |
+
] = {
|
| 130 |
+
torch.add: operator.add,
|
| 131 |
+
torch.mul: operator.mul,
|
| 132 |
+
torch.sub: operator.sub,
|
| 133 |
+
torch.div: operator.truediv,
|
| 134 |
+
torch.floor_divide: operator.floordiv,
|
| 135 |
+
torch.remainder: operator.mod,
|
| 136 |
+
torch.eq: operator.eq,
|
| 137 |
+
torch.ne: operator.ne,
|
| 138 |
+
torch.lt: operator.lt,
|
| 139 |
+
torch.le: operator.le,
|
| 140 |
+
torch.gt: operator.gt,
|
| 141 |
+
torch.ge: operator.ge,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def call_function(
|
| 145 |
+
self, target: Target, args: Tuple[Argument, ...], kwargs: Dict[str, Any]
|
| 146 |
+
):
|
| 147 |
+
# Normalize operators according to the magic methods implemented on tensors here:
|
| 148 |
+
# https://github.com/pytorch/pytorch/blob/28c5d90b679c6b38bf4183ec99f16d933c2f1bcd/tools/autograd/templates/python_variable_methods.cpp#L1137 # noqa: B950
|
| 149 |
+
|
| 150 |
+
assert callable(target)
|
| 151 |
+
|
| 152 |
+
if target in self.binary_magic_method_remap:
|
| 153 |
+
if len(args) != 2:
|
| 154 |
+
return super().call_function(target, args, kwargs)
|
| 155 |
+
lhs, rhs = args
|
| 156 |
+
|
| 157 |
+
return super().call_function(
|
| 158 |
+
target=self.binary_magic_method_remap[target],
|
| 159 |
+
args=(lhs, rhs),
|
| 160 |
+
kwargs={},
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return super().call_function(target, args, kwargs)
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/optimization.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch.fx as fx
|
| 3 |
+
from torch.fx.node import Argument, Target
|
| 4 |
+
from torch.nn.utils.fusion import fuse_conv_bn_eval
|
| 5 |
+
from typing import Type, Dict, Any, Tuple, Iterable, Optional, List, cast
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from torch.fx.passes.shape_prop import ShapeProp
|
| 10 |
+
import copy
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
import torch.utils.mkldnn as th_mkldnn
|
| 13 |
+
import operator
|
| 14 |
+
import time
|
| 15 |
+
import logging
|
| 16 |
+
from enum import Enum
|
| 17 |
+
|
| 18 |
+
def _parent_name(target : str) -> Tuple[str, str]:
|
| 19 |
+
"""
|
| 20 |
+
Splits a qualname into parent path and last atom.
|
| 21 |
+
For example, `foo.bar.baz` -> (`foo.bar`, `baz`)
|
| 22 |
+
"""
|
| 23 |
+
*parent, name = target.rsplit('.', 1)
|
| 24 |
+
return parent[0] if parent else '', name
|
| 25 |
+
|
| 26 |
+
# Works for length 2 patterns with 2 modules
|
| 27 |
+
def matches_module_pattern(pattern: Iterable[Type], node: fx.Node, modules: Dict[str, Any]):
|
| 28 |
+
if len(node.args) == 0:
|
| 29 |
+
return False
|
| 30 |
+
nodes: Tuple[Any, fx.Node] = (node.args[0], node)
|
| 31 |
+
for expected_type, current_node in zip(pattern, nodes):
|
| 32 |
+
if not isinstance(current_node, fx.Node):
|
| 33 |
+
return False
|
| 34 |
+
if current_node.op != 'call_module':
|
| 35 |
+
return False
|
| 36 |
+
if not isinstance(current_node.target, str):
|
| 37 |
+
return False
|
| 38 |
+
if current_node.target not in modules:
|
| 39 |
+
return False
|
| 40 |
+
if type(modules[current_node.target]) is not expected_type:
|
| 41 |
+
return False
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def replace_node_module(node: fx.Node, modules: Dict[str, Any], new_module: torch.nn.Module):
|
| 46 |
+
assert isinstance(node.target, str)
|
| 47 |
+
parent_name, name = _parent_name(node.target)
|
| 48 |
+
modules[node.target] = new_module
|
| 49 |
+
setattr(modules[parent_name], name, new_module)
|
| 50 |
+
|
| 51 |
+
def fuse(model: torch.nn.Module, inplace=False, no_trace=False) -> torch.nn.Module:
|
| 52 |
+
"""
|
| 53 |
+
Fuses convolution/BN layers for inference purposes. Will deepcopy your
|
| 54 |
+
model by default, but can modify the model inplace as well.
|
| 55 |
+
"""
|
| 56 |
+
patterns = [(nn.Conv1d, nn.BatchNorm1d),
|
| 57 |
+
(nn.Conv2d, nn.BatchNorm2d),
|
| 58 |
+
(nn.Conv3d, nn.BatchNorm3d)]
|
| 59 |
+
if not inplace:
|
| 60 |
+
model = copy.deepcopy(model)
|
| 61 |
+
if not no_trace or not isinstance(model, torch.fx.GraphModule):
|
| 62 |
+
fx_model = fx.symbolic_trace(model)
|
| 63 |
+
else:
|
| 64 |
+
fx_model = model
|
| 65 |
+
modules = dict(fx_model.named_modules())
|
| 66 |
+
new_graph = copy.deepcopy(fx_model.graph)
|
| 67 |
+
|
| 68 |
+
for pattern in patterns:
|
| 69 |
+
for node in new_graph.nodes:
|
| 70 |
+
if matches_module_pattern(pattern, node, modules):
|
| 71 |
+
if len(node.args[0].users) > 1: # Output of conv is used by other nodes
|
| 72 |
+
continue
|
| 73 |
+
conv = modules[node.args[0].target]
|
| 74 |
+
bn = modules[node.target]
|
| 75 |
+
if not bn.track_running_stats:
|
| 76 |
+
continue
|
| 77 |
+
fused_conv = fuse_conv_bn_eval(conv, bn)
|
| 78 |
+
replace_node_module(node.args[0], modules, fused_conv)
|
| 79 |
+
node.replace_all_uses_with(node.args[0])
|
| 80 |
+
new_graph.erase_node(node)
|
| 81 |
+
return fx.GraphModule(fx_model, new_graph)
|
| 82 |
+
|
| 83 |
+
def remove_dropout(model: nn.Module) -> nn.Module:
|
| 84 |
+
"""
|
| 85 |
+
Removes all dropout layers from the module.
|
| 86 |
+
"""
|
| 87 |
+
fx_model = fx.symbolic_trace(model)
|
| 88 |
+
|
| 89 |
+
class DropoutRemover(torch.fx.Transformer):
|
| 90 |
+
def call_module(self, target : Target, args : Tuple[Argument, ...], kwargs : Dict[str, Any]) -> Any:
|
| 91 |
+
if isinstance(self.submodules[target], nn.Dropout):
|
| 92 |
+
assert len(args) == 1
|
| 93 |
+
return args[0]
|
| 94 |
+
else:
|
| 95 |
+
return super().call_module(target, args, kwargs)
|
| 96 |
+
return DropoutRemover(fx_model).transform()
|
| 97 |
+
|
| 98 |
+
def extract_subgraph(orig_module: nn.Module, nodes: List[fx.Node], inputs: List[fx.Node], outputs: List[fx.Node]):
|
| 99 |
+
"""
|
| 100 |
+
Given lists of nodes from an existing graph that represent a subgraph, returns a submodule that executes that subgraph.
|
| 101 |
+
"""
|
| 102 |
+
new_graph = fx.Graph()
|
| 103 |
+
env: Dict[fx.Node, fx.Node] = {}
|
| 104 |
+
for input in inputs:
|
| 105 |
+
new_node = new_graph.placeholder(input.name)
|
| 106 |
+
env[input] = new_node
|
| 107 |
+
for node in nodes:
|
| 108 |
+
new_node = new_graph.node_copy(node, lambda x: env[x])
|
| 109 |
+
env[node] = new_node
|
| 110 |
+
new_graph.output([env[output] for output in outputs])
|
| 111 |
+
new_graph.lint()
|
| 112 |
+
return fx.GraphModule(orig_module, new_graph)
|
| 113 |
+
|
| 114 |
+
mkldnn_supported = [
|
| 115 |
+
nn.Conv2d, nn.Linear, nn.BatchNorm2d, nn.ReLU, nn.MaxPool2d, nn.AvgPool2d, nn.AdaptiveAvgPool2d,
|
| 116 |
+
torch.relu, torch.transpose, torch.sigmoid,
|
| 117 |
+
F.relu, F.avg_pool2d, F.adaptive_avg_pool2d
|
| 118 |
+
]
|
| 119 |
+
# These are operators that may not be convertible into MKLDNN ops (e.g. the
|
| 120 |
+
# args are scalar values). Thus, we only include them in the subgraph if their
|
| 121 |
+
# arguments are already in MKLDNN.
|
| 122 |
+
# TODO: Determine whether this can be removed after type inference.
|
| 123 |
+
mkldnn_supported_unknown = [operator.add, operator.mul]
|
| 124 |
+
mkldnn_map = {
|
| 125 |
+
nn.Conv2d: th_mkldnn.MkldnnConv2d,
|
| 126 |
+
nn.Linear: th_mkldnn.MkldnnLinear,
|
| 127 |
+
nn.BatchNorm2d: lambda a, _: th_mkldnn.MkldnnBatchNorm(a)
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def modules_to_mkldnn(nodes: List[fx.Node], modules: Dict[str, nn.Module]):
|
| 132 |
+
"""
|
| 133 |
+
For each node, if it's a module that can be preconverted into MKLDNN,
|
| 134 |
+
then we do so and create a mapping to allow us to convert from the MKLDNN
|
| 135 |
+
version of the module to the original.
|
| 136 |
+
"""
|
| 137 |
+
old_modules: Dict[nn.Module, nn.Module] = {}
|
| 138 |
+
for node in nodes:
|
| 139 |
+
if node.op == 'call_module':
|
| 140 |
+
assert isinstance(node.target, str)
|
| 141 |
+
cur_module = modules[node.target]
|
| 142 |
+
if type(cur_module) in mkldnn_map:
|
| 143 |
+
new_module = mkldnn_map[type(cur_module)](cur_module, torch.float)
|
| 144 |
+
assert isinstance(new_module, nn.Module)
|
| 145 |
+
old_modules[new_module] = copy.deepcopy(cur_module)
|
| 146 |
+
replace_node_module(node, modules, new_module)
|
| 147 |
+
return old_modules
|
| 148 |
+
|
| 149 |
+
def reset_modules(nodes: List[fx.Node], modules: Dict[str, nn.Module], old_modules: Dict[nn.Module, nn.Module]):
|
| 150 |
+
"""
|
| 151 |
+
Maps each module that's been changed with `modules_to_mkldnn` back to its
|
| 152 |
+
original.
|
| 153 |
+
"""
|
| 154 |
+
for node in nodes:
|
| 155 |
+
if node.op == 'call_module':
|
| 156 |
+
assert (isinstance(node.target, str))
|
| 157 |
+
cur_module = modules[node.target]
|
| 158 |
+
if cur_module in old_modules:
|
| 159 |
+
replace_node_module(node, modules, old_modules[cur_module])
|
| 160 |
+
|
| 161 |
+
class MklSubgraph:
|
| 162 |
+
def __init__(self, fx_graph: fx.Graph):
|
| 163 |
+
self.fx_graph = fx_graph
|
| 164 |
+
self.nodes: List[fx.Node] = []
|
| 165 |
+
self.start_nodes: List[fx.Node] = []
|
| 166 |
+
self.end_nodes: List[fx.Node] = []
|
| 167 |
+
|
| 168 |
+
def gen_mkl_autotuner(example_inputs, iters=10, warmup=1):
|
| 169 |
+
"""
|
| 170 |
+
This generates a heuristic that can be passed into `optimize_for_inference` that
|
| 171 |
+
determines whether a subgraph should be run in MKL by running it with the example_inputs.
|
| 172 |
+
|
| 173 |
+
Example usage:
|
| 174 |
+
heuristic = gen_mkl_autotuner(example_inputs, iters=10)
|
| 175 |
+
fast_model = optimization.optimize_for_inference(model, heuristic)
|
| 176 |
+
"""
|
| 177 |
+
fx_model = None
|
| 178 |
+
old_modules = None
|
| 179 |
+
|
| 180 |
+
def use_mkl_heuristic(graph: MklSubgraph) -> bool:
|
| 181 |
+
nonlocal fx_model, old_modules
|
| 182 |
+
input_nodes = graph.start_nodes
|
| 183 |
+
if fx_model is None:
|
| 184 |
+
fx_model = graph.fx_graph.owning_module
|
| 185 |
+
old_modules = graph.fx_graph.old_modules # type: ignore[attr-defined]
|
| 186 |
+
ShapeProp(fx_model).propagate(example_inputs)
|
| 187 |
+
sample_inputs = [torch.randn(node.shape) for node in input_nodes] # type: ignore[attr-defined]
|
| 188 |
+
output_args = cast(List[fx.Node], [node.args[0] for node in graph.end_nodes])
|
| 189 |
+
submodule = extract_subgraph(fx_model, graph.nodes, input_nodes, output_args)
|
| 190 |
+
|
| 191 |
+
def benchmark(f):
|
| 192 |
+
for _ in range(warmup):
|
| 193 |
+
f()
|
| 194 |
+
begin = time.time()
|
| 195 |
+
for _ in range(iters):
|
| 196 |
+
out = f()
|
| 197 |
+
return time.time() - begin
|
| 198 |
+
|
| 199 |
+
mkl_time = benchmark(lambda: [i.to_dense() for i in submodule(*[i.to_mkldnn() for i in sample_inputs])])
|
| 200 |
+
|
| 201 |
+
reset_modules(submodule.graph.nodes, dict(submodule.named_modules()), old_modules)
|
| 202 |
+
no_mkl_time = benchmark(lambda: submodule(*sample_inputs))
|
| 203 |
+
return mkl_time < no_mkl_time
|
| 204 |
+
return use_mkl_heuristic
|
| 205 |
+
|
| 206 |
+
def use_mkl_length(graph: MklSubgraph) -> bool:
|
| 207 |
+
"""
|
| 208 |
+
This is a heuristic that can be passed into `optimize_for_inference` that
|
| 209 |
+
determines whether a subgraph should be run in MKL by checking if there
|
| 210 |
+
are more than 2 nodes in it
|
| 211 |
+
"""
|
| 212 |
+
return len(graph.nodes) > 2
|
| 213 |
+
|
| 214 |
+
class UnionFind:
|
| 215 |
+
def __init__(self, n):
|
| 216 |
+
self.parent: List[Optional[int]] = [None] * n
|
| 217 |
+
self.size: List[int] = [0] * n
|
| 218 |
+
|
| 219 |
+
def make_set(self, v: int):
|
| 220 |
+
self.parent[v] = v
|
| 221 |
+
self.size[v] = 1
|
| 222 |
+
|
| 223 |
+
def find(self, v: int) -> int:
|
| 224 |
+
par = self.parent[v]
|
| 225 |
+
if v == par:
|
| 226 |
+
return v
|
| 227 |
+
assert par is not None
|
| 228 |
+
self.parent[v] = self.find(par)
|
| 229 |
+
return cast(int, self.parent[v])
|
| 230 |
+
|
| 231 |
+
def join(self, a: int, b: int):
|
| 232 |
+
a, b = self.find(a), self.find(b)
|
| 233 |
+
if a == b:
|
| 234 |
+
return a
|
| 235 |
+
if self.size[a] < self.size[b]:
|
| 236 |
+
a, b = b, a
|
| 237 |
+
self.parent[b] = a
|
| 238 |
+
self.size[a] += self.size[b]
|
| 239 |
+
|
| 240 |
+
def optimize_for_inference(
|
| 241 |
+
model: torch.nn.Module,
|
| 242 |
+
pass_config: Optional[Dict[str, Any]] = None,
|
| 243 |
+
tracer: Type[fx.Tracer] = fx.Tracer
|
| 244 |
+
) -> torch.nn.Module:
|
| 245 |
+
"""
|
| 246 |
+
Performs a set of optimization passes to optimize a model for the
|
| 247 |
+
purposes of inference. Specifically, the passes that are run are:
|
| 248 |
+
1. Conv/BN fusion
|
| 249 |
+
2. Dropout removal
|
| 250 |
+
3. MKL layout optimizations
|
| 251 |
+
|
| 252 |
+
The third optimization takes a function `use_mkl_heuristic` that's used
|
| 253 |
+
to determine whether a subgraph should be explicitly run in MKL layout.
|
| 254 |
+
|
| 255 |
+
Note: As FX does not currently handle aliasing, this pass currently
|
| 256 |
+
assumes nothing aliases. If that isn't true, use at your own risk.
|
| 257 |
+
"""
|
| 258 |
+
default_pass_config = {
|
| 259 |
+
"conv_bn_fuse": True,
|
| 260 |
+
"remove_dropout": True,
|
| 261 |
+
"mkldnn_layout_optimize": {'heuristic': use_mkl_length},
|
| 262 |
+
}
|
| 263 |
+
if pass_config is None:
|
| 264 |
+
pass_config = {}
|
| 265 |
+
default_pass_config.update(pass_config)
|
| 266 |
+
|
| 267 |
+
if default_pass_config["conv_bn_fuse"]:
|
| 268 |
+
model = fuse(model)
|
| 269 |
+
if default_pass_config["remove_dropout"]:
|
| 270 |
+
model = remove_dropout(model)
|
| 271 |
+
if default_pass_config["mkldnn_layout_optimize"] is False:
|
| 272 |
+
return model
|
| 273 |
+
if not isinstance(default_pass_config["mkldnn_layout_optimize"], dict):
|
| 274 |
+
raise RuntimeError("mkldnn_layout_optimize config is not a dict")
|
| 275 |
+
if "heuristic" not in default_pass_config["mkldnn_layout_optimize"]:
|
| 276 |
+
raise RuntimeError("Heuristic not found in mkldnn_layout_optimize config")
|
| 277 |
+
use_mkl_heuristic = default_pass_config["mkldnn_layout_optimize"]["heuristic"]
|
| 278 |
+
|
| 279 |
+
cur_tracer = tracer()
|
| 280 |
+
fx_graph = cur_tracer.trace(copy.deepcopy(model))
|
| 281 |
+
fx_model = fx.GraphModule(cur_tracer.root, fx_graph)
|
| 282 |
+
modules: Dict[str, nn.Module] = dict(model.named_modules())
|
| 283 |
+
|
| 284 |
+
class MklSupport(Enum):
|
| 285 |
+
NO = 1
|
| 286 |
+
YES = 2
|
| 287 |
+
UNKNOWN = 3
|
| 288 |
+
|
| 289 |
+
# Inserts to_mkldnn and to_dense around every node we want to be a MKLDNN node.
|
| 290 |
+
# If the op is in `mkldnn_supported` then we always treat it as a MKLDNN node.
|
| 291 |
+
# However, if it's in `mkldnn_supported_unknown`, then we only treat it as
|
| 292 |
+
# a MKLDNN node if its inputs are MKLDNN nodes.
|
| 293 |
+
for node in list(fx_graph.nodes):
|
| 294 |
+
supports_mkldnn = MklSupport.NO
|
| 295 |
+
if node.op == 'call_module':
|
| 296 |
+
cur_module = modules[node.target]
|
| 297 |
+
if type(cur_module) in mkldnn_supported:
|
| 298 |
+
supports_mkldnn = MklSupport.YES
|
| 299 |
+
sample_parameter = next(cur_module.parameters(), None)
|
| 300 |
+
if sample_parameter is not None:
|
| 301 |
+
assert sample_parameter.dtype == torch.float, "this pass is only for torch.float modules"
|
| 302 |
+
assert sample_parameter.device == torch.device('cpu'), "this pass is only for CPU modules"
|
| 303 |
+
elif node.op == 'call_function':
|
| 304 |
+
if node.target in mkldnn_supported:
|
| 305 |
+
supports_mkldnn = MklSupport.YES
|
| 306 |
+
elif node.target in mkldnn_supported_unknown:
|
| 307 |
+
supports_mkldnn = MklSupport.UNKNOWN
|
| 308 |
+
|
| 309 |
+
if supports_mkldnn != MklSupport.NO:
|
| 310 |
+
if supports_mkldnn == MklSupport.UNKNOWN:
|
| 311 |
+
if not any(arg.target == 'to_dense' for arg in node.args):
|
| 312 |
+
continue
|
| 313 |
+
with fx_graph.inserting_before(node):
|
| 314 |
+
mkldnn_args = fx.map_arg(node.args, lambda n: fx_graph.call_method('to_mkldnn', (n, )))
|
| 315 |
+
|
| 316 |
+
node.args = cast(Tuple[fx.node.Argument], mkldnn_args)
|
| 317 |
+
|
| 318 |
+
with fx_graph.inserting_after(node):
|
| 319 |
+
dense_x = fx_graph.create_node('call_method', 'to_dense', (node,))
|
| 320 |
+
node.replace_all_uses_with(dense_x)
|
| 321 |
+
dense_x.args = (node,)
|
| 322 |
+
|
| 323 |
+
# Does pre-conversion of all modules into MKLDNN (when possible)
|
| 324 |
+
old_modules = modules_to_mkldnn(list(fx_graph.nodes), modules)
|
| 325 |
+
fx_graph.old_modules = old_modules # type: ignore[attr-defined]
|
| 326 |
+
|
| 327 |
+
# optimizes all a -> to_dense -> to_mkldnn -> b patterns into a -> b
|
| 328 |
+
for node in fx_graph.nodes:
|
| 329 |
+
if node.op == 'call_method' and node.target == 'to_dense':
|
| 330 |
+
prv_node = node.args[0]
|
| 331 |
+
users = list(node.users)
|
| 332 |
+
for user in users:
|
| 333 |
+
if user.op == 'call_method' and user.target == 'to_mkldnn':
|
| 334 |
+
user.replace_all_uses_with(prv_node)
|
| 335 |
+
fx_graph.erase_node(user)
|
| 336 |
+
if len(node.users) == 0:
|
| 337 |
+
fx_graph.erase_node(node)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
num_nodes = len(fx_graph.nodes)
|
| 341 |
+
uf = UnionFind(num_nodes)
|
| 342 |
+
|
| 343 |
+
def get_color(n):
|
| 344 |
+
if hasattr(n, 'color'): # Current node is part of a MKL subgraph
|
| 345 |
+
return uf.find(n.color)
|
| 346 |
+
if hasattr(n, 'start_color'): # Current node is input to MKL subgraph
|
| 347 |
+
return uf.find(n.start_color)
|
| 348 |
+
return None
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# This code is to find each MKLDNN subgraph. Each MKLDNN subgraph consists
|
| 352 |
+
# of input nodes (which are only `to_mkldnn` calls), output nodes
|
| 353 |
+
# (`to_dense` calls), and intermediate nodes, which are run entirely on
|
| 354 |
+
# MKLDNN layout tensors.
|
| 355 |
+
#
|
| 356 |
+
# Specifically, this code does a flood fill on a directed acyclic graph
|
| 357 |
+
# (DAG), starting from each possible "start node" (i.e: `to_mkldnn` nodes).
|
| 358 |
+
# If every node only had one input, this would be sufficient. However, in
|
| 359 |
+
# the case that a node has multiple inputs coming from different start
|
| 360 |
+
# nodes (i.e. colors), we need to join these 2 colors into 1. That's done
|
| 361 |
+
# using a Disjoint Set Union.
|
| 362 |
+
for cur_idx, node in enumerate(fx_graph.nodes):
|
| 363 |
+
if node.op == 'call_method' and node.target == 'to_mkldnn':
|
| 364 |
+
node.start_color = cur_idx
|
| 365 |
+
uf.make_set(cur_idx)
|
| 366 |
+
elif node.op == 'call_method' and node.target == 'to_dense':
|
| 367 |
+
assert get_color(node.args[0]) is not None
|
| 368 |
+
node.end_color = get_color(node.args[0])
|
| 369 |
+
else:
|
| 370 |
+
cur_colors = [get_color(i) for i in node.all_input_nodes if isinstance(i, fx.Node) if get_color(i) is not None]
|
| 371 |
+
|
| 372 |
+
if len(cur_colors) == 0:
|
| 373 |
+
continue
|
| 374 |
+
assert not any(i is None for i in cur_colors)
|
| 375 |
+
cur_colors = sorted(cur_colors)
|
| 376 |
+
node.color = cur_colors[0]
|
| 377 |
+
for other_color in cur_colors[1:]:
|
| 378 |
+
uf.join(cur_colors[0], other_color)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
mkldnn_graphs: Dict[int, MklSubgraph] = defaultdict(lambda: MklSubgraph(fx_graph))
|
| 382 |
+
for node in fx_graph.nodes:
|
| 383 |
+
if hasattr(node, 'color'):
|
| 384 |
+
mkldnn_graphs[uf.find(node.color)].nodes.append(node)
|
| 385 |
+
if hasattr(node, 'start_color'):
|
| 386 |
+
mkldnn_graphs[uf.find(node.start_color)].start_nodes.append(node)
|
| 387 |
+
if hasattr(node, 'end_color'):
|
| 388 |
+
mkldnn_graphs[uf.find(node.end_color)].end_nodes.append(node)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# Now that we have all the subgraphs, we need to decide which MKLDNN
|
| 392 |
+
# subgraphs we actually want to keep in MKLDNN.
|
| 393 |
+
for graph in mkldnn_graphs.values():
|
| 394 |
+
if not use_mkl_heuristic(graph):
|
| 395 |
+
for node in graph.start_nodes + graph.end_nodes:
|
| 396 |
+
prv = node.args[0]
|
| 397 |
+
node.replace_all_uses_with(prv)
|
| 398 |
+
fx_graph.erase_node(node)
|
| 399 |
+
reset_modules(graph.nodes, modules, old_modules)
|
| 400 |
+
|
| 401 |
+
mkldnn_conversions = 0
|
| 402 |
+
for node in fx_graph.nodes:
|
| 403 |
+
if node.target == 'to_mkldnn' or node.target == 'to_dense':
|
| 404 |
+
mkldnn_conversions += 1
|
| 405 |
+
|
| 406 |
+
logging.getLogger(__name__).info("mkldnn conversions: %s", mkldnn_conversions)
|
| 407 |
+
fx_graph.lint()
|
| 408 |
+
result = fx.GraphModule(model, fx_graph)
|
| 409 |
+
return result
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/partitioner_utils.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from enum import Enum
|
| 3 |
+
from typing import NamedTuple, Dict, List, Set
|
| 4 |
+
|
| 5 |
+
from torch.fx.node import Node, map_arg
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Partition:
|
| 9 |
+
"""Partition class contains all the information about an individual partition.
|
| 10 |
+
It also provides necessary methods for manipulation the partition.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __init__(self, partition_id: int) -> None:
|
| 14 |
+
self.nodes: Set[Node] = set()
|
| 15 |
+
self.partition_id = partition_id
|
| 16 |
+
self.parents: Set[Partition] = set()
|
| 17 |
+
self.children: Set[Partition] = set()
|
| 18 |
+
self.bfs_level: int = -1
|
| 19 |
+
self.used_mem_bytes: int = 0
|
| 20 |
+
self.logical_device_ids: List[int] = []
|
| 21 |
+
|
| 22 |
+
def __str__(self):
|
| 23 |
+
return str(self.partition_id)
|
| 24 |
+
|
| 25 |
+
def recalculate_mem_size(self):
|
| 26 |
+
self.used_mem_bytes = 0
|
| 27 |
+
for node in self.nodes:
|
| 28 |
+
self.used_mem_bytes += get_extra_size_of(node, self.nodes)
|
| 29 |
+
|
| 30 |
+
def add_node(self, node):
|
| 31 |
+
input_nodes: Dict[Node, None] = {}
|
| 32 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 33 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 34 |
+
# Add current node's input nodes if they are placeholder or constants
|
| 35 |
+
for n in input_nodes:
|
| 36 |
+
if n.op in {"placeholder", "get_attr"}:
|
| 37 |
+
self.nodes.add(n)
|
| 38 |
+
self.nodes.add(node)
|
| 39 |
+
self.recalculate_mem_size()
|
| 40 |
+
|
| 41 |
+
def remove_node(self, node):
|
| 42 |
+
# Remove a node only if the node is in the partition
|
| 43 |
+
if node in self.nodes:
|
| 44 |
+
self.nodes.remove(node)
|
| 45 |
+
# Collect the node's input nodes
|
| 46 |
+
input_nodes: Dict[Node, None] = {}
|
| 47 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 48 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 49 |
+
# Check if an input node is a placeholder or get_attr,
|
| 50 |
+
# and this input node is not used by some other nodes in this partition,
|
| 51 |
+
# the remove this input node
|
| 52 |
+
for input_node in input_nodes:
|
| 53 |
+
if all(
|
| 54 |
+
n not in self.nodes for n in input_node.users
|
| 55 |
+
) and input_node.op in {"placeholder", "get_attr"}:
|
| 56 |
+
self.nodes.remove(input_node)
|
| 57 |
+
self.recalculate_mem_size()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Device(NamedTuple):
|
| 61 |
+
name: str
|
| 62 |
+
available_mem_bytes: int
|
| 63 |
+
logical_id: int
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class NodeLatency(NamedTuple):
|
| 67 |
+
# Latency due to the memory bandwidth
|
| 68 |
+
mem_latency_sec: float
|
| 69 |
+
# Latency due to the computation
|
| 70 |
+
computer_latency_sec: float
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PartitionLatency(NamedTuple):
|
| 74 |
+
# Sum of all nodes' memory latency on the critical path
|
| 75 |
+
mem_latency_sec: float
|
| 76 |
+
# Sum of all nodes' compute latency on the critical path
|
| 77 |
+
computer_latency_sec: float
|
| 78 |
+
# Latency of the critical path
|
| 79 |
+
overall_latency_sec: float
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class PartitionMode(Enum):
|
| 83 |
+
size_based = 0
|
| 84 |
+
sparse_nn = 1
|
| 85 |
+
cost_aware = 2
|
| 86 |
+
kl_based = 3
|
| 87 |
+
aot_based = 4
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class PartitionerConfig(NamedTuple):
|
| 91 |
+
devices: List[Device]
|
| 92 |
+
mode: PartitionMode = PartitionMode.size_based
|
| 93 |
+
transfer_rate_bytes_per_sec: float = 0.0
|
| 94 |
+
node_to_latency_mapping: Dict[Node, NodeLatency] = {}
|
| 95 |
+
node_to_partition_mapping: Dict[Node, int] = {}
|
| 96 |
+
partition_to_logical_device_mapping: Dict[int, List[int]] = {}
|
| 97 |
+
# Saturate host by replicating partitions to the remaining idle devices.
|
| 98 |
+
saturate_host: bool = False
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def get_extra_size_of(node: Node, nodes: Set[Node]) -> int:
|
| 102 |
+
"""Given a node and a set of nodes,
|
| 103 |
+
this function return the extra size that needed
|
| 104 |
+
if this node is included in this set.
|
| 105 |
+
"""
|
| 106 |
+
# Find all its input nodes
|
| 107 |
+
input_nodes: Dict[Node, None] = {}
|
| 108 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 109 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 110 |
+
# Calculate total size of related nodes
|
| 111 |
+
total_size_of_input_nodes = 0
|
| 112 |
+
for n in input_nodes:
|
| 113 |
+
# Make sure this node hasn't been in this set yet
|
| 114 |
+
if n not in nodes:
|
| 115 |
+
size_bytes = getattr(n, "size_bytes", None)
|
| 116 |
+
if size_bytes:
|
| 117 |
+
total_size_of_input_nodes += size_bytes.output_size
|
| 118 |
+
else:
|
| 119 |
+
raise RuntimeError("node has no size_bytes attr")
|
| 120 |
+
# Don't forget the op node itself
|
| 121 |
+
size_bytes = getattr(node, "size_bytes", None)
|
| 122 |
+
if size_bytes:
|
| 123 |
+
total_size_of_input_nodes += size_bytes.total_size
|
| 124 |
+
else:
|
| 125 |
+
raise RuntimeError("node has no size_bytes attr")
|
| 126 |
+
return total_size_of_input_nodes
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_latency_of_one_partition(
|
| 130 |
+
partition: Partition, node_to_latency_mapping: Dict[Node, NodeLatency]
|
| 131 |
+
) -> PartitionLatency:
|
| 132 |
+
"""Given a partition and its nodes' latency, return a PartitionLatency for this partition"""
|
| 133 |
+
|
| 134 |
+
def get_top_nodes(partition: Partition) -> List[Node]:
|
| 135 |
+
"""Given a partition, return a list of nodes on the top bfs level"""
|
| 136 |
+
top_nodes: List[Node] = []
|
| 137 |
+
for node in partition.nodes:
|
| 138 |
+
# Skip placeholder and get_attr nodes
|
| 139 |
+
if node.op in {"placeholder", "get_attr"}:
|
| 140 |
+
continue
|
| 141 |
+
input_nodes: Dict[Node, None] = {}
|
| 142 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 143 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 144 |
+
# If a node has no input nodes in this partition,
|
| 145 |
+
# or its input nodes in this partition are placeholders and get_attrs
|
| 146 |
+
# this node is on the top bfs level in this partition
|
| 147 |
+
if not any(
|
| 148 |
+
n in partition.nodes and n.op not in {"placeholder", "get_attr"}
|
| 149 |
+
for n in input_nodes
|
| 150 |
+
):
|
| 151 |
+
top_nodes.append(node)
|
| 152 |
+
return top_nodes
|
| 153 |
+
|
| 154 |
+
def dfs_helper(node: Node, partition_latency) -> PartitionLatency:
|
| 155 |
+
"""Given a top node of a partition, this function returns
|
| 156 |
+
the latency of the critical path in the partition
|
| 157 |
+
"""
|
| 158 |
+
node_latency = node_to_latency_mapping[node]
|
| 159 |
+
# Calculate the current overall latency of the partition
|
| 160 |
+
overall_latency_sec = partition_latency.overall_latency_sec + max(
|
| 161 |
+
node_latency.computer_latency_sec, node_latency.mem_latency_sec
|
| 162 |
+
)
|
| 163 |
+
# Update the mem latency of this path
|
| 164 |
+
mem_latency_sec = (
|
| 165 |
+
partition_latency.mem_latency_sec + node_latency.mem_latency_sec
|
| 166 |
+
)
|
| 167 |
+
# Update the compute latency of this path
|
| 168 |
+
computer_latency_sec = (
|
| 169 |
+
partition_latency.computer_latency_sec + node_latency.computer_latency_sec
|
| 170 |
+
)
|
| 171 |
+
# Get all users of this node that are in this partition
|
| 172 |
+
users = set(node.users).intersection(partition.nodes)
|
| 173 |
+
if users:
|
| 174 |
+
max_latency = PartitionLatency(
|
| 175 |
+
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
|
| 176 |
+
)
|
| 177 |
+
for n in users:
|
| 178 |
+
# Get new partition latency recursively
|
| 179 |
+
new_partition_latency = dfs_helper(
|
| 180 |
+
n,
|
| 181 |
+
PartitionLatency(
|
| 182 |
+
mem_latency_sec, computer_latency_sec, overall_latency_sec
|
| 183 |
+
),
|
| 184 |
+
)
|
| 185 |
+
if (
|
| 186 |
+
new_partition_latency.overall_latency_sec
|
| 187 |
+
> max_latency.overall_latency_sec
|
| 188 |
+
):
|
| 189 |
+
max_latency = new_partition_latency
|
| 190 |
+
return max_latency
|
| 191 |
+
# If there is no user, the node is at bottom of the partition
|
| 192 |
+
return PartitionLatency(
|
| 193 |
+
mem_latency_sec, computer_latency_sec, overall_latency_sec
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# Main part starts
|
| 197 |
+
# Get all top level nodes of this partition
|
| 198 |
+
top_nodes = get_top_nodes(partition)
|
| 199 |
+
critical_path_latency = PartitionLatency(
|
| 200 |
+
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
|
| 201 |
+
)
|
| 202 |
+
# Go through all top nodes and find the largest latency (critical pass latency)
|
| 203 |
+
for node in top_nodes:
|
| 204 |
+
partition_latency = dfs_helper(
|
| 205 |
+
node,
|
| 206 |
+
PartitionLatency(
|
| 207 |
+
mem_latency_sec=0.0, computer_latency_sec=0.0, overall_latency_sec=0.0
|
| 208 |
+
),
|
| 209 |
+
)
|
| 210 |
+
if (
|
| 211 |
+
partition_latency.overall_latency_sec
|
| 212 |
+
> critical_path_latency.overall_latency_sec
|
| 213 |
+
):
|
| 214 |
+
critical_path_latency = partition_latency
|
| 215 |
+
return critical_path_latency
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def get_partition_to_latency_mapping(
|
| 219 |
+
partitions: List[Partition], node_to_latency_mapping: Dict[Node, NodeLatency]
|
| 220 |
+
) -> Dict[Partition, PartitionLatency]:
|
| 221 |
+
"""Given all the partitions and node_to_latency_mapping dictionary,
|
| 222 |
+
return a mapping dictionary of each partition to its overall latency
|
| 223 |
+
"""
|
| 224 |
+
partition_to_latency_mapping: Dict[Partition, PartitionLatency] = {}
|
| 225 |
+
# Go through each partition and get its latency
|
| 226 |
+
for partition in partitions:
|
| 227 |
+
partition_latency = get_latency_of_one_partition(
|
| 228 |
+
partition, node_to_latency_mapping
|
| 229 |
+
)
|
| 230 |
+
partition_to_latency_mapping[partition] = partition_latency
|
| 231 |
+
return partition_to_latency_mapping
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def get_comm_latency_between(
|
| 235 |
+
parent_partition: Partition,
|
| 236 |
+
child_partition: Partition,
|
| 237 |
+
transfer_rate_bytes_per_sec: float,
|
| 238 |
+
):
|
| 239 |
+
"""Given two partitions (parent and child),
|
| 240 |
+
calculate the communication latency between the two.
|
| 241 |
+
"""
|
| 242 |
+
# If two partitions are on the same device, the comm latency is 0.
|
| 243 |
+
if (
|
| 244 |
+
parent_partition.logical_device_ids != []
|
| 245 |
+
and child_partition.logical_device_ids != []
|
| 246 |
+
and parent_partition.logical_device_ids == child_partition.logical_device_ids
|
| 247 |
+
):
|
| 248 |
+
return 0.0
|
| 249 |
+
# Keep tracking the communication size between parent and child
|
| 250 |
+
comm_size = 0
|
| 251 |
+
# Keep tracking all the counted node
|
| 252 |
+
visited_nodes = set()
|
| 253 |
+
# Go through all nodes in the child partition
|
| 254 |
+
# If a node has input nodes from the parent partition,
|
| 255 |
+
# the output size of those input nodes will be counted
|
| 256 |
+
# and added to comm_size
|
| 257 |
+
for node in child_partition.nodes:
|
| 258 |
+
input_nodes: Dict[Node, None] = {}
|
| 259 |
+
map_arg(node.args, input_nodes.setdefault)
|
| 260 |
+
map_arg(node.kwargs, input_nodes.setdefault)
|
| 261 |
+
for n in input_nodes:
|
| 262 |
+
if n in parent_partition.nodes and n not in visited_nodes:
|
| 263 |
+
size_bytes = getattr(n, "size_bytes", None)
|
| 264 |
+
if size_bytes is not None:
|
| 265 |
+
comm_size += size_bytes.output_size
|
| 266 |
+
visited_nodes.add(n)
|
| 267 |
+
return comm_size / transfer_rate_bytes_per_sec
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def get_latency_of_partitioned_graph(
|
| 271 |
+
partitions: List[Partition],
|
| 272 |
+
partition_to_latency_mapping: Dict[Partition, PartitionLatency],
|
| 273 |
+
transfer_rate_bytes_per_sec: float,
|
| 274 |
+
):
|
| 275 |
+
"""Given all partitions in a graph, find the critical path among all partitions
|
| 276 |
+
and return its latency as the latency of the whole graph
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
def dfs_helper(partition: Partition, latency_so_far_sec: float) -> float:
|
| 280 |
+
"""This function helps to recursively get the latency of a path of partitions"""
|
| 281 |
+
# Update latency by adding current partition's latency
|
| 282 |
+
latency_so_far_sec += partition_to_latency_mapping[
|
| 283 |
+
partition
|
| 284 |
+
].overall_latency_sec
|
| 285 |
+
children = partition.children
|
| 286 |
+
if partition.children:
|
| 287 |
+
max_latency_sec = 0.0
|
| 288 |
+
for child in partition.children:
|
| 289 |
+
# Calculate latency between
|
| 290 |
+
comm_latency_sec = get_comm_latency_between(
|
| 291 |
+
partition, child, transfer_rate_bytes_per_sec
|
| 292 |
+
)
|
| 293 |
+
new_latency_sec = dfs_helper(
|
| 294 |
+
child, latency_so_far_sec + comm_latency_sec
|
| 295 |
+
)
|
| 296 |
+
if new_latency_sec > max_latency_sec:
|
| 297 |
+
max_latency_sec = new_latency_sec
|
| 298 |
+
return max_latency_sec
|
| 299 |
+
return latency_so_far_sec
|
| 300 |
+
|
| 301 |
+
def get_top_partitions(partitions: List[Partition]) -> List[Partition]:
|
| 302 |
+
"""This function is to return all the partitions without parents
|
| 303 |
+
as the starting points of all the paths
|
| 304 |
+
"""
|
| 305 |
+
top_partitions = []
|
| 306 |
+
for partition in partitions:
|
| 307 |
+
# If a partition has no parents, then it is a top partition
|
| 308 |
+
if len(partition.parents) == 0:
|
| 309 |
+
top_partitions.append(partition)
|
| 310 |
+
return top_partitions
|
| 311 |
+
|
| 312 |
+
top_partitions = get_top_partitions(partitions)
|
| 313 |
+
critical_path_latency_sec = 0.0
|
| 314 |
+
for partition in top_partitions:
|
| 315 |
+
latency_sec = dfs_helper(partition, 0.0)
|
| 316 |
+
if latency_sec > critical_path_latency_sec:
|
| 317 |
+
critical_path_latency_sec = latency_sec
|
| 318 |
+
return critical_path_latency_sec
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py
ADDED
|
@@ -0,0 +1,2215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 3 |
+
# All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# This source code is licensed under the BSD-style license found in the
|
| 6 |
+
# LICENSE file in the root directory of this source tree.
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import functools
|
| 11 |
+
import inspect
|
| 12 |
+
import logging
|
| 13 |
+
import operator
|
| 14 |
+
import traceback
|
| 15 |
+
import typing
|
| 16 |
+
import typing_extensions
|
| 17 |
+
import warnings
|
| 18 |
+
import weakref
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from contextlib import contextmanager, ExitStack, nullcontext
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from typing import (
|
| 23 |
+
Any,
|
| 24 |
+
Callable,
|
| 25 |
+
Dict,
|
| 26 |
+
Generator,
|
| 27 |
+
List,
|
| 28 |
+
Mapping,
|
| 29 |
+
Optional,
|
| 30 |
+
overload,
|
| 31 |
+
Protocol,
|
| 32 |
+
Sequence,
|
| 33 |
+
Tuple,
|
| 34 |
+
Type,
|
| 35 |
+
TYPE_CHECKING,
|
| 36 |
+
TypeVar,
|
| 37 |
+
Union,
|
| 38 |
+
)
|
| 39 |
+
from typing_extensions import Concatenate, ParamSpec, Self
|
| 40 |
+
from weakref import WeakKeyDictionary
|
| 41 |
+
|
| 42 |
+
import torch
|
| 43 |
+
import torch._ops
|
| 44 |
+
import torch.fx as fx
|
| 45 |
+
import torch.fx.traceback as fx_traceback
|
| 46 |
+
import torch.utils._pytree as pytree
|
| 47 |
+
from torch import SymBool, SymInt, Tensor
|
| 48 |
+
from torch._dispatch.python import enable_python_dispatcher
|
| 49 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 50 |
+
from torch._subclasses.fake_impls import fast_detach
|
| 51 |
+
from torch._subclasses.fake_tensor import (
|
| 52 |
+
FakeTensor,
|
| 53 |
+
FakeTensorMode,
|
| 54 |
+
is_fake,
|
| 55 |
+
unset_fake_temporarily,
|
| 56 |
+
)
|
| 57 |
+
from torch._subclasses.meta_utils import is_sparse_any
|
| 58 |
+
from torch.fx import GraphModule, Proxy, Tracer
|
| 59 |
+
from torch.fx.graph_module import _assign_attr
|
| 60 |
+
from torch.fx.node import _side_effectful_need_to_be_preserved_pre_dispatch
|
| 61 |
+
from torch.fx.passes.shape_prop import _extract_tensor_metadata
|
| 62 |
+
from torch.nn import Module
|
| 63 |
+
from torch.overrides import TorchFunctionMode
|
| 64 |
+
from torch.utils._python_dispatch import (
|
| 65 |
+
_disable_infra_mode,
|
| 66 |
+
_push_mode,
|
| 67 |
+
_unset_infra_mode,
|
| 68 |
+
TorchDispatchMode,
|
| 69 |
+
)
|
| 70 |
+
from torch.utils._stats import count
|
| 71 |
+
from torch.utils._thunk import Thunk
|
| 72 |
+
from torch.utils._traceback import CapturedTraceback
|
| 73 |
+
from torch.utils.weak import _WeakHashRef, WeakIdKeyDictionary, WeakTensorKeyDictionary
|
| 74 |
+
|
| 75 |
+
from ._backward_state import BackwardState
|
| 76 |
+
from .sym_node import SymNode
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if TYPE_CHECKING:
|
| 80 |
+
import types
|
| 81 |
+
from collections.abc import MutableMapping
|
| 82 |
+
|
| 83 |
+
import sympy
|
| 84 |
+
|
| 85 |
+
from torch._ops import OpOverload
|
| 86 |
+
from torch.fx._symbolic_trace import PHBase
|
| 87 |
+
from torch.types import IntLikeType
|
| 88 |
+
|
| 89 |
+
__all__ = [
|
| 90 |
+
"PythonKeyTracer",
|
| 91 |
+
"dispatch_trace",
|
| 92 |
+
"make_fx",
|
| 93 |
+
"DecompositionInterpreter",
|
| 94 |
+
"py_sym_types",
|
| 95 |
+
"get_innermost_proxy_mode",
|
| 96 |
+
"get_proxy_mode",
|
| 97 |
+
"handle_sym_dispatch",
|
| 98 |
+
"maybe_enable_thunkify",
|
| 99 |
+
"maybe_disable_thunkify",
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
_ProxyTracer = Union["PythonKeyTracer", "_GraphAppendingTracerEx"]
|
| 103 |
+
|
| 104 |
+
_AnyScriptObject = (torch.ScriptObject, FakeScriptObject)
|
| 105 |
+
_AnyScriptObjectType = Union[torch.ScriptObject, FakeScriptObject]
|
| 106 |
+
|
| 107 |
+
aten = torch.ops.aten
|
| 108 |
+
prim = torch.ops.prim
|
| 109 |
+
|
| 110 |
+
log = logging.getLogger(__name__)
|
| 111 |
+
not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented")
|
| 112 |
+
|
| 113 |
+
CURRENT_DECOMPOSITION_TABLE: Mapping[OpOverload, Callable] = {}
|
| 114 |
+
|
| 115 |
+
CONSTANT_NUMEL_LIMIT = 1
|
| 116 |
+
|
| 117 |
+
T = TypeVar("T")
|
| 118 |
+
U = TypeVar("U")
|
| 119 |
+
_P = ParamSpec("_P")
|
| 120 |
+
R = TypeVar("R")
|
| 121 |
+
|
| 122 |
+
null_ctx_type = type(nullcontext)
|
| 123 |
+
# We currently convert all SymInt to proxies before we use them.
|
| 124 |
+
# This could plausibly be handled at the Dynamo level.
|
| 125 |
+
pytree.register_pytree_node(
|
| 126 |
+
torch.Size,
|
| 127 |
+
lambda xs: (list(xs), None),
|
| 128 |
+
lambda xs, _: tuple(xs),
|
| 129 |
+
flatten_with_keys_fn=lambda xs: (
|
| 130 |
+
[(pytree.SequenceKey(i), x) for i, x in enumerate(xs)],
|
| 131 |
+
None,
|
| 132 |
+
),
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def fake_signature(fn: Callable[_P, R], nargs: int) -> Callable[_P, R]:
|
| 137 |
+
"""FX gets confused by varargs, de-confuse it"""
|
| 138 |
+
argnames = ",".join(f"arg{i}" for i in range(nargs))
|
| 139 |
+
return eval(f"lambda {argnames}: fn({argnames})", {"fn": fn})
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@contextmanager
|
| 143 |
+
def decompose(
|
| 144 |
+
decomposition_table: Optional[Mapping[OpOverload, Callable]]
|
| 145 |
+
) -> Generator[Mapping[OpOverload, Callable], None, None]:
|
| 146 |
+
global CURRENT_DECOMPOSITION_TABLE
|
| 147 |
+
old_decomposition_table = CURRENT_DECOMPOSITION_TABLE
|
| 148 |
+
CURRENT_DECOMPOSITION_TABLE = decomposition_table or {}
|
| 149 |
+
try:
|
| 150 |
+
yield CURRENT_DECOMPOSITION_TABLE
|
| 151 |
+
finally:
|
| 152 |
+
CURRENT_DECOMPOSITION_TABLE = old_decomposition_table
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ensure we cannot collide with other properties
|
| 156 |
+
proxy_slot = object()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class _NoDefault:
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
no_default = _NoDefault()
|
| 164 |
+
|
| 165 |
+
from torch.types import py_sym_types, PySymType
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class _HasMeta(Protocol):
|
| 169 |
+
meta: Dict[str, PySymType]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def is_sym_node(node: _HasMeta) -> bool:
|
| 173 |
+
assert hasattr(node, "meta"), "All nodes traced with proxy_tensor should have meta"
|
| 174 |
+
return "val" in node.meta and isinstance(node.meta["val"], py_sym_types)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@overload
|
| 178 |
+
def set_proxy_slot(obj: Tensor, tracer: _ProxyTracer, proxy: _ProxyTensor) -> None:
|
| 179 |
+
...
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@overload
|
| 183 |
+
def set_proxy_slot(
|
| 184 |
+
obj: _AnyScriptObjectType, tracer: _ProxyTracer, proxy: Proxy
|
| 185 |
+
) -> None:
|
| 186 |
+
...
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@overload
|
| 190 |
+
def set_proxy_slot(
|
| 191 |
+
obj: PySymType, tracer: _ProxyTracer, proxy: _PySymProxyType
|
| 192 |
+
) -> None:
|
| 193 |
+
...
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def set_proxy_slot(
|
| 197 |
+
obj: Union[PySymType, _AnyScriptObjectType, Tensor],
|
| 198 |
+
tracer: _ProxyTracer,
|
| 199 |
+
proxy: object,
|
| 200 |
+
) -> None:
|
| 201 |
+
log.debug("set_proxy_slot %s (%s) %s", obj, id(obj), proxy)
|
| 202 |
+
if isinstance(obj, Tensor):
|
| 203 |
+
# We DO want to clobber proxies whenever we run an inplace operation
|
| 204 |
+
# on a tensor, and it affects the metadata on the proxy.
|
| 205 |
+
assert isinstance(proxy, _ProxyTensor)
|
| 206 |
+
tracer.tensor_tracker[obj] = proxy
|
| 207 |
+
elif isinstance(obj, (_AnyScriptObject)):
|
| 208 |
+
# We DO want to clobber proxies, with a similar rationale as for tensors.
|
| 209 |
+
assert isinstance(proxy, Proxy)
|
| 210 |
+
tracer.script_object_tracker[obj] = proxy
|
| 211 |
+
else:
|
| 212 |
+
# NB: Never clobber pre-existing proxy. Although the proxies
|
| 213 |
+
# are in principle equivalent, when we do graph partitioning
|
| 214 |
+
# we need there not to be spurious dependencies on tangent inputs.
|
| 215 |
+
# This works because primals get their SymInts set first, and
|
| 216 |
+
# THEN later we allocate tangent inputs. Make sure if a SymInt
|
| 217 |
+
# is derivable from a primal that we use that.
|
| 218 |
+
assert isinstance(obj, py_sym_types), type(obj)
|
| 219 |
+
if obj not in tracer.symnode_tracker:
|
| 220 |
+
tracer.symnode_tracker[obj] = typing.cast(_PySymProxyType, proxy)
|
| 221 |
+
|
| 222 |
+
# WAR: python test/dynamo/test_subclasses.py
|
| 223 |
+
# TestNestedTensor.test_basic_autograd
|
| 224 |
+
#
|
| 225 |
+
# AOTAutograd doesn't pass the "outer sizes" as an actual argument
|
| 226 |
+
# to make_fx, but it is made use of internally in AOTAutograd's
|
| 227 |
+
# call to tensor unflatten. Because the outer sizes isn't passed
|
| 228 |
+
# as an argument, it is therefore untracked. However, it turns
|
| 229 |
+
# out you luck out, because *Dynamo* will manually add the outer
|
| 230 |
+
# sizes as an argument so you can fix up the proxy'ness.
|
| 231 |
+
#
|
| 232 |
+
# This is probably fixed in
|
| 233 |
+
# https://github.com/pytorch/pytorch/pull/125941/
|
| 234 |
+
import sympy
|
| 235 |
+
|
| 236 |
+
if isinstance(obj.node.expr, sympy.Symbol):
|
| 237 |
+
tracer.sympy_expr_tracker[obj.node.expr] = proxy
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def has_proxy_slot(obj: Tensor, tracer: _ProxyTracer) -> bool:
|
| 241 |
+
assert isinstance(obj, (Tensor, SymNode)), type(obj)
|
| 242 |
+
return bool(get_proxy_slot(obj, tracer, False, lambda _: True))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
_PySymProxyType = Thunk[Proxy]
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@overload
|
| 249 |
+
def get_proxy_slot(
|
| 250 |
+
obj: Tensor,
|
| 251 |
+
tracer: _ProxyTracer,
|
| 252 |
+
) -> _ProxyTensor:
|
| 253 |
+
...
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@overload
|
| 257 |
+
def get_proxy_slot(
|
| 258 |
+
obj: Tensor,
|
| 259 |
+
tracer: _ProxyTracer,
|
| 260 |
+
default: U,
|
| 261 |
+
) -> Union[_ProxyTensor, U]:
|
| 262 |
+
...
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@overload
|
| 266 |
+
def get_proxy_slot(
|
| 267 |
+
obj: Tensor,
|
| 268 |
+
tracer: _ProxyTracer,
|
| 269 |
+
default: U,
|
| 270 |
+
transform: Callable[[_ProxyTensor], R],
|
| 271 |
+
) -> Union[R, U]:
|
| 272 |
+
...
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@overload
|
| 276 |
+
def get_proxy_slot(
|
| 277 |
+
obj: _AnyScriptObjectType,
|
| 278 |
+
tracer: _ProxyTracer,
|
| 279 |
+
) -> Proxy:
|
| 280 |
+
...
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@overload
|
| 284 |
+
def get_proxy_slot(
|
| 285 |
+
obj: _AnyScriptObjectType,
|
| 286 |
+
tracer: _ProxyTracer,
|
| 287 |
+
default: U,
|
| 288 |
+
) -> Union[Proxy, U]:
|
| 289 |
+
...
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@overload
|
| 293 |
+
def get_proxy_slot(
|
| 294 |
+
obj: _AnyScriptObjectType,
|
| 295 |
+
tracer: _ProxyTracer,
|
| 296 |
+
default: U,
|
| 297 |
+
transform: Callable[[Proxy], R],
|
| 298 |
+
) -> Union[R, U]:
|
| 299 |
+
...
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@overload
|
| 303 |
+
def get_proxy_slot(
|
| 304 |
+
obj: PySymType,
|
| 305 |
+
tracer: _ProxyTracer,
|
| 306 |
+
) -> _PySymProxyType:
|
| 307 |
+
...
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
@overload
|
| 311 |
+
def get_proxy_slot(
|
| 312 |
+
obj: PySymType,
|
| 313 |
+
tracer: _ProxyTracer,
|
| 314 |
+
default: T,
|
| 315 |
+
) -> Union[T, _PySymProxyType]:
|
| 316 |
+
...
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@overload
|
| 320 |
+
def get_proxy_slot(
|
| 321 |
+
obj: PySymType,
|
| 322 |
+
tracer: _ProxyTracer,
|
| 323 |
+
default: U,
|
| 324 |
+
transform: Callable[[_PySymProxyType], R],
|
| 325 |
+
) -> Union[R, U]:
|
| 326 |
+
...
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# the default argument is what to return if the slot is not set.
|
| 330 |
+
# the transform argument is handy if you need to extract a subfield from
|
| 331 |
+
# the successfully looked up result (but NOT the default.)
|
| 332 |
+
def get_proxy_slot(
|
| 333 |
+
obj: Union[Tensor, _AnyScriptObjectType, PySymType],
|
| 334 |
+
tracer: _ProxyTracer,
|
| 335 |
+
default: object = no_default,
|
| 336 |
+
transform: Callable = lambda x: x,
|
| 337 |
+
) -> object:
|
| 338 |
+
tracker: Any
|
| 339 |
+
if isinstance(obj, Tensor):
|
| 340 |
+
tracker = tracer.tensor_tracker
|
| 341 |
+
elif isinstance(obj, _AnyScriptObject):
|
| 342 |
+
tracker = tracer.script_object_tracker
|
| 343 |
+
else:
|
| 344 |
+
assert isinstance(obj, py_sym_types), type(obj)
|
| 345 |
+
tracker = tracer.symnode_tracker
|
| 346 |
+
|
| 347 |
+
if obj not in tracker:
|
| 348 |
+
# Last ditch
|
| 349 |
+
if isinstance(obj, py_sym_types) and obj.node.expr in tracer.sympy_expr_tracker:
|
| 350 |
+
value = tracer.sympy_expr_tracker[obj.node.expr]
|
| 351 |
+
else:
|
| 352 |
+
if isinstance(default, _NoDefault):
|
| 353 |
+
raise RuntimeError(
|
| 354 |
+
f"{obj} ({id(obj)})is not tracked with proxy for {tracer}"
|
| 355 |
+
)
|
| 356 |
+
return default
|
| 357 |
+
else:
|
| 358 |
+
value = tracker[obj]
|
| 359 |
+
res = transform(value)
|
| 360 |
+
return res
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def snapshot_fake(val: Tensor) -> Optional[Tensor]:
|
| 364 |
+
# val.detach() will also eventually call fast_detach(),
|
| 365 |
+
# but this saves us a full trip into __torch_dispatch__
|
| 366 |
+
# (snapshot_fake is called a lot)
|
| 367 |
+
if isinstance(val, FakeTensor):
|
| 368 |
+
return fast_detach(val.fake_mode, val)
|
| 369 |
+
else:
|
| 370 |
+
return val.detach()
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
_ExtractValType = Optional[
|
| 374 |
+
Union[
|
| 375 |
+
PySymType,
|
| 376 |
+
_AnyScriptObjectType,
|
| 377 |
+
BackwardState,
|
| 378 |
+
List["_ExtractValType"],
|
| 379 |
+
Tuple["_ExtractValType", ...],
|
| 380 |
+
Dict[str, "_ExtractValType"],
|
| 381 |
+
Tensor,
|
| 382 |
+
int,
|
| 383 |
+
float,
|
| 384 |
+
bool,
|
| 385 |
+
]
|
| 386 |
+
]
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def extract_val(val: _ExtractValType) -> _ExtractValType:
|
| 390 |
+
if is_fake(val):
|
| 391 |
+
return snapshot_fake(val)
|
| 392 |
+
elif isinstance(val, py_sym_types):
|
| 393 |
+
return val
|
| 394 |
+
elif isinstance(val, _AnyScriptObject):
|
| 395 |
+
return val
|
| 396 |
+
elif isinstance(val, BackwardState):
|
| 397 |
+
return val
|
| 398 |
+
elif isinstance(val, (list, tuple)):
|
| 399 |
+
return val.__class__([extract_val(x) for x in val])
|
| 400 |
+
elif isinstance(val, dict):
|
| 401 |
+
return {k: extract_val(v) for k, v in val.items()}
|
| 402 |
+
elif isinstance(val, Tensor):
|
| 403 |
+
if not val.is_sparse:
|
| 404 |
+
# NB: Kinda hacky, but we should try to get val as the metadata
|
| 405 |
+
# everywhere
|
| 406 |
+
# TODO: This doesn't properly track storages. A more robust
|
| 407 |
+
# approach would be to maintain a per-trace FakeTensorMode and
|
| 408 |
+
# from_real_tensor to create fake values (don't forget to
|
| 409 |
+
# snapshot_fake)
|
| 410 |
+
fake_tensor_mode = FakeTensorMode(allow_fallback_kernels=True)
|
| 411 |
+
with fake_tensor_mode:
|
| 412 |
+
return torch.empty_strided(
|
| 413 |
+
val.shape, val.stride(), device=val.device, dtype=val.dtype
|
| 414 |
+
)
|
| 415 |
+
else:
|
| 416 |
+
return None
|
| 417 |
+
elif isinstance(val, (int, float, bool)):
|
| 418 |
+
return val
|
| 419 |
+
elif val is None:
|
| 420 |
+
return None
|
| 421 |
+
|
| 422 |
+
typing_extensions.assert_never(val)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
@contextmanager
|
| 426 |
+
def _enable_thunkify(
|
| 427 |
+
tracer: _ProxyTracer, *, enable: bool = True
|
| 428 |
+
) -> Generator[None, None, None]:
|
| 429 |
+
"""
|
| 430 |
+
Enable thunkification inside the context manager. Thunkification prevents
|
| 431 |
+
SymNode computation from directly being traced into an FX graph; instead,
|
| 432 |
+
the compute is only added to the graph if it is actually used. This helps
|
| 433 |
+
us track SymNode compute when it is computed (since we need /something/
|
| 434 |
+
to put in the tracker) even if it is unlikely to be used.
|
| 435 |
+
"""
|
| 436 |
+
old = tracer.enable_thunkify
|
| 437 |
+
tracer.enable_thunkify = enable
|
| 438 |
+
try:
|
| 439 |
+
yield
|
| 440 |
+
finally:
|
| 441 |
+
tracer.enable_thunkify = old
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@contextmanager
|
| 445 |
+
def maybe_disable_thunkify() -> Generator[None, None, None]:
|
| 446 |
+
"""Within a context, disable thunkification. See :func:`maybe_enable_thunkify`
|
| 447 |
+
for more details. This is helpful if you have a wrapper function which
|
| 448 |
+
you want to enable thunkification on, but in some segment on the inside (say,
|
| 449 |
+
the original user function), you want to disable thunkification as you know
|
| 450 |
+
it is not needed there.
|
| 451 |
+
"""
|
| 452 |
+
proxy_mode = get_proxy_mode()
|
| 453 |
+
if proxy_mode is not None:
|
| 454 |
+
with _enable_thunkify(proxy_mode.tracer, enable=False):
|
| 455 |
+
yield
|
| 456 |
+
else:
|
| 457 |
+
yield
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@contextmanager
|
| 461 |
+
def maybe_enable_thunkify() -> Generator[None, None, None]:
|
| 462 |
+
"""Within this context manager, if you are doing make_fx tracing, we will thunkify
|
| 463 |
+
all SymNode compute and avoid tracing it into the graph unless it is actually needed.
|
| 464 |
+
You should prefer to avoid using this as much as possible, as lazy evaluation of
|
| 465 |
+
SymNode tracing can lead to long chains of thunks which will stack overflow
|
| 466 |
+
if you evaluate them. However, this is currently sometimes necessary as there
|
| 467 |
+
are buggy parts of PT2 which will fail with "s0 is not tracked with proxy" error
|
| 468 |
+
due to insufficient tracing of SymNode computation.
|
| 469 |
+
"""
|
| 470 |
+
proxy_mode = get_proxy_mode()
|
| 471 |
+
if proxy_mode is not None:
|
| 472 |
+
with _enable_thunkify(proxy_mode.tracer):
|
| 473 |
+
yield
|
| 474 |
+
else:
|
| 475 |
+
yield
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# Note [invariants for node meta 'val']
|
| 479 |
+
# What invariants do we have for the 'val' set on the FX node? It has accurate
|
| 480 |
+
# metadata... but only for metadata that exists "below" all other subsystems
|
| 481 |
+
# (most notably autograd, but also vmap, functorch transforms, etc). This means
|
| 482 |
+
# you can get the dtype, shape, stride, storage, but you CANNOT get requires_grad,
|
| 483 |
+
# grad_fn, _base (_base actually may be set due to recursive call to
|
| 484 |
+
# ADInplaceOrView, but you shouldn't rely on it.)
|
| 485 |
+
def set_meta(proxy: Proxy, val: _ExtractValType) -> Proxy:
|
| 486 |
+
proxy.node.meta["val"] = extract_val(val)
|
| 487 |
+
|
| 488 |
+
with _enable_thunkify(proxy.tracer): # type: ignore[arg-type]
|
| 489 |
+
# Best effort tensor_meta setting; prefer using val!
|
| 490 |
+
if is_fake(val):
|
| 491 |
+
proxy.node.meta["tensor_meta"] = _extract_tensor_metadata(val)
|
| 492 |
+
elif isinstance(val, Tensor) and not val.is_sparse:
|
| 493 |
+
proxy.node.meta["tensor_meta"] = _extract_tensor_metadata(val)
|
| 494 |
+
return proxy
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def thunkify(
|
| 498 |
+
tracer: _ProxyTracer, f: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs
|
| 499 |
+
) -> Thunk[R]:
|
| 500 |
+
"""
|
| 501 |
+
Delays computation of f until it's called again
|
| 502 |
+
Also caches the result
|
| 503 |
+
"""
|
| 504 |
+
if tracer.enable_thunkify:
|
| 505 |
+
return Thunk(functools.partial(f, *args, **kwargs))
|
| 506 |
+
else:
|
| 507 |
+
r = f(*args, **kwargs)
|
| 508 |
+
return Thunk(lambda: r)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def track_tensor(
|
| 512 |
+
tensor: Tensor, proxy: Proxy, *, constant: Optional[Tensor], tracer: _ProxyTracer
|
| 513 |
+
) -> None:
|
| 514 |
+
def try_set_proxy_slot(
|
| 515 |
+
outer_s: IntLikeType,
|
| 516 |
+
proxy_callable: Callable[Concatenate[PySymType, _P], Proxy],
|
| 517 |
+
*args: _P.args,
|
| 518 |
+
**kwargs: _P.kwargs,
|
| 519 |
+
) -> None:
|
| 520 |
+
assert callable(proxy_callable)
|
| 521 |
+
if isinstance(outer_s, SymInt):
|
| 522 |
+
with _enable_thunkify(tracer):
|
| 523 |
+
set_proxy_slot(
|
| 524 |
+
outer_s,
|
| 525 |
+
tracer,
|
| 526 |
+
thunkify(tracer, proxy_callable, outer_s, *args, **kwargs),
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# The basic idea is that we need to associate each tensor/SymInt
|
| 530 |
+
# with a Proxy. How do we setup this association? We just store
|
| 531 |
+
# the proxy on the proxy slot of the object, keyed on the tracer
|
| 532 |
+
# (so that if we have multiple tracers at the same time, they
|
| 533 |
+
# don't clobber each other.)
|
| 534 |
+
for i, s in enumerate(tensor.shape):
|
| 535 |
+
try_set_proxy_slot(
|
| 536 |
+
s,
|
| 537 |
+
lambda x, i: set_meta(
|
| 538 |
+
tracer.create_proxy(
|
| 539 |
+
"call_function", torch.ops.aten.sym_size.int, (proxy, i), {}
|
| 540 |
+
),
|
| 541 |
+
x,
|
| 542 |
+
),
|
| 543 |
+
i,
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
if not is_sparse_any(tensor):
|
| 547 |
+
for i, s in enumerate(tensor.stride()):
|
| 548 |
+
try_set_proxy_slot(
|
| 549 |
+
s,
|
| 550 |
+
lambda x, i: set_meta(
|
| 551 |
+
tracer.create_proxy(
|
| 552 |
+
"call_function", torch.ops.aten.sym_stride.int, (proxy, i), {}
|
| 553 |
+
),
|
| 554 |
+
x,
|
| 555 |
+
),
|
| 556 |
+
i,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
try_set_proxy_slot(
|
| 560 |
+
tensor.numel(),
|
| 561 |
+
lambda x: set_meta(
|
| 562 |
+
tracer.create_proxy(
|
| 563 |
+
"call_function", torch.ops.aten.sym_numel.default, (proxy,), {}
|
| 564 |
+
),
|
| 565 |
+
x,
|
| 566 |
+
),
|
| 567 |
+
)
|
| 568 |
+
if not is_sparse_any(tensor):
|
| 569 |
+
try_set_proxy_slot(
|
| 570 |
+
tensor.storage_offset(),
|
| 571 |
+
lambda x: set_meta(
|
| 572 |
+
tracer.create_proxy(
|
| 573 |
+
"call_function",
|
| 574 |
+
torch.ops.aten.sym_storage_offset.default,
|
| 575 |
+
(proxy,),
|
| 576 |
+
{},
|
| 577 |
+
),
|
| 578 |
+
x,
|
| 579 |
+
),
|
| 580 |
+
)
|
| 581 |
+
set_proxy_slot(tensor, tracer, _ProxyTensor(proxy, constant))
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
_NestedProxys = Union[
|
| 585 |
+
Proxy, Sequence["_NestedProxys"], Mapping[object, "_NestedProxys"]
|
| 586 |
+
]
|
| 587 |
+
_NestedTensors = Union[
|
| 588 |
+
Tensor, Sequence["_NestedTensors"], Mapping[object, "_NestedTensors"]
|
| 589 |
+
]
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def track_tensor_tree(
|
| 593 |
+
inner_res: T,
|
| 594 |
+
proxy_res: _NestedProxys,
|
| 595 |
+
*,
|
| 596 |
+
constant: Optional[_NestedTensors],
|
| 597 |
+
tracer: _ProxyTracer,
|
| 598 |
+
) -> T:
|
| 599 |
+
# NB: We call set_unbacked_bindings only on the *topmost* call to
|
| 600 |
+
# track_tensor_tree, not recursive calls. This is because there must
|
| 601 |
+
# be only ONE unbacked_binding proxy call, and it should be the one
|
| 602 |
+
# where all of the unbacked SymInts actually first come into existence.
|
| 603 |
+
# If you call this again on the inner proxies for the tuple projections,
|
| 604 |
+
# you will have multiple unbacked_bindings for the same symbol, but
|
| 605 |
+
# they're not going to show up anywhere.
|
| 606 |
+
#
|
| 607 |
+
# I was briefly deceived into setting unbacked bindings recursively when
|
| 608 |
+
# working on https://github.com/pytorch/pytorch/pull/133585 because I
|
| 609 |
+
# observed that some extra unbacked bindings were needed to handle some
|
| 610 |
+
# higher order operator code. But actually it looks like this was
|
| 611 |
+
# just an unrelated bug that needed to be fixed separately.
|
| 612 |
+
_set_unbacked_bindings(inner_res, proxy_res)
|
| 613 |
+
|
| 614 |
+
def wrap_with_proxy(
|
| 615 |
+
e: object, proxy: _NestedProxys, constant: Optional[_NestedTensors]
|
| 616 |
+
) -> None:
|
| 617 |
+
if isinstance(e, Tensor):
|
| 618 |
+
assert isinstance(proxy, Proxy)
|
| 619 |
+
assert constant is None or isinstance(constant, Tensor)
|
| 620 |
+
track_tensor(e, proxy, tracer=tracer, constant=constant)
|
| 621 |
+
set_meta(proxy, e)
|
| 622 |
+
elif isinstance(e, py_sym_types):
|
| 623 |
+
assert isinstance(proxy, Proxy)
|
| 624 |
+
# NB: eagerly set meta here, so that the numbering is in order
|
| 625 |
+
set_meta(proxy, e)
|
| 626 |
+
set_proxy_slot(e, tracer, thunkify(tracer, lambda: proxy))
|
| 627 |
+
elif isinstance(e, _AnyScriptObject):
|
| 628 |
+
assert isinstance(proxy, Proxy)
|
| 629 |
+
set_proxy_slot(e, tracer, proxy)
|
| 630 |
+
set_meta(proxy, e)
|
| 631 |
+
elif isinstance(e, (tuple, list)):
|
| 632 |
+
# example use case: allreduce_ returns ([tensor], work)
|
| 633 |
+
if isinstance(proxy, fx.Proxy):
|
| 634 |
+
set_meta(proxy, e)
|
| 635 |
+
|
| 636 |
+
def get_constant(
|
| 637 |
+
c: Optional[_NestedTensors], idx: int
|
| 638 |
+
) -> Optional[_NestedTensors]:
|
| 639 |
+
if c is None:
|
| 640 |
+
return None
|
| 641 |
+
else:
|
| 642 |
+
assert isinstance(c, (list, tuple))
|
| 643 |
+
return c[idx]
|
| 644 |
+
|
| 645 |
+
for idx, ee in enumerate(e):
|
| 646 |
+
# Use an indexer here - if proxy is a List then it will unwrap
|
| 647 |
+
# it. If it's a Proxy then it will proxy the getelem.
|
| 648 |
+
wrap_with_proxy(ee, proxy[idx], get_constant(constant, idx)) # type: ignore[index]
|
| 649 |
+
|
| 650 |
+
elif isinstance(e, dict):
|
| 651 |
+
# example use case: triton_kernel_wrapper takes arguments as kwargs
|
| 652 |
+
|
| 653 |
+
# In theory we could support const-prop when proxy-tensor-tracing
|
| 654 |
+
# operators that returns dicts of tensors, but we have no use case
|
| 655 |
+
# for it today (since the only op we currently trace that can
|
| 656 |
+
# return a dict is triton_kernel_wrapper_functional/mutation,
|
| 657 |
+
# which does not participate in const-prop)
|
| 658 |
+
assert constant is None
|
| 659 |
+
|
| 660 |
+
if isinstance(proxy, fx.Proxy):
|
| 661 |
+
set_meta(proxy, e)
|
| 662 |
+
|
| 663 |
+
for key, val in e.items():
|
| 664 |
+
wrap_with_proxy(val, proxy[key], None) # type: ignore[index]
|
| 665 |
+
|
| 666 |
+
elif isinstance(e, BackwardState):
|
| 667 |
+
assert isinstance(proxy, Proxy)
|
| 668 |
+
set_meta(proxy, e)
|
| 669 |
+
e.proxy = proxy
|
| 670 |
+
else:
|
| 671 |
+
# intentionally pass on primitives
|
| 672 |
+
pass
|
| 673 |
+
|
| 674 |
+
wrap_with_proxy(inner_res, proxy_res, constant)
|
| 675 |
+
|
| 676 |
+
return inner_res
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@dataclass
|
| 680 |
+
class _ProxyTensor:
|
| 681 |
+
proxy: Proxy
|
| 682 |
+
constant: Optional[Tensor]
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def fetch_sym_proxy(
|
| 686 |
+
tracer: _ProxyTracer,
|
| 687 |
+
) -> Callable[[PySymType], Union[bool, int, float, Proxy]]:
|
| 688 |
+
def inner(e: PySymType) -> Union[int, bool, float, Proxy]:
|
| 689 |
+
n = e.node
|
| 690 |
+
if n.constant is not None:
|
| 691 |
+
return n.constant
|
| 692 |
+
if e.node.expr.is_number:
|
| 693 |
+
if isinstance(e, SymBool):
|
| 694 |
+
return bool(e.node.expr)
|
| 695 |
+
elif isinstance(e, SymInt):
|
| 696 |
+
return int(e.node.expr)
|
| 697 |
+
return float(e.node.expr)
|
| 698 |
+
else:
|
| 699 |
+
assert isinstance(e, py_sym_types)
|
| 700 |
+
# NB: we REQUIRE all symints to be tracked
|
| 701 |
+
return get_proxy_slot(e, tracer).force()
|
| 702 |
+
|
| 703 |
+
return inner
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
@overload
|
| 707 |
+
def fetch_object_proxy(tracer: _ProxyTracer, t: Tensor) -> Union[_ProxyTensor, Tensor]:
|
| 708 |
+
...
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
@overload
|
| 712 |
+
def fetch_object_proxy(
|
| 713 |
+
tracer: _ProxyTracer, t: _AnyScriptObjectType
|
| 714 |
+
) -> Union[Proxy, _AnyScriptObjectType]:
|
| 715 |
+
...
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
@overload
|
| 719 |
+
def fetch_object_proxy(
|
| 720 |
+
tracer: _ProxyTracer, t: PySymType
|
| 721 |
+
) -> Union[_PySymProxyType, PySymType]:
|
| 722 |
+
...
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def fetch_object_proxy(
|
| 726 |
+
tracer: _ProxyTracer, t: Union[Tensor, _AnyScriptObjectType, PySymType]
|
| 727 |
+
) -> object:
|
| 728 |
+
return get_proxy_slot(t, tracer, t)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
HANDLED_TYPES = (Tensor, torch.nn.Parameter, FakeTensor)
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def _maybe_record_pointwise_barrier(
|
| 735 |
+
func: object, proxy_mode: ProxyTorchDispatchMode
|
| 736 |
+
) -> None:
|
| 737 |
+
"""
|
| 738 |
+
Records pointwise operators in user program (non decomposed) that were output in fp16/bf16
|
| 739 |
+
"""
|
| 740 |
+
if proxy_mode.decomp_layers or not proxy_mode.emulate_precision_casts:
|
| 741 |
+
return
|
| 742 |
+
|
| 743 |
+
if (
|
| 744 |
+
not isinstance(func, torch._ops.OpOverload)
|
| 745 |
+
or torch.Tag.pointwise not in func.tags
|
| 746 |
+
):
|
| 747 |
+
return
|
| 748 |
+
|
| 749 |
+
last_node = next(iter(reversed(proxy_mode.tracer.graph.nodes)))
|
| 750 |
+
t = last_node.meta.get("val")
|
| 751 |
+
if not isinstance(t, torch.Tensor) or t.dtype not in (
|
| 752 |
+
torch.bfloat16,
|
| 753 |
+
torch.float16,
|
| 754 |
+
):
|
| 755 |
+
return
|
| 756 |
+
|
| 757 |
+
last_node.meta["low_precision_pointwise_barrier"] = True
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def proxy_call(
|
| 761 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 762 |
+
func: OpOverload,
|
| 763 |
+
pre_dispatch: bool,
|
| 764 |
+
args: Tuple[object, ...],
|
| 765 |
+
kwargs: Dict[str, object],
|
| 766 |
+
) -> object:
|
| 767 |
+
unrecognized_types: List[Type] = []
|
| 768 |
+
flat_args_kwargs, spec = pytree.tree_flatten((args, kwargs))
|
| 769 |
+
|
| 770 |
+
def can_handle_tensor(x: Tensor) -> bool:
|
| 771 |
+
r = type(x) in HANDLED_TYPES or has_proxy_slot(x, proxy_mode.tracer)
|
| 772 |
+
if proxy_mode._allow_fake_constant:
|
| 773 |
+
r = r or type(x) in (torch._subclasses.FakeTensor,)
|
| 774 |
+
if not r:
|
| 775 |
+
unrecognized_types.append(type(x))
|
| 776 |
+
return r
|
| 777 |
+
|
| 778 |
+
# If there are any tensor subclasses, we need to handle those tensor subclasses first
|
| 779 |
+
# TODO: we could use types to test this
|
| 780 |
+
if not all(can_handle_tensor(x) for x in flat_args_kwargs if isinstance(x, Tensor)):
|
| 781 |
+
not_implemented_log.debug(
|
| 782 |
+
"ProxyTensorMode tensors without proxy had unrecognized subclasses: %s",
|
| 783 |
+
unrecognized_types,
|
| 784 |
+
)
|
| 785 |
+
return NotImplemented
|
| 786 |
+
|
| 787 |
+
r = maybe_handle_decomp(proxy_mode, func, args, kwargs)
|
| 788 |
+
if r is not NotImplemented:
|
| 789 |
+
_maybe_record_pointwise_barrier(func, proxy_mode)
|
| 790 |
+
return r
|
| 791 |
+
|
| 792 |
+
# For pre-autograd tracing, we do not want to run CompositeImplicit decomps.
|
| 793 |
+
if not pre_dispatch and func not in [
|
| 794 |
+
torch.ops.aten.size.default,
|
| 795 |
+
torch.ops.aten.stride.default,
|
| 796 |
+
torch.ops.aten.storage_offset.default,
|
| 797 |
+
]:
|
| 798 |
+
with proxy_mode:
|
| 799 |
+
r = func.decompose(*args, **kwargs)
|
| 800 |
+
if r is not NotImplemented:
|
| 801 |
+
return r
|
| 802 |
+
|
| 803 |
+
tracer = proxy_mode.tracer
|
| 804 |
+
f_flat_args_kwargs = [
|
| 805 |
+
(
|
| 806 |
+
fetch_object_proxy(tracer, x)
|
| 807 |
+
if isinstance(x, (Tensor, _AnyScriptObject))
|
| 808 |
+
else x
|
| 809 |
+
)
|
| 810 |
+
for x in flat_args_kwargs
|
| 811 |
+
]
|
| 812 |
+
|
| 813 |
+
# If there are SymInts, we also should not consider this constant.
|
| 814 |
+
# However, fake tensor handling of SymInts is sufficiently broken that
|
| 815 |
+
# I couldn't write a test for this case
|
| 816 |
+
all_constant = (
|
| 817 |
+
not any(
|
| 818 |
+
t.constant is None
|
| 819 |
+
for t in f_flat_args_kwargs
|
| 820 |
+
if isinstance(t, _ProxyTensor)
|
| 821 |
+
)
|
| 822 |
+
# TODO: maybe constant SymInts should also be allowed? Not sure if
|
| 823 |
+
# this can happen
|
| 824 |
+
and not any(isinstance(x, py_sym_types) for x in flat_args_kwargs)
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
if torch.Tag.data_dependent_output in func.tags:
|
| 828 |
+
# Check if all of the Tensor inputs are constants
|
| 829 |
+
if all_constant:
|
| 830 |
+
const_flat_args_kwargs = [
|
| 831 |
+
t.constant if isinstance(t, _ProxyTensor) else t
|
| 832 |
+
for t in f_flat_args_kwargs
|
| 833 |
+
]
|
| 834 |
+
const_args, const_kwargs = pytree.tree_unflatten(
|
| 835 |
+
const_flat_args_kwargs, spec
|
| 836 |
+
)
|
| 837 |
+
with unset_fake_temporarily():
|
| 838 |
+
return func(*const_args, **const_kwargs)
|
| 839 |
+
# If any of the Tensor inputs are "real" (not FakeTensor), we may
|
| 840 |
+
# incorrectly burn in constants by allowing this access. Raise
|
| 841 |
+
# an error in this case
|
| 842 |
+
if proxy_mode._error_on_data_dependent_ops and pytree.tree_all_only(
|
| 843 |
+
Tensor, lambda t: not is_fake(t), (args, kwargs)
|
| 844 |
+
):
|
| 845 |
+
raise RuntimeError(
|
| 846 |
+
f"It appears that you're trying to get value out of a tracing tensor with {func} - erroring out! "
|
| 847 |
+
"It's likely that this is caused by data-dependent control flow or similar. "
|
| 848 |
+
"It may be possible to trace this with dynamic shapes; try setting tracing_mode='symbolic' "
|
| 849 |
+
"in your make_fx call."
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
proxy_flat_args_kwargs = [
|
| 853 |
+
e.proxy if isinstance(e, _ProxyTensor) else e for e in f_flat_args_kwargs
|
| 854 |
+
]
|
| 855 |
+
proxy_flat_args_kwargs = [
|
| 856 |
+
(fetch_sym_proxy(proxy_mode.tracer)(e) if isinstance(e, py_sym_types) else e)
|
| 857 |
+
for e in proxy_flat_args_kwargs
|
| 858 |
+
]
|
| 859 |
+
proxy_args, proxy_kwargs = pytree.tree_unflatten(proxy_flat_args_kwargs, spec)
|
| 860 |
+
|
| 861 |
+
# When we trace through a torch.tensor invocation, you never actually
|
| 862 |
+
# see a torch.ops.aten.tensor call. Instead, the way this function is
|
| 863 |
+
# implemented internally is that we allocate a plain tensor (this is
|
| 864 |
+
# *guaranteed* to be a plain tensor, we disable all modes when doing
|
| 865 |
+
# so), and then call at::lift_fresh on it (to give modes a chance to do
|
| 866 |
+
# their stuff). Furthermore, the tensor argument to lift_fresh is guaranteed
|
| 867 |
+
# to be freshly allocated, so we want lift_fresh to be a no-op (directly
|
| 868 |
+
# returning the input argument).
|
| 869 |
+
#
|
| 870 |
+
# Here is the basic problem: when we trace this sequence of executions
|
| 871 |
+
# into an FX graph, what happens to this call sequence? Traditionally,
|
| 872 |
+
# tensor constants get interned as buffers on the FX GraphModule. But
|
| 873 |
+
# this is dangerous. Consider:
|
| 874 |
+
#
|
| 875 |
+
# x = torch.tensor(1)
|
| 876 |
+
# x.add_(2)
|
| 877 |
+
#
|
| 878 |
+
# Naively, this traces into:
|
| 879 |
+
#
|
| 880 |
+
# t = self._tensor_constant0 # initialized to torch.tensor(1)
|
| 881 |
+
# x = torch.ops.aten.lift_fresh(t)
|
| 882 |
+
# x.add_(2)
|
| 883 |
+
#
|
| 884 |
+
# If lift_fresh returns t directly, the subsequent add_ call will
|
| 885 |
+
# modify the tensor constant. Really, the problem is we've violated
|
| 886 |
+
# the invariant the argument to lift is fresh. So what we should
|
| 887 |
+
# preserve the invariant by replacing lift_fresh with lift_fresh_copy:
|
| 888 |
+
#
|
| 889 |
+
# t = self._tensor_constant0 # initialized to torch.tensor(1)
|
| 890 |
+
# x = torch.ops.aten.lift_fresh_copy(t)
|
| 891 |
+
# x.add_(2)
|
| 892 |
+
#
|
| 893 |
+
# This is what the overload modification does.
|
| 894 |
+
if func is torch.ops.aten.lift_fresh.default:
|
| 895 |
+
func = torch.ops.aten.lift_fresh_copy.default
|
| 896 |
+
|
| 897 |
+
proxy_out = proxy_mode.tracer.create_proxy(
|
| 898 |
+
"call_function",
|
| 899 |
+
func,
|
| 900 |
+
proxy_args,
|
| 901 |
+
proxy_kwargs,
|
| 902 |
+
name=proxy_mode.tracer.graph._target_to_str(func.overloadpacket.__name__),
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
with _enable_thunkify(proxy_mode.tracer):
|
| 906 |
+
out = func(*args, **kwargs)
|
| 907 |
+
|
| 908 |
+
# In some circumstances, we will be tracing in a situation where a tensor
|
| 909 |
+
# is *statically* known to be a constant (currently, this only happens if
|
| 910 |
+
# you run torch.tensor; deterministic factory functions like torch.arange
|
| 911 |
+
# don't get this treatment). When the tensor in question is small, it's
|
| 912 |
+
# helpful to due constant propagation in case we call item() (in which
|
| 913 |
+
# case we can return the constant value that is known, rather than give
|
| 914 |
+
# an error.) The logic here tests if constant propagation is possible
|
| 915 |
+
# (because all of the inputs are constant). If so, we disable fake tensor
|
| 916 |
+
# mode (if it is on) and do true compute on the constant.
|
| 917 |
+
#
|
| 918 |
+
# It's worth highlighting that we're making a policy decision here.
|
| 919 |
+
# There is a potential that the tensor is actually quite large, and we
|
| 920 |
+
# don't actually want to run the compute. The tensor being quite large
|
| 921 |
+
# is one of the reasons why factory functions don't get this treatment
|
| 922 |
+
# (since they can be quite large; if a parameter is initialized to a
|
| 923 |
+
# constant value it will be!) Similarly, there is also a potential
|
| 924 |
+
# to run an operator that blows up the size of a small tensor; we don't
|
| 925 |
+
# protect against this case, but we could force, e.g., only single
|
| 926 |
+
# element constant computation by testing the numel of the result before
|
| 927 |
+
# propagating const-ness. Similarly, we don't require the constant to
|
| 928 |
+
# live on CPU, but we could.
|
| 929 |
+
any_constant = any(
|
| 930 |
+
t.constant is not None
|
| 931 |
+
for t in f_flat_args_kwargs
|
| 932 |
+
if isinstance(t, _ProxyTensor)
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
constant = None
|
| 936 |
+
|
| 937 |
+
def tensor_numel_in_limit(t: Tensor) -> bool:
|
| 938 |
+
return t.numel() <= CONSTANT_NUMEL_LIMIT
|
| 939 |
+
|
| 940 |
+
# If this is a lift, the input tensor is guaranteed to be a
|
| 941 |
+
# constant, so we keep a copy of the original argument along so
|
| 942 |
+
# we can query it if we're asked to item() it at some later point
|
| 943 |
+
if (
|
| 944 |
+
func is torch.ops.aten.lift_fresh_copy.default
|
| 945 |
+
and out.numel() <= CONSTANT_NUMEL_LIMIT
|
| 946 |
+
):
|
| 947 |
+
with unset_fake_temporarily():
|
| 948 |
+
assert isinstance(args[0], (Proxy, Tensor)), type(args[0])
|
| 949 |
+
constant = args[0].clone()
|
| 950 |
+
elif (
|
| 951 |
+
torch.Tag.nondeterministic_seeded not in func.tags
|
| 952 |
+
and all_constant
|
| 953 |
+
and any_constant
|
| 954 |
+
and pytree.tree_all_only(Tensor, tensor_numel_in_limit, out)
|
| 955 |
+
):
|
| 956 |
+
# NB: do NOT include factories as constants
|
| 957 |
+
with unset_fake_temporarily():
|
| 958 |
+
const_flat_args_kwargs = [
|
| 959 |
+
t.constant if isinstance(t, _ProxyTensor) else t
|
| 960 |
+
for t in f_flat_args_kwargs
|
| 961 |
+
]
|
| 962 |
+
const_args, const_kwargs = pytree.tree_unflatten(
|
| 963 |
+
const_flat_args_kwargs, spec
|
| 964 |
+
)
|
| 965 |
+
constant = func(*const_args, **const_kwargs)
|
| 966 |
+
else:
|
| 967 |
+
constant = None
|
| 968 |
+
|
| 969 |
+
track_tensor_tree(out, proxy_out, constant=constant, tracer=tracer)
|
| 970 |
+
_maybe_record_pointwise_barrier(func, proxy_mode)
|
| 971 |
+
return out
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
class _SymNodeDict:
|
| 975 |
+
"""
|
| 976 |
+
Wrapper around a dictionary that will hash SymInts with their nodes
|
| 977 |
+
"""
|
| 978 |
+
|
| 979 |
+
def __init__(self) -> None:
|
| 980 |
+
self.sym_node_dict: Dict[PySymType, _PySymProxyType] = {}
|
| 981 |
+
|
| 982 |
+
def __setitem__(self, key: PySymType, value: _PySymProxyType) -> None:
|
| 983 |
+
self.sym_node_dict[key.node] = value
|
| 984 |
+
|
| 985 |
+
def __getitem__(self, key: PySymType) -> _PySymProxyType:
|
| 986 |
+
return self.sym_node_dict[key.node]
|
| 987 |
+
|
| 988 |
+
def __contains__(self, key: PySymType) -> bool:
|
| 989 |
+
return key.node in self.sym_node_dict
|
| 990 |
+
|
| 991 |
+
def get(
|
| 992 |
+
self, key: PySymType, default: Optional[_PySymProxyType] = None
|
| 993 |
+
) -> _PySymProxyType:
|
| 994 |
+
# dict.get()'s annotation doesn't accept `None` when the value type
|
| 995 |
+
# isn't Optional.
|
| 996 |
+
return self.sym_node_dict.get(key.node, default) # type: ignore[arg-type]
|
| 997 |
+
|
| 998 |
+
def __iter__(self) -> Any:
|
| 999 |
+
raise NotImplementedError
|
| 1000 |
+
|
| 1001 |
+
def __len__(self) -> int:
|
| 1002 |
+
return len(self.sym_node_dict)
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
class PythonKeyTracer(Tracer):
|
| 1006 |
+
script_object_tracker: MutableMapping[_AnyScriptObjectType, Proxy]
|
| 1007 |
+
symnode_tracker: _SymNodeDict
|
| 1008 |
+
sympy_expr_tracker: Dict[sympy.Symbol, object]
|
| 1009 |
+
tensor_tracker: MutableMapping[Tensor, _ProxyTensor]
|
| 1010 |
+
torch_fn_counts: Dict[OpOverload, int]
|
| 1011 |
+
enable_thunkify: bool = False
|
| 1012 |
+
|
| 1013 |
+
def __init__(self) -> None:
|
| 1014 |
+
super().__init__(autowrap_modules=()) # type: ignore[arg-type]
|
| 1015 |
+
self.tensor_tracker = WeakTensorKeyDictionary()
|
| 1016 |
+
self.symnode_tracker = _SymNodeDict()
|
| 1017 |
+
self.script_object_tracker = WeakIdKeyDictionary(
|
| 1018 |
+
dict=None, ref_type=_WeakHashRef
|
| 1019 |
+
)
|
| 1020 |
+
self.sympy_expr_tracker = dict()
|
| 1021 |
+
|
| 1022 |
+
# Stores the torch function that was called during tracing
|
| 1023 |
+
self.torch_fn_metadata = None
|
| 1024 |
+
# Stores the counts for every torch function called. This is to help
|
| 1025 |
+
# distinguish between different calls to the same torch function.
|
| 1026 |
+
self.torch_fn_counts = {}
|
| 1027 |
+
self.enable_thunkify = False
|
| 1028 |
+
|
| 1029 |
+
# In general, we don't want to make modules leaves. In principle, users of
|
| 1030 |
+
# this tracer might want to override this in order to turn a couple specific
|
| 1031 |
+
# modules into leaves in the traced graph.
|
| 1032 |
+
def call_module(
|
| 1033 |
+
self,
|
| 1034 |
+
m: Module,
|
| 1035 |
+
forward: Callable[..., Any],
|
| 1036 |
+
args: Tuple[Any, ...],
|
| 1037 |
+
kwargs: Dict[str, Any],
|
| 1038 |
+
) -> Any:
|
| 1039 |
+
return forward(*args, **kwargs)
|
| 1040 |
+
|
| 1041 |
+
# We don't want to turn getattr calls into proxies. So we just return the actual value.
|
| 1042 |
+
def getattr(
|
| 1043 |
+
self, attr: str, attr_val: object, parameter_proxy_cache: Dict[str, Proxy]
|
| 1044 |
+
) -> object:
|
| 1045 |
+
return attr_val
|
| 1046 |
+
|
| 1047 |
+
def create_arg(self, a: object) -> fx.node.Node:
|
| 1048 |
+
if isinstance(a, torch.nn.Parameter):
|
| 1049 |
+
for n, p in self.root.named_parameters():
|
| 1050 |
+
if a is p:
|
| 1051 |
+
return self.create_node("get_attr", n, (), {})
|
| 1052 |
+
|
| 1053 |
+
qualname = self.get_fresh_qualname("_param_constant")
|
| 1054 |
+
setattr(self.root, qualname, a)
|
| 1055 |
+
|
| 1056 |
+
return self.create_node("get_attr", qualname, (), {})
|
| 1057 |
+
elif isinstance(a, py_sym_types):
|
| 1058 |
+
assert a.node.constant is not None
|
| 1059 |
+
return a.node.constant
|
| 1060 |
+
return super().create_arg(a) # type: ignore[return-value]
|
| 1061 |
+
|
| 1062 |
+
@overload
|
| 1063 |
+
def unwrap_proxy(self, e: Tensor) -> Union[Proxy, Tensor]:
|
| 1064 |
+
...
|
| 1065 |
+
|
| 1066 |
+
@overload
|
| 1067 |
+
def unwrap_proxy(self, e: PySymType) -> Union[Proxy, PySymType]:
|
| 1068 |
+
...
|
| 1069 |
+
|
| 1070 |
+
@overload
|
| 1071 |
+
def unwrap_proxy(
|
| 1072 |
+
self, e: _AnyScriptObjectType
|
| 1073 |
+
) -> Union[Proxy, _AnyScriptObjectType]:
|
| 1074 |
+
...
|
| 1075 |
+
|
| 1076 |
+
def unwrap_proxy(self, e: T) -> object:
|
| 1077 |
+
if isinstance(e, Tensor):
|
| 1078 |
+
return get_proxy_slot(e, self, e, lambda x: x.proxy)
|
| 1079 |
+
elif isinstance(e, py_sym_types):
|
| 1080 |
+
return get_proxy_slot(e, self, e, lambda e: e.force())
|
| 1081 |
+
elif isinstance(e, _AnyScriptObject):
|
| 1082 |
+
return get_proxy_slot(e, self, e)
|
| 1083 |
+
else:
|
| 1084 |
+
return e
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
@contextmanager
|
| 1088 |
+
def _temp_remove_pre_dispatch_torch_function_mode() -> Generator[None, None, None]:
|
| 1089 |
+
from torch.overrides import _len_torch_function_stack, _pop_mode, _push_mode
|
| 1090 |
+
|
| 1091 |
+
temp_elements = []
|
| 1092 |
+
pre_dispatch_mode = None
|
| 1093 |
+
|
| 1094 |
+
while _len_torch_function_stack() > 0:
|
| 1095 |
+
mode = _pop_mode()
|
| 1096 |
+
if isinstance(mode, PreDispatchTorchFunctionMode):
|
| 1097 |
+
pre_dispatch_mode = mode
|
| 1098 |
+
break
|
| 1099 |
+
else:
|
| 1100 |
+
temp_elements.append(mode)
|
| 1101 |
+
|
| 1102 |
+
for mode in reversed(temp_elements):
|
| 1103 |
+
_push_mode(mode)
|
| 1104 |
+
|
| 1105 |
+
try:
|
| 1106 |
+
yield
|
| 1107 |
+
|
| 1108 |
+
finally:
|
| 1109 |
+
if pre_dispatch_mode is not None:
|
| 1110 |
+
count = len(temp_elements)
|
| 1111 |
+
while count > 0:
|
| 1112 |
+
mode = _pop_mode()
|
| 1113 |
+
count -= 1
|
| 1114 |
+
|
| 1115 |
+
temp_elements.append(pre_dispatch_mode)
|
| 1116 |
+
|
| 1117 |
+
for mode in reversed(temp_elements):
|
| 1118 |
+
_push_mode(mode)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
@torch._disable_dynamo
|
| 1122 |
+
def dispatch_trace(
|
| 1123 |
+
root: Union[Module, Callable],
|
| 1124 |
+
tracer: Tracer,
|
| 1125 |
+
concrete_args: Optional[Tuple[Any, ...]] = None,
|
| 1126 |
+
) -> GraphModule:
|
| 1127 |
+
graph = tracer.trace(root, concrete_args) # type: ignore[arg-type]
|
| 1128 |
+
|
| 1129 |
+
# NB: be careful not to DCE .item() calls
|
| 1130 |
+
def impure_pred(n: fx.Node) -> bool:
|
| 1131 |
+
from .symbolic_shapes import is_accessor_node
|
| 1132 |
+
|
| 1133 |
+
# Always defer to the built-in notion of impure
|
| 1134 |
+
if n.is_impure():
|
| 1135 |
+
return True
|
| 1136 |
+
|
| 1137 |
+
# Accessors always OK to DCE
|
| 1138 |
+
if is_accessor_node(n):
|
| 1139 |
+
return False
|
| 1140 |
+
|
| 1141 |
+
# If the operator in question takes SymInt args to SymInt output,
|
| 1142 |
+
# we assume it's pure and OK to DCE
|
| 1143 |
+
if (
|
| 1144 |
+
isinstance(n.meta.get("val"), py_sym_types)
|
| 1145 |
+
and
|
| 1146 |
+
# NB: constant args ok
|
| 1147 |
+
all(
|
| 1148 |
+
isinstance(a.meta.get("val"), py_sym_types)
|
| 1149 |
+
for a in n.args
|
| 1150 |
+
if isinstance(a, fx.Node)
|
| 1151 |
+
)
|
| 1152 |
+
):
|
| 1153 |
+
return False
|
| 1154 |
+
|
| 1155 |
+
# No idea, just assume it's not OK
|
| 1156 |
+
return True
|
| 1157 |
+
|
| 1158 |
+
graph.eliminate_dead_code(impure_pred)
|
| 1159 |
+
from torch._inductor.fx_passes.dedupe_symint_uses import dedupe_symints
|
| 1160 |
+
|
| 1161 |
+
dedupe_symints(graph)
|
| 1162 |
+
name = root.__class__.__name__ if isinstance(root, Module) else root.__name__
|
| 1163 |
+
return fx._lazy_graph_module._make_graph_module(tracer.root, graph, name)
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
def wrap_key(
|
| 1167 |
+
f: Callable[_P, R], tensors: _P.args, tracer: _ProxyTracer, pre_dispatch: bool
|
| 1168 |
+
) -> Callable[_P, R]:
|
| 1169 |
+
flat_tensors, tensors_spec = pytree.tree_flatten(tensors)
|
| 1170 |
+
|
| 1171 |
+
@functools.wraps(f)
|
| 1172 |
+
def wrapped(*proxies: _P.args, **_unused: _P.kwargs) -> R:
|
| 1173 |
+
flat_proxies, proxies_spec = pytree.tree_flatten(proxies)
|
| 1174 |
+
assert len(flat_proxies) == len(flat_tensors)
|
| 1175 |
+
with disable_proxy_modes_tracing() as m:
|
| 1176 |
+
assert isinstance(m, ProxyTorchDispatchMode)
|
| 1177 |
+
track_tensor_tree(flat_tensors, flat_proxies, constant=None, tracer=tracer)
|
| 1178 |
+
|
| 1179 |
+
def get_tensor_proxy_slot(t: Tensor) -> Union[Tensor, Proxy]:
|
| 1180 |
+
return get_proxy_slot(t, tracer, t, lambda x: x.proxy)
|
| 1181 |
+
|
| 1182 |
+
out = f(*tensors)
|
| 1183 |
+
out = pytree.tree_map_only(Tensor, get_tensor_proxy_slot, out)
|
| 1184 |
+
out = pytree.tree_map_only(
|
| 1185 |
+
_AnyScriptObject, lambda t: get_proxy_slot(t, tracer, t, lambda x: x), out
|
| 1186 |
+
)
|
| 1187 |
+
|
| 1188 |
+
def get_sym_proxy_slot(t: PySymType) -> Proxy:
|
| 1189 |
+
return get_proxy_slot(t, tracer).force()
|
| 1190 |
+
|
| 1191 |
+
out = pytree.tree_map_only(py_sym_types, get_sym_proxy_slot, out)
|
| 1192 |
+
return out
|
| 1193 |
+
|
| 1194 |
+
return wrapped
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
# TODO: Make downstream users of this work with OperatorBase
|
| 1198 |
+
ORIGINAL_ATEN: Optional[object] = None
|
| 1199 |
+
|
| 1200 |
+
|
| 1201 |
+
@contextmanager
|
| 1202 |
+
def set_original_aten_op(func: OpOverload) -> Generator[None, None, None]:
|
| 1203 |
+
global ORIGINAL_ATEN
|
| 1204 |
+
if ORIGINAL_ATEN is None and fx_traceback.has_preserved_node_meta():
|
| 1205 |
+
ORIGINAL_ATEN = func
|
| 1206 |
+
fx_traceback.current_meta["original_aten"] = func
|
| 1207 |
+
try:
|
| 1208 |
+
yield
|
| 1209 |
+
finally:
|
| 1210 |
+
ORIGINAL_ATEN = None
|
| 1211 |
+
fx_traceback.current_meta["original_aten"] = None
|
| 1212 |
+
else:
|
| 1213 |
+
yield
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
class TorchFunctionMetadataMode(TorchFunctionMode):
|
| 1217 |
+
def __init__(self, tracer: _ProxyTracer) -> None:
|
| 1218 |
+
self.tracer = tracer
|
| 1219 |
+
|
| 1220 |
+
def __torch_function__(
|
| 1221 |
+
self,
|
| 1222 |
+
func: OpOverload,
|
| 1223 |
+
types: Tuple[torch._C._TensorMeta, ...],
|
| 1224 |
+
args: Tuple[object, ...] = (),
|
| 1225 |
+
kwargs: Optional[Dict[str, object]] = None,
|
| 1226 |
+
) -> object:
|
| 1227 |
+
kwargs = kwargs or {}
|
| 1228 |
+
self.tracer.torch_fn_metadata = func
|
| 1229 |
+
self.tracer.torch_fn_counts[func] = self.tracer.torch_fn_counts.get(func, 0) + 1
|
| 1230 |
+
return func(*args, **kwargs)
|
| 1231 |
+
|
| 1232 |
+
|
| 1233 |
+
# This mode is **only** used for pre_dispatch tracing.
|
| 1234 |
+
# In particular, we need to make sure that autograd/autocast API's
|
| 1235 |
+
# that do not desugar into dispatcher operators stay in the graph.
|
| 1236 |
+
class PreDispatchTorchFunctionMode(TorchFunctionMode):
|
| 1237 |
+
def __init__(self, tracer: _ProxyTracer) -> None:
|
| 1238 |
+
self.tracer = tracer
|
| 1239 |
+
|
| 1240 |
+
def __torch_function__(
|
| 1241 |
+
self,
|
| 1242 |
+
func: OpOverload,
|
| 1243 |
+
types: Tuple[torch._C._TensorMeta, ...],
|
| 1244 |
+
args: Tuple[object, ...] = (),
|
| 1245 |
+
kwargs: Optional[Dict[str, object]] = None,
|
| 1246 |
+
) -> object:
|
| 1247 |
+
kwargs = kwargs or {}
|
| 1248 |
+
if func in _side_effectful_need_to_be_preserved_pre_dispatch:
|
| 1249 |
+
# It's for passing the export verifier which needs to verify the meta['val']
|
| 1250 |
+
# TODO(tmanlaibaatar): we should systematically couple it with expoert verifier,
|
| 1251 |
+
# instead of hardcoding it here.
|
| 1252 |
+
node = self.tracer.create_node("call_function", func, args, {}) # type: ignore[arg-type]
|
| 1253 |
+
if func is torch._C._set_grad_enabled:
|
| 1254 |
+
node.meta["val"] = None
|
| 1255 |
+
return node
|
| 1256 |
+
# Don't actually run the function! We just want to trace the calls
|
| 1257 |
+
# into a graph. We don't actualy want to change global autograd state.
|
| 1258 |
+
return func(*args, **kwargs)
|
| 1259 |
+
|
| 1260 |
+
|
| 1261 |
+
class ProxyTorchDispatchMode(TorchDispatchMode):
|
| 1262 |
+
# Ensure this is read-only; this exists only for legacy reasons
|
| 1263 |
+
@property
|
| 1264 |
+
def enable_tracing(self) -> bool:
|
| 1265 |
+
return True
|
| 1266 |
+
|
| 1267 |
+
def __init__(
|
| 1268 |
+
self,
|
| 1269 |
+
tracer: _ProxyTracer,
|
| 1270 |
+
tracing_mode: str,
|
| 1271 |
+
pre_dispatch: bool = False,
|
| 1272 |
+
_allow_fake_constant: bool = False,
|
| 1273 |
+
_error_on_data_dependent_ops: bool = True,
|
| 1274 |
+
) -> None:
|
| 1275 |
+
dk = torch._C.DispatchKey.PreDispatch if pre_dispatch else None
|
| 1276 |
+
super().__init__(dk)
|
| 1277 |
+
self.tracer = tracer
|
| 1278 |
+
self.tracing_mode = tracing_mode
|
| 1279 |
+
self.pre_dispatch = pre_dispatch
|
| 1280 |
+
self._allow_fake_constant = _allow_fake_constant
|
| 1281 |
+
self._error_on_data_dependent_ops = _error_on_data_dependent_ops
|
| 1282 |
+
# Indicates to our torch_dispatch dispatching infra that
|
| 1283 |
+
# this is an "infra" mode with lower dispatching precedence.
|
| 1284 |
+
self._mode_key = torch._C._TorchDispatchModeKey.PROXY
|
| 1285 |
+
# Every time we enter a mode, we maintain a stack telling us what the previous
|
| 1286 |
+
# ProxyTorchDispatchMode state was (if there was any).
|
| 1287 |
+
# This lets us properly reset the state on exit.
|
| 1288 |
+
self.enter_stack: List[Optional[ProxyTorchDispatchMode]] = []
|
| 1289 |
+
self.decomp_layers = 0
|
| 1290 |
+
from torch._inductor import config
|
| 1291 |
+
|
| 1292 |
+
self.emulate_precision_casts = config.emulate_precision_casts
|
| 1293 |
+
|
| 1294 |
+
@count
|
| 1295 |
+
def __torch_dispatch__(
|
| 1296 |
+
self,
|
| 1297 |
+
func: OpOverload,
|
| 1298 |
+
types: Tuple[torch._C._TensorMeta, ...],
|
| 1299 |
+
args: Tuple[object, ...] = (),
|
| 1300 |
+
kwargs: Optional[Dict[str, object]] = None,
|
| 1301 |
+
) -> object:
|
| 1302 |
+
with set_original_aten_op(func):
|
| 1303 |
+
kwargs = kwargs or {}
|
| 1304 |
+
|
| 1305 |
+
if func in (prim.device.default,):
|
| 1306 |
+
return func(*args, **kwargs)
|
| 1307 |
+
|
| 1308 |
+
return proxy_call(self, func, self.pre_dispatch, args, kwargs)
|
| 1309 |
+
|
| 1310 |
+
def __enter__(self) -> Self:
|
| 1311 |
+
# Stash and store the previous proxy mode (there may or may not be one)
|
| 1312 |
+
maybe_prev_proxy_mode = _unset_infra_mode(torch._C._TorchDispatchModeKey.PROXY)
|
| 1313 |
+
self.enter_stack.append(maybe_prev_proxy_mode)
|
| 1314 |
+
return super().__enter__()
|
| 1315 |
+
|
| 1316 |
+
def __exit__(
|
| 1317 |
+
self,
|
| 1318 |
+
exc_type: Optional[Type[BaseException]],
|
| 1319 |
+
exc_value: Optional[BaseException],
|
| 1320 |
+
traceback: Optional[types.TracebackType],
|
| 1321 |
+
) -> Optional[bool]:
|
| 1322 |
+
b = super().__exit__(exc_type, exc_value, traceback)
|
| 1323 |
+
|
| 1324 |
+
# Re-enable the previous proxy mode, if there was one.
|
| 1325 |
+
mb_previous_proxy_mode = self.enter_stack.pop()
|
| 1326 |
+
if mb_previous_proxy_mode is not None:
|
| 1327 |
+
_push_mode(mb_previous_proxy_mode)
|
| 1328 |
+
|
| 1329 |
+
return b
|
| 1330 |
+
|
| 1331 |
+
@classmethod
|
| 1332 |
+
def is_infra_mode(cls) -> bool:
|
| 1333 |
+
return True
|
| 1334 |
+
|
| 1335 |
+
def _compute_proxy(
|
| 1336 |
+
self, func: OpOverload, args: Tuple[object, ...], out: PySymType
|
| 1337 |
+
) -> Proxy:
|
| 1338 |
+
n_args = tuple(
|
| 1339 |
+
get_proxy_slot(a, self.tracer).force().node
|
| 1340 |
+
if isinstance(a, py_sym_types)
|
| 1341 |
+
else a
|
| 1342 |
+
for a in args
|
| 1343 |
+
)
|
| 1344 |
+
|
| 1345 |
+
# func doesn't have a __torch_function__ that Proxy can interpose, so
|
| 1346 |
+
# we gotta do it manually
|
| 1347 |
+
n_out = self.tracer.create_node("call_function", func, n_args, {}) # type: ignore[arg-type]
|
| 1348 |
+
p_out = fx.Proxy(n_out, self.tracer)
|
| 1349 |
+
set_meta(p_out, out)
|
| 1350 |
+
return p_out
|
| 1351 |
+
|
| 1352 |
+
def __sym_dispatch__(
|
| 1353 |
+
self,
|
| 1354 |
+
func: OpOverload,
|
| 1355 |
+
types: Tuple[torch._C._TensorMeta, ...],
|
| 1356 |
+
args: Tuple[object, ...],
|
| 1357 |
+
kwargs: Dict[str, object],
|
| 1358 |
+
) -> object:
|
| 1359 |
+
# Peephole optimize multiply by one
|
| 1360 |
+
# NB: be careful not to trigger guards here!
|
| 1361 |
+
if func == operator.mul:
|
| 1362 |
+
if isinstance(args[1], int) and args[1] == 1:
|
| 1363 |
+
return args[0]
|
| 1364 |
+
elif isinstance(args[0], int) and args[0] == 1:
|
| 1365 |
+
return args[1]
|
| 1366 |
+
|
| 1367 |
+
# For speed, we assume there are no nested data structures
|
| 1368 |
+
# (otherwise we could use tree_map)
|
| 1369 |
+
# We also assume there are no keyword arguments.
|
| 1370 |
+
assert not kwargs
|
| 1371 |
+
out = func(*args, **kwargs)
|
| 1372 |
+
|
| 1373 |
+
# If func returned a constant, we don't need to trace; we have
|
| 1374 |
+
# determined that the result is constant (no matter if the inputs
|
| 1375 |
+
# were symbolic) and it is no longer necessary to trace the
|
| 1376 |
+
# computation. This could occur if func triggered some guards.
|
| 1377 |
+
if isinstance(out, py_sym_types):
|
| 1378 |
+
p_out_thunk = thunkify(
|
| 1379 |
+
self.tracer, self._compute_proxy, func=func, args=args, out=out
|
| 1380 |
+
)
|
| 1381 |
+
set_proxy_slot(out, self.tracer, p_out_thunk)
|
| 1382 |
+
|
| 1383 |
+
return out
|
| 1384 |
+
|
| 1385 |
+
|
| 1386 |
+
class _GraphAppendingTracerEx(fx.proxy.GraphAppendingTracer):
|
| 1387 |
+
script_object_tracker: MutableMapping[_AnyScriptObjectType, Proxy]
|
| 1388 |
+
symnode_tracker: MutableMapping[PySymType, _PySymProxyType]
|
| 1389 |
+
tensor_tracker: MutableMapping[Tensor, _ProxyTensor]
|
| 1390 |
+
sympy_expr_tracker: Dict[sympy.Symbol, object]
|
| 1391 |
+
torch_fn_metadata: Optional[OpOverload]
|
| 1392 |
+
torch_fn_counts: Dict[OpOverload, int]
|
| 1393 |
+
enable_thunkify: bool = False
|
| 1394 |
+
|
| 1395 |
+
def __init__(self, graph: fx.graph.Graph) -> None:
|
| 1396 |
+
super().__init__(graph)
|
| 1397 |
+
self.symnode_tracker = weakref.WeakKeyDictionary()
|
| 1398 |
+
self.tensor_tracker = WeakTensorKeyDictionary()
|
| 1399 |
+
self.sympy_expr_tracker = {}
|
| 1400 |
+
self.script_object_tracker = WeakIdKeyDictionary(
|
| 1401 |
+
dict=None, ref_type=_WeakHashRef
|
| 1402 |
+
)
|
| 1403 |
+
# Stores the torch function that was called during tracing
|
| 1404 |
+
self.torch_fn_metadata = None
|
| 1405 |
+
# Stores the counts for every torch function called. This is to help
|
| 1406 |
+
# distinguish between different calls to the same torch function.
|
| 1407 |
+
self.torch_fn_counts = {}
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
# TODO: I'm not sure what the point of this class is; you can just
|
| 1411 |
+
# make_fx through a regular Interpreter
|
| 1412 |
+
class DecompositionInterpreter(fx.Interpreter):
|
| 1413 |
+
def __init__(
|
| 1414 |
+
self,
|
| 1415 |
+
module: fx.GraphModule,
|
| 1416 |
+
new_graph: fx.Graph,
|
| 1417 |
+
decomposition_table: Optional[Mapping[OpOverload, Callable]] = None,
|
| 1418 |
+
**kwargs: object,
|
| 1419 |
+
) -> None:
|
| 1420 |
+
super().__init__(module, **kwargs) # type: ignore[arg-type]
|
| 1421 |
+
self.new_graph = new_graph
|
| 1422 |
+
self.tracer = _GraphAppendingTracerEx(self.new_graph)
|
| 1423 |
+
# Blegh
|
| 1424 |
+
self.decomposition_table = decomposition_table or {}
|
| 1425 |
+
self.mode = ProxyTorchDispatchMode(self.tracer, tracing_mode="real")
|
| 1426 |
+
|
| 1427 |
+
def placeholder(
|
| 1428 |
+
self, target: str, args: Tuple[object, ...], kwargs: Dict[str, object] # type: ignore[override]
|
| 1429 |
+
) -> object:
|
| 1430 |
+
out = super().placeholder(target, args, kwargs) # type: ignore[arg-type]
|
| 1431 |
+
proxy = fx.Proxy(self.new_graph.placeholder(target), self.tracer)
|
| 1432 |
+
track_tensor_tree(out, proxy, constant=None, tracer=self.tracer)
|
| 1433 |
+
# TODO handle case where the first character of target is '*'
|
| 1434 |
+
return out
|
| 1435 |
+
|
| 1436 |
+
def get_attr(
|
| 1437 |
+
self, target: str, args: Tuple[object, ...], kwargs: Dict[str, object] # type: ignore[override]
|
| 1438 |
+
) -> object:
|
| 1439 |
+
out = super().get_attr(target, args, kwargs) # type: ignore[arg-type]
|
| 1440 |
+
proxy = fx.Proxy(self.new_graph.get_attr(target), self.tracer)
|
| 1441 |
+
track_tensor_tree(out, proxy, constant=None, tracer=self.tracer)
|
| 1442 |
+
return out
|
| 1443 |
+
|
| 1444 |
+
# call_function, call_method, call_module get traced automatically by the outer mode.
|
| 1445 |
+
|
| 1446 |
+
def output(
|
| 1447 |
+
self, target: str, args: Tuple[object, ...], kwargs: Dict[str, object] # type: ignore[override]
|
| 1448 |
+
) -> object:
|
| 1449 |
+
out = super().output(target, args, kwargs) # type: ignore[arg-type]
|
| 1450 |
+
|
| 1451 |
+
def get_proxy_node(x: _ProxyTensor) -> fx.node.Node:
|
| 1452 |
+
return x.proxy.node
|
| 1453 |
+
|
| 1454 |
+
def unwrap(e: Tensor) -> Union[Tensor, fx.Node]:
|
| 1455 |
+
return get_proxy_slot(e, self.tracer, e, get_proxy_node)
|
| 1456 |
+
|
| 1457 |
+
self.new_graph.output(pytree.tree_map(unwrap, out))
|
| 1458 |
+
return out
|
| 1459 |
+
|
| 1460 |
+
def run(self, *args: object, **kwargs: object) -> object:
|
| 1461 |
+
# Should enter the mode at least once for being able to restore it later
|
| 1462 |
+
# See: https://github.com/pytorch/pytorch/pull/82549#discussion_r934782025
|
| 1463 |
+
with decompose(self.decomposition_table), self.mode:
|
| 1464 |
+
return super().run(*args, **kwargs) # type: ignore[arg-type]
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
def wrapper_and_args_for_make_fx(
|
| 1468 |
+
func: Callable[..., R], args: Tuple[object, ...], kwargs: Dict[str, object]
|
| 1469 |
+
) -> Tuple[Callable[[List[object]], R], List[object]]:
|
| 1470 |
+
# make_fx doesn't support kwargs, so we need to do this flattening
|
| 1471 |
+
# and then unflatten the args before calling func
|
| 1472 |
+
flat_args, spec = pytree.tree_flatten((args, kwargs))
|
| 1473 |
+
|
| 1474 |
+
def wrapped(flat_args: List[object]) -> R:
|
| 1475 |
+
fn_args, fn_kwargs = pytree.tree_unflatten(flat_args, spec)
|
| 1476 |
+
return func(*fn_args, **fn_kwargs)
|
| 1477 |
+
|
| 1478 |
+
return wrapped, flat_args
|
| 1479 |
+
|
| 1480 |
+
|
| 1481 |
+
@contextmanager
|
| 1482 |
+
def disable_autocast_cache() -> Generator[None, None, None]:
|
| 1483 |
+
old_value = torch.is_autocast_cache_enabled()
|
| 1484 |
+
torch.set_autocast_cache_enabled(False)
|
| 1485 |
+
try:
|
| 1486 |
+
yield
|
| 1487 |
+
finally:
|
| 1488 |
+
torch.set_autocast_cache_enabled(old_value)
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
class _ModuleNotInstalledAsSubmoduleError(NameError):
|
| 1492 |
+
pass
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
# Base class for inline _ModuleStackTracer.__init__.AttrProxy
|
| 1496 |
+
class _AttrProxy:
|
| 1497 |
+
def reset_proxy_mapping(self, base: Module, path: str) -> None:
|
| 1498 |
+
pass
|
| 1499 |
+
|
| 1500 |
+
|
| 1501 |
+
class _ModuleStackTracer(PythonKeyTracer):
|
| 1502 |
+
r"""Customized version of PythonKeyTracer that retains module stack
|
| 1503 |
+
information in node.meta["nn_module_stack"].
|
| 1504 |
+
|
| 1505 |
+
FX symbolic trace actually does this already, but it relies on `self.root`
|
| 1506 |
+
being the actual module being traced. Since make_fx traces a lambda of our
|
| 1507 |
+
creation, things don't work properly.
|
| 1508 |
+
|
| 1509 |
+
So for this version we hold onto a reference to the original module
|
| 1510 |
+
(scope_root) and use that to match the path. Also when we see,
|
| 1511 |
+
A
|
| 1512 |
+
/ \
|
| 1513 |
+
B C
|
| 1514 |
+
\ /
|
| 1515 |
+
D
|
| 1516 |
+
we want to record the path as A.B.D by recording only one path.
|
| 1517 |
+
See Note [Preserving the nn module stack metadata during export non-strict mode] # noqa: W605
|
| 1518 |
+
"""
|
| 1519 |
+
|
| 1520 |
+
def __init__(self, scope_root: GraphModule) -> None:
|
| 1521 |
+
super().__init__()
|
| 1522 |
+
self.scope_root = scope_root
|
| 1523 |
+
self.proxy_paths: WeakKeyDictionary[_AttrProxy, str] = WeakKeyDictionary()
|
| 1524 |
+
self.attr_proxy_map: WeakKeyDictionary[Module, _AttrProxy] = WeakKeyDictionary()
|
| 1525 |
+
self.proxy_modules: WeakKeyDictionary[_AttrProxy, Module] = WeakKeyDictionary()
|
| 1526 |
+
self.counter = 0
|
| 1527 |
+
|
| 1528 |
+
self.module_id_cache = defaultdict(list)
|
| 1529 |
+
for name, mod in self.scope_root.named_modules(remove_duplicate=False):
|
| 1530 |
+
self.module_id_cache[id(mod)].append(name)
|
| 1531 |
+
|
| 1532 |
+
# Build a wrapper around _AttrProxy to provide the tracer. We can't
|
| 1533 |
+
# store it on _AttrProxy itself beceause we mimic the underlying class
|
| 1534 |
+
# (including its attributes).
|
| 1535 |
+
tracer = self
|
| 1536 |
+
|
| 1537 |
+
class AttrProxy(_AttrProxy):
|
| 1538 |
+
def __init__(self, base: Module, path: str) -> None:
|
| 1539 |
+
# Class is modified to be a subclass of torch.nn.Module
|
| 1540 |
+
# Warning: We blow away our own attributes here to mimic the base class
|
| 1541 |
+
# - so don't expect `self.x` to do anything useful.
|
| 1542 |
+
self.__class__ = type(
|
| 1543 |
+
base.__class__.__name__,
|
| 1544 |
+
(self.__class__, base.__class__),
|
| 1545 |
+
{},
|
| 1546 |
+
)
|
| 1547 |
+
self.__dict__ = base.__dict__
|
| 1548 |
+
self.__class__.__module__ = base.__class__.__module__
|
| 1549 |
+
self.__class__.__qualname__ = base.__class__.__qualname__
|
| 1550 |
+
self.reset_proxy_mapping(base, path)
|
| 1551 |
+
|
| 1552 |
+
def reset_proxy_mapping(self, base: Module, path: str) -> None:
|
| 1553 |
+
tracer.proxy_paths[self] = path
|
| 1554 |
+
tracer.proxy_modules[self] = base
|
| 1555 |
+
|
| 1556 |
+
def __getattr__(self, name: str) -> AttrProxy:
|
| 1557 |
+
assert isinstance(self, Module)
|
| 1558 |
+
# Calling into torch.nn.Module.__getattr__ with super(),
|
| 1559 |
+
# That __getattr__ is patched to be module_getattr_wrapper in _symbolic_trace.py.
|
| 1560 |
+
# which then calls into _ModuleStackTracer.getattr
|
| 1561 |
+
attr_val = super().__getattr__(name) # type: ignore[misc]
|
| 1562 |
+
if isinstance(attr_val, AttrProxy):
|
| 1563 |
+
attr_val = tracer.proxy_modules[attr_val]
|
| 1564 |
+
elif not isinstance(attr_val, Module):
|
| 1565 |
+
return attr_val
|
| 1566 |
+
if attr_val not in tracer.attr_proxy_map:
|
| 1567 |
+
tracer.attr_proxy_map[attr_val] = AttrProxy(
|
| 1568 |
+
attr_val, tracer.proxy_paths[self] + "." + name
|
| 1569 |
+
)
|
| 1570 |
+
else:
|
| 1571 |
+
# NOTE [caching AttrProxy]. Caching ensures a 1-1 mapping between AttrProxy and the actual attr_val.
|
| 1572 |
+
# 1. We reset the proxy_mapping to solve the diamond shape reference problem: we want to record the
|
| 1573 |
+
# path as A.B.D instead of A.C.D (the purpose of _ModuleStackTracer).
|
| 1574 |
+
# 2. Instead of creating a new AttrProxy, we just reset the proxy_mapping of existing one. This is to avoid
|
| 1575 |
+
# dynamo creating multiple guards for the same attr_val but different AttrProxy when exporting
|
| 1576 |
+
# a model that calls torch.compile (e.g when a model uses torch.cond.)
|
| 1577 |
+
tracer.attr_proxy_map[attr_val].reset_proxy_mapping(
|
| 1578 |
+
attr_val, tracer.proxy_paths[self] + "." + name
|
| 1579 |
+
)
|
| 1580 |
+
return tracer.attr_proxy_map[attr_val]
|
| 1581 |
+
|
| 1582 |
+
def get_base(self) -> Module:
|
| 1583 |
+
return tracer.proxy_modules[self]
|
| 1584 |
+
|
| 1585 |
+
@property
|
| 1586 |
+
def _modules(self) -> Dict[str, AttrProxy]:
|
| 1587 |
+
assert "_modules" in self.__dict__
|
| 1588 |
+
submodules = self.__dict__["_modules"]
|
| 1589 |
+
assert isinstance(submodules, dict)
|
| 1590 |
+
return {
|
| 1591 |
+
key: AttrProxy(value, tracer.proxy_paths[self] + "." + str(key))
|
| 1592 |
+
for key, value in submodules.items()
|
| 1593 |
+
}
|
| 1594 |
+
|
| 1595 |
+
self.proxy_type = AttrProxy
|
| 1596 |
+
|
| 1597 |
+
def path_of_module(self, mod: Module) -> str:
|
| 1598 |
+
"""
|
| 1599 |
+
Use tracked access path during tracing instead of the default BFS behavior.
|
| 1600 |
+
Still use all the possible module paths to verify the result.
|
| 1601 |
+
"""
|
| 1602 |
+
if mod is self.scope_root:
|
| 1603 |
+
return ""
|
| 1604 |
+
|
| 1605 |
+
if isinstance(mod, _AttrProxy):
|
| 1606 |
+
return self.proxy_paths[mod]
|
| 1607 |
+
|
| 1608 |
+
try:
|
| 1609 |
+
return Tracer.path_of_module(self, mod)
|
| 1610 |
+
except NameError as e:
|
| 1611 |
+
raise _ModuleNotInstalledAsSubmoduleError from e
|
| 1612 |
+
|
| 1613 |
+
def getattr(
|
| 1614 |
+
self, attr: str, attr_val: object, parameter_proxy_cache: Dict[str, Proxy]
|
| 1615 |
+
) -> object:
|
| 1616 |
+
if not isinstance(attr_val, Module) or isinstance(attr_val, fx.GraphModule):
|
| 1617 |
+
return super().getattr(attr, attr_val, parameter_proxy_cache)
|
| 1618 |
+
if isinstance(attr_val, _AttrProxy):
|
| 1619 |
+
return attr_val
|
| 1620 |
+
|
| 1621 |
+
# See NOTE [caching AttrProxy].
|
| 1622 |
+
if attr_val not in self.attr_proxy_map:
|
| 1623 |
+
self.attr_proxy_map[attr_val] = self.proxy_type(attr_val, attr)
|
| 1624 |
+
else:
|
| 1625 |
+
self.attr_proxy_map[attr_val].reset_proxy_mapping(attr_val, attr)
|
| 1626 |
+
return self.attr_proxy_map[attr_val]
|
| 1627 |
+
|
| 1628 |
+
def trace( # type: ignore[override]
|
| 1629 |
+
self, root: Union[Module, Callable], concrete_args: Optional[Dict[str, object]]
|
| 1630 |
+
) -> fx.Graph:
|
| 1631 |
+
res = super().trace(root, concrete_args)
|
| 1632 |
+
|
| 1633 |
+
# Since we are making _AttrProxy mimic the original
|
| 1634 |
+
# submodule, when someone registers a module directly
|
| 1635 |
+
# to the tracer while tracing, the proxy object gets registered
|
| 1636 |
+
# first. So we need to replace the proxy modules with the real ones
|
| 1637 |
+
# This can happen during HOO tracing
|
| 1638 |
+
proxy_module_names_to_be_replaced: List[Tuple[str, _AttrProxy]] = []
|
| 1639 |
+
for name, module in self.root.named_modules():
|
| 1640 |
+
if module in self.proxy_modules:
|
| 1641 |
+
proxy_module_names_to_be_replaced.append((name, module))
|
| 1642 |
+
|
| 1643 |
+
def _delete_proxy_attr(obj: Module, target: str) -> bool:
|
| 1644 |
+
# Copied from fx/graph_module.py
|
| 1645 |
+
# Customized it for proxy type
|
| 1646 |
+
atoms = target.split(".")
|
| 1647 |
+
path, target_submod = atoms[:-1], atoms[-1]
|
| 1648 |
+
assert isinstance(obj, Module)
|
| 1649 |
+
mod = obj
|
| 1650 |
+
|
| 1651 |
+
# Get the parent module
|
| 1652 |
+
for item in path:
|
| 1653 |
+
if not hasattr(mod, item):
|
| 1654 |
+
return False
|
| 1655 |
+
|
| 1656 |
+
mod = getattr(mod, item)
|
| 1657 |
+
|
| 1658 |
+
if not isinstance(mod, (_AttrProxy, Module)):
|
| 1659 |
+
return False
|
| 1660 |
+
|
| 1661 |
+
if not hasattr(mod, target_submod):
|
| 1662 |
+
return False
|
| 1663 |
+
|
| 1664 |
+
# At least the leaf module should be proxy type.
|
| 1665 |
+
if not isinstance(getattr(mod, target_submod), _AttrProxy):
|
| 1666 |
+
return False
|
| 1667 |
+
|
| 1668 |
+
delattr(mod, target_submod)
|
| 1669 |
+
return True
|
| 1670 |
+
|
| 1671 |
+
for proxy_module_name, proxy_module in proxy_module_names_to_be_replaced:
|
| 1672 |
+
_delete_proxy_attr(self.root, proxy_module_name)
|
| 1673 |
+
actual_module = self.proxy_modules[proxy_module]
|
| 1674 |
+
_assign_attr(actual_module, self.root, proxy_module_name)
|
| 1675 |
+
|
| 1676 |
+
return res
|
| 1677 |
+
|
| 1678 |
+
def call_module(
|
| 1679 |
+
self,
|
| 1680 |
+
m: Module,
|
| 1681 |
+
forward: Callable,
|
| 1682 |
+
args: Tuple[object, ...],
|
| 1683 |
+
kwargs: Dict[str, object],
|
| 1684 |
+
) -> None:
|
| 1685 |
+
"""PythonKeyTracer overrides call_module to avoid the scope handling,
|
| 1686 |
+
but we actually want it.
|
| 1687 |
+
"""
|
| 1688 |
+
from torch._dynamo import OptimizedModule
|
| 1689 |
+
|
| 1690 |
+
# FIXME (tmanlaibaatar)
|
| 1691 |
+
# When we call torch.compile inside HOO, we will end up
|
| 1692 |
+
# invoking a module that is not registered on the root. For
|
| 1693 |
+
# now, we just inline them. But once we start supporting
|
| 1694 |
+
# mark_strict in export, we do need to properly handle this.
|
| 1695 |
+
# Right now, it doesn't matter because current non-strict
|
| 1696 |
+
# use cases don't need to work with HOO.
|
| 1697 |
+
if isinstance(m, (OptimizedModule, GraphModule)):
|
| 1698 |
+
return forward(*args, **kwargs)
|
| 1699 |
+
|
| 1700 |
+
try:
|
| 1701 |
+
return Tracer.call_module(self, m, forward, args, kwargs)
|
| 1702 |
+
except _ModuleNotInstalledAsSubmoduleError as e:
|
| 1703 |
+
warnings.warn(
|
| 1704 |
+
f"Unable to find the path of the module {m}. "
|
| 1705 |
+
"This might be because the module was not properly registered "
|
| 1706 |
+
"as a submodule, which is not good practice. We will trace "
|
| 1707 |
+
"through the module without recording stack information."
|
| 1708 |
+
)
|
| 1709 |
+
return forward(*args, **kwargs)
|
| 1710 |
+
|
| 1711 |
+
def is_leaf_module(self, m: Module, module_qualified_name: str) -> bool:
|
| 1712 |
+
return False
|
| 1713 |
+
|
| 1714 |
+
def create_node(self, *args: object, **kwargs: object) -> fx.node.Node:
|
| 1715 |
+
"""
|
| 1716 |
+
Create node and add on metadata.
|
| 1717 |
+
Add nn_module_stack here instead of TracerBase,
|
| 1718 |
+
since calls to make_fx() might not want to record module stack metadata.
|
| 1719 |
+
Add torch_fn by looking at torch_fn_metadata and torch_fn_counts.
|
| 1720 |
+
Add stack_trace by filtering out forward() stack frames.
|
| 1721 |
+
"""
|
| 1722 |
+
node = super().create_node(*args, **kwargs) # type: ignore[arg-type]
|
| 1723 |
+
|
| 1724 |
+
# nn_module_stack
|
| 1725 |
+
if node.op not in ["placeholder", "output"]:
|
| 1726 |
+
if "nn_module_stack" not in node.meta:
|
| 1727 |
+
node.meta["nn_module_stack"] = self.module_stack
|
| 1728 |
+
# convert nn_module_stack from Dict[key, (FQN, class)] -> Dict[str, Tuple[str, str]]
|
| 1729 |
+
for key, (fqn, mod_cls) in node.meta["nn_module_stack"].items():
|
| 1730 |
+
if isinstance(mod_cls, type):
|
| 1731 |
+
node.meta["nn_module_stack"][key] = (
|
| 1732 |
+
fqn,
|
| 1733 |
+
mod_cls.__module__ + "." + mod_cls.__qualname__,
|
| 1734 |
+
)
|
| 1735 |
+
|
| 1736 |
+
# torch_fn
|
| 1737 |
+
if (
|
| 1738 |
+
node.op == "call_function"
|
| 1739 |
+
and self.torch_fn_metadata is not None
|
| 1740 |
+
and "torch_fn" not in node.meta
|
| 1741 |
+
):
|
| 1742 |
+
node.meta["torch_fn"] = (
|
| 1743 |
+
f"{self.torch_fn_metadata.__name__}_{self.torch_fn_counts[self.torch_fn_metadata]}",
|
| 1744 |
+
f"{self.torch_fn_metadata.__class__.__name__}.{self.torch_fn_metadata.__name__}",
|
| 1745 |
+
)
|
| 1746 |
+
|
| 1747 |
+
# stack_trace
|
| 1748 |
+
if "stack_trace" not in node.meta and node.op not in ["placeholder", "output"]:
|
| 1749 |
+
user_frame_summary = CapturedTraceback.extract().summary()
|
| 1750 |
+
if user_frame_summary:
|
| 1751 |
+
# we retain frames from forward() calls, or ops
|
| 1752 |
+
# located in torch/__init__.py (e.g. sym_int, sym_constrain_range, vmap)
|
| 1753 |
+
stack_trace = [
|
| 1754 |
+
frame
|
| 1755 |
+
for frame in user_frame_summary
|
| 1756 |
+
if (
|
| 1757 |
+
frame.name == "forward"
|
| 1758 |
+
or frame.filename.endswith("torch/__init__.py")
|
| 1759 |
+
)
|
| 1760 |
+
]
|
| 1761 |
+
# filter out forward() frames from fx/_symbolic_trace.py, export/_trace.py
|
| 1762 |
+
# this is hardcoded, but leads to a much cleaner stack trace
|
| 1763 |
+
stack_trace = [
|
| 1764 |
+
frame
|
| 1765 |
+
for frame in stack_trace
|
| 1766 |
+
if not (
|
| 1767 |
+
frame.filename.endswith("fx/_symbolic_trace.py")
|
| 1768 |
+
or frame.filename.endswith("export/_trace.py")
|
| 1769 |
+
)
|
| 1770 |
+
]
|
| 1771 |
+
if (
|
| 1772 |
+
stack_trace
|
| 1773 |
+
): # empty list for strict mode, dynamo should handle stack_trace
|
| 1774 |
+
stack_trace = traceback.StackSummary.from_list(stack_trace)
|
| 1775 |
+
node.meta["stack_trace"] = "".join(stack_trace.format()).strip()
|
| 1776 |
+
|
| 1777 |
+
return node
|
| 1778 |
+
|
| 1779 |
+
|
| 1780 |
+
class _MakefxTracer:
|
| 1781 |
+
def __init__(
|
| 1782 |
+
self,
|
| 1783 |
+
decomposition_table: Optional[Mapping[OpOverload, Callable]],
|
| 1784 |
+
tracing_mode: str,
|
| 1785 |
+
_allow_non_fake_inputs: bool,
|
| 1786 |
+
pre_dispatch: bool,
|
| 1787 |
+
record_module_stack: bool,
|
| 1788 |
+
_allow_fake_constant: bool,
|
| 1789 |
+
_error_on_data_dependent_ops: bool,
|
| 1790 |
+
) -> None:
|
| 1791 |
+
# Configurations that are used to initialize the context managers and their states.
|
| 1792 |
+
# Should not modify them during tracing.
|
| 1793 |
+
self.decomposition_table: Dict[OpOverload, Callable] = dict(
|
| 1794 |
+
decomposition_table or {}
|
| 1795 |
+
)
|
| 1796 |
+
self.decomposition_table.setdefault(
|
| 1797 |
+
torch.ops.aten.sym_numel.default, torch._decomp.decompositions.sym_numel
|
| 1798 |
+
)
|
| 1799 |
+
self.tracing_mode: str = tracing_mode
|
| 1800 |
+
self._allow_non_fake_inputs: bool = _allow_non_fake_inputs
|
| 1801 |
+
self.pre_dispatch: bool = pre_dispatch
|
| 1802 |
+
self.record_module_stack: bool = record_module_stack
|
| 1803 |
+
self._allow_fake_constant: bool = _allow_fake_constant
|
| 1804 |
+
self._error_on_data_dependent_ops: bool = _error_on_data_dependent_ops
|
| 1805 |
+
|
| 1806 |
+
# All context managers and their states should be initialized before tracing based on the inputs
|
| 1807 |
+
# and configurations. After tracing, their states should be cleaned except for shape_env.
|
| 1808 |
+
# Remember to specify how to intialize it from user inputs and from parent tracer whenever
|
| 1809 |
+
# adding new modes in _MakefxTracer.
|
| 1810 |
+
self.fake_tensor_mode: Optional[FakeTensorMode] = None
|
| 1811 |
+
self.proxy_mode: Union[nullcontext, ProxyTorchDispatchMode] = nullcontext()
|
| 1812 |
+
self.proxy_function_mode: Union[
|
| 1813 |
+
nullcontext, PreDispatchTorchFunctionMode
|
| 1814 |
+
] = nullcontext()
|
| 1815 |
+
self.fx_tracer: Optional[PythonKeyTracer] = None
|
| 1816 |
+
self.python_dispatcher_mode: Union[nullcontext, Any] = nullcontext()
|
| 1817 |
+
self.torch_fn_metadata_mode: Union[
|
| 1818 |
+
nullcontext, TorchFunctionMetadataMode
|
| 1819 |
+
] = nullcontext()
|
| 1820 |
+
|
| 1821 |
+
def _checkpoint_modes(self) -> List[Any]:
|
| 1822 |
+
return [
|
| 1823 |
+
self.fake_tensor_mode,
|
| 1824 |
+
self.proxy_mode,
|
| 1825 |
+
self.proxy_function_mode,
|
| 1826 |
+
self.fx_tracer,
|
| 1827 |
+
self.python_dispatcher_mode,
|
| 1828 |
+
self.torch_fn_metadata_mode,
|
| 1829 |
+
]
|
| 1830 |
+
|
| 1831 |
+
def _restore_modes(
|
| 1832 |
+
self,
|
| 1833 |
+
prev_fake_tensor_mode: Optional[FakeTensorMode],
|
| 1834 |
+
prev_proxy_mode: Union[nullcontext, ProxyTorchDispatchMode],
|
| 1835 |
+
prev_proxy_function_mode: Union[nullcontext, PreDispatchTorchFunctionMode],
|
| 1836 |
+
prev_fx_tracer: Optional[PythonKeyTracer],
|
| 1837 |
+
prev_python_dispatcher_mode: Union[nullcontext, Any],
|
| 1838 |
+
prev_torch_fn_metadata_mode: Union[nullcontext, TorchFunctionMetadataMode],
|
| 1839 |
+
) -> None:
|
| 1840 |
+
self.fake_tensor_mode = prev_fake_tensor_mode
|
| 1841 |
+
self.proxy_mode = prev_proxy_mode
|
| 1842 |
+
self.proxy_function_mode = prev_proxy_function_mode
|
| 1843 |
+
self.fx_tracer = prev_fx_tracer
|
| 1844 |
+
self.python_dispatcher_mode = prev_python_dispatcher_mode
|
| 1845 |
+
self.torch_fn_metadata_mode = prev_torch_fn_metadata_mode
|
| 1846 |
+
|
| 1847 |
+
@contextmanager
|
| 1848 |
+
def _init_modes_from_inputs(
|
| 1849 |
+
self, f: Callable, args: Tuple[object, ...]
|
| 1850 |
+
) -> Generator[None, None, None]:
|
| 1851 |
+
prev_modes = self._checkpoint_modes()
|
| 1852 |
+
try:
|
| 1853 |
+
# Avoid importing sympy at a module level
|
| 1854 |
+
from .symbolic_shapes import ShapeEnv
|
| 1855 |
+
|
| 1856 |
+
if hasattr(f, "_orig_mod") and self.record_module_stack:
|
| 1857 |
+
scope_root = f._orig_mod
|
| 1858 |
+
self.fx_tracer = _ModuleStackTracer(scope_root)
|
| 1859 |
+
else:
|
| 1860 |
+
self.fx_tracer = PythonKeyTracer()
|
| 1861 |
+
|
| 1862 |
+
if self.tracing_mode == "fake":
|
| 1863 |
+
import torch._dynamo
|
| 1864 |
+
|
| 1865 |
+
fake_tensor_mode = torch._dynamo.utils.detect_fake_mode(args)
|
| 1866 |
+
if fake_tensor_mode is None:
|
| 1867 |
+
import torch._functorch.config as _config
|
| 1868 |
+
|
| 1869 |
+
with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False):
|
| 1870 |
+
fake_tensor_mode = FakeTensorMode(
|
| 1871 |
+
allow_fallback_kernels=True,
|
| 1872 |
+
allow_non_fake_inputs=self._allow_non_fake_inputs,
|
| 1873 |
+
shape_env=ShapeEnv(),
|
| 1874 |
+
static_shapes=True,
|
| 1875 |
+
)
|
| 1876 |
+
self.fake_tensor_mode = fake_tensor_mode
|
| 1877 |
+
elif self.tracing_mode == "symbolic":
|
| 1878 |
+
import torch._dynamo
|
| 1879 |
+
|
| 1880 |
+
fake_tensor_mode = torch._dynamo.utils.detect_fake_mode(args)
|
| 1881 |
+
if fake_tensor_mode is None:
|
| 1882 |
+
shape_env = ShapeEnv()
|
| 1883 |
+
import torch._functorch.config as _config
|
| 1884 |
+
|
| 1885 |
+
with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False):
|
| 1886 |
+
fake_tensor_mode = FakeTensorMode(
|
| 1887 |
+
allow_fallback_kernels=False,
|
| 1888 |
+
allow_non_fake_inputs=self._allow_non_fake_inputs,
|
| 1889 |
+
shape_env=shape_env,
|
| 1890 |
+
)
|
| 1891 |
+
assert (
|
| 1892 |
+
fake_tensor_mode.shape_env is not None
|
| 1893 |
+
), "shape_env should be set if tracing with 'symbolic'"
|
| 1894 |
+
self.fake_tensor_mode = fake_tensor_mode
|
| 1895 |
+
else:
|
| 1896 |
+
if not self.tracing_mode == "real":
|
| 1897 |
+
raise AssertionError(
|
| 1898 |
+
f"Unexpected tracing type: {self.tracing_mode}"
|
| 1899 |
+
)
|
| 1900 |
+
|
| 1901 |
+
self._construct_modes_with_fx_tracer(self.fx_tracer)
|
| 1902 |
+
yield
|
| 1903 |
+
finally:
|
| 1904 |
+
self._restore_modes(*prev_modes)
|
| 1905 |
+
|
| 1906 |
+
def _construct_modes_with_fx_tracer(self, fx_tracer: _ProxyTracer) -> None:
|
| 1907 |
+
self.proxy_mode = ProxyTorchDispatchMode(
|
| 1908 |
+
fx_tracer,
|
| 1909 |
+
self.tracing_mode,
|
| 1910 |
+
pre_dispatch=self.pre_dispatch,
|
| 1911 |
+
_allow_fake_constant=self._allow_fake_constant,
|
| 1912 |
+
_error_on_data_dependent_ops=self._error_on_data_dependent_ops,
|
| 1913 |
+
)
|
| 1914 |
+
|
| 1915 |
+
if self.pre_dispatch:
|
| 1916 |
+
self.proxy_function_mode = PreDispatchTorchFunctionMode(fx_tracer)
|
| 1917 |
+
|
| 1918 |
+
# pre-autograd tracing uses per-dispatch-key modes,
|
| 1919 |
+
# which requires the python dispatcher
|
| 1920 |
+
if self.tracing_mode == "symbolic" or self.pre_dispatch:
|
| 1921 |
+
self.python_dispatcher_mode = enable_python_dispatcher()
|
| 1922 |
+
|
| 1923 |
+
self.torch_fn_metadata_mode = TorchFunctionMetadataMode(fx_tracer)
|
| 1924 |
+
|
| 1925 |
+
@contextmanager
|
| 1926 |
+
def _init_modes_from_parent(
|
| 1927 |
+
self, parent_tracer: _MakefxTracer
|
| 1928 |
+
) -> Generator[None, None, None]:
|
| 1929 |
+
# By default, subtracer creates new modes based on parent tracer's config.
|
| 1930 |
+
# However, there are cases where we want to share the same modes with parent tracer
|
| 1931 |
+
# For example, fake_tensor_mode, we want the example value's fake_mode of parent graph and subgraphs to be the same.
|
| 1932 |
+
prev_modes = self._checkpoint_modes()
|
| 1933 |
+
try:
|
| 1934 |
+
self.fake_tensor_mode = parent_tracer.fake_tensor_mode
|
| 1935 |
+
|
| 1936 |
+
def _create_sub_fx_tracer(parent_tracer: _ProxyTracer) -> PythonKeyTracer:
|
| 1937 |
+
if type(parent_tracer) == PythonKeyTracer:
|
| 1938 |
+
return PythonKeyTracer()
|
| 1939 |
+
elif type(parent_tracer) == _ModuleStackTracer:
|
| 1940 |
+
return _ModuleStackTracer(parent_tracer.scope_root)
|
| 1941 |
+
else:
|
| 1942 |
+
raise RuntimeError(
|
| 1943 |
+
f"Unexpected tracer type: {type(parent_tracer)}."
|
| 1944 |
+
)
|
| 1945 |
+
|
| 1946 |
+
assert parent_tracer.fx_tracer is not None
|
| 1947 |
+
self.fx_tracer = _create_sub_fx_tracer(parent_tracer.fx_tracer)
|
| 1948 |
+
self._construct_modes_with_fx_tracer(self.fx_tracer)
|
| 1949 |
+
yield
|
| 1950 |
+
finally:
|
| 1951 |
+
self._restore_modes(*prev_modes)
|
| 1952 |
+
|
| 1953 |
+
def _trace_inner(self, f: Callable, *args: object) -> GraphModule:
|
| 1954 |
+
phs = pytree.tree_map(lambda _: torch.fx._symbolic_trace.PH, args)
|
| 1955 |
+
|
| 1956 |
+
def _wrap_fake(args: T) -> T:
|
| 1957 |
+
arg_count = 0
|
| 1958 |
+
|
| 1959 |
+
def inner_wrap_fake(x: object) -> object:
|
| 1960 |
+
nonlocal arg_count
|
| 1961 |
+
# TODO: it would be nice to line these up with the names
|
| 1962 |
+
# FX will choose for the placeholders, but we don't
|
| 1963 |
+
# actually know what the names will be at this point yet
|
| 1964 |
+
# NB: the Source here is actually meaningless
|
| 1965 |
+
from torch._dynamo.source import ConstantSource
|
| 1966 |
+
|
| 1967 |
+
assert self.fake_tensor_mode is not None
|
| 1968 |
+
source = ConstantSource(f"input{arg_count}")
|
| 1969 |
+
if isinstance(x, Tensor):
|
| 1970 |
+
arg_count += 1
|
| 1971 |
+
return self.fake_tensor_mode.from_tensor(x, source=source)
|
| 1972 |
+
# NB: don't match on bools
|
| 1973 |
+
elif type(x) is int and self.tracing_mode == "symbolic":
|
| 1974 |
+
assert (
|
| 1975 |
+
self.fake_tensor_mode.shape_env is not None
|
| 1976 |
+
), "shape_env should be set if tracing with 'symbolic'"
|
| 1977 |
+
return self.fake_tensor_mode.shape_env.create_symintnode(
|
| 1978 |
+
self.fake_tensor_mode.shape_env.create_symbol(
|
| 1979 |
+
x, source, positive=None
|
| 1980 |
+
),
|
| 1981 |
+
hint=x,
|
| 1982 |
+
source=source,
|
| 1983 |
+
)
|
| 1984 |
+
elif isinstance(x, torch.ScriptObject):
|
| 1985 |
+
return torch._library.fake_class_registry.maybe_to_fake_obj(
|
| 1986 |
+
self.fake_tensor_mode, x
|
| 1987 |
+
)
|
| 1988 |
+
|
| 1989 |
+
assert not isinstance(
|
| 1990 |
+
x, FakeScriptObject
|
| 1991 |
+
), f"ScriptObject {x} has been fakified. Cannot wrap_fake it again."
|
| 1992 |
+
return x
|
| 1993 |
+
|
| 1994 |
+
wrap_fn_map = {
|
| 1995 |
+
"real": lambda x: x,
|
| 1996 |
+
"fake": inner_wrap_fake,
|
| 1997 |
+
"symbolic": inner_wrap_fake,
|
| 1998 |
+
}
|
| 1999 |
+
return pytree.tree_map(wrap_fn_map[self.tracing_mode], args)
|
| 2000 |
+
|
| 2001 |
+
def _wrap_func(f: Callable[_P, R], phs: Sequence[PHBase]) -> Callable[_P, R]:
|
| 2002 |
+
if (
|
| 2003 |
+
not hasattr(inspect.unwrap(f), "__code__")
|
| 2004 |
+
or inspect.unwrap(f).__code__.co_flags & inspect.CO_VARARGS
|
| 2005 |
+
):
|
| 2006 |
+
# FX doesn't support varargs, so we gotta fake up a wrapper
|
| 2007 |
+
# TODO: Would be nice to fix this at the source...
|
| 2008 |
+
return fake_signature(f, len(phs))
|
| 2009 |
+
return f
|
| 2010 |
+
|
| 2011 |
+
args = _wrap_fake(args)
|
| 2012 |
+
func = _wrap_func(f, phs)
|
| 2013 |
+
# We disable the autocast cache as the autocast cache causes type conversions on parameters to
|
| 2014 |
+
# check a cache, which introduces untracked tensors into the graph
|
| 2015 |
+
#
|
| 2016 |
+
# We also disable tracing by any other tensor proxy-based tracers except the current. The
|
| 2017 |
+
# purpose of `make_fx` is to produce graphmodules as a side effect; its internal execution is
|
| 2018 |
+
# thus irrelevant to any external functional trace.
|
| 2019 |
+
proxy_mode: ProxyTorchDispatchMode = typing.cast(
|
| 2020 |
+
ProxyTorchDispatchMode, self.proxy_mode
|
| 2021 |
+
)
|
| 2022 |
+
with ExitStack() as stack:
|
| 2023 |
+
stack.enter_context(decompose(self.decomposition_table))
|
| 2024 |
+
if self.fake_tensor_mode:
|
| 2025 |
+
stack.enter_context(self.fake_tensor_mode)
|
| 2026 |
+
stack.enter_context(self.python_dispatcher_mode)
|
| 2027 |
+
stack.enter_context(self.proxy_function_mode)
|
| 2028 |
+
stack.enter_context(self.torch_fn_metadata_mode)
|
| 2029 |
+
stack.enter_context(proxy_mode)
|
| 2030 |
+
stack.enter_context(disable_autocast_cache())
|
| 2031 |
+
stack.enter_context(_set_make_fx_tracer(self))
|
| 2032 |
+
|
| 2033 |
+
assert self.fx_tracer is not None
|
| 2034 |
+
t = dispatch_trace(
|
| 2035 |
+
wrap_key(func, args, self.fx_tracer, self.pre_dispatch),
|
| 2036 |
+
tracer=self.fx_tracer,
|
| 2037 |
+
concrete_args=tuple(phs),
|
| 2038 |
+
)
|
| 2039 |
+
|
| 2040 |
+
# TODO: kind of a bad way to do it, should maybe figure out a better way
|
| 2041 |
+
if self.tracing_mode == "symbolic":
|
| 2042 |
+
assert self.fake_tensor_mode is not None
|
| 2043 |
+
t.shape_env = self.fake_tensor_mode.shape_env
|
| 2044 |
+
return t
|
| 2045 |
+
|
| 2046 |
+
def trace(self, f: Callable, *args: object) -> fx.GraphModule:
|
| 2047 |
+
with self._init_modes_from_inputs(f, args):
|
| 2048 |
+
return self._trace_inner(f, *args)
|
| 2049 |
+
|
| 2050 |
+
def trace_subgraph(self, f: Callable, *args: object) -> GraphModule:
|
| 2051 |
+
# Create a new tracer based on parent's config
|
| 2052 |
+
sub_tracer = _MakefxTracer(
|
| 2053 |
+
self.decomposition_table,
|
| 2054 |
+
"real",
|
| 2055 |
+
self._allow_non_fake_inputs,
|
| 2056 |
+
self.pre_dispatch,
|
| 2057 |
+
self.record_module_stack,
|
| 2058 |
+
self._allow_fake_constant,
|
| 2059 |
+
self._error_on_data_dependent_ops,
|
| 2060 |
+
)
|
| 2061 |
+
with sub_tracer._init_modes_from_parent(self):
|
| 2062 |
+
return sub_tracer._trace_inner(f, *args)
|
| 2063 |
+
|
| 2064 |
+
|
| 2065 |
+
_CURRENT_MAKE_FX_TRACER: Optional[_MakefxTracer] = None
|
| 2066 |
+
|
| 2067 |
+
|
| 2068 |
+
@contextmanager
|
| 2069 |
+
def _set_make_fx_tracer(tracer: _MakefxTracer) -> Generator[None, None, None]:
|
| 2070 |
+
global _CURRENT_MAKE_FX_TRACER
|
| 2071 |
+
prev_tracer = _CURRENT_MAKE_FX_TRACER
|
| 2072 |
+
try:
|
| 2073 |
+
_CURRENT_MAKE_FX_TRACER = tracer
|
| 2074 |
+
yield
|
| 2075 |
+
finally:
|
| 2076 |
+
_CURRENT_MAKE_FX_TRACER = prev_tracer
|
| 2077 |
+
|
| 2078 |
+
|
| 2079 |
+
def make_fx(
|
| 2080 |
+
f: Callable,
|
| 2081 |
+
decomposition_table: Optional[Mapping[OpOverload, Callable]] = None,
|
| 2082 |
+
tracing_mode: str = "real",
|
| 2083 |
+
_allow_non_fake_inputs: bool = False,
|
| 2084 |
+
*,
|
| 2085 |
+
pre_dispatch: bool = False,
|
| 2086 |
+
record_module_stack: bool = False,
|
| 2087 |
+
_allow_fake_constant: bool = False,
|
| 2088 |
+
_error_on_data_dependent_ops: bool = True,
|
| 2089 |
+
) -> Callable[..., GraphModule]:
|
| 2090 |
+
"""
|
| 2091 |
+
Given a function f, return a new function which when executed with valid
|
| 2092 |
+
arguments to f, returns an FX GraphModule representing the set of operations that
|
| 2093 |
+
were executed during the course of execution.
|
| 2094 |
+
"""
|
| 2095 |
+
|
| 2096 |
+
assert tracing_mode in ["real", "fake", "symbolic"]
|
| 2097 |
+
|
| 2098 |
+
make_fx_tracer = _MakefxTracer(
|
| 2099 |
+
decomposition_table,
|
| 2100 |
+
tracing_mode,
|
| 2101 |
+
_allow_non_fake_inputs,
|
| 2102 |
+
pre_dispatch,
|
| 2103 |
+
record_module_stack,
|
| 2104 |
+
_allow_fake_constant,
|
| 2105 |
+
_error_on_data_dependent_ops,
|
| 2106 |
+
)
|
| 2107 |
+
|
| 2108 |
+
@functools.wraps(f)
|
| 2109 |
+
def wrapped(*args: object) -> GraphModule:
|
| 2110 |
+
return make_fx_tracer.trace(f, *args)
|
| 2111 |
+
|
| 2112 |
+
return wrapped
|
| 2113 |
+
|
| 2114 |
+
|
| 2115 |
+
def get_torch_dispatch_modes() -> List[TorchDispatchMode]:
|
| 2116 |
+
return torch.utils._python_dispatch._get_current_dispatch_mode_stack()
|
| 2117 |
+
|
| 2118 |
+
|
| 2119 |
+
# TODO: this is a legacy name, there is only ever one proxy mode as it's an
|
| 2120 |
+
# infra mode
|
| 2121 |
+
def get_innermost_proxy_mode() -> Optional[ProxyTorchDispatchMode]:
|
| 2122 |
+
return get_proxy_mode()
|
| 2123 |
+
|
| 2124 |
+
|
| 2125 |
+
def get_proxy_mode() -> Optional[ProxyTorchDispatchMode]:
|
| 2126 |
+
"""
|
| 2127 |
+
Current the currently active proxy tracing mode, or None if
|
| 2128 |
+
we are not currently tracing. This includes pre-dispatch proxy
|
| 2129 |
+
tracing.
|
| 2130 |
+
"""
|
| 2131 |
+
pre_dispatch_mode = torch._ops._get_dispatch_mode_pre_dispatch(
|
| 2132 |
+
torch._C._TorchDispatchModeKey.PROXY
|
| 2133 |
+
)
|
| 2134 |
+
mode = torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY)
|
| 2135 |
+
assert (
|
| 2136 |
+
pre_dispatch_mode is None or mode is None
|
| 2137 |
+
), f"pre_dispatch_mode={pre_dispatch_mode}, mode={mode}"
|
| 2138 |
+
return pre_dispatch_mode or mode
|
| 2139 |
+
|
| 2140 |
+
|
| 2141 |
+
def handle_sym_dispatch(func: Callable[_P, R], args: _P.args, kwargs: _P.kwargs) -> R:
|
| 2142 |
+
"""
|
| 2143 |
+
Call into the currently active proxy tracing mode to do a
|
| 2144 |
+
SymInt/SymFloat/SymBool dispatch trace on a function that operates on
|
| 2145 |
+
these arguments.
|
| 2146 |
+
"""
|
| 2147 |
+
mode = get_proxy_mode()
|
| 2148 |
+
assert mode
|
| 2149 |
+
# Have to do it manually, because we're not doing the normal torch
|
| 2150 |
+
# dispatch machinery which disables it for us
|
| 2151 |
+
with disable_proxy_modes_tracing():
|
| 2152 |
+
# TODO: properly compute types
|
| 2153 |
+
types: List[Type] = []
|
| 2154 |
+
return mode.__sym_dispatch__(func, types, args, kwargs) # type: ignore[arg-type, return-value]
|
| 2155 |
+
|
| 2156 |
+
|
| 2157 |
+
@contextmanager
|
| 2158 |
+
def disable_proxy_modes_tracing() -> Generator[ProxyTorchDispatchMode, None, None]:
|
| 2159 |
+
return _disable_infra_mode(torch._C._TorchDispatchModeKey.PROXY)
|
| 2160 |
+
|
| 2161 |
+
|
| 2162 |
+
def maybe_handle_decomp(
|
| 2163 |
+
proxy_mode: ProxyTorchDispatchMode,
|
| 2164 |
+
op: OpOverload,
|
| 2165 |
+
args: Tuple[object, ...],
|
| 2166 |
+
kwargs: Dict[str, object],
|
| 2167 |
+
) -> object:
|
| 2168 |
+
if op in CURRENT_DECOMPOSITION_TABLE:
|
| 2169 |
+
with proxy_mode:
|
| 2170 |
+
proxy_mode.decomp_layers += 1
|
| 2171 |
+
out = CURRENT_DECOMPOSITION_TABLE[op](*args, **kwargs)
|
| 2172 |
+
proxy_mode.decomp_layers -= 1
|
| 2173 |
+
return out
|
| 2174 |
+
|
| 2175 |
+
return NotImplemented
|
| 2176 |
+
|
| 2177 |
+
|
| 2178 |
+
def get_isolated_graphmodule(
|
| 2179 |
+
func: Callable,
|
| 2180 |
+
args: Tuple[object, ...],
|
| 2181 |
+
kwargs: Dict[str, object],
|
| 2182 |
+
tracing_mode: str = "real",
|
| 2183 |
+
decomposition_table: Optional[Mapping[OpOverload, Callable]] = None,
|
| 2184 |
+
) -> GraphModule:
|
| 2185 |
+
"""A helper function used to get the GraphModule for the given func.
|
| 2186 |
+
|
| 2187 |
+
It's expected to be used in the ProxyTensor tracing context.
|
| 2188 |
+
It detaches the args and kwargs from the current tracer so that the trace of
|
| 2189 |
+
the current graph module can be created without any side-effects.
|
| 2190 |
+
"""
|
| 2191 |
+
wrapped, all_args = wrapper_and_args_for_make_fx(func, args, kwargs)
|
| 2192 |
+
|
| 2193 |
+
with disable_proxy_modes_tracing():
|
| 2194 |
+
gm = make_fx(
|
| 2195 |
+
wrapped, decomposition_table=decomposition_table, tracing_mode=tracing_mode
|
| 2196 |
+
)(all_args)
|
| 2197 |
+
return gm
|
| 2198 |
+
|
| 2199 |
+
|
| 2200 |
+
def _set_unbacked_bindings(out: object, out_proxy: _NestedProxys) -> None:
|
| 2201 |
+
"""A helper function for setting up unbacked_bindings on the destination FX graph."""
|
| 2202 |
+
from .symbolic_shapes import compute_unbacked_bindings
|
| 2203 |
+
|
| 2204 |
+
# Can't use detect_fake_mode here,
|
| 2205 |
+
#
|
| 2206 |
+
# python test/distributed/_tensor/test_dtensor_compile.py -k
|
| 2207 |
+
# test_tp_compile_fullgraph_is_seq_parallel_False
|
| 2208 |
+
#
|
| 2209 |
+
# will fail. Very strange, it probably isn't right for them to be using
|
| 2210 |
+
# two fake modes there...
|
| 2211 |
+
fake_mode = torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.FAKE)
|
| 2212 |
+
if fake_mode and fake_mode.shape_env:
|
| 2213 |
+
if symbol_to_path := compute_unbacked_bindings(fake_mode.shape_env, out):
|
| 2214 |
+
assert isinstance(out_proxy, Proxy), out_proxy
|
| 2215 |
+
out_proxy.node.meta["unbacked_bindings"] = symbol_to_path
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/recording.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import logging
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.utils._pytree as pytree
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger(__name__)
|
| 14 |
+
trace_shape_events_log = torch._logging.getArtifactLogger(
|
| 15 |
+
__name__, "trace_shape_events"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"ShapeEnvEvent",
|
| 21 |
+
"record_shapeenv_event",
|
| 22 |
+
"replay_shape_env_events",
|
| 23 |
+
"FakeTensorMeta",
|
| 24 |
+
"shape_env_check_state_equal",
|
| 25 |
+
"NotEqualError",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
# [Note: Recording ShapeEnv Events]
|
| 29 |
+
# =================================
|
| 30 |
+
#
|
| 31 |
+
# What is a ShapeEnv event?
|
| 32 |
+
# -------------------------
|
| 33 |
+
# We consider a ShapeEnv event every function call (ShapeEnv method or
|
| 34 |
+
# independent function) that modifies the state of the ShapeEnv instance.
|
| 35 |
+
# Such calls are recorded alongside their positional and keyword arguments,
|
| 36 |
+
# so that it may be replayed over a different ShapeEnv instance.
|
| 37 |
+
#
|
| 38 |
+
# See [Note: ShapeEnv State Equality] for what is considered the state
|
| 39 |
+
# of a ShapeEnv instance.
|
| 40 |
+
#
|
| 41 |
+
# What is it for?
|
| 42 |
+
# ---------------
|
| 43 |
+
# ShapeEnv events recording is used for reconstructing the ShapeEnv in an
|
| 44 |
+
# arbitrary state in time.
|
| 45 |
+
#
|
| 46 |
+
# Being able to arbitrarily replay events like so is useful, mainly for
|
| 47 |
+
# translation validation bisection. i.e. if a ValidationException has been
|
| 48 |
+
# raised, find the earliest point in time where the translation validation
|
| 49 |
+
# fails.
|
| 50 |
+
#
|
| 51 |
+
# Besides that, it also allows us to inspect the given instance and,
|
| 52 |
+
# for example, check the guards that would actually be issued at that point.
|
| 53 |
+
#
|
| 54 |
+
# What kind of arguments can be stored in an event?
|
| 55 |
+
# -------------------------------------------------
|
| 56 |
+
# There's no specific rule for what cannot be used as an argument.
|
| 57 |
+
# That said, pay special attention to the following cases:
|
| 58 |
+
#
|
| 59 |
+
# 1. Tensor inputs: there are some tests that check whether the inputs
|
| 60 |
+
# were garbage collected after execution. These will fail if there's
|
| 61 |
+
# an event that is holding a reference to those inputs.
|
| 62 |
+
#
|
| 63 |
+
# 2. ShapeEnv arguments: if there is an argument of ShapeEnv type, that
|
| 64 |
+
# will be automatically replaced by the new given ShapeEnv instance.
|
| 65 |
+
#
|
| 66 |
+
# 3. SymTypes arguments: they also hold references to ShapeEnv. So,
|
| 67 |
+
# whenever we see them, we create a new instance, replacing the
|
| 68 |
+
# ShapeEnv reference.
|
| 69 |
+
#
|
| 70 |
+
# 4. FX nodes: specifically, FX nodes from the FX graph for symbolic
|
| 71 |
+
# shapes. That argument must be replaced when replaying the event at
|
| 72 |
+
# ShapeEnvEvent.run, since it has to reference a node from the given
|
| 73 |
+
# instance, and not from the recorded instance.
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Event class for reconstructing ShapeEnv at arbitrary time.
|
| 77 |
+
#
|
| 78 |
+
# Represents a method call that mutates ShapeEnv in a way that affects the
|
| 79 |
+
# issued guards, when ShapeEnv.produce_guards is called.
|
| 80 |
+
@dataclass
|
| 81 |
+
class ShapeEnvEvent:
|
| 82 |
+
# ShapeEnv method.
|
| 83 |
+
f: Callable
|
| 84 |
+
|
| 85 |
+
# Arguments and keyword arguments called with.
|
| 86 |
+
args: Optional[List[Any]] = None
|
| 87 |
+
kwargs: Optional[Dict[str, Any]] = None
|
| 88 |
+
|
| 89 |
+
# List of tracked_fakes at the time the method was called.
|
| 90 |
+
tracked_fakes: Optional[List[Any]] = None
|
| 91 |
+
|
| 92 |
+
# Name of the captured event.
|
| 93 |
+
# Used for special handling of particular methods.
|
| 94 |
+
name: Optional[str] = None
|
| 95 |
+
|
| 96 |
+
# Replay itself, but using shape_env as self.
|
| 97 |
+
def run(self, shape_env=None) -> Any:
|
| 98 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 99 |
+
is_symbolic,
|
| 100 |
+
ShapeEnv,
|
| 101 |
+
SymTypes,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Special handling for the constructor event.
|
| 105 |
+
if self.f is ShapeEnv:
|
| 106 |
+
assert shape_env is None and self.args is None and self.kwargs is not None
|
| 107 |
+
return ShapeEnv(**self.kwargs)
|
| 108 |
+
|
| 109 |
+
assert shape_env is not None
|
| 110 |
+
args = list(self.args or [])
|
| 111 |
+
kwargs = dict(self.kwargs or {})
|
| 112 |
+
|
| 113 |
+
# Replace any argument of type ShapeEnv by the given one.
|
| 114 |
+
args, kwargs = pytree.tree_map_only(
|
| 115 |
+
ShapeEnv, lambda _: shape_env, (args, kwargs)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Replace any argument of type SymTypes by a new instance,
|
| 119 |
+
# replacing its ShapeEnv reference.
|
| 120 |
+
args, kwargs = pytree.tree_map_only(
|
| 121 |
+
lambda x: isinstance(x, SymTypes) and is_symbolic(x),
|
| 122 |
+
lambda a: type(a)(a.node.with_shape_env(shape_env)),
|
| 123 |
+
(args, kwargs),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Converts FX nodes using the mapping argument.
|
| 127 |
+
def maybe_convert_node(x: Any) -> Any:
|
| 128 |
+
if not isinstance(x, torch.fx.Node):
|
| 129 |
+
# Don't do anything to x if it's not an FX node.
|
| 130 |
+
return x
|
| 131 |
+
|
| 132 |
+
# If, at some point, we created an FX node, it means that translation validation is on.
|
| 133 |
+
# It also means we are building an FX graph for symbolic shapes at shape_env.graph, and
|
| 134 |
+
# we are tracking node names at shape_env.name_to_node.
|
| 135 |
+
assert hasattr(shape_env, "name_to_node")
|
| 136 |
+
name_to_node = shape_env.name_to_node # type: ignore[attr-defined]
|
| 137 |
+
assert x.name in name_to_node
|
| 138 |
+
return name_to_node[x.name]
|
| 139 |
+
|
| 140 |
+
# Replaces the value of an specific argument by the result of fn.
|
| 141 |
+
def replacearg(index: int, key: str, fn: Callable):
|
| 142 |
+
if index < len(args):
|
| 143 |
+
args[index] = fn(args[index])
|
| 144 |
+
if key in kwargs:
|
| 145 |
+
kwargs[key] = fn(kwargs[key])
|
| 146 |
+
|
| 147 |
+
if self.is_create_fx_call_function():
|
| 148 |
+
# ShapeEnv.create_fx_call_function:
|
| 149 |
+
# "args" parameter is a tuple of FX nodes from the FX graph of the old ShapeEnv.
|
| 150 |
+
# They must be replaced, since a "call_function" FX node with this tuple as argument
|
| 151 |
+
# will be added to the FX graph of the new shape_env.
|
| 152 |
+
replacearg(
|
| 153 |
+
index=2,
|
| 154 |
+
key="args",
|
| 155 |
+
fn=lambda args: tuple(maybe_convert_node(a) for a in args),
|
| 156 |
+
)
|
| 157 |
+
if self.is_evaluate_expr() or self.is_defer_runtime_assert():
|
| 158 |
+
# ShapeEnv.evaluate_expr and ShapeEnv.defer_runtime_assert:
|
| 159 |
+
# "fx_node" parameter is an (optional) FX node that represents the evaluate expression.
|
| 160 |
+
# They must be replaced, since it will be part of a "call_function" FX node for
|
| 161 |
+
# torch._assert, which will be added to the FX graph of the new shape_env.
|
| 162 |
+
replacearg(index=3, key="fx_node", fn=maybe_convert_node)
|
| 163 |
+
|
| 164 |
+
# Actually call the method with the converted arguments.
|
| 165 |
+
return self.f(*args, **kwargs)
|
| 166 |
+
|
| 167 |
+
def __str__(self) -> str:
|
| 168 |
+
name = self.name if self.name is not None else self.f.__name__
|
| 169 |
+
return f"event: {name} ({self.args}, {self.kwargs})"
|
| 170 |
+
|
| 171 |
+
def is_create_fx_call_function(self) -> bool:
|
| 172 |
+
return self.name == "_create_fx_call_function"
|
| 173 |
+
|
| 174 |
+
def is_evaluate_expr(self) -> bool:
|
| 175 |
+
return self.name == "evaluate_expr"
|
| 176 |
+
|
| 177 |
+
def is_defer_runtime_assert(self) -> bool:
|
| 178 |
+
return self.name == "defer_runtime_assert"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
NEST = 0
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Extracts a ShapeEnv instance inside args and kwargs.
|
| 185 |
+
# Specifically, it looks for:
|
| 186 |
+
# 1. ShapeEnv arguments
|
| 187 |
+
# 2. SymInt, SymFloat, or SymBool arguments
|
| 188 |
+
# If we find more than one object of any of the above types, we
|
| 189 |
+
# also check that the ShapeEnv instance is the same for all of them.
|
| 190 |
+
def _extract_shape_env_and_assert_equal(args, kwargs):
|
| 191 |
+
from torch.fx.experimental.symbolic_shapes import is_symbolic, ShapeEnv, SymTypes
|
| 192 |
+
|
| 193 |
+
def assert_equal(old: Optional[ShapeEnv], new: ShapeEnv) -> ShapeEnv:
|
| 194 |
+
if old is not None:
|
| 195 |
+
assert old is new, "call with different ShapeEnv"
|
| 196 |
+
return new
|
| 197 |
+
|
| 198 |
+
shape_env = None
|
| 199 |
+
for val in itertools.chain(args, kwargs.values()):
|
| 200 |
+
if isinstance(val, ShapeEnv):
|
| 201 |
+
shape_env = assert_equal(shape_env, val)
|
| 202 |
+
if isinstance(val, SymTypes) and is_symbolic(val):
|
| 203 |
+
shape_env = assert_equal(shape_env, val.node.shape_env)
|
| 204 |
+
|
| 205 |
+
return shape_env
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# Decorator for recording the given function as a replayable event.
|
| 209 |
+
#
|
| 210 |
+
# This decorator should be used at every function that mutates the state of
|
| 211 |
+
# ShapeEnv in some way that affects the resulting issued guards (i.e. when
|
| 212 |
+
# ShapeEnv.produce_guards is called).
|
| 213 |
+
#
|
| 214 |
+
# save_tracked_fakes: saves a snapshot of the TrackedFake list.
|
| 215 |
+
# This is used when calling ShapeEnv.produce_guards at arbitrary points in time.
|
| 216 |
+
#
|
| 217 |
+
# When to save the list of TrackedFake?
|
| 218 |
+
# =====================================
|
| 219 |
+
# We should save the list of TrackedFake whenever the translation validation
|
| 220 |
+
# bisection may actually stop and call the produce_guards method at the moment
|
| 221 |
+
# right after the recorded function was played. In other words, since the
|
| 222 |
+
# bisection bisects through torch._assert calls, we should save in all methods
|
| 223 |
+
# that adds a torch._assert call to the symbolic shapes FX graph.
|
| 224 |
+
#
|
| 225 |
+
# At the moment, there are 2 methods that save the list:
|
| 226 |
+
# - ShapeEnv.evaluate_expr
|
| 227 |
+
# - ShapeEnv.defer_runtime_assert
|
| 228 |
+
def record_shapeenv_event(*, save_tracked_fakes: bool = False) -> Callable:
|
| 229 |
+
def decorator(fn: Callable) -> Callable:
|
| 230 |
+
assert callable(fn)
|
| 231 |
+
args = inspect.getfullargspec(fn).args
|
| 232 |
+
assert args and args[0] == "self", (
|
| 233 |
+
"record_shapeenv_event should only wrap methods on ShapeEnv; refactor your "
|
| 234 |
+
"code so that it calls into a method on ShapeEnv"
|
| 235 |
+
)
|
| 236 |
+
name = fn.__name__
|
| 237 |
+
|
| 238 |
+
@functools.wraps(fn)
|
| 239 |
+
def wrapper(*args, **kwargs):
|
| 240 |
+
from torch.fx.experimental.symbolic_shapes import ShapeEnv
|
| 241 |
+
|
| 242 |
+
assert isinstance(args[0], ShapeEnv)
|
| 243 |
+
|
| 244 |
+
global NEST
|
| 245 |
+
|
| 246 |
+
trace_shape_events_log.debug(
|
| 247 |
+
"%scall %s(*%r, **%r)", " " * NEST, name, args[1:], kwargs
|
| 248 |
+
)
|
| 249 |
+
NEST += 1
|
| 250 |
+
|
| 251 |
+
def retlog(r):
|
| 252 |
+
trace_shape_events_log.debug("%s-> %s", " " * (NEST - 1), r)
|
| 253 |
+
return r
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
if args[0].is_recording: # type: ignore[has-type]
|
| 257 |
+
# If ShapeEnv is already recording an event, call the wrapped
|
| 258 |
+
# function directly.
|
| 259 |
+
#
|
| 260 |
+
# NB: here, we skip the check of whether all ShapeEnv instances
|
| 261 |
+
# are equal, in favor of a faster dispatch.
|
| 262 |
+
return retlog(fn(*args, **kwargs))
|
| 263 |
+
|
| 264 |
+
# Retrieve an instance of ShapeEnv.
|
| 265 |
+
# Assumption: the collection of args and kwargs may not reference
|
| 266 |
+
# different ShapeEnv instances.
|
| 267 |
+
self = _extract_shape_env_and_assert_equal(args, kwargs)
|
| 268 |
+
|
| 269 |
+
# If we are calling this function without any ShapeEnv instance
|
| 270 |
+
# alive in its arguments, we don't record and call the original.
|
| 271 |
+
if self is None:
|
| 272 |
+
return retlog(fn(*args, **kwargs))
|
| 273 |
+
|
| 274 |
+
# Otherwise, start recording and call the function.
|
| 275 |
+
with self._recording():
|
| 276 |
+
# Take a snapshot of the current tracked_fakes.
|
| 277 |
+
tracked_fakes = (
|
| 278 |
+
self._snapshot_tracked_fakes() if save_tracked_fakes else None
|
| 279 |
+
)
|
| 280 |
+
# Record the event for 'fn'.
|
| 281 |
+
event = ShapeEnvEvent(
|
| 282 |
+
fn, list(args), kwargs, tracked_fakes, name=fn.__name__
|
| 283 |
+
)
|
| 284 |
+
# Play the event on this ShapeEnv.
|
| 285 |
+
# NB: It's important to put the event first, because running
|
| 286 |
+
# the event can trigger internal events that must be ordered
|
| 287 |
+
# after this event. However, if an exception happens, we do
|
| 288 |
+
# NOT want to have the event in the list, so pop it off from
|
| 289 |
+
# the record if an error happened
|
| 290 |
+
self.events.append(event)
|
| 291 |
+
try:
|
| 292 |
+
return retlog(event.run(self))
|
| 293 |
+
except Exception:
|
| 294 |
+
self.events.pop()
|
| 295 |
+
raise
|
| 296 |
+
|
| 297 |
+
except Exception:
|
| 298 |
+
log.error( # noqa: G201
|
| 299 |
+
"failed while running %s(*%s, **%s)",
|
| 300 |
+
name,
|
| 301 |
+
args[1:],
|
| 302 |
+
kwargs,
|
| 303 |
+
exc_info=log.isEnabledFor(logging.INFO),
|
| 304 |
+
)
|
| 305 |
+
raise
|
| 306 |
+
|
| 307 |
+
finally:
|
| 308 |
+
NEST -= 1
|
| 309 |
+
|
| 310 |
+
return wrapper
|
| 311 |
+
|
| 312 |
+
return decorator
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# Replays the ShapeEnvEvents list.
|
| 316 |
+
# It assumes the first event is the constructor call.
|
| 317 |
+
#
|
| 318 |
+
# fn: transforms an old FX node into one corresponding to the newly created ShapeEnv.
|
| 319 |
+
def replay_shape_env_events(events):
|
| 320 |
+
from torch.fx.experimental.symbolic_shapes import ShapeEnv
|
| 321 |
+
|
| 322 |
+
constructor_event = events[0]
|
| 323 |
+
assert constructor_event.f == ShapeEnv
|
| 324 |
+
|
| 325 |
+
# Constructs the new ShapeEnv.
|
| 326 |
+
shape_env = constructor_event.run()
|
| 327 |
+
|
| 328 |
+
for event in events[1:]:
|
| 329 |
+
try:
|
| 330 |
+
# Actually replays each event.
|
| 331 |
+
# We need to call create_mapping_fn every time, since the node list might
|
| 332 |
+
# change after each event is replayed.
|
| 333 |
+
event.run(shape_env)
|
| 334 |
+
except Exception as e:
|
| 335 |
+
log.error("failed when running event: %s", event)
|
| 336 |
+
raise
|
| 337 |
+
|
| 338 |
+
return shape_env
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# FakeTensor metadata.
|
| 342 |
+
# This is to be used in place of FakeTensor placeholders when calling
|
| 343 |
+
# ShapeEnv.produce_guards.
|
| 344 |
+
@dataclass
|
| 345 |
+
class FakeTensorMeta:
|
| 346 |
+
tensor_size: Tuple[Union[int, torch.SymInt], ...]
|
| 347 |
+
tensor_stride: Tuple[Union[int, torch.SymInt], ...]
|
| 348 |
+
tensor_storage_offset: Union[int, torch.SymInt]
|
| 349 |
+
is_nested: bool
|
| 350 |
+
|
| 351 |
+
def size(self) -> Tuple[Union[int, torch.SymInt], ...]:
|
| 352 |
+
return self.tensor_size
|
| 353 |
+
|
| 354 |
+
def stride(self) -> Tuple[Union[int, torch.SymInt], ...]:
|
| 355 |
+
return self.tensor_stride
|
| 356 |
+
|
| 357 |
+
def storage_offset(self) -> Union[int, torch.SymInt]:
|
| 358 |
+
return self.tensor_storage_offset
|
| 359 |
+
|
| 360 |
+
def dim(self) -> int:
|
| 361 |
+
return len(self.tensor_size)
|
| 362 |
+
|
| 363 |
+
@staticmethod
|
| 364 |
+
def from_fake(fake) -> "FakeTensorMeta":
|
| 365 |
+
return FakeTensorMeta(
|
| 366 |
+
fake.size(), fake.stride(), fake.storage_offset(), fake.is_nested
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
# [Note: ShapeEnv State Equality]
|
| 371 |
+
# ===============================
|
| 372 |
+
#
|
| 373 |
+
# What is considered ShapeEnv state?
|
| 374 |
+
# ----------------------------------
|
| 375 |
+
# We consider to be the state of a ShapeEnv instance everything that
|
| 376 |
+
# is not in the inline tuple inside remove_nonstate_variables function.
|
| 377 |
+
# That is: the fields within ShapeEnv that modify the flow of execution
|
| 378 |
+
# of the program.
|
| 379 |
+
#
|
| 380 |
+
# So, for example: the replacements field might influence on how an
|
| 381 |
+
# expression is simplified. That, in turn, may result in a guard being
|
| 382 |
+
# statically known (i.e. not added).
|
| 383 |
+
#
|
| 384 |
+
# On the other hand, var_to_stack serves only changes what is printed
|
| 385 |
+
# in the screen, i.e. used only for debugging purposes. Therefore, we
|
| 386 |
+
# should not consider it when comparing states.
|
| 387 |
+
#
|
| 388 |
+
# What to do on NotEqualError?
|
| 389 |
+
# ----------------------------
|
| 390 |
+
# Here are a few possible causes for getting a NotEqualError raised:
|
| 391 |
+
#
|
| 392 |
+
# 1. New field that does not belong in the ShapeEnv state.
|
| 393 |
+
# For example: log field of type ShapeEnvLoggerAdapter. Different
|
| 394 |
+
# ShapeEnv instances will always have different ShapeEnvLoggerAdapter
|
| 395 |
+
# instances, i.e. equality comparison would fail.
|
| 396 |
+
# Solution: add it to the inlined tuple inside remove_nonstate_variables
|
| 397 |
+
# function inside check_equal method.
|
| 398 |
+
#
|
| 399 |
+
# 2. New field that is not directly comparable across instances.
|
| 400 |
+
# For example: guards field of type List[ShapeGuard]. More specifically,
|
| 401 |
+
# the ShapeGuard type holds an expression and a stack information
|
| 402 |
+
# for debugging purposes. When replaying the even on a new ShapeEnv
|
| 403 |
+
# instance, the stack would be different, which would trigger this error.
|
| 404 |
+
# Solution: add a special case to the map_value function inside
|
| 405 |
+
# check_equal function.
|
| 406 |
+
#
|
| 407 |
+
# 3. Mutation of ShapeEnv on some not recorded function.
|
| 408 |
+
# If a mutation of the state of ShapeEnv happens inside a function
|
| 409 |
+
# that is not recorded (or that no caller in the stack is recorded),
|
| 410 |
+
# then, the replayed ShapeEnv won't catch that.
|
| 411 |
+
# Solution: decorate the function with record_shape_env_event.
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
# Checks whether the state of two ShapeEnv are equal w.r.t. the guards
|
| 415 |
+
# returned by ShapeEnv.produce_guards.
|
| 416 |
+
def shape_env_check_state_equal(env1, env2, non_state_variable_names, map_value):
|
| 417 |
+
# Collect and remove variables that don't necessarily represent the state
|
| 418 |
+
# of a ShapeEnv. Note: we copy the dictionary so that we don't modify the
|
| 419 |
+
# instance itself.
|
| 420 |
+
env1_vars = vars(env1).copy()
|
| 421 |
+
env2_vars = vars(env2).copy()
|
| 422 |
+
|
| 423 |
+
for v in non_state_variable_names:
|
| 424 |
+
if v in env1_vars:
|
| 425 |
+
env1_vars.pop(v)
|
| 426 |
+
if v in env2_vars:
|
| 427 |
+
env2_vars.pop(v)
|
| 428 |
+
|
| 429 |
+
# Function for transforming the mismatched values into string.
|
| 430 |
+
# Needed, since dict and set entries order might not be the same every time.
|
| 431 |
+
def value_to_str(value: Any) -> str:
|
| 432 |
+
if isinstance(value, dict):
|
| 433 |
+
return (
|
| 434 |
+
"{"
|
| 435 |
+
+ ", ".join(f"{k}: {value[k]}" for k in sorted(value.keys(), key=str))
|
| 436 |
+
+ "}"
|
| 437 |
+
)
|
| 438 |
+
if isinstance(value, set):
|
| 439 |
+
return "{" + ", ".join(f"{v}" for v in sorted(value)) + "}"
|
| 440 |
+
return str(value)
|
| 441 |
+
|
| 442 |
+
# Compares env1_vars with env2_vars.
|
| 443 |
+
# Here, we allow the value of each field to be mapped, so that we appropriately
|
| 444 |
+
# compare the two values.
|
| 445 |
+
def compare_vars(
|
| 446 |
+
map_value: Callable[[str, Any], Any]
|
| 447 |
+
) -> List[Tuple[str, str, str]]:
|
| 448 |
+
env1_set, env2_set = set(env1_vars), set(env2_vars)
|
| 449 |
+
|
| 450 |
+
# First, compare the set of keys in each vars dictionary.
|
| 451 |
+
if env1_set != env2_set:
|
| 452 |
+
raise NotEqualError(
|
| 453 |
+
"field set mismatch:",
|
| 454 |
+
[
|
| 455 |
+
(
|
| 456 |
+
"found unique fields:",
|
| 457 |
+
str(sorted(env1_set - env2_set)),
|
| 458 |
+
str(sorted(env2_set - env1_set)),
|
| 459 |
+
),
|
| 460 |
+
],
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
# Then, sort the keys, and compare the mapped values of each key.
|
| 464 |
+
sorted_keys = list(env1_set)
|
| 465 |
+
sorted_keys.sort()
|
| 466 |
+
|
| 467 |
+
mapped_dict = [
|
| 468 |
+
(k, map_value(k, env1_vars[k]), map_value(k, env2_vars[k]))
|
| 469 |
+
for k in sorted_keys
|
| 470 |
+
]
|
| 471 |
+
|
| 472 |
+
# Return a list of tuples representing the fields that did not match
|
| 473 |
+
# alongside their respective mapped values.
|
| 474 |
+
return [
|
| 475 |
+
(f"{k}: values don't match.", value_to_str(val1), value_to_str(val2))
|
| 476 |
+
for k, val1, val2 in mapped_dict
|
| 477 |
+
if val1 != val2
|
| 478 |
+
]
|
| 479 |
+
|
| 480 |
+
# Accumulate the mismatching fields.
|
| 481 |
+
errors = compare_vars(map_value)
|
| 482 |
+
|
| 483 |
+
if len(errors) > 0:
|
| 484 |
+
raise NotEqualError("field values don't match:", errors)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class NotEqualError(Exception):
|
| 488 |
+
def __init__(
|
| 489 |
+
self,
|
| 490 |
+
msg: str,
|
| 491 |
+
mismatched: List[Tuple[str, str, str]],
|
| 492 |
+
) -> None:
|
| 493 |
+
details = "\n".join(
|
| 494 |
+
[
|
| 495 |
+
"\n".join(
|
| 496 |
+
[
|
| 497 |
+
f"==> {inner_msg}",
|
| 498 |
+
f" > Left: {str1}",
|
| 499 |
+
f" > Right: {str2}",
|
| 500 |
+
]
|
| 501 |
+
)
|
| 502 |
+
for inner_msg, str1, str2 in mismatched
|
| 503 |
+
]
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
super().__init__(
|
| 507 |
+
f"""\
|
| 508 |
+
ShapeEnv not equal: {msg}
|
| 509 |
+
|
| 510 |
+
{details}
|
| 511 |
+
"""
|
| 512 |
+
)
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/refinement_types.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
class Equality:
|
| 3 |
+
def __init__(self, lhs, rhs):
|
| 4 |
+
self.lhs = lhs
|
| 5 |
+
self.rhs = rhs
|
| 6 |
+
|
| 7 |
+
def __str__(self):
|
| 8 |
+
return f'{self.lhs} = {self.rhs}'
|
| 9 |
+
|
| 10 |
+
def __repr__(self):
|
| 11 |
+
return f'{self.lhs} = {self.rhs}'
|
| 12 |
+
|
| 13 |
+
def __eq__(self, other):
|
| 14 |
+
if isinstance(other, Equality):
|
| 15 |
+
return self.lhs == other.lhs and self.rhs == other.rhs
|
| 16 |
+
else:
|
| 17 |
+
return False
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/rewriter.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import ast
|
| 4 |
+
import inspect
|
| 5 |
+
import textwrap
|
| 6 |
+
import copy
|
| 7 |
+
import functools
|
| 8 |
+
from types import FunctionType
|
| 9 |
+
from typing import cast, Union, Callable, Dict, Optional, Any
|
| 10 |
+
from torch.fx._symbolic_trace import Tracer
|
| 11 |
+
from torch.fx.graph import Graph
|
| 12 |
+
from torch._sources import normalize_source_lines
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
class AST_Rewriter(ast.NodeTransformer):
|
| 16 |
+
"""
|
| 17 |
+
Take a FunctionType object representing a `forward` method, then
|
| 18 |
+
perform an AST rewrite to swap out nodes that are not symbolically
|
| 19 |
+
traceable with a callsite to the FX alternative.
|
| 20 |
+
|
| 21 |
+
To support swapping out an AST node, define a new `visit` method on
|
| 22 |
+
that node. For more details, see:
|
| 23 |
+
https://docs.python.org/3/library/ast.html#ast.NodeTransformer
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
# This function checks for new keys added in the globals dict. TorchDynamo
|
| 27 |
+
# can insert new keys in the global dict and upset the check. Therefore, put
|
| 28 |
+
# a disable here. This function is an optimization pass and not really
|
| 29 |
+
# suitable for dynamo tracing anyways.
|
| 30 |
+
@torch._dynamo.disable
|
| 31 |
+
def rewrite(self, fn: FunctionType):
|
| 32 |
+
|
| 33 |
+
# Normalize the source lines
|
| 34 |
+
sourcelines, _ = inspect.getsourcelines(fn)
|
| 35 |
+
sourcelines = normalize_source_lines(sourcelines)
|
| 36 |
+
source = ''.join(sourcelines)
|
| 37 |
+
normalized_str = textwrap.dedent(source)
|
| 38 |
+
|
| 39 |
+
# Rewrite the original AST
|
| 40 |
+
source_ast = ast.parse(normalized_str)
|
| 41 |
+
dest_ast = ast.fix_missing_locations(self.visit(source_ast))
|
| 42 |
+
|
| 43 |
+
# Pull out the compiled function from the newly-created Module
|
| 44 |
+
code = compile(dest_ast, "", "exec")
|
| 45 |
+
globals_dict = copy.copy(fn.__globals__)
|
| 46 |
+
keys_before = set(globals_dict.keys())
|
| 47 |
+
exec(code, globals_dict)
|
| 48 |
+
new_keys = list(set(globals_dict.keys()) - keys_before)
|
| 49 |
+
assert len(new_keys) == 1
|
| 50 |
+
fn_compiled = globals_dict[new_keys[0]]
|
| 51 |
+
|
| 52 |
+
# return the compiled function with the original globals
|
| 53 |
+
def change_func_globals(f, globals):
|
| 54 |
+
"""Based on https://stackoverflow.com/a/13503277/2988730 (@unutbu)"""
|
| 55 |
+
# __globals__ is a private member of the function class
|
| 56 |
+
# so we have to copy the function, f, all of its member, except f.__globals__
|
| 57 |
+
g = FunctionType(
|
| 58 |
+
f.__code__,
|
| 59 |
+
globals,
|
| 60 |
+
name=f.__name__,
|
| 61 |
+
argdefs=f.__defaults__,
|
| 62 |
+
closure=f.__closure__,
|
| 63 |
+
)
|
| 64 |
+
g = functools.update_wrapper(g, f)
|
| 65 |
+
g.__kwdefaults__ = copy.copy(f.__kwdefaults__) # type:ignore[attr-defined]
|
| 66 |
+
return g
|
| 67 |
+
# Return the correct FunctionType object
|
| 68 |
+
return change_func_globals(fn_compiled, globals=fn.__globals__)
|
| 69 |
+
|
| 70 |
+
def visit_Assert(self, node):
|
| 71 |
+
"""
|
| 72 |
+
Swap out the Assert node (Python's `assert`) with a callsite to the
|
| 73 |
+
symbolically-traceable torch._assert function
|
| 74 |
+
"""
|
| 75 |
+
# Create the Call node
|
| 76 |
+
n = ast.parse('torch._assert()', mode='eval')
|
| 77 |
+
assert isinstance(n, ast.Expression)
|
| 78 |
+
call_node = n.body
|
| 79 |
+
assert isinstance(call_node, ast.Call)
|
| 80 |
+
msg = node.msg if node.msg else ast.Constant(value="", kind=None)
|
| 81 |
+
call_node.args = [node.test, msg]
|
| 82 |
+
|
| 83 |
+
# Ensure that the new node conforms to the Python AST grammar
|
| 84 |
+
expr_wrapper = ast.Expr(value=call_node)
|
| 85 |
+
|
| 86 |
+
# Return the new Call node to signify that we want to use it as
|
| 87 |
+
# a replacement for the original _assert node
|
| 88 |
+
return ast.copy_location(expr_wrapper, node)
|
| 89 |
+
|
| 90 |
+
def visit_AnnAssign(self, node):
|
| 91 |
+
"""
|
| 92 |
+
Swap out Python's AnnAssign with an Assign node where the annotation function is called.
|
| 93 |
+
Example:
|
| 94 |
+
Original:
|
| 95 |
+
y: Tensor_Type(1,2,3, Dyn) = f2(x)
|
| 96 |
+
Output:
|
| 97 |
+
y = annotate(f2(x),Tensor_Type((1,2,3,Dyn)))
|
| 98 |
+
"""
|
| 99 |
+
return ast.Assign(targets=[node.target], value=ast.Call(
|
| 100 |
+
func=ast.Name(id='annotate', ctx=ast.Load()),
|
| 101 |
+
args=[node.value, node.annotation], keywords=[]))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class RewritingTracer(Tracer):
|
| 105 |
+
def trace(self, root: Union[torch.nn.Module, Callable], concrete_args: Optional[Dict[str, Any]] = None) -> Graph:
|
| 106 |
+
return super().trace(_rewrite(root), concrete_args)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _rewrite(fn: Union[torch.nn.Module, Callable]) -> Union[torch.nn.Module, Callable]:
|
| 110 |
+
if isinstance(fn, torch.nn.Module):
|
| 111 |
+
# Rewrite this module's `forward` as well as the `forward`s of
|
| 112 |
+
# all of this module's recursive descendents. Return the new,
|
| 113 |
+
# rewritten module hierarchy.
|
| 114 |
+
def rewrite_module(m : torch.nn.Module):
|
| 115 |
+
class RewrittenModule(torch.nn.Module):
|
| 116 |
+
def __init__(self, orig):
|
| 117 |
+
super().__init__()
|
| 118 |
+
for k, v in orig.__dict__.items():
|
| 119 |
+
if isinstance(v, torch.nn.Module):
|
| 120 |
+
self.__dict__[k] = copy.copy(rewrite_module(v))
|
| 121 |
+
else:
|
| 122 |
+
self.__dict__[k] = copy.copy(v)
|
| 123 |
+
RewrittenModule.forward = AST_Rewriter().rewrite(cast(FunctionType, m.forward))
|
| 124 |
+
return RewrittenModule(m)
|
| 125 |
+
return rewrite_module(fn)
|
| 126 |
+
else:
|
| 127 |
+
# Rewrite this single free function
|
| 128 |
+
return AST_Rewriter().rewrite(cast(FunctionType, fn))
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/schema_type_annotation.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.fx
|
| 4 |
+
import inspect
|
| 5 |
+
from typing import Any, Dict, Optional, Tuple
|
| 6 |
+
from torch.fx.node import Argument, Target
|
| 7 |
+
from torch._jit_internal import boolean_dispatched
|
| 8 |
+
from torch.fx.operator_schemas import _torchscript_type_to_python_type
|
| 9 |
+
|
| 10 |
+
from torch.fx import Transformer
|
| 11 |
+
|
| 12 |
+
class AnnotateTypesWithSchema(Transformer):
|
| 13 |
+
"""
|
| 14 |
+
Use Python function signatures to annotate types for `Nodes` within an FX graph.
|
| 15 |
+
This pulls out Python function signatures for:
|
| 16 |
+
|
| 17 |
+
1. Standard `torch.nn` Module calls
|
| 18 |
+
2. `torch.nn.functional` calls
|
| 19 |
+
3. Attribute fetches via `get_attr`
|
| 20 |
+
|
| 21 |
+
Example usage:
|
| 22 |
+
|
| 23 |
+
m = torchvision.models.resnet18()
|
| 24 |
+
|
| 25 |
+
traced = torch.fx.symbolic_trace(m)
|
| 26 |
+
|
| 27 |
+
traced = AnnotateTypesWithSchema(traced).transform()
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
def __init__(self, module : torch.nn.Module, annotate_functionals : bool = True,
|
| 31 |
+
annotate_modules : bool = True, annotate_get_attrs : bool = True):
|
| 32 |
+
super().__init__(module)
|
| 33 |
+
self.annotate_functionals = annotate_functionals
|
| 34 |
+
self.annotate_modules = annotate_modules
|
| 35 |
+
self.annotate_get_attrs = annotate_get_attrs
|
| 36 |
+
|
| 37 |
+
def call_function(self, target : Target, args : Tuple[Argument, ...], kwargs : Dict[str, Any]):
|
| 38 |
+
python_ret_type = None
|
| 39 |
+
if self.annotate_functionals and target.__module__ == 'torch.nn.functional':
|
| 40 |
+
target_for_analysis = target
|
| 41 |
+
if target in boolean_dispatched:
|
| 42 |
+
# HACK: `boolean_dispatch` as used in `torch.nn.functional` makes it so that we have
|
| 43 |
+
# a 2-way dispatch based on a boolean value. Here we check that the `true` and `false`
|
| 44 |
+
# branches of the dispatch have exactly the same signature. If they do, use the `true`
|
| 45 |
+
# branch signature for analysis. Otherwise, leave this un-normalized
|
| 46 |
+
assert not isinstance(target, str)
|
| 47 |
+
dispatched = boolean_dispatched[target]
|
| 48 |
+
if_true, if_false = dispatched['if_true'], dispatched['if_false']
|
| 49 |
+
# TODO: can we emit the union of these? What are the implications on TorchScript
|
| 50 |
+
# compilation?
|
| 51 |
+
if inspect.signature(if_true).return_annotation != inspect.signature(if_false).return_annotation:
|
| 52 |
+
return super().call_function(target, args, kwargs)
|
| 53 |
+
target_for_analysis = if_true
|
| 54 |
+
|
| 55 |
+
python_ret_type = self._extract_python_return_type(target_for_analysis)
|
| 56 |
+
|
| 57 |
+
return_proxy = super().call_function(target, args, kwargs)
|
| 58 |
+
return_proxy.node.type = return_proxy.node.type if return_proxy.node.type else python_ret_type
|
| 59 |
+
return return_proxy
|
| 60 |
+
|
| 61 |
+
def call_module(self, target : Target, args : Tuple[Argument, ...], kwargs : Dict[str, Any]):
|
| 62 |
+
python_ret_type = None
|
| 63 |
+
assert isinstance(target, str)
|
| 64 |
+
submod = self.fetch_attr(target)
|
| 65 |
+
if self.annotate_modules and hasattr(submod.__class__, '__name__'):
|
| 66 |
+
classname = submod.__class__.__name__
|
| 67 |
+
if getattr(torch.nn, classname, None) == submod.__class__:
|
| 68 |
+
python_ret_type = self._extract_python_return_type(submod.forward)
|
| 69 |
+
return_proxy = super().call_module(target, args, kwargs)
|
| 70 |
+
return_proxy.node.type = return_proxy.node.type if return_proxy.node.type else python_ret_type
|
| 71 |
+
return return_proxy
|
| 72 |
+
|
| 73 |
+
def get_attr(self, target : torch.fx.node.Target, args : Tuple[Argument, ...], kwargs : Dict[str, Any]):
|
| 74 |
+
attr_proxy = super().get_attr(target, args, kwargs)
|
| 75 |
+
|
| 76 |
+
if self.annotate_get_attrs:
|
| 77 |
+
module_itr = self.module
|
| 78 |
+
assert isinstance(target, str)
|
| 79 |
+
atoms = target.split('.')
|
| 80 |
+
for i, atom in enumerate(atoms):
|
| 81 |
+
if not hasattr(module_itr, atom):
|
| 82 |
+
raise RuntimeError(f'Node referenced nonextent target {".".join(atoms[:i])}!')
|
| 83 |
+
module_itr = getattr(module_itr, atom)
|
| 84 |
+
|
| 85 |
+
maybe_inferred_ts_type = torch._C._jit_try_infer_type(module_itr)
|
| 86 |
+
if maybe_inferred_ts_type.success():
|
| 87 |
+
python_type = _torchscript_type_to_python_type(maybe_inferred_ts_type.type())
|
| 88 |
+
attr_proxy.node.type = python_type if not attr_proxy.node.type else attr_proxy.node.type
|
| 89 |
+
|
| 90 |
+
return attr_proxy
|
| 91 |
+
|
| 92 |
+
def _extract_python_return_type(self, target : Target) -> Optional[Any]:
|
| 93 |
+
"""
|
| 94 |
+
Given a Python call target, try to extract the Python return annotation
|
| 95 |
+
if it is available, otherwise return None
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
|
| 99 |
+
target (Callable): Python callable to get return annotation for
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
|
| 103 |
+
Optional[Any]: Return annotation from the `target`, or None if it was
|
| 104 |
+
not available.
|
| 105 |
+
"""
|
| 106 |
+
assert callable(target)
|
| 107 |
+
try:
|
| 108 |
+
sig = inspect.signature(target)
|
| 109 |
+
except (ValueError, TypeError):
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
return sig.return_annotation if sig.return_annotation is not inspect.Signature.empty else None
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/sym_node.py
ADDED
|
@@ -0,0 +1,1554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
This file does three things:
|
| 4 |
+
- Contains the definition of SymNode
|
| 5 |
+
- Installs all the magic methods into SymBool, SymFloat, SymFloat at import time
|
| 6 |
+
- Does not depend on sympy at import time
|
| 7 |
+
|
| 8 |
+
As this file is imported from within torch/__init__.py we do not want it to depend on SymPy
|
| 9 |
+
to avoid having to load SymPy at import time, as doing so is *very* slow.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import builtins
|
| 13 |
+
import itertools
|
| 14 |
+
import logging
|
| 15 |
+
import math
|
| 16 |
+
import operator
|
| 17 |
+
import sys
|
| 18 |
+
from functools import lru_cache, update_wrapper
|
| 19 |
+
from typing import Optional, Type, TYPE_CHECKING, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
# NB: The sym_* functions are used via getattr() and must be imported here.
|
| 24 |
+
from torch import ( # noqa: F401
|
| 25 |
+
sym_float,
|
| 26 |
+
sym_ite,
|
| 27 |
+
sym_max,
|
| 28 |
+
sym_min,
|
| 29 |
+
sym_not,
|
| 30 |
+
SymBool,
|
| 31 |
+
SymFloat,
|
| 32 |
+
SymInt,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from torch.fx.experimental.symbolic_shapes import ShapeEnv
|
| 38 |
+
|
| 39 |
+
log = logging.getLogger(__name__)
|
| 40 |
+
sym_node_log = torch._logging.getArtifactLogger(__name__, "sym_node")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
__all__ = ["SymNode", "method_to_operator", "magic_methods"]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
from torch.types import py_sym_types as SymTypes
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _to_symtype(t):
|
| 50 |
+
if t is bool:
|
| 51 |
+
return SymBool
|
| 52 |
+
if t is int:
|
| 53 |
+
return SymInt
|
| 54 |
+
if t is float:
|
| 55 |
+
return SymFloat
|
| 56 |
+
return t
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# TODO: An incomplete list
|
| 60 |
+
# 1. Set variables to be equal when we do equality
|
| 61 |
+
# 2. Specialize on 0/1 when we do subtraction
|
| 62 |
+
class SymNode:
|
| 63 |
+
"""
|
| 64 |
+
This is a type erased SymInt/SymFloat which we use to do actual operations.
|
| 65 |
+
End users don't touch this. Magic methods are NOT defined on this object.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
expr,
|
| 71 |
+
shape_env,
|
| 72 |
+
pytype,
|
| 73 |
+
hint: Optional[Union[int, float, bool]],
|
| 74 |
+
constant=None,
|
| 75 |
+
fx_node=None,
|
| 76 |
+
):
|
| 77 |
+
self._expr = expr
|
| 78 |
+
self.shape_env = shape_env
|
| 79 |
+
self.pytype = pytype
|
| 80 |
+
|
| 81 |
+
# What's the difference between hint and constant?
|
| 82 |
+
#
|
| 83 |
+
# - A constant is known to be invariant across invocations of the model;
|
| 84 |
+
# it will always be this value. We only really know this when we
|
| 85 |
+
# encounter an honest-to-goodness literal (when wrapping it into
|
| 86 |
+
# a SymNode, we set constant.) Most of the time, constant is None
|
| 87 |
+
#
|
| 88 |
+
# - A hint is a *particular* value from the particular run we are
|
| 89 |
+
# tracing, but it may vary the next time around. It's useful to
|
| 90 |
+
# keep this around, as if we need a concrete value from a SymNode,
|
| 91 |
+
# we will return the hint and guard on the expression that produced
|
| 92 |
+
# it giving the same hint next time around. The hint is not
|
| 93 |
+
# guaranteed to be set either: if you have an unbacked SymNode,
|
| 94 |
+
# there won't be any hint; it was the result of some tensor-dependent
|
| 95 |
+
# computation, but we don't know what it actually is because we
|
| 96 |
+
# haven't actually run the tensor computation.
|
| 97 |
+
#
|
| 98 |
+
# If _hint is None, we will query maybe_evaluate_static(compute_hint=True)
|
| 99 |
+
# in hopes that we've learned enough about the unbacked symints to
|
| 100 |
+
# discharge the hint; otherwise, you're likely to just error out.
|
| 101 |
+
#
|
| 102 |
+
# (A previous version of this system had some optimizations to only
|
| 103 |
+
# recompute when it was possible we had learned enough about the
|
| 104 |
+
# unbacked symint that a hint was now possible, but as we added more
|
| 105 |
+
# potential refinements to unbacked symints this got harder to keep
|
| 106 |
+
# in sync, so we've deleted it for now.)
|
| 107 |
+
|
| 108 |
+
def compute_hint():
|
| 109 |
+
from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 110 |
+
|
| 111 |
+
# This occasionally gets exercised by, e.g.,
|
| 112 |
+
# convert_shape_to_symint. It's just a nicety so you don't HAVE
|
| 113 |
+
# to have a correct hint on hand when making a SymNode.
|
| 114 |
+
# Don't attempt to compute for unbacked, this can be quite
|
| 115 |
+
# expensive.
|
| 116 |
+
if free_unbacked_symbols(self.expr):
|
| 117 |
+
return None
|
| 118 |
+
hint = self.shape_env._maybe_evaluate_static(self.expr, compute_hint=True)
|
| 119 |
+
if hint is not None:
|
| 120 |
+
hint = self.pytype(hint) if not isinstance(hint, SymTypes) else hint
|
| 121 |
+
return hint
|
| 122 |
+
|
| 123 |
+
if hint is not None:
|
| 124 |
+
assert type(hint) is pytype or type(hint) is _to_symtype(pytype), (
|
| 125 |
+
"Cannot create SymNode of type "
|
| 126 |
+
f"{pytype} with incompatible hint of type {type(hint)}"
|
| 127 |
+
)
|
| 128 |
+
if self.shape_env and self.shape_env._translation_validation_enabled:
|
| 129 |
+
# This is technically not TV, but this assert is expensive so
|
| 130 |
+
# let's only do it when we're already doing expensive things
|
| 131 |
+
computed_hint = compute_hint()
|
| 132 |
+
assert (
|
| 133 |
+
hint == computed_hint
|
| 134 |
+
), f"{hint} != {computed_hint} (for {self.expr})"
|
| 135 |
+
else:
|
| 136 |
+
hint = compute_hint()
|
| 137 |
+
self._hint = hint
|
| 138 |
+
self.constant: Optional[Union[int, float, bool]] = constant
|
| 139 |
+
|
| 140 |
+
# Record the FX node of the current node if we are doing translation
|
| 141 |
+
# validation. They will be used for building the input assertions for
|
| 142 |
+
# the translation validation problem.
|
| 143 |
+
tx_validation_en = (
|
| 144 |
+
self.shape_env and self.shape_env._translation_validation_enabled
|
| 145 |
+
)
|
| 146 |
+
self.fx_node = tx_validation_en and fx_node
|
| 147 |
+
|
| 148 |
+
def with_shape_env(self, shape_env: "ShapeEnv") -> "SymNode":
|
| 149 |
+
return SymNode(
|
| 150 |
+
self._expr, shape_env, self.pytype, self._hint, self.constant, self.fx_node
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def _value_eq(self, other: "SymNode") -> bool:
|
| 154 |
+
# Purposely don't include the shape_env in the eq.
|
| 155 |
+
return (
|
| 156 |
+
self._expr == other._expr
|
| 157 |
+
and self.pytype == other.pytype
|
| 158 |
+
and self._hint == other._hint
|
| 159 |
+
and self.constant == other.constant
|
| 160 |
+
and self.fx_node == other.fx_node
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def _value_hash(self) -> int:
|
| 164 |
+
# Purposely don't include the shape_env in the hash.
|
| 165 |
+
return hash((self._expr, self.pytype, self._hint, self.constant, self.fx_node))
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def expr(self):
|
| 169 |
+
return self.shape_env.replace(self._expr)
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def hint(self):
|
| 173 |
+
return self._hint
|
| 174 |
+
|
| 175 |
+
def has_hint(self):
|
| 176 |
+
return self._hint is not None
|
| 177 |
+
|
| 178 |
+
def require_hint(self, fallback=None):
|
| 179 |
+
if self._hint is None:
|
| 180 |
+
if fallback is not None:
|
| 181 |
+
return fallback
|
| 182 |
+
# NB: we expect this to raise
|
| 183 |
+
return self.shape_env.size_hint(self.expr)
|
| 184 |
+
return self._hint
|
| 185 |
+
|
| 186 |
+
def maybe_as_int(self):
|
| 187 |
+
if self.expr.is_number:
|
| 188 |
+
return int(self.expr)
|
| 189 |
+
else:
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
# NB: This does conversions, not sure if this is good or not
|
| 193 |
+
def maybe_as_float(self):
|
| 194 |
+
import sympy
|
| 195 |
+
|
| 196 |
+
if isinstance(self.expr, sympy.Float):
|
| 197 |
+
return float(self.expr)
|
| 198 |
+
else:
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
def maybe_as_bool(self):
|
| 202 |
+
import sympy
|
| 203 |
+
|
| 204 |
+
if self.expr is sympy.true:
|
| 205 |
+
return True
|
| 206 |
+
elif self.expr is sympy.false:
|
| 207 |
+
return False
|
| 208 |
+
else:
|
| 209 |
+
return None
|
| 210 |
+
|
| 211 |
+
def is_int(self):
|
| 212 |
+
return self.pytype is int
|
| 213 |
+
|
| 214 |
+
def is_float(self):
|
| 215 |
+
return self.pytype is float
|
| 216 |
+
|
| 217 |
+
def is_bool(self):
|
| 218 |
+
return self.pytype is bool
|
| 219 |
+
|
| 220 |
+
def is_nested_int(self):
|
| 221 |
+
# Unbacked SymInts cannot be nested int today
|
| 222 |
+
return (
|
| 223 |
+
self._hint is not None
|
| 224 |
+
and isinstance(self._hint, SymInt)
|
| 225 |
+
and self._hint.node.is_nested_int()
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
def wrap_int(self, num):
|
| 229 |
+
assert type(num) is int
|
| 230 |
+
import sympy
|
| 231 |
+
|
| 232 |
+
return SymNode(
|
| 233 |
+
sympy.Integer(num), self.shape_env, int, num, constant=num, fx_node=num
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def wrap_float(self, num):
|
| 237 |
+
assert type(num) is float
|
| 238 |
+
import sympy
|
| 239 |
+
|
| 240 |
+
return SymNode(
|
| 241 |
+
sympy.Float(num), self.shape_env, float, num, constant=num, fx_node=num
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
def wrap_bool(self, num):
|
| 245 |
+
assert type(num) is bool
|
| 246 |
+
import sympy
|
| 247 |
+
|
| 248 |
+
return SymNode(
|
| 249 |
+
sympy.true if num else sympy.false,
|
| 250 |
+
self.shape_env,
|
| 251 |
+
bool,
|
| 252 |
+
num,
|
| 253 |
+
constant=num,
|
| 254 |
+
fx_node=num,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
def clone(self):
|
| 258 |
+
return self
|
| 259 |
+
|
| 260 |
+
def str(self):
|
| 261 |
+
return f"{self.expr}"
|
| 262 |
+
|
| 263 |
+
def __str__(self):
|
| 264 |
+
return self.str()
|
| 265 |
+
|
| 266 |
+
def __repr__(self):
|
| 267 |
+
rep = [
|
| 268 |
+
f"SymNode({self._expr}, shape_env={self.shape_env}, pytype={self.pytype}",
|
| 269 |
+
]
|
| 270 |
+
if self._hint is not None:
|
| 271 |
+
rep.append(f"hint={self._hint}")
|
| 272 |
+
if self.constant is not None:
|
| 273 |
+
rep.append(f"constant={self.constant}")
|
| 274 |
+
if self.fx_node is not None:
|
| 275 |
+
rep.append(f"fx_node={self.fx_node}")
|
| 276 |
+
return ", ".join(rep) + ")"
|
| 277 |
+
|
| 278 |
+
def _graph_repr(self) -> builtins.str:
|
| 279 |
+
# Representation used by GraphModule to create a pythonic version of a graph
|
| 280 |
+
return self.str()
|
| 281 |
+
|
| 282 |
+
# These methods call the metaprogrammed methods, they're hand written
|
| 283 |
+
# here so we get good stack traces
|
| 284 |
+
def abs(self) -> "SymNode":
|
| 285 |
+
return self._abs() # type: ignore[attr-defined]
|
| 286 |
+
|
| 287 |
+
def pos(self) -> "SymNode":
|
| 288 |
+
return self._pos() # type: ignore[attr-defined]
|
| 289 |
+
|
| 290 |
+
def round(self, ndigits=None) -> "SymNode":
|
| 291 |
+
return self._round(ndigits) # type: ignore[attr-defined]
|
| 292 |
+
|
| 293 |
+
def trunc(self) -> "SymNode":
|
| 294 |
+
return self._trunc() # type: ignore[attr-defined]
|
| 295 |
+
|
| 296 |
+
def add(self, other) -> "SymNode":
|
| 297 |
+
return self._add(other) # type: ignore[attr-defined]
|
| 298 |
+
|
| 299 |
+
def sub(self, other) -> "SymNode":
|
| 300 |
+
return self._sub(other) # type: ignore[attr-defined]
|
| 301 |
+
|
| 302 |
+
def mul(self, other) -> "SymNode":
|
| 303 |
+
return self._mul(other) # type: ignore[attr-defined]
|
| 304 |
+
|
| 305 |
+
def mod(self, other) -> "SymNode":
|
| 306 |
+
return self._mod(other) # type: ignore[attr-defined]
|
| 307 |
+
|
| 308 |
+
def float_pow(self, other) -> "SymNode":
|
| 309 |
+
return self._float_pow(other) # type: ignore[attr-defined]
|
| 310 |
+
|
| 311 |
+
def pow_by_natural(self, other) -> "SymNode":
|
| 312 |
+
return self._pow_by_natural(other) # type: ignore[attr-defined]
|
| 313 |
+
|
| 314 |
+
def and_(self, other) -> "SymNode":
|
| 315 |
+
return self._and_(other) # type: ignore[attr-defined]
|
| 316 |
+
|
| 317 |
+
def or_(self, other) -> "SymNode":
|
| 318 |
+
return self._or_(other) # type: ignore[attr-defined]
|
| 319 |
+
|
| 320 |
+
def float_truediv(self, other) -> "SymNode":
|
| 321 |
+
return self._float_truediv(other) # type: ignore[attr-defined]
|
| 322 |
+
|
| 323 |
+
def int_truediv(self, other) -> "SymNode":
|
| 324 |
+
return self._int_truediv(other) # type: ignore[attr-defined]
|
| 325 |
+
|
| 326 |
+
def int_floordiv(self, other) -> "SymNode":
|
| 327 |
+
return self._int_floordiv(other) # type: ignore[attr-defined]
|
| 328 |
+
|
| 329 |
+
def lshift(self, other) -> "SymNode":
|
| 330 |
+
return self._lshift(other) # type: ignore[attr-defined]
|
| 331 |
+
|
| 332 |
+
def rshift(self, other) -> "SymNode":
|
| 333 |
+
return self._rshift(other) # type: ignore[attr-defined]
|
| 334 |
+
|
| 335 |
+
def sym_not(self) -> "SymNode": # noqa: F811
|
| 336 |
+
return self._sym_not() # type: ignore[attr-defined]
|
| 337 |
+
|
| 338 |
+
def eq(self, other) -> "SymNode":
|
| 339 |
+
return self._eq(other) # type: ignore[attr-defined]
|
| 340 |
+
|
| 341 |
+
def ne(self, other) -> "SymNode":
|
| 342 |
+
return self._ne(other) # type: ignore[attr-defined]
|
| 343 |
+
|
| 344 |
+
def gt(self, other) -> "SymNode":
|
| 345 |
+
return self._gt(other) # type: ignore[attr-defined]
|
| 346 |
+
|
| 347 |
+
def lt(self, other) -> "SymNode":
|
| 348 |
+
return self._lt(other) # type: ignore[attr-defined]
|
| 349 |
+
|
| 350 |
+
def le(self, other) -> "SymNode":
|
| 351 |
+
return self._le(other) # type: ignore[attr-defined]
|
| 352 |
+
|
| 353 |
+
def ge(self, other) -> "SymNode":
|
| 354 |
+
return self._ge(other) # type: ignore[attr-defined]
|
| 355 |
+
|
| 356 |
+
def floor(self) -> "SymNode":
|
| 357 |
+
return self._floor() # type: ignore[attr-defined]
|
| 358 |
+
|
| 359 |
+
def is_integer(self) -> "SymNode":
|
| 360 |
+
return self._is_integer() # type: ignore[attr-defined]
|
| 361 |
+
|
| 362 |
+
def sym_float(self) -> "SymNode": # noqa: F811
|
| 363 |
+
return self._sym_float() # type: ignore[attr-defined]
|
| 364 |
+
|
| 365 |
+
def sym_int(self) -> "SymNode":
|
| 366 |
+
return self._sym_int() # type: ignore[attr-defined]
|
| 367 |
+
|
| 368 |
+
def ceil(self) -> "SymNode":
|
| 369 |
+
return self._ceil() # type: ignore[attr-defined]
|
| 370 |
+
|
| 371 |
+
def neg(self) -> "SymNode":
|
| 372 |
+
return self._neg() # type: ignore[attr-defined]
|
| 373 |
+
|
| 374 |
+
def sym_min(self, other) -> "SymNode": # noqa: F811
|
| 375 |
+
return self._sym_min(other) # type: ignore[attr-defined]
|
| 376 |
+
|
| 377 |
+
def sym_max(self, other) -> "SymNode": # noqa: F811
|
| 378 |
+
return self._sym_max(other) # type: ignore[attr-defined]
|
| 379 |
+
|
| 380 |
+
def sym_ite(self, then_val, else_val) -> "SymNode":
|
| 381 |
+
return self._sym_ite(then_val, else_val) # type: ignore[attr-defined]
|
| 382 |
+
|
| 383 |
+
def is_contiguous(self, sizes, strides) -> "SymNode":
|
| 384 |
+
return self._is_contiguous(sizes, strides) # type: ignore[attr-defined]
|
| 385 |
+
|
| 386 |
+
def is_channels_last_contiguous_2d(self, sizes, strides) -> "SymNode":
|
| 387 |
+
return self._is_channels_last_contiguous_2d(sizes, strides) # type: ignore[attr-defined]
|
| 388 |
+
|
| 389 |
+
def is_channels_last_contiguous_3d(self, sizes, strides) -> "SymNode":
|
| 390 |
+
return self._is_channels_last_contiguous_3d(sizes, strides) # type: ignore[attr-defined]
|
| 391 |
+
|
| 392 |
+
def is_channels_last_strides_2d(self, sizes, strides) -> "SymNode":
|
| 393 |
+
return self._is_channels_last_strides_2d(sizes, strides) # type: ignore[attr-defined]
|
| 394 |
+
|
| 395 |
+
def is_channels_last_strides_3d(self, sizes, strides) -> "SymNode":
|
| 396 |
+
return self._is_channels_last_strides_3d(sizes, strides) # type: ignore[attr-defined]
|
| 397 |
+
|
| 398 |
+
def is_non_overlapping_and_dense_indicator(self, sizes, strides) -> "SymNode":
|
| 399 |
+
return self._is_non_overlapping_and_dense_indicator(sizes, strides) # type: ignore[attr-defined]
|
| 400 |
+
|
| 401 |
+
# Make C++ happy
|
| 402 |
+
def sym_or(self, other):
|
| 403 |
+
return self.or_(other)
|
| 404 |
+
|
| 405 |
+
def sym_and(self, other):
|
| 406 |
+
return self.and_(other)
|
| 407 |
+
|
| 408 |
+
# There is no int_truediv available from C++
|
| 409 |
+
def truediv(self, other):
|
| 410 |
+
return self.float_truediv(other)
|
| 411 |
+
|
| 412 |
+
def floordiv(self, other) -> "SymNode":
|
| 413 |
+
return self.int_floordiv(other)
|
| 414 |
+
|
| 415 |
+
# We didn't bind integer pow in C++
|
| 416 |
+
def pow(self, other):
|
| 417 |
+
return self.float_pow(other)
|
| 418 |
+
|
| 419 |
+
def is_non_overlapping_and_dense(self, sizes, strides):
|
| 420 |
+
return self.is_non_overlapping_and_dense_indicator(sizes, strides).eq(to_node(self, 1)) # type: ignore[attr-defined]
|
| 421 |
+
|
| 422 |
+
def int_(self):
|
| 423 |
+
return self.guard_int("", 0) # NB: uses Python backtrace
|
| 424 |
+
|
| 425 |
+
# You can manually trigger a guard with this function
|
| 426 |
+
def guard_int(self, file, line):
|
| 427 |
+
# TODO: use the file/line for some useful diagnostic on why a
|
| 428 |
+
# guard occurred
|
| 429 |
+
r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node)
|
| 430 |
+
try:
|
| 431 |
+
return int(r)
|
| 432 |
+
except Exception:
|
| 433 |
+
log.warning("Failed to convert to int: %s", r)
|
| 434 |
+
raise
|
| 435 |
+
|
| 436 |
+
def guard_float(self, file, line):
|
| 437 |
+
# TODO: use the file/line for some useful diagnostic on why a
|
| 438 |
+
# guard occurred
|
| 439 |
+
r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node)
|
| 440 |
+
try:
|
| 441 |
+
return float(r)
|
| 442 |
+
except Exception:
|
| 443 |
+
log.warning("Failed to convert to float: %s", r)
|
| 444 |
+
raise
|
| 445 |
+
|
| 446 |
+
def guard_bool(self, file, line):
|
| 447 |
+
# TODO: use the file/line for some useful diagnostic on why a
|
| 448 |
+
# guard occurred
|
| 449 |
+
r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node)
|
| 450 |
+
try:
|
| 451 |
+
return bool(r)
|
| 452 |
+
except Exception:
|
| 453 |
+
log.warning("Failed to convert to bool: %s", r)
|
| 454 |
+
raise
|
| 455 |
+
|
| 456 |
+
def expect_true(self, file, line):
|
| 457 |
+
from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 458 |
+
|
| 459 |
+
if (
|
| 460 |
+
self.has_hint()
|
| 461 |
+
and not free_unbacked_symbols(self.expr)
|
| 462 |
+
and not self.shape_env.prefer_deferred_runtime_asserts_over_guards
|
| 463 |
+
):
|
| 464 |
+
# OK to generate guards
|
| 465 |
+
return self.guard_bool(file, line)
|
| 466 |
+
# Generate a deferred runtime assert (this might actually end up doing
|
| 467 |
+
# a regular guard if we can!)
|
| 468 |
+
# TODO: file/line here is very important, because the assert has been
|
| 469 |
+
# deferred so you can't backtrace easily
|
| 470 |
+
return self.shape_env.defer_runtime_assert(
|
| 471 |
+
self.expr, f"{file}:{line}", fx_node=self.fx_node
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
def expect_size(self, file, line):
|
| 475 |
+
from torch.fx.experimental.symbolic_shapes import _advise_is_size
|
| 476 |
+
|
| 477 |
+
b = self.ge(self.wrap_int(0))
|
| 478 |
+
# Generate a deferred runtime assert
|
| 479 |
+
r = b.expect_true(file, line)
|
| 480 |
+
# Refine compile time range, but only if it's unbacked.
|
| 481 |
+
# If you refine range for hinted variables, you can end up making
|
| 482 |
+
# improper deductions since compile time reasoning may be
|
| 483 |
+
# incompatible with runtime reasoning.
|
| 484 |
+
if r and not self.has_hint():
|
| 485 |
+
_advise_is_size(SymInt(self))
|
| 486 |
+
return r
|
| 487 |
+
|
| 488 |
+
def guard_size_oblivious(self, file, line):
|
| 489 |
+
"""
|
| 490 |
+
Like guard_bool, but if we encounter unbacked symbols, if those symbols
|
| 491 |
+
are size-like, we will treat them as >= 2 for the purposes of the analysis.
|
| 492 |
+
|
| 493 |
+
This CHANGES the runtime semantics, but all size-oblivious sites have been
|
| 494 |
+
audited to ensure that the runtime semantics don't change in a material way.
|
| 495 |
+
Acceptable runtime semantic changes are, e.g., squeeze() no longer dropping
|
| 496 |
+
an unbacked one size, or a tensor reporting as non-contiguous even if it's
|
| 497 |
+
contiguous if it would have been reported contiguous due to being empty.
|
| 498 |
+
"""
|
| 499 |
+
# TODO: use the file/line for some useful diagnostic on why a
|
| 500 |
+
# guard occurred
|
| 501 |
+
r = self.shape_env.evaluate_expr(
|
| 502 |
+
self.expr, self.hint, fx_node=self.fx_node, size_oblivious=True
|
| 503 |
+
)
|
| 504 |
+
try:
|
| 505 |
+
return bool(r)
|
| 506 |
+
except Exception:
|
| 507 |
+
log.warning("Failed to convert to bool: %s", r)
|
| 508 |
+
raise
|
| 509 |
+
|
| 510 |
+
def bool_(self):
|
| 511 |
+
return self.guard_bool("", 0)
|
| 512 |
+
|
| 513 |
+
def is_symbolic(self):
|
| 514 |
+
return True
|
| 515 |
+
|
| 516 |
+
def nested_int(self):
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
def is_constant(self):
|
| 520 |
+
return False
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# TODO: this probably needs the sizes-strides eval functions
|
| 524 |
+
METHOD_TO_OPERATOR = {
|
| 525 |
+
"pos": operator.pos,
|
| 526 |
+
"abs": operator.abs,
|
| 527 |
+
"add": operator.add,
|
| 528 |
+
"and": operator.and_,
|
| 529 |
+
"ceil": math.ceil,
|
| 530 |
+
"eq": operator.eq,
|
| 531 |
+
"floor": math.floor,
|
| 532 |
+
"trunc": math.trunc,
|
| 533 |
+
"int_floordiv": operator.floordiv,
|
| 534 |
+
"ge": operator.ge,
|
| 535 |
+
"gt": operator.gt,
|
| 536 |
+
"is_integer": lambda x: x.is_integer(),
|
| 537 |
+
"le": operator.le,
|
| 538 |
+
"lshift": operator.lshift,
|
| 539 |
+
"lt": operator.lt,
|
| 540 |
+
"mod": operator.mod,
|
| 541 |
+
"mul": operator.mul,
|
| 542 |
+
"ne": operator.ne,
|
| 543 |
+
"neg": operator.neg,
|
| 544 |
+
"or": operator.or_,
|
| 545 |
+
"float_pow": operator.pow,
|
| 546 |
+
"pow_by_natural": operator.pow,
|
| 547 |
+
"round": builtins.round,
|
| 548 |
+
"rshift": operator.rshift,
|
| 549 |
+
"sub": operator.sub,
|
| 550 |
+
"sym_float": sym_float,
|
| 551 |
+
"sym_ite": sym_ite,
|
| 552 |
+
"sym_max": sym_max,
|
| 553 |
+
"sym_min": sym_min,
|
| 554 |
+
"sym_not": sym_not,
|
| 555 |
+
"float_truediv": operator.truediv,
|
| 556 |
+
"int_truediv": operator.truediv,
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
unary_magic_methods = {
|
| 560 |
+
"abs",
|
| 561 |
+
"sym_float",
|
| 562 |
+
"sym_int",
|
| 563 |
+
"ceil",
|
| 564 |
+
"floor",
|
| 565 |
+
"neg",
|
| 566 |
+
"sym_not",
|
| 567 |
+
"pos",
|
| 568 |
+
"trunc",
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# Adding math ops: sqrt, cos, sin, ...
|
| 573 |
+
def _get_sym_node_fn(name):
|
| 574 |
+
def fn(self):
|
| 575 |
+
return getattr(self, f"_sym_{name}")()
|
| 576 |
+
|
| 577 |
+
return fn
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
math_op_names = (
|
| 581 |
+
"sqrt",
|
| 582 |
+
"cos",
|
| 583 |
+
"cosh",
|
| 584 |
+
"sin",
|
| 585 |
+
"sinh",
|
| 586 |
+
"tan",
|
| 587 |
+
"tanh",
|
| 588 |
+
"asin",
|
| 589 |
+
"acos",
|
| 590 |
+
"atan",
|
| 591 |
+
)
|
| 592 |
+
for name in math_op_names:
|
| 593 |
+
sym_name = f"sym_{name}"
|
| 594 |
+
priv_sym_name = f"_{sym_name}"
|
| 595 |
+
setattr(SymNode, sym_name, _get_sym_node_fn(name))
|
| 596 |
+
METHOD_TO_OPERATOR[sym_name] = getattr(torch, priv_sym_name)
|
| 597 |
+
unary_magic_methods.add(sym_name)
|
| 598 |
+
__all__.append(sym_name)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
# Unary methods that are not magic methods
|
| 602 |
+
unary_nonmagic_methods = {
|
| 603 |
+
"is_integer",
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
unary_methods = unary_magic_methods | unary_nonmagic_methods
|
| 607 |
+
|
| 608 |
+
# Most methods are only registered on SymInt and SymFloat
|
| 609 |
+
# Some methods are only be registered on SymBool
|
| 610 |
+
only_bool_magic_methods = {"and", "or", "sym_not", "sym_ite"}
|
| 611 |
+
# Methods that implicitly convert SymBool into SymInt
|
| 612 |
+
bool_becomes_int_magic_methods = {"add", "sub", "mul"}
|
| 613 |
+
# Methods that are also on SymBool, in addition to on SymInt and SymFloat
|
| 614 |
+
also_bool_magic_methods = {"eq"}
|
| 615 |
+
bool_magic_methods = only_bool_magic_methods | also_bool_magic_methods
|
| 616 |
+
|
| 617 |
+
# Methods that are only for float
|
| 618 |
+
only_float_magic_methods = {"is_integer", "round", "sym_int"}
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
magic_methods_on_operator_with_trailing_underscore = {"and", "or"}
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
always_float_magic_methods = {"int_truediv", "float_truediv", "sym_float", "float_pow"}
|
| 625 |
+
|
| 626 |
+
for name in math_op_names:
|
| 627 |
+
sym_name = f"sym_{name}"
|
| 628 |
+
always_float_magic_methods.add(sym_name)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
always_int_magic_methods = {"ceil", "floor", "trunc", "pow_by_natural"}
|
| 632 |
+
always_bool_magic_methods = {
|
| 633 |
+
"eq",
|
| 634 |
+
"ne",
|
| 635 |
+
"gt",
|
| 636 |
+
"lt",
|
| 637 |
+
"le",
|
| 638 |
+
"ge",
|
| 639 |
+
"and",
|
| 640 |
+
"or",
|
| 641 |
+
"sym_not",
|
| 642 |
+
"is_non_overlapping_and_dense",
|
| 643 |
+
"is_integer",
|
| 644 |
+
}
|
| 645 |
+
|
| 646 |
+
# Methods that have a `__foo__` as well as `__rfoo__`
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def _sympy_float_truediv(a, b):
|
| 650 |
+
from torch.utils._sympy.functions import FloatTrueDiv
|
| 651 |
+
|
| 652 |
+
return FloatTrueDiv(a, b)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def _sympy_int_truediv(a, b):
|
| 656 |
+
from torch.utils._sympy.functions import IntTrueDiv
|
| 657 |
+
|
| 658 |
+
return IntTrueDiv(a, b)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _sympy_floordiv(a, b):
|
| 662 |
+
from torch.utils._sympy.functions import FloorDiv
|
| 663 |
+
|
| 664 |
+
return FloorDiv(a, b)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def _sympy_mod(a, b):
|
| 668 |
+
from torch.utils._sympy.functions import Mod, PythonMod
|
| 669 |
+
|
| 670 |
+
if a.is_nonnegative and b.is_nonnegative:
|
| 671 |
+
return Mod(a, b)
|
| 672 |
+
else:
|
| 673 |
+
return PythonMod(a, b)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def _sympy_pow_by_natural(a, b):
|
| 677 |
+
from torch.utils._sympy.functions import PowByNatural
|
| 678 |
+
|
| 679 |
+
return PowByNatural(a, b)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def _sympy_float_pow(a, b):
|
| 683 |
+
from torch.utils._sympy.functions import FloatPow
|
| 684 |
+
|
| 685 |
+
return FloatPow(a, b)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def _sympy_and(a, b):
|
| 689 |
+
import sympy
|
| 690 |
+
|
| 691 |
+
return sympy.And(a, b)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def _sympy_or(a, b):
|
| 695 |
+
import sympy
|
| 696 |
+
|
| 697 |
+
return sympy.Or(a, b)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def _sympy_lshift(a, b):
|
| 701 |
+
from torch.utils._sympy.functions import LShift
|
| 702 |
+
|
| 703 |
+
return LShift(a, b)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def _sympy_rshift(a, b):
|
| 707 |
+
from torch.utils._sympy.functions import RShift
|
| 708 |
+
|
| 709 |
+
return RShift(a, b)
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
reflectable_magic_methods = {
|
| 713 |
+
"add": operator.add,
|
| 714 |
+
"sub": operator.sub,
|
| 715 |
+
"mul": operator.mul,
|
| 716 |
+
"mod": _sympy_mod,
|
| 717 |
+
"pow_by_natural": _sympy_pow_by_natural,
|
| 718 |
+
"float_pow": _sympy_float_pow,
|
| 719 |
+
"and": _sympy_and,
|
| 720 |
+
"or": _sympy_or,
|
| 721 |
+
"float_truediv": _sympy_float_truediv,
|
| 722 |
+
"int_truediv": _sympy_int_truediv,
|
| 723 |
+
"int_floordiv": _sympy_floordiv,
|
| 724 |
+
"lshift": _sympy_lshift,
|
| 725 |
+
"rshift": _sympy_rshift,
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _floor_ceil_helper(a, fn):
|
| 730 |
+
import sympy
|
| 731 |
+
|
| 732 |
+
if isinstance(a, sympy.Mul):
|
| 733 |
+
aa = a.args
|
| 734 |
+
if len(aa) == 2 and isinstance(aa[0], sympy.Float) and aa[1].is_integer:
|
| 735 |
+
coef = sympy.Integer(aa[0])
|
| 736 |
+
if aa[0] == coef: # structural equality test
|
| 737 |
+
return coef * aa[1]
|
| 738 |
+
if (
|
| 739 |
+
isinstance(a, sympy.Float)
|
| 740 |
+
and a == sympy.Integer(a)
|
| 741 |
+
or isinstance(a, sympy.Integer)
|
| 742 |
+
):
|
| 743 |
+
return sympy.Integer(a)
|
| 744 |
+
return fn(a)
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _sympy_floor(a):
|
| 748 |
+
from torch.utils._sympy.functions import FloorToInt
|
| 749 |
+
|
| 750 |
+
return FloorToInt(a)
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
# NB: this is Python trunc semantics which returns an int. Do NOT use this to
|
| 754 |
+
# represent torch.trunc (which is float to float)
|
| 755 |
+
def _sympy_trunc(a):
|
| 756 |
+
from torch.utils._sympy.functions import TruncToInt
|
| 757 |
+
|
| 758 |
+
return TruncToInt(a)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def _sympy_ceil(a):
|
| 762 |
+
from torch.utils._sympy.functions import CeilToInt
|
| 763 |
+
|
| 764 |
+
return CeilToInt(a)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def _sympy_eq(a, b):
|
| 768 |
+
import sympy
|
| 769 |
+
|
| 770 |
+
return sympy.Eq(a, b)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def _sympy_ne(a, b):
|
| 774 |
+
import sympy
|
| 775 |
+
|
| 776 |
+
return sympy.Ne(a, b)
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def _sympy_gt(a, b):
|
| 780 |
+
import sympy
|
| 781 |
+
|
| 782 |
+
return sympy.Gt(a, b)
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
def _sympy_lt(a, b):
|
| 786 |
+
import sympy
|
| 787 |
+
|
| 788 |
+
return sympy.Lt(a, b)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _sympy_le(a, b):
|
| 792 |
+
import sympy
|
| 793 |
+
|
| 794 |
+
return sympy.Le(a, b)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def _sympy_ge(a, b):
|
| 798 |
+
import sympy
|
| 799 |
+
|
| 800 |
+
return sympy.Ge(a, b)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def _sympy_min(a, b):
|
| 804 |
+
from torch.utils._sympy.functions import Min
|
| 805 |
+
|
| 806 |
+
return Min(a, b)
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _sympy_max(a, b):
|
| 810 |
+
from torch.utils._sympy.functions import Max
|
| 811 |
+
|
| 812 |
+
return Max(a, b)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def _sympy_ite(a, t, f):
|
| 816 |
+
import sympy
|
| 817 |
+
|
| 818 |
+
return sympy.Piecewise((t, a), (f, True))
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
current_module = sys.modules[__name__]
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def _get_sym_math_fn(name):
|
| 825 |
+
def fn(a):
|
| 826 |
+
import torch.utils._sympy.functions
|
| 827 |
+
|
| 828 |
+
return getattr(torch.utils._sympy.functions, f"OpaqueUnaryFn_{name}")(a)
|
| 829 |
+
|
| 830 |
+
return fn
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
for name in math_op_names:
|
| 834 |
+
priv_sympy_name = f"_sympy_{name}"
|
| 835 |
+
fn = _get_sym_math_fn(name)
|
| 836 |
+
fn.__qualname__ = fn.__name__ = priv_sympy_name
|
| 837 |
+
setattr(current_module, priv_sympy_name, fn)
|
| 838 |
+
|
| 839 |
+
del fn, name, priv_sympy_name # type: ignore[possibly-undefined]
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def _sympy_abs(a):
|
| 843 |
+
import sympy
|
| 844 |
+
|
| 845 |
+
return sympy.Abs(a)
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
def _sympy_round(number, ndigits=None):
|
| 849 |
+
from torch.utils._sympy.functions import RoundDecimal, RoundToInt
|
| 850 |
+
|
| 851 |
+
if ndigits is None:
|
| 852 |
+
return RoundToInt(number)
|
| 853 |
+
else:
|
| 854 |
+
return RoundDecimal(number, ndigits)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def _sympy_sym_float(a):
|
| 858 |
+
from torch.utils._sympy.functions import ToFloat
|
| 859 |
+
|
| 860 |
+
# NB: Cannot use a * 1.0 here, because 0 * 1.0 is 0 which incorrectly
|
| 861 |
+
# reports that it is an integer
|
| 862 |
+
return ToFloat(a)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
def _sympy_is_integer(a):
|
| 866 |
+
import sympy
|
| 867 |
+
|
| 868 |
+
from torch.utils._sympy.functions import ToFloat
|
| 869 |
+
|
| 870 |
+
return sympy.Eq(ToFloat(sympy.floor(a)), a)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
magic_methods = {
|
| 874 |
+
**reflectable_magic_methods,
|
| 875 |
+
"sym_not": operator.invert,
|
| 876 |
+
"pos": operator.pos,
|
| 877 |
+
"eq": _sympy_eq,
|
| 878 |
+
"ne": _sympy_ne,
|
| 879 |
+
"gt": _sympy_gt,
|
| 880 |
+
"lt": _sympy_lt,
|
| 881 |
+
"le": _sympy_le,
|
| 882 |
+
"ge": _sympy_ge,
|
| 883 |
+
"floor": _sympy_floor,
|
| 884 |
+
"trunc": _sympy_trunc,
|
| 885 |
+
"sym_float": _sympy_sym_float,
|
| 886 |
+
"ceil": _sympy_ceil,
|
| 887 |
+
"neg": operator.neg,
|
| 888 |
+
"sym_min": _sympy_min,
|
| 889 |
+
"sym_max": _sympy_max,
|
| 890 |
+
"sym_ite": _sympy_ite,
|
| 891 |
+
"abs": _sympy_abs,
|
| 892 |
+
"round": _sympy_round,
|
| 893 |
+
"is_integer": _sympy_is_integer,
|
| 894 |
+
}
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
for name in math_op_names:
|
| 898 |
+
sym_name = f"sym_{name}"
|
| 899 |
+
magic_methods[sym_name] = getattr(current_module, f"_sympy_{name}")
|
| 900 |
+
|
| 901 |
+
del name, sym_name, math_op_names, current_module # type: ignore[possibly-undefined]
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def sympy_is_contiguous(sizes, strides):
|
| 905 |
+
dim = len(sizes)
|
| 906 |
+
return sympy_is_contiguous_generic(sizes, strides, list(range(dim - 1, -1, -1)))
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def sympy_is_contiguous_generic(sizes, strides, dim_order):
|
| 910 |
+
import sympy
|
| 911 |
+
|
| 912 |
+
dim = len(sizes)
|
| 913 |
+
|
| 914 |
+
if len(dim_order) != dim:
|
| 915 |
+
return sympy.false
|
| 916 |
+
|
| 917 |
+
is_contiguous = sympy.true
|
| 918 |
+
z = sympy.Integer(1)
|
| 919 |
+
# Contiguous if the strides make sense (or the dim is size 1)
|
| 920 |
+
for d in dim_order:
|
| 921 |
+
is_contiguous &= sympy.Eq(sizes[d], sympy.Integer(1)) | sympy.Eq(strides[d], z)
|
| 922 |
+
z *= sizes[d]
|
| 923 |
+
# OR if any size is zero
|
| 924 |
+
for d in range(dim):
|
| 925 |
+
is_contiguous |= sympy.Eq(sizes[d], sympy.Integer(0))
|
| 926 |
+
return is_contiguous
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
# NB: There is a TODO in C++ to allow omitting the batch dim. If that
|
| 930 |
+
# happens you will need to refactor this
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
def sympy_is_channels_last_contiguous_2d(sizes, strides):
|
| 934 |
+
return sympy_is_contiguous_generic(sizes, strides, [1, 3, 2, 0])
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def sympy_is_channels_last_contiguous_3d(sizes, strides):
|
| 938 |
+
return sympy_is_contiguous_generic(sizes, strides, [1, 4, 3, 2, 0])
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def sympy_is_channels_last_strides_generic(sizes, strides, dim_order):
|
| 942 |
+
import sympy
|
| 943 |
+
|
| 944 |
+
from torch.utils._sympy.functions import Max
|
| 945 |
+
|
| 946 |
+
dim = len(sizes)
|
| 947 |
+
|
| 948 |
+
if dim != len(dim_order):
|
| 949 |
+
return sympy.false
|
| 950 |
+
|
| 951 |
+
m = sympy.Integer(0)
|
| 952 |
+
r = sympy.true
|
| 953 |
+
|
| 954 |
+
# special case for trivial C dimension. default to NCHW
|
| 955 |
+
r &= sympy.Ne(strides[1], 0)
|
| 956 |
+
|
| 957 |
+
for d in dim_order:
|
| 958 |
+
r &= sympy.Ne(sizes[d], 0) & (strides[d] >= m)
|
| 959 |
+
# Fallback to NCHW as default layout for ambiguous cases
|
| 960 |
+
# This is the flaw of implicit memory_format from strides.
|
| 961 |
+
# N111 tensor with identical strides for size 1 dimension;
|
| 962 |
+
# Two cases could lead us here:
|
| 963 |
+
# a. N111 contiguous Tensor ([N,1,1,1]@[1,1,1,1])
|
| 964 |
+
# b. N11W contiguous Tensor sliced on the W-dimension.
|
| 965 |
+
# ([N,1,1,1]@[W,W,W,W])
|
| 966 |
+
if d == 0:
|
| 967 |
+
r &= sympy.Ne(m, strides[1])
|
| 968 |
+
# This is necessary to:
|
| 969 |
+
# 1. distinguish the memory_format of N1H1;
|
| 970 |
+
# [H, 1, 1, 1] channels_last stride
|
| 971 |
+
# [H, H, 1, 1] contiguous stride
|
| 972 |
+
# 2. permutation of 1C1W:
|
| 973 |
+
# [1, C, 1, H]@[HC, H, H, 1] transpose(1, 3)
|
| 974 |
+
# [1, H, 1, C]@[HC, 1, H, H] shouldn't be identified as
|
| 975 |
+
# channels_last
|
| 976 |
+
m = strides[d] * Max(sizes[d], 1)
|
| 977 |
+
|
| 978 |
+
return r
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def sympy_is_channels_last_strides_2d(sizes, strides):
|
| 982 |
+
return sympy_is_channels_last_strides_generic(sizes, strides, [1, 3, 2, 0])
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def sympy_is_channels_last_strides_3d(sizes, strides):
|
| 986 |
+
return sympy_is_channels_last_strides_generic(sizes, strides, [1, 4, 3, 2, 0])
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def _sympy_is_non_overlapping_and_dense_indicator(sizes, strides):
|
| 990 |
+
from torch.utils._sympy.functions import IsNonOverlappingAndDenseIndicator
|
| 991 |
+
|
| 992 |
+
return IsNonOverlappingAndDenseIndicator(*sizes, *strides)
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
sizes_strides_methods = {
|
| 996 |
+
# TODO: These could also be done with indicators, maybe it is better
|
| 997 |
+
# for reasoning to do it that way
|
| 998 |
+
"is_contiguous": sympy_is_contiguous,
|
| 999 |
+
"is_channels_last_contiguous_2d": sympy_is_channels_last_contiguous_2d,
|
| 1000 |
+
"is_channels_last_contiguous_3d": sympy_is_channels_last_contiguous_3d,
|
| 1001 |
+
"is_channels_last_strides_2d": sympy_is_channels_last_strides_2d,
|
| 1002 |
+
"is_channels_last_strides_3d": sympy_is_channels_last_strides_3d,
|
| 1003 |
+
"is_non_overlapping_and_dense_indicator": _sympy_is_non_overlapping_and_dense_indicator,
|
| 1004 |
+
}
|
| 1005 |
+
|
| 1006 |
+
alternate_impl_if_hinted_methods = {
|
| 1007 |
+
"sym_min": builtins.min,
|
| 1008 |
+
"sym_max": builtins.max,
|
| 1009 |
+
}
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
def to_node(self, num):
|
| 1013 |
+
if isinstance(num, SymTypes):
|
| 1014 |
+
return num.node
|
| 1015 |
+
elif type(num) is bool:
|
| 1016 |
+
return self.wrap_bool(num)
|
| 1017 |
+
elif type(num) is int:
|
| 1018 |
+
return self.wrap_int(num)
|
| 1019 |
+
elif type(num) is float:
|
| 1020 |
+
return self.wrap_float(num)
|
| 1021 |
+
else:
|
| 1022 |
+
# NotImplemented is important so that Python tries the
|
| 1023 |
+
# other magic method
|
| 1024 |
+
return NotImplemented
|
| 1025 |
+
|
| 1026 |
+
|
| 1027 |
+
def wrap_node(x):
|
| 1028 |
+
# TODO: let C++ also take advantage of this
|
| 1029 |
+
if isinstance(x, SymNode) and x.constant is not None:
|
| 1030 |
+
return x.constant
|
| 1031 |
+
if x.is_int():
|
| 1032 |
+
return SymInt(x)
|
| 1033 |
+
elif x.is_float():
|
| 1034 |
+
return SymFloat(x)
|
| 1035 |
+
elif x.is_bool():
|
| 1036 |
+
return SymBool(x)
|
| 1037 |
+
else:
|
| 1038 |
+
raise AssertionError(f"unrecognized return type {x}")
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
def method_to_operator(method):
|
| 1042 |
+
return METHOD_TO_OPERATOR[method]
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def _make_node_magic(method, func):
|
| 1046 |
+
func = lru_cache(256)(func)
|
| 1047 |
+
|
| 1048 |
+
if method in magic_methods_on_operator_with_trailing_underscore:
|
| 1049 |
+
method_attr = f"{method}_"
|
| 1050 |
+
else:
|
| 1051 |
+
method_attr = method
|
| 1052 |
+
|
| 1053 |
+
def binary_magic_impl(self, other):
|
| 1054 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 1055 |
+
get_proxy_mode,
|
| 1056 |
+
handle_sym_dispatch,
|
| 1057 |
+
)
|
| 1058 |
+
from torch.fx.experimental.symbolic_shapes import safe_expand
|
| 1059 |
+
|
| 1060 |
+
op = method_to_operator(method)
|
| 1061 |
+
|
| 1062 |
+
out_hint = None
|
| 1063 |
+
if self.hint is not None and other.hint is not None:
|
| 1064 |
+
out_hint = op(self.hint, other.hint)
|
| 1065 |
+
|
| 1066 |
+
alternate_impl = alternate_impl_if_hinted_methods.get(method)
|
| 1067 |
+
if alternate_impl and out_hint is not None:
|
| 1068 |
+
return to_node(self, alternate_impl(wrap_node(self), wrap_node(other)))
|
| 1069 |
+
|
| 1070 |
+
if get_proxy_mode():
|
| 1071 |
+
return to_node(
|
| 1072 |
+
self, handle_sym_dispatch(op, (wrap_node(self), wrap_node(other)), {})
|
| 1073 |
+
)
|
| 1074 |
+
assert isinstance(other, SymNode)
|
| 1075 |
+
try:
|
| 1076 |
+
if method == "mod":
|
| 1077 |
+
from torch.utils._sympy.functions import Mod, PythonMod
|
| 1078 |
+
|
| 1079 |
+
# Special handling for mod that requires access to the value
|
| 1080 |
+
# ranges
|
| 1081 |
+
shape_env = self.shape_env
|
| 1082 |
+
if (
|
| 1083 |
+
self.expr.is_nonnegative
|
| 1084 |
+
or shape_env.bound_sympy(self.expr).lower >= 0
|
| 1085 |
+
) and (
|
| 1086 |
+
other.expr.is_nonnegative
|
| 1087 |
+
or shape_env.bound_sympy(other.expr).lower >= 0
|
| 1088 |
+
):
|
| 1089 |
+
out = Mod(self.expr, other.expr)
|
| 1090 |
+
else:
|
| 1091 |
+
out = PythonMod(self.expr, other.expr)
|
| 1092 |
+
else:
|
| 1093 |
+
# TODO: consider constant prop here
|
| 1094 |
+
out = func(self.expr, other.expr)
|
| 1095 |
+
except Exception:
|
| 1096 |
+
log.warning("failed to eval %s(%s, %s)", method, self.expr, other.expr)
|
| 1097 |
+
raise
|
| 1098 |
+
out = safe_expand(out)
|
| 1099 |
+
sym_node_log.debug("%s %s %s -> %s", method, self.expr, other.expr, out)
|
| 1100 |
+
pytype: Type
|
| 1101 |
+
# This is not strictly correct. In Python, a**b may return complex when
|
| 1102 |
+
# a < 0 and b is a float: (-1)**2.1. Same for sympy.sqrt(-3.14). This
|
| 1103 |
+
# returns a float while both arguments are ints: 2**(-1). Also, max and
|
| 1104 |
+
# min do not type promote. To avoid having data-dependent control flow
|
| 1105 |
+
# here, we just set the type to float if one of the args is a float. In
|
| 1106 |
+
# case of a type mismatch, we assume that it will be detected during
|
| 1107 |
+
# evaluation.
|
| 1108 |
+
if method in always_float_magic_methods:
|
| 1109 |
+
pytype = float
|
| 1110 |
+
elif method in always_bool_magic_methods:
|
| 1111 |
+
pytype = bool
|
| 1112 |
+
elif self.pytype is float or other.pytype is float:
|
| 1113 |
+
pytype = float
|
| 1114 |
+
else:
|
| 1115 |
+
pytype = self.pytype
|
| 1116 |
+
|
| 1117 |
+
if (
|
| 1118 |
+
pytype is not None
|
| 1119 |
+
and out_hint is not None
|
| 1120 |
+
and not isinstance(out_hint, SymTypes)
|
| 1121 |
+
):
|
| 1122 |
+
out_hint = pytype(out_hint)
|
| 1123 |
+
|
| 1124 |
+
# Create a FX node that corresponds to the operation being applied to
|
| 1125 |
+
# this node.
|
| 1126 |
+
fx_node, _ = self.shape_env._create_fx_call_function(
|
| 1127 |
+
op, (self.fx_node, other.fx_node)
|
| 1128 |
+
)
|
| 1129 |
+
return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node)
|
| 1130 |
+
|
| 1131 |
+
def unary_magic_impl(self):
|
| 1132 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 1133 |
+
get_proxy_mode,
|
| 1134 |
+
handle_sym_dispatch,
|
| 1135 |
+
)
|
| 1136 |
+
from torch.fx.experimental.symbolic_shapes import safe_expand
|
| 1137 |
+
|
| 1138 |
+
op = method_to_operator(method)
|
| 1139 |
+
if get_proxy_mode():
|
| 1140 |
+
return to_node(self, handle_sym_dispatch(op, (wrap_node(self),), {}))
|
| 1141 |
+
# TODO: consider constant prop here
|
| 1142 |
+
expr = self.expr
|
| 1143 |
+
if method == "floor" or method == "ceiling":
|
| 1144 |
+
expr = self.shape_env._simplify_floor_div(expr)
|
| 1145 |
+
|
| 1146 |
+
try:
|
| 1147 |
+
out = func(expr)
|
| 1148 |
+
except Exception:
|
| 1149 |
+
log.warning("failed to eval %s(%s)", method, expr)
|
| 1150 |
+
raise
|
| 1151 |
+
sym_node_log.debug("%s %s -> %s", func, expr, out)
|
| 1152 |
+
out_hint = None
|
| 1153 |
+
if self.hint is not None:
|
| 1154 |
+
out_hint = op(self.hint)
|
| 1155 |
+
out = safe_expand(out)
|
| 1156 |
+
pytype: Type
|
| 1157 |
+
if method in always_int_magic_methods:
|
| 1158 |
+
pytype = int
|
| 1159 |
+
elif method in always_bool_magic_methods:
|
| 1160 |
+
pytype = bool
|
| 1161 |
+
elif method in always_float_magic_methods:
|
| 1162 |
+
pytype = float
|
| 1163 |
+
else:
|
| 1164 |
+
pytype = self.pytype
|
| 1165 |
+
|
| 1166 |
+
fx_node, _ = self.shape_env._create_fx_call_function(op, (self.fx_node,))
|
| 1167 |
+
return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node)
|
| 1168 |
+
|
| 1169 |
+
if method in unary_methods:
|
| 1170 |
+
setattr(SymNode, f"_{method_attr}", unary_magic_impl)
|
| 1171 |
+
elif method == "sym_ite":
|
| 1172 |
+
|
| 1173 |
+
def sym_ite_impl(pred_node, then_node, else_node):
|
| 1174 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 1175 |
+
get_proxy_mode,
|
| 1176 |
+
handle_sym_dispatch,
|
| 1177 |
+
)
|
| 1178 |
+
from torch.fx.experimental.symbolic_shapes import safe_expand
|
| 1179 |
+
|
| 1180 |
+
out_hint = then_node.hint if pred_node.hint else else_node.hint
|
| 1181 |
+
if get_proxy_mode():
|
| 1182 |
+
return to_node(
|
| 1183 |
+
pred_node,
|
| 1184 |
+
handle_sym_dispatch(
|
| 1185 |
+
sym_ite,
|
| 1186 |
+
(
|
| 1187 |
+
wrap_node(pred_node),
|
| 1188 |
+
wrap_node(then_node),
|
| 1189 |
+
wrap_node(else_node),
|
| 1190 |
+
),
|
| 1191 |
+
{},
|
| 1192 |
+
),
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
try:
|
| 1196 |
+
out = func(pred_node.expr, then_node.expr, else_node.expr)
|
| 1197 |
+
except Exception:
|
| 1198 |
+
log.warning(
|
| 1199 |
+
"failed to eval %s(%s, %s, %s)",
|
| 1200 |
+
method,
|
| 1201 |
+
pred_node.expr,
|
| 1202 |
+
then_node.expr,
|
| 1203 |
+
else_node.expr,
|
| 1204 |
+
)
|
| 1205 |
+
raise
|
| 1206 |
+
|
| 1207 |
+
out = safe_expand(out)
|
| 1208 |
+
fx_node, _ = pred_node.shape_env._create_fx_call_function(
|
| 1209 |
+
sym_ite, (pred_node.fx_node, then_node.fx_node, else_node.fx_node)
|
| 1210 |
+
)
|
| 1211 |
+
return SymNode(
|
| 1212 |
+
out, pred_node.shape_env, then_node.pytype, out_hint, fx_node=fx_node
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
setattr(SymNode, f"_{method_attr}", sym_ite_impl)
|
| 1216 |
+
elif method == "round":
|
| 1217 |
+
|
| 1218 |
+
def round_impl(self, ndigits=None):
|
| 1219 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 1220 |
+
get_proxy_mode,
|
| 1221 |
+
handle_sym_dispatch,
|
| 1222 |
+
)
|
| 1223 |
+
from torch.fx.experimental.symbolic_shapes import safe_expand
|
| 1224 |
+
|
| 1225 |
+
op = builtins.round
|
| 1226 |
+
if get_proxy_mode():
|
| 1227 |
+
return to_node(
|
| 1228 |
+
self, handle_sym_dispatch(op, (wrap_node(self), ndigits), {})
|
| 1229 |
+
)
|
| 1230 |
+
|
| 1231 |
+
expr = self.expr
|
| 1232 |
+
try:
|
| 1233 |
+
out = func(expr, ndigits)
|
| 1234 |
+
except Exception:
|
| 1235 |
+
log.warning("failed to eval %s(%s, ndigits=%s)", method, expr, ndigits)
|
| 1236 |
+
raise
|
| 1237 |
+
|
| 1238 |
+
out = safe_expand(out)
|
| 1239 |
+
|
| 1240 |
+
if ndigits is None:
|
| 1241 |
+
pytype = int
|
| 1242 |
+
else:
|
| 1243 |
+
pytype = self.pytype
|
| 1244 |
+
|
| 1245 |
+
out_hint = None
|
| 1246 |
+
if self.hint is not None:
|
| 1247 |
+
out_hint = op(self.hint, ndigits)
|
| 1248 |
+
|
| 1249 |
+
# Internally, None is used as sentinel to indicate that a something is not a node on an FX graph. At the
|
| 1250 |
+
# same time, there is no way to wrap a plain None into an FX node. Thus, there is no way to pass None here
|
| 1251 |
+
# without triggering some asserts that check whether we are mixing FX nodes with untracked arguments. The
|
| 1252 |
+
# hack down below works, because all round function down the line all take ndigits=None as default in their
|
| 1253 |
+
# signature.
|
| 1254 |
+
# TODO: Remove the args construction below if a different sentinel is used by FX.
|
| 1255 |
+
# ezyang(May 2024): LOL
|
| 1256 |
+
args = [self.fx_node]
|
| 1257 |
+
if ndigits is not None:
|
| 1258 |
+
args.append(ndigits)
|
| 1259 |
+
fx_node, _ = self.shape_env._create_fx_call_function(op, tuple(args))
|
| 1260 |
+
return SymNode(out, self.shape_env, pytype, out_hint, fx_node=fx_node)
|
| 1261 |
+
|
| 1262 |
+
setattr(SymNode, f"_{method_attr}", round_impl)
|
| 1263 |
+
else:
|
| 1264 |
+
setattr(SymNode, f"_{method_attr}", binary_magic_impl)
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
def _make_node_sizes_strides(method, func):
|
| 1268 |
+
# NB: don't LRU cache, lots of arguments
|
| 1269 |
+
|
| 1270 |
+
def sizes_strides_impl(self, sizes, strides):
|
| 1271 |
+
from torch.fx.experimental.proxy_tensor import (
|
| 1272 |
+
get_proxy_mode,
|
| 1273 |
+
handle_sym_dispatch,
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
op = getattr(sys.modules[__name__], method)
|
| 1277 |
+
if get_proxy_mode():
|
| 1278 |
+
return to_node(
|
| 1279 |
+
self,
|
| 1280 |
+
handle_sym_dispatch(
|
| 1281 |
+
op,
|
| 1282 |
+
([wrap_node(s) for s in sizes], [wrap_node(s) for s in strides]),
|
| 1283 |
+
{},
|
| 1284 |
+
),
|
| 1285 |
+
)
|
| 1286 |
+
size_exprs = [s.expr for s in sizes]
|
| 1287 |
+
stride_exprs = [s.expr for s in strides]
|
| 1288 |
+
try:
|
| 1289 |
+
out = func(size_exprs, stride_exprs)
|
| 1290 |
+
except Exception:
|
| 1291 |
+
log.warning("failed to eval %s(%s, %s)", method, size_exprs, stride_exprs)
|
| 1292 |
+
raise
|
| 1293 |
+
# bool is never expandable
|
| 1294 |
+
|
| 1295 |
+
size_hints = []
|
| 1296 |
+
out_hint = None
|
| 1297 |
+
for s in sizes:
|
| 1298 |
+
if s.hint is None:
|
| 1299 |
+
break
|
| 1300 |
+
size_hints.append(s.hint)
|
| 1301 |
+
else:
|
| 1302 |
+
stride_hints = []
|
| 1303 |
+
for s in strides:
|
| 1304 |
+
if s.hint is None:
|
| 1305 |
+
break
|
| 1306 |
+
stride_hints.append(s.hint)
|
| 1307 |
+
else:
|
| 1308 |
+
out_hint = op(size_hints, stride_hints)
|
| 1309 |
+
|
| 1310 |
+
# NB: This is the indicator function, not the actual bool!
|
| 1311 |
+
pytype: Type
|
| 1312 |
+
if method.endswith("_indicator"):
|
| 1313 |
+
pytype = int
|
| 1314 |
+
else:
|
| 1315 |
+
pytype = bool
|
| 1316 |
+
return SymNode(out, self.shape_env, pytype, out_hint)
|
| 1317 |
+
|
| 1318 |
+
setattr(SymNode, f"_{method}", sizes_strides_impl)
|
| 1319 |
+
|
| 1320 |
+
# TODO: This is technically hotpath, but in the ideal end state
|
| 1321 |
+
# guards on this will resolve at a higher level so you never
|
| 1322 |
+
# spend time in this code
|
| 1323 |
+
def sizes_strides_user(sizes, strides):
|
| 1324 |
+
import sympy
|
| 1325 |
+
|
| 1326 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 1327 |
+
eval_is_non_overlapping_and_dense,
|
| 1328 |
+
)
|
| 1329 |
+
|
| 1330 |
+
for a in itertools.chain(sizes, strides):
|
| 1331 |
+
if isinstance(a, SymInt):
|
| 1332 |
+
return wrap_node(
|
| 1333 |
+
getattr(a.node, method)(
|
| 1334 |
+
[to_node(a.node, b) for b in sizes],
|
| 1335 |
+
[to_node(a.node, b) for b in strides],
|
| 1336 |
+
)
|
| 1337 |
+
)
|
| 1338 |
+
if method == "is_non_overlapping_and_dense_indicator":
|
| 1339 |
+
return eval_is_non_overlapping_and_dense(sizes, strides)
|
| 1340 |
+
else:
|
| 1341 |
+
# TODO: this is an awful implementation
|
| 1342 |
+
return bool(
|
| 1343 |
+
func(
|
| 1344 |
+
[sympy.sympify(a) for a in sizes],
|
| 1345 |
+
[sympy.sympify(a) for a in strides],
|
| 1346 |
+
)
|
| 1347 |
+
)
|
| 1348 |
+
|
| 1349 |
+
# Skip for is_non_overlapping_and_dense_indicator
|
| 1350 |
+
if not hasattr(sys.modules[__name__], method):
|
| 1351 |
+
setattr(sys.modules[__name__], method, sizes_strides_user)
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
for method, func in magic_methods.items():
|
| 1355 |
+
_make_node_magic(method, func)
|
| 1356 |
+
|
| 1357 |
+
for method, func in sizes_strides_methods.items():
|
| 1358 |
+
_make_node_sizes_strides(method, func)
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
def _make_user_magic(method, user_type):
|
| 1362 |
+
# User magic takes care of wrapping the other operand into a node,
|
| 1363 |
+
# so that our internal logic can assume everything is nodes
|
| 1364 |
+
|
| 1365 |
+
if method in magic_methods_on_operator_with_trailing_underscore:
|
| 1366 |
+
method_attr = f"sym_{method}"
|
| 1367 |
+
else:
|
| 1368 |
+
method_attr = method
|
| 1369 |
+
|
| 1370 |
+
def get_constant(x: Union[SymInt, int, SymFloat, float, SymBool, bool]):
|
| 1371 |
+
if isinstance(x, (int, float, bool)):
|
| 1372 |
+
return x
|
| 1373 |
+
if isinstance(x, SymBool):
|
| 1374 |
+
return x.node.guard_bool("", 0)
|
| 1375 |
+
raise AssertionError("expect to be called with constant SymBools")
|
| 1376 |
+
|
| 1377 |
+
def is_constant(x):
|
| 1378 |
+
if isinstance(x, (int, float, bool)):
|
| 1379 |
+
return True
|
| 1380 |
+
if isinstance(x, (SymInt, SymFloat, SymBool)):
|
| 1381 |
+
return x.node.is_constant()
|
| 1382 |
+
return False
|
| 1383 |
+
|
| 1384 |
+
# Promotion rules for binary operations. NB: we preserve PYTHON semantics
|
| 1385 |
+
# - if args are same type, do nothing
|
| 1386 |
+
# - if one arg is float, promote other arg to float
|
| 1387 |
+
# - nb: this applies to floordiv, even though output is integral
|
| 1388 |
+
# (it's still float)
|
| 1389 |
+
# - pow is funny business
|
| 1390 |
+
# - if both ints
|
| 1391 |
+
# - trigger a guard on exponent >= 0
|
| 1392 |
+
# - if non-negative, output is int
|
| 1393 |
+
# - otherwise, output is float
|
| 1394 |
+
# - otherwise, promote other arg to float
|
| 1395 |
+
# - nb: complex is impossible to handle correctly lol, with
|
| 1396 |
+
# negative base and integral float need to diverge semantics and
|
| 1397 |
+
# just always return complex. Neener neener pretend this problem
|
| 1398 |
+
# doesn't exist
|
| 1399 |
+
# - equality is pain: Python does the fancy thing where it unpacks the
|
| 1400 |
+
# mantissa from the float and then compares that against the int.
|
| 1401 |
+
# Which means it is able to tell that
|
| 1402 |
+
# 9007199254740993 != 9007199254740992. (rather than if the LHS was
|
| 1403 |
+
# promoted to float, in which case it would have truncated to the RHS
|
| 1404 |
+
# and subsequently been equal). We'll model this exactly by having
|
| 1405 |
+
# special mixed type equality operations. Unfortunately, we need to
|
| 1406 |
+
# do this for all comparison operations (maybe I'll only implement
|
| 1407 |
+
# compare)
|
| 1408 |
+
# - sym_ite mumble mumble really shouldn't allow mixed but whatever
|
| 1409 |
+
|
| 1410 |
+
if method in bool_becomes_int_magic_methods:
|
| 1411 |
+
|
| 1412 |
+
def promote(x):
|
| 1413 |
+
"""Implements True+True=2, which works in python but not sympy"""
|
| 1414 |
+
if isinstance(x, SymBool):
|
| 1415 |
+
return SymInt(x.node.wrap_int(int(x)))
|
| 1416 |
+
return x
|
| 1417 |
+
|
| 1418 |
+
else:
|
| 1419 |
+
|
| 1420 |
+
def promote(x):
|
| 1421 |
+
return x
|
| 1422 |
+
|
| 1423 |
+
def promote2(self, other):
|
| 1424 |
+
# TODO: Remove eq and other relations from this list.
|
| 1425 |
+
# CPython has fancy implementations for these to get as much precision
|
| 1426 |
+
# as possible instead of just promoting to float64 and praying, so we
|
| 1427 |
+
# need to handle them specially too.
|
| 1428 |
+
# Also, note that int_truediv doesn't go through this path: both
|
| 1429 |
+
# arguments are "int" so there isn't any promotion
|
| 1430 |
+
if method not in [
|
| 1431 |
+
"add",
|
| 1432 |
+
"sub",
|
| 1433 |
+
"mul",
|
| 1434 |
+
"mod",
|
| 1435 |
+
"float_pow",
|
| 1436 |
+
"float_truediv",
|
| 1437 |
+
"int_floordiv",
|
| 1438 |
+
"sym_min",
|
| 1439 |
+
"sym_max",
|
| 1440 |
+
# TODO: remove these
|
| 1441 |
+
"eq",
|
| 1442 |
+
"ne",
|
| 1443 |
+
"gt",
|
| 1444 |
+
"lt",
|
| 1445 |
+
"le",
|
| 1446 |
+
"ge",
|
| 1447 |
+
]:
|
| 1448 |
+
return self, other
|
| 1449 |
+
f_self = isinstance(self, (float, torch.SymFloat))
|
| 1450 |
+
f_other = isinstance(other, (float, torch.SymFloat))
|
| 1451 |
+
if f_self or f_other:
|
| 1452 |
+
if not f_self:
|
| 1453 |
+
self = torch.sym_float(self)
|
| 1454 |
+
if not f_other:
|
| 1455 |
+
other = torch.sym_float(other)
|
| 1456 |
+
return self, other
|
| 1457 |
+
|
| 1458 |
+
# Before and after performing the operation, check if any operands are constant.
|
| 1459 |
+
# If so, extract out the constant values first. If `self` itself is a
|
| 1460 |
+
# constant, then "redispatch" by calling back into the operator. Sometimes
|
| 1461 |
+
# this means that operations involving SymBool return plain bools.
|
| 1462 |
+
# Alternatively, we could also rewrap into constant Symbool (i.e. by
|
| 1463 |
+
# implementing wrap_bool in ConstantSymNodeImpl), but we're not doing that
|
| 1464 |
+
# today for no particular reason.
|
| 1465 |
+
def unary_magic_impl(self):
|
| 1466 |
+
self = promote(self)
|
| 1467 |
+
if is_constant(self):
|
| 1468 |
+
return (method_to_operator(method))(get_constant(self))
|
| 1469 |
+
return wrap_node(getattr(self.node, method_attr)())
|
| 1470 |
+
|
| 1471 |
+
def binary_magic_impl(self, other):
|
| 1472 |
+
if not isinstance(other, (int, float, bool, SymInt, SymFloat, SymBool)):
|
| 1473 |
+
return NotImplemented
|
| 1474 |
+
sym_node_log.debug("MAGIC %s %s %s", method, self, other)
|
| 1475 |
+
self = promote(self)
|
| 1476 |
+
other = promote(other)
|
| 1477 |
+
self, other = promote2(self, other)
|
| 1478 |
+
if is_constant(self):
|
| 1479 |
+
return (method_to_operator(method))(get_constant(self), other)
|
| 1480 |
+
if is_constant(other):
|
| 1481 |
+
other = get_constant(other)
|
| 1482 |
+
other_node = to_node(self.node, other)
|
| 1483 |
+
if other_node is NotImplemented:
|
| 1484 |
+
return NotImplemented
|
| 1485 |
+
ret = wrap_node(getattr(self.node, method_attr)(other_node))
|
| 1486 |
+
return get_constant(ret) if is_constant(ret) else ret
|
| 1487 |
+
|
| 1488 |
+
def rbinary_magic_impl(self, other):
|
| 1489 |
+
if not isinstance(other, (int, float, bool, SymInt, SymFloat, SymBool)):
|
| 1490 |
+
return NotImplemented
|
| 1491 |
+
self = promote(self)
|
| 1492 |
+
other = promote(other)
|
| 1493 |
+
self, other = promote2(self, other)
|
| 1494 |
+
if is_constant(self):
|
| 1495 |
+
return (method_to_operator(method))(get_constant(self), other)
|
| 1496 |
+
if is_constant(other):
|
| 1497 |
+
other = get_constant(other)
|
| 1498 |
+
other_node = to_node(self.node, other)
|
| 1499 |
+
if other_node is NotImplemented:
|
| 1500 |
+
return NotImplemented
|
| 1501 |
+
ret = wrap_node(getattr(other_node, method_attr)(self.node))
|
| 1502 |
+
return get_constant(ret) if is_constant(ret) else ret
|
| 1503 |
+
|
| 1504 |
+
if method in unary_magic_methods:
|
| 1505 |
+
setattr(user_type, f"__{method}__", unary_magic_impl)
|
| 1506 |
+
elif method in unary_nonmagic_methods:
|
| 1507 |
+
orig = getattr(user_type, method)
|
| 1508 |
+
setattr(user_type, method, update_wrapper(unary_magic_impl, orig))
|
| 1509 |
+
elif method == "sym_ite":
|
| 1510 |
+
|
| 1511 |
+
def sym_ite_magic_impl(pred, then_val, else_val):
|
| 1512 |
+
pred_node = pred.node
|
| 1513 |
+
then_node = to_node(pred_node, then_val)
|
| 1514 |
+
else_node = to_node(pred_node, else_val)
|
| 1515 |
+
if then_node is NotImplemented or else_node is NotImplemented:
|
| 1516 |
+
return NotImplemented
|
| 1517 |
+
assert (
|
| 1518 |
+
isinstance(then_node, SymNode)
|
| 1519 |
+
and isinstance(else_node, SymNode)
|
| 1520 |
+
and then_node.pytype == else_node.pytype
|
| 1521 |
+
)
|
| 1522 |
+
ret = wrap_node(getattr(pred.node, method_attr)(then_node, else_node))
|
| 1523 |
+
return get_constant(ret) if ret.node.is_constant() else ret
|
| 1524 |
+
|
| 1525 |
+
setattr(user_type, f"__{method}__", sym_ite_magic_impl)
|
| 1526 |
+
elif method == "round":
|
| 1527 |
+
|
| 1528 |
+
def round_magic_impl(self, ndigits=None):
|
| 1529 |
+
if is_constant(self):
|
| 1530 |
+
return builtins.round(get_constant(self), ndigits)
|
| 1531 |
+
|
| 1532 |
+
return wrap_node(getattr(self.node, method)(ndigits))
|
| 1533 |
+
|
| 1534 |
+
setattr(user_type, f"__{method}__", round_magic_impl)
|
| 1535 |
+
else:
|
| 1536 |
+
setattr(user_type, f"__{method}__", binary_magic_impl)
|
| 1537 |
+
if method in reflectable_magic_methods:
|
| 1538 |
+
setattr(user_type, f"__r{method}__", rbinary_magic_impl)
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
for method, func in magic_methods.items(): # type: ignore[assignment]
|
| 1542 |
+
if method in only_bool_magic_methods:
|
| 1543 |
+
_make_user_magic(method, SymBool)
|
| 1544 |
+
continue
|
| 1545 |
+
if method in only_float_magic_methods:
|
| 1546 |
+
_make_user_magic(method, SymFloat)
|
| 1547 |
+
continue
|
| 1548 |
+
if method in also_bool_magic_methods or method in bool_becomes_int_magic_methods:
|
| 1549 |
+
_make_user_magic(method, SymBool)
|
| 1550 |
+
_make_user_magic(method, SymInt)
|
| 1551 |
+
_make_user_magic(method, SymFloat)
|
| 1552 |
+
|
| 1553 |
+
del method
|
| 1554 |
+
del func
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/symbolic_shapes.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code=attr-defined
|
| 2 |
+
from .core import unify, reify # noqa: F403
|
| 3 |
+
from .more import unifiable # noqa: F403
|
| 4 |
+
from .variable import var, isvar, vars, variables, Var # noqa: F403
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (372 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/core.cpython-310.pyc
ADDED
|
Binary file (2.44 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/dispatch.cpython-310.pyc
ADDED
|
Binary file (316 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/match.cpython-310.pyc
ADDED
|
Binary file (4.52 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/more.cpython-310.pyc
ADDED
|
Binary file (3.46 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/unification_tools.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/fx/experimental/unification/__pycache__/variable.cpython-310.pyc
ADDED
|
Binary file (2.88 kB). View file
|
|
|