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,255 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ import dataclasses
17
+ import tempfile
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ from ai_edge_torch import odml_torch
21
+ from ai_edge_torch._convert import conversion_utils
22
+ from ai_edge_torch._convert import signature as signature_module
23
+ from ai_edge_torch.lowertools import common_utils
24
+ from ai_edge_torch.lowertools import translate_recipe
25
+ from ai_edge_torch.odml_torch import export
26
+ from ai_edge_torch.odml_torch import export_utils
27
+ from ai_edge_torch.quantize import quant_config as qcfg
28
+ import tensorflow as tf
29
+ import torch
30
+
31
+ from tensorflow.compiler.tf2xla.python import xla as tfxla
32
+ from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metadata_fb
33
+
34
+ MlirBundle = odml_torch.export.MlirLowered
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class MergedBundle:
39
+ """A bundle of MlirLowered that has been merged."""
40
+
41
+ bundles: list[odml_torch.export.MlirLowered]
42
+ exported_programs: list[torch.export.ExportedProgram]
43
+ deduped_tf_vars: list[tf.Variable]
44
+
45
+
46
+ def torch_dtype_to_tf(dtype):
47
+ return {
48
+ torch.double: tf.float64,
49
+ torch.float32: tf.float32,
50
+ torch.half: tf.float16,
51
+ torch.long: tf.int64,
52
+ torch.int32: tf.int32,
53
+ torch.int16: tf.int16,
54
+ torch.bool: tf.bool,
55
+ }.get(dtype)
56
+
57
+
58
+ def _get_shape_with_dynamic(signature: export.VariableSignature):
59
+ return [
60
+ None if export_utils.is_torch_dynamic(s) else s for s in signature.shape
61
+ ]
62
+
63
+
64
+ def _extract_call_args(
65
+ bundle: export.MlirLowered,
66
+ args: Tuple[Any],
67
+ tf_state_dict: Dict[str, tf.Variable],
68
+ ):
69
+ call_args = []
70
+ for sig in bundle.input_signature:
71
+ if sig.input_spec.is_user_input:
72
+ call_args.append(args[sig.input_spec.i])
73
+ elif sig.input_spec.is_parameter:
74
+ name = sig.input_spec.name
75
+ call_args.append(tf_state_dict[name])
76
+ return call_args
77
+
78
+
79
+ def _wrap_as_tf_func(
80
+ bundle: export.MlirLowered,
81
+ tf_state_dict: Dict[str, tf.Variable],
82
+ exported_program: torch.export.ExportedProgram,
83
+ ):
84
+ def inner(*args):
85
+ t_outs = [torch_dtype_to_tf(sig.dtype) for sig in bundle.output_signature]
86
+ s_outs = [_get_shape_with_dynamic(sig) for sig in bundle.output_signature]
87
+ call_args = _extract_call_args(bundle, args, tf_state_dict)
88
+ # HACK: In OSS, we use MLIR pybinding and StableHLO dialect from JAX's
89
+ # build, which may not have the same StableHLO version as what used in
90
+ # TFLite converter. Therefore we always serialize MLIR module in VHLO.
91
+ # TODO(b/362798610) Build MLIR pybinding in ai-edge-torch release.
92
+ call_module_return = tfxla.call_module(
93
+ tuple(call_args),
94
+ version=5,
95
+ Tout=t_outs, # dtype information
96
+ Sout=s_outs, # Shape information
97
+ function_list=[],
98
+ module=bundle.module_bytecode_vhlo,
99
+ )
100
+ spec = exported_program.call_spec.out_spec
101
+
102
+ # The module returning a flat array.
103
+ if not spec.context:
104
+ return call_module_return
105
+
106
+ flat_names = common_utils.flat_dict_names(spec.children_specs, spec.context)
107
+ return {name: value for name, value in zip(flat_names, call_module_return)}
108
+
109
+ return inner
110
+
111
+
112
+ def _make_tf_signature(
113
+ input_signature: list[export.VariableSignature],
114
+ signature: signature_module.Signature,
115
+ ) -> List[tf.TensorSpec]:
116
+ input_names = signature.flat_arg_names
117
+ user_input_signature = sorted(
118
+ [sig for sig in input_signature if sig.input_spec.is_user_input],
119
+ key=lambda sig: sig.input_spec.i,
120
+ )
121
+ tf_signature = []
122
+
123
+ for sig in user_input_signature:
124
+ shape = _get_shape_with_dynamic(sig)
125
+ tf_signature.append(
126
+ tf.TensorSpec(
127
+ shape=shape,
128
+ dtype=torch_dtype_to_tf(sig.dtype),
129
+ name=input_names[sig.input_spec.i],
130
+ )
131
+ )
132
+ return tf_signature
133
+
134
+
135
+ def merged_bundle_to_tfl_model(
136
+ merged_bundle: MergedBundle,
137
+ signatures: list[signature_module.Signature],
138
+ *,
139
+ quant_config: Optional[qcfg.QuantConfig] = None,
140
+ _tfl_converter_flags: dict = {},
141
+ ):
142
+ tf_state_dict = merged_bundle.bundles[0].state_dict
143
+
144
+ tf_signatures = [
145
+ _make_tf_signature(bundle.input_signature, sig)
146
+ for bundle, sig in zip(merged_bundle.bundles, signatures)
147
+ ]
148
+ tf_functions = [
149
+ _wrap_as_tf_func(bundle, tf_state_dict, ep)
150
+ for bundle, ep in zip(
151
+ merged_bundle.bundles, merged_bundle.exported_programs
152
+ )
153
+ ]
154
+
155
+ tf_module = tf.Module()
156
+ tf_module.f = []
157
+
158
+ for tf_sig, func in zip(tf_signatures, tf_functions):
159
+ tf_module.f.append(
160
+ tf.function(
161
+ func,
162
+ input_signature=tf_sig,
163
+ )
164
+ )
165
+
166
+ tf_module._variables = merged_bundle.deduped_tf_vars
167
+
168
+ tf_concrete_funcs = [
169
+ func.get_concrete_function(*tf_sig)
170
+ for func, tf_sig in zip(tf_module.f, tf_signatures)
171
+ ]
172
+
173
+ # We need to temporarily save since TFLite's from_concrete_functions does not
174
+ # allow providing names for each of the concrete functions.
175
+ with tempfile.TemporaryDirectory() as temp_dir_path:
176
+ tf.saved_model.save(
177
+ tf_module,
178
+ temp_dir_path,
179
+ signatures={
180
+ sig.name: tf_concrete_funcs[idx]
181
+ for idx, sig in enumerate(signatures)
182
+ },
183
+ )
184
+
185
+ converter = tf.lite.TFLiteConverter.from_saved_model(temp_dir_path)
186
+ converter._set_original_model_type(conversion_metadata_fb.ModelType.PYTORCH)
187
+ converter._experimental_enable_composite_direct_lowering = True
188
+ converter.model_origin_framework = "PYTORCH"
189
+
190
+ conversion_utils.set_tfl_converter_quant_flags(converter, quant_config)
191
+ if (
192
+ quant_config is not None
193
+ and quant_config._quantizer_mode
194
+ == quant_config._QuantizerMode.AI_EDGE_QUANTIZER
195
+ ):
196
+ translated_recipe = translate_recipe.translate_to_ai_edge_recipe(
197
+ quant_config.generative_recipe
198
+ )
199
+
200
+ conversion_utils.apply_tfl_converter_flags(converter, _tfl_converter_flags)
201
+
202
+ tflite_model = converter.convert()
203
+
204
+ if (
205
+ quant_config is not None
206
+ and quant_config._quantizer_mode
207
+ == quant_config._QuantizerMode.AI_EDGE_QUANTIZER
208
+ ):
209
+ tflite_model = translate_recipe.quantize_model(
210
+ tflite_model, translated_recipe
211
+ )
212
+
213
+ return tflite_model
214
+
215
+
216
+ def exported_program_to_mlir_text(
217
+ exported_program: torch.export.ExportedProgram,
218
+ ) -> str:
219
+ """Converts a ExportedProgram to a MLIR text."""
220
+ return odml_torch.export.exported_program_to_mlir(exported_program).get_text(
221
+ enable_debug_info=True
222
+ )
223
+
224
+
225
+ def exported_program_to_mlir(
226
+ exported_program: torch.export.ExportedProgram,
227
+ sample_args: tuple[torch.Tensor],
228
+ ) -> export.MlirLowered:
229
+ """Converts a ExportedProgram to a MlirLowered."""
230
+ return odml_torch.export.exported_program_to_mlir(exported_program)
231
+
232
+
233
+ def merge_mlir_bundles(
234
+ bundles: list[export.MlirLowered],
235
+ signatures: list[signature_module.Signature],
236
+ exported_programs: list[torch.export.ExportedProgram],
237
+ ) -> MergedBundle:
238
+ """Merges a list of MlirLowered into one."""
239
+ state_dict, deduped_vars = common_utils.gather_state_dict(
240
+ exported_programs, signatures
241
+ )
242
+
243
+ merged_bundle = MergedBundle(
244
+ bundles=bundles.copy(),
245
+ exported_programs=exported_programs,
246
+ deduped_tf_vars=deduped_vars,
247
+ )
248
+ for bundle, signature in zip(merged_bundle.bundles, signatures):
249
+ bundle.state_dict = state_dict
250
+
251
+ for var_sig in bundle.input_signature:
252
+ if var_sig.input_spec.is_parameter:
253
+ var_sig.input_spec.name = signature.name + "_" + var_sig.input_spec.name
254
+
255
+ return merged_bundle
@@ -0,0 +1,60 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ import re
17
+ from typing import Optional
18
+ from ai_edge_torch import config
19
+ from absl.testing import absltest as googletest
20
+
21
+
22
+ def _extract_backend_configs(mlir):
23
+ mlir = mlir.replace("\\22", '"')
24
+ configs = []
25
+ for match in re.finditer(r"backend_config\s*=\s*\"(\{.*\})\"", mlir):
26
+ configs.append(match.group(1))
27
+ return "\n".join(configs)
28
+
29
+
30
+ def assert_string_count(
31
+ test_case: googletest.TestCase,
32
+ mlir: str,
33
+ torch_xla_pattern_counter: dict[str, int],
34
+ odml_torch_pattern_counter: dict[str, int],
35
+ odml_torch_attr_counter: Optional[dict[str, int]] = None,
36
+ ):
37
+
38
+ if odml_torch_attr_counter is None:
39
+ odml_torch_attr_counter = {}
40
+
41
+ if config.Config.use_torch_xla:
42
+ for key in torch_xla_pattern_counter:
43
+ test_case.assertEqual(
44
+ mlir.count(key),
45
+ torch_xla_pattern_counter[key],
46
+ )
47
+ else:
48
+ for key in odml_torch_pattern_counter:
49
+ test_case.assertEqual(
50
+ mlir.count(key),
51
+ odml_torch_pattern_counter[key],
52
+ )
53
+ backend_configs = _extract_backend_configs(mlir)
54
+ print("backend_configs:")
55
+ print(backend_configs)
56
+ for key in odml_torch_attr_counter:
57
+ test_case.assertEqual(
58
+ backend_configs.count(key),
59
+ odml_torch_attr_counter[key],
60
+ )
@@ -0,0 +1,284 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ import copy
17
+ import dataclasses
18
+ from dataclasses import dataclass
19
+ import gc
20
+ import itertools
21
+ import logging
22
+ import tempfile
23
+ from typing import Any, Dict, Optional, Tuple, Union
24
+
25
+ from ai_edge_torch import model
26
+ from ai_edge_torch._convert import conversion_utils
27
+ from ai_edge_torch._convert import signature as signature_module
28
+ from ai_edge_torch.lowertools import common_utils
29
+ from ai_edge_torch.lowertools import translate_recipe
30
+ from ai_edge_torch.quantize import quant_config as qcfg
31
+ import torch
32
+ from torch_xla import stablehlo
33
+
34
+ try:
35
+ import tensorflow as tf
36
+
37
+ from tensorflow.compiler.tf2xla.python import xla as tfxla
38
+
39
+ from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metadata_fb # isort:skip
40
+ except ImportError:
41
+ logging.error(
42
+ "This module needs tensorflow with xla support.\n"
43
+ "Please install tensorflow with `pip install tf-nightly`.\n"
44
+ )
45
+ raise
46
+
47
+ MlirBundle = stablehlo.StableHLOModelBundle
48
+
49
+
50
+ @dataclasses.dataclass
51
+ class MergedBundle:
52
+
53
+ bundle: stablehlo.StableHLOModelBundle
54
+ exported_programs: list[torch.export.ExportedProgram]
55
+ deduped_tf_vars: list[tf.Variable]
56
+
57
+
58
+ def exported_program_to_mlir(
59
+ exported_program: torch.export.ExportedProgram,
60
+ sample_args: tuple[torch.Tensor],
61
+ ) -> stablehlo.StableHLOModelBundle:
62
+ # Setting export_weights to False here so that pytorch/xla avoids copying the
63
+ # weights to a numpy array which would lead to memory bloat. This means that
64
+ # the state_dict in the returned bundle is going to be empty.
65
+ return stablehlo.exported_program_to_stablehlo(
66
+ exported_program,
67
+ stablehlo.StableHLOExportOptions(
68
+ override_tracing_arguments=sample_args, export_weights=False
69
+ ),
70
+ )._bundle
71
+
72
+
73
+ def merge_mlir_bundles(
74
+ bundles: list[stablehlo.StableHLOModelBundle],
75
+ signatures: list[signature_module.Signature],
76
+ exported_programs: list[torch.export.ExportedProgram],
77
+ ) -> stablehlo.StableHLOGraphModule:
78
+ state_dict, deduped_tf_vars = common_utils.gather_state_dict(
79
+ exported_programs, signatures
80
+ )
81
+
82
+ new_shlo_model_bundle = stablehlo.StableHLOModelBundle(
83
+ state_dict=state_dict, additional_constants=[], stablehlo_funcs=[]
84
+ )
85
+
86
+ for bundle, signature in zip(bundles, signatures):
87
+ const_offset = len(new_shlo_model_bundle.additional_constants)
88
+ for func in bundle.stablehlo_funcs:
89
+ func.meta.name = signature.name + "_" + func.meta.name
90
+ for loc in func.meta.input_locations:
91
+ if loc.type_ == stablehlo.VariableType.CONSTANT:
92
+ loc.position += const_offset
93
+ elif loc.type_ == stablehlo.VariableType.PARAMETER:
94
+ loc.name = signature.name + "_" + loc.name
95
+ new_shlo_model_bundle.stablehlo_funcs.append(func)
96
+ new_shlo_model_bundle.additional_constants.extend(
97
+ bundle.additional_constants
98
+ )
99
+ return MergedBundle(
100
+ bundle=new_shlo_model_bundle,
101
+ exported_programs=exported_programs,
102
+ deduped_tf_vars=deduped_tf_vars,
103
+ )
104
+
105
+
106
+ def _get_shape_with_dynamic(signature: stablehlo.VariableSignature):
107
+ shape = copy.copy(signature.shape)
108
+ for i in signature.dynamic_dims:
109
+ shape[i] = None
110
+ return shape
111
+
112
+
113
+ def _wrap_as_tf_func(
114
+ func: stablehlo.StableHLOFunc,
115
+ bundle: stablehlo.StableHLOModelBundle,
116
+ exported_program: torch.export.ExportedProgram,
117
+ ):
118
+ def inner(*args):
119
+ type_info = [sig.dtype for sig in func.meta.output_signature]
120
+ shape_info = [
121
+ _get_shape_with_dynamic(sig) for sig in func.meta.output_signature
122
+ ]
123
+ call_args = stablehlo._extract_call_parameters(args, func.meta, bundle)
124
+ call_module_return = tfxla.call_module(
125
+ tuple(call_args),
126
+ version=5,
127
+ Tout=type_info,
128
+ Sout=shape_info,
129
+ function_list=[],
130
+ module=func.bytecode,
131
+ )
132
+ spec = exported_program.call_spec.out_spec
133
+
134
+ # The module returning a flat array.
135
+ if not spec.context:
136
+ return call_module_return
137
+
138
+ flat_names = common_utils.flat_dict_names(spec.children_specs, spec.context)
139
+ return {name: value for name, value in zip(flat_names, call_module_return)}
140
+
141
+ return inner
142
+
143
+
144
+ def _make_tf_signature(
145
+ meta: stablehlo.StableHLOFunctionMeta,
146
+ signature: signature_module.Signature,
147
+ ) -> list[tf.TensorSpec]:
148
+ input_names = signature.flat_arg_names
149
+ input_pos_to_spec = {
150
+ loc.position: spec
151
+ for loc, spec in itertools.chain(
152
+ zip(meta.input_locations, meta.input_signature), meta.unused_inputs
153
+ )
154
+ if loc.type_ == stablehlo.VariableType.INPUT_ARG
155
+ }
156
+ assert len(input_pos_to_spec) == len(input_names)
157
+
158
+ primitive_type_to_tf_type = {"int": "int32", "float": "float32"}
159
+ ret: list[tf.TensorSpec] = []
160
+ for i, name in enumerate(input_names):
161
+ spec = input_pos_to_spec[i]
162
+ shape = _get_shape_with_dynamic(spec)
163
+ ret.append(
164
+ tf.TensorSpec(
165
+ shape=shape,
166
+ dtype=primitive_type_to_tf_type[spec.dtype]
167
+ if spec.dtype in primitive_type_to_tf_type
168
+ else spec.dtype,
169
+ name=name,
170
+ )
171
+ )
172
+ return ret
173
+
174
+
175
+ def exported_program_to_mlir_text(
176
+ exported_program: torch.export.ExportedProgram,
177
+ ) -> str:
178
+ """Converts a ExportedProgram to a MLIR text."""
179
+ return stablehlo.exported_program_to_stablehlo(
180
+ exported_program
181
+ ).get_stablehlo_text()
182
+
183
+
184
+ def merged_bundle_to_tfl_model(
185
+ merged_bundle: MergedBundle,
186
+ signatures: list[signature_module.Signature],
187
+ *,
188
+ quant_config: Optional[qcfg.QuantConfig] = None,
189
+ _tfl_converter_flags: dict = {},
190
+ ) -> None:
191
+ """Converts a StableHLOGraphModule to a tflite model.
192
+
193
+ Args: shlo_bundle - model to export and save
194
+
195
+ signatures: List of signatures from which names of the signatures is
196
+ extracted.
197
+ quant_config: User-defined quantization method and scheme of the model.
198
+ _tfl_converter_flags: A nested dictionary allowing setting flags for the
199
+ underlying tflite converter.
200
+ """
201
+
202
+ tf_module = tf.Module()
203
+
204
+ shlo_bundle = merged_bundle.bundle
205
+
206
+ shlo_bundle.additional_constants = [
207
+ tf.Variable(v, trainable=False) for v in shlo_bundle.additional_constants
208
+ ]
209
+ tf_signatures: list[list[tf.TensorSpec]] = list(
210
+ _make_tf_signature(func.meta, sig)
211
+ for func, sig in zip(shlo_bundle.stablehlo_funcs, signatures)
212
+ )
213
+
214
+ tf_functions = [
215
+ _wrap_as_tf_func(func, shlo_bundle, ep)
216
+ for func, ep in zip(
217
+ shlo_bundle.stablehlo_funcs, merged_bundle.exported_programs
218
+ )
219
+ ]
220
+
221
+ tf_module.f = []
222
+ for tf_sig, func in zip(tf_signatures, tf_functions):
223
+ tf_module.f.append(
224
+ tf.function(
225
+ func,
226
+ input_signature=tf_sig,
227
+ )
228
+ )
229
+
230
+ tf_module._variables = (
231
+ merged_bundle.deduped_tf_vars + shlo_bundle.additional_constants
232
+ )
233
+ del shlo_bundle
234
+ gc.collect()
235
+
236
+ tf_concrete_funcs = [
237
+ func.get_concrete_function(*tf_sig)
238
+ for func, tf_sig in zip(tf_module.f, tf_signatures)
239
+ ]
240
+
241
+ # We need to temporarily save since TFLite's from_concrete_functions does not
242
+ # allow providing names for each of the concrete functions.
243
+ with tempfile.TemporaryDirectory() as temp_dir_path:
244
+ tf.saved_model.save(
245
+ tf_module,
246
+ temp_dir_path,
247
+ signatures={
248
+ sig.name: tf_concrete_funcs[idx]
249
+ for idx, sig in enumerate(signatures)
250
+ },
251
+ )
252
+ # Clean up intermediate memory early.
253
+ del tf_module
254
+ del tf_concrete_funcs
255
+ gc.collect()
256
+
257
+ converter = tf.lite.TFLiteConverter.from_saved_model(temp_dir_path)
258
+ converter._set_original_model_type(conversion_metadata_fb.ModelType.PYTORCH)
259
+ converter._experimental_enable_composite_direct_lowering = True
260
+
261
+ conversion_utils.set_tfl_converter_quant_flags(converter, quant_config)
262
+ if (
263
+ quant_config is not None
264
+ and quant_config._quantizer_mode
265
+ == quant_config._QuantizerMode.AI_EDGE_QUANTIZER
266
+ ):
267
+ translated_recipe = translate_recipe.translate_to_ai_edge_recipe(
268
+ quant_config.generative_recipe
269
+ )
270
+
271
+ conversion_utils.apply_tfl_converter_flags(converter, _tfl_converter_flags)
272
+
273
+ tflite_model = converter.convert()
274
+
275
+ if (
276
+ quant_config is not None
277
+ and quant_config._quantizer_mode
278
+ == quant_config._QuantizerMode.AI_EDGE_QUANTIZER
279
+ ):
280
+ tflite_model = translate_recipe.quantize_model(
281
+ tflite_model, translated_recipe
282
+ )
283
+
284
+ return tflite_model
@@ -13,14 +13,12 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
- import json
17
-
18
16
  from ai_edge_quantizer import quantizer
