ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl → 0.3.0.dev20240926__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (169) hide show
  1. ai_edge_torch/__init__.py +5 -4
  2. ai_edge_torch/_convert/conversion.py +112 -0
  3. ai_edge_torch/_convert/conversion_utils.py +64 -0
  4. ai_edge_torch/{convert → _convert}/converter.py +94 -48
  5. ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
  6. ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
  7. ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
  8. ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
  9. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
  10. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
  11. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
  12. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
  13. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
  14. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
  15. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
  16. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
  17. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
  18. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
  19. ai_edge_torch/_convert/signature.py +66 -0
  20. ai_edge_torch/_convert/test/test_convert.py +495 -0
  21. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  22. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  23. ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
  24. ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
  25. ai_edge_torch/config.py +27 -0
  26. ai_edge_torch/conftest.py +20 -0
  27. ai_edge_torch/debug/culprit.py +72 -40
  28. ai_edge_torch/debug/test/test_culprit.py +7 -5
  29. ai_edge_torch/debug/test/test_search_model.py +8 -7
  30. ai_edge_torch/debug/utils.py +14 -3
  31. ai_edge_torch/fx_pass_base.py +101 -0
  32. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
  33. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
  34. ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
  35. ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
  36. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  37. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
  38. ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
  39. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
  40. ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
  41. ai_edge_torch/generative/examples/openelm/verify.py +64 -0
  42. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  43. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
  44. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
  45. ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
  46. ai_edge_torch/generative/examples/phi/phi3.py +286 -0
  47. ai_edge_torch/generative/examples/phi/verify.py +65 -0
  48. ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
  49. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  50. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
  51. ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
  52. ai_edge_torch/generative/examples/smollm/verify.py +62 -0
  53. ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
  54. ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
  55. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
  56. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
  57. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
  58. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
  59. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
  60. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
  61. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
  62. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
  63. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
  64. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
  65. ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
  66. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
  67. ai_edge_torch/generative/examples/t5/t5.py +208 -159
  68. ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
  69. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  70. ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
  71. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
  72. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  73. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
  74. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
  75. ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
  76. ai_edge_torch/generative/fx_passes/__init__.py +4 -5
  77. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
  78. ai_edge_torch/generative/layers/attention.py +141 -102
  79. ai_edge_torch/generative/layers/attention_utils.py +53 -12
  80. ai_edge_torch/generative/layers/builder.py +37 -7
  81. ai_edge_torch/generative/layers/feed_forward.py +39 -14
  82. ai_edge_torch/generative/layers/kv_cache.py +162 -50
  83. ai_edge_torch/generative/layers/model_config.py +84 -30
  84. ai_edge_torch/generative/layers/normalization.py +185 -7
  85. ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
  86. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
  87. ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
  88. ai_edge_torch/generative/layers/unet/builder.py +7 -4
  89. ai_edge_torch/generative/layers/unet/model_config.py +17 -15
  90. ai_edge_torch/generative/quantize/example.py +7 -8
  91. ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
  92. ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
  93. ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
  94. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  95. ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
  96. ai_edge_torch/generative/test/test_model_conversion.py +124 -188
  97. ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
  98. ai_edge_torch/generative/test/test_quantize.py +76 -60
  99. ai_edge_torch/generative/test/utils.py +54 -0
  100. ai_edge_torch/generative/utilities/converter.py +82 -0
  101. ai_edge_torch/generative/utilities/loader.py +120 -57
  102. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
  103. ai_edge_torch/generative/utilities/t5_loader.py +110 -81
  104. ai_edge_torch/generative/utilities/verifier.py +247 -0
  105. ai_edge_torch/hlfb/__init__.py +1 -1
  106. ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
  107. ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
  108. ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
  109. ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
  110. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
  111. ai_edge_torch/lowertools/__init__.py +18 -0
  112. ai_edge_torch/lowertools/_shim.py +80 -0
  113. ai_edge_torch/lowertools/common_utils.py +142 -0
  114. ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
  115. ai_edge_torch/lowertools/test_utils.py +60 -0
  116. ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
  117. ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
  118. ai_edge_torch/model.py +53 -18
  119. ai_edge_torch/odml_torch/__init__.py +20 -0
  120. ai_edge_torch/odml_torch/_torch_future.py +61 -0
  121. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  122. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  123. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  124. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  125. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  126. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  127. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  128. ai_edge_torch/odml_torch/export.py +357 -0
  129. ai_edge_torch/odml_torch/export_utils.py +168 -0
  130. ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
  131. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
  132. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  133. ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
  134. ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
  135. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  136. ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
  137. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
  138. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
  139. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  140. ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
  141. ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
  142. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  143. ai_edge_torch/odml_torch/tf_integration.py +194 -0
  144. ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
  145. ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
  146. ai_edge_torch/quantize/quant_config.py +13 -9
  147. ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
  148. ai_edge_torch/version.py +16 -0
  149. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
  150. ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
  151. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
  152. ai_edge_torch/convert/conversion.py +0 -117
  153. ai_edge_torch/convert/conversion_utils.py +0 -400
  154. ai_edge_torch/convert/fx_passes/__init__.py +0 -59
  155. ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
  156. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
  157. ai_edge_torch/convert/test/test_convert.py +0 -311
  158. ai_edge_torch/convert/test/test_convert_composites.py +0 -192
  159. ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
  160. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
  161. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
  162. ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
  163. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
  164. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
  165. /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
  166. /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
  167. /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
  168. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
  169. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,234 @@
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 conversion modules that are meant to be wrapped as composites."""
16
+
17
+ from collections.abc import Callable
18
+
19
+ import ai_edge_torch
20
+ from ai_edge_torch.testing import model_coverage
21
+ import parameterized
22
+ import torch
23
+
24
+ from absl.testing import absltest as googletest
25
+
26
+
27
+ def _func_to_torch_module(func: Callable[..., torch.Tensor]):
28
+ """Wraps a function into a torch module."""
29
+
30
+ class TestModule(torch.nn.Module):
31
+
32
+ def __init__(self, func):
33
+ super().__init__()
34
+ self._func = func
35
+
36
+ def forward(self, *args, **kwargs):
37
+ return self._func(*args, **kwargs)
38
+
39
+ return TestModule(func).eval()
40
+
41
+
42
+ class TestConvertComposites(googletest.TestCase):
43
+ """Tests conversion modules that are meant to be wrapped as composites."""
44
+
45
+ def test_convert_hardswish(self):
46
+ """Tests conversion of a HardSwish module."""
47
+
48
+ args = (torch.randn((5, 10)),)
49
+ torch_module = torch.nn.Hardswish().eval()
50
+ edge_model = ai_edge_torch.convert(torch_module, args)
51
+
52
+ self.assertTrue(
53
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
54
+ )
55
+
56
+ @parameterized.parameterized.expand([
57
+ # (input_size, kernel_size, stride, padding, ceil_mode,
58
+ # count_include_pad, divisor_override)
59
+ # no padding, stride = 1
60
+ ([1, 3, 6, 6], [3, 3], [1, 1], [0, 0], False, True, None),
61
+ # add stride
62
+ ([1, 3, 6, 6], [3, 3], [2, 2], [0, 0], False, True, None),
63
+ # default values
64
+ ([1, 3, 6, 6], [3, 3]),
65
+ # add padding
66
+ ([1, 3, 6, 6], [3, 3], [1, 1], [1, 1], False, True, None),
67
+ # add different padding for different dims
68
+ ([1, 3, 6, 6], [3, 3], [1, 1], [0, 1], False, True, None),
69
+ # add both stride and padding
70
+ ([1, 3, 6, 6], [3, 3], [2, 2], [1, 1], False, True, None),
71
+ # padding set to one number
72
+ ([1, 3, 6, 6], [3, 3], [1, 1], 1, False, True, None),
73
+ # count_include_pad = False
74
+ ([1, 3, 6, 6], [3, 3], [1, 1], [1, 1], False, False, None),
75
+ # ceil_mode = True
76
+ ([1, 3, 6, 6], [3, 3], [1, 1], [1, 1], True, True, None),
77
+ # ceil_mode = True, stride=[3, 3]
78
+ ([1, 3, 6, 6], [3, 3], [3, 3], [1, 1], True, True, None),
79
+ # set divisor_override
80
+ ([1, 3, 6, 6], [3, 3], [1, 1], 0, False, True, 6),
81
+ ])
82
+ def test_convert_avg_pool2d(self, input_size, *args):
83
+ """Tests conversion of a module containing an avg_pool2d aten."""
84
+ torch_module = _func_to_torch_module(
85
+ lambda input_tensor: torch.ops.aten.avg_pool2d(input_tensor, *args)
86
+ )
87
+ tracing_args = (torch.randn(*input_size),)
88
+ edge_model = ai_edge_torch.convert(torch_module, tracing_args)
89
+
90
+ self.assertTrue(
91
+ model_coverage.compare_tflite_torch(
92
+ edge_model, torch_module, tracing_args
93
+ )
94
+ )
95
+
96
+ @parameterized.parameterized.expand([
97
+ # use scale_factor with align_corners=False
98
+ (
99
+ [1, 3, 10, 10],
100
+ dict(scale_factor=3.0, mode='bilinear', align_corners=False),
101
+ ),
102
+ # use scale_factor with align_corners=true
103
+ (
104
+ [1, 3, 10, 10],
105
+ dict(scale_factor=3.0, mode='bilinear', align_corners=True),
106
+ ),
107
+ # use size
108
+ ([1, 3, 10, 10], dict(size=[15, 20], mode='bilinear')),
109
+ # use size with align_corners=true
110
+ (
111
+ [1, 3, 10, 10],
112
+ dict(size=[15, 20], mode='bilinear', align_corners=True),
113
+ ),
114
+ ])
115
+ def test_convert_upsample_bilinear_functional(self, input_size, kwargs):
116
+ """Tests conversion of a torch.nn.functional.upsample module."""
117
+ torch_module = _func_to_torch_module(
118
+ lambda input_tensor: torch.nn.functional.upsample( # pylint: disable=unnecessary-lambda
119
+ input_tensor, **kwargs
120
+ )
121
+ )
122
+ tracing_args = (torch.randn(*input_size),)
123
+ edge_model = ai_edge_torch.convert(torch_module, tracing_args)
124
+
125
+ self.assertTrue(
126
+ model_coverage.compare_tflite_torch(
127
+ edge_model, torch_module, tracing_args
128
+ )
129
+ )
130
+
131
+ @parameterized.parameterized.expand([
132
+ # use scale_factor with align_corners=False
133
+ (
134
+ [1, 3, 10, 10],
135
+ dict(scale_factor=3.0, mode='bilinear', align_corners=False),
136
+ ),
137
+ # use scale_factor with align_corners=true
138
+ (
139
+ [1, 3, 10, 10],
140
+ dict(scale_factor=3.0, mode='bilinear', align_corners=True),
141
+ ),
142
+ # use size
143
+ ([1, 3, 10, 10], dict(size=[15, 20], mode='bilinear')),
144
+ # use size with align_corners=true
145
+ (
146
+ [1, 3, 10, 10],
147
+ dict(size=[15, 20], mode='bilinear', align_corners=True),
148
+ ),
149
+ ])
150
+ def test_convert_upsample_bilinear(self, input_size, kwargs):
151
+ """Tests conversion of a torch.nn.Upsample module."""
152
+ torch_module = _func_to_torch_module(
153
+ lambda input_tensor: torch.nn.Upsample(**kwargs)(input_tensor) # pylint: disable=unnecessary-lambda
154
+ )
155
+ tracing_args = (torch.randn(*input_size),)
156
+ edge_model = ai_edge_torch.convert(torch_module, tracing_args)
157
+
158
+ self.assertTrue(
159
+ model_coverage.compare_tflite_torch(
160
+ edge_model, torch_module, tracing_args
161
+ )
162
+ )
163
+
164
+ @parameterized.parameterized.expand([
165
+ # use scale_factor with align_corners=False
166
+ (
167
+ [1, 3, 10, 10],
168
+ dict(scale_factor=3.0, mode='bilinear', align_corners=False),
169
+ ),
170
+ # use scale_factor with align_corners=true
171
+ (
172
+ [1, 3, 10, 10],
173
+ dict(scale_factor=3.0, mode='bilinear', align_corners=True),
174
+ ),
175
+ # use size
176
+ ([1, 3, 10, 10], dict(size=[15, 20], mode='bilinear')),
177
+ # use size with align_corners=true
178
+ (
179
+ [1, 3, 10, 10],
180
+ dict(size=[15, 20], mode='bilinear', align_corners=True),
181
+ ),
182
+ ])
183
+ def test_convert_interpolate_bilinear_functional(self, input_size, kwargs):
184
+ """Tests conversion of a torch.nn.functional.interpolate module."""
185
+ torch_module = _func_to_torch_module(
186
+ lambda input_tensor: torch.nn.functional.interpolate( # pylint: disable=unnecessary-lambda
187
+ input_tensor, **kwargs
188
+ )
189
+ )
190
+ tracing_args = (torch.randn(*input_size),)
191
+ edge_model = ai_edge_torch.convert(torch_module, tracing_args)
192
+
193
+ self.assertTrue(
194
+ model_coverage.compare_tflite_torch(
195
+ edge_model, torch_module, tracing_args
196
+ )
197
+ )
198
+
199
+ def test_convert_gelu(self):
200
+ """Tests conversion of a GELU module."""
201
+
202
+ args = (torch.randn((5, 10)),)
203
+ torch_module = torch.nn.GELU().eval()
204
+ edge_model = ai_edge_torch.convert(torch_module, args)
205
+
206
+ self.assertTrue(
207
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
208
+ )
209
+
210
+ def test_convert_gelu_approximate(self):
211
+ """Tests conversion of an Approximate GELU module."""
212
+
213
+ args = (torch.randn((5, 10)),)
214
+ torch_module = torch.nn.GELU('tanh').eval()
215
+ edge_model = ai_edge_torch.convert(torch_module, args)
216
+
217
+ self.assertTrue(
218
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
219
+ )
220
+
221
+ def test_convert_embedding_lookup(self):
222
+ """Tests conversion of an Embedding module."""
223
+
224
+ args = (torch.full((1, 10), 0, dtype=torch.long),)
225
+ torch_module = torch.nn.Embedding(10, 10)
226
+ edge_model = ai_edge_torch.convert(torch_module, args)
227
+
228
+ self.assertTrue(
229
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
230
+ )
231
+
232
+
233
+ if __name__ == '__main__':
234
+ googletest.main()
@@ -0,0 +1,189 @@
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 multi-signature conversion."""
16
+
17
+ import ai_edge_torch
18
+ from ai_edge_torch.testing import model_coverage
19
+ import torch
20
+ from torch import nn
21
+
22
+ from absl.testing import absltest as googletest
23
+
24
+
25
+ class FullyConnectedModel(nn.Module):
26
+ """A simple fully connected model with two fully connected layers."""
27
+
28
+ def __init__(self, input_size, hidden_size, output_size):
29
+ super(FullyConnectedModel, self).__init__()
30
+ self.fc = nn.Linear(input_size, hidden_size) # Fully connected layer
31
+ self.relu = nn.ReLU() # Activation function
32
+ self.output = nn.Linear(hidden_size, output_size)
33
+
34
+ def forward(self, x):
35
+ x = self.fc(x)
36
+ x = self.relu(x)
37
+ x = self.output(x)
38
+ return x
39
+
40
+
41
+ class FullyConvModel(nn.Module):
42
+ """A simple fully convolutional model with two convolutions."""
43
+
44
+ def __init__(self):
45
+ super(FullyConvModel, self).__init__()
46
+ self.conv1 = nn.Conv2d(
47
+ 3, 16, kernel_size=3, padding=1
48
+ ) # Input channels: 3 (RGB), Output channels: 16
49
+ self.relu = nn.ReLU(inplace=True)
50
+ self.conv2 = nn.Conv2d(
51
+ 16, 1, kernel_size=1
52
+ ) # Output channels: 1 (single channel output)
53
+
54
+ def forward(self, x):
55
+ x = self.conv1(x)
56
+ x = self.relu(x)
57
+ x = self.conv2(x)
58
+ return x
59
+
60
+
61
+ class TestConvertMultiSignature(googletest.TestCase):
62
+ """Tests conversion of various modules through multi-signature conversion."""
63
+
64
+ def setUp(self):
65
+ super().setUp()
66
+ torch.manual_seed(0)
67
+
68
+ def test_convert_with_default(self):
69
+ """Tests conversion of a model with two signatures one of which is the default."""
70
+ torch_module = FullyConvModel().eval()
71
+
72
+ args = (torch.randn(4, 3, 12, 12),)
73
+ large_args = (torch.randn(4, 3, 24, 24),)
74
+
75
+ signature_name = "large_input"
76
+
77
+ edge_model = ai_edge_torch.signature(
78
+ signature_name, torch_module, large_args
79
+ ).convert(torch_module, args)
80
+
81
+ self.assertTrue(
82
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
83
+ )
84
+ self.assertTrue(
85
+ model_coverage.compare_tflite_torch(
86
+ edge_model, torch_module, large_args, signature_name=signature_name
87
+ )
88
+ )
89
+
90
+ def test_convert_no_default(self):
91
+ """Tests conversion of a model with two signatures none of which is the default."""
92
+ torch_module = FullyConvModel().eval()
93
+
94
+ args = (torch.randn(4, 3, 12, 12),)
95
+ large_args = (torch.randn(4, 3, 24, 24),)
96
+
97
+ signature_name_1 = "input"
98
+ signature_name_2 = "large_input"
99
+
100
+ edge_model = (
101
+ ai_edge_torch.signature(signature_name_1, torch_module, args)
102
+ .signature(signature_name_2, torch_module, large_args)
103
+ .convert()
104
+ )
105
+
106
+ with self.assertRaises(ValueError):
107
+ edge_model(*args)
108
+
109
+ self.assertTrue(
110
+ model_coverage.compare_tflite_torch(
111
+ edge_model, torch_module, args, signature_name=signature_name_1
112
+ )
113
+ )
114
+ self.assertTrue(
115
+ model_coverage.compare_tflite_torch(
116
+ edge_model,
117
+ torch_module,
118
+ large_args,
119
+ signature_name=signature_name_2,
120
+ )
121
+ )
122
+
123
+ def test_convert_signature_helper(self):
124
+ """Tests the ai_edge_torch.signature helper function works."""
125
+ torch_module = FullyConvModel().eval()
126
+
127
+ args = (torch.randn(4, 3, 12, 12),)
128
+ large_args = (torch.randn(4, 3, 24, 24),)
129
+
130
+ signature_name = "large_input"
131
+
132
+ edge_model = ai_edge_torch.signature(
133
+ signature_name, torch_module, large_args
134
+ ).convert(torch_module, args)
135
+
136
+ self.assertTrue(
137
+ model_coverage.compare_tflite_torch(edge_model, torch_module, args)
138
+ )
139
+ self.assertTrue(
140
+ model_coverage.compare_tflite_torch(
141
+ edge_model, torch_module, large_args, signature_name=signature_name
142
+ )
143
+ )
144
+
145
+ def test_convert_separate_modules(self):
146
+ """Tests conversion of two completely different modules as separate signatures."""
147
+ fully_conv = FullyConvModel().eval()
148
+ fully_connected = FullyConnectedModel(10, 5, 10).eval()
149
+
150
+ fully_conv_args = (torch.randn(4, 3, 12, 12),)
151
+ fully_connected_args = (torch.randn(10),)
152
+
153
+ fully_conv_signature_name = "fully_conv"
154
+ fully_connected_signature_name = "fully_connected"
155
+
156
+ edge_model = (
157
+ ai_edge_torch.signature(
158
+ fully_conv_signature_name, fully_conv, fully_conv_args
159
+ )
160
+ .signature(
161
+ fully_connected_signature_name,
162
+ fully_connected,
163
+ fully_connected_args,
164
+ )
165
+ .convert(fully_connected, fully_connected_args)
166
+ )
167
+
168
+ fully_conv_inference_args = (torch.randn(4, 3, 12, 12),)
169
+ fully_connected_inference_args = (torch.randn(10),)
170
+ self.assertTrue(
171
+ model_coverage.compare_tflite_torch(
172
+ edge_model,
173
+ fully_conv,
174
+ fully_conv_inference_args,
175
+ signature_name=fully_conv_signature_name,
176
+ )
177
+ )
178
+ self.assertTrue(
179
+ model_coverage.compare_tflite_torch(
180
+ edge_model,
181
+ fully_connected,
182
+ fully_connected_inference_args,
183
+ signature_name=fully_connected_signature_name,
184
+ )
185
+ )
186
+
187
+
188
+ if __name__ == "__main__":
189
+ googletest.main()
@@ -12,12 +12,12 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Tests for to_channel_last_io API and module wrapper."""
15
16
 
16
- import unittest
17
-
17
+ import ai_edge_torch
18
18
  import torch
19
19
 
20
- import ai_edge_torch
20
+ from absl.testing import absltest as googletest
21
21
 
22
22
 
23
23
  class Identity(torch.nn.Module):
@@ -26,7 +26,7 @@ class Identity(torch.nn.Module):
26
26
  return x
27
27
 
28
28
 
29
- class TestToChannelLastIO(unittest.TestCase):
29
+ class TestToChannelLastIO(googletest.TestCase):
30
30
  """Tests to_channel_last_io API and module wrapper."""
31
31
 
32
32
  def test_no_transformations(self):
@@ -93,4 +93,4 @@ class TestToChannelLastIO(unittest.TestCase):
93
93
 
94
94
 
95
95
  if __name__ == "__main__":
96
- unittest.main()
96
+ googletest.main()
@@ -12,6 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Transforms the input and output of a module to channel last layout."""
15
16
 
