ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl → 0.3.0.dev20240926__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (169) hide show
  1. ai_edge_torch/__init__.py +5 -4
  2. ai_edge_torch/_convert/conversion.py +112 -0
  3. ai_edge_torch/_convert/conversion_utils.py +64 -0
  4. ai_edge_torch/{convert → _convert}/converter.py +94 -48
  5. ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
  6. ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
  7. ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
  8. ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
  9. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
  10. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
  11. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
  12. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
  13. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
  14. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
  15. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
  16. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
  17. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
  18. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
  19. ai_edge_torch/_convert/signature.py +66 -0
  20. ai_edge_torch/_convert/test/test_convert.py +495 -0
  21. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  22. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  23. ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
  24. ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
  25. ai_edge_torch/config.py +27 -0
  26. ai_edge_torch/conftest.py +20 -0
  27. ai_edge_torch/debug/culprit.py +72 -40
  28. ai_edge_torch/debug/test/test_culprit.py +7 -5
  29. ai_edge_torch/debug/test/test_search_model.py +8 -7
  30. ai_edge_torch/debug/utils.py +14 -3
  31. ai_edge_torch/fx_pass_base.py +101 -0
  32. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
  33. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
  34. ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
  35. ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
  36. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  37. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
  38. ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
  39. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
  40. ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
  41. ai_edge_torch/generative/examples/openelm/verify.py +64 -0
  42. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  43. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
  44. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
  45. ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
  46. ai_edge_torch/generative/examples/phi/phi3.py +286 -0
  47. ai_edge_torch/generative/examples/phi/verify.py +65 -0
  48. ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
  49. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  50. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
  51. ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
  52. ai_edge_torch/generative/examples/smollm/verify.py +62 -0
  53. ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
  54. ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
  55. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
  56. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
  57. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
  58. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
  59. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
  60. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
  61. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
  62. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
  63. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
  64. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
  65. ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
  66. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
  67. ai_edge_torch/generative/examples/t5/t5.py +208 -159
  68. ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
  69. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  70. ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
  71. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
  72. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  73. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
  74. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
  75. ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
  76. ai_edge_torch/generative/fx_passes/__init__.py +4 -5
  77. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
  78. ai_edge_torch/generative/layers/attention.py +141 -102
  79. ai_edge_torch/generative/layers/attention_utils.py +53 -12
  80. ai_edge_torch/generative/layers/builder.py +37 -7
  81. ai_edge_torch/generative/layers/feed_forward.py +39 -14
  82. ai_edge_torch/generative/layers/kv_cache.py +162 -50
  83. ai_edge_torch/generative/layers/model_config.py +84 -30
  84. ai_edge_torch/generative/layers/normalization.py +185 -7
  85. ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
  86. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
  87. ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
  88. ai_edge_torch/generative/layers/unet/builder.py +7 -4
  89. ai_edge_torch/generative/layers/unet/model_config.py +17 -15
  90. ai_edge_torch/generative/quantize/example.py +7 -8
  91. ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
  92. ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
  93. ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
  94. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  95. ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
  96. ai_edge_torch/generative/test/test_model_conversion.py +124 -188
  97. ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
  98. ai_edge_torch/generative/test/test_quantize.py +76 -60
  99. ai_edge_torch/generative/test/utils.py +54 -0
  100. ai_edge_torch/generative/utilities/converter.py +82 -0
  101. ai_edge_torch/generative/utilities/loader.py +120 -57
  102. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
  103. ai_edge_torch/generative/utilities/t5_loader.py +110 -81
  104. ai_edge_torch/generative/utilities/verifier.py +247 -0
  105. ai_edge_torch/hlfb/__init__.py +1 -1
  106. ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
  107. ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
  108. ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
  109. ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
  110. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
  111. ai_edge_torch/lowertools/__init__.py +18 -0
  112. ai_edge_torch/lowertools/_shim.py +80 -0
  113. ai_edge_torch/lowertools/common_utils.py +142 -0
  114. ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
  115. ai_edge_torch/lowertools/test_utils.py +60 -0
  116. ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
  117. ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
  118. ai_edge_torch/model.py +53 -18
  119. ai_edge_torch/odml_torch/__init__.py +20 -0
  120. ai_edge_torch/odml_torch/_torch_future.py +61 -0
  121. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  122. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  123. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  124. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  125. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  126. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  127. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  128. ai_edge_torch/odml_torch/export.py +357 -0
  129. ai_edge_torch/odml_torch/export_utils.py +168 -0
  130. ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
  131. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
  132. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  133. ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
  134. ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
  135. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  136. ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
  137. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
  138. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
  139. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  140. ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
  141. ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
  142. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  143. ai_edge_torch/odml_torch/tf_integration.py +194 -0
  144. ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
  145. ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
  146. ai_edge_torch/quantize/quant_config.py +13 -9
  147. ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
  148. ai_edge_torch/version.py +16 -0
  149. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
  150. ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
  151. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
  152. ai_edge_torch/convert/conversion.py +0 -117
  153. ai_edge_torch/convert/conversion_utils.py +0 -400
  154. ai_edge_torch/convert/fx_passes/__init__.py +0 -59
  155. ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
  156. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
  157. ai_edge_torch/convert/test/test_convert.py +0 -311
  158. ai_edge_torch/convert/test/test_convert_composites.py +0 -192
  159. ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
  160. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
  161. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
  162. ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
  163. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
  164. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
  165. /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
  166. /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
  167. /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
  168. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
  169. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/top_level.txt +0 -0
