ai-edge-torch-nightly 0.3.0.dev20250114__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- ai_edge_torch/__init__.py +32 -0
- ai_edge_torch/_config.py +69 -0
- ai_edge_torch/_convert/__init__.py +14 -0
- ai_edge_torch/_convert/conversion.py +153 -0
- ai_edge_torch/_convert/conversion_utils.py +64 -0
- ai_edge_torch/_convert/converter.py +270 -0
- ai_edge_torch/_convert/fx_passes/__init__.py +23 -0
- ai_edge_torch/_convert/fx_passes/build_aten_composite_pass.py +288 -0
- ai_edge_torch/_convert/fx_passes/build_interpolate_composite_pass.py +131 -0
- ai_edge_torch/_convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +258 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +50 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +18 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +68 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +216 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +449 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +303 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/utils.py +64 -0
- ai_edge_torch/_convert/fx_passes/remove_non_user_outputs_pass.py +52 -0
- ai_edge_torch/_convert/signature.py +66 -0
- ai_edge_torch/_convert/test/__init__.py +14 -0
- ai_edge_torch/_convert/test/test_convert.py +558 -0
- ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
- ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
- ai_edge_torch/_convert/test/test_to_channel_last_io.py +96 -0
- ai_edge_torch/_convert/to_channel_last_io.py +92 -0
- ai_edge_torch/conftest.py +20 -0
- ai_edge_torch/debug/__init__.py +17 -0
- ai_edge_torch/debug/culprit.py +496 -0
- ai_edge_torch/debug/test/__init__.py +14 -0
- ai_edge_torch/debug/test/test_culprit.py +140 -0
- ai_edge_torch/debug/test/test_search_model.py +51 -0
- ai_edge_torch/debug/utils.py +59 -0
- ai_edge_torch/experimental/__init__.py +14 -0
- ai_edge_torch/fx_pass_base.py +110 -0
- ai_edge_torch/generative/__init__.py +14 -0
- ai_edge_torch/generative/examples/__init__.py +14 -0
- ai_edge_torch/generative/examples/amd_llama_135m/__init__.py +14 -0
- ai_edge_torch/generative/examples/amd_llama_135m/amd_llama_135m.py +87 -0
- ai_edge_torch/generative/examples/amd_llama_135m/convert_to_tflite.py +70 -0
- ai_edge_torch/generative/examples/amd_llama_135m/verify.py +72 -0
- ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/gemma/gemma1.py +107 -0
- ai_edge_torch/generative/examples/gemma/gemma2.py +295 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma2.py +43 -0
- ai_edge_torch/generative/examples/gemma/verify_util.py +157 -0
- ai_edge_torch/generative/examples/llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/llama/convert_to_tflite.py +91 -0
- ai_edge_torch/generative/examples/llama/llama.py +196 -0
- ai_edge_torch/generative/examples/llama/verify.py +88 -0
- ai_edge_torch/generative/examples/moonshine/__init__.py +14 -0
- ai_edge_torch/generative/examples/moonshine/convert_moonshine_to_tflite.py +50 -0
- ai_edge_torch/generative/examples/moonshine/moonshine.py +103 -0
- ai_edge_torch/generative/examples/openelm/__init__.py +14 -0
- ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/openelm/openelm.py +127 -0
- ai_edge_torch/generative/examples/openelm/verify.py +71 -0
- ai_edge_torch/generative/examples/paligemma/__init__.py +14 -0
- ai_edge_torch/generative/examples/paligemma/convert_to_tflite.py +95 -0
- ai_edge_torch/generative/examples/paligemma/decoder.py +151 -0
- ai_edge_torch/generative/examples/paligemma/decoder2.py +177 -0
- ai_edge_torch/generative/examples/paligemma/image_encoder.py +160 -0
- ai_edge_torch/generative/examples/paligemma/paligemma.py +179 -0
- ai_edge_torch/generative/examples/paligemma/verify.py +161 -0
- ai_edge_torch/generative/examples/paligemma/verify_decoder.py +75 -0
- ai_edge_torch/generative/examples/paligemma/verify_decoder2.py +72 -0
- ai_edge_torch/generative/examples/paligemma/verify_image_encoder.py +99 -0
- ai_edge_torch/generative/examples/phi/__init__.py +14 -0
- ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/phi/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/phi/phi2.py +107 -0
- ai_edge_torch/generative/examples/phi/phi3.py +219 -0
- ai_edge_torch/generative/examples/phi/verify.py +64 -0
- ai_edge_torch/generative/examples/phi/verify_phi3.py +69 -0
- ai_edge_torch/generative/examples/qwen/__init__.py +14 -0
- ai_edge_torch/generative/examples/qwen/convert_to_tflite.py +93 -0
- ai_edge_torch/generative/examples/qwen/qwen.py +134 -0
- ai_edge_torch/generative/examples/qwen/verify.py +88 -0
- ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
- ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/smollm/convert_v2_to_tflite.py +71 -0
- ai_edge_torch/generative/examples/smollm/smollm.py +125 -0
- ai_edge_torch/generative/examples/smollm/verify.py +86 -0
- ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
- ai_edge_torch/generative/examples/stable_diffusion/attention.py +108 -0
- ai_edge_torch/generative/examples/stable_diffusion/clip.py +185 -0
- ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +173 -0
- ai_edge_torch/generative/examples/stable_diffusion/decoder.py +398 -0
- ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +749 -0
- ai_edge_torch/generative/examples/stable_diffusion/encoder.py +119 -0
- ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +254 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +62 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +66 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +74 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +39 -0
- ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +111 -0
- ai_edge_torch/generative/examples/stable_diffusion/util.py +77 -0
- ai_edge_torch/generative/examples/t5/__init__.py +14 -0
- ai_edge_torch/generative/examples/t5/convert_to_tflite.py +138 -0
- ai_edge_torch/generative/examples/t5/t5.py +655 -0
- ai_edge_torch/generative/examples/t5/t5_attention.py +246 -0
- ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
- ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
- ai_edge_torch/generative/examples/test_models/toy_model.py +156 -0
- ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +138 -0
- ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +88 -0
- ai_edge_torch/generative/examples/tiny_llama/verify.py +72 -0
- ai_edge_torch/generative/fx_passes/__init__.py +30 -0
- ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +50 -0
- ai_edge_torch/generative/layers/__init__.py +14 -0
- ai_edge_torch/generative/layers/attention.py +399 -0
- ai_edge_torch/generative/layers/attention_utils.py +210 -0
- ai_edge_torch/generative/layers/builder.py +160 -0
- ai_edge_torch/generative/layers/feed_forward.py +120 -0
- ai_edge_torch/generative/layers/kv_cache.py +204 -0
- ai_edge_torch/generative/layers/lora.py +557 -0
- ai_edge_torch/generative/layers/model_config.py +238 -0
- ai_edge_torch/generative/layers/normalization.py +222 -0
- ai_edge_torch/generative/layers/rotary_position_embedding.py +94 -0
- ai_edge_torch/generative/layers/scaled_dot_product_attention.py +144 -0
- ai_edge_torch/generative/layers/unet/__init__.py +14 -0
- ai_edge_torch/generative/layers/unet/blocks_2d.py +806 -0
- ai_edge_torch/generative/layers/unet/builder.py +50 -0
- ai_edge_torch/generative/layers/unet/model_config.py +282 -0
- ai_edge_torch/generative/quantize/__init__.py +14 -0
- ai_edge_torch/generative/quantize/example.py +47 -0
- ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
- ai_edge_torch/generative/quantize/quant_recipe.py +154 -0
- ai_edge_torch/generative/quantize/quant_recipe_utils.py +62 -0
- ai_edge_torch/generative/quantize/quant_recipes.py +56 -0
- ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
- ai_edge_torch/generative/test/__init__.py +14 -0
- ai_edge_torch/generative/test/test_custom_dus.py +107 -0
- ai_edge_torch/generative/test/test_kv_cache.py +120 -0
- ai_edge_torch/generative/test/test_loader.py +83 -0
- ai_edge_torch/generative/test/test_lora.py +147 -0
- ai_edge_torch/generative/test/test_model_conversion.py +191 -0
- ai_edge_torch/generative/test/test_model_conversion_large.py +362 -0
- ai_edge_torch/generative/test/test_quantize.py +183 -0
- ai_edge_torch/generative/test/utils.py +82 -0
- ai_edge_torch/generative/utilities/__init__.py +15 -0
- ai_edge_torch/generative/utilities/converter.py +215 -0
- ai_edge_torch/generative/utilities/dynamic_update_slice.py +56 -0
- ai_edge_torch/generative/utilities/loader.py +398 -0
- ai_edge_torch/generative/utilities/model_builder.py +180 -0
- ai_edge_torch/generative/utilities/moonshine_loader.py +154 -0
- ai_edge_torch/generative/utilities/stable_diffusion_loader.py +1032 -0
- ai_edge_torch/generative/utilities/t5_loader.py +512 -0
- ai_edge_torch/generative/utilities/transformers_verifier.py +42 -0
- ai_edge_torch/generative/utilities/verifier.py +335 -0
- ai_edge_torch/hlfb/__init__.py +16 -0
- ai_edge_torch/hlfb/mark_pattern/__init__.py +153 -0
- ai_edge_torch/hlfb/mark_pattern/fx_utils.py +69 -0
- ai_edge_torch/hlfb/mark_pattern/pattern.py +288 -0
- ai_edge_torch/hlfb/test/__init__.py +14 -0
- ai_edge_torch/hlfb/test/test_mark_pattern.py +185 -0
- ai_edge_torch/lowertools/__init__.py +18 -0
- ai_edge_torch/lowertools/_shim.py +86 -0
- ai_edge_torch/lowertools/common_utils.py +142 -0
- ai_edge_torch/lowertools/odml_torch_utils.py +260 -0
- ai_edge_torch/lowertools/test_utils.py +62 -0
- ai_edge_torch/lowertools/torch_xla_utils.py +301 -0
- ai_edge_torch/lowertools/translate_recipe.py +163 -0
- ai_edge_torch/model.py +177 -0
- ai_edge_torch/odml_torch/__init__.py +20 -0
- ai_edge_torch/odml_torch/_torch_future.py +88 -0
- ai_edge_torch/odml_torch/_torch_library.py +19 -0
- ai_edge_torch/odml_torch/composite/__init__.py +16 -0
- ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
- ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
- ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
- ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
- ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
- ai_edge_torch/odml_torch/export.py +403 -0
- ai_edge_torch/odml_torch/export_utils.py +157 -0
- ai_edge_torch/odml_torch/jax_bridge/__init__.py +18 -0
- ai_edge_torch/odml_torch/jax_bridge/_wrap.py +180 -0
- ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
- ai_edge_torch/odml_torch/lowerings/__init__.py +27 -0
- ai_edge_torch/odml_torch/lowerings/_basic.py +294 -0
- ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
- ai_edge_torch/odml_torch/lowerings/_convolution.py +243 -0
- ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +285 -0
- ai_edge_torch/odml_torch/lowerings/_layer_norm.py +87 -0
- ai_edge_torch/odml_torch/lowerings/_quantized_decomposed.py +177 -0
- ai_edge_torch/odml_torch/lowerings/_rand.py +142 -0
- ai_edge_torch/odml_torch/lowerings/context.py +42 -0
- ai_edge_torch/odml_torch/lowerings/decomp.py +69 -0
- ai_edge_torch/odml_torch/lowerings/registry.py +65 -0
- ai_edge_torch/odml_torch/lowerings/utils.py +201 -0
- ai_edge_torch/odml_torch/passes/__init__.py +38 -0
- ai_edge_torch/odml_torch/tf_integration.py +156 -0
- ai_edge_torch/quantize/__init__.py +16 -0
- ai_edge_torch/quantize/pt2e_quantizer.py +466 -0
- ai_edge_torch/quantize/pt2e_quantizer_utils.py +1061 -0
- ai_edge_torch/quantize/quant_config.py +85 -0
- ai_edge_torch/testing/__init__.py +14 -0
- ai_edge_torch/testing/model_coverage/__init__.py +16 -0
- ai_edge_torch/testing/model_coverage/model_coverage.py +145 -0
- ai_edge_torch/version.py +16 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/LICENSE +202 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/METADATA +44 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/RECORD +213 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/WHEEL +5 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/top_level.txt +1 -0
@@ -0,0 +1,288 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
from typing import Any, Callable
|
17
|
+
from ai_edge_torch import fx_pass_base
|
18
|
+
from ai_edge_torch import lowertools
|
19
|
+
import torch
|
20
|
+
import torch.utils._pytree as pytree
|
21
|
+
|
22
|
+
_composite_builders: dict[
|
23
|
+
Callable, Callable[[torch.fx.GraphModule, torch.fx.Node], None]
|
24
|
+
] = {}
|
25
|
+
|
26
|
+
|
27
|
+
def _register_composite_builder(op):
|
28
|
+
def inner(func):
|
29
|
+
if isinstance(op, torch._ops.OpOverloadPacket):
|
30
|
+
for overload in op.overloads():
|
31
|
+
_composite_builders[getattr(op, overload)] = func
|
32
|
+
else:
|
33
|
+
_composite_builders[op] = func
|
34
|
+
return func
|
35
|
+
|
36
|
+
return inner
|
37
|
+
|
38
|
+
|
39
|
+
def _tree_map_to_composite_attr_values(
|
40
|
+
values, *, stringify_incompatible_values=True
|
41
|
+
):
|
42
|
+
"""Convert a tree of values to a tree of composite attribute values.
|
43
|
+
|
44
|
+
This is used for pre-processing op attributes before passing them to
|
45
|
+
the composite op as attributes.
|
46
|
+
|
47
|
+
Args:
|
48
|
+
values: A tree of values.
|
49
|
+
stringify_incompatible_values: If True, stringify values that are not
|
50
|
+
compatible with composite attributes.
|
51
|
+
|
52
|
+
Returns:
|
53
|
+
A tree of composite attribute values.
|
54
|
+
"""
|
55
|
+
|
56
|
+
def convert(value):
|
57
|
+
nonlocal stringify_incompatible_values
|
58
|
+
if value is None:
|
59
|
+
return "py_None"
|
60
|
+
if isinstance(value, (str, int, float, bool)):
|
61
|
+
return value
|
62
|
+
|
63
|
+
if stringify_incompatible_values:
|
64
|
+
return str(value)
|
65
|
+
return value
|
66
|
+
|
67
|
+
return pytree.tree_map(convert, values)
|
68
|
+
|
69
|
+
|
70
|
+
class TorchOpArgumentsMapper:
|
71
|
+
"""A helper class to map op arguments to kwargs.
|
72
|
+
|
73
|
+
This is mainly used to extract the default values for op arguments and present
|
74
|
+
all arguments as kwargs.
|
75
|
+
"""
|
76
|
+
|
77
|
+
def __init__(self, op):
|
78
|
+
if isinstance(op, torch._ops.OpOverloadPacket):
|
79
|
+
op = op.default
|
80
|
+
|
81
|
+
assert hasattr(op, "_schema")
|
82
|
+
self.op = op
|
83
|
+
self.arg_specs = [
|
84
|
+
(spec.name, spec.default_value) for spec in op._schema.arguments
|
85
|
+
]
|
86
|
+
|
87
|
+
def get_full_kwargs(self, args, kwargs=None) -> dict[str, Any]:
|
88
|
+
"""Extracts all arguments of the op as kwargs.
|
89
|
+
|
90
|
+
Inspect the op's schema and extract all its args and kwargs into one single
|
91
|
+
kwargs dict, with default values for those unspecified args and kwargs.
|
92
|
+
|
93
|
+
Args:
|
94
|
+
args: The op's arguments.
|
95
|
+
kwargs: The op's kwargs.
|
96
|
+
|
97
|
+
Returns:
|
98
|
+
A kwargs dict with all args and kwargs.
|
99
|
+
"""
|
100
|
+
full_kwargs = {**(kwargs or {})}
|
101
|
+
|
102
|
+
for arg, (name, _) in zip(args, self.arg_specs):
|
103
|
+
full_kwargs[name] = arg
|
104
|
+
|
105
|
+
for name, default_value in self.arg_specs[len(args) :]:
|
106
|
+
if name not in full_kwargs:
|
107
|
+
full_kwargs[name] = default_value
|
108
|
+
|
109
|
+
return full_kwargs
|
110
|
+
|
111
|
+
|
112
|
+
@_register_composite_builder(torch.ops.aten.hardswish.default)
|
113
|
+
def _aten_hardswish(_: torch.fx.GraphModule, node: torch.fx.Node):
|
114
|
+
"""Build a composite for aten.hardswish.default."""
|
115
|
+
op = node.target
|
116
|
+
|
117
|
+
def hardswish(self: torch.Tensor):
|
118
|
+
nonlocal op
|
119
|
+
builder = lowertools.StableHLOCompositeBuilder("aten.hardswish.default")
|
120
|
+
self = builder.mark_inputs(self)
|
121
|
+
output = op(self)
|
122
|
+
output = builder.mark_outputs(output)
|
123
|
+
return output
|
124
|
+
|
125
|
+
node.target = hardswish
|
126
|
+
|
127
|
+
|
128
|
+
@_register_composite_builder(torch.ops.aten.gelu.default)
|
129
|
+
def _aten_gelu(_: torch.fx.GraphModule, node: torch.fx.Node):
|
130
|
+
"""Build a composite for aten.gelu.default."""
|
131
|
+
op = node.target
|
132
|
+
args_mapper = TorchOpArgumentsMapper(op)
|
133
|
+
|
134
|
+
def gelu(*args, **kwargs):
|
135
|
+
nonlocal op, args_mapper
|
136
|
+
|
137
|
+
full_kwargs = args_mapper.get_full_kwargs(args, kwargs)
|
138
|
+
|
139
|
+
# TFLite supports exact and tanh approximate.
|
140
|
+
if (
|
141
|
+
full_kwargs["approximate"] != "none"
|
142
|
+
and full_kwargs["approximate"] != "tanh"
|
143
|
+
):
|
144
|
+
return op(*args, **kwargs)
|
145
|
+
|
146
|
+
builder = lowertools.StableHLOCompositeBuilder(
|
147
|
+
"aten.gelu.default",
|
148
|
+
attr=_tree_map_to_composite_attr_values({
|
149
|
+
"approximate": full_kwargs["approximate"],
|
150
|
+
}),
|
151
|
+
)
|
152
|
+
full_kwargs["self"] = builder.mark_inputs(full_kwargs["self"])
|
153
|
+
output = op(full_kwargs["self"])
|
154
|
+
output = builder.mark_outputs(output)
|
155
|
+
return output
|
156
|
+
|
157
|
+
node.target = gelu
|
158
|
+
|
159
|
+
|
160
|
+
@_register_composite_builder(torch.ops.aten.avg_pool2d.default)
|
161
|
+
def _aten_avg_pool2d(_: torch.fx.GraphModule, node: torch.fx.Node):
|
162
|
+
"""Build a composite for aten.avg_pool2d.default."""
|
163
|
+
op = node.target
|
164
|
+
args_mapper = TorchOpArgumentsMapper(op)
|
165
|
+
|
166
|
+
def avg_pool2d(*args, **kwargs):
|
167
|
+
nonlocal op, args_mapper
|
168
|
+
|
169
|
+
full_kwargs = args_mapper.get_full_kwargs(args, kwargs)
|
170
|
+
|
171
|
+
def is_same_padding(
|
172
|
+
input_shape: list[int],
|
173
|
+
kernel_size: list[int],
|
174
|
+
stride: list[int],
|
175
|
+
padding: list[int],
|
176
|
+
):
|
177
|
+
for dim_input_size, dim_kernel_size, dim_stride, dim_padding in zip(
|
178
|
+
input_shape, kernel_size, stride, padding
|
179
|
+
):
|
180
|
+
dim_output_size = int((dim_input_size + dim_stride - 1) / dim_stride)
|
181
|
+
padding_needed = max(
|
182
|
+
0,
|
183
|
+
(dim_output_size - 1) * dim_stride
|
184
|
+
+ dim_kernel_size
|
185
|
+
- dim_input_size,
|
186
|
+
)
|
187
|
+
if padding_needed % 2 != 0:
|
188
|
+
return False
|
189
|
+
|
190
|
+
if padding_needed // 2 != dim_padding:
|
191
|
+
return False
|
192
|
+
return True
|
193
|
+
|
194
|
+
def is_valid_padding(padding: list[int]):
|
195
|
+
return not any(padding)
|
196
|
+
|
197
|
+
# We prefer to avoid passing empty arrays to composite attributes
|
198
|
+
# as they will be lowered to an ArrayAttr so canonicalizing according
|
199
|
+
# to the default behaviour here.
|
200
|
+
if not full_kwargs["stride"]:
|
201
|
+
full_kwargs["stride"] = full_kwargs["kernel_size"]
|
202
|
+
|
203
|
+
# Only wrap in a composite when the underlying converter can handle it.
|
204
|
+
# TODO We should be able to remove this if the converter can inline composites when it can not handle them.
|
205
|
+
|
206
|
+
# We don't cover any cases where the divisor_override is set.
|
207
|
+
if full_kwargs["divisor_override"] is not None:
|
208
|
+
return op(*args, **kwargs)
|
209
|
+
|
210
|
+
if full_kwargs["ceil_mode"] and not full_kwargs["count_include_pad"]:
|
211
|
+
return op(*args, **kwargs)
|
212
|
+
|
213
|
+
# We also can not cover a case where count_include_pad is False but the padding is custom.
|
214
|
+
if (
|
215
|
+
not full_kwargs["count_include_pad"]
|
216
|
+
and not is_valid_padding(full_kwargs["padding"])
|
217
|
+
and not is_same_padding(
|
218
|
+
list(full_kwargs["self"].shape)[2:],
|
219
|
+
full_kwargs["kernel_size"],
|
220
|
+
full_kwargs["stride"],
|
221
|
+
full_kwargs["padding"],
|
222
|
+
)
|
223
|
+
):
|
224
|
+
return op(*args, **kwargs)
|
225
|
+
|
226
|
+
builder = lowertools.StableHLOCompositeBuilder(
|
227
|
+
"aten.avg_pool2d.default",
|
228
|
+
attr=_tree_map_to_composite_attr_values({
|
229
|
+
"kernel_size": full_kwargs["kernel_size"],
|
230
|
+
"stride": full_kwargs["stride"],
|
231
|
+
"padding": full_kwargs["padding"],
|
232
|
+
"ceil_mode": full_kwargs["ceil_mode"],
|
233
|
+
"count_include_pad": full_kwargs["count_include_pad"],
|
234
|
+
"divisor_override": full_kwargs["divisor_override"],
|
235
|
+
}),
|
236
|
+
)
|
237
|
+
|
238
|
+
full_kwargs["self"] = builder.mark_inputs(full_kwargs["self"])
|
239
|
+
output = op(**full_kwargs)
|
240
|
+
output = builder.mark_outputs(output)
|
241
|
+
return output
|
242
|
+
|
243
|
+
node.target = avg_pool2d
|
244
|
+
|
245
|
+
|
246
|
+
@_register_composite_builder(torch.ops.aten.embedding.default)
|
247
|
+
def _aten_embedding(gm: torch.fx.GraphModule, node: torch.fx.Node):
|
248
|
+
op = node.target
|
249
|
+
args_mapper = TorchOpArgumentsMapper(op)
|
250
|
+
|
251
|
+
def embedding(*args, **kwargs):
|
252
|
+
nonlocal op, args_mapper
|
253
|
+
full_kwargs = args_mapper.get_full_kwargs(args, kwargs)
|
254
|
+
_, embedding_dim = full_kwargs["weight"].size()
|
255
|
+
idx = full_kwargs["indices"]
|
256
|
+
|
257
|
+
# Explicitly cast to INT32. This places the CastOp outside of the HLFB.
|
258
|
+
idx = idx.type(torch.int)
|
259
|
+
original_idx_shape = idx.size()
|
260
|
+
|
261
|
+
# Explicitly reshape to 1D. This places the ReshapeOp outside of the HLFB.
|
262
|
+
idx = torch.reshape(idx, (idx.numel(),))
|
263
|
+
|
264
|
+
builder = lowertools.StableHLOCompositeBuilder("odml.embedding_lookup")
|
265
|
+
full_kwargs["indices"], full_kwargs["weight"] = builder.mark_inputs(
|
266
|
+
idx,
|
267
|
+
full_kwargs["weight"],
|
268
|
+
)
|
269
|
+
output = op(**full_kwargs)
|
270
|
+
output = builder.mark_outputs(output)
|
271
|
+
|
272
|
+
# Explicitly reshape back to the original shape. This places the ReshapeOp outside of the HLFB.
|
273
|
+
output = torch.reshape(output, (*(original_idx_shape), embedding_dim))
|
274
|
+
return output
|
275
|
+
|
276
|
+
node.target = embedding
|
277
|
+
|
278
|
+
|
279
|
+
class BuildAtenCompositePass(fx_pass_base.PassBase):
|
280
|
+
|
281
|
+
def call(self, graph_module: torch.fx.GraphModule):
|
282
|
+
for node in graph_module.graph.nodes:
|
283
|
+
if node.target in _composite_builders:
|
284
|
+
_composite_builders[node.target](graph_module, node)
|
285
|
+
|
286
|
+
graph_module.graph.lint()
|
287
|
+
graph_module.recompile()
|
288
|
+
return fx_pass_base.PassResult(graph_module, True)
|
@@ -0,0 +1,131 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
"""Build interpolate composite pass."""
|
16
|
+
|
17
|
+
import functools
|
18
|
+
|
19
|
+
from ai_edge_torch import fx_pass_base
|
20
|
+
from ai_edge_torch.hlfb import mark_pattern
|
21
|
+
from ai_edge_torch.hlfb.mark_pattern import pattern as pattern_module
|
22
|
+
import torch
|
23
|
+
|
24
|
+
# For torch nightly released after mid June 2024,
|
25
|
+
# torch.nn.functional.interpolate no longer gets exported into decomposed graph
|
26
|
+
# but a single aten op:
|
27
|
+
# torch.ops.aten.upsample_nearest2d.vec/torch.ops.aten.upsample_bilinear2d.vec.
|
28
|
+
# This would interefere with our pattern matching based composite builder.
|
29
|
+
# Here we register the now missing decompositions first.
|
30
|
+
_INTERPOLATE_DECOMPOSITIONS = torch._decomp.get_decompositions([
|
31
|
+
torch.ops.aten.upsample_bilinear2d.vec,
|
32
|
+
torch.ops.aten.upsample_nearest2d.vec,
|
33
|
+
])
|
34
|
+
|
35
|
+
|
36
|
+
@functools.cache
|
37
|
+
def _get_upsample_bilinear2d_pattern():
|
38
|
+
pattern = pattern_module.Pattern(
|
39
|
+
"odml.upsample_bilinear2d",
|
40
|
+
lambda x: torch.nn.functional.interpolate(
|
41
|
+
x, scale_factor=2, mode="bilinear", align_corners=False
|
42
|
+
),
|
43
|
+
export_args=(torch.rand(1, 3, 100, 100),),
|
44
|
+
decomp_table=_INTERPOLATE_DECOMPOSITIONS,
|
45
|
+
)
|
46
|
+
|
47
|
+
@pattern.register_attr_builder
|
48
|
+
def attr_builder(pattern, graph_module, internal_match):
|
49
|
+
output = internal_match.returning_nodes[0]
|
50
|
+
output_h, output_w = output.meta["val"].shape[-2:]
|
51
|
+
return {
|
52
|
+
"size": (int(output_h), int(output_w)),
|
53
|
+
"align_corners": False,
|
54
|
+
"is_nchw_op": True,
|
55
|
+
}
|
56
|
+
|
57
|
+
return pattern
|
58
|
+
|
59
|
+
|
60
|
+
@functools.cache
|
61
|
+
def _get_upsample_bilinear2d_align_corners_pattern():
|
62
|
+
pattern = pattern_module.Pattern(
|
63
|
+
"odml.upsample_bilinear2d",
|
64
|
+
lambda x: torch.nn.functional.interpolate(
|
65
|
+
x, scale_factor=2, mode="bilinear", align_corners=True
|
66
|
+
),
|
67
|
+
export_args=(torch.rand(1, 3, 100, 100),),
|
68
|
+
decomp_table=_INTERPOLATE_DECOMPOSITIONS,
|
69
|
+
)
|
70
|
+
|
71
|
+
@pattern.register_attr_builder
|
72
|
+
def attr_builder(graph_module, pattern, internal_match):
|
73
|
+
output = internal_match.returning_nodes[0]
|
74
|
+
output_h, output_w = output.meta["val"].shape[-2:]
|
75
|
+
return {
|
76
|
+
"size": (int(output_h), int(output_w)),
|
77
|
+
"align_corners": True,
|
78
|
+
"is_nchw_op": True,
|
79
|
+
}
|
80
|
+
|
81
|
+
return pattern
|
82
|
+
|
83
|
+
|
84
|
+
@functools.cache
|
85
|
+
def _get_interpolate_nearest2d_pattern():
|
86
|
+
pattern = pattern_module.Pattern(
|
87
|
+
"tfl.resize_nearest_neighbor",
|
88
|
+
lambda x: torch.nn.functional.interpolate(
|
89
|
+
x, scale_factor=2, mode="nearest"
|
90
|
+
),
|
91
|
+
export_args=(torch.rand(1, 3, 100, 100),),
|
92
|
+
decomp_table=_INTERPOLATE_DECOMPOSITIONS,
|
93
|
+
)
|
94
|
+
|
95
|
+
@pattern.register_attr_builder
|
96
|
+
def attr_builder(pattern, graph_module, internal_match):
|
97
|
+
output = internal_match.returning_nodes[0]
|
98
|
+
output_h, output_w = output.meta["val"].shape[-2:]
|
99
|
+
return {
|
100
|
+
"size": (int(output_h), int(output_w)),
|
101
|
+
"is_nchw_op": True,
|
102
|
+
}
|
103
|
+
|
104
|
+
return pattern
|
105
|
+
|
106
|
+
|
107
|
+
class BuildInterpolateCompositePass(fx_pass_base.ExportedProgramPassBase):
|
108
|
+
|
109
|
+
def __init__(self):
|
110
|
+
super().__init__()
|
111
|
+
self._patterns = [
|
112
|
+
_get_upsample_bilinear2d_pattern(),
|
113
|
+
_get_upsample_bilinear2d_align_corners_pattern(),
|
114
|
+
_get_interpolate_nearest2d_pattern(),
|
115
|
+
]
|
116
|
+
|
117
|
+
def call(self, exported_program: torch.export.ExportedProgram):
|
118
|
+
exported_program = fx_pass_base.run_passes(
|
119
|
+
exported_program, [fx_pass_base.CanonicalizePass()]
|
120
|
+
)
|
121
|
+
exported_program = exported_program.run_decompositions(
|
122
|
+
_INTERPOLATE_DECOMPOSITIONS
|
123
|
+
)
|
124
|
+
|
125
|
+
graph_module = exported_program.graph_module
|
126
|
+
for pattern in self._patterns:
|
127
|
+
graph_module = mark_pattern.mark_pattern(graph_module, pattern)
|
128
|
+
|
129
|
+
graph_module.graph.lint()
|
130
|
+
graph_module.recompile()
|
131
|
+
return fx_pass_base.ExportedProgramPassResult(exported_program, True)
|
@@ -0,0 +1,73 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
from ai_edge_torch import fx_pass_base
|
17
|
+
from ai_edge_torch import lowertools
|
18
|
+
import torch
|
19
|
+
import torch.utils._pytree as pytree
|
20
|
+
|
21
|
+
|
22
|
+
def _get_mlir_debuginfo(node: torch.fx.Node):
|
23
|
+
def class_fullname(cls):
|
24
|
+
module = cls.__module__
|
25
|
+
if module == "builtins":
|
26
|
+
return cls.__qualname__
|
27
|
+
return module + "." + cls.__qualname__
|
28
|
+
|
29
|
+
def get_hierarchy(node: torch.fx.Node):
|
30
|
+
nn_module_stack = node.meta.get("nn_module_stack", {})
|
31
|
+
layers = []
|
32
|
+
for name, layer in nn_module_stack.values():
|
33
|
+
iid = ("_" + name.split(".")[-1]) if name else ""
|
34
|
+
layer_str = layer if isinstance(layer, str) else class_fullname(layer)
|
35
|
+
layers.append(layer_str + iid)
|
36
|
+
|
37
|
+
hierachy_str = "/".join(layers) + ";"
|
38
|
+
return hierachy_str
|
39
|
+
|
40
|
+
# TODO(yijieyang): Encode aten op and attrs.
|
41
|
+
return get_hierarchy(node)
|
42
|
+
|
43
|
+
|
44
|
+
def _wrap_call_function_node_with_debuginfo_writer(node: torch.fx.GraphModule):
|
45
|
+
if not node.op.startswith("call_function"):
|
46
|
+
return
|
47
|
+
|
48
|
+
target = node.target
|
49
|
+
debuginfo = _get_mlir_debuginfo(node)
|
50
|
+
|
51
|
+
def debuginfo_writer(*args, **kwargs):
|
52
|
+
nonlocal target, debuginfo
|
53
|
+
outputs = target(*args, **kwargs)
|
54
|
+
outputs = pytree.tree_map_only(
|
55
|
+
torch.Tensor,
|
56
|
+
lambda x: lowertools.write_mlir_debuginfo_op(x, debuginfo),
|
57
|
+
outputs,
|
58
|
+
)
|
59
|
+
return outputs
|
60
|
+
|
61
|
+
node.target = debuginfo_writer
|
62
|
+
|
63
|
+
|
64
|
+
class InjectMlirDebuginfoPass(fx_pass_base.PassBase):
|
65
|
+
"""DEPRECATED: Debuginfo is injected automatically by odml_torch."""
|
66
|
+
|
67
|
+
def call(self, graph_module: torch.fx.GraphModule):
|
68
|
+
for node in graph_module.graph.nodes:
|
69
|
+
_wrap_call_function_node_with_debuginfo_writer(node)
|
70
|
+
|
71
|
+
graph_module.graph.lint()
|
72
|
+
graph_module.recompile()
|
73
|
+
return fx_pass_base.PassResult(graph_module, True)
|
@@ -0,0 +1,16 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass.pass_body import OptimizeLayoutTransposesPass # NOQA
|