19
-
20
17
  from ai_edge_torch.generative.quantize import quant_attrs
21
18
  from ai_edge_torch.generative.quantize import quant_recipe
22
19
 
23
- _OpExecutionMode = quantizer.qtyping.OpExecutionMode
20
+ _ComputePrecision = quantizer.qtyping.ComputePrecision
21
+ _QuantGranularity = quantizer.qtyping.QuantGranularity
24
22
  _OpName = quantizer.qtyping.TFLOperationName
25
23
  _TensorQuantConfig = quantizer.qtyping.TensorQuantizationConfig
26
24
  _OpQuantConfig = quantizer.qtyping.OpQuantizationConfig
@@ -44,26 +42,40 @@ def _get_nbits_from_dtype(dtype: quant_attrs.Dtype) -> int:
44
42
  raise ValueError('Unimplemented number of bits')
45
43
 
46
44
 
47
- def _get_dtype_from_dtype(dtype: quant_attrs.Dtype) -> quantizer.qtyping.TensorDataType:
45
+ def _get_dtype_from_dtype(
46
+ dtype: quant_attrs.Dtype,
47
+ ) -> quantizer.qtyping.TensorDataType:
48
48
  if dtype == quant_attrs.Dtype.FP32 or dtype == quant_attrs.Dtype.FP16:
49
49
  return quantizer.qtyping.TensorDataType.FLOAT
50
50
  else:
51
51
  return quantizer.qtyping.TensorDataType.INT
52
52
 
53
53
 
54
- def _get_execution_mode_from_mode(mode: quant_attrs.Mode) -> _OpExecutionMode:
54
+ def _get_compute_precision_from_mode(
55
+ mode: quant_attrs.Mode,
56
+ ) -> _ComputePrecision:
55
57
  if mode == quant_attrs.Mode.DYNAMIC_RANGE:
56
- return _OpExecutionMode.DRQ
58
+ return _ComputePrecision.INTEGER
57
59
  elif mode == quant_attrs.Mode.WEIGHT_ONLY:
58
- return _OpExecutionMode.WEIGHT_ONLY
60
+ return _ComputePrecision.FLOAT
59
61
  raise ValueError('Unimplemented execution mode')
60
62
 
61
63
 
62
- def _get_channelwise_from_granularity(granularity: quant_attrs.Granularity) -> bool:
63
- if granularity == quant_attrs.Granularity.CHANNELWISE:
64
- return True
65
- elif granularity == quant_attrs.Granularity.NONE:
64
+ def _get_explicit_dequant_from_mode(mode: quant_attrs.Mode) -> bool:
65
+ if mode == quant_attrs.Mode.DYNAMIC_RANGE:
66
66
  return False