@@ -12,13 +12,25 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Passes to clean up the model graph for pattern matching."""
16
+
15
17
  import torch
16
18
 
17
19
 
18
20
  def remove_clone_ops(gm: torch.fx.GraphModule):
19
- # torch export adds additional aten.clone nodes to produce contiguous in memory tensors
20
- # depending on tensor sizes for runtime efficiency. However, these unpredictable clone
21
- # nodes can break the pattern matching. Thus remove all clones in model and pattern graphs.
21
+ """Removes clone ops from the graph.
22
+
23
+ torch export adds additional aten.clone nodes to produce contiguous in memory
24
+ tensors depending on tensor sizes for runtime efficiency. However, these
25
+ unpredictable clone nodes can break the pattern matching. Thus remove all
26
+ clones in model and pattern graphs.
27
+
28
+ Args:
29
+ gm: The graph module to remove clone ops from.
30
+
31
+ Returns:
32
+ The graph module with clone ops removed.
33
+ """
22
34
  for node in gm.graph.nodes:
23
35
  if node.op == "call_function" and node.name.startswith("clone"):
24
36
  node.replace_all_uses_with(node.args[0])
@@ -30,6 +42,14 @@ def remove_clone_ops(gm: torch.fx.GraphModule):
30
42
 
31
43
 
32
44
  def remove_dangling_args(gm: torch.fx.GraphModule):
45
+ """Removes dangling args from the graph.
46
+
47
+ Args:
48
+ gm: The graph module to remove dangling args from.
49
+
50
+ Returns:
51
+ The graph module with dangling args removed.
52
+ """
33
53
  nodes_to_erase = []
34
54
  for node in gm.graph.nodes:
35
55
  if node.op == "placeholder" and len(node.users) == 0:
@@ -12,10 +12,12 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- import copy
15
+ """Mark pattern."""
16
+
16
17
  import dataclasses
17
18
  from typing import Any, Callable, Optional, Union
18
19
 
20
+ from ai_edge_torch.hlfb.mark_pattern import passes
19
21
  import torch
20
22
  from torch.export.graph_signature import TensorArgument
21
23
  from torch.fx import Graph
@@ -23,8 +25,6 @@ from torch.fx import GraphModule
23
25
  from torch.fx.passes.utils.matcher_utils import InternalMatch
24
26
  from torch.fx.passes.utils.matcher_utils import SubgraphMatcher
25
27
 
26
- from ai_edge_torch.hlfb.mark_pattern import passes
27
-
28
28
 
29
29
  def _are_equal(x: Any, y: Any) -> bool:
30
30
  if type(x) != type(y):
@@ -46,6 +46,7 @@ def _are_equal(x: Any, y: Any) -> bool:
46
46
  @dataclasses.dataclass
47
47
  class ScalarAttrTracker:
48
48
  """ScalarAttrTracker is used to track the occurrence of a pattern's
