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,177 @@
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
+ """Lowerings for PT2E torch.ops.quantized_decomposed ops."""
16
+ from typing import Optional, Union, cast
17
+
18
+ from ai_edge_torch.odml_torch.lowerings import context
19
+ from ai_edge_torch.odml_torch.lowerings import utils
20
+ from jax._src.lib.mlir import ir
21
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
22
+ import torch
23
+ import torch.ao.quantization.fx._decomposed
24
+ import torch.utils._pytree as pytree
25
+
26
+ from . import registry
27
+
28
+ lower = registry.lower
29
+ LoweringContext = context.LoweringContext
30
+
31
+
32
+ def _uniform_quantized_type(
33
+ stored_type: Union[str, ir.Type],
34
+ expressed_type: Union[str, ir.Type],
35
+ *,
36
+ scale=Union[float, list[float], tuple[float]],
37
+ zero_point=Union[float, list[float], tuple[float]],
38
+ storage_type_min: Optional[int] = None,
39
+ storage_type_max: Optional[int] = None,
40
+ channel_axis: Optional[int] = None,
41
+ channel_axis_size: Optional[int] = None,
42
+ ):
43
+ """Polyfill for quant.UniformQuantizedType."""
44
+ if storage_type_min and storage_type_max:
45
+ storage_min_max = f"<{storage_type_min}:{storage_type_max}>"
46
+ else:
47
+ storage_min_max = ""
48
+
49
+ if channel_axis is not None:
50
+ # Per-channel quantization
51
+ # https://mlir.llvm.org/docs/Dialects/QuantDialect/#per-channel-quantization
52
+ assert isinstance(scale, (list, tuple))
53
+ assert isinstance(zero_point, (list, tuple))
54
+
55
+ scale = list(scale)
56
+ zero_point = list(zero_point)
57
+
58
+ if len(scale) == 1:
59
+ scale = scale * channel_axis_size
60
+ if len(zero_point) == 1:
61
+ zero_point = zero_point * channel_axis_size
62
+
63
+ assert len(scale) == len(zero_point) == channel_axis_size
64
+ scale_zp_strs = []
65
+ for s, zp in zip(scale, zero_point):
66
+ scale_zp_strs.append(f"{s}:{zp}")
67
+ scale_zp = "{" + ",".join(scale_zp_strs) + "}"
68
+ return ir.Type.parse(
69
+ f"!quant.uniform<{stored_type}{storage_min_max}:{expressed_type}:{channel_axis},{scale_zp}>"
70
+ )
71
+ else:
72
+ # Per-layer quantization
73
+ # https://mlir.llvm.org/docs/Dialects/QuantDialect/#per-layer-quantization
74
+ scale = pytree.tree_flatten([scale])[0][-1]
75
+ zero_point = pytree.tree_flatten([zero_point])[0][-1]
76
+ scale_zp = f"{scale}:{zero_point}"
77
+ return ir.Type.parse(
78
+ f"!quant.uniform<{stored_type}{storage_min_max}:{expressed_type},{scale_zp}>"
79
+ )
80
+
81
+
82
+ # Quant dialect is not registered in the Python MLIR pybinding used by
83
+ # odml-torch. Therefore, stablehlo.uniform_quantize/uniform_dequantize ops and
84
+ # quant types are represented in stablehlo.custom_call to pass MLIR verification
85
+ # and VHLO serialization before converter.
86
+ # TODO(b/362798610) Build MLIR pybinding in ai-edge-torch release.
87
+
88
+
89
+ # Schema:
90
+ # - quantized_decomposed::quantize_per_tensor(Tensor input, float scale,
91
+ # int zero_point, int quant_min, int quant_max,
92
+ # ScalarType dtype) -> Tensor
93
+ # - quantized_decomposed::quantize_per_tensor.tensor(Tensor input,
94
+ # Tensor scale, Tensor zero_point, int quant_min, int quant_max,
95
+ # ScalarType dtype) -> Tensor
96
+ #
97
+ # Scale and zero_point in tensors are automatically converted to list before
98
+ # lowering.
99
+ @lower(torch.ops.quantized_decomposed.quantize_per_tensor)
100
+ def _quantize_per_tensor(
101
+ lctx: LoweringContext,
102
+ input: ir.Value,
103
+ scale: Union[float, list[float]],
104
+ zero_point: Union[float, list[float]],
105
+ quant_min: int,
106
+ quant_max: int,
107
+ dtype: torch.dtype,
108
+ ):
109
+ input_ty = cast(ir.RankedTensorType, input.type)
110
+ qty = _uniform_quantized_type(
111
+ utils.torch_dtype_to_ir_element_type(dtype),
112
+ input_ty.element_type,
113
+ scale=scale,
114
+ zero_point=zero_point,
115
+ storage_type_min=quant_min,
116
+ storage_type_max=quant_max,
117
+ )
118
+ return stablehlo.custom_call(
119
+ call_target_name="odml_torch.uniform_quantize",
120
+ inputs=[input],
121
+ result=[input_ty],
122
+ backend_config=ir.StringAttr.get(
123
+ str(ir.RankedTensorType.get(input_ty.shape, qty))
124
+ ),
125
+ )
126
+
127
+
128
+ # Schema:
129
+ # - quantized_decomposed::quantize_per_channel(Tensor input, Tensor scales,
130
+ # Tensor zero_points, int axis, int quant_min, int quant_max,
131
+ # ScalarType dtype) -> Tensor
132
+ #
133
+ # Scale and zero_point in tensors are automatically converted to list before
134
+ # lowering.
135
+ @lower(torch.ops.quantized_decomposed.quantize_per_channel)
136
+ def _quantize_per_channel(
137
+ lctx: LoweringContext,
138
+ input: ir.Value,
139
+ scale: list[float],
140
+ zero_point: list[float],
141
+ axis: int,
142
+ quant_min: int,
143
+ quant_max: int,
144
+ dtype: torch.dtype,
145
+ ):
146
+ input_ty = cast(ir.RankedTensorType, input.type)
147
+ qty = _uniform_quantized_type(
148
+ utils.torch_dtype_to_ir_element_type(dtype),
149
+ input_ty.element_type,
150
+ scale=scale,
151
+ zero_point=zero_point,
152
+ channel_axis=axis,
153
+ channel_axis_size=input_ty.shape[axis],
154
+ storage_type_min=quant_min,
155
+ storage_type_max=quant_max,
156
+ )
157
+ return stablehlo.custom_call(
158
+ call_target_name="odml_torch.uniform_quantize",
159
+ inputs=[input],
160
+ result=[input_ty],
161
+ backend_config=ir.StringAttr.get(
162
+ str(ir.RankedTensorType.get(input_ty.shape, qty))
163
+ ),
164
+ )
165
+
166
+
167
+ @lower(torch.ops.quantized_decomposed.dequantize_per_tensor)
168
+ @lower(torch.ops.quantized_decomposed.dequantize_per_channel)
169
+ def _dequantize(lctx: LoweringContext, input: ir.Value, *args, **kwargs):
170
+ result_meta = lctx.node.meta.get("tensor_meta")
171
+ result_elty = utils.torch_dtype_to_ir_element_type(result_meta.dtype)
172
+
173
+ return stablehlo.custom_call(
174
+ call_target_name="odml_torch.uniform_dequantize",
175
+ inputs=[input],
176
+ result=[ir.RankedTensorType.get(result_meta.shape, result_elty)],
177
+ )
@@ -0,0 +1,142 @@
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
+ import uuid
16
+
17
+ from ai_edge_torch.odml_torch import export_utils
18
+ from ai_edge_torch.odml_torch.lowerings import context
19
+ from ai_edge_torch.odml_torch.lowerings import registry
20
+ from jax._src.lib.mlir import ir
21
+ from jax._src.lib.mlir.dialects import func
22
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
23
+ import numpy as np
24
+ import torch
25
+ import torch.utils._pytree as pytree
26
+
27
+ LoweringContext = context.LoweringContext
28
+ lower = registry.lower
29
+
30
+
31
+ def _random_lowering(
32
+ lctx: LoweringContext,
33
+ size: list[int],
34
+ generator,
35
+ dtype: torch.dtype,
36
+ rand_tensor,
37
+ composite_name: str,
38
+ ):
39
+ if dtype is None:
40
+ dtype = torch.float32
41
+
42
+ rand_tensor = rand_tensor.type(dtype)
43
+ data = rand_tensor.detach().numpy()
44
+
45
+ shape, _ = pytree.tree_flatten(size)
46
+ elty = export_utils.torch_dtype_to_ir_element_type(dtype)
47
+
48
+ decomp_name = f"{composite_name}.impl_{uuid.uuid4().hex[:8]}"
49
+
50
+ with ir.InsertionPoint(lctx.ir_module.body):
51
+
52
+ @func.FuncOp.from_py_func(
53
+ ir.RankedTensorType.get(
54
+ [len(shape)],
55
+ ir.IntegerType.get_signless(32),
56
+ ),
57
+ name=decomp_name,
58
+ )
59
+ def _rand_impl(_):
60
+ return [stablehlo.constant(ir.DenseElementsAttr.get(data))]
61
+
62
+ seed, seed2 = (
63
+ torch.randint(
64
+ torch.iinfo(torch.int64).min,
65
+ torch.iinfo(torch.int64).max,
66
+ (2,),
67
+ dtype=torch.int64,
68
+ generator=generator,
69
+ )
70
+ .detach()
71
+ .numpy()
72
+ )
73
+
74
+ shape_ = stablehlo.constant(
75
+ ir.DenseElementsAttr.get(np.array(shape, dtype=np.int32))
76
+ )
77
+ return stablehlo.CompositeOp(
78
+ result=[ir.RankedTensorType.get(shape, elty)],
79
+ inputs=[shape_],
80
+ name=composite_name,
81
+ composite_attributes=ir.DictAttr.get({
82
+ "seed": ir.IntegerAttr.get(ir.IntegerType.get_signless(64), seed),
83
+ "seed2": ir.IntegerAttr.get(ir.IntegerType.get_signless(64), seed2),
84
+ }),
85
+ decomposition=decomp_name,
86
+ ).results[0]
87
+
88
+
89
+ # Schema:
90
+ # - aten::rand(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None,
91
+ # Device? device=None, bool? pin_memory=None) -> Tensor
92
+ # - aten::rand.generator(SymInt[] size, *, Generator? generator,
93
+ # ScalarType? dtype=None, Layout? layout=None, Device? device=None,
94
+ # bool? pin_memory=None) -> Tensor
95
+ @registry.lower(torch.ops.aten.rand)
96
+ def _aten_rand(
97
+ lctx: LoweringContext,
98
+ size,
99
+ generator=None,
100
+ dtype=None,
101
+ layout=torch.strided,
102
+ device=None,
103
+ pin_memory=False,
104
+ ):
105
+ return _random_lowering(
106
+ lctx,
107
+ size,
108
+ generator,
109
+ dtype,
110
+ rand_tensor=torch.ops.aten.rand.generator(
111
+ size, generator=generator, dtype=dtype
112
+ ),
113
+ composite_name="odml.random_uniform",
114
+ )
115
+
116
+
117
+ # Schema:
118
+ # - aten::randn(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None,
119
+ # Device? device=None, bool? pin_memory=None) -> Tensor
120
+ # - aten::randn.generator(SymInt[] size, *, Generator? generator,
121
+ # ScalarType? dtype=None, Layout? layout=None, Device? device=None,
122
+ # bool? pin_memory=None) -> Tensor
123
+ @registry.lower(torch.ops.aten.randn)
124
+ def _aten_randn(
125
+ lctx: LoweringContext,
126
+ size,
127
+ generator=None,
128
+ dtype=None,
129
+ layout=torch.strided,
130
+ device=None,
131
+ pin_memory=False,
132
+ ):
133
+ return _random_lowering(
134
+ lctx,
135
+ size,
136
+ generator,
137
+ dtype,
138
+ rand_tensor=torch.ops.aten.randn.generator(
139
+ size, generator=generator, dtype=dtype
140
+ ),
141
+ composite_name="odml.random_standard_normal",
142
+ )
@@ -0,0 +1,42 @@
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
+ """Define context object for export and MLIR lowerings."""
16
+
17
+ import dataclasses
18
+ from jax._src.lib.mlir import ir
19
+ import torch
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class LoweringContext:
24
+ """The context object used in export interpreter and MLIR lowerings."""
25
+
26
+ ir_context: ir.Context
27
+ ir_module: ir.Module
28
+ ir_location: ir.Location = None
29
+ node: torch.fx.Node = None
30
+
31
+ @property
32
+ def ctx(self):
33
+ """Shortcut for ir_context."""
34
+ return self.ir_context
35
+
36
+ @property
37
+ def loc(self):
38
+ """Shortcut for ir_location."""
39
+ return self.ir_location
40
+
41
+ def replace(self, **kwargs):
42
+ return dataclasses.replace(self, **kwargs)
@@ -0,0 +1,69 @@
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
+ """Torch export decompositions to run before lowering."""
16
+
17
+ import functools
18
+
19
+ import torch
20
+
21
+
22
+ @functools.cache
23
+ def decompositions():
24
+ # Base: Core ATen decompositions
25
+ decompositions = torch._decomp.core_aten_decompositions()
26
+
27
+ decompositions.update(
28
+ torch._decomp.get_decompositions([
29
+ torch.ops.aten.upsample_nearest2d,
30
+ torch.ops.aten._native_batch_norm_legit.no_stats,
31
+ torch.ops.aten._native_batch_norm_legit_functional,
32
+ torch.ops.aten._adaptive_avg_pool2d,
33
+ torch.ops.aten._adaptive_avg_pool3d,
34
+ torch.ops.aten.grid_sampler_2d,
35
+ torch.ops.aten.native_group_norm,
36
+ torch.ops.aten.native_dropout,
37
+ torch.ops.aten.reflection_pad1d,
38
+ torch.ops.aten.reflection_pad2d,
39
+ torch.ops.aten.reflection_pad3d,
40
+ torch.ops.aten.replication_pad1d,
41
+ torch.ops.aten.replication_pad2d,
42
+ torch.ops.aten.replication_pad3d,
43
+ torch.ops.aten.addmm,
44
+ ])
45
+ )
46
+
47
+ torch._decomp.remove_decompositions(
48
+ decompositions,
49
+ [
50
+ torch.ops.aten.roll,
51
+ # Torch's default einsum impl/decompositions is less efficient and
52
+ # optimized through converter than JAX's impl. Disable einsum
53
+ # decomposition to use JAX bridge for a more efficient lowering.
54
+ torch.ops.aten.einsum.default,
55
+ ],
56
+ )
57
+
58
+ # Override noop aten op decompositions for faster run_decompositions.
59
+ decompositions[torch.ops.aten.alias.default] = lambda x: x
60
+ decompositions[torch.ops.aten.detach.default] = lambda x: x
61
+
62
+ # Override _safe_softmax decompositions with regular softmax.
63
+ # _safe_softmax introduces additional check-select ops to guard extreme
64
+ # input values to softmax, which could make the converted model inefficient
65
+ # on-device.
66
+ if hasattr(torch.ops.aten, "_safe_softmax"):
67
+ decompositions[torch.ops.aten._safe_softmax.default] = torch.softmax
68
+
69
+ return decompositions
@@ -0,0 +1,65 @@
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
+ """Torch op decompositions and MLIR lowerings registry."""
16
+
17
+ from typing import Any, Callable
18
+
19
+ import torch
20
+
21
+ from . import context
22
+
23
+
24
+ class LoweringRegistry:
25
+ """Registry object for torch op decompositions and to-MLIR lowerings."""
26
+
27
+ def __init__(self):
28
+ self.registered_ops = {}
29
+
30
+ def lookup(self, op_or_name):
31
+ candidate = self._get_lowering(op_or_name)
32
+ if candidate is None:
33
+ if isinstance(op_or_name, torch._ops.OpOverloadPacket):
34
+ candidate = self._get_lowering(op_or_name.default)
35
+ if isinstance(op_or_name, torch._ops.OpOverload):
36
+ candidate = self._get_lowering(op_or_name.overloadpacket)
37
+ return candidate
38
+
39
+ def _get_lowering(self, op):
40
+ candidate = self.registered_ops.get(op)
41
+ return candidate
42
+
43
+ def register(self, op, lowering):
44
+ if isinstance(op, torch._ops.OpOverloadPacket):
45
+ ops = [getattr(op, overload) for overload in op.overloads()]
46
+ else:
47
+ ops = [op]
48
+
49
+ for op in ops:
50
+ self.registered_ops[op] = lowering
51
+
52
+
53
+ global_registry = LoweringRegistry()
54
+
55
+
56
+ def lookup(op):
57
+ return global_registry.lookup(op)
58
+
59
+
60
+ def lower(op):
61
+ def inner(lowering: Callable[[context.LoweringContext, ...], Any]):
62
+ global_registry.register(op, lowering)
63
+ return lowering
64
+
65
+ return inner
@@ -0,0 +1,201 @@
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 building MLIR lowerings."""
16
+
17
+ import functools
18
+ import numbers
19
+ from typing import Any
20
+ from typing import Optional
21
+
22
+ from jax._src.lib.mlir import ir
23
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
24
+ import numpy as np
25
+ import torch
26
+
27
+
28
+ def torch_dtype_to_ir_element_type(dtype):
29
+ ty_get = {
30
+ torch.double: ir.F64Type.get,
31
+ torch.float32: ir.F32Type.get,
32
+ torch.half: ir.F16Type.get,
33
+ torch.long: functools.partial(ir.IntegerType.get_signless, 64),
34
+ torch.int32: functools.partial(ir.IntegerType.get_signless, 32),
35
+ torch.int16: functools.partial(ir.IntegerType.get_signless, 16),
36
+ torch.int8: functools.partial(ir.IntegerType.get_signless, 8),
37
+ torch.bool: functools.partial(ir.IntegerType.get_signless, 1),
38
+ }[dtype]
39
+ return ty_get()
40
+
41
+
42
+ def splat(val, ty, shape=tuple(), *, loc: Optional[Any] = None):
43
+ if isinstance(ty, ir.IntegerType):
44
+ if ty.width == 1:
45
+ attr = ir.BoolAttr.get(bool(val))
46
+ else:
47
+ attr = ir.IntegerAttr.get(ty, int(val))
48
+ elif isinstance(ty, ir.FloatType):
49
+ attr = ir.FloatAttr.get(ty, val)
50
+ else:
51
+ raise ValueError("Unsupported type: %s" % str(ty))
52
+
53
+ return stablehlo.constant(
54
+ ir.DenseElementsAttr.get_splat(
55
+ ir.RankedTensorType.get(shape, ty),
56
+ attr,
57
+ ),
58
+ loc=loc,
59
+ )
60
+
61
+
62
+ def get_common_broadcast_shape(
63
+ shape_1: list[int], shape_2: list[int]
64
+ ) -> Optional[list[int]]:
65
+ if not shape_1 and not shape_2:
66
+ return None
67
+
68
+ shape_1 = shape_1 if shape_1 else [1]
69
+ shape_2 = shape_2 if shape_2 else [1]
70
+
71
+ length_diff = abs(len(shape_1) - len(shape_2))
72
+ if len(shape_1) < len(shape_2):
73
+ shape_1 = [1] * length_diff + shape_1
74
+ elif len(shape_1) > len(shape_2):
75
+ shape_2 = [1] * length_diff + shape_2
76
+
77
+ common_broadcast_shape = []
78
+ for idx in reversed(range(len(shape_1))):
79
+ dim_size1 = shape_1[idx]
80
+ dim_size2 = shape_2[idx]
81
+
82
+ if dim_size1 == dim_size2:
83
+ common_broadcast_shape.insert(0, dim_size1)
84
+ elif dim_size1 == 1 or dim_size2 == 1:
85
+ common_broadcast_shape.insert(0, max(dim_size1, dim_size2))
86
+ else:
87
+ return None
88
+
89
+ return common_broadcast_shape
90
+
91
+
92
+ def get_broadcast_dimensions(
93
+ shape_from: list[int], shape_to: list[int]
94
+ ) -> list[int]:
95
+ assert get_common_broadcast_shape(shape_from, shape_to) == shape_to
96
+
97
+ ret = []
98
+ for val in range(len(shape_to) - len(shape_from), len(shape_to)):
99
+ ret.append(val)
100
+
101
+ return ir.DenseI64ArrayAttr.get(np.asarray(ret, np.int64))
102
+
103
+
104
+ def broadcast_args_if_needed(
105
+ val_1: ir.Value, val_2: ir.Value
106
+ ) -> tuple[Optional[ir.Value], Optional[ir.Value]]:
107
+ broadcast_shape = get_common_broadcast_shape(
108
+ val_1.type.shape, val_2.type.shape
109
+ )
110
+ if broadcast_shape is None:
111
+ return None, None
112
+
113
+ new_val_1, new_val_2 = val_1, val_2
114
+
115
+ if val_1.type.shape != broadcast_shape:
116
+ new_val_1 = stablehlo.broadcast_in_dim(
117
+ result=ir.RankedTensorType.get(
118
+ broadcast_shape, val_1.type.element_type
119
+ ),
120
+ operand=val_1,
121
+ broadcast_dimensions=get_broadcast_dimensions(
122
+ val_1.type.shape, broadcast_shape
123
+ ),
124
+ )
125
+ if val_2.type.shape != broadcast_shape:
126
+ new_val_2 = stablehlo.broadcast_in_dim(
127
+ result=ir.RankedTensorType.get(
128
+ broadcast_shape, val_2.type.element_type
129
+ ),
130
+ operand=val_2,
131
+ broadcast_dimensions=get_broadcast_dimensions(
132
+ val_2.type.shape, broadcast_shape
133
+ ),
134
+ )
135
+ return new_val_1, new_val_2
136
+
137
+
138
+ def upcast_to_same_type(*vals: ir.Value):
139
+ if not vals:
140
+ return None
141
+ if len(vals) == 1:
142
+ return vals[0]
143
+
144
+ def get_priority(ty: ir.Type):
145
+ priorities = [
146
+ ir.IntegerType.get_signless(1),
147
+ ir.IntegerType.get_signless(16),
148
+ ir.IntegerType.get_signless(32),
149
+ ir.IntegerType.get_signless(64),
150
+ ir.F16Type,
151
+ ir.F32Type,
152
+ ir.F64Type,
153
+ ]
154
+ for i, tycls in enumerate(priorities):
155
+ if tycls.isinstance(ty):
156
+ return i
157
+ raise ValueError("Unsupported type: %s" % str(ty))
158
+
159
+ cast_tycls = type(max([v.type.element_type for v in vals], key=get_priority))
160
+ new_vals = []
161
+ for val in vals:
162
+ if not cast_tycls.isinstance(val.type.element_type):
163
+ val = stablehlo.convert(
164
+ ir.RankedTensorType.get(val.type.shape, cast_tycls.get()), val
165
+ )
166
+ new_vals.append(val)
167
+ return tuple(new_vals)
168
+
169
+
170
+ def minmax(ty: ir.Type) -> tuple[numbers.Number, numbers.Number]:
171
+ if isinstance(ty, ir.IntegerType):
172
+ if ty.is_unsigned:
173
+ return (0, 1 << ty.width)
174
+ else:
175
+ return (-(1 << (ty.width - 1)), (1 << (ty.width - 1)) - 1)
176
+ elif isinstance(ty, ir.F16Type):
177
+ return (np.finfo(np.float16).min, np.finfo(np.float16).max)
178
+ elif isinstance(ty, ir.F32Type):
179
+ return (np.finfo(np.float32).min, np.finfo(np.float32).max)
180
+ elif isinstance(ty, ir.F64Type):
181
+ return (np.finfo(np.float64).min, np.finfo(np.float64).max)
182
+ else:
183
+ raise ValueError("Unsupported type: %s" % ty)
184
+
185
+
186
+ def convert_int_to_float(t: ir.Value) -> ir.Value:
187
+ """Converts an input with type ir.IntegerType to an ir.FloatType of equivalent width."""
188
+ elty = t.type.element_type
189
+ if not isinstance(elty, ir.IntegerType):
190
+ raise ValueError(
191
+ "Expected input with integer type, received %s" % type(elty)
192
+ )
193
+
194
+ if elty.width == 32:
195
+ return stablehlo.convert(
196
+ ir.RankedTensorType.get(t.type.shape, ir.F32Type.get()), t
197
+ )
198
+ elif elty.width == 64:
199
+ return stablehlo.convert(
200
+ ir.RankedTensorType.get(t.type.shape, ir.F64Type.get()), t
201
+ )