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,38 @@
|
|
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
|
+
from jax._src.lib.mlir import ir
|
16
|
+
from jax._src.lib.mlir import passmanager
|
17
|
+
|
18
|
+
|
19
|
+
def run_pass(pipeline, module: ir.Module):
|
20
|
+
pm = passmanager.PassManager.parse(pipeline)
|
21
|
+
pm.run(module.operation)
|
22
|
+
return module
|
23
|
+
|
24
|
+
|
25
|
+
def canonicalize(module: ir.Module):
|
26
|
+
return run_pass("builtin.module(canonicalize)", module)
|
27
|
+
|
28
|
+
|
29
|
+
def cse(module: ir.Module):
|
30
|
+
return run_pass("builtin.module(cse)", module)
|
31
|
+
|
32
|
+
|
33
|
+
def inline(module: ir.Module):
|
34
|
+
return run_pass("builtin.module(inline)", module)
|
35
|
+
|
36
|
+
|
37
|
+
def strip_debuginfo(module: ir.Module):
|
38
|
+
return run_pass("builtin.module(strip-debuginfo)", module)
|
@@ -0,0 +1,156 @@
|
|
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
|
+
"""APIs to convert lowered MLIR from PyTorch to TensorFlow artifacts."""
|
16
|
+
|
17
|
+
import re
|
18
|
+
|
19
|
+
import tensorflow as tf
|
20
|
+
import torch
|
21
|
+
|
22
|
+
from tensorflow.compiler.tf2xla.python import xla as tfxla
|
23
|
+
|
24
|
+
from . import export
|
25
|
+
from . import export_utils
|
26
|
+
|
27
|
+
|
28
|
+
def torch_dtype_to_tf(dtype):
|
29
|
+
return {
|
30
|
+
torch.double: tf.float64,
|
31
|
+
torch.float32: tf.float32,
|
32
|
+
torch.half: tf.float16,
|
33
|
+
torch.long: tf.int64,
|
34
|
+
torch.int32: tf.int32,
|
35
|
+
torch.int16: tf.int16,
|
36
|
+
torch.bool: tf.bool,
|
37
|
+
}.get(dtype)
|
38
|
+
|
39
|
+
|
40
|
+
def _get_shape_with_dynamic(signature: export.VariableSignature):
|
41
|
+
return [
|
42
|
+
None if export_utils.is_torch_dynamic(s) else s for s in signature.shape
|
43
|
+
]
|
44
|
+
|
45
|
+
|
46
|
+
def _mangle_tf_root_scope_name(name):
|
47
|
+
r"""Build the mangled name for tf.Variable.
|
48
|
+
|
49
|
+
TF has more restricted constrain on the variable names at root scope. Root
|
50
|
+
scope name constrain: [A-Za-z0-9.][A-Za-z0-9_.\\-/]* Non-root scope name
|
51
|
+
constrain: [A-Za-z0-9_.\\-/]*
|
52
|
+
https://github.com/tensorflow/tensorflow/blob/51b601fa6bb7e801c0b6ae73c25580e40a8b5745/tensorflow/python/framework/ops.py#L3301-L3302
|
53
|
+
The state_dict key doesn't have such constrain, the name need to be mangled
|
54
|
+
when a root-scoped TF variable is created.
|
55
|
+
|
56
|
+
FX Graph Node may contain characters other than [A-Za-z0-9_.\\-/], replace
|
57
|
+
offending characters with '_'.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
name: the tensor name to be mangled.
|
61
|
+
|
62
|
+
Returns:
|
63
|
+
Mangled name in str.
|
64
|
+
"""
|
65
|
+
if name[0] in "._\\-/":
|
66
|
+
name = "k" + name
|
67
|
+
name = re.sub(r"[^^\w\-/\\]+", "_", name)
|
68
|
+
return name
|
69
|
+
|
70
|
+
|
71
|
+
def _build_tf_state_dict(
|
72
|
+
lowered: export.MlirLowered,
|
73
|
+
) -> dict[str, tf.Variable]:
|
74
|
+
"""Build a dictionary of tf.Variable from the state_dict in lowered."""
|
75
|
+
tf_state_dict = {}
|
76
|
+
for sig in lowered.input_signature:
|
77
|
+
if sig.input_spec.is_parameter:
|
78
|
+
name = sig.input_spec.name
|
79
|
+
tf_state_dict[name] = tf.Variable(
|
80
|
+
lowered.state_dict[name].detach().numpy(),
|
81
|
+
trainable=False,
|
82
|
+
name=_mangle_tf_root_scope_name(name),
|
83
|
+
)
|
84
|
+
return tf_state_dict
|
85
|
+
|
86
|
+
|
87
|
+
def _extract_call_args(
|
88
|
+
lowered: export.MlirLowered,
|
89
|
+
args,
|
90
|
+
tf_state_dict: dict[str, tf.Variable],
|
91
|
+
):
|
92
|
+
"""Extract the flattened inputs to built tf.function."""
|
93
|
+
call_args = []
|
94
|
+
for sig in lowered.input_signature:
|
95
|
+
if sig.input_spec.is_user_input:
|
96
|
+
call_args.append(args[sig.input_spec.i])
|
97
|
+
elif sig.input_spec.is_parameter:
|
98
|
+
name = sig.input_spec.name
|
99
|
+
call_args.append(tf_state_dict[name])
|
100
|
+
return call_args
|
101
|
+
|
102
|
+
|
103
|
+
def _wrap_as_tf_func(lowered, tf_state_dict):
|
104
|
+
"""Build tf.function from lowered and tf_state_dict."""
|
105
|
+
|
106
|
+
version = 6
|
107
|
+
if hasattr(tfxla, "call_module_maximum_supported_version"):
|
108
|
+
version = tfxla.call_module_maximum_supported_version()
|
109
|
+
|
110
|
+
def tf_func(*args):
|
111
|
+
t_outs = [torch_dtype_to_tf(sig.dtype) for sig in lowered.output_signature]
|
112
|
+
s_outs = [_get_shape_with_dynamic(sig) for sig in lowered.output_signature]
|
113
|
+
call_args = _extract_call_args(lowered, args, tf_state_dict)
|
114
|
+
return tfxla.call_module(
|
115
|
+
tuple(call_args),
|
116
|
+
version=version,
|
117
|
+
Tout=t_outs, # dtype information
|
118
|
+
Sout=s_outs, # shape information
|
119
|
+
function_list=[],
|
120
|
+
module=lowered.module_bytecode_vhlo,
|
121
|
+
has_token_input_output=False,
|
122
|
+
platforms=["CPU"],
|
123
|
+
)
|
124
|
+
|
125
|
+
return tf_func
|
126
|
+
|
127
|
+
|
128
|
+
def _make_input_signatures(
|
129
|
+
lowered: export.MlirLowered,
|
130
|
+
) -> list[tf.TensorSpec]:
|
131
|
+
"""Build the input signatures in tf.TensorSpec for building tf.function."""
|
132
|
+
user_input_signature = sorted(
|
133
|
+
[sig for sig in lowered.input_signature if sig.input_spec.is_user_input],
|
134
|
+
key=lambda sig: sig.input_spec.i,
|
135
|
+
)
|
136
|
+
tf_signatures = []
|
137
|
+
|
138
|
+
for sig in user_input_signature:
|
139
|
+
shape = _get_shape_with_dynamic(sig)
|
140
|
+
tf_signatures.append(
|
141
|
+
tf.TensorSpec(
|
142
|
+
shape=shape,
|
143
|
+
dtype=torch_dtype_to_tf(sig.dtype),
|
144
|
+
name=f"args_{sig.input_spec.i}",
|
145
|
+
)
|
146
|
+
)
|
147
|
+
return tf_signatures
|
148
|
+
|
149
|
+
|
150
|
+
def mlir_to_tf_function(lowered: export.MlirLowered):
|
151
|
+
"""Convert the MLIR lowered to a executable tf.function."""
|
152
|
+
tf_state_dict = _build_tf_state_dict(lowered)
|
153
|
+
return tf.function(
|
154
|
+
_wrap_as_tf_func(lowered, tf_state_dict),
|
155
|
+
input_signature=_make_input_signatures(lowered),
|
156
|
+
)
|
@@ -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 .pt2e_quantizer import PT2EQuantizer
|
@@ -0,0 +1,466 @@
|
|
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 __future__ import annotations
|
17
|
+
|
18
|
+
import copy
|
19
|
+
import functools
|
20
|
+
from typing import Any, Callable, Dict, List, Optional, Set
|
21
|
+
|
22
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import _convert_scalars_to_attrs # NOQA
|
23
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import OP_TO_ANNOTATOR
|
24
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import OperatorConfig
|
25
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import OperatorPatternType
|
26
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import propagate_annotation
|
27
|
+
from ai_edge_torch.quantize.pt2e_quantizer_utils import QuantizationConfig
|
28
|
+
import torch
|
29
|
+
from torch.ao.quantization.fake_quantize import FusedMovingAvgObsFakeQuantize
|
30
|
+
from torch.ao.quantization.observer import HistogramObserver
|
31
|
+
from torch.ao.quantization.observer import MinMaxObserver
|
32
|
+
from torch.ao.quantization.observer import MovingAverageMinMaxObserver
|
33
|
+
from torch.ao.quantization.observer import MovingAveragePerChannelMinMaxObserver # NOQA
|
34
|
+
from torch.ao.quantization.observer import PerChannelMinMaxObserver
|
35
|
+
from torch.ao.quantization.observer import PlaceholderObserver
|
36
|
+
from torch.ao.quantization.qconfig import _ObserverOrFakeQuantizeConstructor
|
37
|
+
from torch.ao.quantization.quantizer import FixedQParamsQuantizationSpec
|
38
|
+
from torch.ao.quantization.quantizer import QuantizationSpec
|
39
|
+
from torch.ao.quantization.quantizer import Quantizer
|
40
|
+
from torch.fx import Node
|
41
|
+
import torch.nn.functional as F
|
42
|
+
|
43
|
+
__all__ = [
|
44
|
+
"PT2EQuantizer",
|
45
|
+
"get_symmetric_quantization_config",
|
46
|
+
]
|
47
|
+
|
48
|
+
|
49
|
+
def _supported_symmetric_quantized_operators() -> (
|
50
|
+
Dict[str, List[OperatorPatternType]]
|
51
|
+
):
|
52
|
+
supported_operators: Dict[str, List[OperatorPatternType]] = {
|
53
|
+
# Both conv and linear should be able to handle relu + hardtanh fusion since
|
54
|
+
# those are clamp ops
|
55
|
+
"conv2d": [
|
56
|
+
[torch.nn.Conv2d, torch.nn.ReLU],
|
57
|
+
[torch.nn.Conv2d, F.relu],
|
58
|
+
[F.conv2d, torch.nn.ReLU],
|
59
|
+
[F.conv2d, F.relu],
|
60
|
+
],
|
61
|
+
"linear": [[torch.nn.Linear], [F.linear]],
|
62
|
+
"add": [[torch.add]],
|
63
|
+
"max_pool2d": [[torch.nn.MaxPool2d], [F.max_pool2d]],
|
64
|
+
"adaptive_avg_pool2d": [
|
65
|
+
[torch.nn.AdaptiveAvgPool2d],
|
66
|
+
[F.adaptive_avg_pool2d],
|
67
|
+
],
|
68
|
+
}
|
69
|
+
return copy.deepcopy(supported_operators)
|
70
|
+
|
71
|
+
|
72
|
+
def _get_supported_symmetric_config_and_operators() -> List[OperatorConfig]:
|
73
|
+
supported_config_and_operators: List[OperatorConfig] = []
|
74
|
+
for quantization_config in [
|
75
|
+
get_symmetric_quantization_config(),
|
76
|
+
get_symmetric_quantization_config(is_qat=True),
|
77
|
+
get_symmetric_quantization_config(is_per_channel=True),
|
78
|
+
get_symmetric_quantization_config(is_per_channel=True, is_qat=True),
|
79
|
+
]:
|
80
|
+
ops = _supported_symmetric_quantized_operators()
|
81
|
+
for pattern_list in ops.values():
|
82
|
+
supported_config_and_operators.append(
|
83
|
+
OperatorConfig(quantization_config, pattern_list)
|
84
|
+
)
|
85
|
+
return copy.deepcopy(supported_config_and_operators)
|
86
|
+
|
87
|
+
|
88
|
+
@functools.lru_cache
|
89
|
+
def get_symmetric_quantization_config(
|
90
|
+
is_per_channel: bool = False,
|
91
|
+
is_qat: bool = False,
|
92
|
+
is_dynamic: bool = False,
|
93
|
+
):
|
94
|
+
if is_qat:
|
95
|
+
if is_dynamic:
|
96
|
+
raise NotImplementedError(
|
97
|
+
"dynamic quantization for qat is not yet implemented."
|
98
|
+
)
|
99
|
+
act_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize
|
100
|
+
else:
|
101
|
+
if is_dynamic:
|
102
|
+
act_observer_or_fake_quant_ctr = PlaceholderObserver # type: ignore[assignment]
|
103
|
+
else:
|
104
|
+
act_observer_or_fake_quant_ctr = HistogramObserver # type: ignore[assignment]
|
105
|
+
|
106
|
+
act_quantization_spec = QuantizationSpec(
|
107
|
+
dtype=torch.int8,
|
108
|
+
quant_min=-128,
|
109
|
+
quant_max=127,
|
110
|
+
qscheme=torch.per_tensor_affine,
|
111
|
+
is_dynamic=is_dynamic,
|
112
|
+
observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args(
|
113
|
+
eps=2**-12
|
114
|
+
),
|
115
|
+
)
|
116
|
+
qscheme = (
|
117
|
+
torch.per_channel_symmetric
|
118
|
+
if is_per_channel
|
119
|
+
else torch.per_tensor_symmetric
|
120
|
+
)
|
121
|
+
weight_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = (
|
122
|
+
MinMaxObserver
|
123
|
+
)
|
124
|
+
if is_qat:
|
125
|
+
weight_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize
|
126
|
+
elif is_per_channel:
|
127
|
+
weight_observer_or_fake_quant_ctr = PerChannelMinMaxObserver
|
128
|
+
|
129
|
+
extra_args: Dict[str, Any] = {"eps": 2**-12}
|
130
|
+
if is_qat:
|
131
|
+
if qscheme == torch.per_tensor_symmetric:
|
132
|
+
extra_args["observer"] = MovingAverageMinMaxObserver
|
133
|
+
else:
|
134
|
+
extra_args["observer"] = MovingAveragePerChannelMinMaxObserver # type: ignore[dict-item]
|
135
|
+
weight_quantization_spec = QuantizationSpec(
|
136
|
+
dtype=torch.int8,
|
137
|
+
quant_min=-127,
|
138
|
+
quant_max=127,
|
139
|
+
qscheme=qscheme,
|
140
|
+
ch_axis=0,
|
141
|
+
is_dynamic=False,
|
142
|
+
observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args(
|
143
|
+
**extra_args
|
144
|
+
),
|
145
|
+
)
|
146
|
+
|
147
|
+
bias_quantization_spec = None
|
148
|
+
|
149
|
+
# Some TFLite ops (e.g. Logistic, Softmax) have fixed qparams requirements
|
150
|
+
fixed_qparams_spec = FixedQParamsQuantizationSpec(
|
151
|
+
dtype=torch.int8,
|
152
|
+
scale=1 / 256,
|
153
|
+
zero_point=-128,
|
154
|
+
quant_min=-128,
|
155
|
+
quant_max=127,
|
156
|
+
qscheme=torch.per_tensor_affine,
|
157
|
+
)
|
158
|
+
|
159
|
+
if is_dynamic:
|
160
|
+
# Only valid for TFLite downstream to have no input activation quantization
|
161
|
+
# because dynamic quantization should be legalized to TFLite DRQ kernels
|
162
|
+
# which calculate quantization parameters during runtime inside the kernels
|
163
|
+
quantization_config = QuantizationConfig(
|
164
|
+
None,
|
165
|
+
None,
|
166
|
+
weight_quantization_spec,
|
167
|
+
bias_quantization_spec,
|
168
|
+
None,
|
169
|
+
is_qat,
|
170
|
+
True,
|
171
|
+
)
|
172
|
+
else:
|
173
|
+
quantization_config = QuantizationConfig(
|
174
|
+
act_quantization_spec,
|
175
|
+
act_quantization_spec,
|
176
|
+
weight_quantization_spec,
|
177
|
+
bias_quantization_spec,
|
178
|
+
fixed_qparams_spec,
|
179
|
+
is_qat,
|
180
|
+
False,
|
181
|
+
)
|
182
|
+
return quantization_config
|
183
|
+
|
184
|
+
|
185
|
+
def _get_supported_config_and_operators() -> List[OperatorConfig]:
|
186
|
+
return _get_supported_symmetric_config_and_operators()
|
187
|
+
|
188
|
+
|
189
|
+
def _get_module_name_filter(module_name: str):
|
190
|
+
"""Get the module_name_filter function for a given module name, the filter accepts
|
191
|
+
|
192
|
+
a node and checks if the node comes from a module that has certain module name
|
193
|
+
|
194
|
+
For example:
|
195
|
+
node: linear_op = call_function[...](...) # comes from a module with name
|
196
|
+
blocks.sub.linear1
|
197
|
+
|
198
|
+
|
199
|
+
>> module_name_filter = _get_module_name_filter("blocks.sub")
|
200
|
+
>> print(module_name_filter(node))
|
201
|
+
True # the node is from "blocks.sub" based on the fully qualified name
|
202
|
+
"blocks.sub.linear1"
|
203
|
+
"""
|
204
|
+
|
205
|
+
def module_name_filter(n: Node) -> bool:
|
206
|
+
# example: {
|
207
|
+
# 'L__self___sub': ("L['self'].sub", <class '....Sub'>),
|
208
|
+
# 'L__self___sub_linear': ("L['self'].sub.linear", <class 'torch.nn.modules.linear.Linear'>)
|
209
|
+
# }
|
210
|
+
# get_attr nodes doesn't have nn_module_stack?
|
211
|
+
nn_module_stack = n.meta.get("nn_module_stack", {})
|
212
|
+
names = [
|
213
|
+
n[len("L__self___") :].replace("_", ".") for n in nn_module_stack.keys()
|
214
|
+
]
|
215
|
+
return module_name in names
|
216
|
+
|
217
|
+
return module_name_filter
|
218
|
+
|
219
|
+
|
220
|
+
def _get_module_type_filter(tp: Callable):
|
221
|
+
"""Get the module_type_filter function for a given module type, the filter accepts
|
222
|
+
|
223
|
+
a node and checks if the node comes from a module that has certain module type
|
224
|
+
|
225
|
+
For example:
|
226
|
+
node: linear_op = call_function[...](...) # comes from a module with type
|
227
|
+
Block -> Sub -> Linear
|
228
|
+
|
229
|
+
|
230
|
+
>> module_type_filter = _get_module_type_filter(Sub) # submodule with type
|
231
|
+
`Sub`, under the `Block` submodule
|
232
|
+
>> print(module_type_filter(node))
|
233
|
+
True # the node is from the submodule `Sub` (same for `Block` and `Linear` as
|
234
|
+
well)
|
235
|
+
"""
|
236
|
+
|
237
|
+
def module_type_filter(n: Node) -> bool:
|
238
|
+
# example: {
|
239
|
+
# 'L__self___sub': ("L['self'].sub", <class '....Sub'>),
|
240
|
+
# 'L__self___sub_linear': ("L['self'].sub.linear", <class 'torch.nn.modules.linear.Linear'>)
|
241
|
+
# }
|
242
|
+
nn_module_stack = n.meta.get("nn_module_stack", {})
|
243
|
+
types = [t for _, t in nn_module_stack.values()]
|
244
|
+
return tp in types
|
245
|
+
|
246
|
+
return module_type_filter
|
247
|
+
|
248
|
+
|
249
|
+
def _get_not_module_type_or_name_filter(
|
250
|
+
tp_list: List[Callable], module_name_list: List[str]
|
251
|
+
) -> Callable[[Node], bool]:
|
252
|
+
module_type_filters = [_get_module_type_filter(tp) for tp in tp_list]
|
253
|
+
module_name_list_filters = [
|
254
|
+
_get_module_name_filter(m) for m in module_name_list
|
255
|
+
]
|
256
|
+
|
257
|
+
def not_module_type_or_name_filter(n: Node) -> bool:
|
258
|
+
return not any(f(n) for f in module_type_filters + module_name_list_filters)
|
259
|
+
|
260
|
+
return not_module_type_or_name_filter
|
261
|
+
|
262
|
+
|
263
|
+
class PT2EQuantizer(Quantizer):
|
264
|
+
supported_config_and_operators = _get_supported_config_and_operators()
|
265
|
+
STATIC_QAT_ONLY_OPS = [
|
266
|
+
"conv_bn_relu",
|
267
|
+
"conv_bn",
|
268
|
+
]
|
269
|
+
|
270
|
+
# static quantization ops (both PTQ and QAT)
|
271
|
+
STATIC_OPS = [
|
272
|
+
"linear",
|
273
|
+
"addmm",
|
274
|
+
"conv_relu",
|
275
|
+
"conv",
|
276
|
+
"adaptive_avg_pool2d",
|
277
|
+
"gru_io_only",
|
278
|
+
"max_pool2d",
|
279
|
+
"add_relu",
|
280
|
+
"add",
|
281
|
+
"mul_relu",
|
282
|
+
"mul",
|
283
|
+
"cat",
|
284
|
+
"fixed_qparams",
|
285
|
+
]
|
286
|
+
|
287
|
+
DYNAMIC_OPS = [
|
288
|
+
"linear",
|
289
|
+
"addmm",
|
290
|
+
"conv",
|
291
|
+
"conv_relu",
|
292
|
+
]
|
293
|
+
|
294
|
+
def __init__(self):
|
295
|
+
super().__init__()
|
296
|
+
self.global_config: Optional[QuantizationConfig] = None
|
297
|
+
self.operator_type_config: Dict[
|
298
|
+
torch._ops.OpOverloadPacket, Optional[QuantizationConfig]
|
299
|
+
] = {}
|
300
|
+
self.module_type_config: Dict[Callable, Optional[QuantizationConfig]] = {}
|
301
|
+
self.module_name_config: Dict[str, Optional[QuantizationConfig]] = {}
|
302
|
+
|
303
|
+
@classmethod
|
304
|
+
def get_supported_quantization_configs(cls) -> List[QuantizationConfig]:
|
305
|
+
op_configs: Set[QuantizationConfig] = set({})
|
306
|
+
for spec, _ in cls.supported_config_and_operators:
|
307
|
+
op_configs.add(spec)
|
308
|
+
return list(op_configs)
|
309
|
+
|
310
|
+
@classmethod
|
311
|
+
def get_supported_operator_for_quantization_config(
|
312
|
+
cls, quantization_config: Optional[QuantizationConfig]
|
313
|
+
) -> List[OperatorPatternType]:
|
314
|
+
if quantization_config is None:
|
315
|
+
all_ops = []
|
316
|
+
for _, ops in cls.supported_config_and_operators:
|
317
|
+
all_ops.extend(ops)
|
318
|
+
return all_ops
|
319
|
+
|
320
|
+
for config, ops in cls.supported_config_and_operators:
|
321
|
+
# note: this assumes each entry in cls.supported_spec_and_operators
|
322
|
+
# corresponds to one spec, e.g. we don't have
|
323
|
+
# [(spec1, op_list1), (spec1, op_list2), (spec2, op_list3)]
|
324
|
+
# where the first and second entry have the same spec but did not
|
325
|
+
# merge the op list
|
326
|
+
if config == quantization_config:
|
327
|
+
return ops
|
328
|
+
return []
|
329
|
+
|
330
|
+
def set_global(
|
331
|
+
self, quantization_config: QuantizationConfig
|
332
|
+
) -> PT2EQuantizer:
|
333
|
+
self.global_config = quantization_config
|
334
|
+
return self
|
335
|
+
|
336
|
+
def set_operator_type(
|
337
|
+
self,
|
338
|
+
operator_type: torch._ops.OpOverloadPacket,
|
339
|
+
quantization_config: QuantizationConfig,
|
340
|
+
) -> PT2EQuantizer:
|
341
|
+
self.operator_type_config[operator_type] = quantization_config
|
342
|
+
return self
|
343
|
+
|
344
|
+
def set_module_type(
|
345
|
+
self, module_type: Callable, quantization_config: QuantizationConfig
|
346
|
+
):
|
347
|
+
"""Set quantization_config for a submodule with type: `module_type`, for example:
|
348
|
+
|
349
|
+
quantizer.set_module_name(Sub) or quantizer.set_module_name(nn.Linear), it
|
350
|
+
will quantize all supported operator/operator
|
351
|
+
patterns in the submodule with this module type with the given
|
352
|
+
`quantization_config`
|
353
|
+
"""
|
354
|
+
self.module_type_config[module_type] = quantization_config
|
355
|
+
return self
|
356
|
+
|
357
|
+
def set_module_name(
|
358
|
+
self, module_name: str, quantization_config: Optional[QuantizationConfig]
|
359
|
+
):
|
360
|
+
"""Set quantization_config for a submodule with name: `module_name`, for example:
|
361
|
+
|
362
|
+
quantizer.set_module_name("blocks.sub"), it will quantize all supported
|
363
|
+
operator/operator
|
364
|
+
patterns in the submodule with this module name with the given
|
365
|
+
`quantization_config`
|
366
|
+
"""
|
367
|
+
assert (
|
368
|
+
quantization_config is not None
|
369
|
+
), " quantization_config == None is not supported yet"
|
370
|
+
self.module_name_config[module_name] = quantization_config
|
371
|
+
return self
|
372
|
+
|
373
|
+
def transform_for_annotation(
|
374
|
+
self, model: torch.fx.GraphModule
|
375
|
+
) -> torch.fx.GraphModule:
|
376
|
+
"""Transforms scalar values to tensor attributes"""
|
377
|
+
return _convert_scalars_to_attrs(model)
|
378
|
+
|
379
|
+
def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:
|
380
|
+
"""just handling global spec for now"""
|
381
|
+
if self.global_config and not self.global_config.input_activation: # type: ignore[union-attr]
|
382
|
+
model = self._annotate_for_dynamic_quantization_config(model)
|
383
|
+
else:
|
384
|
+
model = self._annotate_for_static_quantization_config(model)
|
385
|
+
propagate_annotation(model)
|
386
|
+
return model
|
387
|
+
|
388
|
+
def _annotate_all_static_patterns(
|
389
|
+
self,
|
390
|
+
model: torch.fx.GraphModule,
|
391
|
+
quantization_config: Optional[QuantizationConfig],
|
392
|
+
filter_fn: Optional[Callable[[Node], bool]] = None,
|
393
|
+
) -> torch.fx.GraphModule:
|
394
|
+
if quantization_config is None:
|
395
|
+
return model
|
396
|
+
|
397
|
+
if quantization_config.is_qat:
|
398
|
+
for op in self.STATIC_QAT_ONLY_OPS:
|
399
|
+
OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn)
|
400
|
+
for op in self.STATIC_OPS:
|
401
|
+
OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn)
|
402
|
+
return model
|
403
|
+
|
404
|
+
def _annotate_all_dynamic_patterns(
|
405
|
+
self,
|
406
|
+
model: torch.fx.GraphModule,
|
407
|
+
quantization_config: Optional[QuantizationConfig],
|
408
|
+
filter_fn: Optional[Callable[[Node], bool]] = None,
|
409
|
+
) -> torch.fx.GraphModule:
|
410
|
+
if quantization_config is None:
|
411
|
+
return model
|
412
|
+
|
413
|
+
for op in self.DYNAMIC_OPS:
|
414
|
+
OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn)
|
415
|
+
return model
|
416
|
+
|
417
|
+
def _annotate_for_static_quantization_config(
|
418
|
+
self, model: torch.fx.GraphModule
|
419
|
+
) -> torch.fx.GraphModule:
|
420
|
+
module_name_list = list(self.module_name_config.keys())
|
421
|
+
for module_name, config in self.module_name_config.items():
|
422
|
+
self._annotate_all_static_patterns(
|
423
|
+
model, config, _get_module_name_filter(module_name)
|
424
|
+
)
|
425
|
+
|
426
|
+
tp_list = list(self.module_type_config.keys())
|
427
|
+
for module_type, config in self.module_type_config.items():
|
428
|
+
self._annotate_all_static_patterns(
|
429
|
+
model, config, _get_module_type_filter(module_type)
|
430
|
+
)
|
431
|
+
|
432
|
+
self._annotate_all_static_patterns(
|
433
|
+
model,
|
434
|
+
self.global_config,
|
435
|
+
_get_not_module_type_or_name_filter(tp_list, module_name_list),
|
436
|
+
)
|
437
|
+
return model
|
438
|
+
|
439
|
+
def _annotate_for_dynamic_quantization_config(
|
440
|
+
self, model: torch.fx.GraphModule
|
441
|
+
) -> torch.fx.GraphModule:
|
442
|
+
module_name_list = list(self.module_name_config.keys())
|
443
|
+
for module_name, config in self.module_name_config.items():
|
444
|
+
self._annotate_all_dynamic_patterns(
|
445
|
+
model, config, _get_module_name_filter(module_name)
|
446
|
+
)
|
447
|
+
|
448
|
+
tp_list = list(self.module_type_config.keys())
|
449
|
+
for module_type, config in self.module_type_config.items():
|
450
|
+
self._annotate_all_dynamic_patterns(
|
451
|
+
model, config, _get_module_type_filter(module_type)
|
452
|
+
)
|
453
|
+
|
454
|
+
self._annotate_all_dynamic_patterns(
|
455
|
+
model,
|
456
|
+
self.global_config,
|
457
|
+
_get_not_module_type_or_name_filter(tp_list, module_name_list),
|
458
|
+
)
|
459
|
+
return model
|
460
|
+
|
461
|
+
def validate(self, model: torch.fx.GraphModule) -> None:
|
462
|
+
pass
|
463
|
+
|
464
|
+
@classmethod
|
465
|
+
def get_supported_operators(cls) -> List[OperatorConfig]:
|
466
|
+
return cls.supported_config_and_operators
|