49
+
49
50
  scalar arg/attr in the pattern decomposed graph. Since a scalar attr
50
51
  to the pattern can be transformed and turned into a/some ops' scalar
51
52
  arg in the decomposed graph, it would be hard to programmatically get
@@ -58,27 +59,31 @@ class ScalarAttrTracker:
58
59
  pattern_arg_pos (int): the index of the attr to track in the pattern's
59
60
  export_args.
60
61
  transform (Callable): the transform function used when targeting the
61
- occurrence of the attr value in the decomposed graph. An attr value
62
- may be transformed during the decomposition and appear as a derived
63
- value.
64
- inverse_transform (Callable): the inverse transform function that maps
65
- the transformed value back to the original attr value.
62
+ occurrence of the attr value in the decomposed graph. An attr value may be
63
+ transformed during the decomposition and appear as a derived value.
64
+ inverse_transform (Callable): the inverse transform function that maps the
65
+ transformed value back to the original attr value.
66
66
  """
67
67
 
68
68
  attr_name: str
69
69
  pattern_arg_pos: int
70
70
  transform: Callable = lambda x: x
71
71
  inverse_transform: Callable = lambda x: x
72
- _source_targets: list[tuple[Any, Any]] = dataclasses.field(default_factory=list)
72
+ _source_targets: list[tuple[Any, Any]] = dataclasses.field(
73
+ default_factory=list
74
+ )
73
75
 
74
76
  def track(self, *sources):
75
77
  """Register magic values to track the (transformed) attr values in
78
+
76
79
  the pattern decomposed graph.
77
80
  """
78
81
  for source in sources:
79
82
  target = self.transform(source)
80
83
  if not _are_equal(self.inverse_transform(target), source):
81
- raise Exception(f"Invalid transform/inverse_transform for {self.attr_name}")
84
+ raise Exception(
85
+ f"Invalid transform/inverse_transform for {self.attr_name}"
86
+ )
82
87
  self._source_targets.append([source, target])
83
88
  return self
84
89
 
@@ -155,24 +160,22 @@ class Pattern:
155
160
  """The PyTorch computation pattern to match against a model.
156
161
 
157
162
  Args:
158
- name (str): the name of the pattern. It would be propagated to
159
- the `name` attr in StableHLO composite ops for the matched
160
- model subgraphs in the lowering.
163
+ name (str): the name of the pattern. It would be propagated to the `name`
164
+ attr in StableHLO composite ops for the matched model subgraphs in the
165
+ lowering.
161
166
  module (torch.nn.Module or Callable): the PyTorch computation.
