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,303 @@
|
|
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
|
+
"""Optimize layout transposes pass."""
|
16
|
+
|
17
|
+
import operator
|
18
|
+
import os
|
19
|
+
from typing import Union
|
20
|
+
|
21
|
+
from ai_edge_torch import fx_pass_base
|
22
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import layout_check # NOQA
|
23
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import layout_mark # NOQA
|
24
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import layout_partitioners # NOQA
|
25
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import layout_rewrite # NOQA
|
26
|
+
from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import utils # NOQA
|
27
|
+
import torch
|
28
|
+
import torch.ao.quantization.quantize_pt2e
|
29
|
+
|
30
|
+
TransposeFunc = Union[utils.tensor_to_nchw, utils.tensor_to_nhwc]
|
31
|
+
|
32
|
+
|
33
|
+
class OptimizeLayoutTransposesPass(fx_pass_base.ExportedProgramPassBase):
|
34
|
+
|
35
|
+
def get_source_meta(self, node: torch.fx.Node):
|
36
|
+
keys = ["stack_trace", "nn_module_stack", "source_fn_stack", "from_node"]
|
37
|
+
meta = {}
|
38
|
+
for key in keys:
|
39
|
+
if key in node.meta:
|
40
|
+
meta[key] = node.meta[key]
|
41
|
+
return meta
|
42
|
+
|
43
|
+
def insert_t_q_dq(
|
44
|
+
self,
|
45
|
+
graph: torch.fx.Graph,
|
46
|
+
input_dq: torch.fx.Node,
|
47
|
+
target: torch.fx.Node,
|
48
|
+
transpose_func: TransposeFunc,
|
49
|
+
transpose_node_meta: dict,
|
50
|
+
) -> list[torch.fx.Node]:
|
51
|
+
"""original:
|
52
|
+
|
53
|
+
input_dq -> target
|
54
|
+
insert the node as:
|
55
|
+
input_dq -> (T q dq) -> target
|
56
|
+
"""
|
57
|
+
assert utils.is_dq_node(input_dq)
|
58
|
+
|
59
|
+
q_args = input_dq.args[1:]
|
60
|
+
q_kwargs = input_dq.kwargs
|
61
|
+
q_op, dq_op = utils.get_paired_q_dq_ops(input_dq.target)
|
62
|
+
with graph.inserting_before(target):
|
63
|
+
t = graph.call_function(transpose_func, (input_dq,))
|
64
|
+
# Q and DQ inserted here may required updating the `axis` arg when they
|
65
|
+
# are per_channel ops. However, instead of updating here, the nodes would
|
66
|
+
# be marked as NHWC/NCHW and applied rewriters after partitioning.
|
67
|
+
q = graph.call_function(q_op, (t,) + q_args, q_kwargs)
|
68
|
+
dq = graph.call_function(dq_op, (q,) + q_args, q_kwargs)
|
69
|
+
|
70
|
+
input_dq.meta = transpose_node_meta
|
71
|
+
t.meta = transpose_node_meta
|
72
|
+
q.meta = transpose_node_meta
|
73
|
+
dq.meta = self.get_source_meta(target)
|
74
|
+
|
75
|
+
target.replace_input_with(input_dq, dq)
|
76
|
+
return [t, q, dq]
|
77
|
+
|
78
|
+
def insert_dq_t_q(
|
79
|
+
self,
|
80
|
+
graph: torch.fx.Graph,
|
81
|
+
input_q: torch.fx.Node,
|
82
|
+
target: torch.fx.Node,
|
83
|
+
transpose_func: TransposeFunc,
|
84
|
+
transpose_node_meta: dict,
|
85
|
+
) -> list[torch.fx.Node]:
|
86
|
+
"""original:
|
87
|
+
|
88
|
+
input_q -> target
|
89
|
+
insert the node as:
|
90
|
+
input_q -> (dq T q) -> target
|
91
|
+
"""
|
92
|
+
assert utils.is_q_node(input_q)
|
93
|
+
|
94
|
+
q_args = input_q.args[1:]
|
95
|
+
q_kwargs = input_q.kwargs
|
96
|
+
q_op, dq_op = utils.get_paired_q_dq_ops(input_q.target)
|
97
|
+
with graph.inserting_before(target):
|
98
|
+
# Q and DQ inserted here may required updating the `axis` arg when they
|
99
|
+
# are per_channel ops. However, instead of updating here, the nodes would
|
100
|
+
# be marked as NHWC/NCHW and applied rewriters after partitioning.
|
101
|
+
dq = graph.call_function(dq_op, (input_q,) + q_args, q_kwargs)
|
102
|
+
t = graph.call_function(transpose_func, (dq,))
|
103
|
+
q = graph.call_function(q_op, (t,) + q_args, q_kwargs)
|
104
|
+
|
105
|
+
dq.meta = transpose_node_meta
|
106
|
+
t.meta = transpose_node_meta
|
107
|
+
q.meta = transpose_node_meta
|
108
|
+
|
109
|
+
target.replace_input_with(input_q, q)
|
110
|
+
return [dq, t, q]
|
111
|
+
|
112
|
+
def insert_layout_transpose(
|
113
|
+
self,
|
114
|
+
graph: torch.fx.Graph,
|
115
|
+
input_node: torch.fx.Node,
|
116
|
+
target_node: torch.fx.Node,
|
117
|
+
transpose_func: TransposeFunc,
|
118
|
+
transpose_node_meta: dict,
|
119
|
+
) -> None:
|
120
|
+
assert transpose_func in (utils.tensor_to_nchw, utils.tensor_to_nhwc)
|
121
|
+
|
122
|
+
# new_nodes only contains Q/DQ/Transpose nodes, which are all SISO.
|
123
|
+
# Insertion order input nodes -> output nodes
|
124
|
+
new_nodes = []
|
125
|
+
|
126
|
+
# Constraint Q2: the NHWC partition's entry and exit must not be output
|
127
|
+
# edges of Q/DQ ops that are connected to a constant/weight tensor.
|
128
|
+
while layout_mark.is_const_node(input_node) and (
|
129
|
+
utils.is_dq_node(input_node) or utils.is_q_node(input_node)
|
130
|
+
):
|
131
|
+
with graph.inserting_before(target_node):
|
132
|
+
new_input_node = graph.node_copy(input_node)
|
133
|
+
|
134
|
+
target_node.replace_input_with(input_node, new_input_node)
|
135
|
+
|
136
|
+
new_nodes = [new_input_node] + new_nodes
|
137
|
+
input_node, target_node = new_input_node.args[0], new_input_node
|
138
|
+
|
139
|
+
if utils.is_q_node(input_node):
|
140
|
+
# Constraint Q3: when the entry and exit is right after a q op (occur after a (dq-op-q)
|
141
|
+
# triplet), the transpose must be added as a quantized transpose in (dq-T-q)
|
142
|
+
# input_q -> (dq T q) -> target
|
143
|
+
new_nodes = (
|
144
|
+
self.insert_dq_t_q(
|
145
|
+
graph,
|
146
|
+
input_node,
|
147
|
+
target_node,
|
148
|
+
transpose_func,
|
149
|
+
transpose_node_meta,
|
150
|
+
)
|
151
|
+
+ new_nodes
|
152
|
+
)
|
153
|
+
elif utils.is_dq_node(input_node):
|
154
|
+
# Constraint Q1: the NHWC partition's entry and exit cannot be edges
|
155
|
+
# within (dq-op-q) triplet.
|
156
|
+
# input_dq -> (T q dq) -> target
|
157
|
+
new_nodes = (
|
158
|
+
self.insert_t_q_dq(
|
159
|
+
graph,
|
160
|
+
input_node,
|
161
|
+
target_node,
|
162
|
+
transpose_func,
|
163
|
+
transpose_node_meta,
|
164
|
+
)
|
165
|
+
+ new_nodes
|
166
|
+
)
|
167
|
+
else:
|
168
|
+
# input -> target
|
169
|
+
with graph.inserting_before(target_node):
|
170
|
+
t = graph.call_function(transpose_func, (input_node,))
|
171
|
+
t.meta = transpose_node_meta
|
172
|
+
target_node.replace_input_with(input_node, t)
|
173
|
+
new_nodes = [t] + new_nodes
|
174
|
+
|
175
|
+
# Mark new nodes as NCHW or NHWC
|
176
|
+
# For all nodes before the transpose, mark it as input_marker
|
177
|
+
# For all nodes after the transpose (incl. transpose), mark it as output_marker
|
178
|
+
if transpose_func == utils.tensor_to_nchw:
|
179
|
+
input_marker, target_marker = (
|
180
|
+
layout_mark.mark_as_nhwc_node,
|
181
|
+
layout_mark.mark_as_nchw_node,
|
182
|
+
)
|
183
|
+
else:
|
184
|
+
input_marker, target_marker = (
|
185
|
+
layout_mark.mark_as_nchw_node,
|
186
|
+
layout_mark.mark_as_nhwc_node,
|
187
|
+
)
|
188
|
+
|
189
|
+
marker = input_marker
|
190
|
+
for node in new_nodes:
|
191
|
+
if node.target == transpose_func:
|
192
|
+
marker = target_marker
|
193
|
+
marker(node)
|
194
|
+
assert marker == target_marker
|
195
|
+
|
196
|
+
def input_to_nhwc(
|
197
|
+
self,
|
198
|
+
graph: torch.fx.Graph,
|
199
|
+
input_node: torch.fx.Node,
|
200
|
+
target_node: torch.fx.Node,
|
201
|
+
) -> None:
|
202
|
+
if layout_mark.is_nhwc_node(input_node):
|
203
|
+
return
|
204
|
+
|
205
|
+
if not layout_check.is_4d(input_node):
|
206
|
+
raise AssertionError(
|
207
|
+
"Attempting to convert non-NHWC compatible node to NHWC:"
|
208
|
+
f" {input_node}"
|
209
|
+
)
|
210
|
+
|
211
|
+
# Assign target node's source meta to the to_NHWC node, because the transpose
|
212
|
+
# is added for the existence of target node.
|
213
|
+
self.insert_layout_transpose(
|
214
|
+
graph,
|
215
|
+
input_node,
|
216
|
+
target_node,
|
217
|
+
utils.tensor_to_nhwc,
|
218
|
+
self.get_source_meta(target_node),
|
219
|
+
)
|
220
|
+
|
221
|
+
def input_to_nchw(
|
222
|
+
self,
|
223
|
+
graph: torch.fx.Graph,
|
224
|
+
input_node: torch.fx.Node,
|
225
|
+
target_node: torch.fx.Node,
|
226
|
+
) -> None:
|
227
|
+
if layout_mark.is_nchw_node(input_node):
|
228
|
+
return
|
229
|
+
|
230
|
+
self.insert_layout_transpose(
|
231
|
+
graph,
|
232
|
+
input_node,
|
233
|
+
target_node,
|
234
|
+
utils.tensor_to_nchw,
|
235
|
+
self.get_source_meta(input_node),
|
236
|
+
)
|
237
|
+
|
238
|
+
def mark_const_nodes(self, exported_program: torch.export.ExportedProgram):
|
239
|
+
graph_module = exported_program.graph_module
|
240
|
+
graph = graph_module.graph
|
241
|
+
|
242
|
+
input_specs = exported_program.graph_signature.input_specs
|
243
|
+
non_user_input_names = set()
|
244
|
+
for spec in input_specs:
|
245
|
+
if spec.kind != torch.export.graph_signature.InputKind.USER_INPUT:
|
246
|
+
non_user_input_names.add(spec.arg.name)
|
247
|
+
|
248
|
+
for node in graph.nodes:
|
249
|
+
has_input_nodes = len(node.all_input_nodes) > 0
|
250
|
+
all_inputs_are_const = all(
|
251
|
+
map(layout_mark.is_const_node, node.all_input_nodes)
|
252
|
+
)
|
253
|
+
if (
|
254
|
+
node.name in non_user_input_names
|
255
|
+
or (has_input_nodes and all_inputs_are_const)
|
256
|
+
or (node.op != "placeholder" and not has_input_nodes)
|
257
|
+
):
|
258
|
+
layout_mark.mark_as_const_node(node)
|
259
|
+
|
260
|
+
def call(self, exported_program: torch.export.ExportedProgram):
|
261
|
+
self.mark_const_nodes(exported_program)
|
262
|
+
|
263
|
+
graph_module = exported_program.graph_module
|
264
|
+
partitioner = os.environ.get(
|
265
|
+
"AIEDGETORCH_LAYOUT_OPTIMIZE_PARTITIONER", None
|
266
|
+
)
|
267
|
+
if partitioner == "MINCUT":
|
268
|
+
graph_module = layout_partitioners.min_cut.partition(graph_module)
|
269
|
+
elif partitioner == "GREEDY":
|
270
|
+
graph_module = layout_partitioners.greedy.partition(graph_module)
|
271
|
+
else:
|
272
|
+
# By default use min cut partitioner if possible
|
273
|
+
if layout_partitioners.min_cut.can_partition(graph_module):
|
274
|
+
graph_module = layout_partitioners.min_cut.partition(graph_module)
|
275
|
+
else:
|
276
|
+
graph_module = layout_partitioners.greedy.partition(graph_module)
|
277
|
+
|
278
|
+
graph = graph_module.graph
|
279
|
+
for node in list(graph.nodes):
|
280
|
+
if node.target == operator.getitem:
|
281
|
+
# force the layout mark of a getitem node to follow its producer.
|
282
|
+
if layout_mark.is_nchw_node(node.args[0]):
|
283
|
+
layout_mark.mark_as_nchw_node(node)
|
284
|
+
else:
|
285
|
+
layout_mark.mark_as_nhwc_node(node)
|
286
|
+
|
287
|
+
for node in list(graph.nodes):
|
288
|
+
if layout_mark.is_nhwc_node(node):
|
289
|
+
for input_node in layout_check.get_layout_sensitive_inputs(node):
|
290
|
+
self.input_to_nhwc(graph, input_node, node)
|
291
|
+
layout_rewrite.rewrite_nhwc_node(node)
|
292
|
+
else:
|
293
|
+
for input_node in layout_check.get_layout_sensitive_inputs(node):
|
294
|
+
# Note: for non-4D tensors input_to_nchw is always noop.
|
295
|
+
self.input_to_nchw(graph, input_node, node)
|
296
|
+
|
297
|
+
graph_module.graph.eliminate_dead_code()
|
298
|
+
graph_module.recompile()
|
299
|
+
graph_module.graph.lint()
|
300
|
+
# Mark const node again for debugging
|
301
|
+
self.mark_const_nodes(exported_program)
|
302
|
+
|
303
|
+
return fx_pass_base.ExportedProgramPassResult(exported_program, True)
|
@@ -0,0 +1,64 @@
|
|
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
|
+
"""Utils for the optimized layout transposes pass."""
|
16
|
+
|
17
|
+
from typing import Callable
|
18
|
+
|
19
|
+
import torch
|
20
|
+
import torch.ao.quantization.quantize_pt2e
|
21
|
+
|
22
|
+
|
23
|
+
def tensor_to_nhwc(t: torch.Tensor):
|
24
|
+
return torch.ops.aten.permute(t.contiguous(), [0, 2, 3, 1]).contiguous()
|
25
|
+
|
26
|
+
|
27
|
+
def tensor_to_nchw(t: torch.Tensor):
|
28
|
+
return torch.ops.aten.permute(t.contiguous(), [0, 3, 1, 2]).contiguous()
|
29
|
+
|
30
|
+
|
31
|
+
def flatten_torch_op_overloads(op):
|
32
|
+
if isinstance(op, torch._ops.OpOverloadPacket):
|
33
|
+
return [getattr(op, overload) for overload in op.overloads()]
|
34
|
+
return [op]
|
35
|
+
|
36
|
+
|
37
|
+
_TORCH_Q_OPS = [
|
38
|
+
torch.ops.quantized_decomposed.quantize_per_tensor.default,
|
39
|
+
torch.ops.quantized_decomposed.quantize_per_tensor.tensor,
|
40
|
+
torch.ops.quantized_decomposed.quantize_per_tensor.tensor2,
|
41
|
+
torch.ops.quantized_decomposed.quantize_per_channel.default,
|
42
|
+
]
|
43
|
+
|
44
|
+
_TORCH_DQ_OPS = [
|
45
|
+
torch.ops.quantized_decomposed.dequantize_per_tensor.default,
|
46
|
+
torch.ops.quantized_decomposed.dequantize_per_tensor.tensor,
|
47
|
+
torch.ops.quantized_decomposed.dequantize_per_tensor.tensor2,
|
48
|
+
torch.ops.quantized_decomposed.dequantize_per_channel.default,
|
49
|
+
]
|
50
|
+
|
51
|
+
|
52
|
+
def is_q_node(node: torch.fx.Node):
|
53
|
+
return node.target in _TORCH_Q_OPS
|
54
|
+
|
55
|
+
|
56
|
+
def is_dq_node(node: torch.fx.Node):
|
57
|
+
return node.target in _TORCH_DQ_OPS
|
58
|
+
|
59
|
+
|
60
|
+
def get_paired_q_dq_ops(op: Callable) -> tuple[Callable, Callable]:
|
61
|
+
for q, dq in zip(_TORCH_Q_OPS, _TORCH_DQ_OPS):
|
62
|
+
if op in (q, dq):
|
63
|
+
return q, dq
|
64
|
+
raise AssertionError(f"{op} is not a Q/DQ op.")
|
@@ -0,0 +1,52 @@
|
|
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
|
+
"""Pass to remove all non user outputs from exported program."""
|
16
|
+
|
17
|
+
|
18
|
+
from ai_edge_torch import fx_pass_base
|
19
|
+
import torch
|
20
|
+
|
21
|
+
|
22
|
+
class RemoveNonUserOutputsPass(fx_pass_base.ExportedProgramPassBase):
|
23
|
+
"""This pass removes all non user outputs from the exported program's output.
|
24
|
+
|
25
|
+
The FX graph may output more tensors/data than what user's original model
|
26
|
+
returns. Those additional outputs include user input mutations, gradient to
|
27
|
+
parameter, etc. Those outputs are not supported by our inference only
|
28
|
+
conversion or runtime. This pass remove all those outputs to ensure the
|
29
|
+
converted models' outputs match what returned from user's model in eval mode.
|
30
|
+
"""
|
31
|
+
|
32
|
+
def call(self, exported_program: torch.export.ExportedProgram):
|
33
|
+
for node in exported_program.graph.nodes:
|
34
|
+
if node.op != "output":
|
35
|
+
continue
|
36
|
+
|
37
|
+
outputs = node.args[0]
|
38
|
+
output_specs = exported_program.graph_signature.output_specs
|
39
|
+
|
40
|
+
new_outputs = []
|
41
|
+
new_output_specs = []
|
42
|
+
for output, spec in zip(outputs, output_specs):
|
43
|
+
if spec.kind == torch.export.graph_signature.OutputKind.USER_OUTPUT:
|
44
|
+
new_outputs.append(output)
|
45
|
+
new_output_specs.append(spec)
|
46
|
+
|
47
|
+
node.args = (tuple(new_outputs),)
|
48
|
+
exported_program.graph_signature.output_specs = new_output_specs
|
49
|
+
|
50
|
+
exported_program.graph_module.graph.lint()
|
51
|
+
exported_program.graph_module.recompile()
|
52
|
+
return fx_pass_base.ExportedProgramPassResult(exported_program, True)
|
@@ -0,0 +1,66 @@
|
|
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
|
+
import dataclasses
|
17
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
18
|
+
|
19
|
+
from ai_edge_torch import lowertools
|
20
|
+
import torch
|
21
|
+
import torch.utils._pytree as pytree
|
22
|
+
|
23
|
+
|
24
|
+
@dataclasses.dataclass
|
25
|
+
class Signature:
|
26
|
+
name: str
|
27
|
+
module: torch.nn.Module
|
28
|
+
sample_args: tuple[torch.Tensor]
|
29
|
+
sample_kwargs: dict[str, torch.Tensor]
|
30
|
+
dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None
|
31
|
+
|
32
|
+
@property
|
33
|
+
def _normalized_sample_args_kwargs(self):
|
34
|
+
args, kwargs = self.sample_args, self.sample_kwargs
|
35
|
+
if args is not None:
|
36
|
+
if not isinstance(args, tuple):
|
37
|
+
# TODO(b/352584188): Check value types
|
38
|
+
raise ValueError("sample_args must be a tuple of torch tensors.")
|
39
|
+
if kwargs is not None:
|
40
|
+
if not isinstance(kwargs, dict) or not all(
|
41
|
+
isinstance(key, str) for key in kwargs.keys()
|
42
|
+
):
|
43
|
+
# TODO(b/352584188): Check value types
|
44
|
+
raise ValueError("sample_kwargs must be a dict of string to tensor.")
|
45
|
+
args = args if args is not None else tuple()
|
46
|
+
kwargs = kwargs if kwargs is not None else {}
|
47
|
+
return args, kwargs
|
48
|
+
|
49
|
+
@property
|
50
|
+
def flat_arg_names(self) -> list[str]:
|
51
|
+
spec = pytree.tree_flatten(self._normalized_sample_args_kwargs)[1]
|
52
|
+
args_spec, kwargs_spec = spec.children_specs
|
53
|
+
names = []
|
54
|
+
for i in range(args_spec.num_leaves):
|
55
|
+
names.append(f"args_{i}")
|
56
|
+
|
57
|
+
kwargs_names = lowertools.flat_dict_names(
|
58
|
+
kwargs_spec.children_specs, kwargs_spec.context
|
59
|
+
)
|
60
|
+
names.extend(kwargs_names)
|
61
|
+
return names
|
62
|
+
|
63
|
+
@property
|
64
|
+
def flat_args(self) -> tuple[Any]:
|
65
|
+
args, kwargs = self._normalized_sample_args_kwargs
|
66
|
+
return tuple([*args, *kwargs.values()])
|
@@ -0,0 +1,14 @@
|
|
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
|
+
# ==============================================================================
|