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
ai_edge_torch/__init__.py CHANGED
@@ -13,10 +13,11 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
 
16
- from .convert.converter import convert
17
- from .convert.converter import signature
18
- from .convert.to_channel_last_io import to_channel_last_io
19
- from .model import Model
16
+ from ai_edge_torch._convert.converter import convert
17
+ from ai_edge_torch._convert.converter import signature
18
+ from ai_edge_torch._convert.to_channel_last_io import to_channel_last_io
19
+ from ai_edge_torch.model import Model
20
+ from ai_edge_torch.version import __version__
20
21
 
21
22
 
22
23
  def load(path: str) -> Model:
@@ -0,0 +1,112 @@
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 logging
17
+ import os
18
+ from typing import Any, Optional
19
+
20
+ from ai_edge_torch import fx_pass_base
21
+ from ai_edge_torch import lowertools
22
+ from ai_edge_torch import model
23
+ from ai_edge_torch._convert import fx_passes
24
+ from ai_edge_torch._convert import signature
25
+ from ai_edge_torch.generative import fx_passes as generative_fx_passes
26
+ from ai_edge_torch.quantize import quant_config as qcfg
27
+ import torch
28
+
29
+ os.environ["EXPERIMENTAL_XLA_UNBOUNDED_DYNAMISM"] = "1"
30
+
31
+
32
+ def _run_convert_passes(
33
+ exported_program: torch.export.ExportedProgram,
34
+ ) -> torch.export.ExportedProgram:
35
+ exported_program = generative_fx_passes.run_generative_passes(
36
+ exported_program
37
+ )
38
+ return fx_pass_base.run_passes(
39
+ exported_program,
40
+ [
41
+ fx_passes.BuildInterpolateCompositePass(),
42
+ fx_passes.CanonicalizePass(),
43
+ fx_passes.OptimizeLayoutTransposesPass(),
44
+ fx_passes.CanonicalizePass(),
45
+ fx_passes.BuildAtenCompositePass(),
46
+ fx_passes.CanonicalizePass(),
47
+ fx_passes.InjectMlirDebuginfoPass(),
48
+ fx_passes.CanonicalizePass(),
49
+ ],
50
+ )
51
+
52
+
53
+ def _warn_training_modules(signatures: list[signature.Signature]):
54
+ """Warns the user if the module is in training mode (.eval not called)."""
55
+ for sig in signatures:
56
+ if not sig.module.training:
57
+ continue
58
+
59
+ message = (
60
+ "Your model {sig_name}is converted in training mode. Please set the"
61
+ " module in evaluation mode with `module.eval()` for better on-device"
62
+ " performance and compatibility."
63
+ )
64
+ if len(signatures) == 1 and sig.name == model.DEFAULT_SIGNATURE_NAME:
65
+ # User does not specify any signature names explicitly.
66
+ message = message.format(sig_name="")
67
+ else:
68
+ message = message.format(sig_name=f'"{sig.name}" ')
69
+
70
+ logging.warning(message)
71
+
72
+
73
+ def convert_signatures(
74
+ signatures: list[signature.Signature],
75
+ *,
76
+ quant_config: Optional[qcfg.QuantConfig] = None,
77
+ _tfl_converter_flags: Optional[dict[str, Any]],
78
+ ) -> model.TfLiteModel:
79
+ """Converts a list of `signature.Signature`s and embeds them into one `model.TfLiteModel`.
80
+
81
+ Args:
82
+ signatures: The list of 'signature.Signature' objects containing PyTorch
83
+ modules to be converted.
84
+ quant_config: User-defined quantization method and scheme of the model.
85
+ _tfl_converter_flags: A nested dictionary allowing setting flags for the
86
+ underlying tflite converter.
87
+
88
+ Returns:
89
+ The converted `model.TfLiteModel` object.
90
+ """
91
+ if _tfl_converter_flags is None:
92
+ _tfl_converter_flags = {}
93
+
94
+ _warn_training_modules(signatures)
95
+
96
+ exported_programs: torch.export.torch.export.ExportedProgram = [
97
+ torch.export.export(
98
+ sig.module, sig.flat_args, dynamic_shapes=sig.dynamic_shapes
99
+ )
100
+ for sig in signatures
101
+ ]
102
+
103
+ # Apply default fx passes
104
+ exported_programs = list(map(_run_convert_passes, exported_programs))
105
+ tflite_model = lowertools.exported_programs_to_tflite(
106
+ exported_programs,
107
+ signatures,
108
+ quant_config=quant_config,
109
+ _tfl_converter_flags=_tfl_converter_flags,
110
+ )
111
+
112
+ return model.TfLiteModel(tflite_model)
@@ -0,0 +1,64 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from typing import Any
17
+
18
+ from ai_edge_torch.quantize import quant_config as qcfg
19
+ import tensorflow as tf
20
+
21
+
22
+ def apply_tfl_converter_flags(
23
+ converter: tf.lite.TFLiteConverter, tfl_converter_flags: dict[str, Any]
24
+ ):
25
+ """Applies TFLite converter flags to the converter.
26
+
27
+ Args:
28
+ converter: TFLite converter.
29
+ tfl_converter_flags: TFLite converter flags.
30
+ """
31
+
32
+ def _set_converter_flag(path: list[Any]):
33
+ if len(path) < 2:
34
+ raise ValueError("Expecting at least two values in the path.")
35
+
36
+ target_obj = converter
37
+ for idx in range(len(path) - 2):
38
+ target_obj = getattr(target_obj, path[idx])
39
+
40
+ setattr(target_obj, path[-2], path[-1])
41
+
42
+ def _iterate_dict_tree(flags_dict: dict[str, Any], path: list[Any]):
43
+ for key, value in flags_dict.items():
44
+ path.append(key)
45
+ if isinstance(value, dict):
46
+ _iterate_dict_tree(value, path)
47
+ else:
48
+ path.append(value)
49
+ _set_converter_flag(path)
50
+ path.pop()
51
+ path.pop()
52
+
53
+ _iterate_dict_tree(tfl_converter_flags, [])
54
+
55
+
56
+ def set_tfl_converter_quant_flags(
57
+ converter: tf.lite.TFLiteConverter, quant_config: qcfg.QuantConfig
58
+ ):
59
+ if quant_config is not None:
60
+ quantizer_mode = quant_config._quantizer_mode
61
+ if quantizer_mode == qcfg.QuantConfig._QuantizerMode.PT2E_DYNAMIC:
62
+ converter._experimental_qdq_conversion_mode = "DYNAMIC"
63
+ elif quantizer_mode == qcfg.QuantConfig._QuantizerMode.PT2E_STATIC:
64
+ converter._experimental_qdq_conversion_mode = "STATIC"
@@ -15,20 +15,23 @@
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
- from typing import Any, Dict, Optional, Tuple, Union
19
-
20
- import torch
18
+ from typing import Any, Optional, Tuple, Union
21
19
 