16
17
  from typing import Optional
17
18
 
@@ -31,7 +32,9 @@ class ChannelLastIOWrapper(nn.Module):
31
32
  if not torch.is_tensor(x):
32
33
  raise ValueError("Input must be a torch tensor")
33
34
  if x.ndim < 3:
34
- raise ValueError("Input must be a tensor with rank >= 3 in layout (N, C, ...)")
35
+ raise ValueError(
36
+ "Input must be a tensor with rank >= 3 in layout (N, C, ...)"
37
+ )
35
38
  dims = [0, *range(2, x.ndim), 1]
36
39
  return torch.permute(x, dims)
37
40
 
@@ -39,7 +42,9 @@ class ChannelLastIOWrapper(nn.Module):
39
42
  if not torch.is_tensor(x):
40
43
  raise ValueError("Input must be a torch tensor.")
41
44
  if x.ndim < 3:
42
- raise ValueError("Input must be a tensor with rank >= 3 in layout (N, ..., C)")
45
+ raise ValueError(
46
+ "Input must be a tensor with rank >= 3 in layout (N, ..., C)"
47
+ )
43
48
  dims = [0, x.ndim - 1, *range(1, x.ndim - 1)]
44
49
  return torch.permute(x, dims)
45
50
 
@@ -78,8 +83,10 @@ def to_channel_last_io(
78
83
  (N, C, ...) to channel last (N, ..., C).
79
84
  outputs (list[int]): Transform outputs with indices in the list from channel
80
85
  first (N, C, ...) to channel last (N, ..., C).
86
+
81
87
  Returns:
82
- The wrapped nn.Module with additional layout transposes after inputs and/or before
88
+ The wrapped nn.Module with additional layout transposes after inputs and/or
89
+ before
83
90
  outputs.
84
91
  """
85
92
  return ChannelLastIOWrapper(module, args=args, outputs=outputs)
@@ -0,0 +1,27 @@
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
+ """Provides a configuration for the AI Edge Torch library."""
17
+
18
+ import dataclasses
19
+ import os
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class Config:
24
+ use_torch_xla: bool = os.environ.get("USE_TORCH_XLA", "true").lower() in (
25
+ "1",
26
+ "true",
27
+ )
@@ -0,0 +1,20 @@
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 absl import flags
17
+
18
+
19
+ def pytest_configure(config):
20
+ flags.FLAGS.mark_as_parsed()