67
+ elif mode == quant_attrs.Mode.WEIGHT_ONLY:
68
+ return True
69
+ raise ValueError('Unimplemented execution mode')
70
+
71
+
72
+ def _get_granularity(
73
+ granularity: quant_attrs.Granularity,
74
+ ) -> bool:
75
+ if granularity == quant_attrs.Granularity.CHANNELWISE:
76
+ return _QuantGranularity.CHANNELWISE
77
+ if granularity == quant_attrs.Granularity.NONE:
78
+ return _QuantGranularity.TENSORWISE
67
79
  raise ValueError('Unimplemented granularity')
68
80
 
69
81
 
@@ -87,10 +99,13 @@ def _set_quant_config(
87
99
  weight_tensor_config=_TensorQuantConfig(
88
100
  num_bits=_get_nbits_from_dtype(layer_recipe.weight_dtype),
89
101
  symmetric=True,
90
- channel_wise=_get_channelwise_from_granularity(layer_recipe.granularity),
102
+ granularity=_get_granularity(layer_recipe.granularity),
91
103
  dtype=_get_dtype_from_dtype(layer_recipe.weight_dtype),
92
104
  ),
93
- execution_mode=_get_execution_mode_from_mode(layer_recipe.mode),
105
+ compute_precision=_get_compute_precision_from_mode(layer_recipe.mode),
106
+ explicit_dequantize=_get_explicit_dequant_from_mode(
107
+ layer_recipe.mode
108
+ ),
94
109
  ),
95
110
  algorithm_key=_get_algorithm_key_from_algorithm(layer_recipe.algorithm),
96
111
  )