22
20
  from ai_edge_torch import model
23
- from ai_edge_torch.convert import conversion
24
- from ai_edge_torch.convert import conversion_utils as cutils
21
+ from ai_edge_torch._convert import conversion
22
+ from ai_edge_torch._convert import signature as signature_module
25
23
  from ai_edge_torch.quantize import quant_config as qcfg
24
+ import torch
26
25
 
27
26
 
28
27
  class Converter:
28
+ """A converter for converting PyTorch models to edge models.
29
+
30
+ This class allows adding multiple signatures to the converted edge model.
31
+ """
29
32
 
30
33
  def __init__(self):
31
- self._signatures: list[cutils.Signature] = []
34
+ self._signatures: list[signature_module.Signature] = []
32
35
 
33
36
  def signature(
34
37
  self,
@@ -37,9 +40,9 @@ class Converter:
37
40
  sample_args=None,
38
41
  sample_kwargs=None,
39
42
  *,
40
- dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
43
+ dynamic_shapes: Optional[Union[dict[str, Any], Tuple[Any, ...]]] = None,
41
44
  ) -> Converter:
42
- """Alias to `add_signature`"""
45
+ """Functions as an alias to `add_signature`."""
43
46
  return self.add_signature(
44
47
  name, module, sample_args, sample_kwargs, dynamic_shapes=dynamic_shapes
45
48
  )
