Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +14 -0
- python_embeded/Lib/site-packages/torch/_export/db/__init__.py +5 -0
- python_embeded/Lib/site-packages/torch/_export/db/case.py +174 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/assume_constant_result.py +20 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/autograd_function.py +23 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/class_method.py +22 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_branch_class_method.py +44 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_branch_nested_function.py +41 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py +59 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_closed_over_variable.py +22 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_operands.py +35 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/cond_predicate.py +25 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/constrain_as_size_example.py +25 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/constrain_as_value_example.py +28 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/decorator.py +23 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dictionary.py +17 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_assert.py +18 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py +15 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py +19 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_map.py +19 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_round.py +21 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py +15 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/dynamic_shape_view.py +17 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/fn_with_kwargs.py +30 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/list_contains.py +17 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/list_unpack.py +21 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/model_attr_mutation.py +26 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/nested_function.py +23 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/null_context_manager.py +21 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/optional_input.py +20 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/pytree_flatten.py +16 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/scalar_output.py +23 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/specialized_attribute.py +26 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/static_for_loop.py +16 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/static_if.py +18 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/tensor_setattr.py +15 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/type_reflection_method.py +22 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/unsupported_operator.py +18 -0
- python_embeded/Lib/site-packages/torch/_export/db/examples/user_input_mutation.py +17 -0
- python_embeded/Lib/site-packages/torch/_export/db/gen_example.py +21 -0
- python_embeded/Lib/site-packages/torch/_export/db/logging.py +46 -0
- python_embeded/Lib/site-packages/torch/_export/pass_infra/__init__.py +0 -0
- python_embeded/Lib/site-packages/torch/_export/pass_infra/node_metadata.py +32 -0
- python_embeded/Lib/site-packages/torch/_export/pass_infra/proxy_value.py +44 -0
- python_embeded/Lib/site-packages/torch/_export/passes/__init__.py +1 -0
- python_embeded/Lib/site-packages/torch/_export/passes/_node_metadata_hook.py +81 -0
- python_embeded/Lib/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py +227 -0
- python_embeded/Lib/site-packages/torch/_export/passes/collect_tracepoints_pass.py +146 -0
- python_embeded/Lib/site-packages/torch/_export/passes/constant_folding.py +303 -0
- python_embeded/Lib/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py +94 -0
.gitattributes
CHANGED
|
@@ -238,3 +238,17 @@ python_embeded/Lib/site-packages/pyzbar/libzbar-64.dll filter=lfs diff=lfs merge
|
|
| 238 |
python_embeded/Lib/site-packages/safetensors/_safetensors_rust.pyd filter=lfs diff=lfs merge=lfs -text
|
| 239 |
python_embeded/Lib/site-packages/torchvision/jpeg8.dll filter=lfs diff=lfs merge=lfs -text
|
| 240 |
python_embeded/Lib/site-packages/torchvision/libjpeg.dll filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
python_embeded/Lib/site-packages/safetensors/_safetensors_rust.pyd filter=lfs diff=lfs merge=lfs -text
|
| 239 |
python_embeded/Lib/site-packages/torchvision/jpeg8.dll filter=lfs diff=lfs merge=lfs -text
|
| 240 |
python_embeded/Lib/site-packages/torchvision/libjpeg.dll filter=lfs diff=lfs merge=lfs -text
|
| 241 |
+
python_embeded/Lib/site-packages/torchvision/libpng16.dll filter=lfs diff=lfs merge=lfs -text
|
| 242 |
+
python_embeded/Lib/site-packages/win32comext/axcontrol/axcontrol.pyd filter=lfs diff=lfs merge=lfs -text
|
| 243 |
+
python_embeded/Lib/site-packages/torchvision/libwebp.dll filter=lfs diff=lfs merge=lfs -text
|
| 244 |
+
python_embeded/Lib/site-packages/torchvision/nvjpeg64_12.dll filter=lfs diff=lfs merge=lfs -text
|
| 245 |
+
python_embeded/Lib/site-packages/win32com/libs/pythoncom.lib filter=lfs diff=lfs merge=lfs -text
|
| 246 |
+
python_embeded/Lib/site-packages/torch/bin/fbgemm.dll filter=lfs diff=lfs merge=lfs -text
|
| 247 |
+
python_embeded/Lib/site-packages/torch/bin/asmjit.dll filter=lfs diff=lfs merge=lfs -text
|
| 248 |
+
python_embeded/Lib/site-packages/torch/bin/protoc.exe filter=lfs diff=lfs merge=lfs -text
|
| 249 |
+
python_embeded/Lib/site-packages/torchvision/image.pyd filter=lfs diff=lfs merge=lfs -text
|
| 250 |
+
python_embeded/Lib/site-packages/torch/lib/asmjit.lib filter=lfs diff=lfs merge=lfs -text
|
| 251 |
+
python_embeded/Lib/site-packages/torch/lib/asmjit.dll filter=lfs diff=lfs merge=lfs -text
|
| 252 |
+
python_embeded/Lib/site-packages/torch/lib/c10.dll filter=lfs diff=lfs merge=lfs -text
|
| 253 |
+
python_embeded/Lib/site-packages/torch/lib/c10.lib filter=lfs diff=lfs merge=lfs -text
|
| 254 |
+
python_embeded/Lib/site-packages/torch/lib/c10_cuda.dll filter=lfs diff=lfs merge=lfs -text
|
python_embeded/Lib/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.
|
python_embeded/Lib/site-packages/torch/_export/db/case.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
return ExportCase(**{**configs, "model": m, "name": name})
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def export_case(**kwargs):
|
| 139 |
+
"""
|
| 140 |
+
Decorator for registering a user provided case into example bank.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def wrapper(m):
|
| 144 |
+
configs = kwargs
|
| 145 |
+
module = inspect.getmodule(m)
|
| 146 |
+
if module in _MODULES:
|
| 147 |
+
raise RuntimeError("export_case should only be used once per example file.")
|
| 148 |
+
|
| 149 |
+
assert module is not None
|
| 150 |
+
_MODULES.add(module)
|
| 151 |
+
module_name = module.__name__.split(".")[-1]
|
| 152 |
+
case = _make_export_case(m, module_name, configs)
|
| 153 |
+
register_db_case(case)
|
| 154 |
+
return case
|
| 155 |
+
|
| 156 |
+
return wrapper
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def export_rewrite_case(**kwargs):
|
| 160 |
+
def wrapper(m):
|
| 161 |
+
configs = kwargs
|
| 162 |
+
|
| 163 |
+
parent = configs.pop("parent")
|
| 164 |
+
assert isinstance(parent, ExportCase)
|
| 165 |
+
key = parent.name
|
| 166 |
+
if key not in _EXAMPLE_REWRITE_CASES:
|
| 167 |
+
_EXAMPLE_REWRITE_CASES[key] = []
|
| 168 |
+
|
| 169 |
+
configs["example_args"] = parent.example_args
|
| 170 |
+
case = _make_export_case(m, to_snake_case(m.__name__), configs)
|
| 171 |
+
_EXAMPLE_REWRITE_CASES[key].append(case)
|
| 172 |
+
return case
|
| 173 |
+
|
| 174 |
+
return wrapper
|
python_embeded/Lib/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()
|
python_embeded/Lib/site-packages/torch/_export/db/examples/autograd_function.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class MyAutogradFunction(torch.autograd.Function):
|
| 5 |
+
@staticmethod
|
| 6 |
+
def forward(ctx, x):
|
| 7 |
+
return x.clone()
|
| 8 |
+
|
| 9 |
+
@staticmethod
|
| 10 |
+
def backward(ctx, grad_output):
|
| 11 |
+
return grad_output + 1
|
| 12 |
+
|
| 13 |
+
class AutogradFunction(torch.nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
TorchDynamo does not keep track of backward() on autograd functions. We recommend to
|
| 16 |
+
use `allow_in_graph` to mitigate this problem.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
return MyAutogradFunction.apply(x)
|
| 21 |
+
|
| 22 |
+
example_args = (torch.randn(3, 2),)
|
| 23 |
+
model = AutogradFunction()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/site-packages/torch/_export/db/examples/constrain_as_size_example.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 and torch._check_is_size APIs.
|
| 9 |
+
torch._check_is_size is used for values that NEED to be used for constructing
|
| 10 |
+
tensor.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def forward(self, x):
|
| 14 |
+
a = x.item()
|
| 15 |
+
torch._check_is_size(a)
|
| 16 |
+
torch._check(a <= 5)
|
| 17 |
+
return torch.zeros((a, 5))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
example_args = (torch.tensor(4),)
|
| 21 |
+
tags = {
|
| 22 |
+
"torch.dynamic-value",
|
| 23 |
+
"torch.escape-hatch",
|
| 24 |
+
}
|
| 25 |
+
model = ConstrainAsSizeExample()
|
python_embeded/Lib/site-packages/torch/_export/db/examples/constrain_as_value_example.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 and torch._check_is_size APIs.
|
| 9 |
+
torch._check is used for values that don't need to be used for constructing
|
| 10 |
+
tensor.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def forward(self, x, y):
|
| 14 |
+
a = x.item()
|
| 15 |
+
torch._check(a >= 0)
|
| 16 |
+
torch._check(a <= 5)
|
| 17 |
+
|
| 18 |
+
if a < 6:
|
| 19 |
+
return y.sin()
|
| 20 |
+
return y.cos()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
example_args = (torch.tensor(4), torch.randn(5, 5))
|
| 24 |
+
tags = {
|
| 25 |
+
"torch.dynamic-value",
|
| 26 |
+
"torch.escape-hatch",
|
| 27 |
+
}
|
| 28 |
+
model = ConstrainAsValueExample()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/site-packages/torch/_export/db/examples/model_attr_mutation.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
from torch._export.db.case import SupportLevel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ModelAttrMutation(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
Attribute mutation is not supported.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def __init__(self) -> None:
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.attr_list = [torch.randn(3, 2), torch.randn(3, 2)]
|
| 14 |
+
|
| 15 |
+
def recreate_list(self):
|
| 16 |
+
return [torch.zeros(3, 2), torch.zeros(3, 2)]
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
self.attr_list = self.recreate_list()
|
| 20 |
+
return x.sum() + self.attr_list[0].sum()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
example_args = (torch.randn(3, 2),)
|
| 24 |
+
tags = {"python.object-model"}
|
| 25 |
+
support_level = SupportLevel.NOT_SUPPORTED_YET
|
| 26 |
+
model = ModelAttrMutation()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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.NOT_SUPPORTED_YET
|
| 20 |
+
model = OptionalInput()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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()
|
python_embeded/Lib/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]))
|
python_embeded/Lib/site-packages/torch/_export/db/logging.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
attr_name = _ALLOW_LIST[type(e)]
|
| 43 |
+
if attr_name is None:
|
| 44 |
+
return ALWAYS_CLASSIFIED
|
| 45 |
+
return getattr(e, attr_name, None)
|
| 46 |
+
return None
|
python_embeded/Lib/site-packages/torch/_export/pass_infra/__init__.py
ADDED
|
File without changes
|
python_embeded/Lib/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())
|
python_embeded/Lib/site-packages/torch/_export/pass_infra/proxy_value.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pyre-strict
|
| 2 |
+
from typing import Union, Generic
|
| 3 |
+
from collections.abc import Iterator, Iterable
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from typing import TypeVar
|
| 7 |
+
|
| 8 |
+
_T = TypeVar("_T")
|
| 9 |
+
|
| 10 |
+
class ProxyValue(Generic[_T]):
|
| 11 |
+
# pyre-ignore
|
| 12 |
+
def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]):
|
| 13 |
+
# pyre-ignore
|
| 14 |
+
self.data = data
|
| 15 |
+
self.proxy_or_node = proxy
|
| 16 |
+
|
| 17 |
+
@property
|
| 18 |
+
def node(self) -> torch.fx.Node:
|
| 19 |
+
if isinstance(self.proxy_or_node, torch.fx.Node):
|
| 20 |
+
return self.proxy_or_node
|
| 21 |
+
assert isinstance(self.proxy_or_node, torch.fx.Proxy)
|
| 22 |
+
return self.proxy_or_node.node
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def proxy(self) -> torch.fx.Proxy:
|
| 26 |
+
if not isinstance(self.proxy_or_node, torch.fx.Proxy):
|
| 27 |
+
raise RuntimeError(
|
| 28 |
+
f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}"
|
| 29 |
+
)
|
| 30 |
+
return self.proxy_or_node
|
| 31 |
+
|
| 32 |
+
def to_tensor(self) -> torch.Tensor:
|
| 33 |
+
assert isinstance(self.data, torch.Tensor)
|
| 34 |
+
return self.data
|
| 35 |
+
|
| 36 |
+
def is_tensor(self) -> bool:
|
| 37 |
+
return isinstance(self.data, torch.Tensor)
|
| 38 |
+
|
| 39 |
+
# pyre-ignore
|
| 40 |
+
def __iter__(self) -> Iterator[_T]:
|
| 41 |
+
yield from self.data
|
| 42 |
+
|
| 43 |
+
def __bool__(self) -> bool:
|
| 44 |
+
return bool(self.data)
|
python_embeded/Lib/site-packages/torch/_export/passes/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass
|
python_embeded/Lib/site-packages/torch/_export/passes/_node_metadata_hook.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.fx.graph_module import GraphModule
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
_EMPTY_NN_MODULE_STACK_KEY = "_empty_nn_module_stack_from_metadata_hook"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _node_metadata_hook(node: torch.fx.Node, stack_trace: Optional[str] = None) -> None:
|
| 13 |
+
"""
|
| 14 |
+
Hook for adding the appropriate metadata to nodes that are created during a
|
| 15 |
+
pass using graph.create_node. An example of how to use it:
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
with _set_node_metadata_hook(gm,
|
| 19 |
+
functools.partial(_node_metadata_hook, stack_trace="file")
|
| 20 |
+
):
|
| 21 |
+
pass(gm)
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
This hook should not work for all generic cases -- specifically it assumes
|
| 25 |
+
that nodes being added are only call_function nodes, and copies over the
|
| 26 |
+
first argument node's nn_module_stack.
|
| 27 |
+
"""
|
| 28 |
+
assert node.op == "call_function" and callable(node.target)
|
| 29 |
+
|
| 30 |
+
arg_meta = [arg.meta for arg in node.args if isinstance(arg, torch.fx.Node)]
|
| 31 |
+
assert len(arg_meta) >= 1
|
| 32 |
+
arg_meta = arg_meta[0]
|
| 33 |
+
|
| 34 |
+
if (
|
| 35 |
+
isinstance(node.target, torch._ops.OpOverload)
|
| 36 |
+
and len(node.target._schema.returns) == 0
|
| 37 |
+
):
|
| 38 |
+
node.meta["val"] = None
|
| 39 |
+
else:
|
| 40 |
+
fake_args = [
|
| 41 |
+
arg.meta["val"] if isinstance(arg, torch.fx.Node) else arg
|
| 42 |
+
for arg in node.args
|
| 43 |
+
]
|
| 44 |
+
fake_res = node.target(*fake_args)
|
| 45 |
+
node.meta["val"] = fake_res
|
| 46 |
+
|
| 47 |
+
node.meta["stack_trace"] = stack_trace
|
| 48 |
+
node.meta["nn_module_stack"] = arg_meta.get(
|
| 49 |
+
"nn_module_stack",
|
| 50 |
+
{
|
| 51 |
+
_EMPTY_NN_MODULE_STACK_KEY: (
|
| 52 |
+
_EMPTY_NN_MODULE_STACK_KEY,
|
| 53 |
+
_EMPTY_NN_MODULE_STACK_KEY,
|
| 54 |
+
)
|
| 55 |
+
},
|
| 56 |
+
)
|
| 57 |
+
node.meta["torch_fn"] = (
|
| 58 |
+
f"{node.target.__name__}_0",
|
| 59 |
+
f"{node.target.__class__.__name__}.{node.target.__name__}",
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@contextlib.contextmanager
|
| 64 |
+
def _set_node_metadata_hook(gm: torch.fx.GraphModule, f):
|
| 65 |
+
"""
|
| 66 |
+
Takes a callable which will be called after we create a new node. The
|
| 67 |
+
callable takes the newly created node as input and returns None.
|
| 68 |
+
"""
|
| 69 |
+
assert callable(f), "node_metadata_hook must be a callable."
|
| 70 |
+
|
| 71 |
+
# Add the hook to all submodules
|
| 72 |
+
for m in gm.modules():
|
| 73 |
+
if isinstance(m, GraphModule):
|
| 74 |
+
m._register_create_node_hook(f)
|
| 75 |
+
try:
|
| 76 |
+
yield
|
| 77 |
+
finally:
|
| 78 |
+
# Restore hook for all submodules
|
| 79 |
+
for m in gm.modules():
|
| 80 |
+
if isinstance(m, GraphModule):
|
| 81 |
+
m._unregister_create_node_hook(f)
|
python_embeded/Lib/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
import operator
|
| 4 |
+
import traceback
|
| 5 |
+
from functools import partial
|
| 6 |
+
from typing import Callable, NamedTuple
|
| 7 |
+
|
| 8 |
+
import sympy
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.fx
|
| 12 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 13 |
+
from torch.utils._sympy.numbers import int_oo
|
| 14 |
+
from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 15 |
+
from torch.fx.passes.infra.pass_base import PassBase, PassResult
|
| 16 |
+
|
| 17 |
+
__all__ = ["InputDim"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class InputDim(NamedTuple):
|
| 21 |
+
input_name: str
|
| 22 |
+
dim: int
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _convert_to_int(val):
|
| 26 |
+
# Convert simple sympy Integers into concrete int
|
| 27 |
+
if val in (sympy.oo, int_oo):
|
| 28 |
+
return math.inf
|
| 29 |
+
if val in (-sympy.oo, -int_oo):
|
| 30 |
+
return -math.inf
|
| 31 |
+
if isinstance(val, sympy.Integer):
|
| 32 |
+
return int(val)
|
| 33 |
+
raise RuntimeError(
|
| 34 |
+
"Export constraints cannot be non-integer expressions"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _convert_range_to_int(range: ValueRanges):
|
| 39 |
+
assert isinstance(range, ValueRanges)
|
| 40 |
+
min_val = _convert_to_int(range.lower)
|
| 41 |
+
max_val = _convert_to_int(range.upper)
|
| 42 |
+
return min_val, max_val
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class _AddRuntimeAssertionsForInlineConstraintsPass(PassBase):
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
range_constraints: dict[sympy.Symbol, ValueRanges],
|
| 49 |
+
):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints
|
| 52 |
+
self._asserts_generated_unbacked_symbols: set[sympy.Symbol] = set()
|
| 53 |
+
self.counter = 0
|
| 54 |
+
|
| 55 |
+
def _assert_range_constraint(self, node, lower, upper, assert_msg):
|
| 56 |
+
last_node = node
|
| 57 |
+
if lower > -math.inf:
|
| 58 |
+
last_node = self._insert_assert_async(last_node, operator.ge, node, lower, assert_msg)
|
| 59 |
+
|
| 60 |
+
if upper < math.inf:
|
| 61 |
+
last_node = self._insert_assert_async(last_node, operator.le, node, upper, assert_msg)
|
| 62 |
+
|
| 63 |
+
def _insert_assert_async(self, last_node, op, lower, upper, assert_msg):
|
| 64 |
+
"""
|
| 65 |
+
Inserts assert_async call_function nodes in the graph. This function is
|
| 66 |
+
called **during** the interpreter-based pass.
|
| 67 |
+
"""
|
| 68 |
+
self.counter += 1
|
| 69 |
+
graph = last_node.graph
|
| 70 |
+
with graph.inserting_after(last_node):
|
| 71 |
+
cmp = graph.call_function(op, (lower, upper), {})
|
| 72 |
+
with graph.inserting_after(cmp):
|
| 73 |
+
cmp_tensor = graph.call_function(torch.ops.aten.scalar_tensor.default, (cmp,), {})
|
| 74 |
+
with graph.inserting_after(cmp_tensor):
|
| 75 |
+
assert_async = graph.call_function(
|
| 76 |
+
torch.ops.aten._assert_async.msg,
|
| 77 |
+
(cmp_tensor, assert_msg),
|
| 78 |
+
{},
|
| 79 |
+
)
|
| 80 |
+
return assert_async
|
| 81 |
+
|
| 82 |
+
def call(self, graph_module) -> PassResult:
|
| 83 |
+
self.existing_inline_assertions = _get_existing_inline_assertions(
|
| 84 |
+
graph_module, self.range_constraints
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
for module in graph_module.modules():
|
| 88 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 89 |
+
continue
|
| 90 |
+
for node in module.graph.nodes:
|
| 91 |
+
if node.op != "call_function":
|
| 92 |
+
continue
|
| 93 |
+
if "val" not in node.meta:
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
val = node.meta["val"]
|
| 97 |
+
# In general, we may have to deal the case such as: ret[1].shape[0].
|
| 98 |
+
# We need first find out what symbols require assertion, then we need to follow the path
|
| 99 |
+
# from ret to the symbol, construct the proxies along the way and construct the messages
|
| 100 |
+
# piece-wise at the same time.
|
| 101 |
+
#
|
| 102 |
+
# We use post-order traversal to collect all the proxies callbacks needed, construct
|
| 103 |
+
# the error message callbacks, and at the top-level traversal tree we execute all the callbacks.
|
| 104 |
+
# We need the callbacks because, in order to call the function to create a proxy for shape[0], we
|
| 105 |
+
# need the proxy for shape, which further requires the proxy for ret[1], etc.
|
| 106 |
+
|
| 107 |
+
def add_assertions(val):
|
| 108 |
+
call_backs: list[Callable] = []
|
| 109 |
+
messages: list[str] = []
|
| 110 |
+
if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)):
|
| 111 |
+
symbol = val.node.expr
|
| 112 |
+
if symbol in self.existing_inline_assertions:
|
| 113 |
+
return call_backs, messages
|
| 114 |
+
if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols(symbol):
|
| 115 |
+
if symbol in self._asserts_generated_unbacked_symbols:
|
| 116 |
+
return call_backs, messages
|
| 117 |
+
# We only care about unbacked symints for these inline
|
| 118 |
+
# constraints, which are prefixed with 'u'
|
| 119 |
+
constraint = self.range_constraints[symbol]
|
| 120 |
+
min_val, max_val = _convert_range_to_int(constraint)
|
| 121 |
+
assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]."
|
| 122 |
+
call_backs.append(
|
| 123 |
+
partial(self._assert_range_constraint, lower=min_val, upper=max_val)
|
| 124 |
+
)
|
| 125 |
+
messages.append(assert_msg)
|
| 126 |
+
self._asserts_generated_unbacked_symbols.add(symbol)
|
| 127 |
+
|
| 128 |
+
elif isinstance(val, torch.Tensor):
|
| 129 |
+
for i, sym in enumerate(val.shape):
|
| 130 |
+
cbs, msgs = add_assertions(sym)
|
| 131 |
+
for cb, msg in zip(cbs, msgs):
|
| 132 |
+
def sym_size_cb(node, assert_msg, dim):
|
| 133 |
+
with node.graph.inserting_after(node):
|
| 134 |
+
dim_node = module.graph.call_function(
|
| 135 |
+
torch.ops.aten.sym_size.int,
|
| 136 |
+
(node, dim),
|
| 137 |
+
{},
|
| 138 |
+
)
|
| 139 |
+
cb(node=dim_node, assert_msg=assert_msg)
|
| 140 |
+
call_backs.append(partial(sym_size_cb, dim=i))
|
| 141 |
+
messages.append(f".shape[{i}]" + msg)
|
| 142 |
+
return call_backs, messages
|
| 143 |
+
|
| 144 |
+
callbacks, messages = add_assertions(val)
|
| 145 |
+
for cb, msg in zip(callbacks, messages):
|
| 146 |
+
cb(node=node, assert_msg=f"{node}" + msg)
|
| 147 |
+
|
| 148 |
+
module.recompile()
|
| 149 |
+
|
| 150 |
+
# Sometimes this pass would return a wrong graph where we have mismatched
|
| 151 |
+
# node names in signature. Before we fix it, let's just skip it.
|
| 152 |
+
if self.counter == 0 and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass:
|
| 153 |
+
return PassResult(graph_module, False)
|
| 154 |
+
|
| 155 |
+
# Populate the stack trace with dummy vals to respect IR
|
| 156 |
+
for node in graph_module.graph.nodes:
|
| 157 |
+
if not node.meta.get("stack_trace", None) and node.op not in ["placeholder", "output"]:
|
| 158 |
+
node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1))
|
| 159 |
+
return PassResult(graph_module, True)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _get_existing_inline_assertions(
|
| 163 |
+
graph_module: torch.fx.GraphModule,
|
| 164 |
+
range_constraints: dict[sympy.Symbol, ValueRanges],
|
| 165 |
+
) -> dict[sympy.Symbol, ValueRanges]:
|
| 166 |
+
existing_inline_assertions: dict[sympy.Symbol, ValueRanges] = {}
|
| 167 |
+
|
| 168 |
+
for module in graph_module.modules():
|
| 169 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
# Find all the existing inline assertions. They will look something like:
|
| 173 |
+
# %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {})
|
| 174 |
+
# %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {})
|
| 175 |
+
# %_assert_scalar = call_function[target=torch.ops.aten._assert_scalar.default](args = (%scalar_tensor, "..."), kwargs = {})
|
| 176 |
+
for node in module.graph.nodes:
|
| 177 |
+
if node.target != torch.ops.aten._assert_scalar.default:
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
compare_arg = node.args[0]
|
| 181 |
+
if not (
|
| 182 |
+
isinstance(compare_arg, torch.fx.Node) and
|
| 183 |
+
compare_arg.op == "call_function" and
|
| 184 |
+
compare_arg.target in (operator.le, operator.ge) and
|
| 185 |
+
len(compare_arg.args) == 2
|
| 186 |
+
):
|
| 187 |
+
continue
|
| 188 |
+
|
| 189 |
+
compare_op = compare_arg.target
|
| 190 |
+
lhs, rhs = compare_arg.args
|
| 191 |
+
|
| 192 |
+
def maybe_get_symint(x):
|
| 193 |
+
if (
|
| 194 |
+
isinstance(x, torch.fx.Node) and
|
| 195 |
+
"val" in x.meta and
|
| 196 |
+
isinstance(x.meta["val"], torch.SymInt)
|
| 197 |
+
):
|
| 198 |
+
return x.meta["val"].node.expr
|
| 199 |
+
return x
|
| 200 |
+
|
| 201 |
+
lhs = maybe_get_symint(lhs)
|
| 202 |
+
rhs = maybe_get_symint(rhs)
|
| 203 |
+
|
| 204 |
+
if compare_op == operator.ge:
|
| 205 |
+
lhs, rhs = rhs, lhs
|
| 206 |
+
|
| 207 |
+
if isinstance(lhs, sympy.Symbol) and isinstance(rhs, int):
|
| 208 |
+
symint = lhs
|
| 209 |
+
scalar = rhs
|
| 210 |
+
elif isinstance(rhs, sympy.Symbol) and isinstance(lhs, int):
|
| 211 |
+
symint = rhs
|
| 212 |
+
scalar = lhs
|
| 213 |
+
else:
|
| 214 |
+
continue
|
| 215 |
+
|
| 216 |
+
if symint not in range_constraints:
|
| 217 |
+
raise RuntimeError(f"Unable to find symint {symint} in {range_constraints}")
|
| 218 |
+
|
| 219 |
+
previous_range = existing_inline_assertions.get(symint, ValueRanges(-math.inf, math.inf))
|
| 220 |
+
|
| 221 |
+
if symint is lhs:
|
| 222 |
+
bounds = ValueRanges(-math.inf, scalar)
|
| 223 |
+
else:
|
| 224 |
+
bounds = ValueRanges(scalar, math.inf)
|
| 225 |
+
existing_inline_assertions[symint] = previous_range & bounds
|
| 226 |
+
|
| 227 |
+
return existing_inline_assertions
|
python_embeded/Lib/site-packages/torch/_export/passes/collect_tracepoints_pass.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import operator
|
| 5 |
+
from typing import Optional, TYPE_CHECKING, Union
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.export.exported_program import ConstantArgument, TensorArgument
|
| 9 |
+
from torch.fx.passes.infra.pass_base import PassBase, PassResult
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from torch.export.exported_program import ModuleCallSignature
|
| 14 |
+
from torch.export.graph_signature import ExportGraphSignature
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = ["CollectTracepointsPass"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class CollectTracepointsPass(PassBase):
|
| 21 |
+
"""
|
| 22 |
+
Performs constant folding and constant propagation.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self, specs: dict[str, ModuleCallSignature], sig: ExportGraphSignature
|
| 27 |
+
) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.specs = specs
|
| 30 |
+
self.sig = sig
|
| 31 |
+
|
| 32 |
+
def call(self, gm: torch.fx.GraphModule) -> Optional[PassResult]:
|
| 33 |
+
def get_arg_spec(arg) -> Union[TensorArgument, ConstantArgument]:
|
| 34 |
+
if isinstance(arg, torch.fx.Node):
|
| 35 |
+
if isinstance(arg.meta.get("val"), torch.Tensor):
|
| 36 |
+
return TensorArgument(name=arg.name)
|
| 37 |
+
else:
|
| 38 |
+
raise AssertionError(
|
| 39 |
+
"Symint input is not implemented yet for submodule call signature."
|
| 40 |
+
)
|
| 41 |
+
else:
|
| 42 |
+
return ConstantArgument(name="", value=arg)
|
| 43 |
+
|
| 44 |
+
for module in gm.modules():
|
| 45 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 46 |
+
continue
|
| 47 |
+
nn_module_stack = None
|
| 48 |
+
for node in module.graph.nodes:
|
| 49 |
+
if node.op != "call_function":
|
| 50 |
+
continue
|
| 51 |
+
if node.target == torch.ops.higher_order._export_tracepoint:
|
| 52 |
+
kind = node.kwargs["kind"]
|
| 53 |
+
if kind == "module_call_outputs":
|
| 54 |
+
nn_module_stack = node.meta["nn_module_stack"]
|
| 55 |
+
elif kind == "module_call_inputs":
|
| 56 |
+
nn_module_stack = None
|
| 57 |
+
else:
|
| 58 |
+
raise AssertionError(f"Unknown tracepoint kind: {kind}")
|
| 59 |
+
elif node.meta["nn_module_stack"] == nn_module_stack:
|
| 60 |
+
node.meta["nn_module_stack"].popitem()
|
| 61 |
+
else:
|
| 62 |
+
nn_module_stack = None
|
| 63 |
+
nn_module_stack = None
|
| 64 |
+
for node in reversed(module.graph.nodes):
|
| 65 |
+
if node.op != "call_function":
|
| 66 |
+
continue
|
| 67 |
+
if node.target == torch.ops.higher_order._export_tracepoint:
|
| 68 |
+
kind = node.kwargs["kind"]
|
| 69 |
+
if kind == "module_call_inputs":
|
| 70 |
+
nn_module_stack = node.meta["nn_module_stack"]
|
| 71 |
+
elif kind == "module_call_outputs":
|
| 72 |
+
nn_module_stack = None
|
| 73 |
+
else:
|
| 74 |
+
raise AssertionError(f"Unknown tracepoint kind: {kind}")
|
| 75 |
+
elif node.meta["nn_module_stack"] == nn_module_stack:
|
| 76 |
+
node.meta["nn_module_stack"].popitem()
|
| 77 |
+
else:
|
| 78 |
+
nn_module_stack = None
|
| 79 |
+
|
| 80 |
+
def copy_sig(sig) -> ModuleCallSignature:
|
| 81 |
+
from torch.export.exported_program import ModuleCallSignature
|
| 82 |
+
|
| 83 |
+
return ModuleCallSignature(
|
| 84 |
+
inputs=[],
|
| 85 |
+
outputs=[],
|
| 86 |
+
in_spec=sig.in_spec,
|
| 87 |
+
out_spec=sig.out_spec,
|
| 88 |
+
forward_arg_names=None,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
for module in gm.modules():
|
| 92 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 93 |
+
continue
|
| 94 |
+
for node in module.graph.nodes:
|
| 95 |
+
if node.op != "call_function":
|
| 96 |
+
continue
|
| 97 |
+
if node.target == torch.ops.higher_order._export_tracepoint:
|
| 98 |
+
# There's some subtlety worth noting. Here fqn corresponds to
|
| 99 |
+
# the call name, whereas path corresponds to the module name.
|
| 100 |
+
# They are not necessarily the same! When a submodule is shared
|
| 101 |
+
# through different aliases, there are as many _export_tracepoint
|
| 102 |
+
# markers as there are aliases, since the shared submodule is
|
| 103 |
+
# wrapped once for each alias.
|
| 104 |
+
path = node.kwargs["path"]
|
| 105 |
+
fqn, _ = next(reversed(node.meta["nn_module_stack"].values()))
|
| 106 |
+
|
| 107 |
+
module_key = next(reversed(node.meta["nn_module_stack"]))
|
| 108 |
+
if "@" in module_key:
|
| 109 |
+
suffix = module_key.split("@")[-1]
|
| 110 |
+
path = f"{path}@{suffix}"
|
| 111 |
+
|
| 112 |
+
call_fqn = f"{fqn}@{suffix}"
|
| 113 |
+
if call_fqn not in self.specs:
|
| 114 |
+
self.specs[call_fqn] = copy_sig(self.specs[fqn])
|
| 115 |
+
fqn = call_fqn
|
| 116 |
+
|
| 117 |
+
kind = node.kwargs["kind"]
|
| 118 |
+
for i, arg in enumerate(node.args):
|
| 119 |
+
# We only update the signature of the alias used to call
|
| 120 |
+
# the submodule. Otherwise the signatures of all aliases
|
| 121 |
+
# would get conflated; the inputs/outputs of every call
|
| 122 |
+
# would be recorded in every other call as well.
|
| 123 |
+
if fqn == path:
|
| 124 |
+
if kind == "module_call_inputs":
|
| 125 |
+
self.specs[path].inputs.append(get_arg_spec(arg))
|
| 126 |
+
elif kind == "module_call_outputs":
|
| 127 |
+
self.specs[path].outputs.append(get_arg_spec(arg))
|
| 128 |
+
else:
|
| 129 |
+
raise AssertionError(f"Unknown tracepoint kind: {kind}")
|
| 130 |
+
if isinstance(arg, torch.fx.Node):
|
| 131 |
+
for user in node.users:
|
| 132 |
+
assert user.op == "call_function"
|
| 133 |
+
assert user.target == operator.getitem
|
| 134 |
+
assert isinstance(user.args[1], int)
|
| 135 |
+
if user.args[1] == i:
|
| 136 |
+
user.replace_all_uses_with(arg)
|
| 137 |
+
self.sig.replace_all_uses(user.name, arg.name)
|
| 138 |
+
break
|
| 139 |
+
users = list(node.users)
|
| 140 |
+
for user in users:
|
| 141 |
+
assert len(user.users) == 0
|
| 142 |
+
gm.graph.erase_node(user)
|
| 143 |
+
gm.graph.erase_node(node)
|
| 144 |
+
return PassResult(gm, True)
|
| 145 |
+
|
| 146 |
+
return None
|
python_embeded/Lib/site-packages/torch/_export/passes/constant_folding.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import collections
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from typing import Any, Callable, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.utils._pytree as pytree
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
aten = torch.ops.aten
|
| 11 |
+
|
| 12 |
+
# We would like to split modules into two subgraphs for runtime weight updates to work correctly.
|
| 13 |
+
# The use case and more information could be found at:
|
| 14 |
+
# https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing
|
| 15 |
+
META_TAG = "MODULE_TYPE"
|
| 16 |
+
MODULE_TAG = "_MAIN_MODULE"
|
| 17 |
+
CONST_MODULE_TAG = "_CONST_MODULE"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def replace_node_with_constant(gm, node, constant, name=None):
|
| 21 |
+
g = gm.graph
|
| 22 |
+
|
| 23 |
+
if name:
|
| 24 |
+
qualname = name
|
| 25 |
+
else:
|
| 26 |
+
if not hasattr(gm, "_frozen_param_count"):
|
| 27 |
+
gm._frozen_param_count = 0
|
| 28 |
+
i = gm._frozen_param_count
|
| 29 |
+
|
| 30 |
+
while True:
|
| 31 |
+
qualname = f"_frozen_param{i}"
|
| 32 |
+
if not hasattr(gm, qualname):
|
| 33 |
+
break
|
| 34 |
+
i += 1
|
| 35 |
+
|
| 36 |
+
gm._frozen_param_count = i + 1
|
| 37 |
+
|
| 38 |
+
with g.inserting_before(node):
|
| 39 |
+
new_input_node = g.create_node("get_attr", qualname, (), {})
|
| 40 |
+
node.replace_all_uses_with(new_input_node)
|
| 41 |
+
new_input_node.meta.update(node.meta)
|
| 42 |
+
g.erase_node(node)
|
| 43 |
+
|
| 44 |
+
# needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning
|
| 45 |
+
gm.register_buffer(qualname, constant)
|
| 46 |
+
setattr(gm, qualname, constant)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ConstantFolder(torch.fx.Interpreter):
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
gm: torch.fx.GraphModule,
|
| 53 |
+
skip_constructors: bool = False,
|
| 54 |
+
):
|
| 55 |
+
super().__init__(gm)
|
| 56 |
+
self.node_replacements: dict[torch.fx.Node, Any] = {}
|
| 57 |
+
self.replaced_uses: dict[torch.fx.Node, int] = collections.Counter()
|
| 58 |
+
self.unknown_value = object()
|
| 59 |
+
self.skip_constructors: bool = skip_constructors
|
| 60 |
+
|
| 61 |
+
# overwrite this to deallocate env values if their only remaining use
|
| 62 |
+
# is the output
|
| 63 |
+
self.user_to_last_uses = self.node_to_last_non_output_use()
|
| 64 |
+
|
| 65 |
+
def is_impure(self, node: torch.fx.Node) -> bool:
|
| 66 |
+
if (
|
| 67 |
+
node.target == torch.ops.prims.convert_element_type.default
|
| 68 |
+
and node.args[0].op == "get_attr" # type: ignore[union-attr]
|
| 69 |
+
and node.args[0].meta["val"].dtype == torch.int8 # type: ignore[union-attr]
|
| 70 |
+
and node.args[1] == torch.bfloat16
|
| 71 |
+
):
|
| 72 |
+
# For int8_weight -> dq -> bf16_weight
|
| 73 |
+
return True
|
| 74 |
+
if node.target in [
|
| 75 |
+
torch.ops.quantized_decomposed.dequantize_per_channel.default,
|
| 76 |
+
torch.ops.quantized_decomposed.dequantize_per_tensor.default,
|
| 77 |
+
torch.ops.quantized_decomposed.dequantize_per_tensor.tensor,
|
| 78 |
+
torch.ops.pt2e_quant.dequantize_affine,
|
| 79 |
+
]:
|
| 80 |
+
# For the pattern fp32_weight -> q -> dq
|
| 81 |
+
# We only folding fp32_weight -> q
|
| 82 |
+
# int8_weight and leave dq in graph to be fused
|
| 83 |
+
return True
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
def node_to_last_non_output_use(self):
|
| 87 |
+
last_non_output_use = collections.defaultdict(list)
|
| 88 |
+
seen_uses = set()
|
| 89 |
+
output_node = next(iter(reversed(self.module.graph.nodes))) # type: ignore[arg-type, union-attr]
|
| 90 |
+
|
| 91 |
+
for node in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr]
|
| 92 |
+
if node.target == "output":
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
def add_use(inp):
|
| 96 |
+
if inp in seen_uses:
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
seen_uses.add(inp)
|
| 100 |
+
last_non_output_use[node].append(inp)
|
| 101 |
+
|
| 102 |
+
# In-place is fine since we don't mutate
|
| 103 |
+
pytree.tree_map_only_(torch.fx.Node, add_use, (node.args, node.kwargs))
|
| 104 |
+
|
| 105 |
+
# if this node is only used in output, we want to gc it right away
|
| 106 |
+
if len(node.users) == 1 and output_node in node.users:
|
| 107 |
+
last_non_output_use[node].append(node)
|
| 108 |
+
|
| 109 |
+
return last_non_output_use
|
| 110 |
+
|
| 111 |
+
def run_node(self, node):
|
| 112 |
+
if node.target == "output":
|
| 113 |
+
# because we remove nodes from env on last non output use,
|
| 114 |
+
# re-define them now or we'll get error in interpreter
|
| 115 |
+
def set_env(arg):
|
| 116 |
+
self.env[arg] = self.unknown_value
|
| 117 |
+
|
| 118 |
+
# In-place is fine since we don't mutate
|
| 119 |
+
pytree.tree_map_only_(torch.fx.Node, set_env, node.args)
|
| 120 |
+
return super().run_node(node)
|
| 121 |
+
|
| 122 |
+
args, kwargs = self.fetch_args_kwargs_from_env(node)
|
| 123 |
+
flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs)
|
| 124 |
+
|
| 125 |
+
# We need to do this weird thing because in cases where flattened_inputs
|
| 126 |
+
# contains a ScriptObject, equality checking results in a type error if
|
| 127 |
+
# the types are different.
|
| 128 |
+
if any(
|
| 129 |
+
type(self.unknown_value) == type(input_) and self.unknown_value == input_
|
| 130 |
+
for input_ in flattened_inputs
|
| 131 |
+
):
|
| 132 |
+
return self.unknown_value
|
| 133 |
+
|
| 134 |
+
# TODO - fix errors with this
|
| 135 |
+
if (
|
| 136 |
+
node.op == "call_function"
|
| 137 |
+
and node.target == aten._efficientzerotensor.default
|
| 138 |
+
):
|
| 139 |
+
return self.unknown_value
|
| 140 |
+
|
| 141 |
+
# TODO - constant folding triton kernel returns the inputs -- fix this
|
| 142 |
+
if (
|
| 143 |
+
node.op == "call_function"
|
| 144 |
+
and node.name == "triton_kernel_wrapper_functional_proxy"
|
| 145 |
+
):
|
| 146 |
+
return self.unknown_value
|
| 147 |
+
|
| 148 |
+
# skip constructors, since inductor generates optimal code for them already
|
| 149 |
+
# and turning into tensor would result in an additional global memory read
|
| 150 |
+
# TODO - more complicated strategy
|
| 151 |
+
if (
|
| 152 |
+
self.skip_constructors
|
| 153 |
+
and node.op != "get_attr"
|
| 154 |
+
and not any(isinstance(e, torch.Tensor) for e in flattened_inputs)
|
| 155 |
+
):
|
| 156 |
+
return self.unknown_value
|
| 157 |
+
|
| 158 |
+
# All mutations should either be removed or on inputs which we did not make constant
|
| 159 |
+
if (
|
| 160 |
+
isinstance(node.target, torch._ops.OpOverload)
|
| 161 |
+
and torch.Tag.nondeterministic_seeded in node.target.tags
|
| 162 |
+
):
|
| 163 |
+
return self.unknown_value
|
| 164 |
+
|
| 165 |
+
out = super().run_node(node)
|
| 166 |
+
|
| 167 |
+
if node.op != "get_attr" and isinstance(out, torch.Tensor):
|
| 168 |
+
if out.device.type == "meta":
|
| 169 |
+
return out
|
| 170 |
+
|
| 171 |
+
if not self.insertable_tensor_check(out):
|
| 172 |
+
return out
|
| 173 |
+
|
| 174 |
+
if self.is_impure(node):
|
| 175 |
+
return self.unknown_value
|
| 176 |
+
|
| 177 |
+
self.add_node_replacement(node, out)
|
| 178 |
+
|
| 179 |
+
flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs)
|
| 180 |
+
|
| 181 |
+
for n in flattened_node_inps:
|
| 182 |
+
if not isinstance(n, torch.fx.Node):
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
self.replaced_uses[n] += 1
|
| 186 |
+
|
| 187 |
+
for to_delete in self.user_to_last_uses.get(node, []):
|
| 188 |
+
if self.replaced_uses[to_delete] == len(to_delete.users):
|
| 189 |
+
self.node_replacements.pop(to_delete, None)
|
| 190 |
+
|
| 191 |
+
return out
|
| 192 |
+
|
| 193 |
+
def insertable_tensor_check(self, tensor: torch.Tensor) -> bool:
|
| 194 |
+
return True
|
| 195 |
+
|
| 196 |
+
def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None:
|
| 197 |
+
self.node_replacements[node] = tensor
|
| 198 |
+
|
| 199 |
+
def run(self): # type: ignore[override]
|
| 200 |
+
env = {}
|
| 201 |
+
for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr]
|
| 202 |
+
env[n] = self.unknown_value
|
| 203 |
+
return super().run(initial_env=env)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def constant_fold(
|
| 207 |
+
gm: torch.fx.GraphModule,
|
| 208 |
+
constraint_fn: Optional[Callable[[torch.fx.Node], bool]] = None,
|
| 209 |
+
):
|
| 210 |
+
with torch.utils._python_dispatch._disable_current_modes():
|
| 211 |
+
cf = ConstantFolder(gm, skip_constructors=True)
|
| 212 |
+
cf.run()
|
| 213 |
+
|
| 214 |
+
for node, constant in cf.node_replacements.items():
|
| 215 |
+
if constraint_fn is not None and not constraint_fn(node):
|
| 216 |
+
continue
|
| 217 |
+
replace_node_with_constant(gm, node, constant)
|
| 218 |
+
|
| 219 |
+
erased_params = []
|
| 220 |
+
# Get all attr users by looking up the graph instead from node.users, because in this case
|
| 221 |
+
# _tensor_constant0 and _tensor_constant0_1 are actually refereing to the same tensor.
|
| 222 |
+
|
| 223 |
+
# opcode name target args kwargs
|
| 224 |
+
# ------------- ------------------- ---------------- --------------------------- --------
|
| 225 |
+
# placeholder arg0_1 arg0 () {}
|
| 226 |
+
# get_attr _tensor_constant0 state () {}
|
| 227 |
+
# call_function add aten.add.Tensor (arg0_1, _tensor_constant0) {}
|
| 228 |
+
# get_attr _tensor_constant0_1 state () {}
|
| 229 |
+
# call_function add_ aten.add_.Tensor (_tensor_constant0_1, 1) {}
|
| 230 |
+
# output output output ([add],) {}
|
| 231 |
+
|
| 232 |
+
get_attr_node_users = defaultdict(list)
|
| 233 |
+
for node in gm.graph.nodes:
|
| 234 |
+
if node.op == "get_attr":
|
| 235 |
+
get_attr_node_users[node.target].extend(node.users.keys())
|
| 236 |
+
for node in gm.graph.find_nodes(op="get_attr"):
|
| 237 |
+
if node.op == "get_attr" and len(get_attr_node_users[node.target]) == 0:
|
| 238 |
+
if hasattr(gm, node.target):
|
| 239 |
+
delattr(gm, node.target)
|
| 240 |
+
erased_params.append(node)
|
| 241 |
+
for node in erased_params:
|
| 242 |
+
gm.graph.erase_node(node)
|
| 243 |
+
|
| 244 |
+
gm.graph.eliminate_dead_code()
|
| 245 |
+
gm.graph.lint()
|
| 246 |
+
gm.recompile()
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def constant_graph_tag(gm: torch.fx.GraphModule) -> None:
|
| 250 |
+
with torch.utils._python_dispatch._disable_current_modes():
|
| 251 |
+
cf = ConstantFolder(gm, skip_constructors=True)
|
| 252 |
+
cf.run()
|
| 253 |
+
|
| 254 |
+
for node in gm.graph.nodes:
|
| 255 |
+
if (
|
| 256 |
+
node.op == "get_attr"
|
| 257 |
+
or node in cf.node_replacements
|
| 258 |
+
or node in cf.replaced_uses
|
| 259 |
+
):
|
| 260 |
+
node.meta[META_TAG] = CONST_MODULE_TAG
|
| 261 |
+
else:
|
| 262 |
+
node.meta[META_TAG] = MODULE_TAG
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def run_and_get_constant_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
|
| 266 |
+
"""
|
| 267 |
+
Construct a GraphModule which corresponds to the part which could be
|
| 268 |
+
constant folded in provided gm.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
constant_graph_tag(gm)
|
| 272 |
+
# We rewrite the tags, if it's a constant being directly consumed, without
|
| 273 |
+
# any folding opportunity, we keep it in main gm.
|
| 274 |
+
for node in gm.graph.find_nodes(op="get_attr"):
|
| 275 |
+
used_to_fold = False
|
| 276 |
+
for u in node.users:
|
| 277 |
+
if u.meta[META_TAG] == CONST_MODULE_TAG:
|
| 278 |
+
used_to_fold = True
|
| 279 |
+
break
|
| 280 |
+
if not used_to_fold:
|
| 281 |
+
node.meta[META_TAG] = MODULE_TAG
|
| 282 |
+
|
| 283 |
+
new_graph = torch.fx.Graph()
|
| 284 |
+
|
| 285 |
+
node_remapping: dict[torch.fx.Node, torch.fx.Node] = {}
|
| 286 |
+
output_nodes = []
|
| 287 |
+
for node in gm.graph.nodes:
|
| 288 |
+
if node.meta[META_TAG] == MODULE_TAG:
|
| 289 |
+
continue
|
| 290 |
+
|
| 291 |
+
new_node = new_graph.node_copy(node, lambda x: node_remapping[x])
|
| 292 |
+
node_remapping[node] = new_node
|
| 293 |
+
|
| 294 |
+
for user in node.users:
|
| 295 |
+
if user.meta[META_TAG] == MODULE_TAG:
|
| 296 |
+
output_nodes.append(new_node)
|
| 297 |
+
break
|
| 298 |
+
|
| 299 |
+
new_graph.output(tuple(output_nodes))
|
| 300 |
+
new_graph.lint()
|
| 301 |
+
new_gm = torch.fx.GraphModule(gm, new_graph)
|
| 302 |
+
|
| 303 |
+
return new_gm
|
python_embeded/Lib/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse, PassResult, Argument
|
| 6 |
+
from torch._export.pass_infra.node_metadata import NodeMetadata
|
| 7 |
+
from torch._export.pass_infra.proxy_value import ProxyValue
|
| 8 |
+
from torch._ops import OpOverload
|
| 9 |
+
|
| 10 |
+
aten = torch.ops.aten
|
| 11 |
+
|
| 12 |
+
_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: dict[OpOverload, OpOverload] = {
|
| 13 |
+
aten.sym_constrain_range.default: aten._functional_sym_constrain_range,
|
| 14 |
+
aten._assert_async.msg: aten._functional_assert_async.msg,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _FunctionalizeSideEffectfulOpsPass(_ExportPassBaseDeprecatedDoNotUse):
|
| 19 |
+
"""
|
| 20 |
+
Functionalize ops with side effect in graph module by replacing the op with
|
| 21 |
+
functional version of it. A new dependency token (`dep_token`) will be
|
| 22 |
+
created and propagated through functional ops to output.
|
| 23 |
+
For example:
|
| 24 |
+
```
|
| 25 |
+
def f(x):
|
| 26 |
+
sym_constrain_range(x.shape[0], min=1, max=3)
|
| 27 |
+
return x.add(3)
|
| 28 |
+
```
|
| 29 |
+
Will be transformed to:
|
| 30 |
+
```
|
| 31 |
+
def f(x):
|
| 32 |
+
dep_token0 = _make_dep_token()
|
| 33 |
+
dep_token1 = _functional_sym_constrain_range(
|
| 34 |
+
x.shape[0], min=1, max=3, dep_token=dep_token0
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
return x.add(3), dep_token1
|
| 38 |
+
```
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self) -> None:
|
| 42 |
+
super().__init__()
|
| 43 |
+
self._dep_token: Optional[ProxyValue] = None
|
| 44 |
+
self._next_dep_token_index: Optional[int] = None
|
| 45 |
+
|
| 46 |
+
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
|
| 47 |
+
# Early return if no non-functional assertions.
|
| 48 |
+
if not any(
|
| 49 |
+
n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS
|
| 50 |
+
for n in graph_module.graph.nodes
|
| 51 |
+
):
|
| 52 |
+
return PassResult(graph_module=graph_module, modified=False)
|
| 53 |
+
|
| 54 |
+
gm = copy.deepcopy(graph_module)
|
| 55 |
+
self._dep_token = None
|
| 56 |
+
self._next_dep_token_index = None
|
| 57 |
+
return super().call(gm)
|
| 58 |
+
|
| 59 |
+
def call_operator(
|
| 60 |
+
self,
|
| 61 |
+
op: OpOverload,
|
| 62 |
+
args: tuple[Argument, ...],
|
| 63 |
+
kwargs: dict[str, Argument],
|
| 64 |
+
meta: NodeMetadata,
|
| 65 |
+
) -> ProxyValue:
|
| 66 |
+
if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS:
|
| 67 |
+
return super().call_operator(op, args, kwargs, meta)
|
| 68 |
+
|
| 69 |
+
if self._dep_token is None:
|
| 70 |
+
self._dep_token = super().call_operator(
|
| 71 |
+
aten._make_dep_token,
|
| 72 |
+
args=(),
|
| 73 |
+
kwargs={},
|
| 74 |
+
meta=self._create_dummy_node_metadata(),
|
| 75 |
+
)
|
| 76 |
+
self._dep_token.node.name = "dep_token0"
|
| 77 |
+
self._next_dep_token_index = 1
|
| 78 |
+
|
| 79 |
+
self._dep_token = super().call_operator(
|
| 80 |
+
_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op],
|
| 81 |
+
args=args,
|
| 82 |
+
kwargs={**kwargs, "dep_token": self._dep_token},
|
| 83 |
+
meta=meta,
|
| 84 |
+
)
|
| 85 |
+
assert self._next_dep_token_index is not None
|
| 86 |
+
self._dep_token.node.name = f"dep_token{self._next_dep_token_index}"
|
| 87 |
+
self._next_dep_token_index += 1
|
| 88 |
+
|
| 89 |
+
return self._dep_token
|
| 90 |
+
|
| 91 |
+
def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue:
|
| 92 |
+
assert self._dep_token is not None
|
| 93 |
+
|
| 94 |
+
return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type]
|