162
- export_args (tuple[Any]): the args used to export the pattern module
163
- with torch.export.export. If export_args contains non-tensor
164
- Python scalars, there must be a corresponding attr tracker
165
- in `scalar_attr_trackers` for each scalar arg.
166
- attr_builder (Callable[[Pattern, GraphModule, InternalMatch], Optional[dict[str, Any]]]):
167
- the callable that produces the a scalar attrs dict, which would be
168
- propagated to `attr` in StableHLO composite ops for the matched
169
- model subgraphs in the lowering.
170
- scalar_attr_trackers (list[ScalarAttrTracker]): the trackers
171
- for scalar args in `export_args`, which are used to track
172
- the attr occurrence(s) and retrieve their values from the
173
- matched subgraph.
174
- decomp_table (Optional[dict[torch._ops.OperatorBase, Callable]]):
175
- The decomposition table to be run on the pattern's exported program.
167
+ export_args (tuple[Any]): the args used to export the pattern module with
168
+ torch.export.export. If export_args contains non-tensor Python scalars,
169
+ there must be a corresponding attr tracker in `scalar_attr_trackers` for
170
+ each scalar arg. attr_builder (Callable[[Pattern, GraphModule,
171
+ InternalMatch], Optional[dict[str, Any]]]): the callable that produces
172
+ the a scalar attrs dict, which would be propagated to `attr` in
173
+ StableHLO composite ops for the matched model subgraphs in the lowering.
174
+ scalar_attr_trackers (list[ScalarAttrTracker]): the trackers for scalar
175
+ args in `export_args`, which are used to track the attr occurrence(s)
176
+ and retrieve their values from the matched subgraph.
177
+ decomp_table (Optional[dict[torch._ops.OperatorBase, Callable]]): The
178
+ decomposition table to be run on the pattern's exported program.
176
179
  """
177
180
  if not isinstance(module, torch.nn.Module):
178
181
 
@@ -189,7 +192,9 @@ class Pattern:
189
192
 
190
193
  self.name = name
191
194
  self.attr_builder = attr_builder
192
- self._scalar_attr_trackers = scalar_attr_trackers if scalar_attr_trackers else []
195
+ self._scalar_attr_trackers = (
196
+ scalar_attr_trackers if scalar_attr_trackers else []
197
+ )
193
198
 
194
199
  exported_program = torch.export.export(module, export_args)
195
200
  if decomp_table is not None:
@@ -201,7 +206,9 @@ class Pattern:
201
206
  self._scalar_attr_locations = []
202
207
  for tracker in self._scalar_attr_trackers:
203
208
  self._scalar_attr_locations.append(
204
- _find_scalar_attr(module, export_args, tracker, decomp_table=decomp_table)
209
+ _find_scalar_attr(
210
+ module, export_args, tracker, decomp_table=decomp_table
211
+ )
205
212
  )
206
213
 
207
214
  # Sanitize graph_module for more precise pattern matching.
@@ -251,7 +258,9 @@ class Pattern:
251
258
  attrs = {}
252
259
 
253
260
  for loc in self._scalar_attr_locations:
254
- attrs[loc.attr_name] = self._get_attr_value_from_pattern_match(match, loc)
261
+ attrs[loc.attr_name] = self._get_attr_value_from_pattern_match(
262
+ match, loc
263
+ )
255
264
 
256
265
  attrs = attrs if attrs else None
257
266
  match_with_attrs.append((match, attrs))
@@ -12,13 +12,14 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Tests for mark_pattern."""
15
16
 
16
- import unittest
17
-
17
+ from ai_edge_torch import lowertools
18
+ from ai_edge_torch.hlfb import mark_pattern
19
+ from ai_edge_torch.hlfb.mark_pattern import pattern as pattern_module
18
20
  import torch
19
- import torch_xla
20
21
 
21
- from ai_edge_torch.hlfb import mark_pattern
22
+ from absl.testing import absltest as googletest
22
23
 
23
24
 
24
25
  def _export_stablehlo_mlir(model, args=None):
@@ -26,11 +27,10 @@ def _export_stablehlo_mlir(model, args=None):
26
27
  ep = torch.export.export(model, args)
27
28
  else:
28
29
  ep = model
29
- stablehlo_gm = torch_xla.stablehlo.exported_program_to_stablehlo(ep)
30
- return stablehlo_gm.get_stablehlo_text()
30
+ return lowertools.exported_program_to_mlir_text(ep)
31
31
 
32
32
 
33
- class TestMarkPattern(unittest.TestCase):
33
+ class TestMarkPattern(googletest.TestCase):
34
34
 
35
35
  def test_mark_pattern(self):
36
36
 
@@ -39,7 +39,7 @@ class TestMarkPattern(unittest.TestCase):
39
39
  def forward(self, x):
40
40
  return x * x + x + x
41
41
 