@@ -51,31 +54,44 @@ class Converter:
51
54
  sample_args=None,
52
55
  sample_kwargs=None,
53
56
  *,
54
- dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
57
+ dynamic_shapes: Optional[Union[dict[str, Any], Tuple[Any, ...]]] = None,
55
58
  ) -> Converter:
56
59
  """Allows adding a new named torch model along with sample args to the conversion.
57
60
 
58
61
  Args:
59
62
  name: The name of the signature included in the converted edge model.
60
63
  module: The torch module to be converted.
61
- sample_args: Tuple of tensors by which the torch module will be traced with prior to conversion.
62
- sample_kwargs: Dict of str to tensor by which the torch module will be traced with prior to conversion.
63
- dynamic_shapes: Optional dict or tuple that specify dynamic shape specifications for each input in original order.
64
- See https://pytorch.org/docs/stable/export.html#expressing-dynamism for more details.
64
+ sample_args: Tuple of tensors by which the torch module will be traced
65
+ with prior to conversion.
66
+ sample_kwargs: Dict of str to tensor by which the torch module will be
67
+ traced with prior to conversion.
68
+ dynamic_shapes: Optional dict or tuple that specify dynamic shape
69
+ specifications for each input in original order. See
70
+ https://pytorch.org/docs/stable/export.html#expressing-dynamism for more
71
+ details.
72
+
73
+ Returns:
74
+ The converter object itself.
65
75
 
66
76
  Raises:
67
77
  ValueError: If a signature with the provided name already exists.
68
78
  """
69
79
 
70
80
  if name in [sig.name for sig in self._signatures]:
71
- raise ValueError(f"A signature with the provided name ({name}) is already added.")
81
+ raise ValueError(
82
+ f"A signature with the provided name ({name}) is already added."
83
+ )
72
84
 
73
85
  if sample_args is None and sample_kwargs is None:
74
86
  raise ValueError("sample_args or sample_kwargs must be provided.")
75
87
 
76
88
  self._signatures.append(
77
- cutils.Signature(
78
- name, module, sample_args, sample_kwargs, dynamic_shapes=dynamic_shapes
89
+ signature_module.Signature(
90
+ name,
91
+ module,
92
+ sample_args,
93
+ sample_kwargs,
94
+ dynamic_shapes=dynamic_shapes,
79
95
  )
80
96
  )
81
97
  return self
@@ -87,8 +103,8 @@ class Converter:
87
103
  sample_kwargs=None,
88
104
  *,
89
105
  quant_config: Optional[qcfg.QuantConfig] = None,
90
- dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
91
- _ai_edge_converter_flags: dict = {},
106
+ dynamic_shapes: Optional[Union[dict[str, Any], Tuple[Any, ...]]] = None,
107
+ _ai_edge_converter_flags: Optional[dict[str, Any]] = None,
92
108
  ) -> model.TfLiteModel:
93
109
  """Finalizes the conversion and produces an edge model.
94
110
 
@@ -96,31 +112,44 @@ class Converter:
96
112
 
97
113
  edge_model = Converter().signature(name, module, args).convert()
98
114
 
99
- Or it could be used to set the default signature for the converted edge model:
115
+ Or it could be used to set the default signature for the converted edge
116
+ model:
100
117
 
101
118
  edge_model = Converter().convert(module, args)
102
119
 
103
120
  Args:
104
- name: The name of the signature included in the converted edge model.
105
121
  module: The torch module to be converted.
106
- sample_args: Tuple of tensors by which the torch module will be traced with prior to conversion.
107
- sample_kwargs: Dict of str to tensor by which the torch module will be traced with prior to conversion.
122
+ sample_args: Tuple of tensors by which the torch module will be traced
123
+ with prior to conversion.
124
+ sample_kwargs: Dict of str to tensor by which the torch module will be
125
+ traced with prior to conversion.
108
126
  quant_config: User-defined quantization method and scheme of the model.
109
- dynamic_shapes: Optional dict or tuple that specify dynamic shape specifications for each input in original order.
110
- See https://pytorch.org/docs/stable/export.html#expressing-dynamism for more details.
111
- _ai_edge_converter_flags: A nested dictionary allowing setting flags for the underlying converter.
112
- This gives access to an implementation detail of this function and so needs to be treated as such.
113
- Please do not rely on this parameter except for local debugging as this can be removed in a future release.
127
+ dynamic_shapes: Optional dict or tuple that specify dynamic shape
128
+ specifications for each input in original order. See
129
+ https://pytorch.org/docs/stable/export.html#expressing-dynamism for more
130
+ details.
131
+ _ai_edge_converter_flags: A nested dictionary allowing setting flags for
132
+ the underlying converter. This gives access to an implementation detail
133
+ of this function and so needs to be treated as such. Please do not rely
134
+ on this parameter except for local debugging as this can be removed in a
135
+ future release.
136
+
137
+ Returns:
138
+ The converted edge model.
114
139
 
115
140
  Raises:
116
- ValueError: If the arguments are not provided as expected. See the example in this functions's comment.
141
+ ValueError: If the arguments are not provided as expected. See the example
142
+ in this functions's comment.
117
143
  """
144
+ if _ai_edge_converter_flags is None:
145
+ _ai_edge_converter_flags = {}
146
+
118
147
  if module is not None:
119
148
  if (
120
149
  sample_args is not None or sample_kwargs is not None
121
150
  ): # both module and args provided
122
151
  self.add_signature(
123
- cutils.DEFAULT_SIGNATURE_NAME,
152
+ model.DEFAULT_SIGNATURE_NAME,
124
153
  module,
125
154
  sample_args,
126
155
  sample_kwargs,
@@ -128,9 +157,9 @@ class Converter:
128
157
  )
129
158
  else: # module is provided but not args
130
159
  raise ValueError(
131
- "sample_args or sample_kwargs must be provided if a module is specified."
160
+ "sample_args or sample_kwargs must be provided if a module is"
161
+ " specified."
132
162
  )
