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,558 @@
|
|
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
|
+
"""Tests for ai_edge_torch.convert."""
|
16
|
+
|
17
|
+
import dataclasses
|
18
|
+
import os
|
19
|
+
from typing import Tuple
|
20
|
+
|
21
|
+
import ai_edge_torch
|
22
|
+
from ai_edge_torch._convert import conversion_utils
|
23
|
+
from ai_edge_torch.quantize import pt2e_quantizer
|
24
|
+
from ai_edge_torch.testing import model_coverage
|
25
|
+
import numpy as np
|
26
|
+
import torch
|
27
|
+
from torch import nn
|
28
|
+
from torch.ao.quantization import quantize_pt2e
|
29
|
+
import torchvision
|
30
|
+
|
31
|
+
from absl.testing import absltest as googletest
|
32
|
+
from ai_edge_litert import interpreter as tfl_interpreter # pylint: disable=g-direct-tensorflow-import
|
33
|
+
|
34
|
+
|
35
|
+
@dataclasses.dataclass
|
36
|
+
class TestContainer1:
|
37
|
+
data_1: torch.Tensor
|
38
|
+
data_2: Tuple[torch.Tensor, torch.Tensor]
|
39
|
+
|
40
|
+
|
41
|
+
torch.export.register_dataclass(
|
42
|
+
TestContainer1, serialized_type_name="TestContainer1"
|
43
|
+
)
|
44
|
+
|
45
|
+
|
46
|
+
class TestConvert(googletest.TestCase):
|
47
|
+
"""Tests conversion of various modules."""
|
48
|
+
|
49
|
+
def setUp(self):
|
50
|
+
super().setUp()
|
51
|
+
torch.manual_seed(0)
|
52
|
+
|
53
|
+
def test_convert_add(self):
|
54
|
+
"""Tests conversion of a simple Add module."""
|
55
|
+
|
56
|
+
class Add(nn.Module):
|
57
|
+
|
58
|
+
def forward(self, a, b):
|
59
|
+
return a + b
|
60
|
+
|
61
|
+
args = (
|
62
|
+
torch.randn((5, 10)),
|
63
|
+
torch.randn((5, 10)),
|
64
|
+
)
|
65
|
+
torch_module = Add().eval()
|
66
|
+
edge_model = ai_edge_torch.convert(torch_module, args)
|
67
|
+
|
68
|
+
self.assertTrue(
|
69
|
+
model_coverage.compare_tflite_torch(edge_model, torch_module, args)
|
70
|
+
)
|
71
|
+
|
72
|
+
def test_convert_dot_add(self):
|
73
|
+
"""Tests conversion of a matrix multiplication followed by an add."""
|
74
|
+
|
75
|
+
class DotAdd(nn.Module):
|
76
|
+
|
77
|
+
def forward(self, a, b, c):
|
78
|
+
return a @ b + c
|
79
|
+
|
80
|
+
args = (
|
81
|
+
torch.randn((5, 10)),
|
82
|
+
torch.randn((10, 5)),
|
83
|
+
torch.randn((5, 5)),
|
84
|
+
)
|
85
|
+
torch_module = DotAdd().eval()
|
86
|
+
edge_model = ai_edge_torch.convert(torch_module, args)
|
87
|
+
|
88
|
+
self.assertTrue(
|
89
|
+
model_coverage.compare_tflite_torch(edge_model, torch_module, args)
|
90
|
+
)
|
91
|
+
|
92
|
+
def test_convert_resnet18(self):
|
93
|
+
args = (torch.randn(4, 3, 224, 224),)
|
94
|
+
torch_module = torchvision.models.resnet18().eval()
|
95
|
+
edge_model = ai_edge_torch.convert(torch_module, args)
|
96
|
+
|
97
|
+
self.assertTrue(
|
98
|
+
model_coverage.compare_tflite_torch(edge_model, torch_module, args)
|
99
|
+
)
|
100
|
+
|
101
|
+
def test_signature_args_ordering(self):
|
102
|
+
"""Tests conversion of a model with more than 10 arguments."""
|
103
|
+
|
104
|
+
class AddChainWith11Args(nn.Module):
|
105
|
+
"""A model with 11 arguments."""
|
106
|
+
|
107
|
+
def forward(
|
108
|
+
self,
|
109
|
+
arg0: torch.Tensor,
|
110
|
+
arg1: torch.Tensor,
|
111
|
+
arg2: torch.Tensor,
|
112
|
+
arg3: torch.Tensor,
|
113
|
+
arg4: torch.Tensor,
|
114
|
+
arg5: torch.Tensor,
|
115
|
+
arg6: torch.Tensor,
|
116
|
+
arg7: torch.Tensor,
|
117
|
+
arg8: torch.Tensor,
|
118
|
+
arg9: torch.Tensor,
|
119
|
+
arg10: torch.Tensor,
|
120
|
+
):
|
121
|
+
add0 = torch.add(arg0, arg1)
|
122
|
+
add1 = torch.add(add0, arg2)
|
123
|
+
add2 = torch.add(add1, arg3)
|
124
|
+
add3 = torch.add(add2, arg4)
|
125
|
+
add4 = torch.add(add3, arg5)
|
126
|
+
add5 = torch.add(add4, arg6)
|
127
|
+
add6 = torch.add(add5, arg7)
|
128
|
+
add7 = torch.add(add6, arg8)
|
129
|
+
add8 = torch.add(add7, arg9)
|
130
|
+
add9 = torch.add(add8, arg10)
|
131
|
+
return add9
|
132
|
+
|
133
|
+
sample_input = lambda: (
|
134
|
+
torch.rand((64,), dtype=torch.float32),
|
135
|
+
torch.rand((64,), dtype=torch.float32),
|
136
|
+
torch.rand((64,), dtype=torch.float32),
|
137
|
+
torch.rand((64,), dtype=torch.float32),
|
138
|
+
torch.rand((64,), dtype=torch.float32),
|
139
|
+
torch.rand((64,), dtype=torch.float32),
|
140
|
+
torch.rand((64,), dtype=torch.float32),
|
141
|
+
torch.rand((64,), dtype=torch.float32),
|
142
|
+
torch.rand((64,), dtype=torch.float32),
|
143
|
+
torch.rand((64,), dtype=torch.float32),
|
144
|
+
torch.rand((64,), dtype=torch.float32),
|
145
|
+
)
|
146
|
+
torch_model = AddChainWith11Args().eval()
|
147
|
+
edge_model = ai_edge_torch.convert(torch_model, sample_input())
|
148
|
+
|
149
|
+
result = model_coverage.compare_tflite_torch(
|
150
|
+
edge_model, torch_model, sample_input, num_valid_inputs=10
|
151
|
+
)
|
152
|
+
self.assertTrue(result)
|
153
|
+
|
154
|
+
def test_multi_output_model(self):
|
155
|
+
"""Tests conversion of a model that returns multiple outputs."""
|
156
|
+
|
157
|
+
class BasicAddModelWithMultipleOutputs(nn.Module):
|
158
|
+
"""A model that returns multiple outputs."""
|
159
|
+
|
160
|
+
def forward(self, arg0, arg1):
|
161
|
+
add0 = arg0 + arg1
|
162
|
+
mul0 = arg0 * arg1
|
163
|
+
return add0, mul0
|
164
|
+
|
165
|
+
sample_input = (
|
166
|
+
torch.rand((64,), dtype=torch.float32),
|
167
|
+
torch.rand((64,), dtype=torch.float32),
|
168
|
+
)
|
169
|
+
|
170
|
+
torch_model = BasicAddModelWithMultipleOutputs().eval()
|
171
|
+
edge_model = ai_edge_torch.convert(torch_model, sample_input)
|
172
|
+
|
173
|
+
result = model_coverage.compare_tflite_torch(
|
174
|
+
edge_model, torch_model, sample_input
|
175
|
+
)
|
176
|
+
self.assertTrue(result)
|
177
|
+
|
178
|
+
def test_12_outputs_model(self):
|
179
|
+
"""Tests conversion of a model that returns more than 10 outputs."""
|
180
|
+
|
181
|
+
class BasicAddModelWithMultipleOutputs(nn.Module):
|
182
|
+
"""A model that returns multiple outputs."""
|
183
|
+
|
184
|
+
def forward(self, arg0, arg1):
|
185
|
+
add0 = arg0 + arg1
|
186
|
+
mul0 = arg0 * arg1
|
187
|
+
add1 = add0 + mul0
|
188
|
+
mul1 = add0 * mul0
|
189
|
+
add2 = add1 + mul1
|
190
|
+
mul2 = add1 * mul1
|
191
|
+
add3 = add2 + mul2
|
192
|
+
mul3 = add2 * mul2
|
193
|
+
add4 = add3 + mul3
|
194
|
+
mul4 = add3 * mul3
|
195
|
+
add5 = add4 + mul4
|
196
|
+
mul5 = add4 * mul4
|
197
|
+
|
198
|
+
return (
|
199
|
+
add0,
|
200
|
+
mul0,
|
201
|
+
add1,
|
202
|
+
mul1,
|
203
|
+
add2,
|
204
|
+
mul2,
|
205
|
+
add3,
|
206
|
+
mul3,
|
207
|
+
add4,
|
208
|
+
mul4,
|
209
|
+
add5,
|
210
|
+
mul5,
|
211
|
+
)
|
212
|
+
|
213
|
+
sample_input = (
|
214
|
+
torch.rand((64,), dtype=torch.float32),
|
215
|
+
torch.rand((64,), dtype=torch.float32),
|
216
|
+
)
|
217
|
+
|
218
|
+
torch_model = BasicAddModelWithMultipleOutputs().eval()
|
219
|
+
edge_model = ai_edge_torch.convert(torch_model, sample_input)
|
220
|
+
|
221
|
+
result = model_coverage.compare_tflite_torch(
|
222
|
+
edge_model, torch_model, sample_input
|
223
|
+
)
|
224
|
+
self.assertTrue(result)
|
225
|
+
|
226
|
+
def test_apply_tfl_converter_flags(self):
|
227
|
+
"""Tests if _apply_tfl_converter_flags correctly sets the values in a Converter object."""
|
228
|
+
|
229
|
+
class MockConverterInternalObject:
|
230
|
+
|
231
|
+
def __init__(self):
|
232
|
+
self.subkey2 = "original_subvalue2"
|
233
|
+
|
234
|
+
class MockConverter:
|
235
|
+
|
236
|
+
def __init__(self):
|
237
|
+
self.key1 = "original_value1"
|
238
|
+
self.key2 = MockConverterInternalObject()
|
239
|
+
|
240
|
+
mock_converter = MockConverter()
|
241
|
+
flags = {"key1": "new_value1", "key2": {"subkey2": "new_subvalue2"}}
|
242
|
+
conversion_utils.apply_tfl_converter_flags(mock_converter, flags)
|
243
|
+
|
244
|
+
self.assertTrue(flags["key1"], "new_value1")
|
245
|
+
self.assertTrue(flags["key2"]["subkey2"], "new_subvalue2")
|
246
|
+
|
247
|
+
def test_convert_add_converter_flags(self):
|
248
|
+
"""Tests conversion of an add module setting a tflite converter flag."""
|
249
|
+
|
250
|
+
class Add(nn.Module):
|
251
|
+
|
252
|
+
def forward(self, a, b):
|
253
|
+
return a + b
|
254
|
+
|
255
|
+
args = (
|
256
|
+
torch.randn((5, 10)),
|
257
|
+
torch.randn((5, 10)),
|
258
|
+
)
|
259
|
+
torch_module = Add().eval()
|
260
|
+
|
261
|
+
tmp_dir_path = self.create_tempdir()
|
262
|
+
ir_dump_path = os.path.join(
|
263
|
+
tmp_dir_path, "test_convert_add_converter_flags_mlir_dump"
|
264
|
+
)
|
265
|
+
ai_edge_torch.convert(
|
266
|
+
torch_module,
|
267
|
+
args,
|
268
|
+
_ai_edge_converter_flags={"ir_dump_dir": ir_dump_path},
|
269
|
+
)
|
270
|
+
self.assertTrue(os.path.isdir(ir_dump_path))
|
271
|
+
|
272
|
+
def test_convert_conv_transpose_batch_norm(self):
|
273
|
+
"""Tests conversion of a model with ConvTranspose2d and BatchNorm2d."""
|
274
|
+
|
275
|
+
channels = 2
|
276
|
+
size = 2
|
277
|
+
torch_model = nn.Sequential(
|
278
|
+
nn.ConvTranspose2d(
|
279
|
+
channels, channels, 1, stride=2, dilation=1, bias=False
|
280
|
+
),
|
281
|
+
nn.BatchNorm2d(channels),
|
282
|
+
)
|
283
|
+
|
284
|
+
torch_model.eval()
|
285
|
+
sample_input = (torch.rand(1, channels, size, size),)
|
286
|
+
edge_model = ai_edge_torch.convert(torch_model, sample_input)
|
287
|
+
|
288
|
+
result = model_coverage.compare_tflite_torch(
|
289
|
+
edge_model, torch_model, sample_input
|
290
|
+
)
|
291
|
+
self.assertTrue(result)
|
292
|
+
|
293
|
+
@googletest.skipIf(
|
294
|
+
not ai_edge_torch.config.use_torch_xla,
|
295
|
+
reason="Shape polymorphism is not yet support with odml_torch.",
|
296
|
+
)
|
297
|
+
def test_convert_model_with_dynamic_batch(self):
|
298
|
+
"""Test converting a simple model with dynamic batch size."""
|
299
|
+
|
300
|
+
class SampleModel(nn.Module):
|
301
|
+
|
302
|
+
def __init__(self):
|
303
|
+
super().__init__()
|
304
|
+
self.w = torch.ones((10, 10)) * 2.7
|
305
|
+
|
306
|
+
def forward(self, x, y):
|
307
|
+
return x + y + self.w
|
308
|
+
|
309
|
+
sample_input = (torch.randn(4, 3, 10, 10), torch.randn(4, 3, 10, 10))
|
310
|
+
batch = torch.export.Dim("batch")
|
311
|
+
dynamic_shapes = ({0: batch}, {0: batch})
|
312
|
+
|
313
|
+
model = SampleModel().eval()
|
314
|
+
edge_model = ai_edge_torch.convert(
|
315
|
+
model, sample_input, dynamic_shapes=dynamic_shapes
|
316
|
+
)
|
317
|
+
|
318
|
+
for batch_size in [2, 4, 10]:
|
319
|
+
validate_input = (
|
320
|
+
torch.randn(batch_size, 3, 10, 10),
|
321
|
+
torch.randn(batch_size, 3, 10, 10),
|
322
|
+
)
|
323
|
+
self.assertTrue(
|
324
|
+
model_coverage.compare_tflite_torch(edge_model, model, validate_input)
|
325
|
+
)
|
326
|
+
|
327
|
+
def test_convert_model_with_kwargs(self):
|
328
|
+
"""Test converting a simple model with sample_kwargs."""
|
329
|
+
|
330
|
+
class SampleModel(nn.Module):
|
331
|
+
|
332
|
+
def forward(self, x, y):
|
333
|
+
return x + y
|
334
|
+
|
335
|
+
kwargs_gen = lambda: dict(x=torch.randn(10, 10), y=torch.randn(10, 10))
|
336
|
+
|
337
|
+
model = SampleModel().eval()
|
338
|
+
edge_model = ai_edge_torch.convert(model, sample_kwargs=kwargs_gen())
|
339
|
+
|
340
|
+
self.assertTrue(
|
341
|
+
model_coverage.compare_tflite_torch(
|
342
|
+
edge_model, model, kwargs=kwargs_gen
|
343
|
+
)
|
344
|
+
)
|
345
|
+
|
346
|
+
def test_convert_model_with_args_kwargs(self):
|
347
|
+
"""Test converting a simple model with both sample_args and sample_kwargs."""
|
348
|
+
|
349
|
+
class SampleModel(nn.Module):
|
350
|
+
|
351
|
+
def forward(self, x, y):
|
352
|
+
return x + y
|
353
|
+
|
354
|
+
args_gen = lambda: (torch.randn(10, 10),)
|
355
|
+
kwargs_gen = lambda: dict(y=torch.randn(10, 10))
|
356
|
+
|
357
|
+
model = SampleModel().eval()
|
358
|
+
edge_model = ai_edge_torch.convert(model, args_gen(), kwargs_gen())
|
359
|
+
|
360
|
+
self.assertTrue(
|
361
|
+
model_coverage.compare_tflite_torch(
|
362
|
+
edge_model, model, args_gen, kwargs_gen
|
363
|
+
)
|
364
|
+
)
|
365
|
+
|
366
|
+
def test_convert_model_with_args_nested_kwargs_1(self):
|
367
|
+
"""Test converting a simple model with both sample_args and nested sample_kwargs."""
|
368
|
+
|
369
|
+
class SampleModel(nn.Module):
|
370
|
+
|
371
|
+
def forward(self, x: torch.Tensor, y: torch.Tensor, z: TestContainer1):
|
372
|
+
return x + y + z.data_1 + z.data_2[0] + z.data_2[1]
|
373
|
+
|
374
|
+
args = (torch.randn(10, 10),)
|
375
|
+
kwargs = dict(
|
376
|
+
y=torch.randn(10, 10),
|
377
|
+
z=TestContainer1(
|
378
|
+
data_1=torch.randn(10, 10),
|
379
|
+
data_2=(torch.randn(10, 10), torch.randn(10, 10)),
|
380
|
+
),
|
381
|
+
)
|
382
|
+
flat_inputs = {
|
383
|
+
"args_0": args[0].numpy(),
|
384
|
+
"y": kwargs["y"].numpy(),
|
385
|
+
"z_data_1": kwargs["z"].data_1.numpy(),
|
386
|
+
"z_data_2_0": kwargs["z"].data_2[0].numpy(),
|
387
|
+
"z_data_2_1": kwargs["z"].data_2[1].numpy(),
|
388
|
+
}
|
389
|
+
self._compare_tflite_torch_args_kwargs(
|
390
|
+
SampleModel(), args, kwargs, flat_inputs
|
391
|
+
)
|
392
|
+
|
393
|
+
def test_convert_model_with_args_nested_kwargs_2(self):
|
394
|
+
"""Test converting a simple model with both sample_args and nested sample_kwargs."""
|
395
|
+
|
396
|
+
class SampleModel(nn.Module):
|
397
|
+
|
398
|
+
def forward(self, x, y, z):
|
399
|
+
return x + y + z.data_1 + z.data_2[0][0] + z.data_2[1]
|
400
|
+
|
401
|
+
args = (torch.randn(10, 10),)
|
402
|
+
kwargs = dict(
|
403
|
+
y=torch.randn(10, 10),
|
404
|
+
z=TestContainer1(
|
405
|
+
data_1=torch.randn(10, 10),
|
406
|
+
data_2=[(torch.randn(10, 10),), torch.randn(10, 10)],
|
407
|
+
),
|
408
|
+
)
|
409
|
+
flat_inputs = {
|
410
|
+
"args_0": args[0].numpy(),
|
411
|
+
"y": kwargs["y"].numpy(),
|
412
|
+
"z_data_1": kwargs["z"].data_1.numpy(),
|
413
|
+
"z_data_2_0_0": kwargs["z"].data_2[0][0].numpy(),
|
414
|
+
"z_data_2_1": kwargs["z"].data_2[1].numpy(),
|
415
|
+
}
|
416
|
+
self._compare_tflite_torch_args_kwargs(
|
417
|
+
SampleModel(), args, kwargs, flat_inputs
|
418
|
+
)
|
419
|
+
|
420
|
+
def test_convert_model_with_args_nested_kwargs_3(self):
|
421
|
+
"""Test converting a simple model with both sample_args and nested sample_kwargs."""
|
422
|
+
|
423
|
+
class SampleModel(nn.Module):
|
424
|
+
|
425
|
+
def forward(self, x, y, z):
|
426
|
+
return x + y + z.data_1 + z.data_2[0]["foo"] + z.data_2[1]
|
427
|
+
|
428
|
+
args = (torch.randn(10, 10),)
|
429
|
+
kwargs = dict(
|
430
|
+
y=torch.randn(10, 10),
|
431
|
+
z=TestContainer1(
|
432
|
+
data_1=torch.randn(10, 10),
|
433
|
+
data_2=(dict(foo=torch.randn(10, 10)), torch.randn(10, 10)),
|
434
|
+
),
|
435
|
+
)
|
436
|
+
flat_inputs = {
|
437
|
+
"args_0": args[0].numpy(),
|
438
|
+
"y": kwargs["y"].numpy(),
|
439
|
+
"z_data_1": kwargs["z"].data_1.numpy(),
|
440
|
+
"z_data_2_0_foo": kwargs["z"].data_2[0]["foo"].numpy(),
|
441
|
+
"z_data_2_1": kwargs["z"].data_2[1].numpy(),
|
442
|
+
}
|
443
|
+
self._compare_tflite_torch_args_kwargs(
|
444
|
+
SampleModel(), args, kwargs, flat_inputs
|
445
|
+
)
|
446
|
+
|
447
|
+
def test_convert_model_non_flat_output_dict(self):
|
448
|
+
"""Test converting a model with non-flat output structure."""
|
449
|
+
|
450
|
+
class SampleModel(nn.Module):
|
451
|
+
|
452
|
+
def forward(self, x, y, z):
|
453
|
+
return {"x": x, "y": TestContainer1(data_1=y, data_2=[y, z])}
|
454
|
+
|
455
|
+
args = (torch.randn(10, 10), torch.randn(10, 10), torch.randn(10, 10))
|
456
|
+
kwargs = dict()
|
457
|
+
flat_inputs = {
|
458
|
+
"args_0": args[0].numpy(),
|
459
|
+
"args_1": args[1].numpy(),
|
460
|
+
"args_2": args[2].numpy(),
|
461
|
+
}
|
462
|
+
|
463
|
+
edge_model = ai_edge_torch.convert(SampleModel().eval(), args, kwargs)
|
464
|
+
edge_output = edge_model(**flat_inputs)
|
465
|
+
np.testing.assert_almost_equal(edge_output["x"], args[0])
|
466
|
+
np.testing.assert_almost_equal(edge_output["y_data_1"], args[1])
|
467
|
+
np.testing.assert_almost_equal(edge_output["y_data_2_0"], args[1])
|
468
|
+
np.testing.assert_almost_equal(edge_output["y_data_2_1"], args[2])
|
469
|
+
|
470
|
+
interpreter = tfl_interpreter.Interpreter(
|
471
|
+
model_content=edge_model._tflite_model
|
472
|
+
)
|
473
|
+
runner = interpreter.get_signature_runner("serving_default")
|
474
|
+
output_details = runner.get_output_details()
|
475
|
+
self.assertIn("x", output_details.keys())
|
476
|
+
self.assertIn("y_data_1", output_details.keys())
|
477
|
+
self.assertIn("y_data_2_0", output_details.keys())
|
478
|
+
self.assertIn("y_data_2_1", output_details.keys())
|
479
|
+
|
480
|
+
def _compare_tflite_torch_args_kwargs(self, model, args, kwargs, flat_inputs):
|
481
|
+
model.eval()
|
482
|
+
edge_model = ai_edge_torch.convert(model, args, kwargs)
|
483
|
+
interpreter = tfl_interpreter.Interpreter(
|
484
|
+
model_content=edge_model._tflite_model
|
485
|
+
)
|
486
|
+
runner = interpreter.get_signature_runner("serving_default")
|
487
|
+
input_details = runner.get_input_details()
|
488
|
+
self.assertEqual(input_details.keys(), flat_inputs.keys())
|
489
|
+
|
490
|
+
reference_output = model(*args, **kwargs)
|
491
|
+
tflite_output = edge_model(**flat_inputs)
|
492
|
+
np.testing.assert_almost_equal(reference_output, tflite_output)
|
493
|
+
|
494
|
+
def test_convert_model_with_input_mutation(self):
|
495
|
+
class SampleModel(nn.Module):
|
496
|
+
|
497
|
+
def forward(self, x):
|
498
|
+
x /= 1
|
499
|
+
x = x + 10
|
500
|
+
return x
|
501
|
+
|
502
|
+
args = (torch.randn(10, 10),)
|
503
|
+
torch_module = SampleModel().eval()
|
504
|
+
edge_model = ai_edge_torch.convert(torch_module, args)
|
505
|
+
|
506
|
+
self.assertTrue(
|
507
|
+
model_coverage.compare_tflite_torch(edge_model, torch_module, args)
|
508
|
+
)
|
509
|
+
|
510
|
+
def test_convert_resnet18_pt2e_per_layer(self):
|
511
|
+
# Step 1: export resnet18
|
512
|
+
args = (torch.randn(1, 3, 224, 224),)
|
513
|
+
m = torchvision.models.resnet18().eval()
|
514
|
+
m = torch._export.capture_pre_autograd_graph(m, args)
|
515
|
+
|
516
|
+
# Step 2: Insert observers or fake quantize modules
|
517
|
+
quantizer = pt2e_quantizer.PT2EQuantizer().set_global(
|
518
|
+
pt2e_quantizer.get_symmetric_quantization_config(is_per_channel=False)
|
519
|
+
)
|
520
|
+
m = quantize_pt2e.prepare_pt2e(m, quantizer)
|
521
|
+
|
522
|
+
# Step 3: Quantize the model
|
523
|
+
m = quantize_pt2e.convert_pt2e(m, fold_quantize=False)
|
524
|
+
|
525
|
+
# pylint: disable=broad-except
|
526
|
+
try:
|
527
|
+
ai_edge_torch.convert(m, args)
|
528
|
+
except Exception as err:
|
529
|
+
self.fail(f"PT2E conversion failed: {err}")
|
530
|
+
# pylint: enable=broad-except
|
531
|
+
|
532
|
+
def test_convert_resnet18_pt2e_per_channel(self):
|
533
|
+
# Step 1: export resnet18
|
534
|
+
args = (torch.randn(1, 3, 224, 224),)
|
535
|
+
m = torchvision.models.resnet18().eval()
|
536
|
+
m = torch._export.capture_pre_autograd_graph(m, args)
|
537
|
+
|
538
|
+
# Step 2: Insert observers or fake quantize modules
|
539
|
+
quantizer = pt2e_quantizer.PT2EQuantizer().set_global(
|
540
|
+
pt2e_quantizer.get_symmetric_quantization_config(is_per_channel=True)
|
541
|
+
)
|
542
|
+
m = quantize_pt2e.prepare_pt2e(m, quantizer)
|
543
|
+
# Step 3: Run through example inputs, otherwise per-channel
|
544
|
+
# quant may have scalar scale/zero_point
|
545
|
+
m(*args)
|
546
|
+
# Step 4: Quantize the model
|
547
|
+
m = quantize_pt2e.convert_pt2e(m, fold_quantize=False)
|
548
|
+
|
549
|
+
# pylint: disable=broad-except
|
550
|
+
try:
|
551
|
+
ai_edge_torch.convert(m, args)
|
552
|
+
except Exception as err:
|
553
|
+
self.fail(f"PT2E conversion failed: {err}")
|
554
|
+
# pylint: enable=broad-except
|
555
|
+
|
556
|
+
|
557
|
+
if __name__ == "__main__":
|
558
|
+
googletest.main()
|