42
- pattern = mark_pattern.Pattern(
42
+ pattern = pattern_module.Pattern(
43
43
  "test.add",
44
44
  lambda a, b: a + b,
45
45
  export_args=(torch.rand(2, 2), torch.rand(2, 2)),
@@ -51,7 +51,12 @@ class TestMarkPattern(unittest.TestCase):
51
51
  mark_pattern.mark_pattern(exported_program.graph_module, pattern)
52
52
  mlir = _export_stablehlo_mlir(exported_program)
53
53
 
54
- self.assertEqual(mlir.count('stablehlo.composite "test.add"'), 2)
54
+ lowertools.assert_string_count(
55
+ self,
56
+ mlir,
57
+ {'stablehlo.composite "test.add"': 2},
58
+ {"stablehlo.custom_call @mark_tensor": 6},
59
+ )
55
60
 
56
61
  def test_mark_pattern_with_attr_builder(self):
57
62
  class TestModel(torch.nn.Module):
@@ -59,7 +64,7 @@ class TestMarkPattern(unittest.TestCase):
59
64
  def forward(self, x):
60
65
  return x * x * x + x - x * x + x
61
66
 
62
- pattern = mark_pattern.Pattern(
67
+ pattern = pattern_module.Pattern(
63
68
  "test.add",
64
69
  lambda a, b: a + b,
65
70
  export_args=(torch.rand(2, 2), torch.rand(2, 2)),
@@ -72,8 +77,16 @@ class TestMarkPattern(unittest.TestCase):
72
77
  mark_pattern.mark_pattern(exported_program.graph_module, pattern)
73
78
  mlir = _export_stablehlo_mlir(exported_program)
74
79
 
75
- self.assertEqual(mlir.count('stablehlo.composite "test.add"'), 2)
76
- self.assertEqual(mlir.count('composite_attributes = {alias = "test.test_add"}'), 2)
80
+ lowertools.assert_string_count(
81
+ self,
82
+ mlir,
83
+ {
84
+ 'stablehlo.composite "test.add"': 2,
85
+ 'composite_attributes = {alias = "test.test_add"}': 2,
86
+ },
87
+ {"stablehlo.custom_call @mark_tensor": 6},
88
+ {'{"alias": "test.test_add"}': 2},
89
+ )
77
90
 
78
91
  def test_mark_pattern_with_scalar_attr_tracker(self):
79
92
  class TestModel(torch.nn.Module):
@@ -84,12 +97,12 @@ class TestMarkPattern(unittest.TestCase):
84
97
  r = torch.nn.LogSoftmax(dim=idx % 2)(r) * x
85
98
  return r
86
99
 
87
- pattern = mark_pattern.Pattern(
100
+ pattern = pattern_module.Pattern(
88
101
  "test.log_softmax",
89
102
  lambda x, dim: torch.nn.functional.log_softmax(x, dim=dim),
90
103
  export_args=(torch.rand(10, 10, 10), 1),
91
104
  scalar_attr_trackers=[
92
- mark_pattern.ScalarAttrTracker("dim", pattern_arg_pos=1)
105
+ pattern_module.ScalarAttrTracker("dim", pattern_arg_pos=1)
93
106
  .track(0)
94
107
  .track(1)
95
108
  .track(2),
@@ -102,9 +115,17 @@ class TestMarkPattern(unittest.TestCase):
102
115
  mark_pattern.mark_pattern(exported_program.graph_module, pattern)
103
116
  mlir = _export_stablehlo_mlir(exported_program)
104
117
 
105
- self.assertEqual(mlir.count('stablehlo.composite "test.log_softmax"'), 5)
106
- self.assertEqual(mlir.count("composite_attributes = {dim = 0 : i64}"), 3)
107
- self.assertEqual(mlir.count("composite_attributes = {dim = 1 : i64}"), 2)
118
+ lowertools.assert_string_count(
119
+ self,
120
+ mlir,
121
+ {
122
+ 'stablehlo.composite "test.log_softmax"': 5,
123
+ "composite_attributes = {dim = 0 : i64}": 3,
124
+ "composite_attributes = {dim = 1 : i64}": 2,
125
+ },
126
+ {"stablehlo.custom_call @mark_tensor": 10},
127
+ {'{"dim": 0}': 3, '{"dim": 1}': 2},
128
+ )
108
129
 
109
130
  def test_mark_tangent_model_and_pattern_input(self):
110
131
  class TestModel(torch.nn.Module):
@@ -114,7 +135,7 @@ class TestMarkPattern(unittest.TestCase):
114
135
  z = z + y
115
136
  return z
116
137
 
117
- pattern = mark_pattern.Pattern(
138
+ pattern = pattern_module.Pattern(
118
139
  "test.relu",
119
140
  lambda x: torch.ops.aten.relu(x),
120
141
  export_args=(torch.rand(2, 2),),
@@ -126,8 +147,13 @@ class TestMarkPattern(unittest.TestCase):
126
147
  mark_pattern.mark_pattern(exported_program.graph_module, pattern)
127
148
  mlir = _export_stablehlo_mlir(exported_program)
128
149
 
129
- self.assertEqual(mlir.count('stablehlo.composite "test.relu'), 1)
150
+ lowertools.assert_string_count(
151
+ self,
152
+ mlir,
153
+ {'stablehlo.composite "test.relu"': 1},
154
+ {"stablehlo.custom_call @mark_tensor": 2},
155
+ )
130
156
 
131
157
 
132
158
  if __name__ == "__main__":
133
- unittest.main()
159
+ googletest.main()
@@ -12,23 +12,29 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Tests for StableHLOCompositeBuilder."""
16
+
15
17
  import math
16
- import unittest
17
18
 
19
+ from ai_edge_torch import config
20
+ from ai_edge_torch import lowertools
21
+ from ai_edge_torch.hlfb import StableHLOCompositeBuilder
18
22
  import torch
19
23
  import torch.nn.functional as F
20
- import torch_xla
21
24
 
22
- from ai_edge_torch.hlfb import StableHLOCompositeBuilder
25
+ from absl.testing import absltest as googletest
23
26
 
24
27
 
25
28
  def _export_stablehlo_mlir(model, args):
26
29
  ep = torch.export.export(model, args)
27
- stablehlo_gm = torch_xla.stablehlo.exported_program_to_stablehlo(ep)
28
- return stablehlo_gm.get_stablehlo_text()
30
+ return lowertools.exported_program_to_mlir_text(ep)
29
31
 
30
32
 
31
- class TestStableHLOCompositeBuilder(unittest.TestCase):
33
+ @googletest.skipIf(
34
+ not config.Config.use_torch_xla,
35
+ reason="The odml_torch counter part is in odml_torch.",
36
+ )
37
+ class TestStableHLOCompositeBuilder(googletest.TestCase):
32
38
 
33
39
  def test_build_composite(self):
34
40
  class SampleModel(torch.nn.Module):
@@ -80,7 +86,9 @@ class TestStableHLOCompositeBuilder(unittest.TestCase):
80
86
  super().__init__()
81
87
 
82
88
  def log_softmax(self, x: torch.Tensor, dim: int):
83
- builder = StableHLOCompositeBuilder(name="test.log_softmax", attr={"dim": dim})
89
+ builder = StableHLOCompositeBuilder(
90
+ name="test.log_softmax", attr={"dim": dim}
91
+ )
84
92
  x = builder.mark_inputs(x)
85
93
  y = torch.nn.functional.log_softmax(x, dim=dim)
86
94
  y = builder.mark_outputs(y)
@@ -126,7 +134,8 @@ class TestStableHLOCompositeBuilder(unittest.TestCase):
126
134
  self.assertEqual(mlir.count('stablehlo.composite "test.log_softmax"'), 1)
127
135
  self.assertEqual(
128
136
  mlir.count(
129
- 'composite_attributes = {dim = 0 : i64, source = "torch.nn", version = 1.000000e+00 : f32}'
137
+ 'composite_attributes = {dim = 0 : i64, source = "torch.nn",'
138
+ " version = 1.000000e+00 : f32}"
130
139
  ),
131
140
  1,
132
141
  )
@@ -236,8 +245,12 @@ class TestStableHLOCompositeBuilder(unittest.TestCase):
236
245
  self.assertEqual(
237
246
  mlir.count('stablehlo.composite "test.scaled_dot_product_attention"'), 2
238
247
  )
239
- self.assertEqual(mlir.count("composite_attributes = {include_captanh = true}"), 1)
240
- self.assertEqual(mlir.count("composite_attributes = {include_captanh = false}"), 1)
248
+ self.assertEqual(
249
+ mlir.count("composite_attributes = {include_captanh = true}"), 1
250
+ )
251
+ self.assertEqual(
252
+ mlir.count("composite_attributes = {include_captanh = false}"), 1
253
+ )
241
254
 
242
255
  def test_build_composite_with_multiple_inputs_outputs(self):
243
256
  class SampleModel(torch.nn.Module):
@@ -267,4 +280,4 @@ class TestStableHLOCompositeBuilder(unittest.TestCase):
267
280
 
268
281
 
269
282
  if __name__ == "__main__":
270
- unittest.main()
283
+ googletest.main()
@@ -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
+
16
+ from ._shim import *
17
+ from .common_utils import flat_dict_names
18
+ from .test_utils import *
@@ -0,0 +1,80 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from typing import Any, Optional
17
+
18
+ from ai_edge_torch import config
19
+ from ai_edge_torch._convert import signature
20
+ from ai_edge_torch.quantize import quant_config as qcfg
21
+ import torch
22
+
23
+ # isort: off
24
+ if config.Config.use_torch_xla:
25
+ from ai_edge_torch.lowertools import torch_xla_utils as utils
26
+ from ai_edge_torch.lowertools.torch_xla_utils import exported_program_to_mlir_text
27
+ from torch_xla.experimental.mark_pattern_utils import StableHLOCompositeBuilder
28
+ from torch_xla.experimental.xla_marker import serialize_composite_attr
29
+ # The following imports are needed to register the needed torch_xla ops.
30
+ import torch_xla.experimental.xla_marker
31
+ import torch_xla.experimental.xla_mlir_debuginfo
32
+
33
+ mark_tensor_op = torch.ops.xla.mark_tensor.default
34
+ write_mlir_debuginfo_op = torch.ops.xla.write_mlir_debuginfo.default
35
+ else:
36
+ from ai_edge_torch.lowertools import odml_torch_utils as utils
37
+ from ai_edge_torch.lowertools.odml_torch_utils import exported_program_to_mlir_text
38
+ from ai_edge_torch.odml_torch.composite import StableHLOCompositeBuilder
39
+ from ai_edge_torch.odml_torch.composite.mark_tensor import serialize_composite_attr
40
+ from ai_edge_torch.odml_torch.composite.mark_tensor import mark_tensor_op
41
+ from ai_edge_torch.odml_torch.debuginfo import write_mlir_debuginfo_op
42
+ # isort: on
43
+
44
+
45
+ def exported_programs_to_tflite(
46
+ exported_programs: list[torch.export.ExportedProgram],
47
+ signatures: list[signature.Signature],
48
+ *,
49
+ quant_config: Optional[qcfg.QuantConfig] = None,
50
+ _tfl_converter_flags: Optional[dict[str, Any]] = None,
51
+ ):
52
+ """Converts a list of ExportedProgram to a TFLite model.
53
+
54
+ Args:
55
+ exported_programs: A list of ExportedProgram.
56
+ signatures: A list of Signature.
57
+ quant_config: A QuantConfig.
58
+ _tfl_converter_flags: A dict of flags for TFLiteConverter.
59
+
60
+ Returns:
61
+ A TFLite model.
62
+ """
63
+ if _tfl_converter_flags is None:
64
+ _tfl_converter_flags = {}
65
+
66
+ bundles: list[utils.MlirBundle] = [
67
+ utils.exported_program_to_mlir(exported, sig.flat_args)
68
+ for exported, sig in zip(exported_programs, signatures)
69
+ ]
70
+
71
+ merged_bundle: utils.MergedBundle = utils.merge_mlir_bundles(
72
+ bundles, signatures, exported_programs
73
+ )
74
+
75
+ return utils.merged_bundle_to_tfl_model(
76
+ merged_bundle,
77
+ signatures,
78
+ quant_config=quant_config,
79
+ _tfl_converter_flags=_tfl_converter_flags,
80
+ )
@@ -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
+
16
+ import logging
17
+ from typing import List
18
+
19
+ from ai_edge_torch._convert import signature as signature_module
20
+ import tensorflow as tf
21
+ import torch
22
+ import torch.utils._pytree as pytree
23
+
24
+
25
+ def _flatten_list(l: List) -> List:
26
+ flattened = []
27
+ for item in l:
28
+ if isinstance(item, list):
29
+ flattened.extend(_flatten_list(item))
30
+ else:
31
+ flattened.append(item)
32
+ return flattened
33
+
34
+
35
+ def flat_dict_names(
36
+ tree_spec: pytree.TreeSpec, context: pytree.Context
37
+ ) -> List[str]:
38
+ """Given a TreeSpec, this produces a list of names for the leaves.
39
+
40
+ The list of names embeddeds the structure of the tree_spec. A nesting level is
41
+ indicated by an `_` and elements in a list are indicated by `_<index>`.
42
+
43
+ TODO b/361601485: The flattening of names is not collision-free and needs to
44
+ be revised.
45
+
46
+ Args:
47
+ tree_spec: The TreeSpec to extract the names from.
48
+ context: The context used to check if the provided spec belongs to a
49
+ dictionary or a list.
50
+
51
+ Returns:
52
+ A list of flattened names.
53
+ """
54
+ flat_names = []
55
+ if context is None:
56
+ for i, spec in enumerate(tree_spec):
57
+ if spec.children_specs:
58
+ flat_names.extend([
59
+ f"{i}_{name}"
60
+ for name in flat_dict_names(spec.children_specs, spec.context)
61
+ ])
62
+ else:
63
+ flat_names.append(f"{i}")
64
+ else:
65
+ flat_ctx = _flatten_list(context)
66
+ for prefix, spec in zip(flat_ctx, tree_spec):
67
+ leaf_flat_names = flat_dict_names(spec.children_specs, spec.context)
68
+ if leaf_flat_names:
69
+ flat_names.extend([f"{prefix}_{name}" for name in leaf_flat_names])
70
+ else:
71
+ flat_names.append(prefix)
72
+
73
+ return flat_names
74
+
75
+
76
+ def _torch_to_tf_variable(torch_tensor: torch.Tensor):
77
+ if not torch_tensor.is_contiguous():
78
+ torch_tensor = torch_tensor.contiguous()
79
+
80
+ try:
81
+ dlpack_capsule = torch.utils.dlpack.to_dlpack(torch_tensor)
82
+ tf_tensor = tf.experimental.dlpack.from_dlpack(dlpack_capsule)
83
+ except Exception:
84
+ logging.info(
85
+ "Can not use dlpack to convert torch tensors. Falling back to numpy."
86
+ )
87
+ nparray = torch_tensor.cpu().detach().numpy()
88
+ tf_tensor = tf.convert_to_tensor(nparray)
89
+
90
+ return tf.Variable(tf_tensor, trainable=False)
91
+
92
+
93
+ def _get_states(
94
+ exported_programs: list[torch.export.ExportedProgram],
95
+ signatures: list[signature_module.Signature],
96
+ ):
97
+ for exported_program, signature in zip(exported_programs, signatures):
98
+ args, _ = exported_program.example_inputs
99
+ # Calling this to get **all** the state including model buffers.
100
+ _flat_input_args = exported_program._graph_module_flat_inputs(args, {})
101
+ for tensor, input_spec in zip(
102
+ _flat_input_args, exported_program.graph_signature.input_specs
103
+ ):
104
+ # Only interested in Tensors that are part of the state (and not user input).
105
+ if (
106
+ not isinstance(tensor, torch.Tensor)
107
+ or input_spec.kind
108
+ == torch.export.graph_signature.InputKind.USER_INPUT
109
+ ):
110
+ continue
111
+ yield signature, tensor, input_spec
112
+
113
+
114
+ def _tensor_unique_id(tensor: torch.Tensor):
115
+ return (
116
+ str(tensor.device),
117
+ tensor.shape,
118
+ tensor.stride(),
119
+ tensor.untyped_storage().data_ptr(),
120
+ )
121
+
122
+
123
+ def gather_state_dict(
124
+ exported_programs: list[torch.export.ExportedProgram],
125
+ signatures: list[signature_module.Signature],
126
+ ):
127
+ deduped_tensor_map = {}
128
+
129
+ for _, tensor, _ in _get_states(exported_programs, signatures):
130
+ unique_id = _tensor_unique_id(tensor)
131
+ deduped_tensor_map[unique_id] = _torch_to_tf_variable(tensor)
132
+
133
+ state_dict = {}
134
+ for signature, tensor, input_spec in _get_states(
135
+ exported_programs, signatures
136
+ ):
137
+ unique_id = _tensor_unique_id(tensor)
138
+ state_dict[signature.name + "_" + input_spec.target] = deduped_tensor_map[
139
+ unique_id
140
+ ]
141
+
142
+ return state_dict, list(deduped_tensor_map.values())