ai-edge-torch-nightly 0.3.0.dev20250114__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (213) hide show
  1. ai_edge_torch/__init__.py +32 -0
  2. ai_edge_torch/_config.py +69 -0
  3. ai_edge_torch/_convert/__init__.py +14 -0
  4. ai_edge_torch/_convert/conversion.py +153 -0
  5. ai_edge_torch/_convert/conversion_utils.py +64 -0
  6. ai_edge_torch/_convert/converter.py +270 -0
  7. ai_edge_torch/_convert/fx_passes/__init__.py +23 -0
  8. ai_edge_torch/_convert/fx_passes/build_aten_composite_pass.py +288 -0
  9. ai_edge_torch/_convert/fx_passes/build_interpolate_composite_pass.py +131 -0
  10. ai_edge_torch/_convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
  11. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
  12. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +258 -0
  13. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +50 -0
  14. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +18 -0
  15. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +68 -0
  16. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +216 -0
  17. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +449 -0
  18. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
  19. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +303 -0
  20. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/utils.py +64 -0
  21. ai_edge_torch/_convert/fx_passes/remove_non_user_outputs_pass.py +52 -0
  22. ai_edge_torch/_convert/signature.py +66 -0
  23. ai_edge_torch/_convert/test/__init__.py +14 -0
  24. ai_edge_torch/_convert/test/test_convert.py +558 -0
  25. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  26. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  27. ai_edge_torch/_convert/test/test_to_channel_last_io.py +96 -0
  28. ai_edge_torch/_convert/to_channel_last_io.py +92 -0
  29. ai_edge_torch/conftest.py +20 -0
  30. ai_edge_torch/debug/__init__.py +17 -0
  31. ai_edge_torch/debug/culprit.py +496 -0
  32. ai_edge_torch/debug/test/__init__.py +14 -0
  33. ai_edge_torch/debug/test/test_culprit.py +140 -0
  34. ai_edge_torch/debug/test/test_search_model.py +51 -0
  35. ai_edge_torch/debug/utils.py +59 -0
  36. ai_edge_torch/experimental/__init__.py +14 -0
  37. ai_edge_torch/fx_pass_base.py +110 -0
  38. ai_edge_torch/generative/__init__.py +14 -0
  39. ai_edge_torch/generative/examples/__init__.py +14 -0
  40. ai_edge_torch/generative/examples/amd_llama_135m/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/amd_llama_135m/amd_llama_135m.py +87 -0
  42. ai_edge_torch/generative/examples/amd_llama_135m/convert_to_tflite.py +70 -0
  43. ai_edge_torch/generative/examples/amd_llama_135m/verify.py +72 -0
  44. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  45. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +80 -0
  46. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +80 -0
  47. ai_edge_torch/generative/examples/gemma/gemma1.py +107 -0
  48. ai_edge_torch/generative/examples/gemma/gemma2.py +295 -0
  49. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  50. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +43 -0
  51. ai_edge_torch/generative/examples/gemma/verify_util.py +157 -0
  52. ai_edge_torch/generative/examples/llama/__init__.py +14 -0
  53. ai_edge_torch/generative/examples/llama/convert_to_tflite.py +91 -0
  54. ai_edge_torch/generative/examples/llama/llama.py +196 -0
  55. ai_edge_torch/generative/examples/llama/verify.py +88 -0
  56. ai_edge_torch/generative/examples/moonshine/__init__.py +14 -0
  57. ai_edge_torch/generative/examples/moonshine/convert_moonshine_to_tflite.py +50 -0
  58. ai_edge_torch/generative/examples/moonshine/moonshine.py +103 -0
  59. ai_edge_torch/generative/examples/openelm/__init__.py +14 -0
  60. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +80 -0
  61. ai_edge_torch/generative/examples/openelm/openelm.py +127 -0
  62. ai_edge_torch/generative/examples/openelm/verify.py +71 -0
  63. ai_edge_torch/generative/examples/paligemma/__init__.py +14 -0
  64. ai_edge_torch/generative/examples/paligemma/convert_to_tflite.py +95 -0
  65. ai_edge_torch/generative/examples/paligemma/decoder.py +151 -0
  66. ai_edge_torch/generative/examples/paligemma/decoder2.py +177 -0
  67. ai_edge_torch/generative/examples/paligemma/image_encoder.py +160 -0
  68. ai_edge_torch/generative/examples/paligemma/paligemma.py +179 -0
  69. ai_edge_torch/generative/examples/paligemma/verify.py +161 -0
  70. ai_edge_torch/generative/examples/paligemma/verify_decoder.py +75 -0
  71. ai_edge_torch/generative/examples/paligemma/verify_decoder2.py +72 -0
  72. ai_edge_torch/generative/examples/paligemma/verify_image_encoder.py +99 -0
  73. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  74. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +80 -0
  75. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +80 -0
  76. ai_edge_torch/generative/examples/phi/phi2.py +107 -0
  77. ai_edge_torch/generative/examples/phi/phi3.py +219 -0
  78. ai_edge_torch/generative/examples/phi/verify.py +64 -0
  79. ai_edge_torch/generative/examples/phi/verify_phi3.py +69 -0
  80. ai_edge_torch/generative/examples/qwen/__init__.py +14 -0
  81. ai_edge_torch/generative/examples/qwen/convert_to_tflite.py +93 -0
  82. ai_edge_torch/generative/examples/qwen/qwen.py +134 -0
  83. ai_edge_torch/generative/examples/qwen/verify.py +88 -0
  84. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  85. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +80 -0
  86. ai_edge_torch/generative/examples/smollm/convert_v2_to_tflite.py +71 -0
  87. ai_edge_torch/generative/examples/smollm/smollm.py +125 -0
  88. ai_edge_torch/generative/examples/smollm/verify.py +86 -0
  89. ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
  90. ai_edge_torch/generative/examples/stable_diffusion/attention.py +108 -0
  91. ai_edge_torch/generative/examples/stable_diffusion/clip.py +185 -0
  92. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +173 -0
  93. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +398 -0
  94. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +749 -0
  95. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +119 -0
  96. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +254 -0
  97. ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
  98. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +62 -0
  99. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +66 -0
  100. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +74 -0
  101. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +39 -0
  102. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +111 -0
  103. ai_edge_torch/generative/examples/stable_diffusion/util.py +77 -0
  104. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  105. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +138 -0
  106. ai_edge_torch/generative/examples/t5/t5.py +655 -0
  107. ai_edge_torch/generative/examples/t5/t5_attention.py +246 -0
  108. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  109. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  110. ai_edge_torch/generative/examples/test_models/toy_model.py +156 -0
  111. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +138 -0
  112. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  113. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +80 -0
  114. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +88 -0
  115. ai_edge_torch/generative/examples/tiny_llama/verify.py +72 -0
  116. ai_edge_torch/generative/fx_passes/__init__.py +30 -0
  117. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +50 -0
  118. ai_edge_torch/generative/layers/__init__.py +14 -0
  119. ai_edge_torch/generative/layers/attention.py +399 -0
  120. ai_edge_torch/generative/layers/attention_utils.py +210 -0
  121. ai_edge_torch/generative/layers/builder.py +160 -0
  122. ai_edge_torch/generative/layers/feed_forward.py +120 -0
  123. ai_edge_torch/generative/layers/kv_cache.py +204 -0
  124. ai_edge_torch/generative/layers/lora.py +557 -0
  125. ai_edge_torch/generative/layers/model_config.py +238 -0
  126. ai_edge_torch/generative/layers/normalization.py +222 -0
  127. ai_edge_torch/generative/layers/rotary_position_embedding.py +94 -0
  128. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +144 -0
  129. ai_edge_torch/generative/layers/unet/__init__.py +14 -0
  130. ai_edge_torch/generative/layers/unet/blocks_2d.py +806 -0
  131. ai_edge_torch/generative/layers/unet/builder.py +50 -0
  132. ai_edge_torch/generative/layers/unet/model_config.py +282 -0
  133. ai_edge_torch/generative/quantize/__init__.py +14 -0
  134. ai_edge_torch/generative/quantize/example.py +47 -0
  135. ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
  136. ai_edge_torch/generative/quantize/quant_recipe.py +154 -0
  137. ai_edge_torch/generative/quantize/quant_recipe_utils.py +62 -0
  138. ai_edge_torch/generative/quantize/quant_recipes.py +56 -0
  139. ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
  140. ai_edge_torch/generative/test/__init__.py +14 -0
  141. ai_edge_torch/generative/test/test_custom_dus.py +107 -0
  142. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  143. ai_edge_torch/generative/test/test_loader.py +83 -0
  144. ai_edge_torch/generative/test/test_lora.py +147 -0
  145. ai_edge_torch/generative/test/test_model_conversion.py +191 -0
  146. ai_edge_torch/generative/test/test_model_conversion_large.py +362 -0
  147. ai_edge_torch/generative/test/test_quantize.py +183 -0
  148. ai_edge_torch/generative/test/utils.py +82 -0
  149. ai_edge_torch/generative/utilities/__init__.py +15 -0
  150. ai_edge_torch/generative/utilities/converter.py +215 -0
  151. ai_edge_torch/generative/utilities/dynamic_update_slice.py +56 -0
  152. ai_edge_torch/generative/utilities/loader.py +398 -0
  153. ai_edge_torch/generative/utilities/model_builder.py +180 -0
  154. ai_edge_torch/generative/utilities/moonshine_loader.py +154 -0
  155. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +1032 -0
  156. ai_edge_torch/generative/utilities/t5_loader.py +512 -0
  157. ai_edge_torch/generative/utilities/transformers_verifier.py +42 -0
  158. ai_edge_torch/generative/utilities/verifier.py +335 -0
  159. ai_edge_torch/hlfb/__init__.py +16 -0
  160. ai_edge_torch/hlfb/mark_pattern/__init__.py +153 -0
  161. ai_edge_torch/hlfb/mark_pattern/fx_utils.py +69 -0
  162. ai_edge_torch/hlfb/mark_pattern/pattern.py +288 -0
  163. ai_edge_torch/hlfb/test/__init__.py +14 -0
  164. ai_edge_torch/hlfb/test/test_mark_pattern.py +185 -0
  165. ai_edge_torch/lowertools/__init__.py +18 -0
  166. ai_edge_torch/lowertools/_shim.py +86 -0
  167. ai_edge_torch/lowertools/common_utils.py +142 -0
  168. ai_edge_torch/lowertools/odml_torch_utils.py +260 -0
  169. ai_edge_torch/lowertools/test_utils.py +62 -0
  170. ai_edge_torch/lowertools/torch_xla_utils.py +301 -0
  171. ai_edge_torch/lowertools/translate_recipe.py +163 -0
  172. ai_edge_torch/model.py +177 -0
  173. ai_edge_torch/odml_torch/__init__.py +20 -0
  174. ai_edge_torch/odml_torch/_torch_future.py +88 -0
  175. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  176. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  177. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  178. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  179. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  180. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  181. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  182. ai_edge_torch/odml_torch/export.py +403 -0
  183. ai_edge_torch/odml_torch/export_utils.py +157 -0
  184. ai_edge_torch/odml_torch/jax_bridge/__init__.py +18 -0
  185. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +180 -0
  186. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  187. ai_edge_torch/odml_torch/lowerings/__init__.py +27 -0
  188. ai_edge_torch/odml_torch/lowerings/_basic.py +294 -0
  189. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  190. ai_edge_torch/odml_torch/lowerings/_convolution.py +243 -0
  191. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +285 -0
  192. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +87 -0
  193. ai_edge_torch/odml_torch/lowerings/_quantized_decomposed.py +177 -0
  194. ai_edge_torch/odml_torch/lowerings/_rand.py +142 -0
  195. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  196. ai_edge_torch/odml_torch/lowerings/decomp.py +69 -0
  197. ai_edge_torch/odml_torch/lowerings/registry.py +65 -0
  198. ai_edge_torch/odml_torch/lowerings/utils.py +201 -0
  199. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  200. ai_edge_torch/odml_torch/tf_integration.py +156 -0
  201. ai_edge_torch/quantize/__init__.py +16 -0
  202. ai_edge_torch/quantize/pt2e_quantizer.py +466 -0
  203. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1061 -0
  204. ai_edge_torch/quantize/quant_config.py +85 -0
  205. ai_edge_torch/testing/__init__.py +14 -0
  206. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  207. ai_edge_torch/testing/model_coverage/model_coverage.py +145 -0
  208. ai_edge_torch/version.py +16 -0
  209. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/LICENSE +202 -0
  210. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/METADATA +44 -0
  211. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/RECORD +213 -0
  212. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/WHEEL +5 -0
  213. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/top_level.txt +1 -0
