Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/config.py +45 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/converter.py +1613 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/__init__.py +5 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/case.py +175 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/__init__.py +61 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/assume_constant_result.py +20 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/autograd_function.py +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/class_method.py +22 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_class_method.py +44 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nested_function.py +41 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py +59 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_closed_over_variable.py +22 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_operands.py +35 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_predicate.py +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/constrain_as_size_example.py +23 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/constrain_as_value_example.py +26 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/decorator.py +23 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dictionary.py +17 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_assert.py +18 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py +15 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py +19 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_map.py +19 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_round.py +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py +15 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_view.py +17 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/fn_with_kwargs.py +30 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/list_contains.py +17 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/list_unpack.py +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/model_attr_mutation.py +24 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/nested_function.py +23 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/null_context_manager.py +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/optional_input.py +20 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/pytree_flatten.py +16 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/scalar_output.py +23 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/specialized_attribute.py +26 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/static_for_loop.py +16 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/static_if.py +18 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/tensor_setattr.py +15 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/type_reflection_method.py +22 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/unsupported_operator.py +18 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/user_input_mutation.py +17 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/gen_example.py +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/logging.py +47 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/error.py +56 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/non_strict_utils.py +1142 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_base.py +491 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py +32 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py +45 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/passes/__init__.py +1 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/config.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration module for torch.export.export.
|
| 3 |
+
|
| 4 |
+
This module contains various configuration flags and settings that control torch.export's
|
| 5 |
+
behavior, including:
|
| 6 |
+
- Runtime behavior flags
|
| 7 |
+
- Debugging and development options
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
from typing import Any, TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
from torch._environment import is_fbcode
|
| 14 |
+
from torch.utils._config_module import install_config_module
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# this flag controls whether we use new functional tracer. It
|
| 18 |
+
# should be True in the long term.
|
| 19 |
+
use_new_tracer_experimental = True
|
| 20 |
+
|
| 21 |
+
# this flag is used to control whether we want to instrument
|
| 22 |
+
# fake tensor creation to track potential leaks. It is off
|
| 23 |
+
# by default, but user can turn it on to debug leaks.
|
| 24 |
+
detect_non_strict_fake_tensor_leaks = False
|
| 25 |
+
|
| 26 |
+
# error on potentially pre-dispatch/non-strict tracing limitation
|
| 27 |
+
# this type of error usually happens when we encounter an op
|
| 28 |
+
# that we don't know how to proxy, resulting in untracked fake tensors
|
| 29 |
+
error_on_lifted_constant_tensors = True
|
| 30 |
+
|
| 31 |
+
# enable auto_functionalized_v2 in export
|
| 32 |
+
# We turn this off in fbcode due to downstream users not
|
| 33 |
+
# being ready to handle auto_functionalized_v2.
|
| 34 |
+
enable_auto_functionalized_v2_for_export = not is_fbcode()
|
| 35 |
+
|
| 36 |
+
use_legacy_dynamo_graph_capture = True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from torch.utils._config_typing import * # noqa: F401, F403
|
| 41 |
+
|
| 42 |
+
def _make_closure_patcher(**changes: Any) -> Any: ...
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
install_config_module(sys.modules[__name__])
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/converter.py
ADDED
|
@@ -0,0 +1,1613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import builtins
|
| 3 |
+
import logging
|
| 4 |
+
import operator
|
| 5 |
+
import typing
|
| 6 |
+
import warnings
|
| 7 |
+
from collections.abc import Callable, Sequence
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from typing import Any, Optional, Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.export._trace
|
| 13 |
+
from torch import _C
|
| 14 |
+
from torch._export.passes.replace_quantized_ops_with_standard_ops_pass import (
|
| 15 |
+
replace_quantized_ops_with_standard_ops,
|
| 16 |
+
)
|
| 17 |
+
from torch.export.dynamic_shapes import _tree_map_with_path, Dim
|
| 18 |
+
from torch.export.exported_program import ExportedProgram
|
| 19 |
+
from torch.export.graph_signature import (
|
| 20 |
+
ConstantArgument,
|
| 21 |
+
CustomObjArgument,
|
| 22 |
+
InputKind,
|
| 23 |
+
InputSpec,
|
| 24 |
+
OutputKind,
|
| 25 |
+
OutputSpec,
|
| 26 |
+
TensorArgument,
|
| 27 |
+
)
|
| 28 |
+
from torch.fx import subgraph_rewriter
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
log = logging.getLogger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _get_param_count_list(method_graph, args_params):
|
| 35 |
+
param_count_list = []
|
| 36 |
+
for input_, arg_params_ in zip(method_graph.inputs(), args_params):
|
| 37 |
+
if "PackedParams" in str(input_.type()):
|
| 38 |
+
in_vars, _ = torch.jit._flatten(arg_params_)
|
| 39 |
+
param_count_list.append(len(in_vars))
|
| 40 |
+
else:
|
| 41 |
+
param_count_list.append(arg_params_ is not None)
|
| 42 |
+
|
| 43 |
+
return param_count_list
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _trace_and_get_graph_from_model(model, args):
|
| 47 |
+
# A basic sanity check: make sure the state_dict keys are the same
|
| 48 |
+
# before and after running the model. Fail fast!
|
| 49 |
+
orig_state_dict_keys = torch.jit._unique_state_dict(model).keys()
|
| 50 |
+
|
| 51 |
+
# Disable Autocast cache because it replaces kernel's weight and bias
|
| 52 |
+
# by (undesired) constants.
|
| 53 |
+
# No perf impact for when there are reused weights since https://github.com/pytorch/pytorch/pull/85665
|
| 54 |
+
prev_autocast_cache_enabled = torch.is_autocast_cache_enabled()
|
| 55 |
+
torch.set_autocast_cache_enabled(False)
|
| 56 |
+
trace_graph, torch_out, _inputs_states = torch.jit._get_trace_graph(
|
| 57 |
+
model,
|
| 58 |
+
args,
|
| 59 |
+
strict=False,
|
| 60 |
+
_force_outplace=False,
|
| 61 |
+
_return_inputs_states=True,
|
| 62 |
+
)
|
| 63 |
+
torch.set_autocast_cache_enabled(prev_autocast_cache_enabled)
|
| 64 |
+
|
| 65 |
+
if orig_state_dict_keys != torch.jit._unique_state_dict(model).keys():
|
| 66 |
+
raise RuntimeError(
|
| 67 |
+
"state_dict changed after running the tracer; "
|
| 68 |
+
"something weird is happening in your model!"
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
return trace_graph, torch_out
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _create_jit_graph(
|
| 75 |
+
model: Union[torch.nn.Module, torch.jit.ScriptFunction], args: Sequence[Any]
|
| 76 |
+
) -> tuple[torch.Graph, list["_C.IValue"], Any, Optional[torch.ScriptModule]]:
|
| 77 |
+
if isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule)):
|
| 78 |
+
flattened_args = tuple(torch.jit._flatten(tuple(args))[0])
|
| 79 |
+
torch_out = None
|
| 80 |
+
|
| 81 |
+
if isinstance(model, torch.jit.ScriptModule):
|
| 82 |
+
try:
|
| 83 |
+
graph = model.forward.graph # type: ignore[attr-defined]
|
| 84 |
+
except AttributeError as e:
|
| 85 |
+
raise RuntimeError("'forward' method must be a script method") from e
|
| 86 |
+
_C._jit_pass_onnx_function_substitution(graph)
|
| 87 |
+
freezed_module = _C._freeze_module(
|
| 88 |
+
typing.cast(_C.ScriptModule, model._c), preserveParameters=True
|
| 89 |
+
)
|
| 90 |
+
module, params = _C._jit_onnx_list_model_parameters(freezed_module)
|
| 91 |
+
method_graph = module._get_method("forward").graph
|
| 92 |
+
args_params = tuple(args) + tuple(params)
|
| 93 |
+
param_count_list = _get_param_count_list(method_graph, args_params)
|
| 94 |
+
in_vars, _ = torch.jit._flatten(args_params)
|
| 95 |
+
graph = _C._propagate_and_assign_input_shapes(
|
| 96 |
+
method_graph, tuple(in_vars), param_count_list, False, False
|
| 97 |
+
)
|
| 98 |
+
return graph, params, torch_out, module
|
| 99 |
+
|
| 100 |
+
# torch.jit.ScriptFunction
|
| 101 |
+
params = []
|
| 102 |
+
graph = model.graph
|
| 103 |
+
_C._jit_pass_onnx_function_substitution(graph)
|
| 104 |
+
param_count_list = _get_param_count_list(graph, args)
|
| 105 |
+
graph = _C._propagate_and_assign_input_shapes(
|
| 106 |
+
graph, flattened_args, param_count_list, False, False
|
| 107 |
+
)
|
| 108 |
+
return graph, params, torch_out, None
|
| 109 |
+
|
| 110 |
+
graph, torch_out = _trace_and_get_graph_from_model(model, args)
|
| 111 |
+
_C._jit_pass_onnx_lint(graph)
|
| 112 |
+
state_dict = torch.jit._unique_state_dict(model)
|
| 113 |
+
params = list(state_dict.values())
|
| 114 |
+
graph_inputs = list(graph.inputs())
|
| 115 |
+
user_input_num = len(graph_inputs) - len(state_dict)
|
| 116 |
+
param_names = list(state_dict.keys())
|
| 117 |
+
for i, inp in enumerate(graph_inputs):
|
| 118 |
+
if i >= user_input_num:
|
| 119 |
+
inp.setDebugName(param_names[i - user_input_num])
|
| 120 |
+
_C._jit_pass_onnx_function_substitution(graph)
|
| 121 |
+
return graph, params, torch_out, None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def list_add(a, b):
|
| 125 |
+
return a + b
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def list_append(container, element):
|
| 129 |
+
return container + [element]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def execute_subgraph_from_prim_loop(
|
| 133 |
+
subgraph, iter_idx, len_loop_local_arguments, *args, **kwargs
|
| 134 |
+
):
|
| 135 |
+
"""
|
| 136 |
+
subgraph: GraphModule from sub-block.
|
| 137 |
+
iter_idx: The index of interaction.
|
| 138 |
+
len_loop_local_arguments: The number of loop local arguments in args.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
# Loop local variables. TS graph create those as inputs because their values
|
| 142 |
+
# are updated inside the loop.
|
| 143 |
+
loop_local_args = args[:len_loop_local_arguments]
|
| 144 |
+
# Global variables that are not passed in as inputs to the loop sub-blocks
|
| 145 |
+
# but are directly used. Most of time, their values are not updated, but
|
| 146 |
+
# the only exception is when there are some operations that perform inplace
|
| 147 |
+
# updates.
|
| 148 |
+
global_args = args[len_loop_local_arguments:]
|
| 149 |
+
return subgraph(*global_args, iter_idx, *loop_local_args, **kwargs)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def inplace_optimize_sym_size_div(gm: torch.fx.GraphModule):
|
| 153 |
+
def pattern(im, dim, scale):
|
| 154 |
+
sym_size_int = torch.ops.aten.sym_size.int(im, dim)
|
| 155 |
+
scalar_tensor = torch.ops.aten.scalar_tensor(sym_size_int)
|
| 156 |
+
div_scalar_mode = torch.ops.aten.div.Scalar_mode(
|
| 157 |
+
scalar_tensor, scale, rounding_mode="trunc"
|
| 158 |
+
)
|
| 159 |
+
int_tensor = torch.ops.aten.Int.Tensor(div_scalar_mode)
|
| 160 |
+
return int_tensor
|
| 161 |
+
|
| 162 |
+
def replacement(im, dim, scale):
|
| 163 |
+
sym_size_int = torch.ops.aten.sym_size.int(im, dim)
|
| 164 |
+
return sym_size_int // scale
|
| 165 |
+
|
| 166 |
+
subgraph_rewriter.replace_pattern(gm, pattern, replacement)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def is_valid_for_codegen(name):
|
| 170 |
+
if len(name) == 0:
|
| 171 |
+
raise RuntimeError("Empty argument name for codegen")
|
| 172 |
+
if name[0].isdigit():
|
| 173 |
+
return False
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def normalize_name(name: str, prefix: str = "rename") -> str:
|
| 178 |
+
name = name.replace(".", "_")
|
| 179 |
+
if is_valid_for_codegen(name):
|
| 180 |
+
return name
|
| 181 |
+
return f"{prefix}_{name}"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def ir_name_to_func_name(name: str) -> str:
|
| 185 |
+
"""prim::If -> convert_prim_If"""
|
| 186 |
+
name_list = name.split("::")
|
| 187 |
+
return "convert_" + "_".join(name_list)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def get_node_as_placeholder_or_get_attr(fx_graph, name, is_top_level_graph):
|
| 191 |
+
if is_top_level_graph:
|
| 192 |
+
return fx_graph.get_attr(name)
|
| 193 |
+
return fx_graph.placeholder(name)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
_TORCH_DTYPE_TO_ENUM = {
|
| 197 |
+
torch.uint8: 0,
|
| 198 |
+
torch.int8: 1,
|
| 199 |
+
torch.int16: 2,
|
| 200 |
+
torch.int32: 3,
|
| 201 |
+
torch.int64: 4,
|
| 202 |
+
torch.float16: 5,
|
| 203 |
+
torch.float32: 6,
|
| 204 |
+
torch.float64: 7,
|
| 205 |
+
torch.complex32: 8,
|
| 206 |
+
torch.complex64: 9,
|
| 207 |
+
torch.complex128: 10,
|
| 208 |
+
torch.bool: 11,
|
| 209 |
+
torch.qint8: 12,
|
| 210 |
+
torch.quint8: 13,
|
| 211 |
+
torch.bfloat16: 15,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
_TORCH_ENUM_TO_DTYPE = {value: key for key, value in _TORCH_DTYPE_TO_ENUM.items()}
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def get_dtype_as_int(tensor):
|
| 218 |
+
"""
|
| 219 |
+
prim::dtype has the signature "Tensor a) -> int", where it gets the dtype of
|
| 220 |
+
the tensor and returns the integer corresponding to this dtype based on the
|
| 221 |
+
enum in ScalarType.h
|
| 222 |
+
"""
|
| 223 |
+
dtype = tensor.dtype
|
| 224 |
+
if dtype not in _TORCH_DTYPE_TO_ENUM:
|
| 225 |
+
raise RuntimeError(f"Unsupported dtype {dtype}")
|
| 226 |
+
return _TORCH_DTYPE_TO_ENUM[dtype]
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# Those operators will be automatically populated to a instance method
|
| 230 |
+
# of TS2FXGraphConverter with name convert_<namespace>_<opname>().
|
| 231 |
+
# Please check __init__ for method population implementations.
|
| 232 |
+
kind_to_standard_operators: dict[str, Callable[..., Any]] = {
|
| 233 |
+
"prim::max": builtins.max,
|
| 234 |
+
"prim::min": builtins.min,
|
| 235 |
+
"prim::TupleIndex": operator.getitem,
|
| 236 |
+
"aten::__is__": operator.is_,
|
| 237 |
+
"aten::__isnot__": operator.is_not,
|
| 238 |
+
"aten::__not__": operator.not_,
|
| 239 |
+
"aten::__contains__": operator.contains,
|
| 240 |
+
"prim::dtype": get_dtype_as_int,
|
| 241 |
+
"aten::len": len,
|
| 242 |
+
# Mapping from specialized op to its symbolic counterpart.
|
| 243 |
+
# They currently do not have any other overrides.
|
| 244 |
+
"aten::numel": torch.ops.aten.sym_numel,
|
| 245 |
+
"aten::size": torch.ops.aten.sym_size,
|
| 246 |
+
"aten::storage_offset": torch.ops.aten.sym_storage_offset,
|
| 247 |
+
"aten::stride": torch.ops.aten.sym_stride,
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def get_ir_value_parent_name_and_attr_name(node):
|
| 252 |
+
irv_parent_name, irv_name = node.input().debugName(), node.output().debugName()
|
| 253 |
+
attr_name = node.s("name")
|
| 254 |
+
return irv_name, irv_parent_name, attr_name
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def construct_fqn(ir, ref_map, name_map):
|
| 258 |
+
name_list = []
|
| 259 |
+
while ir in ref_map:
|
| 260 |
+
name_list.append(name_map[ir])
|
| 261 |
+
ir = ref_map[ir]
|
| 262 |
+
return ".".join(reversed(name_list))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def get_block_to_lifted_attrs(
|
| 266 |
+
graph: torch._C.Graph,
|
| 267 |
+
) -> tuple[dict[torch._C.Block, set[str]], dict[str, str]]:
|
| 268 |
+
"""
|
| 269 |
+
Perform two passes to get a mapping of blocks to a set of FQNs of its lifted attributes.
|
| 270 |
+
When a graph has control flow, the graph will be divided into multiple blocks. We want to convert
|
| 271 |
+
each block to a graph which will be passed into torch.cond. A restriction for torch.cond is that model
|
| 272 |
+
parameters/buffers are expected to be lifted as inputs to the subgraphs. Before converting the model,
|
| 273 |
+
we will run this pass which will:
|
| 274 |
+
1. Figure out which params/buffers are used within blocks through tracing the GetAttr calls.
|
| 275 |
+
2. Process the graph bottom up to find the lifted attributes of each block by taking the union
|
| 276 |
+
of the attributes used in the current block, and the lifted attributes of all its child blocks.
|
| 277 |
+
|
| 278 |
+
Returns:
|
| 279 |
+
A mapping of blocks to a set of FQNs of its lifted attributes, and a
|
| 280 |
+
mapping of node names to the FQNs of its lifted attributes.
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
# A map from a block to its expected to be lifted arguments.
|
| 284 |
+
blocks_to_lifted_attrs: dict[torch._C.Block, set[str]] = {}
|
| 285 |
+
|
| 286 |
+
# Reference map stores the input (i.e., src) and output (i.e., dest) IR of a
|
| 287 |
+
# GetAttr node. By traversing this reference map, we can figure out the
|
| 288 |
+
# full IR aliasing pass and figure out the FQN of an attribute.
|
| 289 |
+
# E.g., %2 = GetAttr(linear)[%1] --> node_to_parent_map["%2"] = "%1"
|
| 290 |
+
node_to_parent_map: dict[str, str] = {}
|
| 291 |
+
|
| 292 |
+
# Used for reconstructing the FQN of an attribute based on the reference map.
|
| 293 |
+
# In nutshell, for each GetAttr call, GetAttr(input IR, attribute name) -> output IR
|
| 294 |
+
# This name map stores which attribute name is called for a src IR --> dest IR action.
|
| 295 |
+
# E.g., %2 = GetAttr(linear)[%1] --> node_to_attr_name["%2"] = "linear"
|
| 296 |
+
node_to_attr_name: dict[str, str] = {}
|
| 297 |
+
|
| 298 |
+
def _dfs_get_attr_dependency(entry):
|
| 299 |
+
"""
|
| 300 |
+
First DFS path to construct reference map and name map.
|
| 301 |
+
"""
|
| 302 |
+
for node in entry.nodes():
|
| 303 |
+
if node.kind() == "prim::GetAttr":
|
| 304 |
+
(
|
| 305 |
+
irv_name,
|
| 306 |
+
irv_parent_name,
|
| 307 |
+
attr_name,
|
| 308 |
+
) = get_ir_value_parent_name_and_attr_name(node)
|
| 309 |
+
node_to_parent_map[irv_name] = irv_parent_name
|
| 310 |
+
node_to_attr_name[irv_name] = attr_name
|
| 311 |
+
for block in node.blocks():
|
| 312 |
+
_dfs_get_attr_dependency(block)
|
| 313 |
+
|
| 314 |
+
def _map_blocks_to_lifted_attrs(entry):
|
| 315 |
+
"""
|
| 316 |
+
Walk the graph in a bottom-up fashion to build the expected to be
|
| 317 |
+
lifted arguments for each block.
|
| 318 |
+
"""
|
| 319 |
+
arguments: set[str] = set()
|
| 320 |
+
for node in entry.nodes():
|
| 321 |
+
for block in node.blocks():
|
| 322 |
+
# Recursively build.
|
| 323 |
+
arguments = arguments.union(_map_blocks_to_lifted_attrs(block))
|
| 324 |
+
if node.kind() == "prim::GetAttr":
|
| 325 |
+
irv_name = node.output().debugName()
|
| 326 |
+
# Skip for intermediate GetAttr, which will anyway not result a FQN.
|
| 327 |
+
# E.g., node_to_parent_name: {"%3": "%2", "%2": "%1"}
|
| 328 |
+
# node_to_attr_name: {"%3": "weight", "%2": "linear", "%1": "self"}
|
| 329 |
+
# There is only one FQN %3-->%2-->%1: self.linear.weight
|
| 330 |
+
# %2-->%1 is not a FQN: self.linear
|
| 331 |
+
if irv_name not in set(node_to_parent_map.values()):
|
| 332 |
+
arguments.add(
|
| 333 |
+
construct_fqn(irv_name, node_to_parent_map, node_to_attr_name)
|
| 334 |
+
)
|
| 335 |
+
if not isinstance(entry, torch._C.Graph): # Skip the top level.
|
| 336 |
+
blocks_to_lifted_attrs[entry] = arguments
|
| 337 |
+
return arguments
|
| 338 |
+
|
| 339 |
+
_dfs_get_attr_dependency(graph)
|
| 340 |
+
_map_blocks_to_lifted_attrs(graph)
|
| 341 |
+
|
| 342 |
+
return blocks_to_lifted_attrs, node_to_attr_name
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def get_attribute_fqn_from_ts_node(
|
| 346 |
+
name_to_attribute_fqn: dict[str, str], node: torch._C.Node
|
| 347 |
+
) -> str:
|
| 348 |
+
def get_attr(name: str):
|
| 349 |
+
if name in name_to_attribute_fqn:
|
| 350 |
+
return name_to_attribute_fqn[name]
|
| 351 |
+
else:
|
| 352 |
+
raise ValueError(f"Attribute {name} not found")
|
| 353 |
+
|
| 354 |
+
if node.kind() == "prim::SetAttr":
|
| 355 |
+
input_name = next(node.inputs()).debugName()
|
| 356 |
+
elif node.kind() == "prim::GetAttr":
|
| 357 |
+
input_name = node.input().debugName()
|
| 358 |
+
else:
|
| 359 |
+
raise RuntimeError(
|
| 360 |
+
f"Unexpected node kind when getting attribute fqn. node: {node} "
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
attr_name = node.s("name")
|
| 364 |
+
root_attr_name = get_attr(input_name)
|
| 365 |
+
attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name
|
| 366 |
+
|
| 367 |
+
return attr_fqn
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def get_op_overload(node: torch._C.Node):
|
| 371 |
+
schema_str = node.schema()
|
| 372 |
+
assert schema_str != "(no schema)", f"got empty schema for {node}"
|
| 373 |
+
schema: torch._C.FunctionSchema = torch._C.parse_schema(schema_str)
|
| 374 |
+
ns, op_name = str(schema.name).split("::")
|
| 375 |
+
override = schema.overload_name
|
| 376 |
+
|
| 377 |
+
try:
|
| 378 |
+
op_overload_mod = getattr(torch.ops, ns)
|
| 379 |
+
op_overload_packet = getattr(op_overload_mod, op_name)
|
| 380 |
+
if override:
|
| 381 |
+
op_overload = getattr(op_overload_packet, override)
|
| 382 |
+
else:
|
| 383 |
+
op_overload = op_overload_packet.default
|
| 384 |
+
except Exception as e:
|
| 385 |
+
raise RuntimeError(
|
| 386 |
+
f"Unable to find operator {node.kind()} with schema {node.schema()}"
|
| 387 |
+
) from e
|
| 388 |
+
|
| 389 |
+
return op_overload
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class TS2FXGraphConverter:
|
| 393 |
+
def __init__(
|
| 394 |
+
self,
|
| 395 |
+
ts_graph: Union[torch._C.Graph, torch._C.Block],
|
| 396 |
+
name_to_param: dict[str, torch.Tensor],
|
| 397 |
+
name_to_buffer: dict[str, torch.Tensor],
|
| 398 |
+
blocks_to_lifted_attrs: dict[torch._C.Block, set[str]],
|
| 399 |
+
name_to_non_tensor_attribute: dict[str, Any],
|
| 400 |
+
name_to_constant: dict[str, Any],
|
| 401 |
+
name_to_attribute_fqn: dict[str, str],
|
| 402 |
+
):
|
| 403 |
+
self.ts_graph = ts_graph
|
| 404 |
+
# Mapping of parameter FQN to actual parameter value
|
| 405 |
+
self.name_to_param = name_to_param
|
| 406 |
+
# Mapping of buffer FQN to actual buffer value
|
| 407 |
+
self.name_to_buffer = name_to_buffer
|
| 408 |
+
|
| 409 |
+
self.fx_graph: torch.fx.Graph = torch.fx.Graph()
|
| 410 |
+
self.input_specs: list[InputSpec] = []
|
| 411 |
+
self.output_specs: list[OutputSpec] = []
|
| 412 |
+
|
| 413 |
+
# Mapping of TS node name to converted FX node
|
| 414 |
+
self.name_to_node: dict[
|
| 415 |
+
str, Union[torch.fx.Node, list[torch.fx.Node], dict[Any, torch.fx.Node]]
|
| 416 |
+
] = {}
|
| 417 |
+
# Mapping of TS node name to constant value (int, str, TorchBind obj,
|
| 418 |
+
# tensor constants ...)
|
| 419 |
+
self.name_to_constant: dict[str, Any] = name_to_constant
|
| 420 |
+
|
| 421 |
+
# Mapping from torchscript node output name to attribute fully qualified name
|
| 422 |
+
self.name_to_attribute_fqn: dict[str, str] = name_to_attribute_fqn
|
| 423 |
+
|
| 424 |
+
# Mapping from fully qualified name to real values or a fx graph node
|
| 425 |
+
# During convert, this represents the current value of a non-tensor attribute
|
| 426 |
+
# One use case is:
|
| 427 |
+
# def forward(self, x):
|
| 428 |
+
# c1 = self.count
|
| 429 |
+
# self.count += 1
|
| 430 |
+
# c2 = self.count
|
| 431 |
+
# return x + c1 + c2
|
| 432 |
+
self.name_to_non_tensor_attribute_node: dict[str, Any] = {}
|
| 433 |
+
|
| 434 |
+
# Mapping from fully qualified name to initial real values inputs
|
| 435 |
+
# We separate it from self.name_to_non_tensor_attribute_node since
|
| 436 |
+
# we need initial real value input when we construct fx.GraphModule
|
| 437 |
+
self.name_to_non_tensor_attribute: dict[str, Any] = name_to_non_tensor_attribute
|
| 438 |
+
|
| 439 |
+
self.subgraphs: dict[str, torch.fx.GraphModule] = {}
|
| 440 |
+
|
| 441 |
+
# Mapping of block to list of attributes that need to be lifted for each
|
| 442 |
+
# block
|
| 443 |
+
self.blocks_to_lifted_attrs = blocks_to_lifted_attrs
|
| 444 |
+
|
| 445 |
+
# Populate methods for the standard operators.
|
| 446 |
+
for k in kind_to_standard_operators:
|
| 447 |
+
handler_func_name = ir_name_to_func_name(k)
|
| 448 |
+
# Create an indirect function call:
|
| 449 |
+
# convert_<namespace>_<opname> --> lambda node: _convert_standard_operator(node)
|
| 450 |
+
setattr(
|
| 451 |
+
self,
|
| 452 |
+
handler_func_name,
|
| 453 |
+
lambda node: self._convert_standard_operators(node),
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# This stores a list of return results that do not appear in the original TS
|
| 457 |
+
# graph's outputs. The reason we maintain this is because some operations in the sub-block
|
| 458 |
+
# might have inplace updates to the variable defined in the parent fx graph. After
|
| 459 |
+
# the execution of that sub-block, the variable defined in the parent fx graph also
|
| 460 |
+
# needs to be updated.
|
| 461 |
+
self.name_update_from_subblock_to_parent: set[str] = set()
|
| 462 |
+
|
| 463 |
+
def _is_get_attr_node(self, fqn):
|
| 464 |
+
return (
|
| 465 |
+
fqn in self.name_to_buffer
|
| 466 |
+
or fqn in self.name_to_param
|
| 467 |
+
or (
|
| 468 |
+
fqn in self.name_to_constant
|
| 469 |
+
and isinstance(self.name_to_constant[fqn], torch.ScriptObject)
|
| 470 |
+
)
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
def _convert_block_to_subgraph(self, node: torch._C.Node, arguments: list[str]):
|
| 474 |
+
subgraph_nodes, subgraph_converters = [], []
|
| 475 |
+
for block in node.blocks():
|
| 476 |
+
subgraph_converter = TS2FXGraphConverter(
|
| 477 |
+
block,
|
| 478 |
+
self.name_to_param,
|
| 479 |
+
self.name_to_buffer,
|
| 480 |
+
self.blocks_to_lifted_attrs,
|
| 481 |
+
{},
|
| 482 |
+
self.name_to_constant,
|
| 483 |
+
self.name_to_attribute_fqn,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
for block_arg in arguments:
|
| 487 |
+
normalized_block_arg_name = normalize_name(block_arg)
|
| 488 |
+
placeholder_node = subgraph_converter.fx_graph.placeholder(
|
| 489 |
+
normalized_block_arg_name
|
| 490 |
+
)
|
| 491 |
+
subgraph_converter.name_to_node[block_arg] = placeholder_node
|
| 492 |
+
|
| 493 |
+
subgraph = subgraph_converter.convert()
|
| 494 |
+
subgraph_name = self.add_subgraph(subgraph)
|
| 495 |
+
subgraph_nodes.append(self.fx_graph.get_attr(subgraph_name))
|
| 496 |
+
subgraph_converters.append(subgraph_converter)
|
| 497 |
+
return subgraph_nodes, subgraph_converters
|
| 498 |
+
|
| 499 |
+
def _identify_inputs_as_arguments(self, entry):
|
| 500 |
+
"""
|
| 501 |
+
Identify inputs from the innermost sub-block. This is needed
|
| 502 |
+
for nested sub-blocks when the input is hidden in the nested sub-block.
|
| 503 |
+
E.g., example IR of input is hidden in the nested sub-block.
|
| 504 |
+
Graph[x.1]
|
| 505 |
+
%1 = ...
|
| 506 |
+
Block[]
|
| 507 |
+
Block[x.1]
|
| 508 |
+
%2 = x.1 ...
|
| 509 |
+
"""
|
| 510 |
+
arguments: set[str] = set()
|
| 511 |
+
for block in entry.blocks():
|
| 512 |
+
for block_node in block.nodes():
|
| 513 |
+
for block_node_in in block_node.inputs():
|
| 514 |
+
if (
|
| 515 |
+
block_node_in.debugName() in self.name_to_node
|
| 516 |
+
and block_node_in.debugName() not in self.name_to_attribute_fqn
|
| 517 |
+
):
|
| 518 |
+
arguments.add(block_node_in.debugName())
|
| 519 |
+
arguments = arguments.union(
|
| 520 |
+
self._identify_inputs_as_arguments(block_node)
|
| 521 |
+
)
|
| 522 |
+
return arguments
|
| 523 |
+
|
| 524 |
+
def is_top_level_graph(self):
|
| 525 |
+
return isinstance(self.ts_graph, torch._C.Graph)
|
| 526 |
+
|
| 527 |
+
def add_subgraph(self, subgraph) -> str:
|
| 528 |
+
name = f"subgraph_{len(self.subgraphs)}"
|
| 529 |
+
self.subgraphs[name] = subgraph
|
| 530 |
+
return name
|
| 531 |
+
|
| 532 |
+
def get_args_kwargs(self, node: torch._C.Node, schema):
|
| 533 |
+
args = []
|
| 534 |
+
kwargs = {}
|
| 535 |
+
for input, schema_arg in zip(node.inputs(), schema.arguments):
|
| 536 |
+
if schema_arg.kwarg_only:
|
| 537 |
+
kwargs[schema_arg.name] = self.get_fx_value_by_ir_value(input)
|
| 538 |
+
else:
|
| 539 |
+
args.append(self.get_fx_value_by_ir_value(input))
|
| 540 |
+
|
| 541 |
+
return tuple(args), kwargs
|
| 542 |
+
|
| 543 |
+
def get_fx_value_by_ir_value(self, value: torch._C.Value):
|
| 544 |
+
value_name = value.debugName()
|
| 545 |
+
|
| 546 |
+
if value_name in self.name_to_node:
|
| 547 |
+
input_node = self.name_to_node[value_name]
|
| 548 |
+
return input_node
|
| 549 |
+
elif value_name in self.name_to_constant:
|
| 550 |
+
if isinstance(self.name_to_constant[value_name], torch.ScriptObject):
|
| 551 |
+
return self.fx_graph.get_attr(value_name)
|
| 552 |
+
return self.name_to_constant[value_name]
|
| 553 |
+
elif value_name in self.name_to_attribute_fqn:
|
| 554 |
+
return self.get_fx_value_by_fqn(self.name_to_attribute_fqn[value_name])
|
| 555 |
+
else:
|
| 556 |
+
raise ValueError(f"Input {value_name} not found")
|
| 557 |
+
|
| 558 |
+
def get_fx_value_by_fqn(self, name):
|
| 559 |
+
if name in self.name_to_node:
|
| 560 |
+
fx_node = self.name_to_node[name]
|
| 561 |
+
elif name in self.name_to_constant:
|
| 562 |
+
fx_node = self.name_to_constant[name]
|
| 563 |
+
elif name in self.name_to_non_tensor_attribute_node:
|
| 564 |
+
fx_node = self.name_to_non_tensor_attribute_node[name]
|
| 565 |
+
elif name in self.name_to_non_tensor_attribute:
|
| 566 |
+
fx_node = self.name_to_non_tensor_attribute[name]
|
| 567 |
+
else:
|
| 568 |
+
raise ValueError(f"Attribute {name} not found")
|
| 569 |
+
return fx_node
|
| 570 |
+
|
| 571 |
+
def convert(self) -> torch.fx.GraphModule:
|
| 572 |
+
self.convert_graph_inputs()
|
| 573 |
+
|
| 574 |
+
for node in self.ts_graph.nodes():
|
| 575 |
+
self.convert_node(node)
|
| 576 |
+
|
| 577 |
+
self.convert_graph_outputs()
|
| 578 |
+
|
| 579 |
+
# Pass parameter and buffer to the root for lookup.
|
| 580 |
+
gm = torch.fx.GraphModule(
|
| 581 |
+
{
|
| 582 |
+
**self.subgraphs,
|
| 583 |
+
**self.name_to_param,
|
| 584 |
+
**self.name_to_buffer,
|
| 585 |
+
**self.name_to_non_tensor_attribute,
|
| 586 |
+
**self.name_to_constant,
|
| 587 |
+
},
|
| 588 |
+
self.fx_graph,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
inplace_optimize_sym_size_div(gm)
|
| 592 |
+
|
| 593 |
+
gm.graph.lint()
|
| 594 |
+
|
| 595 |
+
return gm
|
| 596 |
+
|
| 597 |
+
def convert_graph_inputs(self):
|
| 598 |
+
for graph_input in self.ts_graph.inputs():
|
| 599 |
+
name = graph_input.debugName()
|
| 600 |
+
|
| 601 |
+
if name in self.name_to_param:
|
| 602 |
+
normalized_name = normalize_name(name)
|
| 603 |
+
self.input_specs.append(
|
| 604 |
+
InputSpec(
|
| 605 |
+
InputKind.PARAMETER,
|
| 606 |
+
arg=TensorArgument(name=normalized_name),
|
| 607 |
+
target=name,
|
| 608 |
+
)
|
| 609 |
+
)
|
| 610 |
+
fx_node = get_node_as_placeholder_or_get_attr(
|
| 611 |
+
self.fx_graph, name, self.is_top_level_graph()
|
| 612 |
+
)
|
| 613 |
+
elif name in self.name_to_buffer:
|
| 614 |
+
normalized_name = normalize_name(name)
|
| 615 |
+
self.input_specs.append(
|
| 616 |
+
InputSpec(
|
| 617 |
+
InputKind.BUFFER,
|
| 618 |
+
arg=TensorArgument(name=normalized_name),
|
| 619 |
+
target=name,
|
| 620 |
+
persistent=True,
|
| 621 |
+
)
|
| 622 |
+
)
|
| 623 |
+
fx_node = get_node_as_placeholder_or_get_attr(
|
| 624 |
+
self.fx_graph, name, self.is_top_level_graph()
|
| 625 |
+
)
|
| 626 |
+
elif name in self.name_to_constant:
|
| 627 |
+
assert isinstance(self.name_to_constant[name], torch.ScriptObject), (
|
| 628 |
+
"Input conversion only handles ScriptObject"
|
| 629 |
+
)
|
| 630 |
+
normalized_name = normalize_name(name)
|
| 631 |
+
self.input_specs.append(
|
| 632 |
+
InputSpec(
|
| 633 |
+
InputKind.CUSTOM_OBJ,
|
| 634 |
+
arg=CustomObjArgument(
|
| 635 |
+
name=normalized_name, class_fqn=normalized_name
|
| 636 |
+
),
|
| 637 |
+
target=name,
|
| 638 |
+
persistent=False,
|
| 639 |
+
)
|
| 640 |
+
)
|
| 641 |
+
fx_node = get_node_as_placeholder_or_get_attr(
|
| 642 |
+
self.fx_graph, name, self.is_top_level_graph()
|
| 643 |
+
)
|
| 644 |
+
elif isinstance(graph_input.type(), torch.ClassType):
|
| 645 |
+
# Directly skip inputs that are ScriptObject but not used in the graph.
|
| 646 |
+
continue
|
| 647 |
+
else:
|
| 648 |
+
normalized_name = normalize_name(name, prefix="input")
|
| 649 |
+
self.input_specs.append(
|
| 650 |
+
InputSpec(
|
| 651 |
+
InputKind.USER_INPUT,
|
| 652 |
+
arg=TensorArgument(name=normalized_name),
|
| 653 |
+
target=name,
|
| 654 |
+
)
|
| 655 |
+
)
|
| 656 |
+
fx_node = self.fx_graph.placeholder(normalized_name)
|
| 657 |
+
|
| 658 |
+
self.name_to_node[name] = fx_node
|
| 659 |
+
|
| 660 |
+
def convert_aten_Float(self, node: torch._C.Node):
|
| 661 |
+
def to_float_tensor(t):
|
| 662 |
+
return t.to(dtype=torch.float).item()
|
| 663 |
+
|
| 664 |
+
inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] # noqa: C416
|
| 665 |
+
fx_node = self.fx_graph.call_function(
|
| 666 |
+
to_float_tensor,
|
| 667 |
+
tuple(inp_list),
|
| 668 |
+
)
|
| 669 |
+
self.name_to_node[node.output().debugName()] = fx_node
|
| 670 |
+
|
| 671 |
+
def convert_aten_tensor(self, node: torch._C.Node):
|
| 672 |
+
"""aten::tensor creates a constant tensor ad-hoc --> GetAttr"""
|
| 673 |
+
args, kwargs = self.get_args_kwargs(node, torch.ops.aten.tensor.default._schema)
|
| 674 |
+
|
| 675 |
+
for k in kwargs:
|
| 676 |
+
if k == "requires_grad":
|
| 677 |
+
kwargs[k] = bool(kwargs[k]) # 0 -> False, 1 -> True
|
| 678 |
+
|
| 679 |
+
to_tensor = (
|
| 680 |
+
torch.tensor
|
| 681 |
+
if all(isinstance(a, int) for a in args)
|
| 682 |
+
else torch._refs.tensor
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
def target(*args, **kwargs):
|
| 686 |
+
if "dtype" in kwargs and kwargs["dtype"] is not None:
|
| 687 |
+
kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]]
|
| 688 |
+
return to_tensor(*args, **kwargs)
|
| 689 |
+
|
| 690 |
+
# def to_dynamic_tensor(*args, **kwargs):
|
| 691 |
+
# if "dtype" in kwargs and kwargs["dtype"] is not None:
|
| 692 |
+
# kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]]
|
| 693 |
+
# return torch._refs.tensor(*args, **kwargs)
|
| 694 |
+
|
| 695 |
+
output_name = node.output().debugName()
|
| 696 |
+
fx_node = self.fx_graph.call_function(target, args, kwargs)
|
| 697 |
+
self.name_to_node[output_name] = fx_node
|
| 698 |
+
|
| 699 |
+
def convert_aten_append(self, node: torch._C.Node):
|
| 700 |
+
# special handle python list append: "aten::append.t(t[](a!) self, t(c -> *) el) -> t[](a!)"
|
| 701 |
+
|
| 702 |
+
# inplace append to the list!! This is kinda crazy, as we are inplace mutating the list
|
| 703 |
+
# This makes the converter "non-functional", and the result depends on the order of the nodes being converter
|
| 704 |
+
# In a sense, the converter now becomes an stateful interpreter
|
| 705 |
+
warnings.warn(
|
| 706 |
+
"Converting aten::append.t, which is a inplace mutation of the list. "
|
| 707 |
+
"This makes the converter non-functional: the result depends on the order of the append nodes being converter!",
|
| 708 |
+
stacklevel=2,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
args = tuple(self.get_fx_value_by_ir_value(inp) for inp in node.inputs())
|
| 712 |
+
fx_node = self.fx_graph.call_function(list_append, args)
|
| 713 |
+
self.name_to_node[node.output().debugName()] = fx_node
|
| 714 |
+
|
| 715 |
+
# inplace mutate arg[0], which is the python list
|
| 716 |
+
self.name_to_node[node.inputsAt(0).debugName()] = fx_node
|
| 717 |
+
|
| 718 |
+
# Variables that need to be updated to parent module.
|
| 719 |
+
if not self.is_top_level_graph() and args[0].op == "placeholder":
|
| 720 |
+
self.name_update_from_subblock_to_parent.add(node.inputsAt(0).debugName())
|
| 721 |
+
|
| 722 |
+
def convert_prim_Constant(self, node: torch._C.Node):
|
| 723 |
+
name = node.output().debugName()
|
| 724 |
+
|
| 725 |
+
value: Any = None
|
| 726 |
+
if node.hasAttribute("value"):
|
| 727 |
+
constant_kind = node.kindOf("value")
|
| 728 |
+
if constant_kind == "i":
|
| 729 |
+
value = node.i("value")
|
| 730 |
+
elif constant_kind == "f":
|
| 731 |
+
value = node.f("value")
|
| 732 |
+
elif constant_kind == "s":
|
| 733 |
+
value = node.s("value")
|
| 734 |
+
elif constant_kind == "t":
|
| 735 |
+
alias_name = (
|
| 736 |
+
f"lifted_tensor_{name}" # Follow naming convention from EP tracing.
|
| 737 |
+
)
|
| 738 |
+
fx_node = self.fx_graph.get_attr(alias_name)
|
| 739 |
+
self.name_to_node[name] = fx_node
|
| 740 |
+
name, value = alias_name, node.t("value")
|
| 741 |
+
elif constant_kind == "ival":
|
| 742 |
+
value = node.ival("value")
|
| 743 |
+
else:
|
| 744 |
+
raise ValueError(f"Unsupported constant type: {node.kindOf('value')}")
|
| 745 |
+
else:
|
| 746 |
+
value = None
|
| 747 |
+
|
| 748 |
+
self.name_to_constant[name] = value
|
| 749 |
+
|
| 750 |
+
def convert_prim_CallMethod(self, node: torch._C.Node):
|
| 751 |
+
inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] # noqa: C416
|
| 752 |
+
fx_node = self.fx_graph.call_method(
|
| 753 |
+
node.s("name"),
|
| 754 |
+
tuple(inp_list),
|
| 755 |
+
)
|
| 756 |
+
self.name_to_node[node.output().debugName()] = fx_node
|
| 757 |
+
|
| 758 |
+
def convert_prim_device(self, node: torch._C.Node):
|
| 759 |
+
input_type = node.input().type()
|
| 760 |
+
if input_type.isSubtypeOf(torch._C.TensorType.get()):
|
| 761 |
+
device = input_type.device() # type: ignore[attr-defined]
|
| 762 |
+
output_name = node.output().debugName()
|
| 763 |
+
self.name_to_constant[output_name] = device
|
| 764 |
+
else:
|
| 765 |
+
raise ValueError(f"Unsupported JitType ({input_type}) when get device")
|
| 766 |
+
|
| 767 |
+
def convert_prim_GetAttr(self, node: torch._C.Node):
|
| 768 |
+
# Build fully qualified name
|
| 769 |
+
attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node)
|
| 770 |
+
output_name = node.output().debugName()
|
| 771 |
+
self.name_to_attribute_fqn[output_name] = attr_fqn
|
| 772 |
+
|
| 773 |
+
if self.is_top_level_graph():
|
| 774 |
+
if self._is_get_attr_node(attr_fqn):
|
| 775 |
+
# We insert a get_attr node due to two reasons.
|
| 776 |
+
# First, ts graph does not lift tensor constants as input nodes. So
|
| 777 |
+
# tensor constants may be ignored by in convert_graph_inputs().
|
| 778 |
+
# Second, attr_fqn may have been written to via SetAttr. Two
|
| 779 |
+
# GetAttr may give different values.
|
| 780 |
+
self.name_to_node[output_name] = self.fx_graph.get_attr(attr_fqn)
|
| 781 |
+
else:
|
| 782 |
+
if attr_fqn not in self.name_to_non_tensor_attribute_node:
|
| 783 |
+
self.name_to_non_tensor_attribute_node[attr_fqn] = (
|
| 784 |
+
self.name_to_non_tensor_attribute[attr_fqn]
|
| 785 |
+
)
|
| 786 |
+
self.name_to_node[output_name] = self.name_to_non_tensor_attribute_node[
|
| 787 |
+
attr_fqn
|
| 788 |
+
]
|
| 789 |
+
else:
|
| 790 |
+
# Special support for if blocks which do not allow SetAttr TorchScript
|
| 791 |
+
# node and get_attr FX Graph Node.
|
| 792 |
+
if self._is_get_attr_node(attr_fqn):
|
| 793 |
+
self.name_to_node[output_name] = self.name_to_node[attr_fqn]
|
| 794 |
+
|
| 795 |
+
def convert_prim_SetAttr(self, node: torch._C.Node):
|
| 796 |
+
attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node)
|
| 797 |
+
attr_value = tuple(node.inputs())[1]
|
| 798 |
+
ts_graph_tensor_input = self.get_fx_value_by_ir_value(attr_value)
|
| 799 |
+
if self._is_get_attr_node(attr_fqn):
|
| 800 |
+
fx_attr_node = self.fx_graph.get_attr(attr_fqn)
|
| 801 |
+
self.fx_graph.call_function(
|
| 802 |
+
torch.Tensor.copy_, (fx_attr_node, ts_graph_tensor_input)
|
| 803 |
+
)
|
| 804 |
+
else:
|
| 805 |
+
self.name_to_non_tensor_attribute_node[attr_fqn] = ts_graph_tensor_input
|
| 806 |
+
|
| 807 |
+
def convert_call_function_op(self, node: torch._C.Node):
|
| 808 |
+
target = get_op_overload(node)
|
| 809 |
+
|
| 810 |
+
args, kwargs = self.get_args_kwargs(node, target._schema)
|
| 811 |
+
|
| 812 |
+
fx_node = self.fx_graph.call_function(target, args, kwargs)
|
| 813 |
+
|
| 814 |
+
# TODO: convert sourceRange() into stack_trace
|
| 815 |
+
# fx_node.meta["stack_trace"] = node.sourceRange()
|
| 816 |
+
|
| 817 |
+
if node.outputsSize() == 1:
|
| 818 |
+
output_name = node.output().debugName()
|
| 819 |
+
self.name_to_node[output_name] = fx_node
|
| 820 |
+
else:
|
| 821 |
+
for i, outp in enumerate(node.outputs()):
|
| 822 |
+
output_name = outp.debugName()
|
| 823 |
+
next_fx_node = self.fx_graph.call_function(
|
| 824 |
+
operator.getitem, (fx_node, i)
|
| 825 |
+
)
|
| 826 |
+
self.name_to_node[output_name] = next_fx_node
|
| 827 |
+
|
| 828 |
+
def convert_prim_TupleConstruct(self, node: torch._C.Node):
|
| 829 |
+
self._convert_prim_iterator(node)
|
| 830 |
+
|
| 831 |
+
def convert_prim_ListConstruct(self, node: torch._C.Node):
|
| 832 |
+
self._convert_prim_iterator(node)
|
| 833 |
+
|
| 834 |
+
def _convert_prim_iterator(self, node: torch._C.Node):
|
| 835 |
+
output_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()]
|
| 836 |
+
|
| 837 |
+
output_name = node.output().debugName()
|
| 838 |
+
self.name_to_node[output_name] = output_list
|
| 839 |
+
|
| 840 |
+
def convert_prim_DictConstruct(self, node: torch._C.Node):
|
| 841 |
+
output_dict = {}
|
| 842 |
+
k, v = None, None
|
| 843 |
+
for i, inp in enumerate(node.inputs()):
|
| 844 |
+
# We assume key value are stored in pair in the DictConstruct.
|
| 845 |
+
# The first element is the key and the following is the value.
|
| 846 |
+
if i % 2 == 0:
|
| 847 |
+
k = self.get_fx_value_by_ir_value(inp)
|
| 848 |
+
else:
|
| 849 |
+
v = self.get_fx_value_by_ir_value(inp)
|
| 850 |
+
assert k is not None and v is not None, (
|
| 851 |
+
"DictConstruct has an empty key value pair."
|
| 852 |
+
)
|
| 853 |
+
output_dict[k] = v
|
| 854 |
+
k, v = None, None
|
| 855 |
+
|
| 856 |
+
assert k is None and v is None, (
|
| 857 |
+
"DictConstruct has an odd number of elements (violating our assumption)."
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
output_name = node.output().debugName()
|
| 861 |
+
self.name_to_node[output_name] = output_dict
|
| 862 |
+
|
| 863 |
+
def convert_prim_ListUnpack(self, node: torch._C.Node):
|
| 864 |
+
self._convert_prim_unpack_iterator(node)
|
| 865 |
+
|
| 866 |
+
def convert_prim_TupleUnpack(self, node: torch._C.Node):
|
| 867 |
+
self._convert_prim_unpack_iterator(node)
|
| 868 |
+
|
| 869 |
+
def _convert_prim_unpack_iterator(self, node: torch._C.Node):
|
| 870 |
+
# Single input and multiple outputs for unpacking.
|
| 871 |
+
for i, outp in enumerate(node.outputs()):
|
| 872 |
+
outp_name = outp.debugName()
|
| 873 |
+
inp = self.get_fx_value_by_ir_value(node.input())
|
| 874 |
+
fx_node = self.fx_graph.call_function(operator.getitem, (inp, i))
|
| 875 |
+
self.name_to_node[outp_name] = fx_node
|
| 876 |
+
|
| 877 |
+
def convert_aten_Int(self, node: torch._C.Node):
|
| 878 |
+
# converts aten::Int as aten._to_copy + aten::_local_scalar_dense
|
| 879 |
+
target = torch.ops.aten._to_copy.default
|
| 880 |
+
args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs())
|
| 881 |
+
to_copy_node = self.fx_graph.call_function(target, args, {"dtype": torch.int32})
|
| 882 |
+
|
| 883 |
+
fx_node = self.fx_graph.call_function(
|
| 884 |
+
torch.ops.aten._local_scalar_dense.default, (to_copy_node,)
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
# TODO: convert sourceRange() into stack_trace
|
| 888 |
+
# fx_node.meta["stack_trace"] = node.sourceRange()
|
| 889 |
+
|
| 890 |
+
output_name = node.output().debugName()
|
| 891 |
+
self.name_to_node[output_name] = fx_node
|
| 892 |
+
|
| 893 |
+
def convert_prim_NumToTensor(self, node: torch._C.Node):
|
| 894 |
+
# Converts prim::NumToTensor as aten.scalar_tensor.
|
| 895 |
+
# prim::NumToTensor IRs are currently triggered by:
|
| 896 |
+
# .size() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L950
|
| 897 |
+
# .numel() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L971
|
| 898 |
+
# For both of those APIs, torch.jit.trace implicitly sets the output tensor type
|
| 899 |
+
# to be LongTensor.
|
| 900 |
+
target = torch.ops.aten.scalar_tensor
|
| 901 |
+
args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs())
|
| 902 |
+
|
| 903 |
+
fx_node = self.fx_graph.call_function(target, args, {"dtype": torch.long})
|
| 904 |
+
output_name = node.output().debugName()
|
| 905 |
+
self.name_to_node[output_name] = fx_node
|
| 906 |
+
|
| 907 |
+
def convert_prim_CreateObject(self, node: torch._C.Node):
|
| 908 |
+
output_name = node.output().debugName()
|
| 909 |
+
self.name_to_attribute_fqn[output_name] = ""
|
| 910 |
+
|
| 911 |
+
def convert_aten__convolution(self, node: torch._C.Node):
|
| 912 |
+
# converts aten::_convolution as aten.convolution, since aten::_convolution
|
| 913 |
+
# doesn't have a meta function
|
| 914 |
+
target = torch.ops.aten.convolution.default
|
| 915 |
+
args, kwargs = self.get_args_kwargs(node, target._schema)
|
| 916 |
+
|
| 917 |
+
fx_node = self.fx_graph.call_function(target, args, kwargs)
|
| 918 |
+
|
| 919 |
+
output_name = node.output().debugName()
|
| 920 |
+
self.name_to_node[output_name] = fx_node
|
| 921 |
+
|
| 922 |
+
def convert_aten_div(self, node: torch._C.Node):
|
| 923 |
+
target = get_op_overload(node)
|
| 924 |
+
schema = target._schema
|
| 925 |
+
|
| 926 |
+
args, kwargs = self.get_args_kwargs(node, schema)
|
| 927 |
+
|
| 928 |
+
# converts aten::div.Tensor_mode(x, tensor_constant)
|
| 929 |
+
# as aten.div.Scalar_mode(x, tensor_constant.item())
|
| 930 |
+
if schema.overload_name == "Tensor_mode":
|
| 931 |
+
arg1_name = args[1].name
|
| 932 |
+
if arg1_name in self.name_to_constant and isinstance(
|
| 933 |
+
self.name_to_constant[arg1_name], torch.Tensor
|
| 934 |
+
):
|
| 935 |
+
tensor_constant = self.name_to_constant[arg1_name]
|
| 936 |
+
if tensor_constant.numel() == 1:
|
| 937 |
+
updated_args = list(args)
|
| 938 |
+
updated_args[1] = self.name_to_constant[arg1_name].item()
|
| 939 |
+
|
| 940 |
+
fx_node = self.fx_graph.call_function(
|
| 941 |
+
torch.ops.aten.div.Scalar_mode,
|
| 942 |
+
tuple(updated_args),
|
| 943 |
+
kwargs,
|
| 944 |
+
)
|
| 945 |
+
|
| 946 |
+
# TODO: convert sourceRange() into stack_trace
|
| 947 |
+
# fx_node.meta["stack_trace"] = node.sourceRange()
|
| 948 |
+
|
| 949 |
+
output_name = node.output().debugName()
|
| 950 |
+
self.name_to_node[output_name] = fx_node
|
| 951 |
+
return
|
| 952 |
+
|
| 953 |
+
self.convert_call_function_op(node)
|
| 954 |
+
|
| 955 |
+
def convert_aten___getitem__(self, node: torch._C.Node):
|
| 956 |
+
input_container, index = tuple(
|
| 957 |
+
self.get_fx_value_by_ir_value(input) for input in node.inputs()
|
| 958 |
+
)
|
| 959 |
+
fx_node = self.fx_graph.call_function(
|
| 960 |
+
operator.getitem, (input_container, index)
|
| 961 |
+
)
|
| 962 |
+
output_name = node.output().debugName()
|
| 963 |
+
self.name_to_node[output_name] = fx_node
|
| 964 |
+
|
| 965 |
+
def convert_aten_to(self, node: torch._C.Node):
|
| 966 |
+
target = get_op_overload(node)
|
| 967 |
+
args, _kwargs = self.get_args_kwargs(node, target._schema)
|
| 968 |
+
|
| 969 |
+
# special handle aten.to.dtype and aten.to.prim_dtype followed by inplace_mutation_op
|
| 970 |
+
# coz aten.to + inplace_mutation_op pattern would trigger
|
| 971 |
+
# "cannot mutate tensors with frozen storage" functionalization error.
|
| 972 |
+
# To work around the issue, we override the copy to be True, so that the output
|
| 973 |
+
# is for sure not an alias of input
|
| 974 |
+
if target is torch.ops.aten.to.dtype or target is torch.ops.aten.to.prim_dtype:
|
| 975 |
+
user_nodes = [use.user for use in node.output().uses()]
|
| 976 |
+
user_targets = [
|
| 977 |
+
get_op_overload(user_node)
|
| 978 |
+
for user_node in user_nodes
|
| 979 |
+
if user_node.schema() != "(no schema)"
|
| 980 |
+
]
|
| 981 |
+
has_mutable_target = any(
|
| 982 |
+
target._schema.is_mutable for target in user_targets
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
if has_mutable_target:
|
| 986 |
+
assert len(args) >= 4
|
| 987 |
+
new_args = list(args)
|
| 988 |
+
new_args[3] = True # copy, override to True
|
| 989 |
+
fx_node = self.fx_graph.call_function(
|
| 990 |
+
torch.ops.aten.to.dtype, tuple(new_args)
|
| 991 |
+
)
|
| 992 |
+
# temp hack to work around the issue https://github.com/pytorch/pytorch/issues/131679
|
| 993 |
+
# When this issue is fixed, the clone node would be no longer needed
|
| 994 |
+
clone_node = self.fx_graph.call_function(
|
| 995 |
+
torch.ops.aten.clone.default, (fx_node,)
|
| 996 |
+
)
|
| 997 |
+
output_name = node.output().debugName()
|
| 998 |
+
self.name_to_node[output_name] = clone_node
|
| 999 |
+
return
|
| 1000 |
+
|
| 1001 |
+
self.convert_call_function_op(node)
|
| 1002 |
+
|
| 1003 |
+
def convert_aten_add(self, node: torch._C.Node):
|
| 1004 |
+
if node.schema() == "(no schema)":
|
| 1005 |
+
if isinstance(node.inputsAt(0).type(), torch.ListType) and isinstance(
|
| 1006 |
+
node.inputsAt(1).type(), torch.ListType
|
| 1007 |
+
):
|
| 1008 |
+
target = torch.ops.aten.add.t
|
| 1009 |
+
else:
|
| 1010 |
+
raise RuntimeError(f"unable to determined the target for {node}")
|
| 1011 |
+
else:
|
| 1012 |
+
target = get_op_overload(node)
|
| 1013 |
+
|
| 1014 |
+
if target is torch.ops.aten.add.t:
|
| 1015 |
+
# special handle python list/tuple add: "aten::add.t(t[] a, t[] b) -> t[]" for
|
| 1016 |
+
# RuntimeError: aten::add() Expected a value of type 'List[t]' for argument 'a' but instead found type 'immutable_list'.
|
| 1017 |
+
args, _kwargs = self.get_args_kwargs(node, target._schema)
|
| 1018 |
+
output_name = node.output().debugName()
|
| 1019 |
+
self.name_to_node[output_name] = self.fx_graph.call_function(list_add, args)
|
| 1020 |
+
else:
|
| 1021 |
+
self.convert_call_function_op(node)
|
| 1022 |
+
|
| 1023 |
+
def _check_prim_loop_support(self, node):
|
| 1024 |
+
inputs = list(node.inputs())
|
| 1025 |
+
|
| 1026 |
+
# TODO: (1/N) stage.
|
| 1027 |
+
if inputs[0].debugName() not in self.name_to_constant:
|
| 1028 |
+
raise RuntimeError(
|
| 1029 |
+
"prim::Loop currently cannot run with dynamic value of number of iterations."
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
# Make sure the condition is not updated in the subblock.
|
| 1033 |
+
subblock = next(node.blocks())
|
| 1034 |
+
condition_output_name = next(subblock.outputs()).debugName()
|
| 1035 |
+
for node in subblock.nodes():
|
| 1036 |
+
if (
|
| 1037 |
+
node.outputsSize() == 1
|
| 1038 |
+
and node.output().debugName() == condition_output_name
|
| 1039 |
+
):
|
| 1040 |
+
raise RuntimeError(
|
| 1041 |
+
"prim::Loop currently cannot run with dynamic value of condition."
|
| 1042 |
+
)
|
| 1043 |
+
if node.outputsSize() >= 2:
|
| 1044 |
+
for outp in node.outputs():
|
| 1045 |
+
if outp.debugName() == condition_output_name:
|
| 1046 |
+
raise RuntimeError(
|
| 1047 |
+
"prim::Loop currently cannot run with dynamic value of condition."
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
def convert_prim_Loop(self, node: torch._C.Node):
|
| 1051 |
+
inputs = list(node.inputs())
|
| 1052 |
+
self._check_prim_loop_support(node)
|
| 1053 |
+
|
| 1054 |
+
num_iterations = self.get_fx_value_by_ir_value(inputs[0])
|
| 1055 |
+
|
| 1056 |
+
# Find inputs.
|
| 1057 |
+
loop_local_arguments = [inp.debugName() for inp in inputs[2:]]
|
| 1058 |
+
|
| 1059 |
+
global_arguments = self._identify_inputs_as_arguments(node)
|
| 1060 |
+
|
| 1061 |
+
# Lift parameters as inputs.
|
| 1062 |
+
for block in node.blocks():
|
| 1063 |
+
global_arguments = global_arguments.union(
|
| 1064 |
+
self.blocks_to_lifted_attrs[block]
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
global_arguments = list(global_arguments)
|
| 1068 |
+
|
| 1069 |
+
subgraph_nodes, subgraph_converters = self._convert_block_to_subgraph(
|
| 1070 |
+
node, global_arguments
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
assert len(subgraph_nodes) == 1
|
| 1074 |
+
subgraph_converter = subgraph_converters[0]
|
| 1075 |
+
if not self.is_top_level_graph():
|
| 1076 |
+
self.name_update_from_subblock_to_parent = (
|
| 1077 |
+
self.name_update_from_subblock_to_parent.union(
|
| 1078 |
+
subgraph_converter.name_update_from_subblock_to_parent
|
| 1079 |
+
)
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
fx_block_args = [
|
| 1083 |
+
self.get_fx_value_by_fqn(name)
|
| 1084 |
+
for name in loop_local_arguments + global_arguments
|
| 1085 |
+
]
|
| 1086 |
+
for iter_idx in range(num_iterations):
|
| 1087 |
+
loop_node = self.fx_graph.call_function(
|
| 1088 |
+
execute_subgraph_from_prim_loop,
|
| 1089 |
+
# Check execute_node function for the expected arguments order.
|
| 1090 |
+
(
|
| 1091 |
+
subgraph_nodes[0],
|
| 1092 |
+
iter_idx,
|
| 1093 |
+
len(loop_local_arguments),
|
| 1094 |
+
*fx_block_args,
|
| 1095 |
+
),
|
| 1096 |
+
{},
|
| 1097 |
+
)
|
| 1098 |
+
|
| 1099 |
+
# Update the value of loop local variables.
|
| 1100 |
+
if node.outputsSize() >= 1:
|
| 1101 |
+
for i, outp in enumerate(node.outputs()):
|
| 1102 |
+
output_name = outp.debugName()
|
| 1103 |
+
self.name_to_node[output_name] = self.fx_graph.call_function(
|
| 1104 |
+
operator.getitem,
|
| 1105 |
+
(
|
| 1106 |
+
loop_node,
|
| 1107 |
+
i + 1,
|
| 1108 |
+
), # + 1 because the 0th element is the condition.
|
| 1109 |
+
)
|
| 1110 |
+
fx_block_args[i] = self.name_to_node[output_name]
|
| 1111 |
+
|
| 1112 |
+
# Update the value of global variables, whose values are modified inplace.
|
| 1113 |
+
|
| 1114 |
+
for i, name in enumerate(
|
| 1115 |
+
subgraph_converter.name_update_from_subblock_to_parent
|
| 1116 |
+
):
|
| 1117 |
+
self.name_to_node[name] = self.fx_graph.call_function(
|
| 1118 |
+
operator.getitem,
|
| 1119 |
+
(
|
| 1120 |
+
loop_node,
|
| 1121 |
+
i + node.outputsSize() + 1,
|
| 1122 |
+
), # + 1 because the 0th element is the condition.
|
| 1123 |
+
)
|
| 1124 |
+
global_argument_index = global_arguments.index(name)
|
| 1125 |
+
fx_block_args[i + node.outputsSize() + global_argument_index] = (
|
| 1126 |
+
self.name_to_node[name]
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
def _check_set_attr_in_if_block(self, if_node: torch._C.Node):
|
| 1130 |
+
for block in if_node.blocks():
|
| 1131 |
+
for node in block.nodes():
|
| 1132 |
+
if node.kind() == "prim::SetAttr":
|
| 1133 |
+
raise RuntimeError(
|
| 1134 |
+
"During converting prim::If to torch.cond, found prim::SetAttr op"
|
| 1135 |
+
" which is not supported yet. Please file an issue if you come "
|
| 1136 |
+
"across this error."
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
def convert_prim_If(self, node: torch._C.Node):
|
| 1140 |
+
self._check_set_attr_in_if_block(node)
|
| 1141 |
+
|
| 1142 |
+
inputs = list(node.inputs())
|
| 1143 |
+
assert len(inputs) == 1
|
| 1144 |
+
predicate = self.get_fx_value_by_ir_value(inputs[0])
|
| 1145 |
+
|
| 1146 |
+
# Find inputs.
|
| 1147 |
+
arguments = self._identify_inputs_as_arguments(node)
|
| 1148 |
+
|
| 1149 |
+
# Lift parameters as inputs.
|
| 1150 |
+
for block in node.blocks():
|
| 1151 |
+
arguments = arguments.union(self.blocks_to_lifted_attrs[block])
|
| 1152 |
+
|
| 1153 |
+
arguments = list(arguments)
|
| 1154 |
+
subgraph_nodes, _ = self._convert_block_to_subgraph(node, arguments)
|
| 1155 |
+
|
| 1156 |
+
assert len(subgraph_nodes) == 2
|
| 1157 |
+
|
| 1158 |
+
fx_block_args = [self.get_fx_value_by_fqn(name) for name in arguments]
|
| 1159 |
+
|
| 1160 |
+
args = (
|
| 1161 |
+
predicate,
|
| 1162 |
+
subgraph_nodes[0],
|
| 1163 |
+
subgraph_nodes[1],
|
| 1164 |
+
tuple(fx_block_args),
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
cond_node = self.fx_graph.call_function(torch.cond, args, {})
|
| 1168 |
+
|
| 1169 |
+
# prim::If can also have zero output.
|
| 1170 |
+
if node.outputsSize() == 1:
|
| 1171 |
+
output_name = node.output().debugName()
|
| 1172 |
+
self.name_to_node[output_name] = cond_node
|
| 1173 |
+
elif node.outputsSize() > 1:
|
| 1174 |
+
for i, output in enumerate(node.outputs()):
|
| 1175 |
+
output_name = output.debugName()
|
| 1176 |
+
getitem = self.fx_graph.call_function(operator.getitem, (cond_node, i))
|
| 1177 |
+
self.name_to_node[output_name] = getitem
|
| 1178 |
+
|
| 1179 |
+
def convert_aten_Bool(self, node: torch._C.Node):
|
| 1180 |
+
self._convert_as_noop(node)
|
| 1181 |
+
|
| 1182 |
+
def convert_prim_Enter(self, node: torch._C.Node):
|
| 1183 |
+
# export generally treats prim::Enter as noop
|
| 1184 |
+
# The only context manager export supports is aten::enable_grad.
|
| 1185 |
+
# Unfortunately, TorchScript does not support aten::enable_grad yet.
|
| 1186 |
+
# TODO: support aten::enable_grad in both TorchScript and Converter.
|
| 1187 |
+
return
|
| 1188 |
+
|
| 1189 |
+
def convert_prim_Exit(self, node: torch._C.Node):
|
| 1190 |
+
# export treats prim::Exit as noop
|
| 1191 |
+
return
|
| 1192 |
+
|
| 1193 |
+
def _convert_as_noop(self, node: torch._C.Node):
|
| 1194 |
+
# Converts the node as a no-op by mapping its output node as arg[0]
|
| 1195 |
+
|
| 1196 |
+
target = get_op_overload(node)
|
| 1197 |
+
schema = target._schema
|
| 1198 |
+
|
| 1199 |
+
args, _kwargs = self.get_args_kwargs(node, schema)
|
| 1200 |
+
|
| 1201 |
+
output_name = node.output().debugName()
|
| 1202 |
+
self.name_to_node[output_name] = args[0]
|
| 1203 |
+
|
| 1204 |
+
def convert_profiler__record_function_exit(self, node: torch._C.Node):
|
| 1205 |
+
# _record_function_exit has side effect so we keep it in fx.graph
|
| 1206 |
+
# currently, _record_function_enter_new and _record_function_exit are
|
| 1207 |
+
# discarded during `retrace_as_exported_program`.
|
| 1208 |
+
target = torch.ops.profiler._record_function_exit
|
| 1209 |
+
args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs())
|
| 1210 |
+
self.fx_graph.call_function(target, args)
|
| 1211 |
+
|
| 1212 |
+
def convert_prim_tolist(self, node: torch._C.Node):
|
| 1213 |
+
# prim::tolist cannot be supported by `_convert_standard_operators`
|
| 1214 |
+
# since it requires call_method instead of call_function.
|
| 1215 |
+
target = "tolist"
|
| 1216 |
+
args = (self.get_fx_value_by_ir_value(next(node.inputs())),)
|
| 1217 |
+
fx_node = self.fx_graph.call_method(target, args)
|
| 1218 |
+
output_name = node.output().debugName()
|
| 1219 |
+
self.name_to_node[output_name] = fx_node
|
| 1220 |
+
|
| 1221 |
+
def convert_prim_Uninitialized(self, node: torch._C.Node):
|
| 1222 |
+
# `prim::Uninitialized` is inserted by the compiler when it can prove
|
| 1223 |
+
# the value will never be used. It can be introduced by exceptions,
|
| 1224 |
+
# breaks, continues, and returns.
|
| 1225 |
+
# So we add a dummy constant to the graph.
|
| 1226 |
+
output_name = node.output().debugName()
|
| 1227 |
+
self.name_to_constant[output_name] = torch.Tensor()
|
| 1228 |
+
|
| 1229 |
+
def _convert_standard_operators(self, node: torch._C.Node):
|
| 1230 |
+
target = kind_to_standard_operators[node.kind()]
|
| 1231 |
+
args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs())
|
| 1232 |
+
fx_node = self.fx_graph.call_function(target, args)
|
| 1233 |
+
output_name = node.output().debugName()
|
| 1234 |
+
self.name_to_node[output_name] = fx_node
|
| 1235 |
+
|
| 1236 |
+
def convert_node(self, node: torch._C.Node):
|
| 1237 |
+
node_kind = node.kind()
|
| 1238 |
+
|
| 1239 |
+
# Get handler based on namespace and operator name.
|
| 1240 |
+
# Provide a default node handler as well in case we don't find
|
| 1241 |
+
# matching converter for that.
|
| 1242 |
+
handler_func_name = ir_name_to_func_name(node_kind)
|
| 1243 |
+
handler_func = getattr(self, handler_func_name, self.convert_call_function_op)
|
| 1244 |
+
|
| 1245 |
+
# str calls print function implemented in CPP. To avoid repeating
|
| 1246 |
+
# the entire logic here, we simply keep first line from node string (getting rid
|
| 1247 |
+
# of sub-blocks IR prints).
|
| 1248 |
+
node_str = "".join(str(node).split("\n")[:1])
|
| 1249 |
+
log.debug("[%s] converts [%s]", handler_func.__name__, node_str)
|
| 1250 |
+
try:
|
| 1251 |
+
handler_func(node)
|
| 1252 |
+
except Exception as e:
|
| 1253 |
+
raise RuntimeError(f"TS2EPConverter failed for node {node_kind}") from e
|
| 1254 |
+
|
| 1255 |
+
def convert_graph_outputs(self):
|
| 1256 |
+
args = []
|
| 1257 |
+
outp_name_list = [outp.debugName() for outp in self.ts_graph.outputs()] + list(
|
| 1258 |
+
self.name_update_from_subblock_to_parent
|
| 1259 |
+
)
|
| 1260 |
+
for output_name in outp_name_list:
|
| 1261 |
+
if output_name in self.name_to_node:
|
| 1262 |
+
fx_node = self.name_to_node[output_name]
|
| 1263 |
+
# TODO: Revisit this later after HigherOrderOp design changes.
|
| 1264 |
+
# Currently, we cannot directly return input as output.
|
| 1265 |
+
if (
|
| 1266 |
+
not self.is_top_level_graph()
|
| 1267 |
+
and isinstance(fx_node, torch.fx.Node)
|
| 1268 |
+
and fx_node.op == "placeholder"
|
| 1269 |
+
):
|
| 1270 |
+
fx_node = self.fx_graph.call_function(torch.clone, (fx_node,))
|
| 1271 |
+
args.append(fx_node)
|
| 1272 |
+
self.output_specs.append(
|
| 1273 |
+
OutputSpec(
|
| 1274 |
+
OutputKind.USER_OUTPUT,
|
| 1275 |
+
arg=TensorArgument(name=output_name),
|
| 1276 |
+
target=output_name,
|
| 1277 |
+
)
|
| 1278 |
+
)
|
| 1279 |
+
elif output_name in self.name_to_constant:
|
| 1280 |
+
args.append(self.name_to_constant[output_name])
|
| 1281 |
+
self.output_specs.append(
|
| 1282 |
+
OutputSpec(
|
| 1283 |
+
OutputKind.USER_OUTPUT,
|
| 1284 |
+
arg=ConstantArgument(
|
| 1285 |
+
name=output_name, value=self.name_to_constant[output_name]
|
| 1286 |
+
),
|
| 1287 |
+
target=output_name,
|
| 1288 |
+
)
|
| 1289 |
+
)
|
| 1290 |
+
else:
|
| 1291 |
+
raise ValueError(f"Output {output_name} not found")
|
| 1292 |
+
|
| 1293 |
+
if len(args) == 0:
|
| 1294 |
+
# Sub-block of prim::If can have zero output.
|
| 1295 |
+
self.fx_graph.output([])
|
| 1296 |
+
elif len(args) == 1:
|
| 1297 |
+
self.fx_graph.output(
|
| 1298 |
+
args[0]
|
| 1299 |
+
) # Get rid of an extra list wrapped around final output.
|
| 1300 |
+
elif len(args) > 1:
|
| 1301 |
+
self.fx_graph.output(
|
| 1302 |
+
args
|
| 1303 |
+
) # For prim::Loop and prim::If with multiple outputs.
|
| 1304 |
+
else:
|
| 1305 |
+
# Sub-block of prim::Loop can have multiple outputs.
|
| 1306 |
+
self.fx_graph.output(args)
|
| 1307 |
+
|
| 1308 |
+
|
| 1309 |
+
class ExplainTS2FXGraphConverter(TS2FXGraphConverter):
|
| 1310 |
+
"""
|
| 1311 |
+
Run TS2FXGraphConverter in an explain mode. It collects all failed operators conversions
|
| 1312 |
+
and provide that information to users. In order to collect all failed conversions, it
|
| 1313 |
+
also mocks some internal attributes (e.g., name_to_node).
|
| 1314 |
+
"""
|
| 1315 |
+
|
| 1316 |
+
class _DictMock(dict):
|
| 1317 |
+
def __init__(self, dict_data, mock_value):
|
| 1318 |
+
super().__init__(dict_data)
|
| 1319 |
+
self.mock_value = mock_value
|
| 1320 |
+
|
| 1321 |
+
def __getitem__(self, key):
|
| 1322 |
+
# If the original dictionary has the key, return its value.
|
| 1323 |
+
# Otherwise, return the mock value.
|
| 1324 |
+
if not super().__contains__(key):
|
| 1325 |
+
return self.mock_value
|
| 1326 |
+
return super().__getitem__(key)
|
| 1327 |
+
|
| 1328 |
+
def __contains__(self, key):
|
| 1329 |
+
return True
|
| 1330 |
+
|
| 1331 |
+
def __init__(
|
| 1332 |
+
self,
|
| 1333 |
+
ts_graph: Union[torch._C.Graph, torch._C.Block],
|
| 1334 |
+
name_to_param: dict[str, torch.Tensor],
|
| 1335 |
+
name_to_buffer: dict[str, torch.Tensor],
|
| 1336 |
+
blocks_to_lifted_attrs: dict[torch._C.Block, set[str]],
|
| 1337 |
+
name_to_non_tensor_attribute: dict[str, Any],
|
| 1338 |
+
name_to_constant: dict[str, Any],
|
| 1339 |
+
name_to_attribute_fqn: dict[str, str],
|
| 1340 |
+
):
|
| 1341 |
+
super().__init__(
|
| 1342 |
+
ts_graph,
|
| 1343 |
+
name_to_param,
|
| 1344 |
+
name_to_buffer,
|
| 1345 |
+
blocks_to_lifted_attrs,
|
| 1346 |
+
name_to_non_tensor_attribute,
|
| 1347 |
+
name_to_constant,
|
| 1348 |
+
name_to_attribute_fqn,
|
| 1349 |
+
)
|
| 1350 |
+
|
| 1351 |
+
# Data to keep track of unsupported nodes.
|
| 1352 |
+
self.unsupported_node_list: list[torch._C.Node] = []
|
| 1353 |
+
|
| 1354 |
+
# Add mock to needed attributes.
|
| 1355 |
+
self.name_to_node = ExplainTS2FXGraphConverter._DictMock(
|
| 1356 |
+
self.name_to_node,
|
| 1357 |
+
# Dummy node.
|
| 1358 |
+
torch.fx.Node(
|
| 1359 |
+
None, # type: ignore[arg-type]
|
| 1360 |
+
"mock",
|
| 1361 |
+
"call_function",
|
| 1362 |
+
lambda: None,
|
| 1363 |
+
(),
|
| 1364 |
+
{},
|
| 1365 |
+
),
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
def explain(self):
|
| 1369 |
+
self.convert_graph_inputs()
|
| 1370 |
+
for node in self.ts_graph.nodes():
|
| 1371 |
+
self.convert_node(node)
|
| 1372 |
+
self.convert_graph_outputs()
|
| 1373 |
+
|
| 1374 |
+
def convert_node(self, node):
|
| 1375 |
+
try:
|
| 1376 |
+
super().convert_node(node)
|
| 1377 |
+
except Exception:
|
| 1378 |
+
self.unsupported_node_list.append(node)
|
| 1379 |
+
|
| 1380 |
+
|
| 1381 |
+
@contextmanager
|
| 1382 |
+
def disable_logging(log):
|
| 1383 |
+
disabled = log.disabled
|
| 1384 |
+
log.disabled = True
|
| 1385 |
+
try:
|
| 1386 |
+
yield
|
| 1387 |
+
finally:
|
| 1388 |
+
log.disabled = disabled
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
class TS2EPConverter:
|
| 1392 |
+
# TorchScript model to ExportedProgram converter
|
| 1393 |
+
def __init__(
|
| 1394 |
+
self,
|
| 1395 |
+
ts_model: Union[torch.jit.ScriptModule, torch.jit.ScriptFunction],
|
| 1396 |
+
sample_args: tuple[Any, ...],
|
| 1397 |
+
sample_kwargs: Optional[dict[str, Any]] = None,
|
| 1398 |
+
):
|
| 1399 |
+
self.ts_model = ts_model
|
| 1400 |
+
self.ts_graph, self.params, _, _ = _create_jit_graph(ts_model, sample_args)
|
| 1401 |
+
|
| 1402 |
+
self.sample_args = sample_args
|
| 1403 |
+
self.sample_kwargs = sample_kwargs
|
| 1404 |
+
|
| 1405 |
+
self.name_to_param: dict[str, torch.Tensor] = {}
|
| 1406 |
+
self.name_to_buffer: dict[str, torch.Tensor] = {}
|
| 1407 |
+
param_list = (
|
| 1408 |
+
list(self.ts_model.parameters())
|
| 1409 |
+
if not isinstance(self.ts_model, torch._C.ScriptFunction)
|
| 1410 |
+
else []
|
| 1411 |
+
)
|
| 1412 |
+
if not isinstance(self.ts_model, torch._C.ScriptFunction):
|
| 1413 |
+
for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr]
|
| 1414 |
+
# Check if tensor belongs to any parameter.
|
| 1415 |
+
if any(
|
| 1416 |
+
(tensor == param).all()
|
| 1417 |
+
for param in param_list
|
| 1418 |
+
if tensor.shape == param.shape
|
| 1419 |
+
):
|
| 1420 |
+
self.name_to_param[k] = tensor
|
| 1421 |
+
else:
|
| 1422 |
+
self.name_to_buffer[k] = tensor
|
| 1423 |
+
|
| 1424 |
+
self.name_to_non_tensor_attributes: dict[str, Any] = {}
|
| 1425 |
+
self.name_to_constant: dict[str, Any] = {}
|
| 1426 |
+
|
| 1427 |
+
self.lift_get_attr()
|
| 1428 |
+
|
| 1429 |
+
def convert(self) -> ExportedProgram:
|
| 1430 |
+
log.info(
|
| 1431 |
+
"""
|
| 1432 |
+
TS2EPConverter logging starts from here.
|
| 1433 |
+
|
| 1434 |
+
INFO: (TORCH_LOGS="export" <cmd>)
|
| 1435 |
+
* Log TorchScript IR.
|
| 1436 |
+
|
| 1437 |
+
DEBUG: (TORCH_LOGS="+export" <cmd>), additionally
|
| 1438 |
+
* Log conversion IR by IR in a format of [<conversion handler name>] converts [<IR>].
|
| 1439 |
+
"""
|
| 1440 |
+
)
|
| 1441 |
+
log.info("TorchScript graph\n\n%s\n", self.ts_graph)
|
| 1442 |
+
|
| 1443 |
+
blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs(
|
| 1444 |
+
self.ts_graph
|
| 1445 |
+
)
|
| 1446 |
+
|
| 1447 |
+
graph_converter = TS2FXGraphConverter(
|
| 1448 |
+
self.ts_graph,
|
| 1449 |
+
self.name_to_param,
|
| 1450 |
+
self.name_to_buffer,
|
| 1451 |
+
blocks_to_lifted_attrs,
|
| 1452 |
+
self.name_to_non_tensor_attributes,
|
| 1453 |
+
self.name_to_constant,
|
| 1454 |
+
name_to_attribute_fqn,
|
| 1455 |
+
)
|
| 1456 |
+
gm = graph_converter.convert()
|
| 1457 |
+
|
| 1458 |
+
# Post-processing step to deal with quantized operators.
|
| 1459 |
+
replace_quantized_ops_with_standard_ops(gm)
|
| 1460 |
+
log.info("GraphModule: %s", gm.print_readable(print_output=False))
|
| 1461 |
+
|
| 1462 |
+
ep = self.retrace_as_exported_program(
|
| 1463 |
+
gm,
|
| 1464 |
+
graph_converter.name_to_constant,
|
| 1465 |
+
)
|
| 1466 |
+
log.info("%s", ep)
|
| 1467 |
+
|
| 1468 |
+
# Post-processing step to ensure ExportedProgram has the same state_dict as
|
| 1469 |
+
# the original TorchScript model. Throw warnings for additionally populated
|
| 1470 |
+
# state_dict entries.
|
| 1471 |
+
if not isinstance(self.ts_model, torch._C.ScriptFunction):
|
| 1472 |
+
for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr]
|
| 1473 |
+
if k not in ep.state_dict:
|
| 1474 |
+
warnings.warn(
|
| 1475 |
+
f"Manually populate {k} into state_dict ExportedProgram, but it is never used by the ExportedProgram.",
|
| 1476 |
+
stacklevel=2,
|
| 1477 |
+
)
|
| 1478 |
+
ep.state_dict[k] = tensor
|
| 1479 |
+
|
| 1480 |
+
return ep
|
| 1481 |
+
|
| 1482 |
+
@disable_logging(log)
|
| 1483 |
+
def explain(self, print_output=True):
|
| 1484 |
+
blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs(
|
| 1485 |
+
self.ts_graph
|
| 1486 |
+
)
|
| 1487 |
+
|
| 1488 |
+
graph_converter = ExplainTS2FXGraphConverter(
|
| 1489 |
+
self.ts_graph,
|
| 1490 |
+
self.name_to_param,
|
| 1491 |
+
self.name_to_buffer,
|
| 1492 |
+
blocks_to_lifted_attrs,
|
| 1493 |
+
self.name_to_non_tensor_attributes,
|
| 1494 |
+
self.name_to_constant,
|
| 1495 |
+
name_to_attribute_fqn,
|
| 1496 |
+
)
|
| 1497 |
+
graph_converter.explain()
|
| 1498 |
+
if len(graph_converter.unsupported_node_list) > 0:
|
| 1499 |
+
explain_str = "Unsupported nodes are found in the following list:"
|
| 1500 |
+
for i, n in enumerate(graph_converter.unsupported_node_list):
|
| 1501 |
+
node_str = "".join(str(n).split("\n")[:1])
|
| 1502 |
+
explain_str += f"\n\n {i}. {n.kind()} [{node_str}]"
|
| 1503 |
+
else:
|
| 1504 |
+
explain_str = "Success!"
|
| 1505 |
+
if print_output:
|
| 1506 |
+
print(explain_str)
|
| 1507 |
+
return explain_str
|
| 1508 |
+
|
| 1509 |
+
def retrace_as_exported_program(
|
| 1510 |
+
self,
|
| 1511 |
+
gm: torch.fx.GraphModule,
|
| 1512 |
+
name_to_constant: dict[str, Any],
|
| 1513 |
+
):
|
| 1514 |
+
dynamic_shapes = _tree_map_with_path(
|
| 1515 |
+
lambda path, x: (
|
| 1516 |
+
[Dim.AUTO] * x.dim() if isinstance(x, torch.Tensor) else None
|
| 1517 |
+
),
|
| 1518 |
+
self.sample_args,
|
| 1519 |
+
)
|
| 1520 |
+
|
| 1521 |
+
# TODO: adjust input orders to match GraphSignature convention
|
| 1522 |
+
ep = torch.export._trace._export(
|
| 1523 |
+
gm,
|
| 1524 |
+
self.sample_args,
|
| 1525 |
+
dynamic_shapes=dynamic_shapes,
|
| 1526 |
+
strict=False,
|
| 1527 |
+
pre_dispatch=True,
|
| 1528 |
+
)
|
| 1529 |
+
|
| 1530 |
+
# Post-processing to make sure the ExportedProgram states are correct.
|
| 1531 |
+
# Because during conversion, we set tensor constants as GetAttr,
|
| 1532 |
+
# retracing cannot recognize them as tensor constants but instead
|
| 1533 |
+
# treat them as buffers. We need to set them again here.
|
| 1534 |
+
ep._constants.update(
|
| 1535 |
+
{
|
| 1536 |
+
k: v
|
| 1537 |
+
for k, v in name_to_constant.items()
|
| 1538 |
+
if isinstance(v, (torch.Tensor, torch.ScriptObject))
|
| 1539 |
+
}
|
| 1540 |
+
)
|
| 1541 |
+
for k in name_to_constant:
|
| 1542 |
+
ep.state_dict.pop(k, None)
|
| 1543 |
+
|
| 1544 |
+
for spec in ep.graph_signature.input_specs:
|
| 1545 |
+
# Mark as constant tensors for erroneously traced buffers.
|
| 1546 |
+
if spec.kind == InputKind.BUFFER and spec.target in name_to_constant:
|
| 1547 |
+
assert isinstance(name_to_constant[spec.target], torch.Tensor), (
|
| 1548 |
+
f"{type(name_to_constant[spec.target])} has been erroneously marked as buffer"
|
| 1549 |
+
)
|
| 1550 |
+
spec.kind = InputKind.CONSTANT_TENSOR
|
| 1551 |
+
spec.persistent = None
|
| 1552 |
+
ep.verifier().check(ep)
|
| 1553 |
+
|
| 1554 |
+
return ep
|
| 1555 |
+
|
| 1556 |
+
def lift_get_attr(self):
|
| 1557 |
+
# This function lifts multiple data types.
|
| 1558 |
+
|
| 1559 |
+
# 1. Tensor constants attributes (e.g., self.data = torch.tensor([2,3]))
|
| 1560 |
+
# to buffers. Currently, when there are tensor constants, export
|
| 1561 |
+
# would error and ask users to register tensor constants as buffers.
|
| 1562 |
+
# Since it is hard to manually do so for TorchScript models
|
| 1563 |
+
# (e.g., source code is missing), this function automatically
|
| 1564 |
+
# lifts tensor constants to be buffers.
|
| 1565 |
+
|
| 1566 |
+
# 2. ScriptObbject to constant. It will then be converted to getattr in
|
| 1567 |
+
# in the fx graph.
|
| 1568 |
+
#
|
| 1569 |
+
# This function should happen in TS2EPConverter instead of
|
| 1570 |
+
# TS2FXGraphConverter since it gets attributes from self.ts_model
|
| 1571 |
+
# which is not accessible in TS2FXGraphConverter. It is similar to where
|
| 1572 |
+
# we collect self.name_to_param and self.name_to_buffer.
|
| 1573 |
+
name_to_attribute_fqn: dict[str, str] = {}
|
| 1574 |
+
|
| 1575 |
+
def get_attr(fqn: str):
|
| 1576 |
+
name = fqn.split(".")
|
| 1577 |
+
v = self.ts_model
|
| 1578 |
+
for n in name:
|
| 1579 |
+
v = getattr(v, n)
|
| 1580 |
+
return v
|
| 1581 |
+
|
| 1582 |
+
def get_fqn(node: torch._C.Node):
|
| 1583 |
+
attr_name = node.s("name")
|
| 1584 |
+
input_name = node.input().debugName()
|
| 1585 |
+
root_attr_name = name_to_attribute_fqn[input_name]
|
| 1586 |
+
attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name
|
| 1587 |
+
return attr_fqn
|
| 1588 |
+
|
| 1589 |
+
def _dfs_get_attr(block):
|
| 1590 |
+
for node in block.nodes():
|
| 1591 |
+
if node.kind() == "prim::CreateObject":
|
| 1592 |
+
output_name = node.output().debugName()
|
| 1593 |
+
name_to_attribute_fqn[output_name] = ""
|
| 1594 |
+
|
| 1595 |
+
if node.kind() == "prim::GetAttr":
|
| 1596 |
+
attr_fqn = get_fqn(node)
|
| 1597 |
+
value = get_attr(attr_fqn)
|
| 1598 |
+
output_name = node.output().debugName()
|
| 1599 |
+
name_to_attribute_fqn[output_name] = attr_fqn
|
| 1600 |
+
if isinstance(value, torch.Tensor):
|
| 1601 |
+
if attr_fqn not in self.name_to_buffer:
|
| 1602 |
+
# Lift tensor constants to be a buffer
|
| 1603 |
+
self.name_to_buffer[attr_fqn] = value
|
| 1604 |
+
elif isinstance(value, torch.ScriptObject):
|
| 1605 |
+
if attr_fqn not in self.name_to_constant:
|
| 1606 |
+
self.name_to_constant[attr_fqn] = value
|
| 1607 |
+
else:
|
| 1608 |
+
self.name_to_non_tensor_attributes[attr_fqn] = value
|
| 1609 |
+
|
| 1610 |
+
for subblock in node.blocks():
|
| 1611 |
+
_dfs_get_attr(subblock)
|
| 1612 |
+
|
| 1613 |
+
_dfs_get_attr(self.ts_graph)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/case.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import inspect
|
| 3 |
+
import re
|
| 4 |
+
import string
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from typing import Any, Optional
|
| 8 |
+
from types import ModuleType
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
_TAGS: dict[str, dict[str, Any]] = {
|
| 13 |
+
"torch": {
|
| 14 |
+
"cond": {},
|
| 15 |
+
"dynamic-shape": {},
|
| 16 |
+
"escape-hatch": {},
|
| 17 |
+
"map": {},
|
| 18 |
+
"dynamic-value": {},
|
| 19 |
+
"operator": {},
|
| 20 |
+
"mutation": {},
|
| 21 |
+
},
|
| 22 |
+
"python": {
|
| 23 |
+
"assert": {},
|
| 24 |
+
"builtin": {},
|
| 25 |
+
"closure": {},
|
| 26 |
+
"context-manager": {},
|
| 27 |
+
"control-flow": {},
|
| 28 |
+
"data-structure": {},
|
| 29 |
+
"standard-library": {},
|
| 30 |
+
"object-model": {},
|
| 31 |
+
},
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SupportLevel(Enum):
|
| 36 |
+
"""
|
| 37 |
+
Indicates at what stage the feature
|
| 38 |
+
used in the example is handled in export.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
SUPPORTED = 1
|
| 42 |
+
NOT_SUPPORTED_YET = 0
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
ArgsType = tuple[Any, ...]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def check_inputs_type(args, kwargs):
|
| 49 |
+
if not isinstance(args, tuple):
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f"Expecting args type to be a tuple, got: {type(args)}"
|
| 52 |
+
)
|
| 53 |
+
if not isinstance(kwargs, dict):
|
| 54 |
+
raise ValueError(
|
| 55 |
+
f"Expecting kwargs type to be a dict, got: {type(kwargs)}"
|
| 56 |
+
)
|
| 57 |
+
for key in kwargs:
|
| 58 |
+
if not isinstance(key, str):
|
| 59 |
+
raise ValueError(
|
| 60 |
+
f"Expecting kwargs keys to be a string, got: {type(key)}"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def _validate_tag(tag: str):
|
| 64 |
+
parts = tag.split(".")
|
| 65 |
+
t = _TAGS
|
| 66 |
+
for part in parts:
|
| 67 |
+
assert set(part) <= set(
|
| 68 |
+
string.ascii_lowercase + "-"
|
| 69 |
+
), f"Tag contains invalid characters: {part}"
|
| 70 |
+
if part in t:
|
| 71 |
+
t = t[part]
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError(f"Tag {tag} is not found in registered tags.")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass(frozen=True)
|
| 77 |
+
class ExportCase:
|
| 78 |
+
example_args: ArgsType
|
| 79 |
+
description: str # A description of the use case.
|
| 80 |
+
model: torch.nn.Module
|
| 81 |
+
name: str
|
| 82 |
+
example_kwargs: dict[str, Any] = field(default_factory=dict)
|
| 83 |
+
extra_args: Optional[ArgsType] = None # For testing graph generalization.
|
| 84 |
+
# Tags associated with the use case. (e.g dynamic-shape, escape-hatch)
|
| 85 |
+
tags: set[str] = field(default_factory=set)
|
| 86 |
+
support_level: SupportLevel = SupportLevel.SUPPORTED
|
| 87 |
+
dynamic_shapes: Optional[dict[str, Any]] = None
|
| 88 |
+
|
| 89 |
+
def __post_init__(self):
|
| 90 |
+
check_inputs_type(self.example_args, self.example_kwargs)
|
| 91 |
+
if self.extra_args is not None:
|
| 92 |
+
check_inputs_type(self.extra_args, {})
|
| 93 |
+
|
| 94 |
+
for tag in self.tags:
|
| 95 |
+
_validate_tag(tag)
|
| 96 |
+
|
| 97 |
+
if not isinstance(self.description, str) or len(self.description) == 0:
|
| 98 |
+
raise ValueError(f'Invalid description: "{self.description}"')
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
_EXAMPLE_CASES: dict[str, ExportCase] = {}
|
| 102 |
+
_MODULES: set[ModuleType] = set()
|
| 103 |
+
_EXAMPLE_CONFLICT_CASES: dict[str, list[ExportCase]] = {}
|
| 104 |
+
_EXAMPLE_REWRITE_CASES: dict[str, list[ExportCase]] = {}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def register_db_case(case: ExportCase) -> None:
|
| 108 |
+
"""
|
| 109 |
+
Registers a user provided ExportCase into example bank.
|
| 110 |
+
"""
|
| 111 |
+
if case.name in _EXAMPLE_CASES:
|
| 112 |
+
if case.name not in _EXAMPLE_CONFLICT_CASES:
|
| 113 |
+
_EXAMPLE_CONFLICT_CASES[case.name] = [_EXAMPLE_CASES[case.name]]
|
| 114 |
+
_EXAMPLE_CONFLICT_CASES[case.name].append(case)
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
_EXAMPLE_CASES[case.name] = case
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def to_snake_case(name):
|
| 121 |
+
name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
|
| 122 |
+
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _make_export_case(m, name, configs):
|
| 126 |
+
if not isinstance(m, torch.nn.Module):
|
| 127 |
+
raise TypeError("Export case class should be a torch.nn.Module.")
|
| 128 |
+
|
| 129 |
+
if "description" not in configs:
|
| 130 |
+
# Fallback to docstring if description is missing.
|
| 131 |
+
assert (
|
| 132 |
+
m.__doc__ is not None
|
| 133 |
+
), f"Could not find description or docstring for export case: {m}"
|
| 134 |
+
configs = {**configs, "description": m.__doc__}
|
| 135 |
+
# pyrefly: ignore [bad-argument-type]
|
| 136 |
+
return ExportCase(**{**configs, "model": m, "name": name})
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def export_case(**kwargs):
|
| 140 |
+
"""
|
| 141 |
+
Decorator for registering a user provided case into example bank.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
def wrapper(m):
|
| 145 |
+
configs = kwargs
|
| 146 |
+
module = inspect.getmodule(m)
|
| 147 |
+
if module in _MODULES:
|
| 148 |
+
raise RuntimeError("export_case should only be used once per example file.")
|
| 149 |
+
|
| 150 |
+
assert module is not None
|
| 151 |
+
_MODULES.add(module)
|
| 152 |
+
module_name = module.__name__.split(".")[-1]
|
| 153 |
+
case = _make_export_case(m, module_name, configs)
|
| 154 |
+
register_db_case(case)
|
| 155 |
+
return case
|
| 156 |
+
|
| 157 |
+
return wrapper
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def export_rewrite_case(**kwargs):
|
| 161 |
+
def wrapper(m):
|
| 162 |
+
configs = kwargs
|
| 163 |
+
|
| 164 |
+
parent = configs.pop("parent")
|
| 165 |
+
assert isinstance(parent, ExportCase)
|
| 166 |
+
key = parent.name
|
| 167 |
+
if key not in _EXAMPLE_REWRITE_CASES:
|
| 168 |
+
_EXAMPLE_REWRITE_CASES[key] = []
|
| 169 |
+
|
| 170 |
+
configs["example_args"] = parent.example_args
|
| 171 |
+
case = _make_export_case(m, to_snake_case(m.__name__), configs)
|
| 172 |
+
_EXAMPLE_REWRITE_CASES[key].append(case)
|
| 173 |
+
return case
|
| 174 |
+
|
| 175 |
+
return wrapper
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import dataclasses
|
| 3 |
+
import glob
|
| 4 |
+
import inspect
|
| 5 |
+
from os.path import basename, dirname, isfile, join
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch._export.db.case import (
|
| 9 |
+
_EXAMPLE_CASES,
|
| 10 |
+
_EXAMPLE_CONFLICT_CASES,
|
| 11 |
+
_EXAMPLE_REWRITE_CASES,
|
| 12 |
+
SupportLevel,
|
| 13 |
+
export_case,
|
| 14 |
+
ExportCase,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _collect_examples():
|
| 19 |
+
case_names = glob.glob(join(dirname(__file__), "*.py"))
|
| 20 |
+
case_names = [
|
| 21 |
+
basename(f)[:-3] for f in case_names if isfile(f) and not f.endswith("__init__.py")
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
case_fields = {f.name for f in dataclasses.fields(ExportCase)}
|
| 25 |
+
for case_name in case_names:
|
| 26 |
+
case = __import__(case_name, globals(), locals(), [], 1)
|
| 27 |
+
variables = [name for name in dir(case) if name in case_fields]
|
| 28 |
+
export_case(**{v: getattr(case, v) for v in variables})(case.model)
|
| 29 |
+
|
| 30 |
+
_collect_examples()
|
| 31 |
+
|
| 32 |
+
def all_examples():
|
| 33 |
+
return _EXAMPLE_CASES
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if len(_EXAMPLE_CONFLICT_CASES) > 0:
|
| 37 |
+
|
| 38 |
+
def get_name(case):
|
| 39 |
+
model = case.model
|
| 40 |
+
if isinstance(model, torch.nn.Module):
|
| 41 |
+
model = type(model)
|
| 42 |
+
return model.__name__
|
| 43 |
+
|
| 44 |
+
msg = "Error on conflict export case name.\n"
|
| 45 |
+
for case_name, cases in _EXAMPLE_CONFLICT_CASES.items():
|
| 46 |
+
msg += f"Case name {case_name} is associated with multiple cases:\n "
|
| 47 |
+
msg += f"[{','.join(map(get_name, cases))}]\n"
|
| 48 |
+
|
| 49 |
+
raise RuntimeError(msg)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def filter_examples_by_support_level(support_level: SupportLevel):
|
| 53 |
+
return {
|
| 54 |
+
key: val
|
| 55 |
+
for key, val in all_examples().items()
|
| 56 |
+
if val.support_level == support_level
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_rewrite_cases(case):
|
| 61 |
+
return _EXAMPLE_REWRITE_CASES.get(case.name, [])
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/assume_constant_result.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch._dynamo as torchdynamo
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class AssumeConstantResult(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Applying `assume_constant_result` decorator to burn make non-tracable code as constant.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
@torchdynamo.assume_constant_result
|
| 12 |
+
def get_item(self, y):
|
| 13 |
+
return y.int().item()
|
| 14 |
+
|
| 15 |
+
def forward(self, x, y):
|
| 16 |
+
return x[: self.get_item(y)]
|
| 17 |
+
|
| 18 |
+
example_args = (torch.randn(3, 2), torch.tensor(4))
|
| 19 |
+
tags = {"torch.escape-hatch"}
|
| 20 |
+
model = AssumeConstantResult()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/autograd_function.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class MyAutogradFunction(torch.autograd.Function):
|
| 5 |
+
@staticmethod
|
| 6 |
+
# pyrefly: ignore [bad-override]
|
| 7 |
+
def forward(ctx, x):
|
| 8 |
+
return x.clone()
|
| 9 |
+
|
| 10 |
+
@staticmethod
|
| 11 |
+
# pyrefly: ignore [bad-override]
|
| 12 |
+
def backward(ctx, grad_output):
|
| 13 |
+
return grad_output + 1
|
| 14 |
+
|
| 15 |
+
class AutogradFunction(torch.nn.Module):
|
| 16 |
+
"""
|
| 17 |
+
TorchDynamo does not keep track of backward() on autograd functions. We recommend to
|
| 18 |
+
use `allow_in_graph` to mitigate this problem.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
return MyAutogradFunction.apply(x)
|
| 23 |
+
|
| 24 |
+
example_args = (torch.randn(3, 2),)
|
| 25 |
+
model = AutogradFunction()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/class_method.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class ClassMethod(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Class methods are inlined during tracing.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
@classmethod
|
| 10 |
+
def method(cls, x):
|
| 11 |
+
return x + 1
|
| 12 |
+
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.linear = torch.nn.Linear(4, 2)
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
x = self.linear(x)
|
| 19 |
+
return self.method(x) * self.__class__.method(x) * type(self).method(x)
|
| 20 |
+
|
| 21 |
+
example_args = (torch.randn(3, 4),)
|
| 22 |
+
model = ClassMethod()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_class_method.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class MySubModule(torch.nn.Module):
|
| 7 |
+
def foo(self, x):
|
| 8 |
+
return x.cos()
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
return self.foo(x)
|
| 12 |
+
|
| 13 |
+
class CondBranchClassMethod(torch.nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
|
| 16 |
+
- both branches must take the same args, which must also match the branch args passed to cond.
|
| 17 |
+
- both branches must return a single tensor
|
| 18 |
+
- returned tensor must have the same tensor metadata, e.g. shape and dtype
|
| 19 |
+
- branch function can be free function, nested function, lambda, class methods
|
| 20 |
+
- branch function can not have closure variables
|
| 21 |
+
- no inplace mutations on inputs or global variables
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
This example demonstrates using class method in cond().
|
| 25 |
+
|
| 26 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self) -> None:
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.subm = MySubModule()
|
| 32 |
+
|
| 33 |
+
def bar(self, x):
|
| 34 |
+
return x.sin()
|
| 35 |
+
|
| 36 |
+
def forward(self, x):
|
| 37 |
+
return cond(x.shape[0] <= 2, self.subm.forward, self.bar, [x])
|
| 38 |
+
|
| 39 |
+
example_args = (torch.randn(3),)
|
| 40 |
+
tags = {
|
| 41 |
+
"torch.cond",
|
| 42 |
+
"torch.dynamic-shape",
|
| 43 |
+
}
|
| 44 |
+
model = CondBranchClassMethod()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nested_function.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondBranchNestedFunction(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
|
| 9 |
+
- both branches must take the same args, which must also match the branch args passed to cond.
|
| 10 |
+
- both branches must return a single tensor
|
| 11 |
+
- returned tensor must have the same tensor metadata, e.g. shape and dtype
|
| 12 |
+
- branch function can be free function, nested function, lambda, class methods
|
| 13 |
+
- branch function can not have closure variables
|
| 14 |
+
- no inplace mutations on inputs or global variables
|
| 15 |
+
|
| 16 |
+
This example demonstrates using nested function in cond().
|
| 17 |
+
|
| 18 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
def true_fn(x):
|
| 23 |
+
def inner_true_fn(y):
|
| 24 |
+
return x + y
|
| 25 |
+
|
| 26 |
+
return inner_true_fn(x)
|
| 27 |
+
|
| 28 |
+
def false_fn(x):
|
| 29 |
+
def inner_false_fn(y):
|
| 30 |
+
return x - y
|
| 31 |
+
|
| 32 |
+
return inner_false_fn(x)
|
| 33 |
+
|
| 34 |
+
return cond(x.shape[0] < 10, true_fn, false_fn, [x])
|
| 35 |
+
|
| 36 |
+
example_args = (torch.randn(3),)
|
| 37 |
+
tags = {
|
| 38 |
+
"torch.cond",
|
| 39 |
+
"torch.dynamic-shape",
|
| 40 |
+
}
|
| 41 |
+
model = CondBranchNestedFunction()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondBranchNonlocalVariables(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
|
| 9 |
+
- both branches must take the same args, which must also match the branch args passed to cond.
|
| 10 |
+
- both branches must return a single tensor
|
| 11 |
+
- returned tensor must have the same tensor metadata, e.g. shape and dtype
|
| 12 |
+
- branch function can be free function, nested function, lambda, class methods
|
| 13 |
+
- branch function can not have closure variables
|
| 14 |
+
- no inplace mutations on inputs or global variables
|
| 15 |
+
|
| 16 |
+
This example demonstrates how to rewrite code to avoid capturing closure variables in branch functions.
|
| 17 |
+
|
| 18 |
+
The code below will not work because capturing closure variables is not supported.
|
| 19 |
+
```
|
| 20 |
+
my_tensor_var = x + 100
|
| 21 |
+
my_primitive_var = 3.14
|
| 22 |
+
|
| 23 |
+
def true_fn(y):
|
| 24 |
+
nonlocal my_tensor_var, my_primitive_var
|
| 25 |
+
return y + my_tensor_var + my_primitive_var
|
| 26 |
+
|
| 27 |
+
def false_fn(y):
|
| 28 |
+
nonlocal my_tensor_var, my_primitive_var
|
| 29 |
+
return y - my_tensor_var - my_primitive_var
|
| 30 |
+
|
| 31 |
+
return cond(x.shape[0] > 5, true_fn, false_fn, [x])
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
my_tensor_var = x + 100
|
| 39 |
+
my_primitive_var = 3.14
|
| 40 |
+
|
| 41 |
+
def true_fn(x, y, z):
|
| 42 |
+
return x + y + z
|
| 43 |
+
|
| 44 |
+
def false_fn(x, y, z):
|
| 45 |
+
return x - y - z
|
| 46 |
+
|
| 47 |
+
return cond(
|
| 48 |
+
x.shape[0] > 5,
|
| 49 |
+
true_fn,
|
| 50 |
+
false_fn,
|
| 51 |
+
[x, my_tensor_var, torch.tensor(my_primitive_var)],
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
example_args = (torch.randn(6),)
|
| 55 |
+
tags = {
|
| 56 |
+
"torch.cond",
|
| 57 |
+
"torch.dynamic-shape",
|
| 58 |
+
}
|
| 59 |
+
model = CondBranchNonlocalVariables()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_closed_over_variable.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondClosedOverVariable(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
torch.cond() supports branches closed over arbitrary variables.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, pred, x):
|
| 12 |
+
def true_fn(val):
|
| 13 |
+
return x * 2
|
| 14 |
+
|
| 15 |
+
def false_fn(val):
|
| 16 |
+
return x - 2
|
| 17 |
+
|
| 18 |
+
return cond(pred, true_fn, false_fn, [x + 1])
|
| 19 |
+
|
| 20 |
+
example_args = (torch.tensor(True), torch.randn(3, 2))
|
| 21 |
+
tags = {"torch.cond", "python.closure"}
|
| 22 |
+
model = CondClosedOverVariable()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_operands.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch.export import Dim
|
| 5 |
+
|
| 6 |
+
x = torch.randn(3, 2)
|
| 7 |
+
y = torch.randn(2)
|
| 8 |
+
dim0_x = Dim("dim0_x")
|
| 9 |
+
|
| 10 |
+
class CondOperands(torch.nn.Module):
|
| 11 |
+
"""
|
| 12 |
+
The operands passed to cond() must be:
|
| 13 |
+
- a list of tensors
|
| 14 |
+
- match arguments of `true_fn` and `false_fn`
|
| 15 |
+
|
| 16 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def forward(self, x, y):
|
| 20 |
+
def true_fn(x, y):
|
| 21 |
+
return x + y
|
| 22 |
+
|
| 23 |
+
def false_fn(x, y):
|
| 24 |
+
return x - y
|
| 25 |
+
|
| 26 |
+
return torch.cond(x.shape[0] > 2, true_fn, false_fn, [x, y])
|
| 27 |
+
|
| 28 |
+
example_args = (x, y)
|
| 29 |
+
tags = {
|
| 30 |
+
"torch.cond",
|
| 31 |
+
"torch.dynamic-shape",
|
| 32 |
+
}
|
| 33 |
+
extra_inputs = (torch.randn(2, 2), torch.randn(2))
|
| 34 |
+
dynamic_shapes = {"x": {0: dim0_x}, "y": None}
|
| 35 |
+
model = CondOperands()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/cond_predicate.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondPredicate(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The conditional statement (aka predicate) passed to cond() must be one of the following:
|
| 9 |
+
- torch.Tensor with a single element
|
| 10 |
+
- boolean expression
|
| 11 |
+
|
| 12 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
pred = x.dim() > 2 and x.shape[2] > 10
|
| 17 |
+
|
| 18 |
+
return cond(pred, lambda x: x.cos(), lambda y: y.sin(), [x])
|
| 19 |
+
|
| 20 |
+
example_args = (torch.randn(6, 4, 3),)
|
| 21 |
+
tags = {
|
| 22 |
+
"torch.cond",
|
| 23 |
+
"torch.dynamic-shape",
|
| 24 |
+
}
|
| 25 |
+
model = CondPredicate()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/constrain_as_size_example.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ConstrainAsSizeExample(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
If the value is not known at tracing time, you can provide hint so that we
|
| 8 |
+
can trace further. Please look at torch._check APIs.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
a = x.item()
|
| 13 |
+
torch._check(a >= 0)
|
| 14 |
+
torch._check(a <= 5)
|
| 15 |
+
return torch.zeros((a, 5))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
example_args = (torch.tensor(4),)
|
| 19 |
+
tags = {
|
| 20 |
+
"torch.dynamic-value",
|
| 21 |
+
"torch.escape-hatch",
|
| 22 |
+
}
|
| 23 |
+
model = ConstrainAsSizeExample()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/constrain_as_value_example.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ConstrainAsValueExample(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
If the value is not known at tracing time, you can provide hint so that we
|
| 8 |
+
can trace further. Please look at torch._check API.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x, y):
|
| 12 |
+
a = x.item()
|
| 13 |
+
torch._check(a >= 0)
|
| 14 |
+
torch._check(a <= 5)
|
| 15 |
+
|
| 16 |
+
if a < 6:
|
| 17 |
+
return y.sin()
|
| 18 |
+
return y.cos()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
example_args = (torch.tensor(4), torch.randn(5, 5))
|
| 22 |
+
tags = {
|
| 23 |
+
"torch.dynamic-value",
|
| 24 |
+
"torch.escape-hatch",
|
| 25 |
+
}
|
| 26 |
+
model = ConstrainAsValueExample()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/decorator.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
def test_decorator(func):
|
| 7 |
+
@functools.wraps(func)
|
| 8 |
+
def wrapper(*args, **kwargs):
|
| 9 |
+
return func(*args, **kwargs) + 1
|
| 10 |
+
|
| 11 |
+
return wrapper
|
| 12 |
+
|
| 13 |
+
class Decorator(torch.nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
Decorators calls are inlined into the exported function during tracing.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@test_decorator
|
| 19 |
+
def forward(self, x, y):
|
| 20 |
+
return x + y
|
| 21 |
+
|
| 22 |
+
example_args = (torch.randn(3, 2), torch.randn(3, 2))
|
| 23 |
+
model = Decorator()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dictionary.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class Dictionary(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Dictionary structures are inlined and flattened along tracing.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def forward(self, x, y):
|
| 10 |
+
elements = {}
|
| 11 |
+
elements["x2"] = x * x
|
| 12 |
+
y = y * elements["x2"]
|
| 13 |
+
return {"y": y}
|
| 14 |
+
|
| 15 |
+
example_args = (torch.randn(3, 2), torch.tensor(4))
|
| 16 |
+
tags = {"python.data-structure"}
|
| 17 |
+
model = Dictionary()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_assert.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeAssert(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
A basic usage of python assertion.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def forward(self, x):
|
| 10 |
+
# assertion with error message
|
| 11 |
+
assert x.shape[0] > 2, f"{x.shape[0]} is greater than 2"
|
| 12 |
+
# assertion without error message
|
| 13 |
+
assert x.shape[0] > 1
|
| 14 |
+
return x
|
| 15 |
+
|
| 16 |
+
example_args = (torch.randn(3, 2),)
|
| 17 |
+
tags = {"python.assert"}
|
| 18 |
+
model = DynamicShapeAssert()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeConstructor(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Tensor constructors should be captured with dynamic shape inputs rather
|
| 7 |
+
than being baked in with static shape.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
return torch.zeros(x.shape[0] * 2)
|
| 12 |
+
|
| 13 |
+
example_args = (torch.randn(3, 2),)
|
| 14 |
+
tags = {"torch.dynamic-shape"}
|
| 15 |
+
model = DynamicShapeConstructor()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeIfGuard(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
`if` statement with backed dynamic shape predicate will be specialized into
|
| 7 |
+
one particular branch and generate a guard. However, export will fail if the
|
| 8 |
+
the dimension is marked as dynamic shape from higher level API.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
if x.shape[0] == 3:
|
| 13 |
+
return x.cos()
|
| 14 |
+
|
| 15 |
+
return x.sin()
|
| 16 |
+
|
| 17 |
+
example_args = (torch.randn(3, 2, 2),)
|
| 18 |
+
tags = {"torch.dynamic-shape", "python.control-flow"}
|
| 19 |
+
model = DynamicShapeIfGuard()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_map.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import map
|
| 5 |
+
|
| 6 |
+
class DynamicShapeMap(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
functorch map() maps a function over the first tensor dimension.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, xs, y):
|
| 12 |
+
def body(x, y):
|
| 13 |
+
return x + y
|
| 14 |
+
|
| 15 |
+
return map(body, xs, y)
|
| 16 |
+
|
| 17 |
+
example_args = (torch.randn(3, 2), torch.randn(2))
|
| 18 |
+
tags = {"torch.dynamic-shape", "torch.map"}
|
| 19 |
+
model = DynamicShapeMap()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_round.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch._export.db.case import SupportLevel
|
| 5 |
+
from torch.export import Dim
|
| 6 |
+
|
| 7 |
+
class DynamicShapeRound(torch.nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Calling round on dynamic shapes is not supported.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def forward(self, x):
|
| 13 |
+
return x[: round(x.shape[0] / 2)]
|
| 14 |
+
|
| 15 |
+
x = torch.randn(3, 2)
|
| 16 |
+
dim0_x = Dim("dim0_x")
|
| 17 |
+
example_args = (x,)
|
| 18 |
+
tags = {"torch.dynamic-shape", "python.builtin"}
|
| 19 |
+
support_level = SupportLevel.NOT_SUPPORTED_YET
|
| 20 |
+
dynamic_shapes = {"x": {0: dim0_x}}
|
| 21 |
+
model = DynamicShapeRound()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeSlicing(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Slices with dynamic shape arguments should be captured into the graph
|
| 7 |
+
rather than being baked in.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
return x[: x.shape[0] - 2, x.shape[1] - 1 :: 2]
|
| 12 |
+
|
| 13 |
+
example_args = (torch.randn(3, 2),)
|
| 14 |
+
tags = {"torch.dynamic-shape"}
|
| 15 |
+
model = DynamicShapeSlicing()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_view.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeView(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Dynamic shapes should be propagated to view arguments instead of being
|
| 7 |
+
baked into the exported graph.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
new_x_shape = x.size()[:-1] + (2, 5)
|
| 12 |
+
x = x.view(*new_x_shape)
|
| 13 |
+
return x.permute(0, 2, 1)
|
| 14 |
+
|
| 15 |
+
example_args = (torch.randn(10, 10),)
|
| 16 |
+
tags = {"torch.dynamic-shape"}
|
| 17 |
+
model = DynamicShapeView()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/fn_with_kwargs.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class FnWithKwargs(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Keyword arguments are not supported at the moment.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def forward(self, pos0, tuple0, *myargs, mykw0, **mykwargs):
|
| 10 |
+
out = pos0
|
| 11 |
+
for arg in tuple0:
|
| 12 |
+
out = out * arg
|
| 13 |
+
for arg in myargs:
|
| 14 |
+
out = out * arg
|
| 15 |
+
out = out * mykw0
|
| 16 |
+
out = out * mykwargs["input0"] * mykwargs["input1"]
|
| 17 |
+
return out
|
| 18 |
+
|
| 19 |
+
example_args = (
|
| 20 |
+
torch.randn(4),
|
| 21 |
+
(torch.randn(4), torch.randn(4)),
|
| 22 |
+
*[torch.randn(4), torch.randn(4)]
|
| 23 |
+
)
|
| 24 |
+
example_kwargs = {
|
| 25 |
+
"mykw0": torch.randn(4),
|
| 26 |
+
"input0": torch.randn(4),
|
| 27 |
+
"input1": torch.randn(4),
|
| 28 |
+
}
|
| 29 |
+
tags = {"python.data-structure"}
|
| 30 |
+
model = FnWithKwargs()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/list_contains.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class ListContains(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
List containment relation can be checked on a dynamic shape or constants.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def forward(self, x):
|
| 10 |
+
assert x.size(-1) in [6, 2]
|
| 11 |
+
assert x.size(0) not in [4, 5, 6]
|
| 12 |
+
assert "monkey" not in ["cow", "pig"]
|
| 13 |
+
return x + x
|
| 14 |
+
|
| 15 |
+
example_args = (torch.randn(3, 2),)
|
| 16 |
+
tags = {"torch.dynamic-shape", "python.data-structure", "python.assert"}
|
| 17 |
+
model = ListContains()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/list_unpack.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
class ListUnpack(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
Lists are treated as static construct, therefore unpacking should be
|
| 8 |
+
erased after tracing.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, args: list[torch.Tensor]):
|
| 12 |
+
"""
|
| 13 |
+
Lists are treated as static construct, therefore unpacking should be
|
| 14 |
+
erased after tracing.
|
| 15 |
+
"""
|
| 16 |
+
x, *y = args
|
| 17 |
+
return x + y[0]
|
| 18 |
+
|
| 19 |
+
example_args = ([torch.randn(3, 2), torch.tensor(4), torch.tensor(5)],)
|
| 20 |
+
tags = {"python.control-flow", "python.data-structure"}
|
| 21 |
+
model = ListUnpack()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/model_attr_mutation.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ModelAttrMutation(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
Attribute mutation raises a warning. Covered in the test_export.py test_detect_leak_strict test.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def __init__(self) -> None:
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.attr_list = [torch.randn(3, 2), torch.randn(3, 2)]
|
| 13 |
+
|
| 14 |
+
def recreate_list(self):
|
| 15 |
+
return [torch.zeros(3, 2), torch.zeros(3, 2)]
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
self.attr_list = self.recreate_list()
|
| 19 |
+
return x.sum() + self.attr_list[0].sum()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
example_args = (torch.randn(3, 2),)
|
| 23 |
+
tags = {"python.object-model"}
|
| 24 |
+
model = ModelAttrMutation()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/nested_function.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class NestedFunction(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Nested functions are traced through. Side effects on global captures
|
| 7 |
+
are not supported though.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, a, b):
|
| 11 |
+
x = a + b
|
| 12 |
+
z = a - b
|
| 13 |
+
|
| 14 |
+
def closure(y):
|
| 15 |
+
nonlocal x
|
| 16 |
+
x += 1
|
| 17 |
+
return x * y + z
|
| 18 |
+
|
| 19 |
+
return closure(x)
|
| 20 |
+
|
| 21 |
+
example_args = (torch.randn(3, 2), torch.randn(2))
|
| 22 |
+
tags = {"python.closure"}
|
| 23 |
+
model = NestedFunction()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/null_context_manager.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
class NullContextManager(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Null context manager in Python will be traced out.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
"""
|
| 13 |
+
Null context manager in Python will be traced out.
|
| 14 |
+
"""
|
| 15 |
+
ctx = contextlib.nullcontext()
|
| 16 |
+
with ctx:
|
| 17 |
+
return x.sin() + x.cos()
|
| 18 |
+
|
| 19 |
+
example_args = (torch.randn(3, 2),)
|
| 20 |
+
tags = {"python.context-manager"}
|
| 21 |
+
model = NullContextManager()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/optional_input.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
from torch._export.db.case import SupportLevel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class OptionalInput(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Tracing through optional input is not supported yet
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x, y=torch.randn(2, 3)):
|
| 12 |
+
if y is not None:
|
| 13 |
+
return x + y
|
| 14 |
+
return x
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
example_args = (torch.randn(2, 3),)
|
| 18 |
+
tags = {"python.object-model"}
|
| 19 |
+
support_level = SupportLevel.SUPPORTED
|
| 20 |
+
model = OptionalInput()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/pytree_flatten.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch.utils import _pytree as pytree
|
| 5 |
+
|
| 6 |
+
class PytreeFlatten(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Pytree from PyTorch can be captured by TorchDynamo.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
y, _spec = pytree.tree_flatten(x)
|
| 13 |
+
return y[0] + 1
|
| 14 |
+
|
| 15 |
+
example_args = ({1: torch.randn(3, 2), 2: torch.randn(3, 2)},),
|
| 16 |
+
model = PytreeFlatten()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/scalar_output.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from torch.export import Dim
|
| 5 |
+
|
| 6 |
+
x = torch.randn(3, 2)
|
| 7 |
+
dim1_x = Dim("dim1_x")
|
| 8 |
+
|
| 9 |
+
class ScalarOutput(torch.nn.Module):
|
| 10 |
+
"""
|
| 11 |
+
Returning scalar values from the graph is supported, in addition to Tensor
|
| 12 |
+
outputs. Symbolic shapes are captured and rank is specialized.
|
| 13 |
+
"""
|
| 14 |
+
def __init__(self) -> None:
|
| 15 |
+
super().__init__()
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
return x.shape[1] + 1
|
| 19 |
+
|
| 20 |
+
example_args = (x,)
|
| 21 |
+
tags = {"torch.dynamic-shape"}
|
| 22 |
+
dynamic_shapes = {"x": {1: dim1_x}}
|
| 23 |
+
model = ScalarOutput()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/specialized_attribute.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from enum import Enum
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
class Animal(Enum):
|
| 7 |
+
COW = "moo"
|
| 8 |
+
|
| 9 |
+
class SpecializedAttribute(torch.nn.Module):
|
| 10 |
+
"""
|
| 11 |
+
Model attributes are specialized.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self) -> None:
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.a = "moo"
|
| 17 |
+
self.b = 4
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
if self.a == Animal.COW.value:
|
| 21 |
+
return x * x + self.b
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError("bad")
|
| 24 |
+
|
| 25 |
+
example_args = (torch.randn(3, 2),)
|
| 26 |
+
model = SpecializedAttribute()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/static_for_loop.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class StaticForLoop(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
A for loop with constant number of iterations should be unrolled in the exported graph.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def forward(self, x):
|
| 10 |
+
# constant
|
| 11 |
+
ret = [i + x for i in range(10)]
|
| 12 |
+
return ret
|
| 13 |
+
|
| 14 |
+
example_args = (torch.randn(3, 2),)
|
| 15 |
+
tags = {"python.control-flow"}
|
| 16 |
+
model = StaticForLoop()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/static_if.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class StaticIf(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
`if` statement with static predicate value should be traced through with the
|
| 7 |
+
taken branch.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
if len(x.shape) == 3:
|
| 12 |
+
return x + torch.ones(1, 1, 1)
|
| 13 |
+
|
| 14 |
+
return x
|
| 15 |
+
|
| 16 |
+
example_args = (torch.randn(3, 2, 2),)
|
| 17 |
+
tags = {"python.control-flow"}
|
| 18 |
+
model = StaticIf()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/tensor_setattr.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TensorSetattr(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
setattr() call onto tensors is not supported.
|
| 8 |
+
"""
|
| 9 |
+
def forward(self, x, attr):
|
| 10 |
+
setattr(x, attr, torch.randn(3, 2))
|
| 11 |
+
return x + 4
|
| 12 |
+
|
| 13 |
+
example_args = (torch.randn(3, 2), "attr")
|
| 14 |
+
tags = {"python.builtin"}
|
| 15 |
+
model = TensorSetattr()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/type_reflection_method.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class A:
|
| 5 |
+
@classmethod
|
| 6 |
+
def func(cls, x):
|
| 7 |
+
return 1 + x
|
| 8 |
+
|
| 9 |
+
class TypeReflectionMethod(torch.nn.Module):
|
| 10 |
+
"""
|
| 11 |
+
type() calls on custom objects followed by attribute accesses are not allowed
|
| 12 |
+
due to its overly dynamic nature.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
a = A()
|
| 17 |
+
return type(a).func(x)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
example_args = (torch.randn(3, 4),)
|
| 21 |
+
tags = {"python.builtin"}
|
| 22 |
+
model = TypeReflectionMethod()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/unsupported_operator.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
from torch._export.db.case import SupportLevel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TorchSymMin(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
torch.sym_min operator is not supported in export.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
return x.sum() + torch.sym_min(x.size(0), 100)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
example_args = (torch.randn(3, 2),)
|
| 16 |
+
tags = {"torch.operator"}
|
| 17 |
+
support_level = SupportLevel.NOT_SUPPORTED_YET
|
| 18 |
+
model = TorchSymMin()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/examples/user_input_mutation.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class UserInputMutation(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
Directly mutate user input in forward
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
x.mul_(2)
|
| 12 |
+
return x.cos()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
example_args = (torch.randn(3, 2),)
|
| 16 |
+
tags = {"torch.mutation"}
|
| 17 |
+
model = UserInputMutation()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/gen_example.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch._export.db.examples as examples
|
| 5 |
+
|
| 6 |
+
TEMPLATE = '''import torch
|
| 7 |
+
|
| 8 |
+
def {case_name}(x):
|
| 9 |
+
"""
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
return
|
| 13 |
+
'''
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
assert len(sys.argv) == 2
|
| 17 |
+
root_dir = examples.__name__.replace(".", "/")
|
| 18 |
+
assert os.path.exists(root_dir)
|
| 19 |
+
with open(os.path.join(root_dir, sys.argv[1] + ".py"), "w") as f:
|
| 20 |
+
print("Writing to", f.name, "...")
|
| 21 |
+
f.write(TEMPLATE.format(case_name=sys.argv[1]))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/db/logging.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
def exportdb_error_message(case_name: str) -> str:
|
| 4 |
+
from .examples import all_examples
|
| 5 |
+
from torch._utils_internal import log_export_usage
|
| 6 |
+
|
| 7 |
+
ALL_EXAMPLES = all_examples()
|
| 8 |
+
# Detect whether case_name is really registered in exportdb.
|
| 9 |
+
if case_name in ALL_EXAMPLES:
|
| 10 |
+
url_case_name = case_name.replace("_", "-")
|
| 11 |
+
return f"See {case_name} in exportdb for unsupported case. \
|
| 12 |
+
https://pytorch.org/docs/main/generated/exportdb/index.html#{url_case_name}"
|
| 13 |
+
else:
|
| 14 |
+
log_export_usage(
|
| 15 |
+
event="export.error.casenotregistered",
|
| 16 |
+
message=case_name,
|
| 17 |
+
)
|
| 18 |
+
return f"{case_name} is unsupported."
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_class_if_classified_error(e: Exception) -> Optional[str]:
|
| 22 |
+
"""
|
| 23 |
+
Returns a string case name if the export error e is classified.
|
| 24 |
+
Returns None otherwise.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from torch._dynamo.exc import TorchRuntimeError, Unsupported, UserError
|
| 28 |
+
|
| 29 |
+
ALWAYS_CLASSIFIED = "always_classified"
|
| 30 |
+
DEFAULT_CLASS_SIGIL = "case_name"
|
| 31 |
+
|
| 32 |
+
# add error types that should be classified, along with any attribute name
|
| 33 |
+
# whose presence acts like a sigil to further distinguish which errors of
|
| 34 |
+
# that type should be classified. If the attribute name is None, then the
|
| 35 |
+
# error type is always classified.
|
| 36 |
+
_ALLOW_LIST = {
|
| 37 |
+
Unsupported: DEFAULT_CLASS_SIGIL,
|
| 38 |
+
UserError: DEFAULT_CLASS_SIGIL,
|
| 39 |
+
TorchRuntimeError: None,
|
| 40 |
+
}
|
| 41 |
+
if type(e) in _ALLOW_LIST:
|
| 42 |
+
# pyrefly: ignore [index-error]
|
| 43 |
+
attr_name = _ALLOW_LIST[type(e)]
|
| 44 |
+
if attr_name is None:
|
| 45 |
+
return ALWAYS_CLASSIFIED
|
| 46 |
+
return getattr(e, attr_name, None)
|
| 47 |
+
return None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/error.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ExportErrorType(Enum):
|
| 5 |
+
# User providing invalid inputs to either tracer, or other public facing APIs
|
| 6 |
+
INVALID_INPUT_TYPE = 1
|
| 7 |
+
|
| 8 |
+
# User returning values from their models that we don't support.
|
| 9 |
+
INVALID_OUTPUT_TYPE = 2
|
| 10 |
+
|
| 11 |
+
# Generated IR does not conform to Export IR Specification.
|
| 12 |
+
VIOLATION_OF_SPEC = 3
|
| 13 |
+
|
| 14 |
+
# User's code contains types and functionalities we don't support.
|
| 15 |
+
NOT_SUPPORTED = 4
|
| 16 |
+
|
| 17 |
+
# User's code didn't provide necessary details for us to successfully trace and export.
|
| 18 |
+
# For example, we use a lot of decorators and ask users to annotate their model.
|
| 19 |
+
MISSING_PROPERTY = 5
|
| 20 |
+
|
| 21 |
+
# User is using an API without proper initialization step.
|
| 22 |
+
UNINITIALIZED = 6
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def internal_assert(pred: bool, assert_msg: str) -> None:
|
| 26 |
+
"""
|
| 27 |
+
This is exir's custom assert method. It internally just throws InternalError.
|
| 28 |
+
Note that the sole purpose is to throw our own error while maintaining similar syntax
|
| 29 |
+
as python assert.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
if not pred:
|
| 33 |
+
raise InternalError(assert_msg)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class InternalError(Exception):
|
| 37 |
+
"""
|
| 38 |
+
Raised when an internal invariance is violated in EXIR stack.
|
| 39 |
+
Should hint users to report a bug to dev and expose the original
|
| 40 |
+
error message.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, message: str) -> None:
|
| 44 |
+
super().__init__(message)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ExportError(Exception):
|
| 48 |
+
"""
|
| 49 |
+
This type of exception is raised for errors that are directly caused by the user
|
| 50 |
+
code. In general, user errors happen during model authoring, tracing, using our public
|
| 51 |
+
facing APIs, and writing graph passes.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, error_code: ExportErrorType, message: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import builtins
|
| 3 |
+
import contextlib
|
| 4 |
+
import functools
|
| 5 |
+
import inspect
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import sys
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from collections.abc import Callable, Sequence
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.utils._pytree as pytree
|
| 16 |
+
from torch._dynamo.source import (
|
| 17 |
+
AttrSource,
|
| 18 |
+
GetItemSource,
|
| 19 |
+
LocalSource,
|
| 20 |
+
TensorProperty,
|
| 21 |
+
TensorPropertySource,
|
| 22 |
+
)
|
| 23 |
+
from torch._dynamo.variables.builder import TrackedFake
|
| 24 |
+
from torch._export.passes.lift_constants_pass import ConstantAttrMap
|
| 25 |
+
from torch._export.utils import _fakify_params_buffers
|
| 26 |
+
from torch._guards import Source
|
| 27 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 28 |
+
from torch._library.opaque_object import is_opaque_type
|
| 29 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 30 |
+
from torch.export import Constraint
|
| 31 |
+
from torch.export.dynamic_shapes import (
|
| 32 |
+
_check_dynamic_shapes,
|
| 33 |
+
_combine_args,
|
| 34 |
+
_DimHint,
|
| 35 |
+
_DimHintType,
|
| 36 |
+
_IntWrapper,
|
| 37 |
+
_process_dynamic_shapes,
|
| 38 |
+
_RelaxedConstraint,
|
| 39 |
+
_tree_map_with_path,
|
| 40 |
+
)
|
| 41 |
+
from torch.export.graph_signature import CustomObjArgument
|
| 42 |
+
from torch.fx.experimental import _config as config
|
| 43 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 44 |
+
_find_user_code_frame,
|
| 45 |
+
_suggest_fixes_for_data_dependent_error_non_strict,
|
| 46 |
+
ConstraintViolationError,
|
| 47 |
+
DimDynamic,
|
| 48 |
+
EqualityConstraint,
|
| 49 |
+
GuardOnDataDependentSymNode,
|
| 50 |
+
RelaxedUnspecConstraint,
|
| 51 |
+
ShapeEnv,
|
| 52 |
+
StatelessSymbolicContext,
|
| 53 |
+
SymIntSymbolicContext,
|
| 54 |
+
ValueRanges,
|
| 55 |
+
)
|
| 56 |
+
from torch.utils._pytree import (
|
| 57 |
+
GetAttrKey,
|
| 58 |
+
KeyPath,
|
| 59 |
+
MappingKey,
|
| 60 |
+
SequenceKey,
|
| 61 |
+
tree_map_with_path,
|
| 62 |
+
)
|
| 63 |
+
from torch.utils._sympy.numbers import int_oo
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if TYPE_CHECKING:
|
| 67 |
+
from sympy import Symbol
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
log = logging.getLogger(__name__)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _KeyPath:
|
| 74 |
+
"""
|
| 75 |
+
Wraps `KeyPath` to aid `isinstance` checks.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, kp: KeyPath):
|
| 79 |
+
self.kp = kp
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class _KeyPathTrie:
|
| 83 |
+
"""
|
| 84 |
+
Builds a trie of `KeyPath` prefixes mapping to `Source` leaves.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(self):
|
| 88 |
+
self.root = {}
|
| 89 |
+
|
| 90 |
+
def add(self, kp: KeyPath, src: Source):
|
| 91 |
+
assert len(kp) > 0
|
| 92 |
+
*path, leaf = kp
|
| 93 |
+
node = self.root
|
| 94 |
+
for k in path:
|
| 95 |
+
if k not in node:
|
| 96 |
+
node[k] = {}
|
| 97 |
+
node = node[k]
|
| 98 |
+
node[leaf] = src
|
| 99 |
+
|
| 100 |
+
def get(self, kp: KeyPath) -> tuple[Source, KeyPath]:
|
| 101 |
+
node = self.root
|
| 102 |
+
while not isinstance(node, Source):
|
| 103 |
+
assert len(kp) > 0
|
| 104 |
+
k, *kp = kp # type: ignore[assignment]
|
| 105 |
+
node = node[k]
|
| 106 |
+
# pyrefly: ignore [bad-return]
|
| 107 |
+
return node, kp
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def make_sourced_prefixes(nn_module, args, kwargs) -> _KeyPathTrie:
|
| 111 |
+
kp_args, kp_kwargs = tree_map_with_path(
|
| 112 |
+
lambda kp, _: _KeyPath(kp),
|
| 113 |
+
(tuple(None for _ in args), {k: None for k in kwargs}), # noqa: C420
|
| 114 |
+
)
|
| 115 |
+
kp_combined_args = _combine_args(nn_module, kp_args, kp_kwargs)
|
| 116 |
+
|
| 117 |
+
sourced_prefixes = _KeyPathTrie()
|
| 118 |
+
for name, struct in kp_combined_args.items():
|
| 119 |
+
src = LocalSource(name)
|
| 120 |
+
|
| 121 |
+
if isinstance(struct, _KeyPath):
|
| 122 |
+
sourced_prefixes.add(struct.kp, src)
|
| 123 |
+
elif isinstance(struct, tuple):
|
| 124 |
+
for i, prefix in enumerate(struct):
|
| 125 |
+
assert isinstance(prefix, _KeyPath)
|
| 126 |
+
sourced_prefixes.add(prefix.kp, GetItemSource(src, i))
|
| 127 |
+
elif isinstance(struct, dict):
|
| 128 |
+
for k, prefix in struct.items():
|
| 129 |
+
assert isinstance(prefix, _KeyPath)
|
| 130 |
+
sourced_prefixes.add(prefix.kp, GetItemSource(src, k))
|
| 131 |
+
|
| 132 |
+
return sourced_prefixes
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def key_path_to_source(
|
| 136 |
+
kp: KeyPath, sourced_prefixes: Optional[_KeyPathTrie] = None
|
| 137 |
+
) -> Source:
|
| 138 |
+
"""
|
| 139 |
+
Given a key path, return the source for the key path.
|
| 140 |
+
"""
|
| 141 |
+
if sourced_prefixes is None:
|
| 142 |
+
source: Source = LocalSource("args")
|
| 143 |
+
else:
|
| 144 |
+
source, kp = sourced_prefixes.get(kp)
|
| 145 |
+
|
| 146 |
+
for k in kp:
|
| 147 |
+
if isinstance(k, SequenceKey):
|
| 148 |
+
source = GetItemSource(source, k.idx)
|
| 149 |
+
elif isinstance(k, MappingKey):
|
| 150 |
+
source = GetItemSource(source, k.key)
|
| 151 |
+
elif isinstance(k, GetAttrKey):
|
| 152 |
+
source = AttrSource(source, k.name)
|
| 153 |
+
else:
|
| 154 |
+
raise ValueError(f"Unknown KeyEntry {k}")
|
| 155 |
+
|
| 156 |
+
return source
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _is_constant_argument(t):
|
| 160 |
+
return t is None or isinstance(t, (float, bool, str))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def fakify(
|
| 164 |
+
mode: FakeTensorMode,
|
| 165 |
+
kp: KeyPath,
|
| 166 |
+
t: Any,
|
| 167 |
+
t_constraints: dict[int, dict[int, Constraint]],
|
| 168 |
+
sources: dict[tuple[int, int], list[Source]],
|
| 169 |
+
sourced_prefixes: Optional[_KeyPathTrie] = None,
|
| 170 |
+
):
|
| 171 |
+
source = key_path_to_source(kp, sourced_prefixes=sourced_prefixes)
|
| 172 |
+
if (
|
| 173 |
+
_is_constant_argument(t)
|
| 174 |
+
or isinstance(t, (torch.ScriptObject, torch.nn.Module))
|
| 175 |
+
or is_opaque_type(type(t))
|
| 176 |
+
):
|
| 177 |
+
return t
|
| 178 |
+
|
| 179 |
+
if isinstance(t, _IntWrapper):
|
| 180 |
+
if t.dynamism is not None and t.dynamism.type in ( # type: ignore[union-attr]
|
| 181 |
+
_DimHintType.DYNAMIC,
|
| 182 |
+
_DimHintType.AUTO,
|
| 183 |
+
):
|
| 184 |
+
symint = mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr]
|
| 185 |
+
t.val, source, DimDynamic.DYNAMIC
|
| 186 |
+
)
|
| 187 |
+
context = (
|
| 188 |
+
SymIntSymbolicContext(
|
| 189 |
+
constraint=RelaxedUnspecConstraint(warn_only=False)
|
| 190 |
+
)
|
| 191 |
+
if t.dynamism.type == _DimHintType.DYNAMIC # type: ignore[union-attr]
|
| 192 |
+
else None
|
| 193 |
+
)
|
| 194 |
+
mode.shape_env.tracked_fakes.append( # type: ignore[union-attr]
|
| 195 |
+
TrackedFake(symint, source, context)
|
| 196 |
+
)
|
| 197 |
+
return symint
|
| 198 |
+
else:
|
| 199 |
+
return t.val
|
| 200 |
+
|
| 201 |
+
if not isinstance(t, torch.Tensor):
|
| 202 |
+
raise ValueError(
|
| 203 |
+
f"Unsupported input type {type(t)}. "
|
| 204 |
+
"Export only supports pytree containers of basic types (Tensor, int, float, ...) as input. "
|
| 205 |
+
"To register a custom dataclass, use torch.export.register_dataclass. "
|
| 206 |
+
"To register a custom container type, use torch.utils._pytree.register_pytree_node. "
|
| 207 |
+
"To register a constant input, use torch.utils._pytree.register_constant"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Create symbolic context (handles subclass recursion internally)
|
| 211 |
+
symbolic_context = _create_symbolic_context_for_tensor(
|
| 212 |
+
t, source, t_constraints, sources, mode
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
fake = mode.from_tensor(t, source=source, symbolic_context=symbolic_context)
|
| 216 |
+
mode.shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context)) # type: ignore[union-attr]
|
| 217 |
+
return fake
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _create_symbolic_context_for_tensor(t, source, t_constraints, sources, mode):
|
| 221 |
+
"""Helper function to create symbolic context for a tensor."""
|
| 222 |
+
from torch._dynamo.source import AttrSource
|
| 223 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 224 |
+
DimDynamic,
|
| 225 |
+
RelaxedUnspecConstraint,
|
| 226 |
+
SubclassSymbolicContext,
|
| 227 |
+
)
|
| 228 |
+
from torch.utils._python_dispatch import is_traceable_wrapper_subclass
|
| 229 |
+
|
| 230 |
+
# Common dynamic dimension logic for both regular tensors and subclasses
|
| 231 |
+
n_dims = len(t.shape)
|
| 232 |
+
dynamic_sizes = []
|
| 233 |
+
constraint_sizes = [None] * n_dims
|
| 234 |
+
|
| 235 |
+
for i in range(n_dims):
|
| 236 |
+
if i in getattr(t, "_dynamo_weak_dynamic_indices", {}):
|
| 237 |
+
dynamic_sizes.append(DimDynamic.DYNAMIC)
|
| 238 |
+
elif i in getattr(t, "_dynamo_dynamic_indices", {}):
|
| 239 |
+
# bit annoying, but we need to replicate process in _dynamo/variables/builder.py
|
| 240 |
+
# where a RelaxedUnspecConstraint is created for Dim.DYNAMIC, so constraint violations
|
| 241 |
+
# are raised when specializing.
|
| 242 |
+
dynamic_sizes.append(DimDynamic.DYNAMIC)
|
| 243 |
+
constraint_sizes[i] = RelaxedUnspecConstraint(warn_only=False) # type: ignore[call-overload]
|
| 244 |
+
else:
|
| 245 |
+
dynamic_sizes.append(DimDynamic.STATIC)
|
| 246 |
+
|
| 247 |
+
# Handle nested subclasses
|
| 248 |
+
if is_traceable_wrapper_subclass(t):
|
| 249 |
+
# Get inner contexts recursively
|
| 250 |
+
inner_contexts = {}
|
| 251 |
+
attrs, _ = type(t).__tensor_flatten__(t)
|
| 252 |
+
|
| 253 |
+
# Propagate outer tensor constraints to inner tensors if not already present
|
| 254 |
+
for attr in attrs:
|
| 255 |
+
inner_tensor = getattr(t, attr)
|
| 256 |
+
inner_source = AttrSource(source, attr)
|
| 257 |
+
inner_contexts[attr] = _create_symbolic_context_for_tensor(
|
| 258 |
+
inner_tensor, inner_source, t_constraints, sources, mode
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
symbolic_context = SubclassSymbolicContext(
|
| 262 |
+
dynamic_sizes=dynamic_sizes,
|
| 263 |
+
constraint_sizes=constraint_sizes, # type: ignore[arg-type]
|
| 264 |
+
view_base_context=None,
|
| 265 |
+
tensor_source=source,
|
| 266 |
+
shape_env_to_source_to_symbol_cache={},
|
| 267 |
+
inner_contexts=inner_contexts,
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
symbolic_context: StatelessSymbolicContext = ( # type: ignore[no-redef]
|
| 271 |
+
StatelessSymbolicContext(
|
| 272 |
+
dynamic_sizes=dynamic_sizes,
|
| 273 |
+
constraint_sizes=constraint_sizes, # type: ignore[arg-type]
|
| 274 |
+
)
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
# Apply constraints (common logic)
|
| 278 |
+
t_id = id(t)
|
| 279 |
+
assert mode.shape_env is not None
|
| 280 |
+
if t_id in t_constraints:
|
| 281 |
+
for i, constraint in t_constraints[t_id].items():
|
| 282 |
+
src = TensorPropertySource(base=source, prop=TensorProperty.SIZE, idx=i)
|
| 283 |
+
sources[(t_id, i)].append(src)
|
| 284 |
+
if isinstance(constraint, _RelaxedConstraint):
|
| 285 |
+
continue
|
| 286 |
+
symbolic_context.constraint_sizes[i] = constraint.constraint_range
|
| 287 |
+
mode.shape_env.source_name_to_debug_name[src.name] = constraint.name # type: ignore[assignment]
|
| 288 |
+
|
| 289 |
+
return symbolic_context
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _is_unbacked_symint(symbol):
|
| 293 |
+
if not isinstance(symbol, torch.SymInt):
|
| 294 |
+
return False
|
| 295 |
+
|
| 296 |
+
return symbol.node.shape_env.is_unbacked_symint(symbol.node.expr)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _tensor_min_max(*args, real_callable, tensor_callable, **kwargs):
|
| 300 |
+
"""
|
| 301 |
+
This logic is replicated from dynamo/variables/builtin.py
|
| 302 |
+
"""
|
| 303 |
+
if len(args) == 2 and not kwargs:
|
| 304 |
+
arg1, arg2 = args
|
| 305 |
+
|
| 306 |
+
# Case 1: Both are tensors
|
| 307 |
+
if isinstance(arg1, torch.Tensor) and isinstance(arg2, torch.Tensor):
|
| 308 |
+
return tensor_callable(arg1, arg2)
|
| 309 |
+
|
| 310 |
+
# Case 2: One tensor, one scalar
|
| 311 |
+
elif isinstance(arg1, torch.Tensor) or isinstance(arg2, torch.Tensor):
|
| 312 |
+
if not isinstance(arg1, torch.Tensor):
|
| 313 |
+
arg1, arg2 = arg2, arg1
|
| 314 |
+
|
| 315 |
+
if isinstance(arg2, (int, float)):
|
| 316 |
+
kwarg = {"min" if tensor_callable is torch.maximum else "max": arg2}
|
| 317 |
+
return torch.clamp(arg1, **kwarg) # type: ignore[call-overload]
|
| 318 |
+
else:
|
| 319 |
+
return real_callable(arg1, arg2)
|
| 320 |
+
|
| 321 |
+
# Case 3: SymInts
|
| 322 |
+
elif isinstance(arg1, torch.SymInt) or isinstance(arg2, torch.SymInt):
|
| 323 |
+
return (
|
| 324 |
+
torch.sym_max(arg1, arg2)
|
| 325 |
+
if tensor_callable is torch.maximum
|
| 326 |
+
else torch.sym_min(arg1, arg2)
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
# Fallback
|
| 330 |
+
else:
|
| 331 |
+
return real_callable(arg1, arg2)
|
| 332 |
+
|
| 333 |
+
# Single iterable argument handling
|
| 334 |
+
if len(args) == 1 and not kwargs:
|
| 335 |
+
iterable = args[0]
|
| 336 |
+
|
| 337 |
+
if isinstance(iterable, torch.Tensor):
|
| 338 |
+
return tensor_callable(iterable)
|
| 339 |
+
try:
|
| 340 |
+
iterator = iter(iterable)
|
| 341 |
+
except TypeError:
|
| 342 |
+
pass
|
| 343 |
+
else:
|
| 344 |
+
items = list(iterator)
|
| 345 |
+
if not items:
|
| 346 |
+
raise ValueError(f"{real_callable.__name__}() arg is an empty sequence")
|
| 347 |
+
|
| 348 |
+
return functools.reduce(
|
| 349 |
+
lambda a, b: _tensor_min_max(
|
| 350 |
+
a, b, real_callable=real_callable, tensor_callable=tensor_callable
|
| 351 |
+
),
|
| 352 |
+
items,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# Fallback to original callable
|
| 356 |
+
return real_callable(*args, **kwargs)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@contextmanager
|
| 360 |
+
def _override_builtin_ops():
|
| 361 |
+
original_max = builtins.max
|
| 362 |
+
original_min = builtins.min
|
| 363 |
+
original_pow = math.pow
|
| 364 |
+
|
| 365 |
+
# pyrefly: ignore [bad-assignment]
|
| 366 |
+
builtins.max = functools.partial(
|
| 367 |
+
_tensor_min_max, real_callable=original_max, tensor_callable=torch.maximum
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
# pyrefly: ignore [bad-assignment]
|
| 371 |
+
builtins.min = functools.partial(
|
| 372 |
+
_tensor_min_max, real_callable=original_min, tensor_callable=torch.minimum
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
math.pow = lambda x, y: x**y # type: ignore[operator]
|
| 376 |
+
|
| 377 |
+
try:
|
| 378 |
+
yield
|
| 379 |
+
finally:
|
| 380 |
+
builtins.max = original_max
|
| 381 |
+
builtins.min = original_min
|
| 382 |
+
math.pow = original_pow
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def make_fake_inputs(
|
| 386 |
+
nn_module,
|
| 387 |
+
args,
|
| 388 |
+
kwargs,
|
| 389 |
+
dynamic_shapes,
|
| 390 |
+
prefer_deferred_runtime_asserts_over_guards=False,
|
| 391 |
+
):
|
| 392 |
+
"""
|
| 393 |
+
Given an nn module, example inputs, and constraints, return a new fake mode,
|
| 394 |
+
fake inputs created in that mode whose dynamic shape dimensions are constrained
|
| 395 |
+
by the given ranges, and sources for pairs of dynamic shape dimensions that are
|
| 396 |
+
constrained to be equal.
|
| 397 |
+
"""
|
| 398 |
+
# TODO(avik): refactor Dynamo to avoid duplication of the following code
|
| 399 |
+
# between non-strict and strict.
|
| 400 |
+
# Specifically, here (non-strict) we do the following pre-tracing steps:
|
| 401 |
+
# - Fakify inputs.
|
| 402 |
+
# - Process input shape equalities.
|
| 403 |
+
# In strict, these steps are spread across multiple files:
|
| 404 |
+
# - output_graph.py fakifies inputs.
|
| 405 |
+
# - [post-tracing] guards.py processes input shape equalities.
|
| 406 |
+
import torch._functorch.config as _config
|
| 407 |
+
|
| 408 |
+
# Map ints to a wrapper structure to help us mark it as dynamic, if it is
|
| 409 |
+
# dynamic. We will unwrap ints in fakify later.
|
| 410 |
+
args, kwargs = pytree.tree_map_only(int, lambda a: _IntWrapper(a), (args, kwargs))
|
| 411 |
+
|
| 412 |
+
combined_args = _combine_args(nn_module, args, kwargs)
|
| 413 |
+
_check_dynamic_shapes(combined_args, dynamic_shapes)
|
| 414 |
+
constraints = _process_dynamic_shapes(combined_args, dynamic_shapes)
|
| 415 |
+
t_constraints: dict[int, dict[int, Constraint]] = defaultdict(dict)
|
| 416 |
+
for constraint in constraints:
|
| 417 |
+
t_constraints[constraint.t_id][constraint.dim] = constraint
|
| 418 |
+
|
| 419 |
+
context = torch._guards.TracingContext.try_get()
|
| 420 |
+
if context is not None:
|
| 421 |
+
# This occurs when we are exporting within dynamo. There already exists
|
| 422 |
+
# a toplevel TracingContext with a fake mode, so we do not want to
|
| 423 |
+
# create another fake mode.
|
| 424 |
+
fake_mode = context.fake_mode
|
| 425 |
+
assert fake_mode is not None
|
| 426 |
+
else:
|
| 427 |
+
if isinstance(nn_module.forward, functools.partial):
|
| 428 |
+
# functools handles nesting by itself, no need to recurse
|
| 429 |
+
code = nn_module.forward.func.__code__
|
| 430 |
+
elif (
|
| 431 |
+
sys.version_info >= (3, 14)
|
| 432 |
+
and (fwd := getattr(nn_module.forward, "__func__", None))
|
| 433 |
+
and isinstance(fwd, functools.partial)
|
| 434 |
+
):
|
| 435 |
+
# functools.partial is now a method descriptor:
|
| 436 |
+
# https://docs.python.org/3/whatsnew/3.14.html#changes-in-the-python-api
|
| 437 |
+
code = fwd.func.__code__
|
| 438 |
+
else:
|
| 439 |
+
code = nn_module.forward.__code__
|
| 440 |
+
co_fields = {
|
| 441 |
+
"co_name": code.co_name,
|
| 442 |
+
"co_filename": code.co_filename,
|
| 443 |
+
"co_firstlineno": code.co_firstlineno,
|
| 444 |
+
}
|
| 445 |
+
with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False):
|
| 446 |
+
fake_mode = FakeTensorMode(
|
| 447 |
+
shape_env=ShapeEnv(
|
| 448 |
+
tracked_fakes=[],
|
| 449 |
+
co_fields=co_fields,
|
| 450 |
+
prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards,
|
| 451 |
+
trace_asserts=True,
|
| 452 |
+
),
|
| 453 |
+
allow_non_fake_inputs=True,
|
| 454 |
+
export=True,
|
| 455 |
+
)
|
| 456 |
+
if fake_mode.shape_env is None or fake_mode.shape_env.tracked_fakes is None:
|
| 457 |
+
raise ValueError(
|
| 458 |
+
"Detected fake_mode does not have a shape_env with tracked fakes. "
|
| 459 |
+
"If you constructed the module under a FakeTensorMode, "
|
| 460 |
+
"please initialize it like: FakeTensorMode(shape_env=ShapeEnv(tracked_fakes=[]))"
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
with fake_mode:
|
| 464 |
+
original_signature = inspect.signature(nn_module.forward)
|
| 465 |
+
sources: dict[tuple[int, int], list[Source]] = defaultdict(list)
|
| 466 |
+
sourced_prefixes = make_sourced_prefixes(nn_module, args, kwargs)
|
| 467 |
+
fake_args, fake_kwargs = tree_map_with_path(
|
| 468 |
+
lambda kp, val: fakify(
|
| 469 |
+
fake_mode,
|
| 470 |
+
kp,
|
| 471 |
+
val,
|
| 472 |
+
t_constraints,
|
| 473 |
+
sources,
|
| 474 |
+
sourced_prefixes=sourced_prefixes,
|
| 475 |
+
),
|
| 476 |
+
(args, kwargs),
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
names: dict[str, tuple[int, int]] = {}
|
| 480 |
+
source_pairs: list[tuple[Source, Source]] = []
|
| 481 |
+
derived_equalities: list[tuple[Source, Union[Source, Symbol], Callable]] = []
|
| 482 |
+
phantom_symbols: dict[str, Symbol] = {}
|
| 483 |
+
relaxed_sources: set[Source] = set()
|
| 484 |
+
for constraint in constraints:
|
| 485 |
+
torch.export.dynamic_shapes._process_equalities(
|
| 486 |
+
constraint,
|
| 487 |
+
lambda t_id, dim: sources[(t_id, dim)],
|
| 488 |
+
fake_mode.shape_env,
|
| 489 |
+
names,
|
| 490 |
+
source_pairs,
|
| 491 |
+
derived_equalities,
|
| 492 |
+
phantom_symbols,
|
| 493 |
+
relaxed_sources,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
equalities_inputs = EqualityConstraint(
|
| 497 |
+
source_pairs=source_pairs,
|
| 498 |
+
derived_equalities=derived_equalities,
|
| 499 |
+
phantom_symbols=list(phantom_symbols.values()),
|
| 500 |
+
relaxed_sources=relaxed_sources,
|
| 501 |
+
warn_only=False,
|
| 502 |
+
)
|
| 503 |
+
return (
|
| 504 |
+
fake_mode,
|
| 505 |
+
fake_args,
|
| 506 |
+
fake_kwargs,
|
| 507 |
+
equalities_inputs,
|
| 508 |
+
original_signature,
|
| 509 |
+
dynamic_shapes,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _flatten_dynamic_shapes(
|
| 514 |
+
combined_args: dict[str, Any],
|
| 515 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any]],
|
| 516 |
+
) -> list[Any]:
|
| 517 |
+
flat_shapes = []
|
| 518 |
+
|
| 519 |
+
def _tree_map_helper(path, t, shape):
|
| 520 |
+
nonlocal flat_shapes
|
| 521 |
+
flat_shapes.append(shape)
|
| 522 |
+
|
| 523 |
+
_tree_map_with_path(_tree_map_helper, combined_args, dynamic_shapes)
|
| 524 |
+
return flat_shapes
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def _clean_dynamic_markers(tensor: torch.Tensor) -> None:
|
| 528 |
+
for attr in [
|
| 529 |
+
"_dynamo_weak_dynamic_indices",
|
| 530 |
+
"_dynamo_dynamic_indices",
|
| 531 |
+
"_dynamo_dynamic_range",
|
| 532 |
+
"_dynamo_static_indices",
|
| 533 |
+
"_dynamo_unbacked_indices",
|
| 534 |
+
]:
|
| 535 |
+
if hasattr(tensor, attr):
|
| 536 |
+
delattr(tensor, attr)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def produce_guards_and_solve_constraints(
|
| 540 |
+
fake_mode: FakeTensorMode,
|
| 541 |
+
gm: torch.fx.GraphModule,
|
| 542 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
|
| 543 |
+
equalities_inputs: EqualityConstraint,
|
| 544 |
+
original_signature: inspect.Signature,
|
| 545 |
+
):
|
| 546 |
+
"""
|
| 547 |
+
Given a fake mode, sources pairs corresponding to equal dynamic shape dimensions,
|
| 548 |
+
and a graph module, produce guards on the fake mode's shape env (raising constraint
|
| 549 |
+
violations if any), solve (to suggest simplifications or fixes).
|
| 550 |
+
Dynamo already performs this, so this is for non-strict mode.
|
| 551 |
+
|
| 552 |
+
Additional inputs:
|
| 553 |
+
equalities_inputs: the equality constraints to use for guards
|
| 554 |
+
original_signature: the signature of the forward method
|
| 555 |
+
"""
|
| 556 |
+
shape_env = fake_mode.shape_env
|
| 557 |
+
assert shape_env is not None
|
| 558 |
+
assert shape_env.tracked_fakes is not None
|
| 559 |
+
|
| 560 |
+
placeholders = [tf.fake for tf in shape_env.tracked_fakes]
|
| 561 |
+
sources = [tf.source for tf in shape_env.tracked_fakes]
|
| 562 |
+
input_contexts = [tf.symbolic_context for tf in shape_env.tracked_fakes]
|
| 563 |
+
constraint_violation_error = None
|
| 564 |
+
try:
|
| 565 |
+
shape_env.produce_guards(
|
| 566 |
+
placeholders,
|
| 567 |
+
sources,
|
| 568 |
+
input_contexts=input_contexts,
|
| 569 |
+
equalities_inputs=equalities_inputs,
|
| 570 |
+
ignore_static=False,
|
| 571 |
+
)
|
| 572 |
+
except ConstraintViolationError as e:
|
| 573 |
+
constraint_violation_error = e
|
| 574 |
+
|
| 575 |
+
shape_env.frozen = True
|
| 576 |
+
dim_constraints = shape_env.dim_constraints
|
| 577 |
+
if dim_constraints is None:
|
| 578 |
+
# Expected when shape_env.produce_guards throws an early constraint violation error.
|
| 579 |
+
# There is nothing to solve for in this case.
|
| 580 |
+
# TODO(avik): Maybe record the constraint violation error instead and replay later?
|
| 581 |
+
assert constraint_violation_error
|
| 582 |
+
raise constraint_violation_error
|
| 583 |
+
dim_constraints.solve()
|
| 584 |
+
forced_specializations = dim_constraints.forced_specializations()
|
| 585 |
+
|
| 586 |
+
msg = dim_constraints.prettify_results(
|
| 587 |
+
original_signature,
|
| 588 |
+
dynamic_shapes, # type: ignore[arg-type]
|
| 589 |
+
constraint_violation_error,
|
| 590 |
+
forced_specializations, # type: ignore[arg-type]
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
if constraint_violation_error:
|
| 594 |
+
if constraint_violation_error.args:
|
| 595 |
+
constraint_violation_error.args = (
|
| 596 |
+
constraint_violation_error.args[0] + msg,
|
| 597 |
+
)
|
| 598 |
+
else:
|
| 599 |
+
constraint_violation_error.args = (msg,)
|
| 600 |
+
elif forced_specializations:
|
| 601 |
+
constraint_violation_error = ConstraintViolationError(msg)
|
| 602 |
+
if constraint_violation_error:
|
| 603 |
+
raise constraint_violation_error
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def is_int(x: object) -> bool:
|
| 607 |
+
return isinstance(x, int) or (isinstance(x, torch.SymInt) and x.node.expr.is_number)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def _constrain_user_specified_dimhint_range(
|
| 611 |
+
symint: torch.SymInt,
|
| 612 |
+
hint: int,
|
| 613 |
+
dim: _DimHint,
|
| 614 |
+
range_constraints,
|
| 615 |
+
shape_env,
|
| 616 |
+
keypath: KeyPath,
|
| 617 |
+
i: Optional[int] = None,
|
| 618 |
+
) -> Optional[str]:
|
| 619 |
+
trace_vr = (
|
| 620 |
+
range_constraints[symint.node.expr]
|
| 621 |
+
if not is_int(symint)
|
| 622 |
+
else ValueRanges(int(symint), int(symint))
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
# warn on 0/1 specialization for Dim.AUTO; not an actual error
|
| 626 |
+
if dim.type == _DimHintType.AUTO and trace_vr.is_singleton() and hint in (0, 1):
|
| 627 |
+
pathstr = f"inputs{pytree.keystr(keypath)}"
|
| 628 |
+
if i is not None:
|
| 629 |
+
pathstr += f".shape[{i}]"
|
| 630 |
+
msg = (
|
| 631 |
+
f"dimension {pathstr} 0/1 specialized; Dim.AUTO was specified along "
|
| 632 |
+
+ f"with a sample input with hint = {hint}."
|
| 633 |
+
)
|
| 634 |
+
log.warning(msg)
|
| 635 |
+
|
| 636 |
+
try:
|
| 637 |
+
user_vr = ValueRanges(
|
| 638 |
+
lower=0 if dim.min is None else dim.min,
|
| 639 |
+
upper=int_oo if dim.max is None else dim.max,
|
| 640 |
+
)
|
| 641 |
+
if is_int(symint):
|
| 642 |
+
out_vr = trace_vr & user_vr
|
| 643 |
+
else:
|
| 644 |
+
range_constraints[symint.node.expr] &= user_vr
|
| 645 |
+
shape_env.var_to_range[symint.node._expr] &= user_vr
|
| 646 |
+
out_vr = range_constraints[symint.node.expr]
|
| 647 |
+
|
| 648 |
+
# check for Dim.DYNAMIC specializations; special case error message on 0/1
|
| 649 |
+
if dim.type == _DimHintType.DYNAMIC and out_vr.is_singleton():
|
| 650 |
+
path = f"inputs{pytree.keystr(keypath)}"
|
| 651 |
+
if i is not None:
|
| 652 |
+
path += f".shape[{i}]"
|
| 653 |
+
if (
|
| 654 |
+
trace_vr.is_singleton()
|
| 655 |
+
and hint in (0, 1)
|
| 656 |
+
and not torch.fx.experimental._config.backed_size_oblivious
|
| 657 |
+
):
|
| 658 |
+
msg = (
|
| 659 |
+
f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), "
|
| 660 |
+
f"but export 0/1 specialized due to hint of {hint} for dimension {path}."
|
| 661 |
+
)
|
| 662 |
+
else:
|
| 663 |
+
msg = (
|
| 664 |
+
f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), "
|
| 665 |
+
f"but tracing inferred a static shape of {out_vr.lower} for dimension {path}."
|
| 666 |
+
)
|
| 667 |
+
return msg
|
| 668 |
+
|
| 669 |
+
except torch.utils._sympy.value_ranges.ValueRangeError:
|
| 670 |
+
path = f"inputs{pytree.keystr(keypath)}"
|
| 671 |
+
if i is not None:
|
| 672 |
+
path += f".shape[{i}]"
|
| 673 |
+
msg = (
|
| 674 |
+
f"- Received user-specified min/max range of [{dim.min}, {dim.max}], "
|
| 675 |
+
f"conflicting with the inferred min/max range of [{trace_vr.lower}, {trace_vr.upper}], "
|
| 676 |
+
f"for {path}."
|
| 677 |
+
)
|
| 678 |
+
return msg
|
| 679 |
+
|
| 680 |
+
return None
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def make_constraints(
|
| 684 |
+
fake_mode: FakeTensorMode,
|
| 685 |
+
gm: torch.fx.GraphModule,
|
| 686 |
+
combined_args: dict[str, Any],
|
| 687 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
|
| 688 |
+
num_lifted_inputs: int,
|
| 689 |
+
):
|
| 690 |
+
"""
|
| 691 |
+
Given a fake mode's shape env and user-specified dynamic shapes,
|
| 692 |
+
return the resulting range constraints and equality constraints.
|
| 693 |
+
|
| 694 |
+
Additional args:
|
| 695 |
+
num_lifted_inputs: the number of non-user-input placeholder nodes in the graph
|
| 696 |
+
(used only to enumerate the user-input nodes)
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
shape_env = fake_mode.shape_env
|
| 700 |
+
assert shape_env is not None
|
| 701 |
+
inline_constraints = gm.meta.get("inline_constraints", [])
|
| 702 |
+
range_constraints = defaultdict(lambda: ValueRanges(0, int_oo)) | inline_constraints
|
| 703 |
+
if not dynamic_shapes:
|
| 704 |
+
return dict(range_constraints)
|
| 705 |
+
|
| 706 |
+
# clean up dynamic markers from tensors
|
| 707 |
+
flat_paths, flat_args = zip(*pytree.tree_flatten_with_path(combined_args)[0])
|
| 708 |
+
for arg in flat_args:
|
| 709 |
+
if isinstance(arg, torch.Tensor):
|
| 710 |
+
_clean_dynamic_markers(arg)
|
| 711 |
+
|
| 712 |
+
# get individual dynamic shapes spec for each input
|
| 713 |
+
if not isinstance(dynamic_shapes, dict):
|
| 714 |
+
assert isinstance(dynamic_shapes, (tuple, list))
|
| 715 |
+
combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc]
|
| 716 |
+
flat_dynamic_shapes = _flatten_dynamic_shapes(combined_args, dynamic_shapes)
|
| 717 |
+
|
| 718 |
+
# check number of shapes vs. number of inputs
|
| 719 |
+
num_placeholders = [node.op == "placeholder" for node in gm.graph.nodes].count(True)
|
| 720 |
+
assert len(flat_dynamic_shapes) == num_placeholders - num_lifted_inputs
|
| 721 |
+
|
| 722 |
+
free_symbols = set()
|
| 723 |
+
range_violations = []
|
| 724 |
+
for input_index, node in enumerate(gm.graph.nodes):
|
| 725 |
+
meta_val = node.meta.get("val")
|
| 726 |
+
|
| 727 |
+
if (
|
| 728 |
+
input_index < num_lifted_inputs
|
| 729 |
+
or node.op != "placeholder"
|
| 730 |
+
or meta_val is None
|
| 731 |
+
):
|
| 732 |
+
continue
|
| 733 |
+
|
| 734 |
+
elif _is_constant_argument(meta_val) or isinstance(meta_val, CustomObjArgument):
|
| 735 |
+
continue
|
| 736 |
+
|
| 737 |
+
shape_spec = flat_dynamic_shapes[input_index - num_lifted_inputs]
|
| 738 |
+
keypath = flat_paths[input_index - num_lifted_inputs]
|
| 739 |
+
flat_arg = flat_args[input_index - num_lifted_inputs]
|
| 740 |
+
|
| 741 |
+
if isinstance(meta_val, int) or (
|
| 742 |
+
isinstance(meta_val, torch.SymInt) and meta_val.node.expr.is_number
|
| 743 |
+
):
|
| 744 |
+
pass
|
| 745 |
+
|
| 746 |
+
elif isinstance(meta_val, torch.SymInt):
|
| 747 |
+
if shape_spec is not None and isinstance(shape_spec, _DimHint):
|
| 748 |
+
hint = flat_arg
|
| 749 |
+
range_constraints[meta_val.node.expr] &= shape_env.bound_sympy(
|
| 750 |
+
meta_val.node._expr
|
| 751 |
+
)
|
| 752 |
+
violation = _constrain_user_specified_dimhint_range(
|
| 753 |
+
meta_val,
|
| 754 |
+
hint,
|
| 755 |
+
shape_spec,
|
| 756 |
+
range_constraints,
|
| 757 |
+
shape_env,
|
| 758 |
+
keypath,
|
| 759 |
+
None,
|
| 760 |
+
)
|
| 761 |
+
if violation:
|
| 762 |
+
range_violations.append(violation)
|
| 763 |
+
else:
|
| 764 |
+
raise RuntimeError("nyi")
|
| 765 |
+
free_symbols.update(meta_val.node.expr.free_symbols)
|
| 766 |
+
|
| 767 |
+
elif isinstance(meta_val, torch.Tensor):
|
| 768 |
+
for i, d in enumerate(node.meta["val"].shape):
|
| 769 |
+
dim = None
|
| 770 |
+
if isinstance(shape_spec, (list, tuple)):
|
| 771 |
+
dim = shape_spec[i]
|
| 772 |
+
elif isinstance(shape_spec, dict):
|
| 773 |
+
dim = shape_spec.get(i)
|
| 774 |
+
if not is_int(d):
|
| 775 |
+
# Compute the range constraint for the symbolic expression corresponding
|
| 776 |
+
# to this shape dimension and store it.
|
| 777 |
+
if dim is None or isinstance(dim, _DimHint):
|
| 778 |
+
range_constraints[d.node.expr] &= shape_env.bound_sympy(
|
| 779 |
+
d.node.expr
|
| 780 |
+
)
|
| 781 |
+
else:
|
| 782 |
+
range_constraints[d.node.expr] &= ValueRanges(
|
| 783 |
+
lower=dim.min, upper=dim.max
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
free_symbols.update(d.node.expr.free_symbols)
|
| 787 |
+
|
| 788 |
+
# check user-specified min/max range for DimHints;
|
| 789 |
+
# we might want to do this even if model tracing inferred a static dimension.
|
| 790 |
+
if isinstance(dim, _DimHint):
|
| 791 |
+
hint = flat_arg.shape[i]
|
| 792 |
+
violation = _constrain_user_specified_dimhint_range(
|
| 793 |
+
d, hint, dim, range_constraints, shape_env, keypath, i
|
| 794 |
+
)
|
| 795 |
+
if violation:
|
| 796 |
+
range_violations.append(violation)
|
| 797 |
+
else:
|
| 798 |
+
raise RuntimeError(f"Unfamiliar meta val: {meta_val}")
|
| 799 |
+
|
| 800 |
+
if range_violations:
|
| 801 |
+
prefix = "Found the following conflicts between user-specified ranges and inferred ranges from model tracing:\n"
|
| 802 |
+
raise ValueError(prefix + "\n".join(range_violations))
|
| 803 |
+
|
| 804 |
+
for symbol in free_symbols:
|
| 805 |
+
if symbol not in range_constraints:
|
| 806 |
+
# Placeholders can have symbolic shapes that are derived expressions.
|
| 807 |
+
# The above code will record direct range constraints for them
|
| 808 |
+
# so that we can do runtime assertions. In addition, for serde checks
|
| 809 |
+
# we want to record range constraints for their root symbols.
|
| 810 |
+
range_constraints[symbol] = shape_env.var_to_range[symbol]
|
| 811 |
+
|
| 812 |
+
return dict(range_constraints)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def _gather_constant_attrs(m: torch.nn.Module) -> ConstantAttrMap:
|
| 816 |
+
"""Search the module hierarchy, gathering up all tensor and ScriptObject constants.
|
| 817 |
+
|
| 818 |
+
Returns a dictionary mapping hash(value) to the name of the constant. We
|
| 819 |
+
have to abuse `hash` here unfortunately, see: [ScriptObject hash].
|
| 820 |
+
"""
|
| 821 |
+
constants = ConstantAttrMap()
|
| 822 |
+
buffers_parameters = set(m.buffers())
|
| 823 |
+
buffers_parameters.update(m.parameters())
|
| 824 |
+
|
| 825 |
+
def inner(m: torch.nn.Module, prefix_atoms: list[str], constants):
|
| 826 |
+
for k, v in m.__dict__.items():
|
| 827 |
+
if isinstance(
|
| 828 |
+
v,
|
| 829 |
+
(
|
| 830 |
+
torch.Tensor,
|
| 831 |
+
torch.ScriptObject,
|
| 832 |
+
FakeScriptObject,
|
| 833 |
+
),
|
| 834 |
+
):
|
| 835 |
+
if v in buffers_parameters:
|
| 836 |
+
# filter out buffers and parameters, leaving only constants
|
| 837 |
+
continue
|
| 838 |
+
|
| 839 |
+
fqn = ".".join(prefix_atoms + [k])
|
| 840 |
+
constants.add(v, fqn)
|
| 841 |
+
for k, v in m.named_children():
|
| 842 |
+
inner(v, prefix_atoms + [k], constants)
|
| 843 |
+
|
| 844 |
+
inner(m, [], constants)
|
| 845 |
+
return constants
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
def _get_graph_inputs_of_type_nn_module(
|
| 849 |
+
args: Optional[tuple[tuple[Any], dict[Any, Any]]],
|
| 850 |
+
) -> set[type[torch.nn.Module]]:
|
| 851 |
+
if args is None:
|
| 852 |
+
return set()
|
| 853 |
+
module_types = set()
|
| 854 |
+
for arg in pytree.tree_leaves(args):
|
| 855 |
+
if isinstance(arg, torch.nn.Module):
|
| 856 |
+
module_types.add(type(arg))
|
| 857 |
+
return module_types
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def _enter_enable_graph_inputs_of_type_nn_module(
|
| 861 |
+
module_types: set[type[torch.nn.Module]],
|
| 862 |
+
) -> None:
|
| 863 |
+
for t in module_types:
|
| 864 |
+
torch._export.utils.register_module_as_pytree_input_node(t)
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def _exit_enable_graph_inputs_of_type_nn_module(
|
| 868 |
+
module_types: set[type[torch.nn.Module]],
|
| 869 |
+
) -> None:
|
| 870 |
+
for t in module_types:
|
| 871 |
+
torch._export.utils.deregister_module_as_pytree_input_node(t)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@contextlib.contextmanager
|
| 875 |
+
def _enable_graph_inputs_of_type_nn_module(
|
| 876 |
+
args: Optional[tuple[tuple[Any], dict[Any, Any]]],
|
| 877 |
+
):
|
| 878 |
+
if args is None:
|
| 879 |
+
yield
|
| 880 |
+
return
|
| 881 |
+
|
| 882 |
+
module_types = _get_graph_inputs_of_type_nn_module(args)
|
| 883 |
+
_enter_enable_graph_inputs_of_type_nn_module(module_types)
|
| 884 |
+
try:
|
| 885 |
+
yield
|
| 886 |
+
finally:
|
| 887 |
+
_exit_enable_graph_inputs_of_type_nn_module(module_types)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
@contextlib.contextmanager
|
| 891 |
+
def _fakify_module_inputs(
|
| 892 |
+
args: tuple[Any],
|
| 893 |
+
kwargs: dict[Any, Any],
|
| 894 |
+
fake_mode: torch._subclasses.fake_tensor.FakeTensorMode,
|
| 895 |
+
):
|
| 896 |
+
# This context manager is used to fakify module inputs.
|
| 897 |
+
# Inputs:
|
| 898 |
+
# args, kwargs: the args and kwargs containing module inputs that haven't been fakified.
|
| 899 |
+
# fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors.
|
| 900 |
+
|
| 901 |
+
ctxs = [_enable_graph_inputs_of_type_nn_module((args, kwargs))]
|
| 902 |
+
for arg in pytree.tree_leaves((args, kwargs)):
|
| 903 |
+
if isinstance(arg, torch.nn.Module):
|
| 904 |
+
fake_params_buffers = _fakify_params_buffers(fake_mode, arg)
|
| 905 |
+
ctxs.append(
|
| 906 |
+
torch.nn.utils.stateless._reparametrize_module(
|
| 907 |
+
arg,
|
| 908 |
+
fake_params_buffers,
|
| 909 |
+
tie_weights=True,
|
| 910 |
+
strict=True,
|
| 911 |
+
stack_weights=True,
|
| 912 |
+
)
|
| 913 |
+
)
|
| 914 |
+
with contextlib.ExitStack() as stack:
|
| 915 |
+
for ctx in ctxs:
|
| 916 |
+
stack.enter_context(ctx)
|
| 917 |
+
yield
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
@contextlib.contextmanager
|
| 921 |
+
def _fakify_script_objects(
|
| 922 |
+
mod: torch.nn.Module,
|
| 923 |
+
args: Sequence[Any],
|
| 924 |
+
kwargs: dict[Any, Any],
|
| 925 |
+
fake_mode: Optional[torch._subclasses.fake_tensor.FakeTensorMode],
|
| 926 |
+
):
|
| 927 |
+
# This context manager is used to fakify script objects into FakeScriptObject.
|
| 928 |
+
# Inputs:
|
| 929 |
+
# mod: the module to be exported, it (and its recursive submodules)'s script object attrs haven't been fakified.
|
| 930 |
+
# args, kwargs: the args and kwargs inputs for mod, script object inputs haven't been fakified.
|
| 931 |
+
# fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors.
|
| 932 |
+
#
|
| 933 |
+
# Returns:
|
| 934 |
+
# mod: the patched module, its (and its recursive submodules) script object attrs have been fakified.
|
| 935 |
+
# fake_args, fake_kwargs: new fakified args and kwargs.
|
| 936 |
+
# Script object inputs have been fakified. Don't touch the tensors.
|
| 937 |
+
# fake_constant_attrs: a new map from FakeScriptObject to the fqn of the original script object.
|
| 938 |
+
# fake_to_real: a mapping between FakeScriptObject and the original script object in order to un-do the patching.
|
| 939 |
+
|
| 940 |
+
constant_attrs: ConstantAttrMap = _gather_constant_attrs(mod)
|
| 941 |
+
assert not any(
|
| 942 |
+
isinstance(obj, FakeScriptObject) for obj in constant_attrs.values()
|
| 943 |
+
), "Mod shouldn't contain any FakeScriptObject."
|
| 944 |
+
assert not pytree.tree_any(
|
| 945 |
+
lambda obj: isinstance(obj, FakeScriptObject), (args, kwargs)
|
| 946 |
+
), "args and kwargs shouldn't contain any FakeScriptObject."
|
| 947 |
+
|
| 948 |
+
patched_attr = {}
|
| 949 |
+
fake_constant_attrs = ConstantAttrMap()
|
| 950 |
+
fake_to_real = {}
|
| 951 |
+
|
| 952 |
+
def _maybe_fakify_obj(obj):
|
| 953 |
+
fake_obj = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, obj)
|
| 954 |
+
fake_to_real[fake_obj] = obj
|
| 955 |
+
return fake_obj
|
| 956 |
+
|
| 957 |
+
def _leaf_mod_and_attr(
|
| 958 |
+
mod: torch.nn.Module, attr_fqn: str
|
| 959 |
+
) -> tuple[torch.nn.Module, str]:
|
| 960 |
+
*prefix_attr, last_attr = attr_fqn.split(".")
|
| 961 |
+
cur_mod = mod
|
| 962 |
+
for attr in prefix_attr:
|
| 963 |
+
cur_mod = getattr(cur_mod, attr)
|
| 964 |
+
return cur_mod, last_attr
|
| 965 |
+
|
| 966 |
+
try:
|
| 967 |
+
for obj, fqns in constant_attrs.items():
|
| 968 |
+
if torch._library.fake_class_registry._is_script_object(
|
| 969 |
+
obj
|
| 970 |
+
) or is_opaque_type(obj):
|
| 971 |
+
fake_script_obj = _maybe_fakify_obj(obj)
|
| 972 |
+
for fqn in fqns:
|
| 973 |
+
cur_mod, attr = _leaf_mod_and_attr(mod, fqn)
|
| 974 |
+
assert obj is getattr(cur_mod, attr)
|
| 975 |
+
setattr(cur_mod, attr, fake_script_obj)
|
| 976 |
+
fake_constant_attrs.add(fake_script_obj, fqn)
|
| 977 |
+
patched_attr[fqn] = obj
|
| 978 |
+
else:
|
| 979 |
+
for fqn in fqns:
|
| 980 |
+
fake_constant_attrs.add(obj, fqn)
|
| 981 |
+
|
| 982 |
+
fake_args, fake_kwargs = pytree.tree_map_only(
|
| 983 |
+
torch.ScriptObject, _maybe_fakify_obj, (args, kwargs)
|
| 984 |
+
)
|
| 985 |
+
yield (mod, fake_args, fake_kwargs, fake_constant_attrs, fake_to_real)
|
| 986 |
+
finally:
|
| 987 |
+
for fqn, orig_obj in patched_attr.items():
|
| 988 |
+
cur_mod, attr = _leaf_mod_and_attr(mod, fqn)
|
| 989 |
+
setattr(cur_mod, attr, orig_obj)
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
class _NonStrictTorchFunctionHandler(torch.overrides.TorchFunctionMode):
|
| 993 |
+
"""
|
| 994 |
+
1. Handles data-dependent errors raised by torch function calls in non-strict.
|
| 995 |
+
|
| 996 |
+
Any data-dependent error is due to some condition on unbacked symints
|
| 997 |
+
that cannot be resolved. A mechanical way of fixing the error is to use
|
| 998 |
+
a torch._check() call to assert either that condition or its negation.
|
| 999 |
+
The handler suggests these options as code and points to the location
|
| 1000 |
+
of the torch function call that raised the error as part of the error
|
| 1001 |
+
message shown to the user, who can then simply select and copy-paste
|
| 1002 |
+
a suggested fix at that location.
|
| 1003 |
+
|
| 1004 |
+
NOTE: Not all data-dependent errors are raised by torch function calls.
|
| 1005 |
+
In particular, conditions on unbacked symints can appear outside such
|
| 1006 |
+
calls, and as such are not handled here.
|
| 1007 |
+
|
| 1008 |
+
2. Overrides torch functions that are known to cause problems in non-strict.
|
| 1009 |
+
|
| 1010 |
+
Certain Python features, such as indexing/slicing, cannot be intercepted
|
| 1011 |
+
in non-strict. Likewise, certain legacy ops, such as distributed collectives,
|
| 1012 |
+
may need to be mapped to other ops. When there is special handling in Dynamo
|
| 1013 |
+
for such things, tracing can fail in non-strict (while succeeding in strict).
|
| 1014 |
+
Fortunately, redirecting to other torch functions can often fix such issues.
|
| 1015 |
+
|
| 1016 |
+
3. Handles line-of-code logging for each torch function call in non-strict.
|
| 1017 |
+
|
| 1018 |
+
Usage: TORCHEXPORT_EXTENDED_DEBUG_CURRENT_LOC=1 TORCH_LOGS="+export" ...
|
| 1019 |
+
"""
|
| 1020 |
+
|
| 1021 |
+
def _override(self, func, args, kwargs):
|
| 1022 |
+
if torch.distributed.is_available():
|
| 1023 |
+
from torch.distributed._functional_collectives import (
|
| 1024 |
+
REDUCE_OP_TO_STR,
|
| 1025 |
+
traceable_collective_remaps,
|
| 1026 |
+
)
|
| 1027 |
+
|
| 1028 |
+
if func in traceable_collective_remaps:
|
| 1029 |
+
# Redirect to a corresponding functional collective, following Dynamo.
|
| 1030 |
+
# See torch/distributed/_functional_collectives.py for details.
|
| 1031 |
+
# The following is an adaptation of CollectiveFunctionRewriteVariable.
|
| 1032 |
+
mapped_func = traceable_collective_remaps[func]
|
| 1033 |
+
signature = inspect.signature(func)
|
| 1034 |
+
kwargs = dict(signature.bind(*args, **kwargs).arguments)
|
| 1035 |
+
args = ()
|
| 1036 |
+
if func in (
|
| 1037 |
+
torch.distributed.all_reduce,
|
| 1038 |
+
torch.distributed.reduce_scatter_tensor,
|
| 1039 |
+
torch.distributed._reduce_scatter_base,
|
| 1040 |
+
):
|
| 1041 |
+
if "op" in kwargs:
|
| 1042 |
+
kwargs["op"] = REDUCE_OP_TO_STR[kwargs["op"]]
|
| 1043 |
+
return mapped_func, args, kwargs
|
| 1044 |
+
if func is torch.tensor:
|
| 1045 |
+
# Redirect to Python implementation of torch.tensor for data with symints.
|
| 1046 |
+
# NOTE(avik): We don't unconditionally redirect to this implementation
|
| 1047 |
+
# because it has some known incompletenesses, e.g., it doesn't support
|
| 1048 |
+
# empty data. See https://github.com/pytorch/pytorch/issues/143216
|
| 1049 |
+
if any(
|
| 1050 |
+
isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool))
|
| 1051 |
+
for a in pytree.tree_flatten(args[0])[0]
|
| 1052 |
+
):
|
| 1053 |
+
return torch._refs.tensor, args, kwargs
|
| 1054 |
+
if func.__name__ == "__getitem__" and isinstance(args[0], torch.Tensor):
|
| 1055 |
+
|
| 1056 |
+
def rewrite(dim, item):
|
| 1057 |
+
# Redirect to torch.select for indexing.
|
| 1058 |
+
if item is None:
|
| 1059 |
+
return dim + 1, (torch.unsqueeze, [dim])
|
| 1060 |
+
if isinstance(item, (int, torch.SymInt)):
|
| 1061 |
+
return dim, (torch.select, [dim, item])
|
| 1062 |
+
# Redirect to torch.ops.aten.slice for slicing.
|
| 1063 |
+
if isinstance(item, slice):
|
| 1064 |
+
step = item.step or 1
|
| 1065 |
+
if item.start is None and item.stop is None and step == 1:
|
| 1066 |
+
# no-op
|
| 1067 |
+
return dim + 1, (lambda t: t, [])
|
| 1068 |
+
return dim + 1, (
|
| 1069 |
+
torch.ops.aten.slice,
|
| 1070 |
+
[dim, item.start, item.stop, step],
|
| 1071 |
+
)
|
| 1072 |
+
# Otherwise do nothing.
|
| 1073 |
+
|
| 1074 |
+
items = list(args[1]) if isinstance(args[1], tuple) else [args[1]]
|
| 1075 |
+
|
| 1076 |
+
has_symint = False
|
| 1077 |
+
index_ellipsis = None
|
| 1078 |
+
t = args[0]
|
| 1079 |
+
n_none_slices = t.ndim + 1
|
| 1080 |
+
for i, item in enumerate(items):
|
| 1081 |
+
if isinstance(item, torch.SymInt) or (
|
| 1082 |
+
isinstance(item, slice)
|
| 1083 |
+
and any(
|
| 1084 |
+
isinstance(s, torch.SymInt)
|
| 1085 |
+
for s in (item.start, item.stop, item.step)
|
| 1086 |
+
)
|
| 1087 |
+
):
|
| 1088 |
+
has_symint = True
|
| 1089 |
+
if item is Ellipsis:
|
| 1090 |
+
index_ellipsis = i
|
| 1091 |
+
if item is not None:
|
| 1092 |
+
n_none_slices -= 1
|
| 1093 |
+
|
| 1094 |
+
# only rewrite when there are symints
|
| 1095 |
+
if has_symint:
|
| 1096 |
+
if index_ellipsis is not None:
|
| 1097 |
+
none_slices = [slice(None)] * n_none_slices
|
| 1098 |
+
items[index_ellipsis : index_ellipsis + 1] = none_slices
|
| 1099 |
+
|
| 1100 |
+
dim = 0
|
| 1101 |
+
# Sequence rewrites.
|
| 1102 |
+
sequence = []
|
| 1103 |
+
for item in items:
|
| 1104 |
+
if (r := rewrite(dim, item)) is None:
|
| 1105 |
+
return func, args, kwargs
|
| 1106 |
+
dim, call_spec = r
|
| 1107 |
+
sequence.append(call_spec)
|
| 1108 |
+
|
| 1109 |
+
def run():
|
| 1110 |
+
# Run sequence.
|
| 1111 |
+
# pyrefly: ignore [index-error]
|
| 1112 |
+
t = args[0]
|
| 1113 |
+
for _method, _args in sequence:
|
| 1114 |
+
t = _method(t, *_args)
|
| 1115 |
+
return t
|
| 1116 |
+
|
| 1117 |
+
return run, [], {}
|
| 1118 |
+
|
| 1119 |
+
return func, args, kwargs
|
| 1120 |
+
|
| 1121 |
+
def __torch_function__(self, func, types, args=(), kwargs=None):
|
| 1122 |
+
kwargs = kwargs or {}
|
| 1123 |
+
if torch.compiler.is_dynamo_compiling():
|
| 1124 |
+
return func(*args, **kwargs)
|
| 1125 |
+
|
| 1126 |
+
if log.isEnabledFor(logging.DEBUG) and config.extended_debug_current_loc:
|
| 1127 |
+
frame = _find_user_code_frame()
|
| 1128 |
+
if frame is not None:
|
| 1129 |
+
log.debug(
|
| 1130 |
+
"%s called at %s:%s in %s",
|
| 1131 |
+
func.__qualname__,
|
| 1132 |
+
frame.f_code.co_filename,
|
| 1133 |
+
frame.f_lineno,
|
| 1134 |
+
frame.f_code.co_name,
|
| 1135 |
+
)
|
| 1136 |
+
|
| 1137 |
+
func, args, kwargs = self._override(func, args, kwargs)
|
| 1138 |
+
try:
|
| 1139 |
+
return func(*args, **kwargs)
|
| 1140 |
+
except GuardOnDataDependentSymNode as e:
|
| 1141 |
+
_suggest_fixes_for_data_dependent_error_non_strict(e)
|
| 1142 |
+
raise
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_base.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
import traceback
|
| 4 |
+
import typing
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from contextlib import nullcontext
|
| 7 |
+
from typing import Any, Optional, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch import fx
|
| 11 |
+
from torch._dispatch.python import enable_python_dispatcher
|
| 12 |
+
from torch._export.pass_infra.node_metadata import NodeMetadata
|
| 13 |
+
from torch._export.pass_infra.proxy_value import ProxyValue
|
| 14 |
+
from torch._higher_order_ops.map import _unstack_pytree
|
| 15 |
+
from torch._subclasses import FakeTensor, UnsupportedFakeTensorException
|
| 16 |
+
from torch._subclasses.fake_tensor import FakeTensorMode
|
| 17 |
+
from torch.fx import traceback as fx_traceback
|
| 18 |
+
from torch.fx.experimental.proxy_tensor import PythonKeyTracer
|
| 19 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 20 |
+
compute_unbacked_bindings,
|
| 21 |
+
PropagateUnbackedSymInts,
|
| 22 |
+
)
|
| 23 |
+
from torch.fx.graph import CodeGen
|
| 24 |
+
from torch.fx.passes.infra.pass_base import PassBase, PassResult
|
| 25 |
+
from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata
|
| 26 |
+
from torch.utils import _pytree as pytree
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = ["_ExportPassBaseDeprecatedDoNotUse"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Argument = Any
|
| 33 |
+
Value = Any
|
| 34 |
+
Fn = Callable[..., Any]
|
| 35 |
+
PassType = Callable[[torch.fx.GraphModule], Optional[PassResult]]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_TORCH_SYM_OPS: set[Callable] = {
|
| 39 |
+
torch.sym_int,
|
| 40 |
+
torch.sym_float,
|
| 41 |
+
torch.sym_ite,
|
| 42 |
+
torch.sym_max,
|
| 43 |
+
torch.sym_min,
|
| 44 |
+
torch.sym_not,
|
| 45 |
+
torch.sym_sqrt,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ExportPassBaseError(RuntimeError):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class _ExportPassBaseDeprecatedDoNotUse(PassBase):
|
| 54 |
+
"""
|
| 55 |
+
Interpreter-based pass class to help users maintain the IR spec while writing
|
| 56 |
+
transformations.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def _create_dummy_node_metadata():
|
| 61 |
+
return NodeMetadata({"stack_trace": "".join(traceback.format_stack(limit=1))})
|
| 62 |
+
|
| 63 |
+
class ExportTracer(PythonKeyTracer):
|
| 64 |
+
def __init__(
|
| 65 |
+
self, callback: "_ExportPassBaseDeprecatedDoNotUse", codegen: CodeGen
|
| 66 |
+
) -> None:
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.callback = callback
|
| 69 |
+
self.root = torch.nn.Module()
|
| 70 |
+
self.graph = torch.fx.Graph()
|
| 71 |
+
self.graph.set_codegen(codegen)
|
| 72 |
+
self.tensor_attrs: dict[str, torch.Tensor] = {} # type: ignore[assignment]
|
| 73 |
+
self.fake_tensor_mode: Optional[FakeTensorMode] = None
|
| 74 |
+
self.submodules: dict[torch.nn.Module, str] = {}
|
| 75 |
+
|
| 76 |
+
def trace(self) -> None: # type: ignore[override]
|
| 77 |
+
raise ExportPassBaseError("ExportTracer doesn't support trace().")
|
| 78 |
+
|
| 79 |
+
def create_arg(self, a: Argument) -> torch.fx.Node:
|
| 80 |
+
if isinstance(a, torch.nn.Module):
|
| 81 |
+
if a not in self.submodules:
|
| 82 |
+
name_submodule = f"submodule_{len(self.submodules)}"
|
| 83 |
+
self.root.add_module(name_submodule, a)
|
| 84 |
+
self.submodules[a] = name_submodule
|
| 85 |
+
elif isinstance(a, FakeTensor):
|
| 86 |
+
if not hasattr(a, "constant") or a.constant is None:
|
| 87 |
+
raise ExportPassBaseError(f"Cannot add {a} to graph.")
|
| 88 |
+
a = a.constant
|
| 89 |
+
node = super().create_arg(a)
|
| 90 |
+
if (
|
| 91 |
+
isinstance(a, torch.Tensor)
|
| 92 |
+
and isinstance(node, torch.fx.Node)
|
| 93 |
+
and node.op == "get_attr"
|
| 94 |
+
):
|
| 95 |
+
self.set_metadata(node, a)
|
| 96 |
+
self.callback.on_attr(ProxyValue(a, node))
|
| 97 |
+
return node
|
| 98 |
+
|
| 99 |
+
def set_metadata(
|
| 100 |
+
self,
|
| 101 |
+
node: torch.fx.Node,
|
| 102 |
+
value: Argument,
|
| 103 |
+
) -> None:
|
| 104 |
+
# propagate the fake tensor or sym nodes
|
| 105 |
+
def make_val(
|
| 106 |
+
x: Argument,
|
| 107 |
+
) -> Union[
|
| 108 |
+
FakeTensor,
|
| 109 |
+
torch.SymInt,
|
| 110 |
+
torch.SymFloat,
|
| 111 |
+
torch.SymBool,
|
| 112 |
+
int,
|
| 113 |
+
float,
|
| 114 |
+
bool,
|
| 115 |
+
str,
|
| 116 |
+
None,
|
| 117 |
+
]:
|
| 118 |
+
if isinstance(x, FakeTensor):
|
| 119 |
+
return x
|
| 120 |
+
elif isinstance(x, torch.Tensor):
|
| 121 |
+
if x.is_quantized:
|
| 122 |
+
# TODO (tmanlaibaatar) properly support Quantized FakeTensor
|
| 123 |
+
x = torch.dequantize(x)
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
assert self.fake_tensor_mode is not None
|
| 127 |
+
# TODO we should allocate static shapes
|
| 128 |
+
# for param/buffer values
|
| 129 |
+
if isinstance(x, torch.nn.Parameter):
|
| 130 |
+
fake_tensor = self.fake_tensor_mode.from_tensor(
|
| 131 |
+
x, static_shapes=True
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
fake_tensor = self.fake_tensor_mode.from_tensor(x)
|
| 135 |
+
except UnsupportedFakeTensorException:
|
| 136 |
+
# TODO: This is just a workaround to get over the
|
| 137 |
+
# x.as_subclass error
|
| 138 |
+
print(
|
| 139 |
+
"Fakeifying a Tensor subclass is not supported \
|
| 140 |
+
right now. Instead a TensorMetadata is used."
|
| 141 |
+
)
|
| 142 |
+
fake_tensor = None
|
| 143 |
+
return fake_tensor
|
| 144 |
+
elif isinstance(
|
| 145 |
+
x,
|
| 146 |
+
(
|
| 147 |
+
torch.SymInt,
|
| 148 |
+
torch.SymFloat,
|
| 149 |
+
torch.SymBool,
|
| 150 |
+
int,
|
| 151 |
+
float,
|
| 152 |
+
bool,
|
| 153 |
+
str,
|
| 154 |
+
),
|
| 155 |
+
):
|
| 156 |
+
return x
|
| 157 |
+
else:
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
node.meta["val"] = pytree.tree_map(make_val, value)
|
| 161 |
+
|
| 162 |
+
# Set the tensor_metadata for values that do not have a corresponding FakeTensor
|
| 163 |
+
def make_tensor_meta(x: Argument) -> Optional[TensorMetadata]:
|
| 164 |
+
if not isinstance(x, FakeTensor) and isinstance(x, torch.Tensor):
|
| 165 |
+
if x.is_quantized:
|
| 166 |
+
# TODO (tmanlaibaatar) properly support Quantized FakeTensor
|
| 167 |
+
x = torch.dequantize(x)
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
assert self.fake_tensor_mode is not None
|
| 171 |
+
_ = self.fake_tensor_mode.from_tensor(x)
|
| 172 |
+
tensor_meta = None
|
| 173 |
+
except UnsupportedFakeTensorException:
|
| 174 |
+
# TODO: This is just a workaround to get over the
|
| 175 |
+
# x.as_subclass error
|
| 176 |
+
tensor_meta = _extract_tensor_metadata(x)
|
| 177 |
+
return tensor_meta
|
| 178 |
+
else:
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
node.meta["tensor_meta"] = pytree.tree_map(make_tensor_meta, value)
|
| 182 |
+
|
| 183 |
+
class ExportInterpreter(fx.Interpreter):
|
| 184 |
+
def __init__(
|
| 185 |
+
self, callback: "_ExportPassBaseDeprecatedDoNotUse", gm: fx.GraphModule
|
| 186 |
+
) -> None:
|
| 187 |
+
super().__init__(gm)
|
| 188 |
+
self.callback = callback
|
| 189 |
+
self.node: torch.fx.Node = next(iter(gm.graph.nodes))
|
| 190 |
+
|
| 191 |
+
# pyrefly: ignore [bad-override]
|
| 192 |
+
def placeholder(
|
| 193 |
+
self,
|
| 194 |
+
target: str, # type: ignore[override]
|
| 195 |
+
args: tuple[Argument, ...],
|
| 196 |
+
kwargs: dict[str, Argument],
|
| 197 |
+
) -> ProxyValue:
|
| 198 |
+
arg = super().placeholder(target, args, kwargs)
|
| 199 |
+
return self.callback.placeholder(target, arg, NodeMetadata(self.node.meta))
|
| 200 |
+
|
| 201 |
+
def output(
|
| 202 |
+
self,
|
| 203 |
+
target: torch.fx.node.Target,
|
| 204 |
+
args: tuple[Argument, ...],
|
| 205 |
+
kwargs: dict[str, Argument],
|
| 206 |
+
) -> ProxyValue:
|
| 207 |
+
return self.callback.output(args[0], NodeMetadata(self.node.meta)).data # type: ignore[return-value]
|
| 208 |
+
|
| 209 |
+
def call_function(
|
| 210 |
+
self,
|
| 211 |
+
target: torch.fx.node.Target,
|
| 212 |
+
args: tuple[Argument, ...],
|
| 213 |
+
kwargs: dict[str, Argument],
|
| 214 |
+
) -> ProxyValue:
|
| 215 |
+
meta = NodeMetadata(self.node.meta)
|
| 216 |
+
|
| 217 |
+
if target is operator.getitem:
|
| 218 |
+
value, key = args
|
| 219 |
+
return self.callback.call_getitem(value, key, meta)
|
| 220 |
+
elif getattr(target, "__module__", None) in {
|
| 221 |
+
"_operator",
|
| 222 |
+
"builtins",
|
| 223 |
+
"math",
|
| 224 |
+
}:
|
| 225 |
+
assert callable(target)
|
| 226 |
+
return self.callback.call_sym(target, args, meta)
|
| 227 |
+
elif target in _TORCH_SYM_OPS:
|
| 228 |
+
assert callable(target)
|
| 229 |
+
return self.callback.call_sym(target, args, meta)
|
| 230 |
+
elif isinstance(
|
| 231 |
+
target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)
|
| 232 |
+
):
|
| 233 |
+
return self.callback.call_operator(
|
| 234 |
+
target,
|
| 235 |
+
args,
|
| 236 |
+
kwargs,
|
| 237 |
+
meta,
|
| 238 |
+
)
|
| 239 |
+
elif target is torch.ops.higher_order.cond:
|
| 240 |
+
pred, true_fn, false_fn, inputs = args
|
| 241 |
+
return self.callback.call_cond(pred, true_fn, false_fn, inputs, meta)
|
| 242 |
+
elif target is torch.ops.higher_order.map_impl:
|
| 243 |
+
f, mapped_args, operands = args # type: ignore[assignment]
|
| 244 |
+
return self.callback.call_map(f, mapped_args, operands, meta)
|
| 245 |
+
# For other unregistered HigherOrderOps, just interpret them blindly
|
| 246 |
+
elif isinstance(target, torch._ops.HigherOrderOperator):
|
| 247 |
+
return self.callback._fx(
|
| 248 |
+
"call_function",
|
| 249 |
+
target,
|
| 250 |
+
args,
|
| 251 |
+
kwargs,
|
| 252 |
+
meta,
|
| 253 |
+
)
|
| 254 |
+
else:
|
| 255 |
+
raise ExportPassBaseError(f"Unsupported target type: {target}")
|
| 256 |
+
|
| 257 |
+
def get_attr( # type: ignore[override]
|
| 258 |
+
self,
|
| 259 |
+
target: str,
|
| 260 |
+
args: tuple[Argument, ...],
|
| 261 |
+
kwargs: dict[str, Argument],
|
| 262 |
+
) -> Argument:
|
| 263 |
+
return super().get_attr(target, args, kwargs)
|
| 264 |
+
|
| 265 |
+
def call_module(
|
| 266 |
+
self,
|
| 267 |
+
target: torch.fx.node.Target,
|
| 268 |
+
args: tuple[Argument, ...],
|
| 269 |
+
kwargs: dict[str, Argument],
|
| 270 |
+
) -> None:
|
| 271 |
+
raise ExportPassBaseError("call_module is not supported.")
|
| 272 |
+
|
| 273 |
+
def call_method( # type: ignore[override]
|
| 274 |
+
self,
|
| 275 |
+
target: str,
|
| 276 |
+
args: tuple[Argument, ...],
|
| 277 |
+
kwargs: dict[str, Argument],
|
| 278 |
+
) -> None:
|
| 279 |
+
raise ExportPassBaseError("call_method is not supported.")
|
| 280 |
+
|
| 281 |
+
def run_node(self, n: torch.fx.Node) -> Argument:
|
| 282 |
+
self.node = n
|
| 283 |
+
self.callback.node_debug_str = n.format_node()
|
| 284 |
+
return super().run_node(n)
|
| 285 |
+
|
| 286 |
+
def __init__(self) -> None:
|
| 287 |
+
self.interpreter = PropagateUnbackedSymInts(
|
| 288 |
+
torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph())
|
| 289 |
+
)
|
| 290 |
+
self.tracer = self.ExportTracer(self, CodeGen())
|
| 291 |
+
self.fake_tensor_mode: Optional[FakeTensorMode] = None
|
| 292 |
+
self._initialized = True
|
| 293 |
+
self.node_debug_str: typing.Optional[str] = None
|
| 294 |
+
|
| 295 |
+
def _fx(
|
| 296 |
+
self,
|
| 297 |
+
kind: str,
|
| 298 |
+
target: torch.fx.node.Target,
|
| 299 |
+
args: tuple[Argument, ...],
|
| 300 |
+
kwargs: dict[str, Argument],
|
| 301 |
+
meta: NodeMetadata,
|
| 302 |
+
) -> ProxyValue:
|
| 303 |
+
args_data, kwargs_data = pytree.tree_map_only(
|
| 304 |
+
ProxyValue, lambda x: x.data, (args, kwargs)
|
| 305 |
+
)
|
| 306 |
+
res_data = getattr(self.interpreter, kind)(target, args_data, kwargs_data)
|
| 307 |
+
args_proxy, kwargs_proxy = pytree.tree_map_only(
|
| 308 |
+
ProxyValue, lambda x: x.proxy, (args, kwargs)
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
name = None
|
| 312 |
+
if isinstance(target, torch._ops.OpOverload):
|
| 313 |
+
name = self.tracer.graph._target_to_str(target.overloadpacket.__name__)
|
| 314 |
+
|
| 315 |
+
res_proxy = self.tracer.create_proxy(
|
| 316 |
+
kind, target, args_proxy, kwargs_proxy, name=name
|
| 317 |
+
)
|
| 318 |
+
res_proxy.node.meta.update(meta.data)
|
| 319 |
+
if self.fake_tensor_mode and (shape_env := self.fake_tensor_mode.shape_env):
|
| 320 |
+
if symbol_to_path := compute_unbacked_bindings(shape_env, res_data):
|
| 321 |
+
res_proxy.node.meta["unbacked_bindings"] = symbol_to_path
|
| 322 |
+
self.tracer.set_metadata(res_proxy.node, res_data)
|
| 323 |
+
return ProxyValue(res_data, res_proxy)
|
| 324 |
+
|
| 325 |
+
def inputs(self, graph_module: torch.fx.GraphModule) -> list[Argument]:
|
| 326 |
+
# TODO(angelayi): Update this with what we decide to do for metadata in
|
| 327 |
+
# the exported graph module
|
| 328 |
+
if (args := graph_module.meta.get("args", None)) is not None:
|
| 329 |
+
return list(args)
|
| 330 |
+
|
| 331 |
+
def extract_input(node: torch.fx.Node) -> Optional[FakeTensor]:
|
| 332 |
+
if "val" in node.meta:
|
| 333 |
+
fake = node.meta["val"]
|
| 334 |
+
if hasattr(fake, "constant") and fake.constant is not None:
|
| 335 |
+
return fake.constant
|
| 336 |
+
return fake
|
| 337 |
+
elif tensor_meta := node.meta.get("tensor_meta"):
|
| 338 |
+
assert self.fake_tensor_mode is not None
|
| 339 |
+
return FakeTensor(
|
| 340 |
+
self.fake_tensor_mode,
|
| 341 |
+
torch.empty(
|
| 342 |
+
tensor_meta.shape,
|
| 343 |
+
dtype=tensor_meta.dtype,
|
| 344 |
+
device="meta",
|
| 345 |
+
requires_grad=tensor_meta.requires_grad,
|
| 346 |
+
memory_format=tensor_meta.memory_format,
|
| 347 |
+
),
|
| 348 |
+
torch.device("cpu"),
|
| 349 |
+
)
|
| 350 |
+
elif len(node.users) == 0:
|
| 351 |
+
return None
|
| 352 |
+
raise ExportPassBaseError(
|
| 353 |
+
f"Cannot construct an input for graph module: {graph_module}.",
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return [
|
| 357 |
+
extract_input(node)
|
| 358 |
+
for node in graph_module.graph.nodes
|
| 359 |
+
if node.op == "placeholder"
|
| 360 |
+
]
|
| 361 |
+
|
| 362 |
+
def on_attr(self, attr: ProxyValue) -> None:
|
| 363 |
+
pass
|
| 364 |
+
|
| 365 |
+
def placeholder(self, name: str, arg: Argument, meta: NodeMetadata) -> ProxyValue:
|
| 366 |
+
arg_proxy = self.tracer.create_proxy("placeholder", name, (), {})
|
| 367 |
+
arg_proxy.node.meta = meta.data
|
| 368 |
+
self.tracer.set_metadata(arg_proxy.node, arg)
|
| 369 |
+
return ProxyValue(arg, arg_proxy)
|
| 370 |
+
|
| 371 |
+
def call_operator(
|
| 372 |
+
self,
|
| 373 |
+
op,
|
| 374 |
+
args: tuple[Argument, ...],
|
| 375 |
+
kwargs: dict[str, Argument],
|
| 376 |
+
meta: NodeMetadata,
|
| 377 |
+
) -> ProxyValue:
|
| 378 |
+
return self._fx("call_function", op, args, kwargs, meta)
|
| 379 |
+
|
| 380 |
+
def call_sym(
|
| 381 |
+
self,
|
| 382 |
+
target: Fn,
|
| 383 |
+
args: tuple[Argument, ...],
|
| 384 |
+
meta: NodeMetadata,
|
| 385 |
+
) -> ProxyValue:
|
| 386 |
+
return self._fx("call_function", target, args, {}, meta)
|
| 387 |
+
|
| 388 |
+
def call_cond(
|
| 389 |
+
self,
|
| 390 |
+
pred: ProxyValue,
|
| 391 |
+
true_fn: torch.fx.GraphModule,
|
| 392 |
+
false_fn: torch.fx.GraphModule,
|
| 393 |
+
inputs: list[Argument],
|
| 394 |
+
meta: NodeMetadata,
|
| 395 |
+
) -> ProxyValue:
|
| 396 |
+
true_branch = self.call_submodule(true_fn, tuple(inputs))
|
| 397 |
+
false_branch = self.call_submodule(false_fn, tuple(inputs))
|
| 398 |
+
assert true_branch is not None
|
| 399 |
+
assert false_branch is not None
|
| 400 |
+
return self._fx(
|
| 401 |
+
"call_function",
|
| 402 |
+
torch.ops.higher_order.cond,
|
| 403 |
+
(pred, true_branch.graph_module, false_branch.graph_module, list(inputs)),
|
| 404 |
+
{},
|
| 405 |
+
meta,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
def call_map(
|
| 409 |
+
self,
|
| 410 |
+
f: torch.fx.GraphModule,
|
| 411 |
+
mapped_args: list[ProxyValue],
|
| 412 |
+
operands: list[ProxyValue],
|
| 413 |
+
meta: NodeMetadata,
|
| 414 |
+
) -> ProxyValue:
|
| 415 |
+
xs = _unstack_pytree([arg.data for arg in mapped_args])[0]
|
| 416 |
+
f_branch = self.call_submodule(f, tuple(xs + [arg.data for arg in operands]))
|
| 417 |
+
assert f_branch is not None
|
| 418 |
+
return self._fx(
|
| 419 |
+
"call_function",
|
| 420 |
+
torch.ops.higher_order.map_impl,
|
| 421 |
+
(f_branch.graph_module, mapped_args, operands),
|
| 422 |
+
{},
|
| 423 |
+
meta,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
def call_getitem(
|
| 427 |
+
self, value: ProxyValue, key: int, meta: NodeMetadata
|
| 428 |
+
) -> ProxyValue:
|
| 429 |
+
return self._fx("call_function", operator.getitem, (value, key), {}, meta)
|
| 430 |
+
|
| 431 |
+
def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue:
|
| 432 |
+
return self._fx("output", "output", (results,), {}, meta)
|
| 433 |
+
|
| 434 |
+
def call_submodule(
|
| 435 |
+
self, graph_module: fx.GraphModule, inputs: tuple[Argument, ...]
|
| 436 |
+
) -> PassResult:
|
| 437 |
+
prev_tracer, self.tracer = (
|
| 438 |
+
self.tracer,
|
| 439 |
+
self.ExportTracer(self, graph_module.graph._codegen),
|
| 440 |
+
)
|
| 441 |
+
self.tracer.fake_tensor_mode = prev_tracer.fake_tensor_mode
|
| 442 |
+
interpreter = self.ExportInterpreter(self, graph_module)
|
| 443 |
+
# pyrefly: ignore [bad-assignment]
|
| 444 |
+
prev_interpreter, self.interpreter = (
|
| 445 |
+
self.interpreter,
|
| 446 |
+
torch.fx.Interpreter( # type: ignore[assignment]
|
| 447 |
+
torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph())
|
| 448 |
+
),
|
| 449 |
+
)
|
| 450 |
+
inputs_data = pytree.tree_map_only(ProxyValue, lambda x: x.data, inputs)
|
| 451 |
+
with fx_traceback.preserve_node_meta():
|
| 452 |
+
interpreter.run(*inputs_data)
|
| 453 |
+
|
| 454 |
+
new_graph_module = torch.fx.GraphModule(self.tracer.root, self.tracer.graph)
|
| 455 |
+
|
| 456 |
+
self.tracer = prev_tracer
|
| 457 |
+
self.interpreter = prev_interpreter
|
| 458 |
+
return PassResult(
|
| 459 |
+
new_graph_module,
|
| 460 |
+
True,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
def call(self, graph_module: fx.GraphModule) -> PassResult:
|
| 464 |
+
if not getattr(self, "_initialized", False):
|
| 465 |
+
raise ExportPassBaseError(
|
| 466 |
+
"ExportPass is not initialized with __init__().",
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
inputs = self.inputs(graph_module)
|
| 470 |
+
|
| 471 |
+
fake_tensor_mode = None
|
| 472 |
+
for i in inputs:
|
| 473 |
+
if isinstance(i, FakeTensor):
|
| 474 |
+
assert fake_tensor_mode is None or fake_tensor_mode is i.fake_mode, (
|
| 475 |
+
"Multiple fake tensor mode detected."
|
| 476 |
+
)
|
| 477 |
+
fake_tensor_mode = i.fake_mode
|
| 478 |
+
if fake_tensor_mode is None:
|
| 479 |
+
self.tracer.fake_tensor_mode = FakeTensorMode(allow_non_fake_inputs=True)
|
| 480 |
+
fake_tensor_mode = nullcontext() # type: ignore[assignment]
|
| 481 |
+
dispatcher_mode = nullcontext() # type: ignore[assignment]
|
| 482 |
+
else:
|
| 483 |
+
fake_tensor_mode.allow_non_fake_inputs = True
|
| 484 |
+
self.tracer.fake_tensor_mode = fake_tensor_mode
|
| 485 |
+
dispatcher_mode = enable_python_dispatcher() # type: ignore[assignment]
|
| 486 |
+
self.fake_tensor_mode = self.tracer.fake_tensor_mode
|
| 487 |
+
|
| 488 |
+
with fake_tensor_mode, dispatcher_mode: # type: ignore[assignment, union-attr]
|
| 489 |
+
result = self.call_submodule(graph_module, tuple(inputs))
|
| 490 |
+
|
| 491 |
+
return result
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
NodeMetadataValue = Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
PROTECTED_KEYS: set[str] = {
|
| 8 |
+
"val",
|
| 9 |
+
"stack_trace",
|
| 10 |
+
"nn_module_stack",
|
| 11 |
+
"debug_handle",
|
| 12 |
+
"tensor_meta",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class NodeMetadata:
|
| 17 |
+
def __init__(self, data: dict[str, Any]) -> None:
|
| 18 |
+
self.data: dict[str, Any] = data.copy()
|
| 19 |
+
|
| 20 |
+
def __getitem__(self, key: str) -> NodeMetadataValue:
|
| 21 |
+
return self.data[key]
|
| 22 |
+
|
| 23 |
+
def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue:
|
| 24 |
+
if key in PROTECTED_KEYS:
|
| 25 |
+
raise RuntimeError(f"Could not override node key: {key}")
|
| 26 |
+
self.data[key] = value
|
| 27 |
+
|
| 28 |
+
def __contains__(self, key: str) -> bool:
|
| 29 |
+
return key in self.data
|
| 30 |
+
|
| 31 |
+
def copy(self) -> "NodeMetadata":
|
| 32 |
+
return NodeMetadata(self.data.copy())
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pyre-strict
|
| 2 |
+
from collections.abc import Iterable, Iterator
|
| 3 |
+
from typing import Generic, TypeVar, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_T = TypeVar("_T")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ProxyValue(Generic[_T]):
|
| 12 |
+
# pyre-ignore
|
| 13 |
+
def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]):
|
| 14 |
+
# pyre-ignore
|
| 15 |
+
self.data = data
|
| 16 |
+
self.proxy_or_node = proxy
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def node(self) -> torch.fx.Node:
|
| 20 |
+
if isinstance(self.proxy_or_node, torch.fx.Node):
|
| 21 |
+
return self.proxy_or_node
|
| 22 |
+
assert isinstance(self.proxy_or_node, torch.fx.Proxy)
|
| 23 |
+
return self.proxy_or_node.node
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def proxy(self) -> torch.fx.Proxy:
|
| 27 |
+
if not isinstance(self.proxy_or_node, torch.fx.Proxy):
|
| 28 |
+
raise RuntimeError(
|
| 29 |
+
f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}"
|
| 30 |
+
)
|
| 31 |
+
return self.proxy_or_node
|
| 32 |
+
|
| 33 |
+
def to_tensor(self) -> torch.Tensor:
|
| 34 |
+
assert isinstance(self.data, torch.Tensor)
|
| 35 |
+
return self.data
|
| 36 |
+
|
| 37 |
+
def is_tensor(self) -> bool:
|
| 38 |
+
return isinstance(self.data, torch.Tensor)
|
| 39 |
+
|
| 40 |
+
# pyre-ignore
|
| 41 |
+
def __iter__(self) -> Iterator[_T]:
|
| 42 |
+
yield from self.data
|
| 43 |
+
|
| 44 |
+
def __bool__(self) -> bool:
|
| 45 |
+
return bool(self.data)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_export/passes/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass
|