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,180 @@
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 wrap JAX functions for using in ODML Torch lowerings."""
16
+
17
+ import functools
18
+ import inspect
19
+ from typing import Any, Callable, cast
20
+ import uuid
21
+ from ai_edge_torch.odml_torch import export_utils
22
+ from ai_edge_torch.odml_torch import passes
23
+ from ai_edge_torch.odml_torch.jax_bridge import utils
24
+ import jax
25
+ from jax._src.lib.mlir import ir
26
+ from jax._src.lib.mlir.dialects import func
27
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
28
+ import torch.utils._pytree as pytree
29
+
30
+ # Jax double (64bit) precision is required to generate StableHLO mlir with
31
+ # i64/f64 tensors from Jax bridged lowerings. If not set properly, all the
32
+ # 64bit tensors would be truncated to 32bit dtype and potentially break the
33
+ # lowering.
34
+ jax.config.update("jax_enable_x64", True)
35
+
36
+
37
+ def _lower_to_ir_text(
38
+ jaxfn, args, kwargs, ir_input_names: list[str] = None
39
+ ) -> tuple[str, list[ir.Value]]:
40
+ args = utils.tree_map_list_to_tuple(args)
41
+ kwargs = utils.tree_map_list_to_tuple(kwargs)
42
+
43
+ names_args = [
44
+ *zip(inspect.signature(jaxfn).parameters.keys(), args),
45
+ *kwargs.items(),
46
+ ]
47
+
48
+ static_argnames = []
49
+ jax_lower_static_kwargs = {}
50
+ jax_lower_args = []
51
+ jax_lower_argnames = []
52
+ ir_inputs = []
53
+
54
+ for i, (name, arg) in enumerate(names_args):
55
+ is_positional = i < len(args)
56
+ if not utils.is_ir_variable(arg):
57
+ static_argnames.append(name)
58
+ jax_lower_static_kwargs[name] = arg
59
+ else:
60
+ # Enforce the arg order in the mlir is the same as the lowering func
61
+ jax_lower_args.append(utils.ir_variable_to_jax(arg))
62
+
63
+ if is_positional and len(jax_lower_args) == i + 1:
64
+ # The first N continuous tensor args are passed to the lowering func
65
+ # as positional args, when they passed to the bridged func as
66
+ # positional args also.
67
+ jax_lower_argnames.append(None)
68
+ else:
69
+ # Otherwise pass the arg to the lowering func as keyword arg.
70
+ jax_lower_argnames.append(name)
71
+
72
+ if ir_input_names is None or name in ir_input_names:
73
+ # ir variable can be a nested tuple, while mlir args should be flat.
74
+ ir_inputs += [
75
+ x for x in pytree.tree_flatten(arg)[0] if isinstance(x, ir.Value)
76
+ ]
77
+
78
+ def lower_wrapper(*args):
79
+ nonlocal jax_lower_static_kwargs
80
+
81
+ jaxfn_args = []
82
+ jaxfn_kwargs = jax_lower_static_kwargs.copy()
83
+ for name, arg in zip(jax_lower_argnames, args):
84
+ if name is None:
85
+ jaxfn_args.append(arg)
86
+ else:
87
+ jaxfn_kwargs[name] = arg
88
+
89
+ return jaxfn(*jaxfn_args, **jaxfn_kwargs)
90
+
91
+ return jax.jit(lower_wrapper).lower(*jax_lower_args).as_text(), ir_inputs
92
+
93
+
94
+ def wrap(jaxfn: Callable[Any, Any], ir_input_names: list[str] = None):
95
+ """Return the wrapped JAX function to be used in ODMLTorch lowerings.
96
+
97
+ If the given jaxfn has signature `jaxfn(*args, **kwargs) -> return`, the
98
+ wrapped function would:
99
+ - Have signature `wrapped(lctx: odml_torch.export.LoweringContext, *args,
100
+ **kwargs) -> return`.
101
+ - Accept mlir.ir.Value for all params expecting jax.Array as inputs.
102
+ - Return mlir.ir.Value for all jax.Array outputs from jaxfn.
103
+
104
+ Args:
105
+ jaxfn: The JAX function to be wrapped.
106
+ ir_input_names: The input (param) names of the JAX function to be used in
107
+ the MLIR lowering. This is useful when the JAX impl only depends on
108
+ specific inputs to the function. If not specified, all ir.Value passed to
109
+ the wrapped function are assumed to be used in the lowering.
110
+ """
111
+
112
+ @functools.wraps(jaxfn)
113
+ def wrapped(lctx, *args, **kwargs):
114
+
115
+ ir_text, ir_inputs = _lower_to_ir_text(
116
+ jaxfn,
117
+ args,
118
+ kwargs,
119
+ ir_input_names=ir_input_names,
120
+ )
121
+
122
+ module = ir.Module.parse(ir_text)
123
+ passes.strip_debuginfo(module)
124
+
125
+ symbol_table = ir.SymbolTable(module.operation)
126
+ main_func = symbol_table["main"]
127
+
128
+ with ir.InsertionPoint.at_block_begin(lctx.ir_module.body):
129
+ cloned_func = cast(func.FuncOp, main_func.clone())
130
+ cloned_func_name = f"{jaxfn.__name__}_{uuid.uuid4().hex[:8]}"
131
+ cloned_func.attributes["sym_name"] = ir.StringAttr.get(cloned_func_name)
132
+ cloned_func.attributes["sym_visibility"] = ir.StringAttr.get("private")
133
+
134
+ # HACK: Use the custom inliner implemented in Python because MLIR inline
135
+ # pass from JAX's MLIR pybinding build in OSS cannot properly inline
136
+ # func.call ops.
137
+ # This should be switched to `passes.inline(module)` when we have our own
138
+ # MLIR pybinding build.
139
+ export_utils.inline(symbol_table, cloned_func.entry_block)
140
+
141
+ if not cloned_func.arguments:
142
+ # Known edge case: when the lowering does not depend on input but
143
+ # just the meta of input like shape or dtype.
144
+ ir_inputs = []
145
+
146
+ results = func.CallOp(cloned_func, ir_inputs).results
147
+
148
+ if lctx.node is None:
149
+ return results[0] if len(results) == 1 else results
150
+
151
+ out_avals = lctx.node.meta.get("tensor_meta") or lctx.node.meta.get("val")
152
+
153
+ if out_avals is None:
154
+ return results[0] if len(results) == 1 else results
155
+
156
+ def sanitize_result_elty(result, aval):
157
+ # JAX implementation may not respect aten op's output dtype. For example,
158
+ # JAX may implement a slightly different dtype upcast rules, leads to
159
+ # different result's dtype from bridged lowering and torch op output.
160
+ # Here we add an additional `stablehlo.convert` op when dtype does not
161
+ # match, to ensure the lowering's result dtype will always be the same
162
+ # as torch op's output dtype.
163
+ if aval is None:
164
+ return result
165
+
166
+ target_elty = export_utils.torch_dtype_to_ir_element_type(aval.dtype)
167
+ if result.type.element_type == target_elty:
168
+ return result
169
+ return stablehlo.convert(
170
+ ir.RankedTensorType.get(result.type.shape, target_elty), result
171
+ )
172
+
173
+ if len(results) == 1:
174
+ return sanitize_result_elty(results[0], out_avals)
175
+ return [
176
+ sanitize_result_elty(result, aval)
177
+ for result, aval in zip(results, out_avals)
178
+ ]
179
+
180
+ return wrapped
@@ -0,0 +1,75 @@
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 Jax bridge."""
16
+
17
+ from ai_edge_torch import odml_torch
18
+ import jax
19
+ import jax.numpy as jnp
20
+ from jax._src.lib.mlir import ir
21
+ import torch
22
+
23
+
24
+ def t2j_dtype(dtype):
25
+ return {
26
+ torch.bfloat16: jnp.bfloat16,
27
+ torch.half: jnp.float16,
28
+ torch.float32: jnp.float32,
29
+ torch.double: jnp.double,
30
+ torch.long: jnp.int64,
31
+ torch.int64: jnp.int64,
32
+ torch.int32: jnp.int32,
33
+ torch.int16: jnp.int16,
34
+ torch.int8: jnp.int8,
35
+ torch.uint8: jnp.uint8,
36
+ torch.bool: jnp.bool_,
37
+ torch.complex64: jnp.complex64,
38
+ torch.complex128: jnp.complex128,
39
+ }.get(dtype)
40
+
41
+
42
+ def is_ir_variable(value):
43
+ if isinstance(value, ir.Value):
44
+ return True
45
+ if isinstance(value, (list, tuple)):
46
+ return any(is_ir_variable(x) for x in value)
47
+ return False
48
+
49
+
50
+ def ir_variable_to_jax(value):
51
+ if isinstance(value, (list, tuple)):
52
+ return tuple([ir_variable_to_jax(x) for x in value])
53
+ elif not isinstance(value, ir.Value):
54
+ return value
55
+ elif not isinstance(value.type, ir.RankedTensorType):
56
+ raise ValueError(
57
+ f"ir.Value to JAX must be in ir.RankedTensorType, got {value}"
58
+ )
59
+
60
+ return jax.ShapeDtypeStruct(
61
+ value.type.shape,
62
+ t2j_dtype(
63
+ odml_torch.export_utils.ir_element_type_to_torch_dtype(
64
+ value.type.element_type
65
+ )
66
+ ),
67
+ )
68
+
69
+
70
+ def tree_map_list_to_tuple(value):
71
+ if isinstance(value, dict):
72
+ return {k: tree_map_list_to_tuple(v) for k, v in value.items()}
73
+ if isinstance(value, (list, tuple)):
74
+ return tuple([tree_map_list_to_tuple(v) for v in value])
75
+ return value
@@ -0,0 +1,27 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ from . import _basic
16
+ from . import _batch_norm
17
+ from . import _convolution
18
+ from . import _jax_lowerings
19
+ from . import _layer_norm
20
+ from . import _quantized_decomposed
21
+ from . import _rand
22
+ from . import context
23
+ from . import registry
24
+ from . import utils
25
+ from .decomp import decompositions
26
+ from .registry import lookup
27
+ from .registry import lower
@@ -0,0 +1,294 @@
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 math
16
+ from typing import Optional, Union
17
+
18
+ from ai_edge_torch.odml_torch import export_utils
19
+ from ai_edge_torch.odml_torch.lowerings import context
20
+ from ai_edge_torch.odml_torch.lowerings import registry
21
+ from ai_edge_torch.odml_torch.lowerings import utils
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
+ LoweringContext = context.LoweringContext
28
+ lower = registry.lower
29
+
30
+
31
+ # add(Tensor self, Tensor other) -> Tensor
32
+ # @lower(torch.ops.aten.add)
33
+ def _aten_add(lctx, x: ir.Value, y: ir.Value, alpha=1):
34
+ x, y = utils.upcast_to_same_type(x, y)
35
+ x, y = utils.broadcast_args_if_needed(x, y)
36
+ if alpha == 1:
37
+ return stablehlo.add(x, y)
38
+
39
+ alpha_splat = utils.splat(alpha, y.type.element_type, y.type.shape)
40
+ return stablehlo.add(x, stablehlo.multiply(y, alpha_splat))
41
+
42
+
43
+ # mul.Tensor(Tensor self, Tensor other) -> Tensor
44
+ # @lower(torch.ops.aten.mul.Tensor)
45
+ def _aten_mul_tensor(lctx, self: ir.Value, other: ir.Value):
46
+ self, other = utils.upcast_to_same_type(self, other)
47
+ self, other = utils.broadcast_args_if_needed(self, other)
48
+
49
+ return stablehlo.multiply(self, other)
50
+
51
+
52
+ # cat(Tensor[] tensors, int dim=0) -> Tensor
53
+ # @lower(torch.ops.aten.cat)
54
+ def _aten_cat(lctx, tensors: list[ir.Value], dim: int = 1):
55
+ return stablehlo.ConcatenateOp(tensors, dim).result
56
+
57
+
58
+ # view(Tensor(a) self, SymInt[] size) -> Tensor(a)
59
+ # @lower(torch.ops.aten.view)
60
+ def _aten_view(lctx, self: ir.Value, size: list[int]):
61
+ return stablehlo.ReshapeOp(
62
+ ir.RankedTensorType.get(size, self.type.element_type), self
63
+ ).result
64
+
65
+
66
+ # hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor
67
+ @lower(torch.ops.aten.hardtanh)
68
+ def _aten_hardtanh(
69
+ lctx,
70
+ self: ir.Value,
71
+ min_val: Union[int, float] = -1.0,
72
+ max_val: Union[int, float] = 1.0,
73
+ ):
74
+ elty = self.type.element_type
75
+ min_val = utils.splat(min_val, elty)
76
+ max_val = utils.splat(max_val, elty)
77
+
78
+ return stablehlo.clamp(min_val, self, max_val)
79
+
80
+
81
+ # mean(Tensor self, *, ScalarType? dtype=None) -> Tensor
82
+ # mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *,
83
+ # ScalarType? dtype=None) -> Tensor
84
+ @lower(torch.ops.aten.mean)
85
+ @lower(torch.ops.aten.mean.dim)
86
+ def _aten_mean_dim(
87
+ lctx,
88
+ self: ir.Value,
89
+ dim: Optional[list[int]] = None,
90
+ keepdim: bool = False,
91
+ *,
92
+ dtype=None,
93
+ ):
94
+ self_shape = self.type.shape
95
+ self_elty = self.type.element_type
96
+ if dim is None:
97
+ dim = list(range(len(self_shape)))
98
+ dim = [len(self_shape) + d if d < 0 else d for d in dim]
99
+ dim_ = ir.DenseI64ArrayAttr.get(np.asarray(dim, np.int64))
100
+ dim_to_keep = [d for d in range(len(self_shape)) if d not in dim]
101
+ dim_to_keep_ = ir.DenseI64ArrayAttr.get(np.asarray(dim_to_keep, np.int64))
102
+
103
+ zero_ = utils.splat(0.0, self_elty)
104
+
105
+ reduce_result_shape = [
106
+ s for d, s in enumerate(self_shape) if d in dim_to_keep
107
+ ]
108
+ reduce_result_ty = ir.RankedTensorType.get(reduce_result_shape, self_elty)
109
+ reduce_op = stablehlo.ReduceOp([reduce_result_ty], [self], [zero_], dim_)
110
+
111
+ reducer_arg_ty = ir.RankedTensorType.get(tuple(), self_elty)
112
+ reducer = reduce_op.regions[0].blocks.append(reducer_arg_ty, reducer_arg_ty)
113
+ with ir.InsertionPoint(reducer):
114
+ stablehlo.return_(
115
+ [stablehlo.add(reducer.arguments[0], reducer.arguments[1])]
116
+ )
117
+
118
+ sum_ = reduce_op.result
119
+ if keepdim:
120
+ sum_ = stablehlo.broadcast_in_dim(
121
+ ir.RankedTensorType.get(
122
+ [s if d in dim_to_keep else 1 for d, s in enumerate(self_shape)],
123
+ self_elty,
124
+ ),
125
+ sum_,
126
+ dim_to_keep_,
127
+ )
128
+
129
+ dim_els = math.prod([s for d, s in enumerate(self_shape) if d in dim])
130
+ dim_els_ = utils.splat(dim_els, self_elty)
131
+ div_ = stablehlo.broadcast_in_dim(
132
+ sum_.type, dim_els_, ir.DenseI64ArrayAttr.get([])
133
+ )
134
+ mean_ = stablehlo.divide(sum_, div_)
135
+
136
+ return mean_
137
+
138
+
139
+ # https://pytorch.org/docs/stable/generated/torch.clone.html
140
+ # https://github.com/pytorch/pytorch/blob/a95ceb51a23ae33c00b3a99224143c609b1b3eb3/aten/src/ATen/native/TensorFactories.cpp#L1730
141
+ @lower(torch.ops.aten.clone)
142
+ def _aten_clone(lctx, x: ir.Value, *, memory_format=None):
143
+ return x
144
+
145
+
146
+ # https://pytorch.org/docs/stable/generated/torch.permute.html
147
+ # https://github.com/pytorch/pytorch/blob/519151a062a9bd4f0d32a9c7c7eae47d7ed847b2/aten/src/ATen/native/TensorShape.cpp#L1448
148
+ # https://github.com/openxla/stablehlo/blob/main/docs/spec.md#transpose
149
+ @lower(torch.ops.aten.permute)
150
+ def _aten_permute(lctx, x: ir.Value, dims: list[int]):
151
+ dim = len(x.type.shape)
152
+ return stablehlo.transpose(x, ir.DenseI64ArrayAttr.get(dims))
153
+
154
+
155
+ # https://pytorch.org/docs/stable/generated/torch.mm.html
156
+ # https://github.com/pytorch/pytorch/blob/ffabb25c489df1dc631a577c12a0c843c8b202f3/aten/src/ATen/native/LinearAlgebra.cpp#L193
157
+ # https://github.com/openxla/stablehlo/blob/main/docs/spec.md#dot_general
158
+ @lower(torch.ops.aten.mm)
159
+ def _aten_mm(mod, mat1: ir.Value, mat2: ir.Value) -> ir.Value:
160
+ mat1_shape = mat1.type.shape
161
+ mat2_shape = mat2.type.shape
162
+ mat1_dims = len(mat1_shape)
163
+ mat2_dims = len(mat2_shape)
164
+
165
+ if mat1_dims != 2 or mat1_dims != 2:
166
+ raise ValueError(
167
+ "Both arguments must be 2D matrices, received dimensions %d and %d"
168
+ % (mat1_dims, mat2_dims)
169
+ )
170
+
171
+ if mat1_shape[1] != mat2_shape[0]:
172
+ raise ValueError(
173
+ "mat1 and mat2 shapes cannot be multiplied, received shapes %s and %s"
174
+ % (mat1_shape, mat2_shape)
175
+ )
176
+
177
+ dot_dnums = stablehlo.DotDimensionNumbers.get(
178
+ lhs_batching_dimensions=[],
179
+ rhs_batching_dimensions=[],
180
+ lhs_contracting_dimensions=(1,),
181
+ rhs_contracting_dimensions=(0,),
182
+ )
183
+ return stablehlo.dot_general(
184
+ ir.RankedTensorType.get(
185
+ (mat1.type.shape[0], mat2.type.shape[1]), mat1.type.element_type
186
+ ),
187
+ mat1,
188
+ mat2,
189
+ dot_dnums,
190
+ )
191
+
192
+
193
+ # https://pytorch.org/docs/stable/generated/torch.div.html
194
+ # https://openxla.org/stablehlo/spec#divide
195
+ # TODO: support rounding mode and type promotion (see torch.div spec).
196
+ # @lower(torch.ops.aten.div)
197
+ def _aten_div(mod, x, y, *, rounding_mode=None, out=None) -> ir.Value:
198
+ # By default, PyTorch performs a "true" division like Python 3. This requires
199
+ # casting integer input types to float to achieve the same semantics using
200
+ # stablehlo.divide.
201
+ if isinstance(x.type.element_type, ir.IntegerType):
202
+ x = utils.convert_int_to_float(x)
203
+ if isinstance(y.type.element_type, ir.IntegerType):
204
+ y = utils.convert_int_to_float(y)
205
+
206
+ x, y = utils.broadcast_args_if_needed(x, y)
207
+
208
+ return stablehlo.divide(x, y)
209
+
210
+
211
+ # https://pytorch.org/docs/stable/generated/torch.floor.html
212
+ # https://openxla.org/stablehlo/spec#floor
213
+ @lower(torch.ops.aten.floor)
214
+ def _aten_floor(lctx, x: ir.Value, *, out=None) -> ir.Value:
215
+ return stablehlo.floor(x)
216
+
217
+
218
+ # Schema:
219
+ # - aten::cat(Tensor[] tensors, int dim=0) -> Tensor
220
+ # Torch Reference:
221
+ # - https://pytorch.org/docs/main/generated/torch.cat.html
222
+ @lower(torch.ops.aten.cat.default)
223
+ def _aten_cat(lctx: LoweringContext, tensors, dim=0):
224
+ assert tensors
225
+ non_empty_tensors = [t for t in tensors if np.prod(t.type.shape) != 0]
226
+ out_aval = lctx.node.meta.get("tensor_meta") or lctx.node.meta.get("val")
227
+ if not non_empty_tensors:
228
+ return utils.splat(
229
+ 0,
230
+ export_utils.torch_dtype_to_ir_element_type(out_aval.dtype),
231
+ out_aval.shape,
232
+ )
233
+
234
+ if dim < 0:
235
+ dim = dim + len(out_aval.shape)
236
+ dim = ir.IntegerAttr.get(ir.IntegerType.get_signless(64), dim)
237
+
238
+ return stablehlo.concatenate(non_empty_tensors, dim)
239
+
240
+
241
+ # Schema:
242
+ # - aten::slice_scatter(Tensor self, Tensor src, int dim=0, SymInt?
243
+ # start=None, SymInt? end=None, SymInt step=1) -> Tensor
244
+ # Torch Reference:
245
+ # - https://pytorch.org/docs/stable/generated/torch.slice_scatter.html
246
+ # - https://github.com/pytorch/pytorch/blob/18f9331e5deb4c02ae5c206e133a9b4add49bd97/aten/src/ATen/native/TensorShape.cpp#L4002
247
+ @lower(torch.ops.aten.slice_scatter)
248
+ def _aten_slice_scatter(lctx, self, src, dim=0, start=None, end=None, step=1):
249
+ start = start if start is not None else 0
250
+ end = end if end is not None else self.type.shape[dim]
251
+
252
+ start, end = np.clip(
253
+ [start, end], -self.type.shape[dim], self.type.shape[dim]
254
+ )
255
+
256
+ if start < 0:
257
+ start = self.type.shape[dim] + start
258
+ if end < 0:
259
+ end = self.type.shape[dim] + end
260
+
261
+ if end <= start or np.prod(src.type.shape) == 0:
262
+ return self
263
+
264
+ end = start + step * math.ceil((end - start) / step) - (step - 1)
265
+ padding_low = start
266
+ padding_high = self.type.shape[dim] - end
267
+ interior_padding = step - 1
268
+
269
+ rank = len(self.type.shape)
270
+ src = stablehlo.pad(
271
+ src,
272
+ utils.splat(0, src.type.element_type, []),
273
+ edge_padding_low=[padding_low if i == dim else 0 for i in range(rank)],
274
+ edge_padding_high=[padding_high if i == dim else 0 for i in range(rank)],
275
+ interior_padding=[
276
+ interior_padding if i == dim else 0 for i in range(rank)
277
+ ],
278
+ )
279
+
280
+ slices = [
281
+ slice(start, end, step) if i == dim else slice(None, None, None)
282
+ for i in range(rank)
283
+ ]
284
+ pred = np.ones(self.type.shape, dtype=np.bool_)
285
+ pred[np.index_exp[tuple(slices)]] = False
286
+ pred = stablehlo.constant(
287
+ ir.DenseElementsAttr.get(
288
+ np.packbits(pred, bitorder="little"),
289
+ type=ir.IntegerType.get_signless(1),
290
+ shape=pred.shape,
291
+ )
292
+ )
293
+ out = stablehlo.select(pred, self, src)
294
+ return out
@@ -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
+ """Provides lowering for coreaten to mlir stablehlo op: Convolution"""
16
+
17
+ from typing import Optional
18
+
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
+
24
+ from .registry import lower
25
+
26
+
27
+ # _native_batch_norm_legit_no_training(
28
+ # Tensor input,
29
+ # Tensor? weight,
30
+ # Tensor? bias,
31
+ # Tensor running_mean,
32
+ # Tensor running_var,
33
+ # float momentum,
34
+ # float eps) -> (Tensor, Tensor, Tensor)
35
+ @lower(torch.ops.aten._native_batch_norm_legit_no_training)
36
+ def _native_batch_norm_legit_no_training(
37
+ lctx,
38
+ input_tensor: ir.Value,
39
+ weight: Optional[ir.Value],
40
+ bias: Optional[ir.Value],
41
+ running_mean: ir.Value,
42
+ running_var: ir.Value,
43
+ momentum: float,
44
+ eps: float,
45
+ ):
46
+ if weight is None:
47
+ weight = utils.splat(
48
+ 1, running_mean.type.element_type, running_mean.type.shape
49
+ )
50
+ if bias is None:
51
+ bias = utils.splat(
52
+ 0, running_mean.type.element_type, running_mean.type.shape
53
+ )
54
+
55
+ return [
56
+ stablehlo.batch_norm_inference(
57
+ input_tensor, weight, bias, running_mean, running_var, eps, 1
58
+ ),
59
+ utils.splat(
60
+ 0, input_tensor.type.element_type
61
+ ), # TODO: return empty array instead
62
+ utils.splat(
63
+ 0, input_tensor.type.element_type
64
+ ), # TODO: return empty array instead
65
+ ]