@@ -0,0 +1,403 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """APIs to convert and lower a PyTorch ExportedProgram to MLIR."""
16
+
17
+ import dataclasses
18
+ import enum
19
+ import io
20
+ import operator
21
+ from typing import Any, Callable, Optional
22
+
23
+ from jax.lib import xla_extension
24
+ from jax._src.lib.mlir import ir
25
+ from jax._src.lib.mlir.dialects import func
26
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
27
+ import torch
28
+ import torch.utils._pytree as pytree
29
+
30
+ from . import _torch_future
31
+ from . import debuginfo
32
+ from . import export_utils
33
+ from . import lowerings
34
+
35
+ LoweringContext = lowerings.context.LoweringContext
36
+
37
+
38
+ def _build_flat_inputs(exported_program: torch.export.ExportedProgram):
39
+ """Build flattened inputs and metadata from exported program's signature."""
40
+ placeholder_nodes = [
41
+ n for n in exported_program.graph.nodes if n.op == "placeholder"
42
+ ]
43
+ export_flat_args = _torch_future.graph_module_flat_inputs(
44
+ exported_program, *exported_program.example_inputs
45
+ )
46
+
47
+ ir_inputs = []
48
+ tensor_metas = []
49
+ for node, arg in zip(placeholder_nodes, export_flat_args):
50
+ tensor_meta = node.meta.get("tensor_meta") or node.meta.get("val")
51
+ if tensor_meta is None:
52
+ raise RuntimeError(
53
+ f"{type(arg)} (for {node.name}) does not have tensor meta"
54
+ )
55
+
56
+ tensor_metas.append(tensor_meta)
57
+ # Assume all dynamic dimensions are unbounded.
58
+ # TODO: Add checks for ep.range_constraints in MLIR.
59
+ shape = tuple(
60
+ export_utils.IR_DYNAMIC if export_utils.is_torch_dynamic(s) else s
61
+ for s in tensor_meta.shape
62
+ )
63
+ ir_inputs.append(
64
+ ir.RankedTensorType.get(
65
+ shape,
66
+ export_utils.torch_dtype_to_ir_element_type(tensor_meta.dtype),
67
+ )
68
+ )
69
+ return tuple(ir_inputs), tuple(export_flat_args), tuple(tensor_metas)
70
+
71
+
72
+ def _get_output_metas(exported_program: torch.export.ExportedProgram):
73
+ """Get the output node's tensor_meta from the exported program."""
74
+ outputs = [n for n in exported_program.graph.nodes if n.op == "output"]
75
+ assert len(outputs) == 1
76
+ outputs, _ = pytree.tree_flatten(outputs[0].args[0])
77
+ assert all(isinstance(output, torch.fx.Node) for output in outputs)
78
+ return tuple(output.meta["tensor_meta"] for output in outputs)
79
+
80
+
81
+ class LoweringInterpreter(torch.fx.Interpreter):
82
+ """The FX interpreter to iterate and invoke corresponding lowering for each PyTorch op in the graph."""
83
+
84
+ def __init__(self, module: torch.fx.GraphModule, lctx: LoweringContext):
85
+ super().__init__(module)
86
+ self.lctx = lctx
87
+ self.outputs = None
88
+
89
+ def _build_loc(self, node: torch.fx.Node):
90
+
91
+ info = debuginfo.build_mlir_debuginfo(node)
92
+ if info is None:
93
+ return ir.Location.unknown()
94
+
95
+ return ir.Location.name(name=info)
96
+
97
+ def run_node(self, node: torch.fx.Node):
98
+ loc = self._build_loc(node)
99
+ with loc:
100
+ self.lctx = self.lctx.replace(ir_location=loc, node=node)
101
+ res = super().run_node(node)
102
+ self.lctx = self.lctx.replace(ir_location=None, node=None)
103
+ return res
104
+
105
+ def call_function(self, target, args, kwargs):
106
+ if target is operator.getitem:
107
+ return super().call_function(target, args, kwargs)
108
+
109
+ if hasattr(target, "_schema"):
110
+ new_args = []
111
+ for arg, spec in zip(args, target._schema.arguments):
112
+ if isinstance(spec.type, torch.TensorType):
113
+ if isinstance(arg, int):
114
+ arg = lowerings.utils.splat(arg, ir.IntegerType.get_signless(32))
115
+ elif isinstance(arg, float):
116
+ arg = lowerings.utils.splat(arg, ir.F32Type.get())
117
+
118
+ new_args.append(arg)
119
+ args = tuple(new_args)
120
+
121
+ lowering = lowerings.lookup(target)
122
+ if lowering is None:
123
+ raise RuntimeError(f"Lowering not found: {target}")
124
+ return lowering(self.lctx, *args, **kwargs)
125
+
126
+ def output(self, target, args, kwargs):
127
+ flat_outputs = pytree.tree_flatten(args[0])[0]
128
+ self.outputs = flat_outputs
129
+
130
+
131
+ @dataclasses.dataclass
132
+ class InputSpec:
133
+
134
+ class VariableType(enum.Enum):
135
+ USER_INPUT = "user_input"
136
+ PARAMETER = "parameter"
137
+
138
+ type_: VariableType
139
+ i: int = -1
140
+ name: str = ""
141
+
142
+ @classmethod
143
+ def parameter(cls, name: str):
144
+ return cls(type_=cls.VariableType.PARAMETER, name=name)
145
+
146
+ @classmethod
147
+ def user_input(cls, i: int):
148
+ return cls(type_=cls.VariableType.USER_INPUT, i=i)
149
+
150
+ @property
151
+ def is_parameter(self):
152
+ return self.type_ == self.VariableType.PARAMETER
153
+
154
+ @property
155
+ def is_user_input(self):
156
+ return self.type_ == self.VariableType.USER_INPUT
157
+
158
+
159
+ @dataclasses.dataclass
160
+ class VariableSignature: # either argument or parameters
161
+ shape: list[int]
162
+ dtype: str
163
+ input_spec: InputSpec = None
164
+
165
+
166
+ @dataclasses.dataclass
167
+ class MlirLowered:
168
+ """The lowered MLIR module, metadata, and weight tensors bundle from exported program."""
169
+
170
+ ctx: ir.Context
171
+ module: ir.Module
172
+ state_dict: dict[str, torch.Tensor]
173
+ input_signature: list[VariableSignature]
174
+ output_signature: list[VariableSignature]
175
+
176
+ _tf_function: Optional[Callable[Any, Any]] = None
177
+
178
+ def __str__(self):
179
+ return str(self.get_text(enable_debug_info=False))
180
+
181
+ def __repr__(self):
182
+ return str(self.get_text(enable_debug_info=False))
183
+
184
+ def get_text(self, enable_debug_info=False):
185
+ return str(
186
+ self.module.operation.get_asm(enable_debug_info=enable_debug_info)
187
+ )
188
+
189
+ @property
190
+ def module_bytecode(self) -> bytes:
191
+ output = io.BytesIO()
192
+ self.module.operation.write_bytecode(file=output)
193
+ return output.getvalue()
194
+
195
+ @property
196
+ def module_bytecode_vhlo(self) -> bytes:
197
+ # HACK: In OSS, we use MLIR pybinding and StableHLO dialect from JAX's
198
+ # build, which may not have the same StableHLO version as what used in
199
+ # TFLite converter. Therefore we always serialize MLIR module in VHLO.
200
+ # TODO(b/362798610) Build MLIR pybinding in ai-edge-torch release.
201
+ if stablehlo.get_api_version() < 9:
202
+ target_version = stablehlo.get_minimum_version()
203
+ else:
204
+ target_version = stablehlo.get_version_from_compatibility_requirement(
205
+ stablehlo.StablehloCompatibilityRequirement.WEEK_12
206
+ )
207
+ module_bytecode = xla_extension.mlir.serialize_portable_artifact(
208
+ self.module_bytecode, target_version
209
+ )
210
+ return module_bytecode
211
+
212
+ @property
213
+ def tf_function(self):
214
+ # Lazy import
215
+ from . import tf_integration
216
+
217
+ if self._tf_function is None:
218
+ self._tf_function = tf_integration.mlir_to_tf_function(self)
219
+ return self._tf_function
220
+
221
+ def __call__(self, *args):
222
+ # Lazy importing TF when execution is needed.
223
+ return self.tf_function(*args)
224
+
225
+
226
+ # TODO(b/331481564) Make this a ai_edge_torch FX pass.
227
+ def _convert_i64_to_i32(exported_program: torch.export.ExportedProgram):
228
+ """Convert internal constant aten ops' output from int64 to int32.
229
+
230
+ Int32 generally has better performance and compatibility than int64 in
231
+ runtime. This pass converts aten op where the output(s) are int64 constant
232
+ tensors to return int32 constant tensors.
233
+
234
+ Args:
235
+ exported_program: The exported program to apply the pass.
236
+ """
237
+
238
+ def in_i32(x: int):
239
+ return -2147483648 <= x <= 2147483647
240
+
241
+ def to_int32(x: torch.Tensor):
242
+ return torch.ops.aten._to_copy.default(x, dtype=torch.int32)
243
+
244
+ def rewrite_arange(node: torch.fx.Node):
245
+ tensor_meta = node.meta.get("tensor_meta", None)
246
+ if not tensor_meta:
247
+ return
248
+
249
+ start, end = node.args[:2]
250
+ if tensor_meta.dtype != torch.int64:
251
+ return
252
+ if not (in_i32(start) and in_i32(end)):
253
+ return
254
+ op = node.target
255
+ node.target = lambda *args, **kwargs: to_int32(op(*args, **kwargs))
256
+
257
+ graph_module = exported_program.graph_module
258
+ for node in graph_module.graph.nodes:
259
+
260
+ if node.target == torch.ops.aten.arange.start_step:
261
+ rewrite_arange(node)
262
+
263
+
264
+ # TODO(b/331481564) Make this a ai_edge_torch FX pass.
265
+ def _convert_q_dq_per_channel_args_to_list(
266
+ exported_program: torch.export.ExportedProgram,
267
+ ):
268
+ """Resolve tensor inputs to Q/DQ ops as static number list for lowering.
269
+
270
+ This pass makes the ExportedProgram in a non-executable state. This pass must
271
+ be run after all run_decompositions calls.
272
+ """
273
+ placeholder_nodes = [
274
+ n for n in exported_program.graph.nodes if n.op == "placeholder"
275
+ ]
276
+ export_flat_args = _torch_future.graph_module_flat_inputs(
277
+ exported_program, *exported_program.example_inputs
278
+ )
279
+
280
+ placeholder_tensor = {
281
+ n: tensor for n, tensor in zip(placeholder_nodes, export_flat_args)
282
+ }
283
+
284
+ graph_module = exported_program.graph_module
285
+ for node in graph_module.graph.nodes:
286
+ if node.target in (
287
+ torch.ops.quantized_decomposed.quantize_per_channel.default,
288
+ torch.ops.quantized_decomposed.quantize_per_tensor.tensor,
289
+ torch.ops.quantized_decomposed.dequantize_per_channel.default,
290
+ torch.ops.quantized_decomposed.dequantize_per_tensor.tensor,
291
+ ):
292
+ input, scale_node, zero_point_node = node.args[:3]
293
+ scale = placeholder_tensor[scale_node]
294
+ zero_point = placeholder_tensor[zero_point_node]
295
+
296
+ scale = scale.detach().numpy().tolist()
297
+ zero_point = zero_point.detach().numpy().tolist()
298
+ node.args = (input, scale, zero_point, *node.args[3:])
299
+
300
+
301
+ def exported_program_to_mlir(
302
+ exported_program: torch.export.ExportedProgram,
303
+ ) -> MlirLowered:
304
+ """Lower the exported program to MLIR."""
305
+ exported_program = _torch_future.safe_run_decompositions(
306
+ exported_program, lowerings.decompositions()
307
+ )
308
+
309
+ _convert_i64_to_i32(exported_program)
310
+
311
+ # No decompositions but just retracing/cananicalization.
312
+ exported_program = _torch_future.safe_run_decompositions(
313
+ exported_program, _torch_future.dummy_decomp_table()
314
+ )
315
+
316
+ # Passes below mutate the exported program to a state not executable by torch.
317
+ # Do not call run_decompositions after applying the passes.
318
+ _convert_q_dq_per_channel_args_to_list(exported_program)
319
+
320
+ with export_utils.create_ir_context() as context, ir.Location.unknown():
321
+
322
+ module = ir.Module.create()
323
+ lctx = LoweringContext(context, module)
324
+ interpreter = LoweringInterpreter(exported_program.graph_module, lctx)
325
+ ir_flat_inputs, export_flat_args, tensor_metas = _build_flat_inputs(
326
+ exported_program
327
+ )
328
+
329
+ # HACK: OSS MLIR pybinding could mysteriously transform func.func under
330
+ # construction into a func.return op after calling ir.Module.parse(..)
331
+ # in the context, which happens in JAX bridge. This is a bug in MLIR
332
+ # pybinding.
333
+ # Workaround steps:
334
+ # 1. Create a temp func.func.
335
+ # 2. Create and insert ops to temp's entry block. During the process
336
+ # the temp func.func would be broken, but the ops in the block are fine.
337
+ # 3. Create the main func.func and copy all the ops in temp's entry block
338
+ # to main.
339
+ # 4. Erase the temp func.func.
340
+ temp_func = func.FuncOp(
341
+ "temp",
342
+ ir.FunctionType.get(ir_flat_inputs, []),
343
+ ip=ir.InsertionPoint.at_block_begin(module.body),
344
+ )
345
+ with ir.InsertionPoint(temp_func.add_entry_block()):
346
+ interpreter.run(*temp_func.arguments, enable_io_processing=False)
347
+ num_mutations = len(exported_program.graph_signature.buffers_to_mutate)
348
+ outputs = interpreter.outputs[num_mutations:]
349
+ func.ReturnOp(interpreter.outputs[num_mutations:])
350
+
351
+ main_func = func.FuncOp(
352
+ "main",
353
+ ir.FunctionType.get(ir_flat_inputs, [o.type for o in outputs]),
354
+ ip=ir.InsertionPoint.at_block_begin(module.body),
355
+ )
356
+ with ir.InsertionPoint(main_func.add_entry_block()):
357
+ outputs = export_utils.clone_func_body_ops(temp_func, main_func.arguments)
358
+ func.ReturnOp(outputs)
359
+
360
+ main_func.attributes["sym_visibility"] = ir.StringAttr.get("public")
361
+ temp_func.erase()
362
+
363
+ module.operation.verify()
364
+
365
+ input_signature = []
366
+ state_dict = {}
367
+
368
+ user_inputs_cnt = 0
369
+ for arg, tensor_meta, input_spec in zip(
370
+ export_flat_args,
371
+ tensor_metas,
372
+ exported_program.graph_signature.input_specs,
373
+ ):
374
+ # Assumption:
375
+ # All states comes first in the list of args, and user provided inputs
376
+ # comes later. Also there is no kwargs.
377
+ if input_spec.kind == torch.export.graph_signature.InputKind.USER_INPUT:
378
+ input_signature.append(
379
+ VariableSignature(
380
+ tensor_meta.shape,
381
+ tensor_meta.dtype,
382
+ input_spec=InputSpec.user_input(user_inputs_cnt),
383
+ )
384
+ )
385
+ user_inputs_cnt += 1
386
+ else:
387
+ # Parameter or constant
388
+ state_dict[input_spec.target] = arg
389
+ input_signature.append(
390
+ VariableSignature(
391
+ tensor_meta.shape,
392
+ tensor_meta.dtype,
393
+ input_spec=InputSpec.parameter(input_spec.target),
394
+ )
395
+ )
396
+
397
+ output_signature = [
398
+ VariableSignature(tensor_meta.shape, tensor_meta.dtype)
399
+ for tensor_meta in _get_output_metas(exported_program)
400
+ ]
401
+ return MlirLowered(
402
+ context, module, state_dict, input_signature, output_signature
403
+ )
@@ -0,0 +1,157 @@
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
+ """Utilities for ODML Torch export."""
16
+
17
+ import re
18
+ from typing import Sequence, cast
19
+ from ai_edge_torch.odml_torch.lowerings import utils as lowering_utils
20
+ import jax._src.interpreters.mlir
21
+ from jax._src.lib.mlir import ir
22
+ from jax._src.lib.mlir.dialects import func
23
+ import torch
24
+
25
+ # std::numeric_limits<int64_t>::min()
26
+ IR_DYNAMIC = -9223372036854775808
27
+
28
+
29
+ def is_ir_dynamic(v):
30
+ return v == IR_DYNAMIC
31
+
32
+
33
+ def is_torch_dynamic(v):
34
+ return isinstance(v, torch.SymInt)
35
+
36
+
37
+ def is_iterable(v):
38
+ try:
39
+ iter(v)
40
+ except TypeError:
41
+ return False
42
+ return True
43
+
44
+
45
+ def create_ir_context():
46
+ # HACK: Use ir context from JAX as base for better stability in OSS.
47
+ # TODO(b/362798610) Build MLIR pybinding in ai-edge-torch release.
48
+ context = jax._src.interpreters.mlir.make_ir_context()
49
+ context.allow_unregistered_dialects = True
50
+ return context
51
+
52
+
53
+ def inline(
54
+ symbol_table: ir.SymbolTable,
55
+ block: ir.Block,
56
+ ):
57
+ """Recursively inlines all func.call ops in the block.
58
+
59
+ The symbol_table must include all func.func called by func.call ops.
60
+ This inliner in Python is implemented because MLIR inline pass from JAX's
61
+ MLIR pybinding build in OSS cannot properly inline func.call ops.
62
+ """
63
+ while True:
64
+ is_changed = False
65
+ for op in block.operations:
66
+ if op.OPERATION_NAME != func.CallOp.OPERATION_NAME:
67
+ continue
68
+
69
+ call_op = cast(func.CallOp, op)
70
+ func_op = cast(func.FuncOp, symbol_table[call_op.callee.value])
71
+ with ir.InsertionPoint(op):
72
+ new_results = clone_func_body_ops(func_op, call_op.operands)
73
+
74
+ for old_result, new_result in zip(call_op.results, new_results):
75
+ old_result = cast(ir.Value, old_result)
76
+ old_result.replace_all_uses_with(new_result)
77
+ call_op.erase()
78
+ is_changed = True
79
+
80
+ if not is_changed:
81
+ break
82
+
83
+ for op in block.operations:
84
+ for region in op.regions:
85
+ for block in region.blocks:
86
+ inline(symbol_table, block)
87
+
88
+
89
+ def clone_func_body_ops(func_op: func.FuncOp, ir_inputs: Sequence[ir.Value]):
90
+ """Clone operations in the func_op's body by one into the current context."""
91
+ func_args = list(func_op.arguments)
92
+ ir_inputs = list(ir_inputs)
93
+ assert len(func_args) == len(ir_inputs)
94
+
95
+ value_mapping = {arg: ir_input for arg, ir_input in zip(func_args, ir_inputs)}
96
+
97
+ for op in list(func_op.entry_block.operations):
98
+ cloned_operands = [value_mapping[val] for val in op.operands]
99
+ if op.OPERATION_NAME == func.ReturnOp.OPERATION_NAME:
100
+ return cloned_operands
101
+
102
+ cloned = cast(ir.Operation, op.operation.clone())
103
+
104
+ for i in range(len(op.operands)):
105
+ cloned.operands[i] = cloned_operands[i]
106
+
107
+ for i in range(len(op.results)):
108
+ value_mapping[op.results[i]] = cloned.results[i]
109
+
110
+ return []
111
+
112
+
113
+ def sanitize_aten_op_name(op, chars=":."):
114
+ return re.sub("[{}]".format(chars), "_", str(op))
115
+
116
+
117
+ def build_ir_attr(val):
118
+ if val is None:
119
+ return ir.StringAttr.get("py_None")
120
+ if isinstance(val, bool):
121
+ return ir.BoolAttr.get(val)
122
+ if isinstance(val, int):
123
+ return ir.IntegerAttr.get(ir.IntegerType.get_signless(64), val)
124
+ if isinstance(val, float):
125
+ return ir.BoolAttr.get(val)
126
+ if isinstance(val, str):
127
+ return ir.StringAttr.get(val)
128
+ if isinstance(val, dict):
129
+ return ir.DictAttr.get({k: build_ir_attr(v) for k, v in val.items()})
130
+ if isinstance(val, (list, tuple)):
131
+ return ir.ArrayAttr.get([build_ir_attr(v) for v in val])
132
+
133
+ # Stringify the value to a StringAttr by default
134
+ return ir.StringAttr.get(str(val))
135
+
136
+
137
+ torch_dtype_to_ir_element_type = lowering_utils.torch_dtype_to_ir_element_type
138
+
139
+
140
+ def ir_element_type_to_torch_dtype(ty):
141
+ if isinstance(ty, ir.F32Type):
142
+ return torch.float32
143
+ if isinstance(ty, ir.F64Type):
144
+ return torch.float64
145
+ if isinstance(ty, ir.F16Type):
146
+ return torch.half
147
+ if isinstance(ty, ir.IntegerType):
148
+ if ty.is_signless:
149
+ if ty.width == 64:
150
+ return torch.long
151
+ if ty.width == 32:
152
+ return torch.int32
153
+ if ty.width == 16:
154
+ return torch.int16
155
+ if ty.width == 1:
156
+ return torch.bool
157
+ raise RuntimeError(f"Unsupported ir element type: {ty}")
@@ -0,0 +1,18 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ from ai_edge_torch.odml_torch.jax_bridge import _wrap
16
+ from ai_edge_torch.odml_torch.jax_bridge import utils
17
+
18
+ wrap = _wrap.wrap