133
-
134
163
  return conversion.convert_signatures(
135
164
  self._signatures,
136
165
  quant_config=quant_config,
@@ -143,22 +172,28 @@ def signature(
143
172
  module: torch.nn.Module,
144
173
  sample_args=None,
145
174
  sample_kwargs=None,
146
- dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
175
+ dynamic_shapes: Optional[Union[dict[str, Any], Tuple[Any, ...]]] = None,
147
176
  ) -> Converter:
148
177
  """Initiates a Converter object with the provided signature.
149
178
 
150
179
  Args:
151
180
  name: The name of the signature included in the converted edge model.
152
181
  module: The torch module to be converted.
153
- sample_args: Tuple of tensors by which the torch module will be traced with prior to conversion.
154
- sample_kwargs: Dict of str to tensor by which the torch module will be traced with prior to conversion.
155
- dynamic_shapes: Optional dict or tuple that specify dynamic shape specifications for each input in original order.
156
- See https://pytorch.org/docs/stable/export.html#expressing-dynamism for more details.
182
+ sample_args: Tuple of tensors by which the torch module will be traced with
183
+ prior to conversion.
184
+ sample_kwargs: Dict of str to tensor by which the torch module will be
185
+ traced with prior to conversion.
186
+ dynamic_shapes: Optional dict or tuple that specify dynamic shape
187
+ specifications for each input in original order. See
188
+ https://pytorch.org/docs/stable/export.html#expressing-dynamism for more
189
+ details.
190
+
191
+ Returns:
192
+ A Converter object with the provided signature.
157
193
 
158
194
  Example:
159
195
  converter = ai_edge_torch.signature(name, module, args)
160
196
  edge_model = converter.convert()
161
-
162
197
  """
163
198
  return Converter().signature(
164
199
  name, module, sample_args, sample_kwargs, dynamic_shapes=dynamic_shapes
@@ -171,27 +206,38 @@ def convert(
171
206
  sample_kwargs=None,
172
207
  *,
173
208
  quant_config: Optional[qcfg.QuantConfig] = None,
174
- dynamic_shapes: Optional[Union[Dict[str, Any], Tuple[Any]]] = None,
175
- _ai_edge_converter_flags: dict = {},
209
+ dynamic_shapes: Optional[Union[dict[str, Any], Tuple[Any, ...]]] = None,
210
+ _ai_edge_converter_flags: Optional[dict[str, Any]] = None,
176
211
  ) -> model.TfLiteModel:
177
- """Allows converting a PyTorch model to an edge model with one default signature in one step.
212
+ """Converts a PyTorch model to an edge model with a default signature.
178
213
 
179
214
  Args:
180
215
  module: The torch module to be converted.
181
- sample_args: Tuple of tensors by which the torch module will be traced with prior to conversion.
182
- sample_kwargs: Dict of str to tensor by which the torch module will be traced with prior to conversion.
216
+ sample_args: Tuple of tensors by which the torch module will be traced with
217
+ prior to conversion.
218
+ sample_kwargs: Dict of str to tensor by which the torch module will be
219
+ traced with prior to conversion.
183
220
  quant_config: User-defined quantization method and scheme of the model.
184
- dynamic_shapes: Optional dict or tuple that specify dynamic shape specifications for each input in original order.
185
- See https://pytorch.org/docs/stable/export.html#expressing-dynamism for more details.
186
- _ai_edge_converter_flags: A nested dictionary allowing setting flags for the underlying converter.
187
- This gives access to an implementation detail of this function and so needs to be treated as such.
188
- Please do not rely on this parameter except for local debugging as this can be removed in a future release.
221
+ dynamic_shapes: Optional dict or tuple that specify dynamic shape
222
+ specifications for each input in original order. See
223
+ https://pytorch.org/docs/stable/export.html#expressing-dynamism for more
224
+ details.
225
+ _ai_edge_converter_flags: A nested dictionary allowing setting flags for the
226
+ underlying converter. This gives access to an implementation detail of
227
+ this function and so needs to be treated as such. Please do not rely on
228
+ this parameter except for local debugging as this can be removed in a
229
+ future release.
230
+
231
+ Returns:
232
+ The converted edge model.
189
233
 
190
234
  Example:
191
235
  edge_model = ai_edge_torch.convert(module, args)
192
-
193
236
  """
194
237
 
238
+ if _ai_edge_converter_flags is None:
239
+ _ai_edge_converter_flags = {}
240
+
195
241
  return Converter().convert(
196
242
  module,
197
243
  sample_args,
@@ -0,0 +1,22 @@
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 typing import Sequence, Union
17
+
18
+ from ai_edge_torch._convert.fx_passes.build_aten_composite_pass import BuildAtenCompositePass
19
+ from ai_edge_torch._convert.fx_passes.build_interpolate_composite_pass import BuildInterpolateCompositePass
20
+ from ai_edge_torch._convert.fx_passes.inject_mlir_debuginfo_pass import InjectMlirDebuginfoPass
21
+ from ai_edge_torch._convert.fx_passes.optimize_layout_transposes_pass import OptimizeLayoutTransposesPass
22
+ from ai_edge_torch.fx_pass_base import CanonicalizePass