Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/converter.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/error.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/pass_base.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/tools.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/utils.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/verifier.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/wrappers.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__init__.py +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/case.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/gen_example.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/logging.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/case.py +174 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nested_function.py +41 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py +59 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py +15 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/list_unpack.py +21 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/model_attr_mutation.py +26 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/gen_example.py +21 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/logging.py +46 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py +32 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py +45 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/__init__.py +1 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/_node_metadata_hook.py +81 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py +250 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/collect_tracepoints_pass.py +146 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/constant_folding.py +303 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py +99 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/insert_custom_op_guards.py +78 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/lift_constants_pass.py +414 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/remove_runtime_assertions.py +36 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py +189 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py +673 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py +121 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py +65 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_with_hop_pass_util.py +187 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/dynamic_shapes.py +322 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/export_schema.thrift +362 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/schema.py +505 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/schema.yaml +536 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/schema_check.py +738 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/serialize.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/union.py +71 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__init__.py +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (6.55 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/converter.cpython-310.pyc
ADDED
|
Binary file (42.4 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/error.cpython-310.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-310.pyc
ADDED
|
Binary file (26.6 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/pass_base.cpython-310.pyc
ADDED
|
Binary file (15 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/tools.cpython-310.pyc
ADDED
|
Binary file (4.37 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (40.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/verifier.cpython-310.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/__pycache__/wrappers.cpython-310.pyc
ADDED
|
Binary file (8.87 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (190 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/case.cpython-310.pyc
ADDED
|
Binary file (4.91 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/gen_example.cpython-310.pyc
ADDED
|
Binary file (719 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/__pycache__/logging.cpython-310.pyc
ADDED
|
Binary file (1.39 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/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
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nested_function.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondBranchNestedFunction(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
|
| 9 |
+
- both branches must take the same args, which must also match the branch args passed to cond.
|
| 10 |
+
- both branches must return a single tensor
|
| 11 |
+
- returned tensor must have the same tensor metadata, e.g. shape and dtype
|
| 12 |
+
- branch function can be free function, nested function, lambda, class methods
|
| 13 |
+
- branch function can not have closure variables
|
| 14 |
+
- no inplace mutations on inputs or global variables
|
| 15 |
+
|
| 16 |
+
This example demonstrates using nested function in cond().
|
| 17 |
+
|
| 18 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
def true_fn(x):
|
| 23 |
+
def inner_true_fn(y):
|
| 24 |
+
return x + y
|
| 25 |
+
|
| 26 |
+
return inner_true_fn(x)
|
| 27 |
+
|
| 28 |
+
def false_fn(x):
|
| 29 |
+
def inner_false_fn(y):
|
| 30 |
+
return x - y
|
| 31 |
+
|
| 32 |
+
return inner_false_fn(x)
|
| 33 |
+
|
| 34 |
+
return cond(x.shape[0] < 10, true_fn, false_fn, [x])
|
| 35 |
+
|
| 36 |
+
example_args = (torch.randn(3),)
|
| 37 |
+
tags = {
|
| 38 |
+
"torch.cond",
|
| 39 |
+
"torch.dynamic-shape",
|
| 40 |
+
}
|
| 41 |
+
model = CondBranchNestedFunction()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from functorch.experimental.control_flow import cond
|
| 5 |
+
|
| 6 |
+
class CondBranchNonlocalVariables(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules:
|
| 9 |
+
- both branches must take the same args, which must also match the branch args passed to cond.
|
| 10 |
+
- both branches must return a single tensor
|
| 11 |
+
- returned tensor must have the same tensor metadata, e.g. shape and dtype
|
| 12 |
+
- branch function can be free function, nested function, lambda, class methods
|
| 13 |
+
- branch function can not have closure variables
|
| 14 |
+
- no inplace mutations on inputs or global variables
|
| 15 |
+
|
| 16 |
+
This example demonstrates how to rewrite code to avoid capturing closure variables in branch functions.
|
| 17 |
+
|
| 18 |
+
The code below will not work because capturing closure variables is not supported.
|
| 19 |
+
```
|
| 20 |
+
my_tensor_var = x + 100
|
| 21 |
+
my_primitive_var = 3.14
|
| 22 |
+
|
| 23 |
+
def true_fn(y):
|
| 24 |
+
nonlocal my_tensor_var, my_primitive_var
|
| 25 |
+
return y + my_tensor_var + my_primitive_var
|
| 26 |
+
|
| 27 |
+
def false_fn(y):
|
| 28 |
+
nonlocal my_tensor_var, my_primitive_var
|
| 29 |
+
return y - my_tensor_var - my_primitive_var
|
| 30 |
+
|
| 31 |
+
return cond(x.shape[0] > 5, true_fn, false_fn, [x])
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
NOTE: If the `pred` is test on a dim with batch size < 2, it will be specialized.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
my_tensor_var = x + 100
|
| 39 |
+
my_primitive_var = 3.14
|
| 40 |
+
|
| 41 |
+
def true_fn(x, y, z):
|
| 42 |
+
return x + y + z
|
| 43 |
+
|
| 44 |
+
def false_fn(x, y, z):
|
| 45 |
+
return x - y - z
|
| 46 |
+
|
| 47 |
+
return cond(
|
| 48 |
+
x.shape[0] > 5,
|
| 49 |
+
true_fn,
|
| 50 |
+
false_fn,
|
| 51 |
+
[x, my_tensor_var, torch.tensor(my_primitive_var)],
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
example_args = (torch.randn(6),)
|
| 55 |
+
tags = {
|
| 56 |
+
"torch.cond",
|
| 57 |
+
"torch.dynamic-shape",
|
| 58 |
+
}
|
| 59 |
+
model = CondBranchNonlocalVariables()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
class DynamicShapeConstructor(torch.nn.Module):
|
| 5 |
+
"""
|
| 6 |
+
Tensor constructors should be captured with dynamic shape inputs rather
|
| 7 |
+
than being baked in with static shape.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
def forward(self, x):
|
| 11 |
+
return torch.zeros(x.shape[0] * 2)
|
| 12 |
+
|
| 13 |
+
example_args = (torch.randn(3, 2),)
|
| 14 |
+
tags = {"torch.dynamic-shape"}
|
| 15 |
+
model = DynamicShapeConstructor()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/examples/list_unpack.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
class ListUnpack(torch.nn.Module):
|
| 6 |
+
"""
|
| 7 |
+
Lists are treated as static construct, therefore unpacking should be
|
| 8 |
+
erased after tracing.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def forward(self, args: list[torch.Tensor]):
|
| 12 |
+
"""
|
| 13 |
+
Lists are treated as static construct, therefore unpacking should be
|
| 14 |
+
erased after tracing.
|
| 15 |
+
"""
|
| 16 |
+
x, *y = args
|
| 17 |
+
return x + y[0]
|
| 18 |
+
|
| 19 |
+
example_args = ([torch.randn(3, 2), torch.tensor(4), torch.tensor(5)],)
|
| 20 |
+
tags = {"python.control-flow", "python.data-structure"}
|
| 21 |
+
model = ListUnpack()
|
data/tefig/envs/olmes-eval/lib/python3.10/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()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/db/gen_example.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch._export.db.examples as examples
|
| 5 |
+
|
| 6 |
+
TEMPLATE = '''import torch
|
| 7 |
+
|
| 8 |
+
def {case_name}(x):
|
| 9 |
+
"""
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
return
|
| 13 |
+
'''
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
assert len(sys.argv) == 2
|
| 17 |
+
root_dir = examples.__name__.replace(".", "/")
|
| 18 |
+
assert os.path.exists(root_dir)
|
| 19 |
+
with open(os.path.join(root_dir, sys.argv[1] + ".py"), "w") as f:
|
| 20 |
+
print("Writing to", f.name, "...")
|
| 21 |
+
f.write(TEMPLATE.format(case_name=sys.argv[1]))
|
data/tefig/envs/olmes-eval/lib/python3.10/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
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/node_metadata.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
NodeMetadataValue = Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
PROTECTED_KEYS: set[str] = {
|
| 8 |
+
"val",
|
| 9 |
+
"stack_trace",
|
| 10 |
+
"nn_module_stack",
|
| 11 |
+
"debug_handle",
|
| 12 |
+
"tensor_meta",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class NodeMetadata:
|
| 17 |
+
def __init__(self, data: dict[str, Any]) -> None:
|
| 18 |
+
self.data: dict[str, Any] = data.copy()
|
| 19 |
+
|
| 20 |
+
def __getitem__(self, key: str) -> NodeMetadataValue:
|
| 21 |
+
return self.data[key]
|
| 22 |
+
|
| 23 |
+
def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue:
|
| 24 |
+
if key in PROTECTED_KEYS:
|
| 25 |
+
raise RuntimeError(f"Could not override node key: {key}")
|
| 26 |
+
self.data[key] = value
|
| 27 |
+
|
| 28 |
+
def __contains__(self, key: str) -> bool:
|
| 29 |
+
return key in self.data
|
| 30 |
+
|
| 31 |
+
def copy(self) -> "NodeMetadata":
|
| 32 |
+
return NodeMetadata(self.data.copy())
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/pass_infra/proxy_value.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pyre-strict
|
| 2 |
+
from collections.abc import Iterable, Iterator
|
| 3 |
+
from typing import Generic, TypeVar, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_T = TypeVar("_T")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ProxyValue(Generic[_T]):
|
| 12 |
+
# pyre-ignore
|
| 13 |
+
def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]):
|
| 14 |
+
# pyre-ignore
|
| 15 |
+
self.data = data
|
| 16 |
+
self.proxy_or_node = proxy
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def node(self) -> torch.fx.Node:
|
| 20 |
+
if isinstance(self.proxy_or_node, torch.fx.Node):
|
| 21 |
+
return self.proxy_or_node
|
| 22 |
+
assert isinstance(self.proxy_or_node, torch.fx.Proxy)
|
| 23 |
+
return self.proxy_or_node.node
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def proxy(self) -> torch.fx.Proxy:
|
| 27 |
+
if not isinstance(self.proxy_or_node, torch.fx.Proxy):
|
| 28 |
+
raise RuntimeError(
|
| 29 |
+
f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}"
|
| 30 |
+
)
|
| 31 |
+
return self.proxy_or_node
|
| 32 |
+
|
| 33 |
+
def to_tensor(self) -> torch.Tensor:
|
| 34 |
+
assert isinstance(self.data, torch.Tensor)
|
| 35 |
+
return self.data
|
| 36 |
+
|
| 37 |
+
def is_tensor(self) -> bool:
|
| 38 |
+
return isinstance(self.data, torch.Tensor)
|
| 39 |
+
|
| 40 |
+
# pyre-ignore
|
| 41 |
+
def __iter__(self) -> Iterator[_T]:
|
| 42 |
+
yield from self.data
|
| 43 |
+
|
| 44 |
+
def __bool__(self) -> bool:
|
| 45 |
+
return bool(self.data)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass
|
data/tefig/envs/olmes-eval/lib/python3.10/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)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 13 |
+
from torch.fx.passes.infra.pass_base import PassBase, PassResult
|
| 14 |
+
from torch.utils._sympy.numbers import int_oo
|
| 15 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["InputDim"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class InputDim(NamedTuple):
|
| 22 |
+
input_name: str
|
| 23 |
+
dim: int
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _convert_to_int(val):
|
| 27 |
+
# Convert simple sympy Integers into concrete int
|
| 28 |
+
if val in (sympy.oo, int_oo):
|
| 29 |
+
return math.inf
|
| 30 |
+
if val in (-sympy.oo, -int_oo):
|
| 31 |
+
return -math.inf
|
| 32 |
+
if isinstance(val, sympy.Integer):
|
| 33 |
+
return int(val)
|
| 34 |
+
raise RuntimeError("Export constraints cannot be non-integer expressions")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _convert_range_to_int(range: ValueRanges):
|
| 38 |
+
assert isinstance(range, ValueRanges)
|
| 39 |
+
min_val = _convert_to_int(range.lower)
|
| 40 |
+
max_val = _convert_to_int(range.upper)
|
| 41 |
+
return min_val, max_val
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class _AddRuntimeAssertionsForInlineConstraintsPass(PassBase):
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
range_constraints: dict[sympy.Symbol, ValueRanges],
|
| 48 |
+
):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints
|
| 51 |
+
self._asserts_generated_unbacked_symbols: set[sympy.Symbol] = set()
|
| 52 |
+
self.counter = 0
|
| 53 |
+
|
| 54 |
+
def _assert_range_constraint(self, node, lower, upper, assert_msg):
|
| 55 |
+
last_node = node
|
| 56 |
+
if lower > -math.inf:
|
| 57 |
+
last_node = self._insert_assert_async(
|
| 58 |
+
last_node, operator.ge, node, lower, assert_msg
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if upper < math.inf:
|
| 62 |
+
last_node = self._insert_assert_async(
|
| 63 |
+
last_node, operator.le, node, upper, assert_msg
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def _insert_assert_async(self, last_node, op, lower, upper, assert_msg):
|
| 67 |
+
"""
|
| 68 |
+
Inserts assert_async call_function nodes in the graph. This function is
|
| 69 |
+
called **during** the interpreter-based pass.
|
| 70 |
+
"""
|
| 71 |
+
self.counter += 1
|
| 72 |
+
graph = last_node.graph
|
| 73 |
+
with graph.inserting_after(last_node):
|
| 74 |
+
cmp = graph.call_function(op, (lower, upper), {})
|
| 75 |
+
with graph.inserting_after(cmp):
|
| 76 |
+
cmp_tensor = graph.call_function(
|
| 77 |
+
torch.ops.aten.scalar_tensor.default, (cmp,), {}
|
| 78 |
+
)
|
| 79 |
+
with graph.inserting_after(cmp_tensor):
|
| 80 |
+
assert_async = graph.call_function(
|
| 81 |
+
torch.ops.aten._assert_async.msg,
|
| 82 |
+
(cmp_tensor, assert_msg),
|
| 83 |
+
{},
|
| 84 |
+
)
|
| 85 |
+
return assert_async
|
| 86 |
+
|
| 87 |
+
def call(self, graph_module) -> PassResult:
|
| 88 |
+
self.existing_inline_assertions = _get_existing_inline_assertions(
|
| 89 |
+
graph_module, self.range_constraints
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
for module in graph_module.modules():
|
| 93 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 94 |
+
continue
|
| 95 |
+
for node in module.graph.nodes:
|
| 96 |
+
if node.op != "call_function":
|
| 97 |
+
continue
|
| 98 |
+
if "val" not in node.meta:
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
val = node.meta["val"]
|
| 102 |
+
# In general, we may have to deal the case such as: ret[1].shape[0].
|
| 103 |
+
# We need first find out what symbols require assertion, then we need to follow the path
|
| 104 |
+
# from ret to the symbol, construct the proxies along the way and construct the messages
|
| 105 |
+
# piece-wise at the same time.
|
| 106 |
+
#
|
| 107 |
+
# We use post-order traversal to collect all the proxies callbacks needed, construct
|
| 108 |
+
# the error message callbacks, and at the top-level traversal tree we execute all the callbacks.
|
| 109 |
+
# We need the callbacks because, in order to call the function to create a proxy for shape[0], we
|
| 110 |
+
# need the proxy for shape, which further requires the proxy for ret[1], etc.
|
| 111 |
+
|
| 112 |
+
def add_assertions(val):
|
| 113 |
+
call_backs: list[Callable] = []
|
| 114 |
+
messages: list[str] = []
|
| 115 |
+
if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)):
|
| 116 |
+
symbol = val.node.expr
|
| 117 |
+
if symbol in self.existing_inline_assertions:
|
| 118 |
+
return call_backs, messages
|
| 119 |
+
if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols(
|
| 120 |
+
symbol
|
| 121 |
+
):
|
| 122 |
+
if symbol in self._asserts_generated_unbacked_symbols:
|
| 123 |
+
return call_backs, messages
|
| 124 |
+
# We only care about unbacked symints for these inline
|
| 125 |
+
# constraints, which are prefixed with 'u'
|
| 126 |
+
constraint = self.range_constraints[symbol]
|
| 127 |
+
min_val, max_val = _convert_range_to_int(constraint)
|
| 128 |
+
assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]."
|
| 129 |
+
call_backs.append(
|
| 130 |
+
partial(
|
| 131 |
+
self._assert_range_constraint,
|
| 132 |
+
lower=min_val,
|
| 133 |
+
upper=max_val,
|
| 134 |
+
)
|
| 135 |
+
)
|
| 136 |
+
messages.append(assert_msg)
|
| 137 |
+
self._asserts_generated_unbacked_symbols.add(symbol)
|
| 138 |
+
|
| 139 |
+
elif isinstance(val, torch.Tensor):
|
| 140 |
+
for i, sym in enumerate(val.shape):
|
| 141 |
+
cbs, msgs = add_assertions(sym)
|
| 142 |
+
for cb, msg in zip(cbs, msgs):
|
| 143 |
+
|
| 144 |
+
def sym_size_cb(node, assert_msg, dim):
|
| 145 |
+
with node.graph.inserting_after(node):
|
| 146 |
+
dim_node = module.graph.call_function(
|
| 147 |
+
torch.ops.aten.sym_size.int,
|
| 148 |
+
(node, dim),
|
| 149 |
+
{},
|
| 150 |
+
)
|
| 151 |
+
cb(node=dim_node, assert_msg=assert_msg)
|
| 152 |
+
|
| 153 |
+
call_backs.append(partial(sym_size_cb, dim=i))
|
| 154 |
+
messages.append(f".shape[{i}]" + msg)
|
| 155 |
+
return call_backs, messages
|
| 156 |
+
|
| 157 |
+
callbacks, messages = add_assertions(val)
|
| 158 |
+
for cb, msg in zip(callbacks, messages):
|
| 159 |
+
cb(node=node, assert_msg=f"{node}" + msg)
|
| 160 |
+
|
| 161 |
+
module.recompile()
|
| 162 |
+
|
| 163 |
+
# Sometimes this pass would return a wrong graph where we have mismatched
|
| 164 |
+
# node names in signature. Before we fix it, let's just skip it.
|
| 165 |
+
if (
|
| 166 |
+
self.counter == 0
|
| 167 |
+
and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass
|
| 168 |
+
):
|
| 169 |
+
return PassResult(graph_module, False)
|
| 170 |
+
|
| 171 |
+
# Populate the stack trace with dummy vals to respect IR
|
| 172 |
+
for node in graph_module.graph.nodes:
|
| 173 |
+
if not node.meta.get("stack_trace", None) and node.op not in [
|
| 174 |
+
"placeholder",
|
| 175 |
+
"output",
|
| 176 |
+
]:
|
| 177 |
+
node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1))
|
| 178 |
+
return PassResult(graph_module, True)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _get_existing_inline_assertions(
|
| 182 |
+
graph_module: torch.fx.GraphModule,
|
| 183 |
+
range_constraints: dict[sympy.Symbol, ValueRanges],
|
| 184 |
+
) -> dict[sympy.Symbol, ValueRanges]:
|
| 185 |
+
existing_inline_assertions: dict[sympy.Symbol, ValueRanges] = {}
|
| 186 |
+
|
| 187 |
+
for module in graph_module.modules():
|
| 188 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
# Find all the existing inline assertions. They will look something like:
|
| 192 |
+
# %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {})
|
| 193 |
+
# %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {})
|
| 194 |
+
# %_assert_scalar = call_function[target=torch.ops.aten._assert_scalar.default](args = (%scalar_tensor, "..."), kwargs = {})
|
| 195 |
+
for node in module.graph.nodes:
|
| 196 |
+
if node.target != torch.ops.aten._assert_scalar.default:
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
compare_arg = node.args[0]
|
| 200 |
+
if not (
|
| 201 |
+
isinstance(compare_arg, torch.fx.Node)
|
| 202 |
+
and compare_arg.op == "call_function"
|
| 203 |
+
and compare_arg.target in (operator.le, operator.ge)
|
| 204 |
+
and len(compare_arg.args) == 2
|
| 205 |
+
):
|
| 206 |
+
continue
|
| 207 |
+
|
| 208 |
+
compare_op = compare_arg.target
|
| 209 |
+
lhs, rhs = compare_arg.args
|
| 210 |
+
|
| 211 |
+
def maybe_get_symint(x):
|
| 212 |
+
if (
|
| 213 |
+
isinstance(x, torch.fx.Node)
|
| 214 |
+
and "val" in x.meta
|
| 215 |
+
and isinstance(x.meta["val"], torch.SymInt)
|
| 216 |
+
):
|
| 217 |
+
return x.meta["val"].node.expr
|
| 218 |
+
return x
|
| 219 |
+
|
| 220 |
+
lhs = maybe_get_symint(lhs)
|
| 221 |
+
rhs = maybe_get_symint(rhs)
|
| 222 |
+
|
| 223 |
+
if compare_op == operator.ge:
|
| 224 |
+
lhs, rhs = rhs, lhs
|
| 225 |
+
|
| 226 |
+
if isinstance(lhs, sympy.Symbol) and isinstance(rhs, int):
|
| 227 |
+
symint = lhs
|
| 228 |
+
scalar = rhs
|
| 229 |
+
elif isinstance(rhs, sympy.Symbol) and isinstance(lhs, int):
|
| 230 |
+
symint = rhs
|
| 231 |
+
scalar = lhs
|
| 232 |
+
else:
|
| 233 |
+
continue
|
| 234 |
+
|
| 235 |
+
if symint not in range_constraints:
|
| 236 |
+
raise RuntimeError(
|
| 237 |
+
f"Unable to find symint {symint} in {range_constraints}"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
previous_range = existing_inline_assertions.get(
|
| 241 |
+
symint, ValueRanges(-math.inf, math.inf)
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
if symint is lhs:
|
| 245 |
+
bounds = ValueRanges(-math.inf, scalar)
|
| 246 |
+
else:
|
| 247 |
+
bounds = ValueRanges(scalar, math.inf)
|
| 248 |
+
existing_inline_assertions[symint] = previous_range & bounds
|
| 249 |
+
|
| 250 |
+
return existing_inline_assertions
|
data/tefig/envs/olmes-eval/lib/python3.10/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
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/constant_folding.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._export.pass_base import (
|
| 6 |
+
_ExportPassBaseDeprecatedDoNotUse,
|
| 7 |
+
Argument,
|
| 8 |
+
PassResult,
|
| 9 |
+
)
|
| 10 |
+
from torch._export.pass_infra.node_metadata import NodeMetadata
|
| 11 |
+
from torch._export.pass_infra.proxy_value import ProxyValue
|
| 12 |
+
from torch._ops import OpOverload
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
aten = torch.ops.aten
|
| 16 |
+
|
| 17 |
+
_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: dict[OpOverload, OpOverload] = {
|
| 18 |
+
aten.sym_constrain_range.default: aten._functional_sym_constrain_range.default,
|
| 19 |
+
aten._assert_async.msg: aten._functional_assert_async.msg,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class _FunctionalizeSideEffectfulOpsPass(_ExportPassBaseDeprecatedDoNotUse):
|
| 24 |
+
"""
|
| 25 |
+
Functionalize ops with side effect in graph module by replacing the op with
|
| 26 |
+
functional version of it. A new dependency token (`dep_token`) will be
|
| 27 |
+
created and propagated through functional ops to output.
|
| 28 |
+
For example:
|
| 29 |
+
```
|
| 30 |
+
def f(x):
|
| 31 |
+
sym_constrain_range(x.shape[0], min=1, max=3)
|
| 32 |
+
return x.add(3)
|
| 33 |
+
```
|
| 34 |
+
Will be transformed to:
|
| 35 |
+
```
|
| 36 |
+
def f(x):
|
| 37 |
+
dep_token0 = _make_dep_token()
|
| 38 |
+
dep_token1 = _functional_sym_constrain_range(
|
| 39 |
+
x.shape[0], min=1, max=3, dep_token=dep_token0
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return x.add(3), dep_token1
|
| 43 |
+
```
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
self._dep_token: Optional[ProxyValue] = None
|
| 49 |
+
self._next_dep_token_index: Optional[int] = None
|
| 50 |
+
|
| 51 |
+
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
|
| 52 |
+
# Early return if no non-functional assertions.
|
| 53 |
+
if not any(
|
| 54 |
+
n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS
|
| 55 |
+
for n in graph_module.graph.nodes
|
| 56 |
+
):
|
| 57 |
+
return PassResult(graph_module=graph_module, modified=False)
|
| 58 |
+
|
| 59 |
+
gm = copy.deepcopy(graph_module)
|
| 60 |
+
self._dep_token = None
|
| 61 |
+
self._next_dep_token_index = None
|
| 62 |
+
return super().call(gm)
|
| 63 |
+
|
| 64 |
+
def call_operator(
|
| 65 |
+
self,
|
| 66 |
+
op: OpOverload,
|
| 67 |
+
args: tuple[Argument, ...],
|
| 68 |
+
kwargs: dict[str, Argument],
|
| 69 |
+
meta: NodeMetadata,
|
| 70 |
+
) -> ProxyValue:
|
| 71 |
+
if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS:
|
| 72 |
+
return super().call_operator(op, args, kwargs, meta)
|
| 73 |
+
|
| 74 |
+
if self._dep_token is None:
|
| 75 |
+
self._dep_token = super().call_operator(
|
| 76 |
+
aten._make_dep_token,
|
| 77 |
+
args=(),
|
| 78 |
+
kwargs={},
|
| 79 |
+
meta=self._create_dummy_node_metadata(),
|
| 80 |
+
)
|
| 81 |
+
self._dep_token.node.name = "dep_token0"
|
| 82 |
+
self._next_dep_token_index = 1
|
| 83 |
+
|
| 84 |
+
self._dep_token = super().call_operator(
|
| 85 |
+
_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op],
|
| 86 |
+
args=args,
|
| 87 |
+
kwargs={**kwargs, "dep_token": self._dep_token},
|
| 88 |
+
meta=meta,
|
| 89 |
+
)
|
| 90 |
+
assert self._next_dep_token_index is not None
|
| 91 |
+
self._dep_token.node.name = f"dep_token{self._next_dep_token_index}"
|
| 92 |
+
self._next_dep_token_index += 1
|
| 93 |
+
|
| 94 |
+
return self._dep_token
|
| 95 |
+
|
| 96 |
+
def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue:
|
| 97 |
+
assert self._dep_token is not None
|
| 98 |
+
|
| 99 |
+
return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/insert_custom_op_guards.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._export.passes._node_metadata_hook import (
|
| 6 |
+
_node_metadata_hook,
|
| 7 |
+
_set_node_metadata_hook,
|
| 8 |
+
)
|
| 9 |
+
from torch._library.fake_profile import OpProfile, TensorMetadata
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def insert_custom_op_guards(gm: torch.fx.GraphModule, ops_to_guard: set[str]) -> None:
|
| 13 |
+
"""
|
| 14 |
+
This is used by draft_export to insert guards in front of calls to custom
|
| 15 |
+
operators which have a generated fake kernel.
|
| 16 |
+
"""
|
| 17 |
+
for node in gm.graph.nodes:
|
| 18 |
+
if node.op == "call_function" and str(node.target) in ops_to_guard:
|
| 19 |
+
with _set_node_metadata_hook(
|
| 20 |
+
gm,
|
| 21 |
+
functools.partial(
|
| 22 |
+
_node_metadata_hook, stack_trace=node.meta.get("stack_trace")
|
| 23 |
+
),
|
| 24 |
+
), gm.graph.inserting_before(node):
|
| 25 |
+
for arg in (*node.args, *node.kwargs.values()):
|
| 26 |
+
if isinstance(arg, torch.fx.Node) and isinstance(
|
| 27 |
+
arg.meta.get("val"), torch.Tensor
|
| 28 |
+
):
|
| 29 |
+
val = arg.meta["val"]
|
| 30 |
+
gm.graph.call_function(
|
| 31 |
+
torch.ops.aten._assert_tensor_metadata.default,
|
| 32 |
+
args=(arg,),
|
| 33 |
+
kwargs={
|
| 34 |
+
"dtype": val.dtype,
|
| 35 |
+
"device": val.device,
|
| 36 |
+
"layout": val.layout,
|
| 37 |
+
},
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
gm.recompile()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_op_profiles(
|
| 44 |
+
gm: torch.fx.GraphModule, ops_to_guard: set[str]
|
| 45 |
+
) -> dict[str, set[OpProfile]]:
|
| 46 |
+
"""
|
| 47 |
+
This is used by draft_export to get a list of custom operator profiles so
|
| 48 |
+
that we can generate fake kernels.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def _get_op_profile(node: torch.fx.Node) -> OpProfile:
|
| 52 |
+
args_profile = tuple(
|
| 53 |
+
[
|
| 54 |
+
TensorMetadata.maybe_from_tensor(arg.meta.get("val"))
|
| 55 |
+
if isinstance(arg, torch.fx.Node)
|
| 56 |
+
else None
|
| 57 |
+
for arg in (*node.args, *node.kwargs.values())
|
| 58 |
+
]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
out_profile = None
|
| 62 |
+
meta = node.meta.get("val")
|
| 63 |
+
assert meta is not None
|
| 64 |
+
if isinstance(meta, torch.Tensor):
|
| 65 |
+
out_profile = TensorMetadata.maybe_from_tensor(meta)
|
| 66 |
+
elif isinstance(meta, (list, tuple)):
|
| 67 |
+
out_profile = tuple([TensorMetadata.maybe_from_tensor(m) for m in meta]) # type: ignore[assignment]
|
| 68 |
+
assert out_profile is not None
|
| 69 |
+
|
| 70 |
+
return OpProfile(args_profile, out_profile) # type: ignore[arg-type]
|
| 71 |
+
|
| 72 |
+
op_profiles: dict[str, set[OpProfile]] = defaultdict(set)
|
| 73 |
+
|
| 74 |
+
for node in gm.graph.nodes:
|
| 75 |
+
if node.op == "call_function" and str(node.target) in ops_to_guard:
|
| 76 |
+
op_profiles[str(node.target)].add(_get_op_profile(node))
|
| 77 |
+
|
| 78 |
+
return op_profiles
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/lift_constants_pass.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import collections
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Any, Optional, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._export.verifier import SpecViolationError
|
| 8 |
+
from torch._guards import detect_fake_mode
|
| 9 |
+
from torch._library.fake_class_registry import FakeScriptObject
|
| 10 |
+
from torch._subclasses.fake_tensor import unset_fake_temporarily
|
| 11 |
+
from torch.export.exported_program import (
|
| 12 |
+
ArgumentSpec,
|
| 13 |
+
CustomObjArgument,
|
| 14 |
+
ExportGraphSignature,
|
| 15 |
+
InputKind,
|
| 16 |
+
InputSpec,
|
| 17 |
+
TensorArgument,
|
| 18 |
+
)
|
| 19 |
+
from torch.fx._symbolic_trace import _ConstantAttributeType
|
| 20 |
+
from torch.fx.graph_module import _get_attr
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ConstantAttrMap(collections.abc.MutableMapping):
|
| 27 |
+
"""A mapping class that understands how to use module constants (tensors,
|
| 28 |
+
ScriptObjects, FakeScriptObjects) as keys. We store tensors and FakeScriptObjects normally,
|
| 29 |
+
but ScriptObjects are stored by hash, because different torch.ScriptObjects can point to
|
| 30 |
+
the same underlying value (but we guarantee that they will `hash()` to the same value
|
| 31 |
+
if that's the case).
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self) -> None:
|
| 35 |
+
# Underlying dict that we use to implement this mapping.
|
| 36 |
+
self._constant_attrs: dict[
|
| 37 |
+
Union[int, torch.Tensor, FakeScriptObject, torch.utils._pytree.TreeSpec],
|
| 38 |
+
list[Any],
|
| 39 |
+
] = {}
|
| 40 |
+
# Map from the hash(ScriptObject) to the ScriptObject itself. Used for
|
| 41 |
+
# APIs like `__iter__` that should look like they're returning the
|
| 42 |
+
# original ScriptObjects.
|
| 43 |
+
self._script_object_map: dict[int, torch.ScriptObject] = {}
|
| 44 |
+
|
| 45 |
+
def __getitem__(self, key: _ConstantAttributeType) -> Any:
|
| 46 |
+
real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
|
| 47 |
+
assert isinstance(real_key, (int, torch.Tensor, FakeScriptObject))
|
| 48 |
+
return self._constant_attrs[real_key]
|
| 49 |
+
|
| 50 |
+
def __setitem__(self, key: _ConstantAttributeType, value):
|
| 51 |
+
# we shouldn't actually call this, should go to add() instead to handle aliasing
|
| 52 |
+
raise NotImplementedError(
|
| 53 |
+
"""Directly setting values for ConstantAttrMap is not supported, please use add(key, value) instead.
|
| 54 |
+
The same key can be mapped to multiple values, for handling constant aliasing."""
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def add(self, key: _ConstantAttributeType, value: Any) -> None:
|
| 58 |
+
if isinstance(key, torch.ScriptObject):
|
| 59 |
+
if hash(key) not in self._constant_attrs:
|
| 60 |
+
self._constant_attrs[hash(key)] = []
|
| 61 |
+
self._constant_attrs[hash(key)].append(value)
|
| 62 |
+
self._script_object_map[hash(key)] = key
|
| 63 |
+
elif isinstance(key, (torch.Tensor, FakeScriptObject)):
|
| 64 |
+
if key not in self._constant_attrs:
|
| 65 |
+
self._constant_attrs[key] = []
|
| 66 |
+
self._constant_attrs[key].append(value)
|
| 67 |
+
else:
|
| 68 |
+
raise TypeError(
|
| 69 |
+
f"Expected key to be a tensor or ScriptObject, got {type(key)}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def __delitem__(self, key: _ConstantAttributeType):
|
| 73 |
+
real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
|
| 74 |
+
|
| 75 |
+
del self._constant_attrs[real_key]
|
| 76 |
+
|
| 77 |
+
def __iter__(self):
|
| 78 |
+
for key in self._constant_attrs:
|
| 79 |
+
if isinstance(key, int):
|
| 80 |
+
yield self._script_object_map[key]
|
| 81 |
+
else:
|
| 82 |
+
yield key
|
| 83 |
+
|
| 84 |
+
def __len__(self):
|
| 85 |
+
return len(self._constant_attrs)
|
| 86 |
+
|
| 87 |
+
def __contains__(self, key: object) -> bool:
|
| 88 |
+
real_key = hash(key) if isinstance(key, torch.ScriptObject) else key
|
| 89 |
+
return real_key in self._constant_attrs
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def get_constant_fqn(node: torch.fx.Node, constant_name: str) -> str:
|
| 93 |
+
# The FQN of the constant tensor in the state dict should
|
| 94 |
+
# correspond to the module where the constant tensor was
|
| 95 |
+
# originally used.
|
| 96 |
+
if len(node.meta["nn_module_stack"]) == 0:
|
| 97 |
+
return constant_name
|
| 98 |
+
parent_fqn = list(node.meta["nn_module_stack"].values())[-1][0]
|
| 99 |
+
if len(parent_fqn) > 0:
|
| 100 |
+
return f"{parent_fqn}.{constant_name}"
|
| 101 |
+
else:
|
| 102 |
+
return constant_name
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _get_first_fqn(
|
| 106 |
+
const_attrs: ConstantAttrMap,
|
| 107 |
+
key: _ConstantAttributeType,
|
| 108 |
+
) -> Any:
|
| 109 |
+
fqns = const_attrs.get(key)
|
| 110 |
+
return fqns[0] if fqns else None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _unused_constant(node: torch.fx.Node) -> Optional[list[torch.fx.Node]]:
|
| 114 |
+
"""
|
| 115 |
+
If there is a tensor constant created while tracing, here is how the graph
|
| 116 |
+
looks like:
|
| 117 |
+
|
| 118 |
+
%_tensor_constant0 : [num_users=1] = get_attr[target=_tensor_constant0]
|
| 119 |
+
%lift_fresh_copy : [num_users=1] = call_function[target=torch.ops.aten.lift_fresh_copy.default](args = (%_tensor_constant0,))
|
| 120 |
+
%detach_ : [num_users=?] = call_function[target=torch.ops.aten.detach_.default](args = (%lift_fresh_copy,))
|
| 121 |
+
|
| 122 |
+
To check to see if the tensor constant is being used, we want to traverse to
|
| 123 |
+
the detach node to see if it's actually being used.
|
| 124 |
+
|
| 125 |
+
This function returns None if this constant is being used, otherwise it returns the
|
| 126 |
+
lift_fresh and detach node to be removed later.
|
| 127 |
+
""" # noqa: B950
|
| 128 |
+
if len(node.users) > 1:
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
lift_fresh_node = next(iter(node.users.keys()))
|
| 132 |
+
if not (
|
| 133 |
+
lift_fresh_node.op == "call_function"
|
| 134 |
+
and lift_fresh_node.target
|
| 135 |
+
in (
|
| 136 |
+
torch.ops.aten.lift_fresh.default,
|
| 137 |
+
torch.ops.aten.lift_fresh_copy.default,
|
| 138 |
+
)
|
| 139 |
+
):
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
if len(lift_fresh_node.users) > 1:
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
detach_node = next(iter(lift_fresh_node.users.keys()))
|
| 146 |
+
if not (
|
| 147 |
+
detach_node.op == "call_function"
|
| 148 |
+
and detach_node.target
|
| 149 |
+
in (
|
| 150 |
+
torch.ops.aten.detach_.default,
|
| 151 |
+
torch.ops.aten.detach.default,
|
| 152 |
+
)
|
| 153 |
+
):
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
if len(detach_node.users) > 0:
|
| 157 |
+
return None
|
| 158 |
+
else:
|
| 159 |
+
return [detach_node, lift_fresh_node, node]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def lift_constants_pass(
|
| 163 |
+
gm: torch.fx.GraphModule,
|
| 164 |
+
graph_signature: ExportGraphSignature,
|
| 165 |
+
constant_attrs: ConstantAttrMap,
|
| 166 |
+
) -> dict[str, _ConstantAttributeType]:
|
| 167 |
+
"""
|
| 168 |
+
Takes a graph module, graph signature, and modifies them implace to lift any
|
| 169 |
+
constants (tensors or custom classes) as inputs to the graph. Returns a
|
| 170 |
+
dictionary of names to constants.
|
| 171 |
+
|
| 172 |
+
Arguments:
|
| 173 |
+
gm (torch.fx.GraphModule): The graph module containing the graph and constants to lift.
|
| 174 |
+
graph_signature (ExportGraphSignature): This graph signature will be
|
| 175 |
+
mutated to add additional CONSTANT_TENSOR and CUSTOM_OBJ inputs.
|
| 176 |
+
constant_attrs (ConstantAttr): A mapping from a constant value to its
|
| 177 |
+
fully-qualified path in `gm`. This is used to maintain consistent
|
| 178 |
+
location of constants between the original module and the exported
|
| 179 |
+
version.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
A dictionary of fqn => constant value.
|
| 183 |
+
"""
|
| 184 |
+
all_constants: dict[str, _ConstantAttributeType] = {}
|
| 185 |
+
|
| 186 |
+
inputs = graph_signature.input_specs
|
| 187 |
+
num_custom_obj = sum(
|
| 188 |
+
input_specs.kind == InputKind.CUSTOM_OBJ for input_specs in inputs
|
| 189 |
+
)
|
| 190 |
+
num_tensor_constants = sum(
|
| 191 |
+
input_specs.kind == InputKind.CONSTANT_TENSOR for input_specs in inputs
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
fake_mode = detect_fake_mode(
|
| 195 |
+
tuple(node.meta["val"] for node in gm.graph.nodes if node.op == "placeholder")
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
first_user_input_loc, first_user_input = 0, next(iter(gm.graph.nodes))
|
| 199 |
+
used_target_names = set()
|
| 200 |
+
for node in gm.graph.nodes:
|
| 201 |
+
if node.op == "placeholder":
|
| 202 |
+
if node.name in graph_signature.user_inputs:
|
| 203 |
+
first_user_input = node
|
| 204 |
+
break
|
| 205 |
+
used_target_names.add(inputs[first_user_input_loc].target)
|
| 206 |
+
first_user_input_loc += 1
|
| 207 |
+
# If we ever hit here, it means that
|
| 208 |
+
# there was no user input so the constants
|
| 209 |
+
# should be inserted right before the first
|
| 210 |
+
# non-placeholder node.
|
| 211 |
+
if node.op != "placeholder":
|
| 212 |
+
first_user_input = node
|
| 213 |
+
break
|
| 214 |
+
|
| 215 |
+
lifted_objs = ConstantAttrMap()
|
| 216 |
+
renamed_targets = {}
|
| 217 |
+
for node in list(gm.graph.nodes):
|
| 218 |
+
if node.op == "get_attr":
|
| 219 |
+
if nodes_to_remove := _unused_constant(node):
|
| 220 |
+
# Remove the node if it's not being used
|
| 221 |
+
for node_rm in nodes_to_remove:
|
| 222 |
+
gm.graph.erase_node(node_rm)
|
| 223 |
+
continue
|
| 224 |
+
|
| 225 |
+
constant_val = _get_attr(gm, node.target)
|
| 226 |
+
# These are not hashable and not gonna be lifted
|
| 227 |
+
# so we can skip them earlier
|
| 228 |
+
if isinstance(constant_val, torch.fx.GraphModule):
|
| 229 |
+
continue
|
| 230 |
+
if "LoweredBackendModule" in type(constant_val).__name__:
|
| 231 |
+
continue
|
| 232 |
+
if "AOTInductorRunnerWrapper" in type(constant_val).__name__:
|
| 233 |
+
continue
|
| 234 |
+
if isinstance(constant_val, torch.utils._pytree.TreeSpec):
|
| 235 |
+
continue
|
| 236 |
+
|
| 237 |
+
if constant_val in lifted_objs:
|
| 238 |
+
# We already lifted this constant elsewhere. Just rewrite uses
|
| 239 |
+
# of this get_attr to point to the already-existing placeholder
|
| 240 |
+
# node.
|
| 241 |
+
const_placeholder_node = _get_first_fqn(lifted_objs, constant_val)
|
| 242 |
+
node.replace_all_uses_with(const_placeholder_node)
|
| 243 |
+
gm.graph.erase_node(node)
|
| 244 |
+
renamed_targets[node.name] = const_placeholder_node.name
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
# For ScriptObject, Tensor and FakeScriptObject constants:
|
| 248 |
+
# First check if the constant was an attribute on some module by
|
| 249 |
+
# consulting `constant_attrs` map. If it is, use the fqn that keeps
|
| 250 |
+
# its location consistent with the eager module.
|
| 251 |
+
#
|
| 252 |
+
# If it's not in the `constant_attrs` map, that means it's an inline
|
| 253 |
+
# constant (e.g. x + torch.tensor(0)), and thus did not have a
|
| 254 |
+
# specific location in the eager module. In that case, just generate
|
| 255 |
+
# some name and attach it to the module in which it was used.
|
| 256 |
+
if isinstance(constant_val, (torch.ScriptObject, FakeScriptObject)):
|
| 257 |
+
constant_kind = InputKind.CUSTOM_OBJ
|
| 258 |
+
constant_fqn = _get_first_fqn(constant_attrs, constant_val)
|
| 259 |
+
if constant_fqn is not None:
|
| 260 |
+
constant_name = constant_fqn.replace(".", "_")
|
| 261 |
+
else:
|
| 262 |
+
constant_name = f"lifted_custom_{num_custom_obj}"
|
| 263 |
+
constant_fqn = get_constant_fqn(node, constant_name)
|
| 264 |
+
while constant_fqn in used_target_names:
|
| 265 |
+
num_custom_obj += 1
|
| 266 |
+
constant_name = f"lifted_custom_{num_custom_obj}"
|
| 267 |
+
constant_fqn = get_constant_fqn(node, constant_name)
|
| 268 |
+
num_custom_obj += 1
|
| 269 |
+
elif isinstance(constant_val, torch.Tensor):
|
| 270 |
+
# Remove the parameterness of constant_val
|
| 271 |
+
if isinstance(constant_val, torch.nn.Parameter):
|
| 272 |
+
log.debug(
|
| 273 |
+
"%s created when tracing %s is a parameter. But "
|
| 274 |
+
"it's not registered with register_parameter(). export will treat it as a constant tensor",
|
| 275 |
+
str(node.target),
|
| 276 |
+
str(node.meta.get("stack_trace", "<unknown stack>")),
|
| 277 |
+
)
|
| 278 |
+
# We get the real data out of the parameter by disabling the surrounding fake mode.
|
| 279 |
+
with unset_fake_temporarily():
|
| 280 |
+
constant_val = constant_val.data
|
| 281 |
+
constant_kind = InputKind.CONSTANT_TENSOR
|
| 282 |
+
constant_fqn = _get_first_fqn(constant_attrs, constant_val)
|
| 283 |
+
if constant_fqn is not None:
|
| 284 |
+
constant_name = constant_fqn.replace(".", "_")
|
| 285 |
+
else:
|
| 286 |
+
constant_name = f"lifted_tensor_{num_tensor_constants}"
|
| 287 |
+
constant_fqn = get_constant_fqn(node, constant_name)
|
| 288 |
+
while constant_fqn in used_target_names:
|
| 289 |
+
num_tensor_constants += 1
|
| 290 |
+
constant_name = f"lifted_tensor_{num_tensor_constants}"
|
| 291 |
+
constant_fqn = get_constant_fqn(node, constant_name)
|
| 292 |
+
num_tensor_constants += 1
|
| 293 |
+
else:
|
| 294 |
+
raise SpecViolationError(
|
| 295 |
+
f"getattr node {node} referencing unsupported type {type(constant_val)}"
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
with gm.graph.inserting_before(first_user_input):
|
| 299 |
+
# Insert the constant node before the first user input
|
| 300 |
+
const_placeholder_node = gm.graph.placeholder(constant_name)
|
| 301 |
+
# match target name with its node name in case there is name collision
|
| 302 |
+
# and suffix is added to node name in fx
|
| 303 |
+
const_placeholder_node.target = const_placeholder_node.name
|
| 304 |
+
|
| 305 |
+
for k, v in node.meta.items():
|
| 306 |
+
const_placeholder_node.meta[k] = v
|
| 307 |
+
|
| 308 |
+
# Once the FQN has been used, remove nn_module_stack, stack_trace
|
| 309 |
+
const_placeholder_node.meta.pop("nn_module_stack")
|
| 310 |
+
const_placeholder_node.meta.pop("stack_trace", None)
|
| 311 |
+
|
| 312 |
+
input_spec_arg: ArgumentSpec
|
| 313 |
+
if isinstance(constant_val, torch.Tensor):
|
| 314 |
+
if fake_mode is not None:
|
| 315 |
+
const_placeholder_node.meta["val"] = fake_mode.from_tensor(
|
| 316 |
+
constant_val, static_shapes=True
|
| 317 |
+
)
|
| 318 |
+
const_placeholder_node.meta["val"].constant = constant_val
|
| 319 |
+
else:
|
| 320 |
+
const_placeholder_node.meta["val"] = constant_val
|
| 321 |
+
input_spec_arg = TensorArgument(name=const_placeholder_node.name)
|
| 322 |
+
elif isinstance(constant_val, torch._C.ScriptObject):
|
| 323 |
+
class_fqn = constant_val._type().qualified_name() # type: ignore[attr-defined]
|
| 324 |
+
const_placeholder_node.meta["val"] = CustomObjArgument(
|
| 325 |
+
constant_fqn, class_fqn
|
| 326 |
+
)
|
| 327 |
+
input_spec_arg = CustomObjArgument(
|
| 328 |
+
name=const_placeholder_node.name, class_fqn=class_fqn
|
| 329 |
+
)
|
| 330 |
+
elif isinstance(constant_val, FakeScriptObject):
|
| 331 |
+
class_fqn = constant_val.script_class_name
|
| 332 |
+
const_placeholder_node.meta["val"] = CustomObjArgument(
|
| 333 |
+
constant_fqn, class_fqn, constant_val
|
| 334 |
+
)
|
| 335 |
+
input_spec_arg = CustomObjArgument(
|
| 336 |
+
name=const_placeholder_node.name,
|
| 337 |
+
class_fqn=class_fqn,
|
| 338 |
+
fake_val=constant_val,
|
| 339 |
+
)
|
| 340 |
+
else:
|
| 341 |
+
raise SpecViolationError(
|
| 342 |
+
f"tried to lift unsupported type {type(constant_val)} from node {node.format_node()}"
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
lifted_objs.add(constant_val, const_placeholder_node)
|
| 346 |
+
node.replace_all_uses_with(const_placeholder_node)
|
| 347 |
+
gm.graph.erase_node(node)
|
| 348 |
+
|
| 349 |
+
renamed_targets[node.name] = const_placeholder_node.name
|
| 350 |
+
|
| 351 |
+
# Add the constant as a buffer to the graph signature
|
| 352 |
+
graph_signature.input_specs.insert(
|
| 353 |
+
first_user_input_loc,
|
| 354 |
+
InputSpec(
|
| 355 |
+
kind=constant_kind,
|
| 356 |
+
arg=input_spec_arg,
|
| 357 |
+
target=constant_fqn,
|
| 358 |
+
),
|
| 359 |
+
)
|
| 360 |
+
if constant_val in constant_attrs:
|
| 361 |
+
for fqn in constant_attrs[constant_val]:
|
| 362 |
+
all_constants[fqn] = constant_val
|
| 363 |
+
else:
|
| 364 |
+
all_constants[constant_fqn] = constant_val
|
| 365 |
+
first_user_input_loc += 1
|
| 366 |
+
|
| 367 |
+
for spec in graph_signature.output_specs:
|
| 368 |
+
if spec.arg.name in renamed_targets:
|
| 369 |
+
spec.arg.name = renamed_targets[spec.arg.name]
|
| 370 |
+
|
| 371 |
+
return all_constants
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def rewrite_script_object_meta(
|
| 375 |
+
gm: torch.fx.GraphModule,
|
| 376 |
+
) -> dict[str, _ConstantAttributeType,]:
|
| 377 |
+
"""When tracing, we produce a graph with FakeScriptObject in the
|
| 378 |
+
meta["val"].
|
| 379 |
+
|
| 380 |
+
For now, we rewrie meta["val"] to be a placeholder CustomObjArgument
|
| 381 |
+
"""
|
| 382 |
+
constants: dict[
|
| 383 |
+
str,
|
| 384 |
+
_ConstantAttributeType,
|
| 385 |
+
] = {}
|
| 386 |
+
for node in gm.graph.nodes:
|
| 387 |
+
if "val" not in node.meta:
|
| 388 |
+
continue
|
| 389 |
+
|
| 390 |
+
old_meta = node.meta["val"]
|
| 391 |
+
|
| 392 |
+
if isinstance(old_meta, torch.ScriptObject):
|
| 393 |
+
class_fqn = old_meta._type().qualified_name() # type: ignore[attr-defined]
|
| 394 |
+
new_meta = CustomObjArgument(node.name, class_fqn)
|
| 395 |
+
constants[node.name] = old_meta
|
| 396 |
+
node.meta["val"] = new_meta
|
| 397 |
+
|
| 398 |
+
elif isinstance(old_meta, FakeScriptObject):
|
| 399 |
+
class_fqn = old_meta.script_class_name # type: ignore[attr-defined]
|
| 400 |
+
new_meta = CustomObjArgument(node.name, class_fqn, old_meta)
|
| 401 |
+
constants[node.name] = old_meta
|
| 402 |
+
node.meta["val"] = new_meta
|
| 403 |
+
|
| 404 |
+
return constants
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _materialize_and_lift_constants(
|
| 408 |
+
gm: torch.fx.GraphModule,
|
| 409 |
+
export_graph_signature: ExportGraphSignature,
|
| 410 |
+
constant_attrs: ConstantAttrMap,
|
| 411 |
+
) -> dict[str, _ConstantAttributeType]:
|
| 412 |
+
constants = rewrite_script_object_meta(gm)
|
| 413 |
+
constants.update(lift_constants_pass(gm, export_graph_signature, constant_attrs))
|
| 414 |
+
return constants
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/remove_runtime_assertions.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.fx.passes.infra.pass_base import PassBase, PassResult
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class _RemoveRuntimeAssertionsPass(PassBase):
|
| 6 |
+
"""
|
| 7 |
+
Remove runtime assertions inserted by the
|
| 8 |
+
_AddRuntimeAssertionsForInlineConstraintsPass.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
|
| 12 |
+
modified = False
|
| 13 |
+
for module in graph_module.modules():
|
| 14 |
+
if not isinstance(module, torch.fx.GraphModule):
|
| 15 |
+
continue
|
| 16 |
+
for node in module.graph.nodes:
|
| 17 |
+
if node.target in [
|
| 18 |
+
torch.ops.aten._assert_async.msg,
|
| 19 |
+
torch.ops.aten._assert_scalar.default,
|
| 20 |
+
torch.ops.aten.sym_constrain_range_for_size.default,
|
| 21 |
+
torch.ops.aten.sym_constrain_range.default,
|
| 22 |
+
torch.ops.aten._assert_tensor_metadata.default,
|
| 23 |
+
]:
|
| 24 |
+
assert_async_node = node
|
| 25 |
+
if len(assert_async_node.users) > 0:
|
| 26 |
+
continue
|
| 27 |
+
module.graph.erase_node(assert_async_node)
|
| 28 |
+
# the upstream scalar_tensor <- {le, ge} <- sym_size
|
| 29 |
+
# linear chain of nodes of nodes is removed by the
|
| 30 |
+
# downstream dead code elimination
|
| 31 |
+
modified = True
|
| 32 |
+
|
| 33 |
+
# We don't necessarily want to run DCE here because it could affect
|
| 34 |
+
# nodes that are in the module_call_graph attribute of the exported
|
| 35 |
+
# program. We will leave it to the pass caller to call DCE.
|
| 36 |
+
return PassResult(graph_module, modified)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Optional, TYPE_CHECKING, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._higher_order_ops.wrap import wrap_with_autocast
|
| 8 |
+
|
| 9 |
+
from ..utils import node_inline_, nodes_filter, nodes_first, sequential_split
|
| 10 |
+
from .replace_with_hop_pass_util import (
|
| 11 |
+
_replace_with_hop_helper,
|
| 12 |
+
_replace_with_hop_pass_helper,
|
| 13 |
+
_sequential_split_and_maybe_inline_subgraphs_helper,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from torch.export.graph_signature import ExportGraphSignature
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _is_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
|
| 22 |
+
return (
|
| 23 |
+
node
|
| 24 |
+
and node.op == "call_function"
|
| 25 |
+
and node.target
|
| 26 |
+
in [
|
| 27 |
+
torch.amp.autocast_mode._enter_autocast,
|
| 28 |
+
torch.amp.autocast_mode._exit_autocast,
|
| 29 |
+
]
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _is_enter_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
|
| 34 |
+
return (
|
| 35 |
+
node
|
| 36 |
+
and node.op == "call_function"
|
| 37 |
+
and node.target == torch.amp.autocast_mode._enter_autocast
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _is_exit_autocast_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
|
| 42 |
+
return (
|
| 43 |
+
node
|
| 44 |
+
and node.op == "call_function"
|
| 45 |
+
and node.target == torch.amp.autocast_mode._exit_autocast
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _is_autocast_sub_mod(node: torch.fx.Node) -> bool:
|
| 50 |
+
"""
|
| 51 |
+
Check if the first non-placeholder node is `torch.amp.autocast_mode._enter_autocast`.
|
| 52 |
+
"""
|
| 53 |
+
if node.op == "call_module":
|
| 54 |
+
assert isinstance(node.target, str)
|
| 55 |
+
subgm = getattr(node.graph.owning_module, node.target)
|
| 56 |
+
first_non_ph = nodes_first(
|
| 57 |
+
subgm.graph.nodes, lambda node: node.op != "placeholder"
|
| 58 |
+
)
|
| 59 |
+
if (
|
| 60 |
+
first_non_ph
|
| 61 |
+
and first_non_ph.op == "call_function"
|
| 62 |
+
and first_non_ph.target == torch.amp.autocast_mode._enter_autocast
|
| 63 |
+
):
|
| 64 |
+
# TODO: check if current auto-cast type is the same as the args of
|
| 65 |
+
# _enter_autocast. If so, return False, i.e. do not create a submodule.
|
| 66 |
+
return True
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _check_valid_autocast_block(
|
| 71 |
+
enter_autocast_node: torch.fx.Node, exit_autocast_node: torch.fx.Node
|
| 72 |
+
) -> None:
|
| 73 |
+
assert _is_enter_autocast_node(enter_autocast_node)
|
| 74 |
+
assert _is_exit_autocast_node(exit_autocast_node)
|
| 75 |
+
assert exit_autocast_node.args[0] == enter_autocast_node
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _replace_with_hop(node: torch.fx.Node) -> None:
|
| 79 |
+
assert node.op == "call_module"
|
| 80 |
+
graph: torch.fx.Graph = node.graph
|
| 81 |
+
assert graph.owning_module is not None
|
| 82 |
+
gm: torch.fx.GraphModule = graph.owning_module
|
| 83 |
+
assert isinstance(node.target, str)
|
| 84 |
+
sub_gm = getattr(gm, node.target)
|
| 85 |
+
sub_graph = sub_gm.graph
|
| 86 |
+
autocast_nodes = nodes_filter(sub_graph.nodes, _is_autocast_node)
|
| 87 |
+
if len(autocast_nodes) > 0:
|
| 88 |
+
assert len(autocast_nodes) > 1 # need at least an enter node and an exist node
|
| 89 |
+
enter_autocast_node = autocast_nodes[0]
|
| 90 |
+
exit_autocast_node = autocast_nodes[-1]
|
| 91 |
+
_check_valid_autocast_block(enter_autocast_node, exit_autocast_node)
|
| 92 |
+
|
| 93 |
+
_replace_with_hop_helper(node, enter_autocast_node, wrap_with_autocast)
|
| 94 |
+
sub_graph.erase_node(exit_autocast_node)
|
| 95 |
+
sub_graph.erase_node(enter_autocast_node)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _split_autocast(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
|
| 99 |
+
"""
|
| 100 |
+
split_autocast creates a new graph module that splits the input graph module into multiple submodules
|
| 101 |
+
based on the `_enter_autocast` and `_exit_autocast` nodes. It doesn't mutate the input graph module.
|
| 102 |
+
|
| 103 |
+
Nodes between the **outer-most** `_enter_autocast` and `_exit_autocast(_enter_autocast)` are splitted
|
| 104 |
+
into a submodule. Nested autocast regions are not splitted.
|
| 105 |
+
`_enter_autocast` and `_exit_autocast(_enter_autocast)` nodes are in the submodule as well.
|
| 106 |
+
|
| 107 |
+
Below is an example of splitting. A, B, C, D, E are blocks of non-autocast nodes in the original graph
|
| 108 |
+
module. Nodes marked with the same number are grouped into the same submodule.
|
| 109 |
+
A # 0
|
| 110 |
+
enter_autocast # 1
|
| 111 |
+
B # 1
|
| 112 |
+
exit_autocast # 1
|
| 113 |
+
C # 2
|
| 114 |
+
enter_autocast # 3
|
| 115 |
+
D # 3
|
| 116 |
+
exit_autocast # 3
|
| 117 |
+
E # 4
|
| 118 |
+
"""
|
| 119 |
+
enter_autocast_node_stack: list[torch.fx.Node] = []
|
| 120 |
+
first_node_after_outer_most_exit: bool = False
|
| 121 |
+
|
| 122 |
+
def node_call_back(node: torch.fx.Node) -> bool:
|
| 123 |
+
nonlocal enter_autocast_node_stack, first_node_after_outer_most_exit
|
| 124 |
+
increment_id = False
|
| 125 |
+
if first_node_after_outer_most_exit or (
|
| 126 |
+
len(enter_autocast_node_stack) == 0 and _is_enter_autocast_node(node)
|
| 127 |
+
):
|
| 128 |
+
assert len(enter_autocast_node_stack) == 0
|
| 129 |
+
first_node_after_outer_most_exit = False
|
| 130 |
+
increment_id = True
|
| 131 |
+
if _is_enter_autocast_node(node):
|
| 132 |
+
enter_autocast_node_stack.append(node)
|
| 133 |
+
elif _is_exit_autocast_node(node):
|
| 134 |
+
assert len(enter_autocast_node_stack) > 0
|
| 135 |
+
last_enter_autocast_node = enter_autocast_node_stack.pop()
|
| 136 |
+
assert node.args[0] == last_enter_autocast_node
|
| 137 |
+
if len(enter_autocast_node_stack) == 0:
|
| 138 |
+
# next node should be in the next submodule since
|
| 139 |
+
# autocast block ends
|
| 140 |
+
first_node_after_outer_most_exit = True
|
| 141 |
+
return increment_id
|
| 142 |
+
|
| 143 |
+
return sequential_split(gm, node_call_back)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _sequential_split_and_maybe_inline_subgraphs(
|
| 147 |
+
gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
|
| 148 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 149 |
+
"""
|
| 150 |
+
Helper function for replace_autocast_with_hop_pass().
|
| 151 |
+
Split the graph module into multiple subgraphs based on the autocast nodes.
|
| 152 |
+
For each subgraph, decides whether to construct a HOO subgraph, or inline the calls
|
| 153 |
+
back into the parent graph module.
|
| 154 |
+
Nodes between `_enter_autocast` and `_exit_autocast(_enter_autocast)` are considered
|
| 155 |
+
as a subgraph.
|
| 156 |
+
"""
|
| 157 |
+
need_replacing = any(_is_autocast_node(node) for node in gm.graph.nodes)
|
| 158 |
+
if not need_replacing:
|
| 159 |
+
return gm, graph_signature
|
| 160 |
+
|
| 161 |
+
# split_autocast returns a new graph module that could have different output
|
| 162 |
+
# args names. We need to fix the graph signature in `_sequential_split_and_maybe_inline_subgraphs_helper`.
|
| 163 |
+
new_gm = _split_autocast(gm)
|
| 164 |
+
|
| 165 |
+
def _maybe_inline_or_replace_with_hop(node: torch.fx.Node) -> None:
|
| 166 |
+
if _is_autocast_sub_mod(node):
|
| 167 |
+
_replace_with_hop(node)
|
| 168 |
+
else:
|
| 169 |
+
assert node.op == "call_module"
|
| 170 |
+
assert isinstance(node.target, str)
|
| 171 |
+
node_inline_(node)
|
| 172 |
+
|
| 173 |
+
return _sequential_split_and_maybe_inline_subgraphs_helper(
|
| 174 |
+
new_gm, graph_signature, _maybe_inline_or_replace_with_hop
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def replace_autocast_with_hop_pass(
|
| 179 |
+
gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
|
| 180 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 181 |
+
"""
|
| 182 |
+
Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
|
| 183 |
+
then recursively call itself on each of the submodules.
|
| 184 |
+
"""
|
| 185 |
+
return _replace_with_hop_pass_helper(
|
| 186 |
+
gm,
|
| 187 |
+
graph_signature,
|
| 188 |
+
_sequential_split_and_maybe_inline_subgraphs,
|
| 189 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.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| 2 |
+
import logging
|
| 3 |
+
import operator
|
| 4 |
+
from typing import Optional, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.export._trace
|
| 8 |
+
from torch._ops import OpOverload
|
| 9 |
+
from torch.ao.quantization.fx._decomposed import (
|
| 10 |
+
dequantize_per_channel,
|
| 11 |
+
dequantize_per_tensor,
|
| 12 |
+
quantize_per_tensor,
|
| 13 |
+
)
|
| 14 |
+
from torch.ao.quantization.utils import calculate_qmin_qmax
|
| 15 |
+
from torch.fx.graph_module import _assign_attr
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
# Those values will need to be carried over multiple operators.
|
| 21 |
+
_INPUT_Q_DTYPE: Optional[Union[torch.dtype, torch.fx.Node]] = None
|
| 22 |
+
_SCALE: Optional[Union[float, torch.fx.Node]] = None
|
| 23 |
+
_ZERO_POINT: Optional[Union[float, torch.fx.Node]] = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def int_to_valid_dtype(val: int) -> torch.dtype:
|
| 27 |
+
from torch._export.converter import _TORCH_ENUM_TO_DTYPE # No circular import.
|
| 28 |
+
|
| 29 |
+
if isinstance(val, torch.dtype):
|
| 30 |
+
return val
|
| 31 |
+
dtype = _TORCH_ENUM_TO_DTYPE[val]
|
| 32 |
+
if dtype == torch.quint8:
|
| 33 |
+
return torch.uint8
|
| 34 |
+
elif dtype == torch.qint8:
|
| 35 |
+
return torch.int8
|
| 36 |
+
return dtype
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def fx_enum_to_dtype(gm: torch.fx.GraphModule, val: int) -> torch.fx.Node:
|
| 40 |
+
return gm.graph.call_function(int_to_valid_dtype, (val,))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def insert_quantized_node(
|
| 44 |
+
gm: torch.fx.GraphModule,
|
| 45 |
+
val_node: torch.fx.Node,
|
| 46 |
+
scale_node: Union[float, torch.fx.Node],
|
| 47 |
+
zero_point_node: Union[float, torch.fx.Node],
|
| 48 |
+
qmin_node: Union[float, int, torch.fx.Node],
|
| 49 |
+
qmax_node: Union[float, int, torch.fx.Node],
|
| 50 |
+
dtype_node: Union[torch.dtype, torch.fx.Node],
|
| 51 |
+
qscheme: Optional[torch.qscheme],
|
| 52 |
+
) -> torch.fx.Node:
|
| 53 |
+
return gm.graph.call_function(
|
| 54 |
+
quantize_per_tensor,
|
| 55 |
+
(
|
| 56 |
+
val_node,
|
| 57 |
+
scale_node,
|
| 58 |
+
zero_point_node,
|
| 59 |
+
qmin_node,
|
| 60 |
+
qmax_node,
|
| 61 |
+
dtype_node,
|
| 62 |
+
),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_dequantized(
|
| 67 |
+
val: torch.Tensor,
|
| 68 |
+
scale: Union[float, torch.Tensor],
|
| 69 |
+
zero_point: Union[float, torch.Tensor],
|
| 70 |
+
qmin: Union[float, int],
|
| 71 |
+
qmax: Union[float, int],
|
| 72 |
+
dtype: torch.dtype,
|
| 73 |
+
axis: Optional[int],
|
| 74 |
+
qscheme: Optional[torch.qscheme],
|
| 75 |
+
) -> torch.Tensor:
|
| 76 |
+
if qscheme is torch.per_tensor_affine:
|
| 77 |
+
return dequantize_per_tensor(
|
| 78 |
+
val,
|
| 79 |
+
scale, # type: ignore[arg-type]
|
| 80 |
+
zero_point, # type: ignore[arg-type]
|
| 81 |
+
qmin, # type: ignore[arg-type]
|
| 82 |
+
qmax, # type: ignore[arg-type]
|
| 83 |
+
dtype,
|
| 84 |
+
)
|
| 85 |
+
elif qscheme is torch.per_channel_affine:
|
| 86 |
+
return dequantize_per_channel(
|
| 87 |
+
val,
|
| 88 |
+
scale, # type: ignore[arg-type]
|
| 89 |
+
zero_point, # type: ignore[arg-type]
|
| 90 |
+
axis, # type: ignore[arg-type]
|
| 91 |
+
qmin, # type: ignore[arg-type]
|
| 92 |
+
qmax, # type: ignore[arg-type]
|
| 93 |
+
dtype,
|
| 94 |
+
)
|
| 95 |
+
else:
|
| 96 |
+
raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def insert_dequantized_node(
|
| 100 |
+
gm: torch.fx.GraphModule,
|
| 101 |
+
val_node: torch.fx.Node,
|
| 102 |
+
scale_node: Union[float, torch.fx.Node],
|
| 103 |
+
zero_point_node: Union[float, torch.fx.Node],
|
| 104 |
+
qmin_node: Union[float, int, torch.fx.Node],
|
| 105 |
+
qmax_node: Union[float, int, torch.fx.Node],
|
| 106 |
+
dtype_node: Union[torch.dtype, torch.fx.Node],
|
| 107 |
+
axis_node: Optional[Union[int, torch.fx.Node]],
|
| 108 |
+
qscheme: Optional[torch.qscheme],
|
| 109 |
+
) -> torch.fx.Node:
|
| 110 |
+
if qscheme is torch.per_tensor_affine:
|
| 111 |
+
return gm.graph.call_function(
|
| 112 |
+
dequantize_per_tensor,
|
| 113 |
+
(
|
| 114 |
+
val_node,
|
| 115 |
+
scale_node,
|
| 116 |
+
zero_point_node,
|
| 117 |
+
qmin_node,
|
| 118 |
+
qmax_node,
|
| 119 |
+
dtype_node,
|
| 120 |
+
),
|
| 121 |
+
)
|
| 122 |
+
elif qscheme is torch.per_channel_affine:
|
| 123 |
+
return gm.graph.call_function(
|
| 124 |
+
dequantize_per_channel,
|
| 125 |
+
(
|
| 126 |
+
val_node,
|
| 127 |
+
scale_node,
|
| 128 |
+
zero_point_node,
|
| 129 |
+
axis_node,
|
| 130 |
+
qmin_node,
|
| 131 |
+
qmax_node,
|
| 132 |
+
dtype_node,
|
| 133 |
+
),
|
| 134 |
+
)
|
| 135 |
+
else:
|
| 136 |
+
raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def get_qmin_qmax(dtype: torch.dtype) -> tuple[Union[int, float], Union[int, float]]:
|
| 140 |
+
return calculate_qmin_qmax(None, None, False, dtype, False) # type: ignore[arg-type]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def insert_qmin_qmax_node(
|
| 144 |
+
gm: torch.fx.GraphModule, dtype_node: Union[torch.dtype, torch.fx.Node]
|
| 145 |
+
) -> tuple[torch.fx.Node, torch.fx.Node]:
|
| 146 |
+
q_min_max_node = gm.graph.call_function(
|
| 147 |
+
calculate_qmin_qmax, (None, None, False, dtype_node, False)
|
| 148 |
+
)
|
| 149 |
+
qmin_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 0))
|
| 150 |
+
qmax_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 1))
|
| 151 |
+
return qmin_node, qmax_node
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_script_object(
|
| 155 |
+
gm: torch.nn.Module, node: torch.fx.Node
|
| 156 |
+
) -> torch._C.ScriptObject:
|
| 157 |
+
assert isinstance(node, torch.fx.Node)
|
| 158 |
+
assert node.op == "get_attr"
|
| 159 |
+
attr_name = node.target
|
| 160 |
+
assert isinstance(attr_name, str)
|
| 161 |
+
|
| 162 |
+
mod = gm
|
| 163 |
+
for attr in attr_name.split("."):
|
| 164 |
+
mod = getattr(mod, attr)
|
| 165 |
+
assert isinstance(mod, torch._C.ScriptObject)
|
| 166 |
+
return mod
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
|
| 170 |
+
gm: torch.fx.GraphModule,
|
| 171 |
+
param_node: torch.fx.Node,
|
| 172 |
+
) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
|
| 173 |
+
"""Directly inline tensor from a get_attr fx node."""
|
| 174 |
+
mod = get_script_object(gm, param_node)
|
| 175 |
+
w_qtensor, b_qtensor = mod.unpack() # type: ignore[attr-defined]
|
| 176 |
+
w_attr_name, b_attr_name = (
|
| 177 |
+
f"dequantized_{param_node.target}_w",
|
| 178 |
+
f"dequantized_{param_node.target}_b",
|
| 179 |
+
)
|
| 180 |
+
return insert_weight_and_bias_get_attr_node(
|
| 181 |
+
gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
|
| 186 |
+
gm: torch.fx.GraphModule,
|
| 187 |
+
get_attr_to_weight_node: torch.fx.Node,
|
| 188 |
+
get_attr_to_bias_node: Optional[torch.fx.Node],
|
| 189 |
+
) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
|
| 190 |
+
assert isinstance(get_attr_to_weight_node.target, str)
|
| 191 |
+
w_qtensor = getattr(gm, get_attr_to_weight_node.target)
|
| 192 |
+
w_attr_name = f"dequantized_{get_attr_to_weight_node.target}_w"
|
| 193 |
+
|
| 194 |
+
if get_attr_to_bias_node is not None:
|
| 195 |
+
assert isinstance(get_attr_to_bias_node.target, str)
|
| 196 |
+
b_qtensor = getattr(gm, get_attr_to_bias_node.target)
|
| 197 |
+
b_attr_name = f"dequantized_{get_attr_to_bias_node.target}_b"
|
| 198 |
+
else:
|
| 199 |
+
b_qtensor, b_attr_name = None, ""
|
| 200 |
+
|
| 201 |
+
return insert_weight_and_bias_get_attr_node(
|
| 202 |
+
gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def insert_weight_and_bias_get_attr_node(
|
| 207 |
+
gm: torch.fx.GraphModule,
|
| 208 |
+
w_qtensor: torch.Tensor,
|
| 209 |
+
b_qtensor: Optional[torch.Tensor],
|
| 210 |
+
w_attr_name: str,
|
| 211 |
+
b_attr_name: str,
|
| 212 |
+
) -> tuple[torch.fx.Node, Optional[torch.fx.Node]]:
|
| 213 |
+
w_tensor = get_tensor_from_qtensor(w_qtensor)
|
| 214 |
+
_assign_attr(w_tensor, gm, w_attr_name)
|
| 215 |
+
w_tensor_attr = gm.graph.get_attr(w_attr_name)
|
| 216 |
+
|
| 217 |
+
if b_qtensor is not None:
|
| 218 |
+
b_tensor = get_tensor_from_qtensor(b_qtensor, dequant=False)
|
| 219 |
+
_assign_attr(b_tensor, gm, b_attr_name)
|
| 220 |
+
b_tensor_attr = gm.graph.get_attr(b_attr_name)
|
| 221 |
+
else:
|
| 222 |
+
b_tensor_attr = None
|
| 223 |
+
|
| 224 |
+
return w_tensor_attr, b_tensor_attr
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def get_tensor_from_qtensor(
|
| 228 |
+
qtensor: torch.Tensor, dequant: bool = True
|
| 229 |
+
) -> torch.Tensor:
|
| 230 |
+
# Manual conversion because qint8 is not used anymore.
|
| 231 |
+
if qtensor.dtype in [torch.qint8, torch.quint8]:
|
| 232 |
+
tensor = qtensor.int_repr()
|
| 233 |
+
else:
|
| 234 |
+
tensor = qtensor
|
| 235 |
+
|
| 236 |
+
# Weights need dequantization with scaling and zero_point adjustment, but
|
| 237 |
+
# bias does not need that.
|
| 238 |
+
if dequant:
|
| 239 |
+
qscheme = qtensor.qscheme()
|
| 240 |
+
if qscheme == torch.per_channel_affine:
|
| 241 |
+
scale, zero_point, axis = (
|
| 242 |
+
qtensor.q_per_channel_scales(),
|
| 243 |
+
qtensor.q_per_channel_zero_points(),
|
| 244 |
+
qtensor.q_per_channel_axis(),
|
| 245 |
+
)
|
| 246 |
+
else:
|
| 247 |
+
scale, zero_point, axis = (
|
| 248 |
+
qtensor.q_scale(), # type: ignore[assignment]
|
| 249 |
+
qtensor.q_zero_point(), # type: ignore[assignment]
|
| 250 |
+
None,
|
| 251 |
+
)
|
| 252 |
+
dtype = tensor.dtype
|
| 253 |
+
qmin, qmax = get_qmin_qmax(dtype)
|
| 254 |
+
return get_dequantized(
|
| 255 |
+
tensor, scale, zero_point, qmin, qmax, dtype, axis, qscheme
|
| 256 |
+
)
|
| 257 |
+
return tensor
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def insert_fused_activation_node(
|
| 261 |
+
gm: torch.fx.GraphModule, opname: str, fx_node: torch.fx.Node
|
| 262 |
+
) -> torch.fx.Node:
|
| 263 |
+
if opname in ["conv1d_relu", "conv2d_relu", "linear_relu", "add_relu", "mul_relu"]:
|
| 264 |
+
fx_node = gm.graph.call_function(torch.ops.aten.relu, (fx_node,))
|
| 265 |
+
return fx_node
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _conv1d_op_with_squeeze(
|
| 269 |
+
inp: torch.Tensor,
|
| 270 |
+
weight: torch.Tensor,
|
| 271 |
+
bias: Optional[torch.Tensor],
|
| 272 |
+
stride: list[int],
|
| 273 |
+
padding: list[int],
|
| 274 |
+
dilation: list[int],
|
| 275 |
+
groups: int,
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
# In quantized version, conv1d is emulated using conv2d with squeeze and unsqueeze
|
| 278 |
+
# operations before and after the conv2d operation to match the dimension of weights.
|
| 279 |
+
# Reference: https://github.com/pytorch/pytorch/blob/eca0cb0fbe84bb0a34fa94afe261bceecd52c436/aten/src/ATen/native/quantized/cpu/qconv.cpp#L1827 # noqa: B950
|
| 280 |
+
s_inp = torch.ops.aten.unsqueeze(inp, 2)
|
| 281 |
+
conv1d_res = torch.ops.aten.conv2d(
|
| 282 |
+
s_inp,
|
| 283 |
+
weight,
|
| 284 |
+
bias,
|
| 285 |
+
stride,
|
| 286 |
+
padding,
|
| 287 |
+
dilation,
|
| 288 |
+
groups,
|
| 289 |
+
)
|
| 290 |
+
uns_conv1d_res = torch.ops.aten.squeeze(conv1d_res, 2)
|
| 291 |
+
return uns_conv1d_res
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _transform_conv_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
| 295 |
+
"""Conv specfic transformation function."""
|
| 296 |
+
assert isinstance(node.target, torch._ops.OpOverload)
|
| 297 |
+
opname = node.target._opname
|
| 298 |
+
scale_node, zero_point_node = node.args[2], node.args[3]
|
| 299 |
+
|
| 300 |
+
op_f = (
|
| 301 |
+
torch.ops.aten.conv2d
|
| 302 |
+
if opname in ["conv2d", "conv2d_relu"]
|
| 303 |
+
else _conv1d_op_with_squeeze
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
inp_node, param_node = node.args[0], node.args[1]
|
| 307 |
+
assert isinstance(inp_node, torch.fx.Node)
|
| 308 |
+
assert isinstance(param_node, torch.fx.Node)
|
| 309 |
+
|
| 310 |
+
if param_node.op == "call_function":
|
| 311 |
+
# Using Conv2dPrepackParam from conv_prepack.
|
| 312 |
+
# We directly skip the packing call and inline weights and bias.
|
| 313 |
+
w_node, b_node = param_node.args[0], param_node.args[1]
|
| 314 |
+
assert isinstance(w_node, torch.fx.Node)
|
| 315 |
+
assert b_node is None or isinstance(b_node, torch.fx.Node)
|
| 316 |
+
(
|
| 317 |
+
param_0,
|
| 318 |
+
param_1,
|
| 319 |
+
) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
|
| 320 |
+
gm, w_node, b_node
|
| 321 |
+
)
|
| 322 |
+
op_res_node = gm.graph.call_function(
|
| 323 |
+
op_f, (inp_node, param_0, param_1, *param_node.args[2:])
|
| 324 |
+
)
|
| 325 |
+
else:
|
| 326 |
+
# Using ConvPrepackedParam.
|
| 327 |
+
param = get_script_object(gm, param_node)
|
| 328 |
+
(
|
| 329 |
+
param_0,
|
| 330 |
+
param_1,
|
| 331 |
+
) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
|
| 332 |
+
gm, param_node
|
| 333 |
+
) # type: ignore[assignment]
|
| 334 |
+
op_res_node = gm.graph.call_function(
|
| 335 |
+
op_f,
|
| 336 |
+
(
|
| 337 |
+
inp_node,
|
| 338 |
+
param_0,
|
| 339 |
+
param_1,
|
| 340 |
+
param.stride(), # type: ignore[attr-defined]
|
| 341 |
+
param.padding(), # type: ignore[attr-defined]
|
| 342 |
+
param.dilation(), # type: ignore[attr-defined]
|
| 343 |
+
param.groups(), # type: ignore[attr-defined]
|
| 344 |
+
),
|
| 345 |
+
)
|
| 346 |
+
return op_res_node, scale_node, zero_point_node
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _transform_linear_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
| 350 |
+
"""Linear specfic transformation function."""
|
| 351 |
+
scale_node, zero_point_node = node.args[2], node.args[3]
|
| 352 |
+
|
| 353 |
+
inp_node, param_node = node.args[0], node.args[1]
|
| 354 |
+
assert isinstance(inp_node, torch.fx.Node)
|
| 355 |
+
assert isinstance(param_node, torch.fx.Node)
|
| 356 |
+
|
| 357 |
+
if param_node.op == "call_function":
|
| 358 |
+
# Using LinearPrepackParam from linear_prepack.
|
| 359 |
+
# We directly skip the packing call and inline weights and bias.
|
| 360 |
+
w_node, b_node = param_node.args[0], param_node.args[1]
|
| 361 |
+
assert isinstance(w_node, torch.fx.Node)
|
| 362 |
+
assert b_node is None or isinstance(b_node, torch.fx.Node)
|
| 363 |
+
(
|
| 364 |
+
param_0,
|
| 365 |
+
param_1,
|
| 366 |
+
) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor(
|
| 367 |
+
gm, w_node, b_node
|
| 368 |
+
)
|
| 369 |
+
op_res_node = gm.graph.call_function(
|
| 370 |
+
torch.ops.aten.linear, (inp_node, param_0, param_1, *param_node.args[2:])
|
| 371 |
+
)
|
| 372 |
+
else:
|
| 373 |
+
# Using LinearPackedParams.
|
| 374 |
+
(
|
| 375 |
+
param_0,
|
| 376 |
+
param_1,
|
| 377 |
+
) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject(
|
| 378 |
+
gm, param_node
|
| 379 |
+
) # type: ignore[assignment]
|
| 380 |
+
op_res_node = gm.graph.call_function(
|
| 381 |
+
torch.ops.aten.linear, (inp_node, param_0, param_1)
|
| 382 |
+
)
|
| 383 |
+
return op_res_node, scale_node, zero_point_node
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def _transform_op_where_last_two_arguments_are_scale_and_zero_point(
|
| 387 |
+
gm: torch.fx.GraphModule, node: torch.fx.Node
|
| 388 |
+
):
|
| 389 |
+
"""
|
| 390 |
+
This transformation function can be used for function where the last two
|
| 391 |
+
parameters are scale and zero point. Additionally, the function's parameters
|
| 392 |
+
do not need any unpacking.
|
| 393 |
+
"""
|
| 394 |
+
to_standard_op = {
|
| 395 |
+
"mul": torch.ops.aten.mul,
|
| 396 |
+
"mul_relu": torch.ops.aten.mul,
|
| 397 |
+
"add": torch.ops.aten.add,
|
| 398 |
+
"add_relu": torch.ops.aten.add,
|
| 399 |
+
"softmax": torch.ops.aten.softmax,
|
| 400 |
+
"cat": torch.ops.aten.cat,
|
| 401 |
+
"hardswish": torch.ops.aten.hardswish,
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
assert isinstance(node.target, torch._ops.OpOverload)
|
| 405 |
+
opname, args = node.target._opname, node.args
|
| 406 |
+
scale_node, zero_point_node = args[-2], args[-1]
|
| 407 |
+
op_res_node = gm.graph.call_function(to_standard_op[opname], tuple(args[:-2]))
|
| 408 |
+
return op_res_node, scale_node, zero_point_node
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _transform_scalar_arithmetic(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
| 412 |
+
"""Transform scalar overload for basic arithmetic."""
|
| 413 |
+
to_standard_op = {
|
| 414 |
+
"mul": torch.ops.aten.mul.Scalar,
|
| 415 |
+
"add": torch.ops.aten.add.Scalar,
|
| 416 |
+
}
|
| 417 |
+
assert isinstance(node.target, torch._ops.OpOverload)
|
| 418 |
+
opname, args = node.target._opname, node.args
|
| 419 |
+
op_res_node = gm.graph.call_function(to_standard_op[opname], args)
|
| 420 |
+
return op_res_node, _SCALE, _ZERO_POINT
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _transform_prepacked_op(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
| 424 |
+
"""
|
| 425 |
+
Transformation for functions under prepacked namespace, where they share
|
| 426 |
+
the same handling logic that [...]OpContext contains all parameters.
|
| 427 |
+
"""
|
| 428 |
+
assert isinstance(node.target, torch._ops.OpOverload)
|
| 429 |
+
opname, args = node.target._opname, node.args
|
| 430 |
+
op_f = None
|
| 431 |
+
if opname == "conv2d_clamp_run":
|
| 432 |
+
op_f = torch.ops.aten.conv2d
|
| 433 |
+
elif opname == "linear_clamp_run":
|
| 434 |
+
op_f = torch.ops.aten.linear
|
| 435 |
+
else:
|
| 436 |
+
raise RuntimeError(f"Invalid operator {opname}")
|
| 437 |
+
|
| 438 |
+
assert isinstance(args[1], torch.fx.Node)
|
| 439 |
+
so = get_script_object(gm, args[1])
|
| 440 |
+
|
| 441 |
+
func_args = []
|
| 442 |
+
func_args += [args[0]]
|
| 443 |
+
func_args += so.unpack()[:2] # type: ignore[attr-defined]
|
| 444 |
+
if opname == "conv2d_clamp_run":
|
| 445 |
+
func_args += torch.ops.prepacked.unpack_prepacked_sizes_conv2d(so)[2:]
|
| 446 |
+
|
| 447 |
+
op_res_node = gm.graph.call_function(op_f, tuple(func_args))
|
| 448 |
+
return op_res_node
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _transform_batch_norm(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
| 452 |
+
args = node.args
|
| 453 |
+
scale_node, zero_point_node = args[-2], args[-1]
|
| 454 |
+
op_res_node = gm.graph.call_function(
|
| 455 |
+
torch.ops.aten.native_batch_norm, (*args[:-3], False, 0.1, args[-3])
|
| 456 |
+
)
|
| 457 |
+
op_res_node = gm.graph.call_function(operator.getitem, (op_res_node, 0))
|
| 458 |
+
return op_res_node, scale_node, zero_point_node
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def fx_transform_quantized_op_to_standard_op(
|
| 462 |
+
gm: torch.fx.GraphModule, node: torch.fx.Node
|
| 463 |
+
) -> torch.fx.Node:
|
| 464 |
+
global _SCALE, _ZERO_POINT, _INPUT_Q_DTYPE
|
| 465 |
+
|
| 466 |
+
assert isinstance(node.target, torch._ops.OpOverload)
|
| 467 |
+
opname, overload = node.target._opname, node.target._overloadname
|
| 468 |
+
|
| 469 |
+
key = f"{opname}.{overload}"
|
| 470 |
+
opname_to_transform_f = {
|
| 471 |
+
"conv1d.new": _transform_conv_with_packedparam,
|
| 472 |
+
"conv1d_relu.new": _transform_conv_with_packedparam,
|
| 473 |
+
"conv1d.default": _transform_conv_with_packedparam,
|
| 474 |
+
"conv1d_relu.default": _transform_conv_with_packedparam,
|
| 475 |
+
"conv2d.new": _transform_conv_with_packedparam,
|
| 476 |
+
"conv2d_relu.new": _transform_conv_with_packedparam,
|
| 477 |
+
"conv2d.default": _transform_conv_with_packedparam,
|
| 478 |
+
"conv2d_relu.default": _transform_conv_with_packedparam,
|
| 479 |
+
"linear.default": _transform_linear_with_packedparam,
|
| 480 |
+
"linear_relu.default": _transform_linear_with_packedparam,
|
| 481 |
+
"add.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 482 |
+
"add_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 483 |
+
"mul.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 484 |
+
"mul_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 485 |
+
"softmax.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 486 |
+
"cat.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 487 |
+
"hardswish.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point,
|
| 488 |
+
"batch_norm2d.default": _transform_batch_norm,
|
| 489 |
+
"mul.Scalar": _transform_scalar_arithmetic,
|
| 490 |
+
"add.Scalar": _transform_scalar_arithmetic,
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
if f"{key}" not in opname_to_transform_f:
|
| 494 |
+
raise RuntimeError(f"Unsupported quantized op during transformation: {key}")
|
| 495 |
+
|
| 496 |
+
op_res_node, scale_node, zero_point_node = opname_to_transform_f[f"{key}"](gm, node)
|
| 497 |
+
|
| 498 |
+
# Add fused activation layer.
|
| 499 |
+
op_res_node = insert_fused_activation_node(gm, opname, op_res_node)
|
| 500 |
+
_SCALE, _ZERO_POINT = scale_node, zero_point_node
|
| 501 |
+
|
| 502 |
+
assert _INPUT_Q_DTYPE is not None
|
| 503 |
+
qmin_node, qmax_node = insert_qmin_qmax_node(gm, _INPUT_Q_DTYPE)
|
| 504 |
+
q_fx_node = insert_quantized_node(
|
| 505 |
+
gm,
|
| 506 |
+
op_res_node,
|
| 507 |
+
scale_node,
|
| 508 |
+
zero_point_node,
|
| 509 |
+
qmin_node,
|
| 510 |
+
qmax_node,
|
| 511 |
+
_INPUT_Q_DTYPE,
|
| 512 |
+
torch.per_tensor_affine,
|
| 513 |
+
)
|
| 514 |
+
dq_fx_node = insert_dequantized_node(
|
| 515 |
+
gm,
|
| 516 |
+
q_fx_node,
|
| 517 |
+
scale_node,
|
| 518 |
+
zero_point_node,
|
| 519 |
+
qmin_node,
|
| 520 |
+
qmax_node,
|
| 521 |
+
_INPUT_Q_DTYPE,
|
| 522 |
+
None,
|
| 523 |
+
torch.per_tensor_affine,
|
| 524 |
+
)
|
| 525 |
+
return dq_fx_node
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def replace_quantized_ops_with_standard_ops(gm: torch.fx.GraphModule):
|
| 529 |
+
"""
|
| 530 |
+
Replace legacy quantized ops (aten.quantize_per_tensor, quantized.conv) with
|
| 531 |
+
PT2 ops (quantize_decomposed.quantize_per_tensor, aten.conv).
|
| 532 |
+
|
| 533 |
+
Before: x || -> aten.q || -> quantized.conv2d || -> quantized.linear || -> aten.dq || -> y
|
| 534 |
+
|
| 535 |
+
After: x || -> qd.q -> qd.dq || -> aten.conv2d -> qd.q -> qd.dq || aten.linear -> qd.q -> qd.dq || -> y
|
| 536 |
+
|
| 537 |
+
(qd == quantized_decomposed library, q = quantize, dq = dequantize)
|
| 538 |
+
^
|
| 539 |
+
|
|
| 540 |
+
getattr(w), getattr(b) from Conv2dParamPrepack
|
| 541 |
+
|
| 542 |
+
During each iteration, the transformation spits out the transformed operator, its quantized output,
|
| 543 |
+
and its dequantized value together. We did this because dequantization need to use the
|
| 544 |
+
scale and zero point parameters from the quantization to recover the approximate original value. After each
|
| 545 |
+
iteration, the new dequantization node will be used as the input to the next node (e.g., dq2 -> linear).
|
| 546 |
+
|
| 547 |
+
For operators like conv2d and linear, their weights and bias are packed in a quantized format in the ScriptObject.
|
| 548 |
+
During the transformation, we unpack those objects, get their dequantized tensor, populate those
|
| 549 |
+
as attributes to the module, and use getattr to access them.
|
| 550 |
+
|
| 551 |
+
One exception in the transformation is conv_prepack and linear_prepack. Those calls pack
|
| 552 |
+
weight and bias constant tensors into ScriptObject, which are then used by subsequent conv2d or linear calls.
|
| 553 |
+
During transformation, we directly skip transforming conv_prepack or linear_prepack. We check whether ScriptObject to the
|
| 554 |
+
quantized::conv2d or linear is from conv_prepack or linear_prepack. If it is, we then inline those parameters
|
| 555 |
+
to the operator by converting them to a getattr fx.node.
|
| 556 |
+
|
| 557 |
+
For prepacked::conv2d_clamp_run and prepacked::linear_clamp_run, we directly convert them to aten.conv2d and aten.linear
|
| 558 |
+
without the need of doing de/quantization.
|
| 559 |
+
|
| 560 |
+
Three global variables defined are _INPUT_Q_DTYPE, _SCALE, _ZERO_POINT. _INPUT_Q_DTYPE determines the de/quantization
|
| 561 |
+
data type, which is the same across the entire program, but it only shows up in the very first quantization
|
| 562 |
+
call. _SCALE and _ZERO_POINT are used only when operators do not have those specified. E.g., mul.Scalar.
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
global _INPUT_Q_DTYPE
|
| 566 |
+
|
| 567 |
+
quantized = False
|
| 568 |
+
|
| 569 |
+
last_quantized_node = None
|
| 570 |
+
for node in gm.graph.nodes:
|
| 571 |
+
if isinstance(node.target, OpOverload):
|
| 572 |
+
with gm.graph.inserting_before(node):
|
| 573 |
+
namespace, opname = node.target.namespace, node.target._opname
|
| 574 |
+
if namespace == "quantized" and opname not in [
|
| 575 |
+
"conv_prepack",
|
| 576 |
+
"linear_prepack",
|
| 577 |
+
]:
|
| 578 |
+
quantized = True
|
| 579 |
+
fx_node = fx_transform_quantized_op_to_standard_op(gm, node)
|
| 580 |
+
node.replace_all_uses_with(fx_node)
|
| 581 |
+
last_quantized_node = fx_node
|
| 582 |
+
elif namespace == "prepacked":
|
| 583 |
+
quantized = True
|
| 584 |
+
fx_node = _transform_prepacked_op(gm, node)
|
| 585 |
+
node.replace_all_uses_with(fx_node)
|
| 586 |
+
last_quantized_node = fx_node
|
| 587 |
+
elif namespace == "aten" and opname == "quantize_per_tensor":
|
| 588 |
+
inp_node, scale_node, zero_point_node, dtype_node = node.args
|
| 589 |
+
dtype_node = fx_enum_to_dtype(gm, dtype_node)
|
| 590 |
+
_INPUT_Q_DTYPE = dtype_node
|
| 591 |
+
qmin_node, qmax_node = insert_qmin_qmax_node(gm, dtype_node)
|
| 592 |
+
q_fx_node = insert_quantized_node(
|
| 593 |
+
gm,
|
| 594 |
+
inp_node,
|
| 595 |
+
scale_node,
|
| 596 |
+
zero_point_node,
|
| 597 |
+
qmin_node,
|
| 598 |
+
qmax_node,
|
| 599 |
+
dtype_node,
|
| 600 |
+
torch.per_tensor_affine,
|
| 601 |
+
)
|
| 602 |
+
dq_fx_node = insert_dequantized_node(
|
| 603 |
+
gm,
|
| 604 |
+
q_fx_node,
|
| 605 |
+
scale_node,
|
| 606 |
+
zero_point_node,
|
| 607 |
+
qmin_node,
|
| 608 |
+
qmax_node,
|
| 609 |
+
dtype_node,
|
| 610 |
+
None,
|
| 611 |
+
torch.per_tensor_affine,
|
| 612 |
+
)
|
| 613 |
+
node.replace_all_uses_with(dq_fx_node)
|
| 614 |
+
last_quantized_node = dq_fx_node
|
| 615 |
+
elif namespace == "aten" and opname == "dequantize":
|
| 616 |
+
assert last_quantized_node is not None
|
| 617 |
+
node.replace_all_uses_with(last_quantized_node)
|
| 618 |
+
else:
|
| 619 |
+
last_quantized_node = node
|
| 620 |
+
|
| 621 |
+
# Post-processing again to remove legacy ScriptObjects and quantizated tensors
|
| 622 |
+
# stored as attributes or in the buffer. This is used to clean up the GraphModule
|
| 623 |
+
# to not trigger tracing errors like missing __obj_flatten__ functions.
|
| 624 |
+
def _clean_attr(mod: torch.nn.Module):
|
| 625 |
+
for submod in mod.modules():
|
| 626 |
+
attr_names_to_clean = set()
|
| 627 |
+
for k, v in submod.__dict__.items():
|
| 628 |
+
if isinstance(v, torch.ScriptObject):
|
| 629 |
+
attr_names_to_clean.add(k)
|
| 630 |
+
if k == "_buffers":
|
| 631 |
+
buffer_name_to_clean = set()
|
| 632 |
+
for b_name, b_value in v.items():
|
| 633 |
+
if isinstance(b_value, torch.Tensor) and b_value.dtype in [
|
| 634 |
+
torch.qint8,
|
| 635 |
+
torch.quint8,
|
| 636 |
+
]:
|
| 637 |
+
buffer_name_to_clean.add(b_name)
|
| 638 |
+
for b_name in buffer_name_to_clean:
|
| 639 |
+
v.pop(b_name, None)
|
| 640 |
+
for attr_name in attr_names_to_clean:
|
| 641 |
+
delattr(submod, attr_name)
|
| 642 |
+
|
| 643 |
+
if quantized:
|
| 644 |
+
"""
|
| 645 |
+
TODO: SetAttr + quantized ops will result incorrect program. This flag is used to temporarily
|
| 646 |
+
bypass test cases.
|
| 647 |
+
|
| 648 |
+
The deadcode elimination pass is needed to remove legacy quantized ops. Otherwise, retracing
|
| 649 |
+
will throw errors. However, the current way of SetAttr does inplace update to attributes, so
|
| 650 |
+
this pass regard them as dead code and remove them. Below is an example of GraphModule before
|
| 651 |
+
and after the dead code elimination pass.
|
| 652 |
+
|
| 653 |
+
class GraphModule(torch.nn.Module):
|
| 654 |
+
def forward(self, x_1):
|
| 655 |
+
# No stacktrace found for following nodes
|
| 656 |
+
data = self.data; data = None
|
| 657 |
+
data_1 = self.data
|
| 658 |
+
add_tensor = torch.ops.aten.add.Tensor(data_1, x_1, alpha = 1); data_1 = None
|
| 659 |
+
data_2 = self.data
|
| 660 |
+
copy_ = torch_Tensor_copy_(data_2, add_tensor); data_2 = add_tensor = copy_ = None
|
| 661 |
+
data_3 = self.data
|
| 662 |
+
add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None
|
| 663 |
+
return add_tensor_1
|
| 664 |
+
|
| 665 |
+
class GraphModule(torch.nn.Module):
|
| 666 |
+
def forward(self, x_1):
|
| 667 |
+
# No stacktrace found for following nodes
|
| 668 |
+
data_3 = self.data
|
| 669 |
+
add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None
|
| 670 |
+
return add_tensor_1
|
| 671 |
+
"""
|
| 672 |
+
gm.graph.eliminate_dead_code()
|
| 673 |
+
_clean_attr(gm)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from typing import Optional, TYPE_CHECKING, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled
|
| 8 |
+
|
| 9 |
+
from ..utils import node_inline_, nodes_filter, nodes_first, nodes_map, sequential_split
|
| 10 |
+
from .replace_with_hop_pass_util import (
|
| 11 |
+
_replace_with_hop_helper,
|
| 12 |
+
_replace_with_hop_pass_helper,
|
| 13 |
+
_sequential_split_and_maybe_inline_subgraphs_helper,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from torch.export.graph_signature import ExportGraphSignature
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _is_set_grad_enabled_node(node: torch.fx.Node) -> Union[torch.fx.Node, bool]:
|
| 22 |
+
return (
|
| 23 |
+
node
|
| 24 |
+
and node.op == "call_function"
|
| 25 |
+
and node.target == torch._C._set_grad_enabled
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _is_set_grad_enabled_sub_mod(
|
| 30 |
+
node: torch.fx.Node, omit_if_same_with_ambient: bool = False
|
| 31 |
+
) -> Union[bool, torch.Tensor]:
|
| 32 |
+
if node.op == "call_module":
|
| 33 |
+
assert isinstance(node.target, str)
|
| 34 |
+
subgm = getattr(node.graph.owning_module, node.target)
|
| 35 |
+
first_non_ph = nodes_first(
|
| 36 |
+
subgm.graph.nodes, lambda node: node.op != "placeholder"
|
| 37 |
+
)
|
| 38 |
+
if (
|
| 39 |
+
first_non_ph
|
| 40 |
+
and first_non_ph.op == "call_function"
|
| 41 |
+
and first_non_ph.target == torch._C._set_grad_enabled
|
| 42 |
+
):
|
| 43 |
+
return (
|
| 44 |
+
first_non_ph.args[0] != torch.is_grad_enabled()
|
| 45 |
+
if omit_if_same_with_ambient
|
| 46 |
+
else True
|
| 47 |
+
)
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _replace_with_hop(node: torch.fx.Node) -> None:
|
| 52 |
+
assert node.op == "call_module"
|
| 53 |
+
graph: torch.fx.Graph = node.graph
|
| 54 |
+
assert graph.owning_module is not None
|
| 55 |
+
gm: torch.fx.GraphModule = graph.owning_module
|
| 56 |
+
assert isinstance(node.target, str)
|
| 57 |
+
sub_gm = getattr(gm, node.target)
|
| 58 |
+
sub_graph = sub_gm.graph
|
| 59 |
+
set_grad_nodes = nodes_filter(sub_graph.nodes, _is_set_grad_enabled_node)
|
| 60 |
+
if len(set_grad_nodes) > 0:
|
| 61 |
+
assert len(set_grad_nodes) == 1
|
| 62 |
+
set_grad_node = set_grad_nodes[0]
|
| 63 |
+
_replace_with_hop_helper(node, set_grad_node, wrap_with_set_grad_enabled)
|
| 64 |
+
sub_graph.erase_node(set_grad_node)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _remove_set_grad_and_inline(node: torch.fx.Node) -> None:
|
| 68 |
+
assert node.op == "call_module"
|
| 69 |
+
graph: torch.fx.Graph = node.graph
|
| 70 |
+
assert graph.owning_module is not None
|
| 71 |
+
gm: torch.fx.GraphModule = graph.owning_module
|
| 72 |
+
assert isinstance(node.target, str)
|
| 73 |
+
sub_gm = getattr(gm, node.target)
|
| 74 |
+
sub_graph = sub_gm.graph
|
| 75 |
+
nodes_map(
|
| 76 |
+
sub_graph.nodes,
|
| 77 |
+
lambda n: sub_graph.erase_node(n) if _is_set_grad_enabled_node(n) else n,
|
| 78 |
+
)
|
| 79 |
+
node_inline_(node)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _sequential_split_and_maybe_inline_subgraphs(
|
| 83 |
+
gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
|
| 84 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 85 |
+
"""
|
| 86 |
+
Helper function for replace_set_grad_with_hop_pass().
|
| 87 |
+
Split the graph module into multiple subgraphs based on the set_grad_enabled nodes.
|
| 88 |
+
For each subgraph, decides whether to construct a HOO subgraph, or inline the calls
|
| 89 |
+
back into the parent graph module.
|
| 90 |
+
"""
|
| 91 |
+
need_replacing = any(_is_set_grad_enabled_node(node) for node in gm.graph.nodes)
|
| 92 |
+
if not need_replacing:
|
| 93 |
+
return gm, graph_signature
|
| 94 |
+
|
| 95 |
+
# sequential_split returns a new graph module that could have different output
|
| 96 |
+
# args names. We need to fix the graph signature.
|
| 97 |
+
new_gm = sequential_split(gm, _is_set_grad_enabled_node)
|
| 98 |
+
|
| 99 |
+
def _maybe_inline_or_replace_with_hop(node: torch.fx.Node):
|
| 100 |
+
if _is_set_grad_enabled_sub_mod(node, omit_if_same_with_ambient=True):
|
| 101 |
+
_replace_with_hop(node)
|
| 102 |
+
else:
|
| 103 |
+
_remove_set_grad_and_inline(node)
|
| 104 |
+
|
| 105 |
+
return _sequential_split_and_maybe_inline_subgraphs_helper(
|
| 106 |
+
new_gm, graph_signature, _maybe_inline_or_replace_with_hop
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def replace_set_grad_with_hop_pass(
|
| 111 |
+
gm: torch.fx.GraphModule, graph_signature: Optional[ExportGraphSignature]
|
| 112 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 113 |
+
"""
|
| 114 |
+
Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
|
| 115 |
+
then recursively call itself on each of the submodules.
|
| 116 |
+
"""
|
| 117 |
+
return _replace_with_hop_pass_helper(
|
| 118 |
+
gm,
|
| 119 |
+
graph_signature,
|
| 120 |
+
_sequential_split_and_maybe_inline_subgraphs,
|
| 121 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._export.error import InternalError
|
| 6 |
+
from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse
|
| 7 |
+
from torch._ops import HigherOrderOperator, OpOverload
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ["ReplaceViewOpsWithViewCopyOpsPass"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: dict[OpOverload, OpOverload] = {
|
| 14 |
+
torch.ops.aten._unsafe_view.default: torch.ops.aten.view_copy.default,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def is_view_op(schema: torch._C.FunctionSchema) -> bool:
|
| 19 |
+
if len(schema.arguments) == 0:
|
| 20 |
+
return False
|
| 21 |
+
alias_info = schema.arguments[0].alias_info
|
| 22 |
+
return (alias_info is not None) and (not alias_info.is_write)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_view_copy_of_view_op(schema: torch._C.FunctionSchema) -> Optional[OpOverload]:
|
| 26 |
+
if is_view_op(schema) and schema.name.startswith("aten::"):
|
| 27 |
+
view_op_name = schema.name.split("::")[1]
|
| 28 |
+
view_op_overload = (
|
| 29 |
+
schema.overload_name if schema.overload_name != "" else "default"
|
| 30 |
+
)
|
| 31 |
+
view_copy_op_name = view_op_name + "_copy"
|
| 32 |
+
if not hasattr(torch.ops.aten, view_copy_op_name):
|
| 33 |
+
raise InternalError(f"{schema.name} is missing a view_copy variant")
|
| 34 |
+
|
| 35 |
+
view_copy_op_overload_packet = getattr(torch.ops.aten, view_copy_op_name)
|
| 36 |
+
|
| 37 |
+
if not hasattr(view_copy_op_overload_packet, view_op_overload):
|
| 38 |
+
raise InternalError(f"{schema.name} is missing a view_copy variant")
|
| 39 |
+
|
| 40 |
+
return getattr(view_copy_op_overload_packet, view_op_overload)
|
| 41 |
+
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ReplaceViewOpsWithViewCopyOpsPass(_ExportPassBaseDeprecatedDoNotUse):
|
| 46 |
+
"""
|
| 47 |
+
Our backend expects pure functional operators. For efficiency
|
| 48 |
+
purposes, we keep view ops around while functionalizing the exported
|
| 49 |
+
program. This pass replaces view ops with view copy ops for backends that
|
| 50 |
+
need AOT memory planning.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def call_operator(self, op, args, kwargs, meta):
|
| 54 |
+
if op in _NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS:
|
| 55 |
+
return super().call_operator(
|
| 56 |
+
(_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS[op]), args, kwargs, meta
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if isinstance(op, HigherOrderOperator):
|
| 60 |
+
return super().call_operator(op, args, kwargs, meta)
|
| 61 |
+
|
| 62 |
+
if view_copy_op := get_view_copy_of_view_op(op._schema):
|
| 63 |
+
return super().call_operator(view_copy_op, args, kwargs, meta)
|
| 64 |
+
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import contextlib
|
| 5 |
+
import copy
|
| 6 |
+
import operator
|
| 7 |
+
from typing import Callable, Optional, TYPE_CHECKING
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from ..utils import node_replace_, nodes_map
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from torch._ops import HigherOrderOperator
|
| 16 |
+
from torch.export.graph_signature import ExportGraphSignature
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _replace_with_hop_helper(
|
| 20 |
+
node: torch.fx.Node,
|
| 21 |
+
enter_block_node: torch.fx.Node,
|
| 22 |
+
wrap_hoo: HigherOrderOperator,
|
| 23 |
+
) -> None:
|
| 24 |
+
graph: torch.fx.Graph = node.graph
|
| 25 |
+
assert graph.owning_module is not None
|
| 26 |
+
gm: torch.fx.GraphModule = graph.owning_module
|
| 27 |
+
assert isinstance(node.target, str)
|
| 28 |
+
sub_gm = getattr(gm, node.target)
|
| 29 |
+
|
| 30 |
+
def set_hoo_node_meta(call_func_node):
|
| 31 |
+
call_func_node.meta["nn_module_stack"] = copy.copy(
|
| 32 |
+
enter_block_node.meta.get("nn_module_stack", {})
|
| 33 |
+
)
|
| 34 |
+
call_func_node.meta["torch_fn"] = (
|
| 35 |
+
f"{wrap_hoo.__name__}",
|
| 36 |
+
f"{wrap_hoo.__class__.__name__}.{wrap_hoo.__name__}",
|
| 37 |
+
)
|
| 38 |
+
if isinstance(output_args, (tuple, list)):
|
| 39 |
+
call_func_node.meta["val"] = tuple(arg.meta["val"] for arg in output_args)
|
| 40 |
+
elif isinstance(output_args, torch.fx.Node):
|
| 41 |
+
call_func_node.meta["val"] = (output_args.meta["val"],)
|
| 42 |
+
|
| 43 |
+
with graph.inserting_before(node):
|
| 44 |
+
get_attr_node = graph.get_attr(node.target)
|
| 45 |
+
get_attr_node.meta["nn_module_stack"] = copy.copy(
|
| 46 |
+
enter_block_node.meta.get("nn_module_stack", {})
|
| 47 |
+
)
|
| 48 |
+
output_node = next(iter(reversed(sub_gm.graph.nodes)), None)
|
| 49 |
+
# Split_module pass intentially doesn't add output node
|
| 50 |
+
# if the graph doesn't return anything.
|
| 51 |
+
# TODO (tmanlaibaatar) Figure out if this is right behaviour
|
| 52 |
+
# for split_module
|
| 53 |
+
if isinstance(output_node, torch.fx.Node) and output_node.op != "output":
|
| 54 |
+
output_node = None
|
| 55 |
+
if output_node is not None:
|
| 56 |
+
assert len(output_node.args) == 1
|
| 57 |
+
output_args = output_node.args[0]
|
| 58 |
+
enter_block_node_args = enter_block_node.args
|
| 59 |
+
if isinstance(output_args, (tuple, list)):
|
| 60 |
+
call_func_node = graph.call_function(
|
| 61 |
+
wrap_hoo,
|
| 62 |
+
(*enter_block_node_args, get_attr_node, *node.args),
|
| 63 |
+
{},
|
| 64 |
+
)
|
| 65 |
+
# Create the metadata
|
| 66 |
+
set_hoo_node_meta(call_func_node)
|
| 67 |
+
node_replace_(node, call_func_node)
|
| 68 |
+
|
| 69 |
+
# Rename the name of getitem nodes to the actual name of its contents
|
| 70 |
+
# for passing verifier and better readability, also propagate metadata
|
| 71 |
+
for get_item_node in call_func_node.users.keys():
|
| 72 |
+
idx: int = get_item_node.args[1] # type: ignore[assignment]
|
| 73 |
+
output_node = output_args[idx]
|
| 74 |
+
get_item_node._rename(output_node.name)
|
| 75 |
+
get_item_node.meta = output_node.meta
|
| 76 |
+
|
| 77 |
+
elif isinstance(output_args, torch.fx.Node):
|
| 78 |
+
call_func_node = graph.create_node(
|
| 79 |
+
"call_function",
|
| 80 |
+
wrap_hoo,
|
| 81 |
+
(*enter_block_node_args, get_attr_node, *node.args),
|
| 82 |
+
{},
|
| 83 |
+
output_args.name,
|
| 84 |
+
)
|
| 85 |
+
# Modify the subgraph to output a singleton list.
|
| 86 |
+
output_node.args = ((output_args,),)
|
| 87 |
+
# Add in an extra `getitem(wrap_hoo, 0)` node to the toplevel graph.
|
| 88 |
+
get_item_node = graph.create_node(
|
| 89 |
+
"call_function",
|
| 90 |
+
operator.getitem,
|
| 91 |
+
(call_func_node, 0),
|
| 92 |
+
{},
|
| 93 |
+
)
|
| 94 |
+
# Create the metadata
|
| 95 |
+
get_item_node.meta = output_args.meta
|
| 96 |
+
set_hoo_node_meta(call_func_node)
|
| 97 |
+
node_replace_(node, get_item_node)
|
| 98 |
+
else:
|
| 99 |
+
raise NotImplementedError(
|
| 100 |
+
f"repalce_with_hop_pass doesnt' support output type {type(output_args)}"
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
# TODO (shangdiy): remove this line, since the export graph can be non-functional
|
| 104 |
+
node.graph.erase_node(node)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _sequential_split_and_maybe_inline_subgraphs_helper(
|
| 108 |
+
new_gm: torch.fx.GraphModule,
|
| 109 |
+
graph_signature: Optional[ExportGraphSignature],
|
| 110 |
+
maybe_inline_or_replace_with_hop: Callable[[torch.fx.Node], None],
|
| 111 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 112 |
+
"""
|
| 113 |
+
Helper function for replacing graph nodse with higher order nodes.
|
| 114 |
+
For each subgraph in `new_gm`, decides whether to construct a HOO subgraph, or inline the calls
|
| 115 |
+
back into the parent graph module, depending on `maybe_inline_or_replace_with_hop`.
|
| 116 |
+
"""
|
| 117 |
+
# new_gm is a new graph module that could have different output args names.
|
| 118 |
+
# We need to fix the graph signature.
|
| 119 |
+
replace_ctx = contextlib.nullcontext()
|
| 120 |
+
new_signature = None
|
| 121 |
+
if graph_signature is not None:
|
| 122 |
+
# Cannot deep copy a real ScriptObject, which is referenced
|
| 123 |
+
# in the FakeScriptObject. Copy should be good enough to guard
|
| 124 |
+
# against accidental mutation to original graph_signature.
|
| 125 |
+
new_signature = copy.copy(graph_signature)
|
| 126 |
+
new_gm_out_node = next(reversed(new_gm.graph.find_nodes(op="output")))
|
| 127 |
+
assert new_gm_out_node.op == "output" and len(new_gm_out_node.args[0]) == len(
|
| 128 |
+
new_signature.output_specs
|
| 129 |
+
)
|
| 130 |
+
for arg_node, out_spec in zip(
|
| 131 |
+
new_gm_out_node.args[0], new_signature.output_specs
|
| 132 |
+
):
|
| 133 |
+
if arg_node is None:
|
| 134 |
+
assert out_spec.arg.value is None # type: ignore[union-attr]
|
| 135 |
+
elif (
|
| 136 |
+
isinstance(arg_node, torch.fx.Node)
|
| 137 |
+
and out_spec.arg.name != arg_node.name
|
| 138 |
+
):
|
| 139 |
+
out_spec.arg.name = arg_node.name
|
| 140 |
+
|
| 141 |
+
replace_ctx = new_gm._set_replace_hook(new_signature.get_replace_hook()) # type: ignore[assignment]
|
| 142 |
+
|
| 143 |
+
with replace_ctx:
|
| 144 |
+
nodes_map(
|
| 145 |
+
list(new_gm.graph.nodes),
|
| 146 |
+
lambda node: (
|
| 147 |
+
maybe_inline_or_replace_with_hop(node)
|
| 148 |
+
if node.op == "call_module"
|
| 149 |
+
else node
|
| 150 |
+
),
|
| 151 |
+
)
|
| 152 |
+
new_gm.recompile()
|
| 153 |
+
new_gm.graph.lint()
|
| 154 |
+
return new_gm, new_signature
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _replace_with_hop_pass_helper(
|
| 158 |
+
gm: torch.fx.GraphModule,
|
| 159 |
+
graph_signature: Optional[ExportGraphSignature],
|
| 160 |
+
sequential_split_and_maybe_inline_subgraphs: Callable[
|
| 161 |
+
[torch.fx.GraphModule, Optional[ExportGraphSignature]],
|
| 162 |
+
tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]],
|
| 163 |
+
],
|
| 164 |
+
) -> tuple[torch.fx.GraphModule, Optional[ExportGraphSignature]]:
|
| 165 |
+
"""
|
| 166 |
+
Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and
|
| 167 |
+
then recursively call itself on each of the submodules.
|
| 168 |
+
"""
|
| 169 |
+
new_gm, new_signature = sequential_split_and_maybe_inline_subgraphs(
|
| 170 |
+
gm, graph_signature
|
| 171 |
+
)
|
| 172 |
+
# recursively call
|
| 173 |
+
for node in new_gm.graph.nodes:
|
| 174 |
+
if node.op == "get_attr":
|
| 175 |
+
subgm = getattr(new_gm, node.target)
|
| 176 |
+
if not isinstance(subgm, torch.fx.GraphModule):
|
| 177 |
+
continue
|
| 178 |
+
new_subgm, _ = _replace_with_hop_pass_helper(
|
| 179 |
+
subgm,
|
| 180 |
+
None,
|
| 181 |
+
sequential_split_and_maybe_inline_subgraphs,
|
| 182 |
+
)
|
| 183 |
+
setattr(new_gm, node.target, new_subgm)
|
| 184 |
+
|
| 185 |
+
new_gm.recompile()
|
| 186 |
+
new_gm.graph.lint()
|
| 187 |
+
return new_gm, new_signature
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/dynamic_shapes.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from typing import Any, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._dynamo.exc import UserError, UserErrorType
|
| 6 |
+
from torch.export.dynamic_shapes import (
|
| 7 |
+
_check_dynamic_shapes,
|
| 8 |
+
_DerivedDim,
|
| 9 |
+
_DimHint,
|
| 10 |
+
_tree_map_with_path,
|
| 11 |
+
Dim,
|
| 12 |
+
)
|
| 13 |
+
from torch.utils._pytree import tree_map
|
| 14 |
+
|
| 15 |
+
from .serialize import _dataclass_to_dict
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclasses.dataclass
|
| 19 |
+
class RootDim:
|
| 20 |
+
"""
|
| 21 |
+
This represents a Dim object.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
min: int
|
| 25 |
+
max: Union[int, None]
|
| 26 |
+
derived: list[str]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclasses.dataclass
|
| 30 |
+
class DynamicShapesSpec:
|
| 31 |
+
"""
|
| 32 |
+
This stores a dynamic_shapes spec for de/serialization.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None]
|
| 36 |
+
dims: dict[str, RootDim]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _postprocess_serialized_shapes(
|
| 40 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
|
| 41 |
+
dims: dict[str, dict[str, Union[int, list[str], None]]],
|
| 42 |
+
to_dict: Optional[bool] = False,
|
| 43 |
+
) -> Union[DynamicShapesSpec, dict[str, Any]]:
|
| 44 |
+
"""
|
| 45 |
+
Sorts dims and dumps to dictionary format.
|
| 46 |
+
"""
|
| 47 |
+
from torch.utils._sympy.numbers import int_oo
|
| 48 |
+
|
| 49 |
+
dims = {
|
| 50 |
+
k: RootDim(
|
| 51 |
+
min=v["min"], # type: ignore[arg-type]
|
| 52 |
+
max=None if v["max"] is int_oo else v["max"], # type: ignore[arg-type]
|
| 53 |
+
derived=sorted(v["derived"]), # type: ignore[arg-type]
|
| 54 |
+
)
|
| 55 |
+
for k, v in sorted(dims.items())
|
| 56 |
+
}
|
| 57 |
+
spec = DynamicShapesSpec(dynamic_shapes=dynamic_shapes, dims=dims)
|
| 58 |
+
if to_dict:
|
| 59 |
+
return _dataclass_to_dict(spec)
|
| 60 |
+
else:
|
| 61 |
+
return spec
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _dump_dynamic_shapes(
|
| 65 |
+
dynamic_shapes: Union[dict[str, Any], tuple[Any], list[Any], None],
|
| 66 |
+
args: tuple[Any],
|
| 67 |
+
kwargs: Optional[dict[str, Any]] = None,
|
| 68 |
+
to_dict: Optional[bool] = False,
|
| 69 |
+
) -> Union[DynamicShapesSpec, dict[str, Any]]:
|
| 70 |
+
"""
|
| 71 |
+
Utility function for dynamic shapes serialization, serializing a dynamic_shapes spec.
|
| 72 |
+
Returns a DynamicShapesSpec dataclass containing 2 fields, "dynamic_shapes" and "dims".
|
| 73 |
+
Uses args & kwargs to distinguish between tensor-level and dim-level specs (only for Nones).
|
| 74 |
+
|
| 75 |
+
dynamic_shapes: A pytree structure mirroring the dynamic_shapes input to export():
|
| 76 |
+
- Each tensor input is represented with a list of values, non-tensor inputs with None.
|
| 77 |
+
- dynamic dimensions (i.e. symbols) in tensors and Dim enums are represented with strings.
|
| 78 |
+
- static dimensions are represented with ints.
|
| 79 |
+
|
| 80 |
+
dims: A dictionary mapping each symbol name to the min/max range and derived dim names.
|
| 81 |
+
|
| 82 |
+
For example:
|
| 83 |
+
```
|
| 84 |
+
dx = Dim("dx", min=4, max=16)
|
| 85 |
+
dy = dx + 1
|
| 86 |
+
|
| 87 |
+
inputs = (
|
| 88 |
+
[
|
| 89 |
+
torch.randn(4, 4),
|
| 90 |
+
torch.randn(5, 4),
|
| 91 |
+
],
|
| 92 |
+
torch.randn(4),
|
| 93 |
+
torch.randn(4, 4),
|
| 94 |
+
"hello",
|
| 95 |
+
)
|
| 96 |
+
dynamic_shapes = {
|
| 97 |
+
"a": [
|
| 98 |
+
(dx, 4),
|
| 99 |
+
(dy, 4),
|
| 100 |
+
],
|
| 101 |
+
"b": (Dim.STATIC,),
|
| 102 |
+
"c": None,
|
| 103 |
+
"d": None,
|
| 104 |
+
}
|
| 105 |
+
out = _dump_dynamic_shapes(dynamic_shapes, inputs, to_dict=True)
|
| 106 |
+
```
|
| 107 |
+
would generate the following output:
|
| 108 |
+
```
|
| 109 |
+
{
|
| 110 |
+
'dynamic_shapes': (
|
| 111 |
+
[
|
| 112 |
+
['dx', 4],
|
| 113 |
+
['dx + 1', 4],
|
| 114 |
+
],
|
| 115 |
+
['_DimHint.STATIC'],
|
| 116 |
+
['_DimHint.STATIC', '_DimHint.STATIC'],
|
| 117 |
+
None,
|
| 118 |
+
),
|
| 119 |
+
'dims': {
|
| 120 |
+
'dx': {
|
| 121 |
+
'min': 4,
|
| 122 |
+
'max': 16,
|
| 123 |
+
'derived': ['dx + 1'],
|
| 124 |
+
},
|
| 125 |
+
},
|
| 126 |
+
}
|
| 127 |
+
```
|
| 128 |
+
"""
|
| 129 |
+
dims: dict[str, dict[str, Any]] = {}
|
| 130 |
+
|
| 131 |
+
def _standardize_shapes(path, tensor, shape): # type: ignore[no-untyped-def]
|
| 132 |
+
"""
|
| 133 |
+
Helps standardize the dynamic_shapes tree structure we serialize,
|
| 134 |
+
returning lists for each tensor shape, handling tensor-level Nones.
|
| 135 |
+
"""
|
| 136 |
+
if not isinstance(tensor, torch.Tensor):
|
| 137 |
+
return None
|
| 138 |
+
if shape is None:
|
| 139 |
+
return [Dim.STATIC] * len(tensor.shape)
|
| 140 |
+
|
| 141 |
+
out = []
|
| 142 |
+
if isinstance(shape, dict):
|
| 143 |
+
for i, s in enumerate(tensor.shape):
|
| 144 |
+
out.append(s if shape.get(i) is None else shape.get(i))
|
| 145 |
+
else:
|
| 146 |
+
assert isinstance(shape, (tuple, list))
|
| 147 |
+
for i, s in enumerate(tensor.shape):
|
| 148 |
+
out.append(s if shape[i] is None else shape[i])
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
def _track_dim_from_dims(
|
| 152 |
+
val: Union[None, int, _DimHint, Dim]
|
| 153 |
+
) -> Union[None, int, str]:
|
| 154 |
+
"""
|
| 155 |
+
Tracks dims, ranges, derived dims from the standardized dynamic_shapes spec.
|
| 156 |
+
"""
|
| 157 |
+
if val is None or isinstance(val, int): # non-tensor input or static
|
| 158 |
+
return val
|
| 159 |
+
if isinstance(val, _DimHint): # store enum as string
|
| 160 |
+
return val.__class__.__name__ + "." + val.type.name
|
| 161 |
+
|
| 162 |
+
assert isinstance(val, Dim)
|
| 163 |
+
|
| 164 |
+
# track root dim
|
| 165 |
+
root = val.root if isinstance(val, _DerivedDim) else val # type: ignore[attr-defined]
|
| 166 |
+
if root.__name__ not in dims:
|
| 167 |
+
dims[root.__name__] = {
|
| 168 |
+
"min": root.min, # type: ignore[attr-defined,union-attr]
|
| 169 |
+
"max": root.max, # type: ignore[attr-defined,union-attr]
|
| 170 |
+
"derived": set(),
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# track derived dims
|
| 174 |
+
if isinstance(val, _DerivedDim):
|
| 175 |
+
dims[root.__name__]["derived"].add(val.__name__)
|
| 176 |
+
|
| 177 |
+
return val.__name__
|
| 178 |
+
|
| 179 |
+
if dynamic_shapes is None:
|
| 180 |
+
return {"dynamic_shapes": None, "dims": {}}
|
| 181 |
+
|
| 182 |
+
# convert to tuple of specs, for each arg/kwarg
|
| 183 |
+
kwargs = kwargs or {}
|
| 184 |
+
if isinstance(dynamic_shapes, dict):
|
| 185 |
+
dynamic_shapes = dynamic_shapes.values() # type: ignore[assignment]
|
| 186 |
+
dynamic_shapes = tuple(dynamic_shapes)
|
| 187 |
+
combined_args = tuple(args) + tuple(kwargs.values())
|
| 188 |
+
|
| 189 |
+
# run same check when we're processing shapes for export - is this too lazy?
|
| 190 |
+
_check_dynamic_shapes(dict(enumerate(combined_args)), dynamic_shapes) # type: ignore[arg-type]
|
| 191 |
+
|
| 192 |
+
tree_shapes = _tree_map_with_path(
|
| 193 |
+
_standardize_shapes, combined_args, dynamic_shapes, tree_name="inputs"
|
| 194 |
+
)
|
| 195 |
+
serialized_shapes = tree_map(_track_dim_from_dims, tree_shapes)
|
| 196 |
+
return _postprocess_serialized_shapes(serialized_shapes, dims, to_dict=to_dict)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _load_dynamic_shapes(
|
| 200 |
+
spec: Union[DynamicShapesSpec, dict[str, Any]],
|
| 201 |
+
from_dict: Optional[bool] = False,
|
| 202 |
+
) -> Union[dict[str, Any], tuple[Any], list[Any], None]:
|
| 203 |
+
"""
|
| 204 |
+
Utility function for dynamic shapes serialization.
|
| 205 |
+
Deserializes a DynamicShapesSpec or corresponding dictionary into a dynamic_shapes input to export().
|
| 206 |
+
"""
|
| 207 |
+
import sympy
|
| 208 |
+
|
| 209 |
+
from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence
|
| 210 |
+
|
| 211 |
+
if from_dict:
|
| 212 |
+
if not isinstance(spec, dict):
|
| 213 |
+
raise UserError(
|
| 214 |
+
UserErrorType.INVALID_INPUT,
|
| 215 |
+
f"With from_dict=True, expected `spec` to be a dict, got {type(spec)}",
|
| 216 |
+
)
|
| 217 |
+
if sorted(spec.keys()) != ["dims", "dynamic_shapes"]:
|
| 218 |
+
raise UserError(
|
| 219 |
+
UserErrorType.INVALID_INPUT,
|
| 220 |
+
"With from_dict=True, expected `spec` to have keys `dims` and `dynamic_shapes`, "
|
| 221 |
+
f"instead found {spec.keys()}",
|
| 222 |
+
)
|
| 223 |
+
dims = {}
|
| 224 |
+
for k, v in spec["dims"].items():
|
| 225 |
+
if not isinstance(k, str):
|
| 226 |
+
raise UserError(
|
| 227 |
+
UserErrorType.INVALID_INPUT,
|
| 228 |
+
f"Expected `spec['dims']` keys to be strings for symbols, got key {type(k)}",
|
| 229 |
+
)
|
| 230 |
+
if sorted(v.keys()) != ["derived", "max", "min"]:
|
| 231 |
+
raise UserError(
|
| 232 |
+
UserErrorType.INVALID_INPUT,
|
| 233 |
+
f"Expected `spec['dims']` values to have keys `derived`, `max`, and `min`, "
|
| 234 |
+
f"instead found {v.keys()}",
|
| 235 |
+
)
|
| 236 |
+
if not isinstance(v["min"], int):
|
| 237 |
+
raise UserError(
|
| 238 |
+
UserErrorType.INVALID_INPUT,
|
| 239 |
+
f"Expected dims in `spec['dims']` to map `min` to an int, got {k}: {v['min']}",
|
| 240 |
+
)
|
| 241 |
+
if not isinstance(v["max"], int) or v["max"] is None:
|
| 242 |
+
raise UserError(
|
| 243 |
+
UserErrorType.INVALID_INPUT,
|
| 244 |
+
f"Expected dims in `spec['dims']` to map `max` to an int or None, got {k}: {v['max']}",
|
| 245 |
+
)
|
| 246 |
+
if not isinstance(v["derived"], list) or any(
|
| 247 |
+
not isinstance(d, str) for d in v["derived"]
|
| 248 |
+
):
|
| 249 |
+
raise UserError(
|
| 250 |
+
UserErrorType.INVALID_INPUT,
|
| 251 |
+
"Expected dims in `spec['dims']` to map `derived` to a list of derived expressions, "
|
| 252 |
+
f"got {k}: {v['derived']}",
|
| 253 |
+
)
|
| 254 |
+
dims[k] = RootDim(**v)
|
| 255 |
+
dynamic_shapes = spec["dynamic_shapes"]
|
| 256 |
+
else:
|
| 257 |
+
if not isinstance(spec, DynamicShapesSpec):
|
| 258 |
+
raise UserError(
|
| 259 |
+
UserErrorType.INVALID_INPUT,
|
| 260 |
+
f"Expected `spec` to be a DynamicShapesSpec, got {type(spec)}",
|
| 261 |
+
)
|
| 262 |
+
dims = spec.dims
|
| 263 |
+
dynamic_shapes = spec.dynamic_shapes
|
| 264 |
+
|
| 265 |
+
if dynamic_shapes is None:
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
dim_cache = {}
|
| 269 |
+
for name, info in dims.items():
|
| 270 |
+
symbol = sympy.sympify(name)
|
| 271 |
+
if not isinstance(symbol, sympy.Symbol):
|
| 272 |
+
raise UserError(
|
| 273 |
+
UserErrorType.INVALID_INPUT,
|
| 274 |
+
f"Expected `spec['dims']` keys to be symbols, got {name}",
|
| 275 |
+
)
|
| 276 |
+
dim_cache[name] = Dim(name, min=info.min, max=info.max) # cache root dim
|
| 277 |
+
for _expr in info.derived:
|
| 278 |
+
expr = sympy.sympify(_expr)
|
| 279 |
+
if len(expr.free_symbols) != 1 or symbol not in expr.free_symbols:
|
| 280 |
+
raise UserError(
|
| 281 |
+
UserErrorType.INVALID_INPUT,
|
| 282 |
+
f"Expected derived expressions in to have {name} as the only free symbol, got {expr}",
|
| 283 |
+
)
|
| 284 |
+
if not _is_supported_equivalence(expr):
|
| 285 |
+
raise UserError(
|
| 286 |
+
UserErrorType.INVALID_INPUT,
|
| 287 |
+
f"Expected derived expressions to be linear expressions, got {expr}",
|
| 288 |
+
)
|
| 289 |
+
modulus, remainder = sympy.polys.polytools.div(expr, symbol)
|
| 290 |
+
ddim = dim_cache[name]
|
| 291 |
+
if modulus != 1:
|
| 292 |
+
ddim = int(modulus) * ddim # type: ignore[assignment, operator]
|
| 293 |
+
if remainder != 0:
|
| 294 |
+
ddim = ddim + int(remainder) # type: ignore[assignment, operator]
|
| 295 |
+
dim_cache[_expr] = ddim # cache derived dims
|
| 296 |
+
|
| 297 |
+
def deserialize_shape(
|
| 298 |
+
val: Union[None, int, str]
|
| 299 |
+
) -> Union[None, int, Dim, _DimHint]:
|
| 300 |
+
if val is None or isinstance(val, int):
|
| 301 |
+
return val
|
| 302 |
+
elif val == "_DimHint.AUTO":
|
| 303 |
+
return _DimHint.AUTO()
|
| 304 |
+
elif val == "_DimHint.DYNAMIC":
|
| 305 |
+
return _DimHint.DYNAMIC()
|
| 306 |
+
elif val == "_DimHint.STATIC":
|
| 307 |
+
return _DimHint.STATIC()
|
| 308 |
+
if not isinstance(val, str):
|
| 309 |
+
raise UserError(
|
| 310 |
+
UserErrorType.INVALID_INPUT,
|
| 311 |
+
"Expected leaves in `spec['dynamic_shapes']` to be ints, None, Dim.AUTO/STATIC, symbols, "
|
| 312 |
+
f" or derived expressions, got {val}",
|
| 313 |
+
)
|
| 314 |
+
if val not in dim_cache:
|
| 315 |
+
raise UserError(
|
| 316 |
+
UserErrorType.INVALID_INPUT,
|
| 317 |
+
"Expected dims in `spec['dynamic_shapes']` to be tracked in `spec['dims']`, "
|
| 318 |
+
f"got {val} which is not in {dims.keys()}",
|
| 319 |
+
)
|
| 320 |
+
return dim_cache[val] # type: ignore[return-value]
|
| 321 |
+
|
| 322 |
+
return tree_map(deserialize_shape, dynamic_shapes)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/export_schema.thrift
ADDED
|
@@ -0,0 +1,362 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// @generated by update_schema.py
|
| 2 |
+
// checksum<<fd7996be362400fc786560be9e3d5680d1d7ec37b21d7a89d74146b669f72da6>>
|
| 3 |
+
|
| 4 |
+
namespace py3 torch._export
|
| 5 |
+
namespace cpp2 torch._export.schema
|
| 6 |
+
|
| 7 |
+
enum ArgumentKind {
|
| 8 |
+
UNKNOWN = 0,
|
| 9 |
+
POSITIONAL = 1,
|
| 10 |
+
KEYWORD = 2,
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
enum Layout {
|
| 15 |
+
Unknown = 0,
|
| 16 |
+
SparseCoo = 1,
|
| 17 |
+
SparseCsr = 2,
|
| 18 |
+
SparseCsc = 3,
|
| 19 |
+
SparseBsr = 4,
|
| 20 |
+
SparseBsc = 5,
|
| 21 |
+
_mkldnn = 6,
|
| 22 |
+
Strided = 7,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
enum MemoryFormat {
|
| 27 |
+
Unknown = 0,
|
| 28 |
+
ContiguousFormat = 1,
|
| 29 |
+
ChannelsLast = 2,
|
| 30 |
+
ChannelsLast3d = 3,
|
| 31 |
+
PreserveFormat = 4,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
enum ScalarType {
|
| 36 |
+
UNKNOWN = 0,
|
| 37 |
+
BYTE = 1,
|
| 38 |
+
CHAR = 2,
|
| 39 |
+
SHORT = 3,
|
| 40 |
+
INT = 4,
|
| 41 |
+
LONG = 5,
|
| 42 |
+
HALF = 6,
|
| 43 |
+
FLOAT = 7,
|
| 44 |
+
DOUBLE = 8,
|
| 45 |
+
COMPLEXHALF = 9,
|
| 46 |
+
COMPLEXFLOAT = 10,
|
| 47 |
+
COMPLEXDOUBLE = 11,
|
| 48 |
+
BOOL = 12,
|
| 49 |
+
BFLOAT16 = 13,
|
| 50 |
+
UINT16 = 28,
|
| 51 |
+
FLOAT8E4M3FN = 29,
|
| 52 |
+
FLOAT8E5M2 = 30,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
struct Device {
|
| 57 |
+
10: string type;
|
| 58 |
+
20: optional i64 index;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
union SymExprHint {
|
| 62 |
+
10: i64 as_int;
|
| 63 |
+
20: bool as_bool;
|
| 64 |
+
30: double as_float;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
struct SymExpr {
|
| 68 |
+
10: string expr_str;
|
| 69 |
+
20: optional SymExprHint hint;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
union SymInt {
|
| 73 |
+
10: SymExpr as_expr;
|
| 74 |
+
20: i64 as_int;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
union SymFloat {
|
| 78 |
+
10: SymExpr as_expr;
|
| 79 |
+
20: double as_float;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
union SymBool {
|
| 83 |
+
10: SymExpr as_expr;
|
| 84 |
+
20: bool as_bool;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
struct TensorMeta {
|
| 88 |
+
10: ScalarType dtype;
|
| 89 |
+
20: list<SymInt> sizes;
|
| 90 |
+
30: bool requires_grad;
|
| 91 |
+
40: Device device;
|
| 92 |
+
50: list<SymInt> strides;
|
| 93 |
+
60: SymInt storage_offset;
|
| 94 |
+
70: Layout layout;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
union SymIntArgument {
|
| 98 |
+
10: string as_name;
|
| 99 |
+
20: i64 as_int;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
union SymFloatArgument {
|
| 103 |
+
10: string as_name;
|
| 104 |
+
20: double as_float;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
union SymBoolArgument {
|
| 108 |
+
10: string as_name;
|
| 109 |
+
20: bool as_bool;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
struct TensorArgument {
|
| 113 |
+
10: string name;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
struct TokenArgument {
|
| 117 |
+
10: string name;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
union OptionalTensorArgument {
|
| 121 |
+
20: TensorArgument as_tensor;
|
| 122 |
+
10: bool as_none;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
struct GraphArgument {
|
| 126 |
+
10: string name;
|
| 127 |
+
20: Graph graph;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
struct CustomObjArgument {
|
| 131 |
+
10: string name;
|
| 132 |
+
20: string class_fqn;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
union Argument {
|
| 136 |
+
10: bool as_none;
|
| 137 |
+
20: TensorArgument as_tensor;
|
| 138 |
+
30: list<TensorArgument> as_tensors;
|
| 139 |
+
50: i64 as_int;
|
| 140 |
+
70: list<i64> as_ints;
|
| 141 |
+
80: double as_float;
|
| 142 |
+
90: list<double> as_floats;
|
| 143 |
+
100: string as_string;
|
| 144 |
+
101: list<string> as_strings;
|
| 145 |
+
110: SymIntArgument as_sym_int;
|
| 146 |
+
120: list<SymIntArgument> as_sym_ints;
|
| 147 |
+
130: ScalarType as_scalar_type;
|
| 148 |
+
140: MemoryFormat as_memory_format;
|
| 149 |
+
150: Layout as_layout;
|
| 150 |
+
160: Device as_device;
|
| 151 |
+
170: bool as_bool;
|
| 152 |
+
180: list<bool> as_bools;
|
| 153 |
+
182: SymBoolArgument as_sym_bool;
|
| 154 |
+
184: list<SymBoolArgument> as_sym_bools;
|
| 155 |
+
200: GraphArgument as_graph;
|
| 156 |
+
190: list<OptionalTensorArgument> as_optional_tensors;
|
| 157 |
+
210: CustomObjArgument as_custom_obj;
|
| 158 |
+
220: string as_operator;
|
| 159 |
+
230: SymFloatArgument as_sym_float;
|
| 160 |
+
240: list<SymFloatArgument> as_sym_floats;
|
| 161 |
+
250: OptionalTensorArgument as_optional_tensor;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
struct NamedArgument {
|
| 165 |
+
10: string name;
|
| 166 |
+
20: Argument arg;
|
| 167 |
+
30: optional ArgumentKind kind;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
struct Node {
|
| 171 |
+
10: string target;
|
| 172 |
+
20: list<NamedArgument> inputs;
|
| 173 |
+
30: list<Argument> outputs;
|
| 174 |
+
40: map<string, string> metadata;
|
| 175 |
+
50: optional bool is_hop_single_tensor_return;
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
struct Graph {
|
| 179 |
+
10: list<Argument> inputs;
|
| 180 |
+
20: list<Argument> outputs;
|
| 181 |
+
30: list<Node> nodes;
|
| 182 |
+
40: map<string, TensorMeta> tensor_values;
|
| 183 |
+
50: map<string, SymInt> sym_int_values;
|
| 184 |
+
60: map<string, SymBool> sym_bool_values;
|
| 185 |
+
70: bool is_single_tensor_return;
|
| 186 |
+
80: map<string, CustomObjArgument> custom_obj_values;
|
| 187 |
+
90: map<string, SymFloat> sym_float_values;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
struct UserInputSpec {
|
| 191 |
+
10: Argument arg;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
union ConstantValue {
|
| 195 |
+
10: bool as_none;
|
| 196 |
+
20: i64 as_int;
|
| 197 |
+
30: double as_float;
|
| 198 |
+
40: string as_string;
|
| 199 |
+
50: bool as_bool;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
struct InputToConstantInputSpec {
|
| 203 |
+
10: string name;
|
| 204 |
+
20: ConstantValue value;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
struct InputToParameterSpec {
|
| 208 |
+
10: TensorArgument arg;
|
| 209 |
+
20: string parameter_name;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
struct InputToBufferSpec {
|
| 213 |
+
10: TensorArgument arg;
|
| 214 |
+
20: string buffer_name;
|
| 215 |
+
30: bool persistent;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
struct InputToTensorConstantSpec {
|
| 219 |
+
10: TensorArgument arg;
|
| 220 |
+
20: string tensor_constant_name;
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
struct InputToCustomObjSpec {
|
| 224 |
+
10: CustomObjArgument arg;
|
| 225 |
+
20: string custom_obj_name;
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
struct InputTokenSpec {
|
| 229 |
+
10: TokenArgument arg;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
union InputSpec {
|
| 233 |
+
10: UserInputSpec user_input;
|
| 234 |
+
20: InputToParameterSpec parameter;
|
| 235 |
+
30: InputToBufferSpec buffer;
|
| 236 |
+
40: InputToTensorConstantSpec tensor_constant;
|
| 237 |
+
50: InputToCustomObjSpec custom_obj;
|
| 238 |
+
70: InputTokenSpec token;
|
| 239 |
+
60: InputToConstantInputSpec constant_input;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
struct UserOutputSpec {
|
| 243 |
+
10: Argument arg;
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
struct LossOutputSpec {
|
| 247 |
+
10: TensorArgument arg;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
struct BufferMutationSpec {
|
| 251 |
+
10: TensorArgument arg;
|
| 252 |
+
20: string buffer_name;
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
struct GradientToParameterSpec {
|
| 256 |
+
10: TensorArgument arg;
|
| 257 |
+
20: string parameter_name;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
struct GradientToUserInputSpec {
|
| 261 |
+
10: TensorArgument arg;
|
| 262 |
+
20: string user_input_name;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
struct UserInputMutationSpec {
|
| 266 |
+
10: TensorArgument arg;
|
| 267 |
+
20: string user_input_name;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
struct OutputTokenSpec {
|
| 271 |
+
10: TokenArgument arg;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
union OutputSpec {
|
| 275 |
+
10: UserOutputSpec user_output;
|
| 276 |
+
20: LossOutputSpec loss_output;
|
| 277 |
+
30: BufferMutationSpec buffer_mutation;
|
| 278 |
+
40: GradientToParameterSpec gradient_to_parameter;
|
| 279 |
+
50: GradientToUserInputSpec gradient_to_user_input;
|
| 280 |
+
60: UserInputMutationSpec user_input_mutation;
|
| 281 |
+
70: OutputTokenSpec token;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
struct GraphSignature {
|
| 285 |
+
10: list<InputSpec> input_specs;
|
| 286 |
+
20: list<OutputSpec> output_specs;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
struct RangeConstraint {
|
| 290 |
+
10: optional i64 min_val;
|
| 291 |
+
20: optional i64 max_val;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
struct ModuleCallSignature {
|
| 295 |
+
10: list<Argument> inputs;
|
| 296 |
+
20: list<Argument> outputs;
|
| 297 |
+
30: string in_spec;
|
| 298 |
+
40: string out_spec;
|
| 299 |
+
50: optional list<string> forward_arg_names;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
struct ModuleCallEntry {
|
| 303 |
+
10: string fqn;
|
| 304 |
+
30: optional ModuleCallSignature signature;
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
struct NamedTupleDef {
|
| 308 |
+
10: list<string> field_names;
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
struct GraphModule {
|
| 312 |
+
10: Graph graph;
|
| 313 |
+
50: GraphSignature signature;
|
| 314 |
+
60: list<ModuleCallEntry> module_call_graph;
|
| 315 |
+
40: map<string, string> metadata;
|
| 316 |
+
70: map<string, NamedTupleDef> treespec_namedtuple_fields;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
struct SchemaVersion {
|
| 320 |
+
10: i64 major;
|
| 321 |
+
20: i64 minor;
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
struct ExportedProgram {
|
| 325 |
+
10: GraphModule graph_module;
|
| 326 |
+
20: map<string, i64> opset_version;
|
| 327 |
+
30: map<string, RangeConstraint> range_constraints;
|
| 328 |
+
60: SchemaVersion schema_version;
|
| 329 |
+
70: list<string> verifiers;
|
| 330 |
+
80: string torch_version;
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
struct Program {
|
| 334 |
+
200: map<string, ExportedProgram> methods;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
struct Model {
|
| 338 |
+
10: string name;
|
| 339 |
+
20: map<string, string> tensorPaths;
|
| 340 |
+
40: Program program;
|
| 341 |
+
50: map<string, Program> delegates;
|
| 342 |
+
60: map<string, string> deviceAllocationMap;
|
| 343 |
+
70: map<string, string> constantPaths;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
struct AOTInductorModelPickleData {
|
| 347 |
+
1: string library_basename;
|
| 348 |
+
2: list<string> input_names;
|
| 349 |
+
3: list<string> output_names;
|
| 350 |
+
4: optional i64 floating_point_input_dtype;
|
| 351 |
+
5: optional i64 floating_point_output_dtype;
|
| 352 |
+
6: optional bool aot_inductor_model_is_cpu;
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
struct ExternKernelNode {
|
| 356 |
+
10: string name;
|
| 357 |
+
20: Node node;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
struct ExternKernelNodes {
|
| 361 |
+
10: list<ExternKernelNode> nodes;
|
| 362 |
+
}
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/schema.py
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This is a placeholder for iterating on export serialization schema design.
|
| 2 |
+
# Anything is subject to change and no guarantee is provided at this point.
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from enum import IntEnum
|
| 6 |
+
from typing import Annotated, Optional
|
| 7 |
+
|
| 8 |
+
from torch._export.serde.union import _Union
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# NOTE: Please update this value if any modifications are made to the schema
|
| 12 |
+
SCHEMA_VERSION = (8, 8)
|
| 13 |
+
TREESPEC_VERSION = 1
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# NOTE: If you updated the schema, please run `scripts/export/update_schema.py`
|
| 17 |
+
# to update the auto generated files.
|
| 18 |
+
class ScalarType(IntEnum):
|
| 19 |
+
UNKNOWN = 0
|
| 20 |
+
BYTE = 1
|
| 21 |
+
CHAR = 2
|
| 22 |
+
SHORT = 3
|
| 23 |
+
INT = 4
|
| 24 |
+
LONG = 5
|
| 25 |
+
HALF = 6
|
| 26 |
+
FLOAT = 7
|
| 27 |
+
DOUBLE = 8
|
| 28 |
+
COMPLEXHALF = 9
|
| 29 |
+
COMPLEXFLOAT = 10
|
| 30 |
+
COMPLEXDOUBLE = 11
|
| 31 |
+
BOOL = 12
|
| 32 |
+
BFLOAT16 = 13
|
| 33 |
+
UINT16 = 28
|
| 34 |
+
FLOAT8E4M3FN = 29
|
| 35 |
+
FLOAT8E5M2 = 30
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Layout(IntEnum):
|
| 39 |
+
Unknown = 0
|
| 40 |
+
SparseCoo = 1
|
| 41 |
+
SparseCsr = 2
|
| 42 |
+
SparseCsc = 3
|
| 43 |
+
SparseBsr = 4
|
| 44 |
+
SparseBsc = 5
|
| 45 |
+
_mkldnn = 6
|
| 46 |
+
Strided = 7
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MemoryFormat(IntEnum):
|
| 50 |
+
Unknown = 0
|
| 51 |
+
ContiguousFormat = 1
|
| 52 |
+
ChannelsLast = 2
|
| 53 |
+
ChannelsLast3d = 3
|
| 54 |
+
PreserveFormat = 4
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class Device:
|
| 59 |
+
type: Annotated[str, 10]
|
| 60 |
+
index: Annotated[Optional[int], 20] = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(repr=False)
|
| 64 |
+
class SymExprHint(_Union):
|
| 65 |
+
as_int: Annotated[int, 10]
|
| 66 |
+
as_bool: Annotated[bool, 20]
|
| 67 |
+
as_float: Annotated[float, 30]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# This is for storing the symbolic expressions behind symints/symfloats/symbools
|
| 71 |
+
# For example, we can get something like
|
| 72 |
+
# SymExpr(expr_str="s0 + s1", hint=SymExprHint(as_int=4)
|
| 73 |
+
# if we also have the hint that s0 and s1 are both 2.
|
| 74 |
+
@dataclass
|
| 75 |
+
class SymExpr:
|
| 76 |
+
expr_str: Annotated[str, 10]
|
| 77 |
+
hint: Annotated[Optional[SymExprHint], 20] = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(repr=False)
|
| 81 |
+
class SymInt(_Union):
|
| 82 |
+
as_expr: Annotated[SymExpr, 10]
|
| 83 |
+
as_int: Annotated[int, 20]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(repr=False)
|
| 87 |
+
class SymFloat(_Union):
|
| 88 |
+
as_expr: Annotated[SymExpr, 10]
|
| 89 |
+
as_float: Annotated[float, 20]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass(repr=False)
|
| 93 |
+
class SymBool(_Union):
|
| 94 |
+
as_expr: Annotated[SymExpr, 10]
|
| 95 |
+
as_bool: Annotated[bool, 20]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dataclass
|
| 99 |
+
class TensorMeta:
|
| 100 |
+
dtype: Annotated[ScalarType, 10]
|
| 101 |
+
sizes: Annotated[list[SymInt], 20]
|
| 102 |
+
requires_grad: Annotated[bool, 30]
|
| 103 |
+
device: Annotated[Device, 40]
|
| 104 |
+
strides: Annotated[list[SymInt], 50]
|
| 105 |
+
storage_offset: Annotated[SymInt, 60]
|
| 106 |
+
layout: Annotated[Layout, 70]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# In most cases we will use the "as_name" field to store arguments which are
|
| 110 |
+
# SymInts.
|
| 111 |
+
# The "as_int" field is used in the case where we have a list containing a mix
|
| 112 |
+
# of SymInt and ints (ex. [1, s0, ...]). We will serialize this type of list to
|
| 113 |
+
# be List[SymIntArgument] and map the SymInts to the "as_name" field, and ints
|
| 114 |
+
# to the "as_int" field.
|
| 115 |
+
@dataclass(repr=False)
|
| 116 |
+
class SymIntArgument(_Union):
|
| 117 |
+
as_name: Annotated[str, 10]
|
| 118 |
+
as_int: Annotated[int, 20]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# In most cases we will use the "as_name" field to store arguments which are
|
| 122 |
+
# SymFloats.
|
| 123 |
+
# The "as_float" field is used in the case where we have a list containing a mix
|
| 124 |
+
# of SymFloat and float (ex. [1.0, s0, ...]). We will serialize this type of list to
|
| 125 |
+
# be List[SymFloatArgument] and map the SymFloats to the "as_name" field, and ints
|
| 126 |
+
# to the "as_float" field.
|
| 127 |
+
@dataclass(repr=False)
|
| 128 |
+
class SymFloatArgument(_Union):
|
| 129 |
+
as_name: Annotated[str, 10]
|
| 130 |
+
as_float: Annotated[float, 20]
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# In most cases we will use the "as_name" field to store arguments which are
|
| 134 |
+
# SymBools.
|
| 135 |
+
# The "as_bool" field is used in the case where we have a list containing a mix
|
| 136 |
+
# of SymBool and bools (ex. [True, i0, ...]). We will serialize this type of list to
|
| 137 |
+
# be List[SymboolArgument] and map the SymBools to the "as_name" field, and bools
|
| 138 |
+
# to the "as_bool" field.
|
| 139 |
+
@dataclass(repr=False)
|
| 140 |
+
class SymBoolArgument(_Union):
|
| 141 |
+
as_name: Annotated[str, 10]
|
| 142 |
+
as_bool: Annotated[bool, 20]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@dataclass
|
| 146 |
+
class TensorArgument:
|
| 147 |
+
name: Annotated[str, 10]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@dataclass
|
| 151 |
+
class TokenArgument:
|
| 152 |
+
name: Annotated[str, 10]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# This is use for storing the contents of a list which contain optional tensors
|
| 156 |
+
# (Tensor?[], ex. [Tensor, None, ...]), where the list will be serialized to the
|
| 157 |
+
# type List[OptionalTensorArgument], with tensor values seiralized to the
|
| 158 |
+
# "as_tensor" field, and None values serialized to the "as_none" field.
|
| 159 |
+
@dataclass(repr=False)
|
| 160 |
+
class OptionalTensorArgument(_Union):
|
| 161 |
+
as_tensor: Annotated[TensorArgument, 20]
|
| 162 |
+
as_none: Annotated[bool, 10]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class GraphArgument:
|
| 167 |
+
name: Annotated[str, 10]
|
| 168 |
+
graph: Annotated["Graph", 20]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@dataclass
|
| 172 |
+
class CustomObjArgument:
|
| 173 |
+
name: Annotated[str, 10]
|
| 174 |
+
class_fqn: Annotated[str, 20]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# This is actually a union type
|
| 178 |
+
@dataclass(repr=False)
|
| 179 |
+
class Argument(_Union):
|
| 180 |
+
as_none: Annotated[bool, 10]
|
| 181 |
+
as_tensor: Annotated[TensorArgument, 20]
|
| 182 |
+
as_tensors: Annotated[list[TensorArgument], 30]
|
| 183 |
+
as_int: Annotated[int, 50]
|
| 184 |
+
as_ints: Annotated[list[int], 70]
|
| 185 |
+
as_float: Annotated[float, 80]
|
| 186 |
+
as_floats: Annotated[list[float], 90]
|
| 187 |
+
as_string: Annotated[str, 100]
|
| 188 |
+
as_strings: Annotated[list[str], 101]
|
| 189 |
+
as_sym_int: Annotated[SymIntArgument, 110]
|
| 190 |
+
as_sym_ints: Annotated[list[SymIntArgument], 120]
|
| 191 |
+
as_scalar_type: Annotated[ScalarType, 130]
|
| 192 |
+
as_memory_format: Annotated[MemoryFormat, 140]
|
| 193 |
+
as_layout: Annotated[Layout, 150]
|
| 194 |
+
as_device: Annotated[Device, 160]
|
| 195 |
+
as_bool: Annotated[bool, 170]
|
| 196 |
+
as_bools: Annotated[list[bool], 180]
|
| 197 |
+
as_sym_bool: Annotated[SymBoolArgument, 182]
|
| 198 |
+
as_sym_bools: Annotated[list[SymBoolArgument], 184]
|
| 199 |
+
as_graph: Annotated[GraphArgument, 200]
|
| 200 |
+
as_optional_tensors: Annotated[list[OptionalTensorArgument], 190]
|
| 201 |
+
as_custom_obj: Annotated[CustomObjArgument, 210]
|
| 202 |
+
as_operator: Annotated[str, 220]
|
| 203 |
+
as_sym_float: Annotated[SymFloatArgument, 230]
|
| 204 |
+
as_sym_floats: Annotated[list[SymFloatArgument], 240]
|
| 205 |
+
as_optional_tensor: Annotated[OptionalTensorArgument, 250]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class ArgumentKind(IntEnum):
|
| 209 |
+
UNKNOWN = 0
|
| 210 |
+
POSITIONAL = 1
|
| 211 |
+
KEYWORD = 2
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@dataclass
|
| 215 |
+
class NamedArgument:
|
| 216 |
+
# Argument name from the operator schema
|
| 217 |
+
name: Annotated[str, 10]
|
| 218 |
+
arg: Annotated[Argument, 20]
|
| 219 |
+
kind: Annotated[Optional[ArgumentKind], 30] = None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@dataclass
|
| 223 |
+
class Node:
|
| 224 |
+
target: Annotated[str, 10]
|
| 225 |
+
inputs: Annotated[list[NamedArgument], 20]
|
| 226 |
+
outputs: Annotated[list[Argument], 30]
|
| 227 |
+
metadata: Annotated[dict[str, str], 40]
|
| 228 |
+
is_hop_single_tensor_return: Annotated[Optional[bool], 50] = None
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@dataclass
|
| 232 |
+
class Graph:
|
| 233 |
+
inputs: Annotated[list[Argument], 10]
|
| 234 |
+
outputs: Annotated[list[Argument], 20]
|
| 235 |
+
nodes: Annotated[list[Node], 30]
|
| 236 |
+
tensor_values: Annotated[dict[str, TensorMeta], 40]
|
| 237 |
+
sym_int_values: Annotated[dict[str, SymInt], 50]
|
| 238 |
+
sym_bool_values: Annotated[dict[str, SymBool], 60]
|
| 239 |
+
# This is for deserializing the submodule graphs from higher order ops
|
| 240 |
+
# (ex. cond, map) where single tensor returns will just return a single
|
| 241 |
+
# tensor, rather than following export schema and returning a singleton
|
| 242 |
+
# list.
|
| 243 |
+
is_single_tensor_return: Annotated[bool, 70] = False
|
| 244 |
+
custom_obj_values: Annotated[dict[str, CustomObjArgument], 80] = field(
|
| 245 |
+
default_factory=dict
|
| 246 |
+
)
|
| 247 |
+
sym_float_values: Annotated[dict[str, SymFloat], 90] = field(default_factory=dict)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@dataclass
|
| 251 |
+
class UserInputSpec:
|
| 252 |
+
# Actually, only tensors and SymInts are allowed here
|
| 253 |
+
arg: Annotated[Argument, 10]
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@dataclass(repr=False)
|
| 257 |
+
class ConstantValue(_Union):
|
| 258 |
+
as_none: Annotated[bool, 10]
|
| 259 |
+
as_int: Annotated[int, 20]
|
| 260 |
+
as_float: Annotated[float, 30]
|
| 261 |
+
as_string: Annotated[str, 40]
|
| 262 |
+
as_bool: Annotated[bool, 50]
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dataclass
|
| 266 |
+
class InputToConstantInputSpec:
|
| 267 |
+
name: Annotated[str, 10]
|
| 268 |
+
value: Annotated[ConstantValue, 20]
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@dataclass
|
| 272 |
+
class InputToParameterSpec:
|
| 273 |
+
arg: Annotated[TensorArgument, 10]
|
| 274 |
+
parameter_name: Annotated[str, 20]
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@dataclass
|
| 278 |
+
class InputToBufferSpec:
|
| 279 |
+
arg: Annotated[TensorArgument, 10]
|
| 280 |
+
buffer_name: Annotated[str, 20]
|
| 281 |
+
persistent: Annotated[bool, 30]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
@dataclass
|
| 285 |
+
class InputToTensorConstantSpec:
|
| 286 |
+
arg: Annotated[TensorArgument, 10]
|
| 287 |
+
tensor_constant_name: Annotated[str, 20]
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@dataclass
|
| 291 |
+
class InputToCustomObjSpec:
|
| 292 |
+
arg: Annotated[CustomObjArgument, 10]
|
| 293 |
+
custom_obj_name: Annotated[str, 20]
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@dataclass
|
| 297 |
+
class InputTokenSpec:
|
| 298 |
+
arg: Annotated[TokenArgument, 10]
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@dataclass(repr=False)
|
| 302 |
+
class InputSpec(_Union):
|
| 303 |
+
user_input: Annotated[UserInputSpec, 10]
|
| 304 |
+
parameter: Annotated[InputToParameterSpec, 20]
|
| 305 |
+
buffer: Annotated[InputToBufferSpec, 30]
|
| 306 |
+
tensor_constant: Annotated[InputToTensorConstantSpec, 40]
|
| 307 |
+
custom_obj: Annotated[InputToCustomObjSpec, 50]
|
| 308 |
+
token: Annotated[InputTokenSpec, 70]
|
| 309 |
+
constant_input: Annotated[InputToConstantInputSpec, 60]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@dataclass
|
| 313 |
+
class UserOutputSpec:
|
| 314 |
+
arg: Annotated[Argument, 10]
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@dataclass
|
| 318 |
+
class LossOutputSpec:
|
| 319 |
+
arg: Annotated[TensorArgument, 10]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@dataclass
|
| 323 |
+
class BufferMutationSpec:
|
| 324 |
+
arg: Annotated[TensorArgument, 10]
|
| 325 |
+
buffer_name: Annotated[str, 20]
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@dataclass
|
| 329 |
+
class GradientToParameterSpec:
|
| 330 |
+
arg: Annotated[TensorArgument, 10]
|
| 331 |
+
parameter_name: Annotated[str, 20]
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@dataclass
|
| 335 |
+
class GradientToUserInputSpec:
|
| 336 |
+
arg: Annotated[TensorArgument, 10]
|
| 337 |
+
user_input_name: Annotated[str, 20]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@dataclass
|
| 341 |
+
class UserInputMutationSpec:
|
| 342 |
+
arg: Annotated[TensorArgument, 10]
|
| 343 |
+
user_input_name: Annotated[str, 20]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
@dataclass
|
| 347 |
+
class OutputTokenSpec:
|
| 348 |
+
arg: Annotated[TokenArgument, 10]
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@dataclass(repr=False)
|
| 352 |
+
class OutputSpec(_Union):
|
| 353 |
+
user_output: Annotated[UserOutputSpec, 10]
|
| 354 |
+
loss_output: Annotated[LossOutputSpec, 20]
|
| 355 |
+
buffer_mutation: Annotated[BufferMutationSpec, 30]
|
| 356 |
+
gradient_to_parameter: Annotated[GradientToParameterSpec, 40]
|
| 357 |
+
gradient_to_user_input: Annotated[GradientToUserInputSpec, 50]
|
| 358 |
+
user_input_mutation: Annotated[UserInputMutationSpec, 60]
|
| 359 |
+
token: Annotated[OutputTokenSpec, 70]
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@dataclass
|
| 363 |
+
class GraphSignature:
|
| 364 |
+
input_specs: Annotated[list[InputSpec], 10]
|
| 365 |
+
output_specs: Annotated[list[OutputSpec], 20]
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
@dataclass
|
| 369 |
+
class RangeConstraint:
|
| 370 |
+
min_val: Annotated[Optional[int], 10]
|
| 371 |
+
max_val: Annotated[Optional[int], 20]
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
@dataclass
|
| 375 |
+
class ModuleCallSignature:
|
| 376 |
+
inputs: Annotated[list[Argument], 10]
|
| 377 |
+
outputs: Annotated[list[Argument], 20]
|
| 378 |
+
|
| 379 |
+
# These are serialized by calling pytree.treespec_loads
|
| 380 |
+
# And deserialized by calling pytree.treespec_dumps
|
| 381 |
+
in_spec: Annotated[str, 30]
|
| 382 |
+
out_spec: Annotated[str, 40]
|
| 383 |
+
|
| 384 |
+
# This field is used to prettify the graph placeholders
|
| 385 |
+
# after we ser/der and retrace
|
| 386 |
+
forward_arg_names: Annotated[Optional[list[str]], 50] = None
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@dataclass
|
| 390 |
+
class ModuleCallEntry:
|
| 391 |
+
fqn: Annotated[str, 10]
|
| 392 |
+
signature: Annotated[Optional[ModuleCallSignature], 30] = None
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@dataclass
|
| 396 |
+
class NamedTupleDef:
|
| 397 |
+
field_names: Annotated[list[str], 10]
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@dataclass
|
| 401 |
+
class GraphModule:
|
| 402 |
+
graph: Annotated[Graph, 10]
|
| 403 |
+
signature: Annotated[GraphSignature, 50]
|
| 404 |
+
# This is used for unflattening, by tracking the calling structure of all of
|
| 405 |
+
# the modules in order to unflatten the modules back to the eager calling
|
| 406 |
+
# conventions.
|
| 407 |
+
module_call_graph: Annotated[list[ModuleCallEntry], 60]
|
| 408 |
+
metadata: Annotated[dict[str, str], 40] = field(default_factory=dict)
|
| 409 |
+
# Mapping of namedtuple types to namedtuple field names, used for BC
|
| 410 |
+
treespec_namedtuple_fields: Annotated[dict[str, NamedTupleDef], 70] = field(
|
| 411 |
+
default_factory=dict
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# Invariant: Every time a change is made to the schema, one of the versions
|
| 416 |
+
# should be upadted.
|
| 417 |
+
@dataclass
|
| 418 |
+
class SchemaVersion:
|
| 419 |
+
major: Annotated[
|
| 420 |
+
int, 10
|
| 421 |
+
] # Major version number is bumped every time a breaking change is made.
|
| 422 |
+
minor: Annotated[
|
| 423 |
+
int, 20
|
| 424 |
+
] # Minor version number is bumped when a compatible change is made.
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
@dataclass
|
| 428 |
+
class ExportedProgram:
|
| 429 |
+
graph_module: Annotated[GraphModule, 10]
|
| 430 |
+
# Key is the opset namespace (ex. aten), and value is the version number
|
| 431 |
+
opset_version: Annotated[dict[str, int], 20]
|
| 432 |
+
range_constraints: Annotated[dict[str, RangeConstraint], 30]
|
| 433 |
+
schema_version: Annotated[SchemaVersion, 60]
|
| 434 |
+
verifiers: Annotated[list[str], 70] = field(default_factory=list)
|
| 435 |
+
torch_version: Annotated[str, 80] = "<=2.4"
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
#########################################################################
|
| 439 |
+
# Container types for inference tasks, not being used directly for export.
|
| 440 |
+
#########################################################################
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
@dataclass
|
| 444 |
+
class Program:
|
| 445 |
+
methods: Annotated[dict[str, ExportedProgram], 200]
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# This is the top-level model definition that be will serialized into the package
|
| 449 |
+
@dataclass
|
| 450 |
+
class Model:
|
| 451 |
+
# unique identifier of the model in the package, e.g. local, remote, merge
|
| 452 |
+
name: Annotated[str, 10]
|
| 453 |
+
# key is the FQN of tensor in exported program
|
| 454 |
+
# value is the archive path of tensor payloads
|
| 455 |
+
# e.g. "L__self__linear.weight" : "/data/tensor/L__self__linear.weight"
|
| 456 |
+
tensorPaths: Annotated[dict[str, str], 20]
|
| 457 |
+
# program exported from torch.export()
|
| 458 |
+
program: Annotated[Program, 40]
|
| 459 |
+
# Backend-specialized Lowered GraphModule
|
| 460 |
+
# e.g. "aotinductor-a100" : ExportedProgram_with_AOTInductor_delegate
|
| 461 |
+
delegates: Annotated[dict[str, Program], 50]
|
| 462 |
+
deviceAllocationMap: Annotated[dict[str, str], 60]
|
| 463 |
+
# key is the FQN of constant in exported program (constant tensor or torchbind objs)
|
| 464 |
+
# value is the archive path of serialized constants
|
| 465 |
+
constantPaths: Annotated[dict[str, str], 70]
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
#
|
| 469 |
+
# The structure is used to serialize instances of AOTInductorModel to pass
|
| 470 |
+
# them from the publishing pipeline to the predictor.
|
| 471 |
+
#
|
| 472 |
+
# All new fields should be marked as optional.
|
| 473 |
+
#
|
| 474 |
+
@dataclass
|
| 475 |
+
class AOTInductorModelPickleData:
|
| 476 |
+
# Base name of an associated .so AOTInductor library. Typically looks like:
|
| 477 |
+
# "abc.so".
|
| 478 |
+
library_basename: Annotated[str, 1]
|
| 479 |
+
|
| 480 |
+
# AOTInductor engine input names.
|
| 481 |
+
input_names: Annotated[list[str], 2]
|
| 482 |
+
|
| 483 |
+
# AOTInductor engine output names.
|
| 484 |
+
output_names: Annotated[list[str], 3]
|
| 485 |
+
|
| 486 |
+
# These fields tell whether floating point inputs/outputs should be converted to
|
| 487 |
+
# a certain type. If None, the dtypes that the AOTInductor engine inferred from the sample
|
| 488 |
+
# inputs are used.
|
| 489 |
+
floating_point_input_dtype: Annotated[Optional[int], 4] = None
|
| 490 |
+
floating_point_output_dtype: Annotated[Optional[int], 5] = None
|
| 491 |
+
|
| 492 |
+
# Whether AOTInductor runtime is for CPU.
|
| 493 |
+
aot_inductor_model_is_cpu: Annotated[Optional[bool], 6] = None
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@dataclass
|
| 497 |
+
class ExternKernelNode:
|
| 498 |
+
# name is not the unique identifier of the node
|
| 499 |
+
name: Annotated[str, 10]
|
| 500 |
+
node: Annotated[Node, 20]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@dataclass
|
| 504 |
+
class ExternKernelNodes:
|
| 505 |
+
nodes: Annotated[list[ExternKernelNode], 10]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/schema.yaml
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# @generated by update_schema.py
|
| 2 |
+
# checksum<<110c364974d3b0f7dcbdf6862781212bdcc7178925c43c894c336fc2b6ca6628>>
|
| 3 |
+
AOTInductorModelPickleData:
|
| 4 |
+
kind: struct
|
| 5 |
+
fields:
|
| 6 |
+
library_basename:
|
| 7 |
+
type: str
|
| 8 |
+
input_names:
|
| 9 |
+
type: List[str]
|
| 10 |
+
output_names:
|
| 11 |
+
type: List[str]
|
| 12 |
+
floating_point_input_dtype:
|
| 13 |
+
type: Optional[int]
|
| 14 |
+
default: None
|
| 15 |
+
floating_point_output_dtype:
|
| 16 |
+
type: Optional[int]
|
| 17 |
+
default: None
|
| 18 |
+
aot_inductor_model_is_cpu:
|
| 19 |
+
type: Optional[bool]
|
| 20 |
+
default: None
|
| 21 |
+
Argument:
|
| 22 |
+
kind: union
|
| 23 |
+
fields:
|
| 24 |
+
as_none:
|
| 25 |
+
type: bool
|
| 26 |
+
as_tensor:
|
| 27 |
+
type: TensorArgument
|
| 28 |
+
as_tensors:
|
| 29 |
+
type: List[TensorArgument]
|
| 30 |
+
as_int:
|
| 31 |
+
type: int
|
| 32 |
+
as_ints:
|
| 33 |
+
type: List[int]
|
| 34 |
+
as_float:
|
| 35 |
+
type: float
|
| 36 |
+
as_floats:
|
| 37 |
+
type: List[float]
|
| 38 |
+
as_string:
|
| 39 |
+
type: str
|
| 40 |
+
as_strings:
|
| 41 |
+
type: List[str]
|
| 42 |
+
as_sym_int:
|
| 43 |
+
type: SymIntArgument
|
| 44 |
+
as_sym_ints:
|
| 45 |
+
type: List[SymIntArgument]
|
| 46 |
+
as_scalar_type:
|
| 47 |
+
type: ScalarType
|
| 48 |
+
as_memory_format:
|
| 49 |
+
type: MemoryFormat
|
| 50 |
+
as_layout:
|
| 51 |
+
type: Layout
|
| 52 |
+
as_device:
|
| 53 |
+
type: Device
|
| 54 |
+
as_bool:
|
| 55 |
+
type: bool
|
| 56 |
+
as_bools:
|
| 57 |
+
type: List[bool]
|
| 58 |
+
as_sym_bool:
|
| 59 |
+
type: SymBoolArgument
|
| 60 |
+
as_sym_bools:
|
| 61 |
+
type: List[SymBoolArgument]
|
| 62 |
+
as_graph:
|
| 63 |
+
type: GraphArgument
|
| 64 |
+
as_optional_tensors:
|
| 65 |
+
type: List[OptionalTensorArgument]
|
| 66 |
+
as_custom_obj:
|
| 67 |
+
type: CustomObjArgument
|
| 68 |
+
as_operator:
|
| 69 |
+
type: str
|
| 70 |
+
as_sym_float:
|
| 71 |
+
type: SymFloatArgument
|
| 72 |
+
as_sym_floats:
|
| 73 |
+
type: List[SymFloatArgument]
|
| 74 |
+
as_optional_tensor:
|
| 75 |
+
type: OptionalTensorArgument
|
| 76 |
+
ArgumentKind:
|
| 77 |
+
kind: enum
|
| 78 |
+
fields:
|
| 79 |
+
UNKNOWN: 0
|
| 80 |
+
POSITIONAL: 1
|
| 81 |
+
KEYWORD: 2
|
| 82 |
+
BufferMutationSpec:
|
| 83 |
+
kind: struct
|
| 84 |
+
fields:
|
| 85 |
+
arg:
|
| 86 |
+
type: TensorArgument
|
| 87 |
+
buffer_name:
|
| 88 |
+
type: str
|
| 89 |
+
ConstantValue:
|
| 90 |
+
kind: union
|
| 91 |
+
fields:
|
| 92 |
+
as_none:
|
| 93 |
+
type: bool
|
| 94 |
+
as_int:
|
| 95 |
+
type: int
|
| 96 |
+
as_float:
|
| 97 |
+
type: float
|
| 98 |
+
as_string:
|
| 99 |
+
type: str
|
| 100 |
+
as_bool:
|
| 101 |
+
type: bool
|
| 102 |
+
CustomObjArgument:
|
| 103 |
+
kind: struct
|
| 104 |
+
fields:
|
| 105 |
+
name:
|
| 106 |
+
type: str
|
| 107 |
+
class_fqn:
|
| 108 |
+
type: str
|
| 109 |
+
Device:
|
| 110 |
+
kind: struct
|
| 111 |
+
fields:
|
| 112 |
+
type:
|
| 113 |
+
type: str
|
| 114 |
+
index:
|
| 115 |
+
type: Optional[int]
|
| 116 |
+
default: None
|
| 117 |
+
ExportedProgram:
|
| 118 |
+
kind: struct
|
| 119 |
+
fields:
|
| 120 |
+
graph_module:
|
| 121 |
+
type: GraphModule
|
| 122 |
+
opset_version:
|
| 123 |
+
type: Dict[str, int]
|
| 124 |
+
range_constraints:
|
| 125 |
+
type: Dict[str, RangeConstraint]
|
| 126 |
+
schema_version:
|
| 127 |
+
type: SchemaVersion
|
| 128 |
+
verifiers:
|
| 129 |
+
type: List[str]
|
| 130 |
+
default: '[]'
|
| 131 |
+
torch_version:
|
| 132 |
+
type: str
|
| 133 |
+
default: <=2.4
|
| 134 |
+
ExternKernelNode:
|
| 135 |
+
kind: struct
|
| 136 |
+
fields:
|
| 137 |
+
name:
|
| 138 |
+
type: str
|
| 139 |
+
node:
|
| 140 |
+
type: Node
|
| 141 |
+
ExternKernelNodes:
|
| 142 |
+
kind: struct
|
| 143 |
+
fields:
|
| 144 |
+
nodes:
|
| 145 |
+
type: List[ExternKernelNode]
|
| 146 |
+
GradientToParameterSpec:
|
| 147 |
+
kind: struct
|
| 148 |
+
fields:
|
| 149 |
+
arg:
|
| 150 |
+
type: TensorArgument
|
| 151 |
+
parameter_name:
|
| 152 |
+
type: str
|
| 153 |
+
GradientToUserInputSpec:
|
| 154 |
+
kind: struct
|
| 155 |
+
fields:
|
| 156 |
+
arg:
|
| 157 |
+
type: TensorArgument
|
| 158 |
+
user_input_name:
|
| 159 |
+
type: str
|
| 160 |
+
Graph:
|
| 161 |
+
kind: struct
|
| 162 |
+
fields:
|
| 163 |
+
inputs:
|
| 164 |
+
type: List[Argument]
|
| 165 |
+
outputs:
|
| 166 |
+
type: List[Argument]
|
| 167 |
+
nodes:
|
| 168 |
+
type: List[Node]
|
| 169 |
+
tensor_values:
|
| 170 |
+
type: Dict[str, TensorMeta]
|
| 171 |
+
sym_int_values:
|
| 172 |
+
type: Dict[str, SymInt]
|
| 173 |
+
sym_bool_values:
|
| 174 |
+
type: Dict[str, SymBool]
|
| 175 |
+
is_single_tensor_return:
|
| 176 |
+
type: bool
|
| 177 |
+
default: 'False'
|
| 178 |
+
custom_obj_values:
|
| 179 |
+
type: Dict[str, CustomObjArgument]
|
| 180 |
+
default: '{}'
|
| 181 |
+
sym_float_values:
|
| 182 |
+
type: Dict[str, SymFloat]
|
| 183 |
+
default: '{}'
|
| 184 |
+
GraphArgument:
|
| 185 |
+
kind: struct
|
| 186 |
+
fields:
|
| 187 |
+
name:
|
| 188 |
+
type: str
|
| 189 |
+
graph:
|
| 190 |
+
type: Graph
|
| 191 |
+
GraphModule:
|
| 192 |
+
kind: struct
|
| 193 |
+
fields:
|
| 194 |
+
graph:
|
| 195 |
+
type: Graph
|
| 196 |
+
signature:
|
| 197 |
+
type: GraphSignature
|
| 198 |
+
module_call_graph:
|
| 199 |
+
type: List[ModuleCallEntry]
|
| 200 |
+
metadata:
|
| 201 |
+
type: Dict[str, str]
|
| 202 |
+
default: '{}'
|
| 203 |
+
treespec_namedtuple_fields:
|
| 204 |
+
type: Dict[str, NamedTupleDef]
|
| 205 |
+
default: '{}'
|
| 206 |
+
GraphSignature:
|
| 207 |
+
kind: struct
|
| 208 |
+
fields:
|
| 209 |
+
input_specs:
|
| 210 |
+
type: List[InputSpec]
|
| 211 |
+
output_specs:
|
| 212 |
+
type: List[OutputSpec]
|
| 213 |
+
InputSpec:
|
| 214 |
+
kind: union
|
| 215 |
+
fields:
|
| 216 |
+
user_input:
|
| 217 |
+
type: UserInputSpec
|
| 218 |
+
parameter:
|
| 219 |
+
type: InputToParameterSpec
|
| 220 |
+
buffer:
|
| 221 |
+
type: InputToBufferSpec
|
| 222 |
+
tensor_constant:
|
| 223 |
+
type: InputToTensorConstantSpec
|
| 224 |
+
custom_obj:
|
| 225 |
+
type: InputToCustomObjSpec
|
| 226 |
+
token:
|
| 227 |
+
type: InputTokenSpec
|
| 228 |
+
constant_input:
|
| 229 |
+
type: InputToConstantInputSpec
|
| 230 |
+
InputToBufferSpec:
|
| 231 |
+
kind: struct
|
| 232 |
+
fields:
|
| 233 |
+
arg:
|
| 234 |
+
type: TensorArgument
|
| 235 |
+
buffer_name:
|
| 236 |
+
type: str
|
| 237 |
+
persistent:
|
| 238 |
+
type: bool
|
| 239 |
+
InputToConstantInputSpec:
|
| 240 |
+
kind: struct
|
| 241 |
+
fields:
|
| 242 |
+
name:
|
| 243 |
+
type: str
|
| 244 |
+
value:
|
| 245 |
+
type: ConstantValue
|
| 246 |
+
InputToCustomObjSpec:
|
| 247 |
+
kind: struct
|
| 248 |
+
fields:
|
| 249 |
+
arg:
|
| 250 |
+
type: CustomObjArgument
|
| 251 |
+
custom_obj_name:
|
| 252 |
+
type: str
|
| 253 |
+
InputToParameterSpec:
|
| 254 |
+
kind: struct
|
| 255 |
+
fields:
|
| 256 |
+
arg:
|
| 257 |
+
type: TensorArgument
|
| 258 |
+
parameter_name:
|
| 259 |
+
type: str
|
| 260 |
+
InputToTensorConstantSpec:
|
| 261 |
+
kind: struct
|
| 262 |
+
fields:
|
| 263 |
+
arg:
|
| 264 |
+
type: TensorArgument
|
| 265 |
+
tensor_constant_name:
|
| 266 |
+
type: str
|
| 267 |
+
InputTokenSpec:
|
| 268 |
+
kind: struct
|
| 269 |
+
fields:
|
| 270 |
+
arg:
|
| 271 |
+
type: TokenArgument
|
| 272 |
+
Layout:
|
| 273 |
+
kind: enum
|
| 274 |
+
fields:
|
| 275 |
+
Unknown: 0
|
| 276 |
+
SparseCoo: 1
|
| 277 |
+
SparseCsr: 2
|
| 278 |
+
SparseCsc: 3
|
| 279 |
+
SparseBsr: 4
|
| 280 |
+
SparseBsc: 5
|
| 281 |
+
_mkldnn: 6
|
| 282 |
+
Strided: 7
|
| 283 |
+
LossOutputSpec:
|
| 284 |
+
kind: struct
|
| 285 |
+
fields:
|
| 286 |
+
arg:
|
| 287 |
+
type: TensorArgument
|
| 288 |
+
MemoryFormat:
|
| 289 |
+
kind: enum
|
| 290 |
+
fields:
|
| 291 |
+
Unknown: 0
|
| 292 |
+
ContiguousFormat: 1
|
| 293 |
+
ChannelsLast: 2
|
| 294 |
+
ChannelsLast3d: 3
|
| 295 |
+
PreserveFormat: 4
|
| 296 |
+
Model:
|
| 297 |
+
kind: struct
|
| 298 |
+
fields:
|
| 299 |
+
name:
|
| 300 |
+
type: str
|
| 301 |
+
tensorPaths:
|
| 302 |
+
type: Dict[str, str]
|
| 303 |
+
program:
|
| 304 |
+
type: Program
|
| 305 |
+
delegates:
|
| 306 |
+
type: Dict[str, Program]
|
| 307 |
+
deviceAllocationMap:
|
| 308 |
+
type: Dict[str, str]
|
| 309 |
+
constantPaths:
|
| 310 |
+
type: Dict[str, str]
|
| 311 |
+
ModuleCallEntry:
|
| 312 |
+
kind: struct
|
| 313 |
+
fields:
|
| 314 |
+
fqn:
|
| 315 |
+
type: str
|
| 316 |
+
signature:
|
| 317 |
+
type: Optional[ModuleCallSignature]
|
| 318 |
+
default: None
|
| 319 |
+
ModuleCallSignature:
|
| 320 |
+
kind: struct
|
| 321 |
+
fields:
|
| 322 |
+
inputs:
|
| 323 |
+
type: List[Argument]
|
| 324 |
+
outputs:
|
| 325 |
+
type: List[Argument]
|
| 326 |
+
in_spec:
|
| 327 |
+
type: str
|
| 328 |
+
out_spec:
|
| 329 |
+
type: str
|
| 330 |
+
forward_arg_names:
|
| 331 |
+
type: Optional[List[str]]
|
| 332 |
+
default: None
|
| 333 |
+
NamedArgument:
|
| 334 |
+
kind: struct
|
| 335 |
+
fields:
|
| 336 |
+
name:
|
| 337 |
+
type: str
|
| 338 |
+
arg:
|
| 339 |
+
type: Argument
|
| 340 |
+
kind:
|
| 341 |
+
type: Optional[ArgumentKind]
|
| 342 |
+
default: None
|
| 343 |
+
NamedTupleDef:
|
| 344 |
+
kind: struct
|
| 345 |
+
fields:
|
| 346 |
+
field_names:
|
| 347 |
+
type: List[str]
|
| 348 |
+
Node:
|
| 349 |
+
kind: struct
|
| 350 |
+
fields:
|
| 351 |
+
target:
|
| 352 |
+
type: str
|
| 353 |
+
inputs:
|
| 354 |
+
type: List[NamedArgument]
|
| 355 |
+
outputs:
|
| 356 |
+
type: List[Argument]
|
| 357 |
+
metadata:
|
| 358 |
+
type: Dict[str, str]
|
| 359 |
+
is_hop_single_tensor_return:
|
| 360 |
+
type: Optional[bool]
|
| 361 |
+
default: None
|
| 362 |
+
OptionalTensorArgument:
|
| 363 |
+
kind: union
|
| 364 |
+
fields:
|
| 365 |
+
as_tensor:
|
| 366 |
+
type: TensorArgument
|
| 367 |
+
as_none:
|
| 368 |
+
type: bool
|
| 369 |
+
OutputSpec:
|
| 370 |
+
kind: union
|
| 371 |
+
fields:
|
| 372 |
+
user_output:
|
| 373 |
+
type: UserOutputSpec
|
| 374 |
+
loss_output:
|
| 375 |
+
type: LossOutputSpec
|
| 376 |
+
buffer_mutation:
|
| 377 |
+
type: BufferMutationSpec
|
| 378 |
+
gradient_to_parameter:
|
| 379 |
+
type: GradientToParameterSpec
|
| 380 |
+
gradient_to_user_input:
|
| 381 |
+
type: GradientToUserInputSpec
|
| 382 |
+
user_input_mutation:
|
| 383 |
+
type: UserInputMutationSpec
|
| 384 |
+
token:
|
| 385 |
+
type: OutputTokenSpec
|
| 386 |
+
OutputTokenSpec:
|
| 387 |
+
kind: struct
|
| 388 |
+
fields:
|
| 389 |
+
arg:
|
| 390 |
+
type: TokenArgument
|
| 391 |
+
Program:
|
| 392 |
+
kind: struct
|
| 393 |
+
fields:
|
| 394 |
+
methods:
|
| 395 |
+
type: Dict[str, ExportedProgram]
|
| 396 |
+
RangeConstraint:
|
| 397 |
+
kind: struct
|
| 398 |
+
fields:
|
| 399 |
+
min_val:
|
| 400 |
+
type: Optional[int]
|
| 401 |
+
max_val:
|
| 402 |
+
type: Optional[int]
|
| 403 |
+
ScalarType:
|
| 404 |
+
kind: enum
|
| 405 |
+
fields:
|
| 406 |
+
UNKNOWN: 0
|
| 407 |
+
BYTE: 1
|
| 408 |
+
CHAR: 2
|
| 409 |
+
SHORT: 3
|
| 410 |
+
INT: 4
|
| 411 |
+
LONG: 5
|
| 412 |
+
HALF: 6
|
| 413 |
+
FLOAT: 7
|
| 414 |
+
DOUBLE: 8
|
| 415 |
+
COMPLEXHALF: 9
|
| 416 |
+
COMPLEXFLOAT: 10
|
| 417 |
+
COMPLEXDOUBLE: 11
|
| 418 |
+
BOOL: 12
|
| 419 |
+
BFLOAT16: 13
|
| 420 |
+
UINT16: 28
|
| 421 |
+
FLOAT8E4M3FN: 29
|
| 422 |
+
FLOAT8E5M2: 30
|
| 423 |
+
SchemaVersion:
|
| 424 |
+
kind: struct
|
| 425 |
+
fields:
|
| 426 |
+
major:
|
| 427 |
+
type: int
|
| 428 |
+
minor:
|
| 429 |
+
type: int
|
| 430 |
+
SymBool:
|
| 431 |
+
kind: union
|
| 432 |
+
fields:
|
| 433 |
+
as_expr:
|
| 434 |
+
type: SymExpr
|
| 435 |
+
as_bool:
|
| 436 |
+
type: bool
|
| 437 |
+
SymBoolArgument:
|
| 438 |
+
kind: union
|
| 439 |
+
fields:
|
| 440 |
+
as_name:
|
| 441 |
+
type: str
|
| 442 |
+
as_bool:
|
| 443 |
+
type: bool
|
| 444 |
+
SymExpr:
|
| 445 |
+
kind: struct
|
| 446 |
+
fields:
|
| 447 |
+
expr_str:
|
| 448 |
+
type: str
|
| 449 |
+
hint:
|
| 450 |
+
type: Optional[SymExprHint]
|
| 451 |
+
default: None
|
| 452 |
+
SymExprHint:
|
| 453 |
+
kind: union
|
| 454 |
+
fields:
|
| 455 |
+
as_int:
|
| 456 |
+
type: int
|
| 457 |
+
as_bool:
|
| 458 |
+
type: bool
|
| 459 |
+
as_float:
|
| 460 |
+
type: float
|
| 461 |
+
SymFloat:
|
| 462 |
+
kind: union
|
| 463 |
+
fields:
|
| 464 |
+
as_expr:
|
| 465 |
+
type: SymExpr
|
| 466 |
+
as_float:
|
| 467 |
+
type: float
|
| 468 |
+
SymFloatArgument:
|
| 469 |
+
kind: union
|
| 470 |
+
fields:
|
| 471 |
+
as_name:
|
| 472 |
+
type: str
|
| 473 |
+
as_float:
|
| 474 |
+
type: float
|
| 475 |
+
SymInt:
|
| 476 |
+
kind: union
|
| 477 |
+
fields:
|
| 478 |
+
as_expr:
|
| 479 |
+
type: SymExpr
|
| 480 |
+
as_int:
|
| 481 |
+
type: int
|
| 482 |
+
SymIntArgument:
|
| 483 |
+
kind: union
|
| 484 |
+
fields:
|
| 485 |
+
as_name:
|
| 486 |
+
type: str
|
| 487 |
+
as_int:
|
| 488 |
+
type: int
|
| 489 |
+
TensorArgument:
|
| 490 |
+
kind: struct
|
| 491 |
+
fields:
|
| 492 |
+
name:
|
| 493 |
+
type: str
|
| 494 |
+
TensorMeta:
|
| 495 |
+
kind: struct
|
| 496 |
+
fields:
|
| 497 |
+
dtype:
|
| 498 |
+
type: ScalarType
|
| 499 |
+
sizes:
|
| 500 |
+
type: List[SymInt]
|
| 501 |
+
requires_grad:
|
| 502 |
+
type: bool
|
| 503 |
+
device:
|
| 504 |
+
type: Device
|
| 505 |
+
strides:
|
| 506 |
+
type: List[SymInt]
|
| 507 |
+
storage_offset:
|
| 508 |
+
type: SymInt
|
| 509 |
+
layout:
|
| 510 |
+
type: Layout
|
| 511 |
+
TokenArgument:
|
| 512 |
+
kind: struct
|
| 513 |
+
fields:
|
| 514 |
+
name:
|
| 515 |
+
type: str
|
| 516 |
+
UserInputMutationSpec:
|
| 517 |
+
kind: struct
|
| 518 |
+
fields:
|
| 519 |
+
arg:
|
| 520 |
+
type: TensorArgument
|
| 521 |
+
user_input_name:
|
| 522 |
+
type: str
|
| 523 |
+
UserInputSpec:
|
| 524 |
+
kind: struct
|
| 525 |
+
fields:
|
| 526 |
+
arg:
|
| 527 |
+
type: Argument
|
| 528 |
+
UserOutputSpec:
|
| 529 |
+
kind: struct
|
| 530 |
+
fields:
|
| 531 |
+
arg:
|
| 532 |
+
type: Argument
|
| 533 |
+
SCHEMA_VERSION:
|
| 534 |
+
- 8
|
| 535 |
+
- 8
|
| 536 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import dataclasses
|
| 3 |
+
import hashlib
|
| 4 |
+
import inspect
|
| 5 |
+
import re
|
| 6 |
+
import typing
|
| 7 |
+
from enum import IntEnum
|
| 8 |
+
from typing import Annotated, Any, ForwardRef, Optional, Union
|
| 9 |
+
|
| 10 |
+
from torch._export.serde import schema
|
| 11 |
+
from torch._export.serde.union import _Union
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SchemaUpdateError(Exception):
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _check(x, msg):
|
| 19 |
+
if not x:
|
| 20 |
+
raise SchemaUpdateError(msg)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_CPP_TYPE_MAP = {
|
| 24 |
+
str: "std::string",
|
| 25 |
+
int: "int64_t",
|
| 26 |
+
float: "F64",
|
| 27 |
+
bool: "bool",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
_THRIFT_TYPE_MAP = {
|
| 31 |
+
str: "string",
|
| 32 |
+
int: "i64",
|
| 33 |
+
float: "double",
|
| 34 |
+
bool: "bool",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _staged_schema():
|
| 39 |
+
yaml_ret: dict[str, Any] = {}
|
| 40 |
+
defs = {}
|
| 41 |
+
cpp_enum_defs: dict[str, str] = {}
|
| 42 |
+
cpp_class_defs: dict[str, str] = {}
|
| 43 |
+
cpp_type_decls: list[str] = []
|
| 44 |
+
cpp_json_defs: list[str] = []
|
| 45 |
+
thrift_enum_defs: list[str] = []
|
| 46 |
+
thrift_type_defs: dict[str, str] = {}
|
| 47 |
+
|
| 48 |
+
def _handle_aggregate(ty) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
| 49 |
+
def dump_type(t, level: int) -> tuple[str, str, str]:
|
| 50 |
+
if getattr(t, "__name__", None) in cpp_enum_defs:
|
| 51 |
+
return t.__name__, "int64_t", t.__name__
|
| 52 |
+
elif t in _CPP_TYPE_MAP:
|
| 53 |
+
return (t.__name__, _CPP_TYPE_MAP[t], _THRIFT_TYPE_MAP[t])
|
| 54 |
+
elif isinstance(t, str):
|
| 55 |
+
assert t in defs
|
| 56 |
+
assert t not in cpp_enum_defs
|
| 57 |
+
assert "[" not in t
|
| 58 |
+
return t, f"ForwardRef<{t}>", t
|
| 59 |
+
elif isinstance(t, ForwardRef):
|
| 60 |
+
return (
|
| 61 |
+
t.__forward_arg__,
|
| 62 |
+
f"ForwardRef<{t.__forward_arg__}>",
|
| 63 |
+
t.__forward_arg__,
|
| 64 |
+
)
|
| 65 |
+
elif o := typing.get_origin(t):
|
| 66 |
+
# Lemme know if there's a better way to do this.
|
| 67 |
+
if o == list:
|
| 68 |
+
yaml_head, cpp_head, thrift_head, thrift_tail = (
|
| 69 |
+
"List",
|
| 70 |
+
"std::vector",
|
| 71 |
+
"list<",
|
| 72 |
+
">",
|
| 73 |
+
)
|
| 74 |
+
elif o == dict:
|
| 75 |
+
yaml_head, cpp_head, thrift_head, thrift_tail = (
|
| 76 |
+
"Dict",
|
| 77 |
+
"std::unordered_map",
|
| 78 |
+
"map<",
|
| 79 |
+
">",
|
| 80 |
+
)
|
| 81 |
+
elif o == Union:
|
| 82 |
+
assert level == 0, "Optional is only supported at the top level."
|
| 83 |
+
args = typing.get_args(t)
|
| 84 |
+
assert len(args) == 2 and args[1] == type(None)
|
| 85 |
+
yaml_type, cpp_type, thrift_type = dump_type(args[0], level + 1)
|
| 86 |
+
return (
|
| 87 |
+
f"Optional[{yaml_type}]",
|
| 88 |
+
f"std::optional<{cpp_type}>",
|
| 89 |
+
f"optional {thrift_type}",
|
| 90 |
+
)
|
| 91 |
+
elif o == Annotated:
|
| 92 |
+
return dump_type(t.__origin__, level)
|
| 93 |
+
else:
|
| 94 |
+
raise AssertionError(f"Type {t} is not supported in export schema.")
|
| 95 |
+
yaml_arg_types, cpp_arg_types, thrift_arg_types = zip(
|
| 96 |
+
*[dump_type(x, level + 1) for x in typing.get_args(t)]
|
| 97 |
+
)
|
| 98 |
+
return (
|
| 99 |
+
(f"{yaml_head}[{', '.join(yaml_arg_types)}]"),
|
| 100 |
+
(f"{cpp_head}<{', '.join(cpp_arg_types)}>"),
|
| 101 |
+
f"{thrift_head}{', '.join(thrift_arg_types)}{thrift_tail}",
|
| 102 |
+
)
|
| 103 |
+
elif isinstance(t, type):
|
| 104 |
+
return (t.__name__, t.__name__, t.__name__)
|
| 105 |
+
else:
|
| 106 |
+
raise AssertionError(f"Type {t} is not supported in export schema.")
|
| 107 |
+
|
| 108 |
+
def dump_cpp_value(v) -> str:
|
| 109 |
+
if v is None:
|
| 110 |
+
return "std::nullopt"
|
| 111 |
+
elif v is True:
|
| 112 |
+
return "true"
|
| 113 |
+
elif v is False:
|
| 114 |
+
return "false"
|
| 115 |
+
elif v == {}:
|
| 116 |
+
return "{}"
|
| 117 |
+
elif v == []:
|
| 118 |
+
return "{}"
|
| 119 |
+
elif v == ():
|
| 120 |
+
return "{}"
|
| 121 |
+
elif isinstance(v, str):
|
| 122 |
+
return f'"{v}"'
|
| 123 |
+
else:
|
| 124 |
+
raise AssertionError(
|
| 125 |
+
f"Default value {v} is not supported yet in export schema."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def dump_field(f) -> tuple[dict[str, Any], str, Optional[str], str, int]:
|
| 129 |
+
t, cpp_type, thrift_type = dump_type(f.type, 0)
|
| 130 |
+
ret = {"type": t}
|
| 131 |
+
cpp_default: Optional[str] = None
|
| 132 |
+
assert (
|
| 133 |
+
typing.get_origin(f.type) == Annotated
|
| 134 |
+
), f"Field {f.name} must be annotated with an integer id."
|
| 135 |
+
thrift_id = f.type.__metadata__[0]
|
| 136 |
+
assert (
|
| 137 |
+
type(thrift_id) is int
|
| 138 |
+
), f"Field {f.name} must be annotated with an integer id."
|
| 139 |
+
|
| 140 |
+
value = dataclasses.MISSING
|
| 141 |
+
if f.default is not dataclasses.MISSING:
|
| 142 |
+
value = f.default
|
| 143 |
+
elif f.default_factory is not dataclasses.MISSING:
|
| 144 |
+
value = f.default_factory()
|
| 145 |
+
|
| 146 |
+
if value is not dataclasses.MISSING:
|
| 147 |
+
default = str(value)
|
| 148 |
+
ret["default"] = default
|
| 149 |
+
cpp_default = dump_cpp_value(value)
|
| 150 |
+
|
| 151 |
+
if t.startswith("Optional[") and value is not None:
|
| 152 |
+
raise AssertionError(
|
| 153 |
+
f"Optional field {ty.__name__}.{f.name} must have default value to be None."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
return ret, cpp_type, cpp_default, thrift_type, thrift_id
|
| 157 |
+
|
| 158 |
+
yaml_ret = {}
|
| 159 |
+
cpp_ret = {}
|
| 160 |
+
thrift_ret = {}
|
| 161 |
+
thrift_ids = set()
|
| 162 |
+
for f in dataclasses.fields(ty):
|
| 163 |
+
yaml_res, cpp_type, cpp_default, thrift_type, thrift_id = dump_field(f)
|
| 164 |
+
yaml_ret[f.name] = yaml_res
|
| 165 |
+
cpp_ret[f.name] = {"cpp_type": cpp_type, "cpp_default": cpp_default}
|
| 166 |
+
thrift_ret[f.name] = {"thrift_type": thrift_type, "thrift_id": thrift_id}
|
| 167 |
+
if thrift_id in thrift_ids:
|
| 168 |
+
raise AssertionError(
|
| 169 |
+
f"Duplicate thrift id {thrift_id} for field {f.name} in {ty.__name__}."
|
| 170 |
+
)
|
| 171 |
+
thrift_ids.add(thrift_id)
|
| 172 |
+
return yaml_ret, cpp_ret, thrift_ret
|
| 173 |
+
|
| 174 |
+
def _handle_int_enum(name, ty):
|
| 175 |
+
yaml_ret[name] = {"kind": "enum", "fields": {x.name: x.value for x in ty}}
|
| 176 |
+
cpp_enum_defs[
|
| 177 |
+
name
|
| 178 |
+
] = f"""
|
| 179 |
+
enum class {name} {{
|
| 180 |
+
{chr(10).join([f" {x.name} = {x.value}," for x in ty])}
|
| 181 |
+
}};
|
| 182 |
+
|
| 183 |
+
inline std::string_view printEnum(const {name}& e) {{
|
| 184 |
+
switch (e) {{
|
| 185 |
+
{chr(10).join([f" case {name}::{x.name}: return {chr(34)}{x.name}{chr(34)};" for x in ty])}
|
| 186 |
+
default:
|
| 187 |
+
throw std::runtime_error("Unknown enum value");
|
| 188 |
+
}}
|
| 189 |
+
}}
|
| 190 |
+
|
| 191 |
+
inline void parseEnum(std::string_view s, {name}& t) {{
|
| 192 |
+
{chr(10).join([f" if (s == {chr(34)}{x.name}{chr(34)}) {{ t = {name}::{x.name}; return; }}" for x in ty])}
|
| 193 |
+
throw std::runtime_error("Unknown enum value: " + std::string{{s}});
|
| 194 |
+
}}
|
| 195 |
+
"""
|
| 196 |
+
thrift_enum_defs.append(
|
| 197 |
+
f"""
|
| 198 |
+
enum {name} {{
|
| 199 |
+
{chr(10).join([f" {x.name} = {x.value}," for x in ty])}
|
| 200 |
+
}}
|
| 201 |
+
"""
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
def _handle_struct(name, ty):
|
| 205 |
+
fields, cpp_fields, thrift_fields = _handle_aggregate(ty)
|
| 206 |
+
yaml_ret[name] = {"kind": "struct", "fields": fields}
|
| 207 |
+
field_decls = "\n".join(
|
| 208 |
+
f" {f['cpp_type']} {name}{' = ' + f['cpp_default'] if f['cpp_default'] is not None else ''};"
|
| 209 |
+
for name, f in cpp_fields.items()
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
def accessor(name, ty):
|
| 213 |
+
type_name = fields[name]["type"]
|
| 214 |
+
if type_name in cpp_enum_defs:
|
| 215 |
+
return f"""
|
| 216 |
+
{type_name} get_{name}() const {{
|
| 217 |
+
return static_cast<{type_name}>({name});
|
| 218 |
+
}}
|
| 219 |
+
|
| 220 |
+
void set_{name}({type_name} def) {{
|
| 221 |
+
{name} = static_cast<int64_t>(def);
|
| 222 |
+
}}
|
| 223 |
+
"""
|
| 224 |
+
return f"""
|
| 225 |
+
const {ty}& get_{name}() const {{
|
| 226 |
+
return {name};
|
| 227 |
+
}}
|
| 228 |
+
|
| 229 |
+
void set_{name}({ty} def) {{
|
| 230 |
+
{name} = std::move(def);
|
| 231 |
+
}}
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
to_json_decl = f"void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t)"
|
| 235 |
+
to_json_def = f"""{{
|
| 236 |
+
{chr(10).join([f' nlohmann_json_j["{name}"] = nlohmann_json_t.{name};' for name, f in cpp_fields.items()])}
|
| 237 |
+
}}
|
| 238 |
+
"""
|
| 239 |
+
from_json_decl = f"void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t)"
|
| 240 |
+
|
| 241 |
+
from_json_def = f"""{{
|
| 242 |
+
{name} nlohmann_json_default_obj;
|
| 243 |
+
{chr(10).join(
|
| 244 |
+
[f' nlohmann_json_t.{name} = nlohmann_json_j.value("{name}", nlohmann_json_default_obj.{name});'
|
| 245 |
+
for name, f in cpp_fields.items()])}
|
| 246 |
+
}}
|
| 247 |
+
"""
|
| 248 |
+
cpp_class_defs[
|
| 249 |
+
name
|
| 250 |
+
] = f"""
|
| 251 |
+
class {name} {{
|
| 252 |
+
private:
|
| 253 |
+
{field_decls}
|
| 254 |
+
|
| 255 |
+
public:
|
| 256 |
+
{"".join([accessor(name, f["cpp_type"]) for name, f in cpp_fields.items()])}
|
| 257 |
+
friend {to_json_decl};
|
| 258 |
+
friend {from_json_decl};
|
| 259 |
+
}};
|
| 260 |
+
"""
|
| 261 |
+
cpp_json_defs.append(f"inline {to_json_decl} {to_json_def}")
|
| 262 |
+
cpp_json_defs.append(f"inline {from_json_decl} {from_json_def}")
|
| 263 |
+
cpp_type_decls.append(f"class {name};")
|
| 264 |
+
|
| 265 |
+
thrift_type_defs[
|
| 266 |
+
name
|
| 267 |
+
] = f"""
|
| 268 |
+
struct {name} {{
|
| 269 |
+
{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())}
|
| 270 |
+
}}"""
|
| 271 |
+
|
| 272 |
+
def _handle_union(name, ty):
|
| 273 |
+
fields, cpp_fields, thrift_fields = _handle_aggregate(ty)
|
| 274 |
+
yaml_ret[name] = {"kind": "union", "fields": fields}
|
| 275 |
+
|
| 276 |
+
def accessor(name, ty, idx):
|
| 277 |
+
return f"""
|
| 278 |
+
const {ty}& get_{name}() const {{
|
| 279 |
+
return std::get<{idx + 1}>(variant_);
|
| 280 |
+
}}
|
| 281 |
+
|
| 282 |
+
void set_{name}({ty} def) {{
|
| 283 |
+
variant_.emplace<{idx + 1}>(std::move(def));
|
| 284 |
+
tag_ = Tag::{name.upper()};
|
| 285 |
+
}}
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
to_json_branches = "".join(
|
| 289 |
+
[
|
| 290 |
+
f"""
|
| 291 |
+
if (nlohmann_json_t.tag_ == Tag::{name.upper()}) {{
|
| 292 |
+
nlohmann_json_j["{name}"] = nlohmann_json_t.get_{name}();
|
| 293 |
+
return;
|
| 294 |
+
}}"""
|
| 295 |
+
for idx, (name, f) in enumerate(cpp_fields.items())
|
| 296 |
+
]
|
| 297 |
+
)
|
| 298 |
+
from_json_branches = "".join(
|
| 299 |
+
[
|
| 300 |
+
f"""
|
| 301 |
+
if (nlohmann_json_j.contains("{name}")) {{
|
| 302 |
+
nlohmann_json_t.variant_.emplace<{idx + 1}>(nlohmann_json_j.at("{name}").template get<{f["cpp_type"]}>());
|
| 303 |
+
nlohmann_json_t.tag_ = Tag::{name.upper()};
|
| 304 |
+
return;
|
| 305 |
+
}}"""
|
| 306 |
+
for idx, (name, f) in enumerate(cpp_fields.items())
|
| 307 |
+
]
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
cpp_class_defs[
|
| 311 |
+
name
|
| 312 |
+
] = f"""
|
| 313 |
+
class {name} {{
|
| 314 |
+
struct Void {{}};
|
| 315 |
+
|
| 316 |
+
public:
|
| 317 |
+
enum class Tag {{
|
| 318 |
+
{", ".join([name.upper() for name in cpp_fields])}
|
| 319 |
+
}};
|
| 320 |
+
|
| 321 |
+
private:
|
| 322 |
+
std::variant<Void, {", ".join(f["cpp_type"] for f in cpp_fields.values())}> variant_;
|
| 323 |
+
Tag tag_;
|
| 324 |
+
|
| 325 |
+
public:
|
| 326 |
+
Tag tag() const {{
|
| 327 |
+
return tag_;
|
| 328 |
+
}}
|
| 329 |
+
{"".join([accessor(name, f["cpp_type"], idx) for idx, (name, f) in enumerate(cpp_fields.items())])}
|
| 330 |
+
friend void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t) {{
|
| 331 |
+
{to_json_branches}
|
| 332 |
+
}}
|
| 333 |
+
|
| 334 |
+
friend void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t) {{
|
| 335 |
+
{from_json_branches}
|
| 336 |
+
}}
|
| 337 |
+
}};
|
| 338 |
+
|
| 339 |
+
inline std::string_view printEnum(const {name}::Tag& e) {{
|
| 340 |
+
switch (e) {{
|
| 341 |
+
{chr(10).join([f" case {name}::Tag::{x.upper()}: return {chr(34)}{x.upper()}{chr(34)};" for x in cpp_fields])}
|
| 342 |
+
default:
|
| 343 |
+
throw std::runtime_error("Unknown enum value");
|
| 344 |
+
}}
|
| 345 |
+
}}
|
| 346 |
+
|
| 347 |
+
inline void parseEnum(std::string_view s, {name}::Tag& t) {{
|
| 348 |
+
{chr(10).join([f" if (s == {chr(34)}{x.upper()}{chr(34)}) {{ t = {name}::Tag::{x.upper()}; return; }}" for x in cpp_fields])}
|
| 349 |
+
throw std::runtime_error("Unknown enum value: " + std::string{{s}});
|
| 350 |
+
}}
|
| 351 |
+
|
| 352 |
+
"""
|
| 353 |
+
cpp_type_decls.append(f"class {name};")
|
| 354 |
+
|
| 355 |
+
thrift_type_defs[
|
| 356 |
+
name
|
| 357 |
+
] = f"""
|
| 358 |
+
union {name} {{
|
| 359 |
+
{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())}
|
| 360 |
+
}}"""
|
| 361 |
+
|
| 362 |
+
for name in dir(schema):
|
| 363 |
+
if name.startswith("_"):
|
| 364 |
+
continue
|
| 365 |
+
|
| 366 |
+
value = getattr(schema, name)
|
| 367 |
+
|
| 368 |
+
if hasattr(value, "__module__") and value.__module__ != schema.__name__:
|
| 369 |
+
continue
|
| 370 |
+
|
| 371 |
+
defs[name] = value
|
| 372 |
+
|
| 373 |
+
class_ordering = {}
|
| 374 |
+
for name, value in defs.items():
|
| 375 |
+
if isinstance(value, type):
|
| 376 |
+
if issubclass(value, IntEnum):
|
| 377 |
+
_handle_int_enum(name, value)
|
| 378 |
+
elif dataclasses.is_dataclass(value):
|
| 379 |
+
class_ordering[name] = inspect.findsource(value)[1]
|
| 380 |
+
if issubclass(value, _Union):
|
| 381 |
+
_handle_union(name, value)
|
| 382 |
+
else:
|
| 383 |
+
_handle_struct(name, value)
|
| 384 |
+
else:
|
| 385 |
+
raise AssertionError(f"Unknown schema type {name}: {value}")
|
| 386 |
+
elif isinstance(value, (int, tuple)):
|
| 387 |
+
assert name in ("SCHEMA_VERSION", "TREESPEC_VERSION")
|
| 388 |
+
else:
|
| 389 |
+
raise AssertionError(f"Unknown variable {name}: {value}")
|
| 390 |
+
|
| 391 |
+
yaml_ret["SCHEMA_VERSION"] = list(defs["SCHEMA_VERSION"])
|
| 392 |
+
assert all(x > 0 for x in yaml_ret["SCHEMA_VERSION"])
|
| 393 |
+
yaml_ret["TREESPEC_VERSION"] = defs["TREESPEC_VERSION"]
|
| 394 |
+
assert yaml_ret["TREESPEC_VERSION"] > 0
|
| 395 |
+
|
| 396 |
+
cpp_header = f"""
|
| 397 |
+
#pragma once
|
| 398 |
+
|
| 399 |
+
#include <optional>
|
| 400 |
+
#include <stdexcept>
|
| 401 |
+
#include <string>
|
| 402 |
+
#include <unordered_map>
|
| 403 |
+
#include <variant>
|
| 404 |
+
#include <vector>
|
| 405 |
+
|
| 406 |
+
#include <nlohmann/json.hpp>
|
| 407 |
+
|
| 408 |
+
#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN
|
| 409 |
+
#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {{
|
| 410 |
+
#endif
|
| 411 |
+
|
| 412 |
+
#ifndef NLOHMANN_JSON_NAMESPACE_END
|
| 413 |
+
#define NLOHMANN_JSON_NAMESPACE_END }}
|
| 414 |
+
#endif
|
| 415 |
+
|
| 416 |
+
// https://github.com/nlohmann/json/pull/2117
|
| 417 |
+
NLOHMANN_JSON_NAMESPACE_BEGIN
|
| 418 |
+
template <typename T>
|
| 419 |
+
struct adl_serializer<std::optional<T>> {{
|
| 420 |
+
static void to_json(json& j, const std::optional<T>& opt) {{
|
| 421 |
+
if (opt == std::nullopt) {{
|
| 422 |
+
j = nullptr;
|
| 423 |
+
}} else {{
|
| 424 |
+
j = *opt; // this will call adl_serializer<T>::to_json which will
|
| 425 |
+
// find the free function to_json in T's namespace!
|
| 426 |
+
}}
|
| 427 |
+
}}
|
| 428 |
+
|
| 429 |
+
static void from_json(const json& j, std::optional<T>& opt) {{
|
| 430 |
+
if (j.is_null()) {{
|
| 431 |
+
opt = std::nullopt;
|
| 432 |
+
}} else {{
|
| 433 |
+
opt = j.template get<T>(); // same as above, but with
|
| 434 |
+
// adl_serializer<T>::from_json
|
| 435 |
+
}}
|
| 436 |
+
}}
|
| 437 |
+
}};
|
| 438 |
+
NLOHMANN_JSON_NAMESPACE_END
|
| 439 |
+
|
| 440 |
+
namespace torch {{
|
| 441 |
+
namespace _export {{
|
| 442 |
+
|
| 443 |
+
template <typename T>
|
| 444 |
+
class ForwardRef {{
|
| 445 |
+
static_assert(!std::is_reference_v<T>, "ForwardRef cannot be a reference type");
|
| 446 |
+
|
| 447 |
+
public:
|
| 448 |
+
ForwardRef(): ptr_(std::make_unique<T>()) {{}}
|
| 449 |
+
ForwardRef(ForwardRef<T>&&);
|
| 450 |
+
ForwardRef(const ForwardRef<T>& other): ptr_(std::make_unique<T>(*other.ptr_)) {{}}
|
| 451 |
+
ForwardRef<T>& operator=(ForwardRef<T>&&);
|
| 452 |
+
ForwardRef<T>& operator=(const ForwardRef<T>& other) {{
|
| 453 |
+
ptr_ = std::make_unique<T>(*other.ptr_);
|
| 454 |
+
return *this;
|
| 455 |
+
}}
|
| 456 |
+
const T& operator*() const {{
|
| 457 |
+
return *ptr_;
|
| 458 |
+
}}
|
| 459 |
+
|
| 460 |
+
const T* operator->() const {{
|
| 461 |
+
return ptr_.get();
|
| 462 |
+
}}
|
| 463 |
+
|
| 464 |
+
void emplace(T&& t) {{
|
| 465 |
+
ptr_ = std::make_unique<T>(std::move(t));
|
| 466 |
+
}}
|
| 467 |
+
|
| 468 |
+
private:
|
| 469 |
+
std::unique_ptr<T> ptr_;
|
| 470 |
+
}};
|
| 471 |
+
|
| 472 |
+
template <typename T>
|
| 473 |
+
void to_json(nlohmann::json& j, const ForwardRef<T>& p) {{
|
| 474 |
+
j = *p;
|
| 475 |
+
}}
|
| 476 |
+
|
| 477 |
+
template <typename T>
|
| 478 |
+
void from_json(const nlohmann::json& j, ForwardRef<T>& p) {{
|
| 479 |
+
p.emplace(j.template get<T>());
|
| 480 |
+
}}
|
| 481 |
+
|
| 482 |
+
class F64 {{
|
| 483 |
+
public:
|
| 484 |
+
double get() const {{
|
| 485 |
+
return value_;
|
| 486 |
+
}}
|
| 487 |
+
|
| 488 |
+
void set(double value) {{
|
| 489 |
+
value_ = value;
|
| 490 |
+
}}
|
| 491 |
+
|
| 492 |
+
private:
|
| 493 |
+
double value_;
|
| 494 |
+
}};
|
| 495 |
+
|
| 496 |
+
inline void to_json(nlohmann::json& j, const F64& f) {{
|
| 497 |
+
if (std::isinf(f.get())) {{
|
| 498 |
+
j = "Infinity";
|
| 499 |
+
}} else if (std::isinf(-f.get())) {{
|
| 500 |
+
j = "-Infinity";
|
| 501 |
+
}} else if (std::isnan(f.get())) {{
|
| 502 |
+
j = "NaN";
|
| 503 |
+
}} else {{
|
| 504 |
+
j = f.get();
|
| 505 |
+
}}
|
| 506 |
+
}}
|
| 507 |
+
|
| 508 |
+
inline void from_json(const nlohmann::json& j, F64& f) {{
|
| 509 |
+
if (j == "Infinity") {{
|
| 510 |
+
f.set(std::numeric_limits<double>::infinity());
|
| 511 |
+
}} else if (j == "-Infinity") {{
|
| 512 |
+
f.set(-std::numeric_limits<double>::infinity());
|
| 513 |
+
}} else if (j == "NaN") {{
|
| 514 |
+
f.set(std::numeric_limits<double>::quiet_NaN());
|
| 515 |
+
}} else {{
|
| 516 |
+
f.set(j.get<double>());
|
| 517 |
+
}}
|
| 518 |
+
}}
|
| 519 |
+
|
| 520 |
+
{chr(10).join(cpp_type_decls)}
|
| 521 |
+
{"".join(cpp_enum_defs.values())}
|
| 522 |
+
{"".join(dict(sorted(cpp_class_defs.items(), key=lambda x: class_ordering[x[0]])).values())}
|
| 523 |
+
{chr(10).join(cpp_json_defs)}
|
| 524 |
+
|
| 525 |
+
template <typename T> ForwardRef<T>::ForwardRef(ForwardRef<T>&&) = default;
|
| 526 |
+
template <typename T> ForwardRef<T>& ForwardRef<T>::operator=(ForwardRef<T>&&) = default;
|
| 527 |
+
}} // namespace _export
|
| 528 |
+
}} // namespace torch
|
| 529 |
+
"""
|
| 530 |
+
thrift_schema = f"""
|
| 531 |
+
namespace py3 torch._export
|
| 532 |
+
namespace cpp2 torch._export.schema
|
| 533 |
+
{chr(10).join(thrift_enum_defs)}
|
| 534 |
+
{chr(10).join(dict(sorted(thrift_type_defs.items(), key=lambda x: class_ordering[x[0]])).values())}
|
| 535 |
+
"""
|
| 536 |
+
return yaml_ret, cpp_header, thrift_schema
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _diff_schema(dst, src):
|
| 540 |
+
additions = {key: src[key] for key in src.keys() - dst.keys()}
|
| 541 |
+
subtractions = {key: dst[key] for key in dst.keys() - src.keys()}
|
| 542 |
+
|
| 543 |
+
common_keys = src.keys() & dst.keys()
|
| 544 |
+
|
| 545 |
+
versions = {"SCHEMA_VERSION", "TREESPEC_VERSION"}
|
| 546 |
+
common_keys -= versions
|
| 547 |
+
|
| 548 |
+
for key in common_keys:
|
| 549 |
+
src_kind = src[key]["kind"]
|
| 550 |
+
src_fields = src[key]["fields"]
|
| 551 |
+
dst_kind = dst[key]["kind"]
|
| 552 |
+
dst_fields = dst[key]["fields"]
|
| 553 |
+
_check(
|
| 554 |
+
src_kind == dst_kind,
|
| 555 |
+
f"Type {key} changed kind from {dst_kind} to {src_kind}",
|
| 556 |
+
)
|
| 557 |
+
assert isinstance(src_fields, dict) and isinstance(dst_fields, dict)
|
| 558 |
+
added_fields = {
|
| 559 |
+
key: src_fields[key] for key in src_fields.keys() - dst_fields.keys()
|
| 560 |
+
}
|
| 561 |
+
subtracted_fields = {
|
| 562 |
+
key: dst_fields[key] for key in dst_fields.keys() - src_fields.keys()
|
| 563 |
+
}
|
| 564 |
+
common_fields = src_fields.keys() & dst_fields.keys()
|
| 565 |
+
|
| 566 |
+
for field in common_fields:
|
| 567 |
+
src_field = src_fields[field]
|
| 568 |
+
dst_field = dst_fields[field]
|
| 569 |
+
if src_kind == "struct":
|
| 570 |
+
_check(
|
| 571 |
+
src_field["type"] == dst_field["type"],
|
| 572 |
+
f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}",
|
| 573 |
+
)
|
| 574 |
+
if "default" in src_field and "default" not in dst_field:
|
| 575 |
+
added_fields[field] = {}
|
| 576 |
+
added_fields[field]["default"] = src_field["default"]
|
| 577 |
+
if "default" not in src_field and "default" in dst_field:
|
| 578 |
+
subtracted_fields[field] = {}
|
| 579 |
+
subtracted_fields[field]["default"] = dst_field["default"]
|
| 580 |
+
elif src_kind == "enum":
|
| 581 |
+
_check(
|
| 582 |
+
src_field == dst_field,
|
| 583 |
+
f"Value of the enum field {key}.{field} changed from {dst_field} to {src_field}",
|
| 584 |
+
)
|
| 585 |
+
elif src_kind == "union":
|
| 586 |
+
_check(
|
| 587 |
+
src_field["type"] == dst_field["type"],
|
| 588 |
+
f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}",
|
| 589 |
+
)
|
| 590 |
+
else:
|
| 591 |
+
raise AssertionError(f"Unknown kind {src_kind}: {key}")
|
| 592 |
+
if len(added_fields) > 0:
|
| 593 |
+
assert key not in additions
|
| 594 |
+
additions[key] = {}
|
| 595 |
+
additions[key]["fields"] = added_fields
|
| 596 |
+
if len(subtracted_fields) > 0:
|
| 597 |
+
assert key not in subtractions
|
| 598 |
+
subtractions[key] = {}
|
| 599 |
+
subtractions[key]["fields"] = subtracted_fields
|
| 600 |
+
|
| 601 |
+
return additions, subtractions
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def _hash_content(s: str):
|
| 605 |
+
return hashlib.sha256(s.strip().encode("utf-8")).hexdigest()
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
@dataclasses.dataclass
|
| 609 |
+
class _Commit:
|
| 610 |
+
result: dict[str, Any]
|
| 611 |
+
checksum_next: str
|
| 612 |
+
yaml_path: str
|
| 613 |
+
additions: dict[str, Any]
|
| 614 |
+
subtractions: dict[str, Any]
|
| 615 |
+
base: dict[str, Any]
|
| 616 |
+
checksum_head: Optional[str]
|
| 617 |
+
cpp_header: str
|
| 618 |
+
cpp_header_path: str
|
| 619 |
+
thrift_checksum_head: Optional[str]
|
| 620 |
+
thrift_checksum_real: Optional[str]
|
| 621 |
+
thrift_checksum_next: str
|
| 622 |
+
thrift_schema: str
|
| 623 |
+
thrift_schema_path: str
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def update_schema():
|
| 627 |
+
import importlib.resources
|
| 628 |
+
|
| 629 |
+
if importlib.resources.is_resource(__package__, "schema.yaml"):
|
| 630 |
+
content = importlib.resources.read_text(__package__, "schema.yaml")
|
| 631 |
+
match = re.search("checksum<<([A-Fa-f0-9]{64})>>", content)
|
| 632 |
+
_check(match is not None, "checksum not found in schema.yaml")
|
| 633 |
+
assert match is not None
|
| 634 |
+
checksum_head = match.group(1)
|
| 635 |
+
|
| 636 |
+
thrift_content = importlib.resources.read_text(
|
| 637 |
+
__package__, "export_schema.thrift"
|
| 638 |
+
)
|
| 639 |
+
match = re.search("checksum<<([A-Fa-f0-9]{64})>>", thrift_content)
|
| 640 |
+
_check(match is not None, "checksum not found in export_schema.thrift")
|
| 641 |
+
assert match is not None
|
| 642 |
+
thrift_checksum_head = match.group(1)
|
| 643 |
+
thrift_content = thrift_content.splitlines()
|
| 644 |
+
assert thrift_content[0].startswith("// @" + "generated")
|
| 645 |
+
assert thrift_content[1].startswith("// checksum<<")
|
| 646 |
+
thrift_checksum_real = _hash_content("\n".join(thrift_content[2:]))
|
| 647 |
+
|
| 648 |
+
from yaml import load, Loader
|
| 649 |
+
|
| 650 |
+
dst = load(content, Loader=Loader)
|
| 651 |
+
assert isinstance(dst, dict)
|
| 652 |
+
else:
|
| 653 |
+
checksum_head = None
|
| 654 |
+
thrift_checksum_head = None
|
| 655 |
+
thrift_checksum_real = None
|
| 656 |
+
dst = {"SCHEMA_VERSION": None, "TREESPEC_VERSION": None}
|
| 657 |
+
|
| 658 |
+
src, cpp_header, thrift_schema = _staged_schema()
|
| 659 |
+
additions, subtractions = _diff_schema(dst, src)
|
| 660 |
+
yaml_path = __package__.replace(".", "/") + "/schema.yaml"
|
| 661 |
+
thrift_schema_path = __package__.replace(".", "/") + "/export_schema.thrift"
|
| 662 |
+
torch_prefix = "torch/"
|
| 663 |
+
assert yaml_path.startswith(torch_prefix) # sanity check
|
| 664 |
+
assert thrift_schema_path.startswith(torch_prefix) # sanity check
|
| 665 |
+
|
| 666 |
+
return _Commit(
|
| 667 |
+
result=src,
|
| 668 |
+
checksum_next=_hash_content(repr(src)),
|
| 669 |
+
yaml_path=yaml_path,
|
| 670 |
+
additions=additions,
|
| 671 |
+
subtractions=subtractions,
|
| 672 |
+
base=dst,
|
| 673 |
+
checksum_head=checksum_head,
|
| 674 |
+
cpp_header=cpp_header,
|
| 675 |
+
cpp_header_path=torch_prefix + "csrc/utils/generated_serialization_types.h",
|
| 676 |
+
thrift_checksum_head=thrift_checksum_head,
|
| 677 |
+
thrift_checksum_real=thrift_checksum_real,
|
| 678 |
+
thrift_checksum_next=_hash_content(thrift_schema),
|
| 679 |
+
thrift_schema=thrift_schema,
|
| 680 |
+
thrift_schema_path=thrift_schema_path,
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def check(commit: _Commit, force_unsafe: bool = False):
|
| 685 |
+
next_version = None
|
| 686 |
+
reason = ""
|
| 687 |
+
# Step 1: Detect major schema updates.
|
| 688 |
+
if len(commit.additions) > 0:
|
| 689 |
+
for k, v in commit.additions.items():
|
| 690 |
+
if k not in commit.base:
|
| 691 |
+
continue
|
| 692 |
+
kind = commit.result[k]["kind"]
|
| 693 |
+
fields = v["fields"]
|
| 694 |
+
for f, d in fields.items():
|
| 695 |
+
if kind == "struct" and "default" not in d:
|
| 696 |
+
reason += (
|
| 697 |
+
f"Field {k}.{f} is added to schema.py without a default value as an incomparible change "
|
| 698 |
+
+ "which requires major version bump.\n"
|
| 699 |
+
)
|
| 700 |
+
next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1]
|
| 701 |
+
|
| 702 |
+
if len(commit.subtractions) > 0:
|
| 703 |
+
for k, v in commit.subtractions.items():
|
| 704 |
+
if k not in commit.result:
|
| 705 |
+
continue
|
| 706 |
+
for f in v["fields"]:
|
| 707 |
+
reason = f"Field {k}.{f} is removed from schema.py as an incompatible change which requires major version bump.\n"
|
| 708 |
+
next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1]
|
| 709 |
+
|
| 710 |
+
if force_unsafe:
|
| 711 |
+
reason += "--force-unsafe is used."
|
| 712 |
+
next_version = commit.result["SCHEMA_VERSION"]
|
| 713 |
+
else:
|
| 714 |
+
# Step 2: Detect minor schema updates.
|
| 715 |
+
if next_version is None and len(commit.additions) > 0:
|
| 716 |
+
for k, v in commit.additions.items():
|
| 717 |
+
for f in v["fields"]:
|
| 718 |
+
reason += (
|
| 719 |
+
f"Field {k}.{f} is added to schema.py as an compatible change "
|
| 720 |
+
+ "which still requires minor version bump.\n"
|
| 721 |
+
)
|
| 722 |
+
next_version = [
|
| 723 |
+
commit.base["SCHEMA_VERSION"][0],
|
| 724 |
+
commit.base["SCHEMA_VERSION"][1] + 1,
|
| 725 |
+
]
|
| 726 |
+
if next_version is None and len(commit.subtractions) > 0:
|
| 727 |
+
for k, v in commit.subtractions.items():
|
| 728 |
+
for f in v["fields"]:
|
| 729 |
+
reason += (
|
| 730 |
+
f"Field {k}.{f} is removed from schema.py as an compatible change "
|
| 731 |
+
+ "which still requires minor version bump.\n"
|
| 732 |
+
)
|
| 733 |
+
next_version = [
|
| 734 |
+
commit.base["SCHEMA_VERSION"][0],
|
| 735 |
+
commit.base["SCHEMA_VERSION"][1] + 1,
|
| 736 |
+
]
|
| 737 |
+
|
| 738 |
+
return next_version, reason
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/serialize.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_export/serde/union.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from collections.abc import Hashable
|
| 4 |
+
from dataclasses import fields
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class _UnionTag(str):
|
| 8 |
+
__slots__ = ("_cls",)
|
| 9 |
+
_cls: Hashable
|
| 10 |
+
|
| 11 |
+
@staticmethod
|
| 12 |
+
def create(t, cls):
|
| 13 |
+
tag = _UnionTag(t)
|
| 14 |
+
assert not hasattr(tag, "_cls")
|
| 15 |
+
tag._cls = cls
|
| 16 |
+
return tag
|
| 17 |
+
|
| 18 |
+
def __eq__(self, cmp) -> bool:
|
| 19 |
+
assert isinstance(cmp, str)
|
| 20 |
+
other = str(cmp)
|
| 21 |
+
assert other in _get_field_names(
|
| 22 |
+
self._cls
|
| 23 |
+
), f"{other} is not a valid tag for {self._cls}. Available tags: {_get_field_names(self._cls)}"
|
| 24 |
+
return str(self) == other
|
| 25 |
+
|
| 26 |
+
def __hash__(self):
|
| 27 |
+
return hash(str(self))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@functools.cache
|
| 31 |
+
def _get_field_names(cls) -> set[str]:
|
| 32 |
+
return {f.name for f in fields(cls)}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _Union:
|
| 36 |
+
_type: _UnionTag
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def create(cls, **kwargs):
|
| 40 |
+
assert len(kwargs) == 1
|
| 41 |
+
obj = cls(**{**{f.name: None for f in fields(cls)}, **kwargs}) # type: ignore[arg-type]
|
| 42 |
+
obj._type = _UnionTag.create(next(iter(kwargs.keys())), cls)
|
| 43 |
+
return obj
|
| 44 |
+
|
| 45 |
+
def __post_init__(self):
|
| 46 |
+
assert not any(f.name in ("type", "_type", "create", "value") for f in fields(self)) # type: ignore[arg-type, misc]
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def type(self) -> str:
|
| 50 |
+
try:
|
| 51 |
+
return self._type
|
| 52 |
+
except AttributeError as e:
|
| 53 |
+
raise RuntimeError(
|
| 54 |
+
f"Please use {type(self).__name__}.create to instantiate the union type."
|
| 55 |
+
) from e
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def value(self):
|
| 59 |
+
return getattr(self, self.type)
|
| 60 |
+
|
| 61 |
+
def __getattribute__(self, name):
|
| 62 |
+
attr = super().__getattribute__(name)
|
| 63 |
+
if attr is None and name in _get_field_names(type(self)) and name != self.type: # type: ignore[arg-type]
|
| 64 |
+
raise AttributeError(f"Field {name} is not set.")
|
| 65 |
+
return attr
|
| 66 |
+
|
| 67 |
+
def __str__(self):
|
| 68 |
+
return self.__repr__()
|
| 69 |
+
|
| 70 |
+
def __repr__(self):
|
| 71 |
+
return f"{type(self).__name__}({self.type}={getattr(self, self.type)})"
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__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.
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (216 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-310.pyc
ADDED
|
Binary file (4.12 kB). View file
|
|
|