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,6 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Culprit finder for AI Edge Torch conversion."""
15
16
 
16
17
  import contextlib
17
18
  import copy
@@ -20,17 +21,15 @@ import functools
20
21
  import io
21
22
  import operator
22
23
  import os
23
- import sys
24
24
  from typing import Any, Callable, Generator, List, Optional, Tuple, Union
25
25
 
26
- from functorch.compile import minifier as fx_minifier
26
+ import ai_edge_torch
27
+ from ai_edge_torch.debug import utils
27
28
  import torch
28
29
  from torch._functorch import aot_autograd
30
+ from torch._functorch.fx_minifier import minifier as fx_minifier
29
31
  import torch.utils._pytree as pytree
30
32
 
31
- import ai_edge_torch
32
- from ai_edge_torch.debug import utils
33
-
34
33
  _torch_float_dtypes = {
35
34
  torch.float32,
36
35
  torch.float,
@@ -117,24 +116,32 @@ class Culprit(SearchResult):
117
116
  print_output: bool - If true, prints the code to stdout. Otherwise returns
118
117
  the code in a str.
119
118
  """
120
- # TODO (b/321263453): Support Python code gen with sample arg tensor values.
119
+ # TODO: b/321263453 - Support Python code gen with sample arg tensor values.
121
120
  random_inputs = True
122
121
 
123
- graph_module_code = self.graph_module.print_readable(print_output=False).rstrip()
122
+ graph_module_code = self.graph_module.print_readable(
123
+ print_output=False
124
+ ).rstrip()
124
125
 
125
126
  input_strs = []
126
127
  for value in self.inputs:
127
128
  if torch.is_tensor(value):
128
129
  if not random_inputs:
129
- input_strs.append(f"# size={_get_shape_str(value)}, dtype={value.dtype}")
130
- input_strs.append(f"torch.load(io.BytesIO({_tensor_to_buffer(value)})),")
130
+ input_strs.append(
131
+ f"# size={_get_shape_str(value)}, dtype={value.dtype}"
132
+ )
133
+ input_strs.append(
134
+ f"torch.load(io.BytesIO({_tensor_to_buffer(value)})),"
135
+ )
131
136
  else:
132
137
  input_strs.append(_tensor_to_random_tensor_call(value) + ",")
133
138
  else:
134
139
  input_strs.append(str(value) + ",")
135
140
 
136
141
  inputs_code = (
137
- "_args = (\n" + "\n".join([" " * 4 + code for code in input_strs]) + "\n)"
142
+ "_args = (\n"
143
+ + "\n".join([" " * 4 + code for code in input_strs])
144
+ + "\n)"
138
145
  )
139
146
 
140
147
  code = graph_module_code + "\n\n" + inputs_code
@@ -145,6 +152,7 @@ class Culprit(SearchResult):
145
152
 
146
153
  def print_code(self, print_output=True):
147
154
  """Print the Python code for culprit graph module, sample args, and AI
155
+
148
156
  Edge Torch conversion that will fail with the error.
149
157
 
150
158
  Args:
@@ -157,7 +165,9 @@ class Culprit(SearchResult):
157
165
  + "from torch import device\n"
158
166
  + "import ai_edge_torch\n\n"
159
167
  + definitions
160
- + f"\n\n_edge_model = ai_edge_torch.convert({_CULPRIT_GRAPH_MODULE_NAME}().eval(), _args)\n"
168
+ + "\n\n_edge_model ="
169
+ f" ai_edge_torch.convert({_CULPRIT_GRAPH_MODULE_NAME}().eval(),"
170
+ " _args)\n"
161
171
  )
162
172
  if self._runtime_errors:
163
173
  code += "_edge_model(*_args)\n"
@@ -179,8 +189,8 @@ class Culprit(SearchResult):
179
189
 
180
190
 
181
191
  def _normalize_getitem_nodes(fx_gm: torch.fx.GraphModule):
182
- """
183
- This function turns all operator getitem nodes in ExportedProgram FX graph to
192
+ """This function turns all operator getitem nodes in ExportedProgram FX graph to
193
+
184
194
  new nodes composed of "computation + getitem". The normalization duplicates
185
195
  some computations in the graph but would make the graph more friendly for
186
196
  partitioning in FX minifier.
@@ -212,7 +222,9 @@ def _normalize_getitem_nodes(fx_gm: torch.fx.GraphModule):
212
222
  return fx_gm
213
223
 
214
224
 
215
- def _erase_unused_inputs(fx_gm: torch.fx.GraphModule, inputs: Tuple[torch.Tensor]):
225
+ def _erase_unused_inputs(
226
+ fx_gm: torch.fx.GraphModule, inputs: Tuple[torch.Tensor]
227
+ ):
216
228
  fx_gm = copy.deepcopy(fx_gm)
217
229
  inputs = tuple(inputs)
218
230
  args = fx_gm.graph.process_inputs(*inputs)
@@ -316,7 +328,9 @@ def _erase_sub_gm_from_gm(
316
328
  return fx_gm, fx_inputs
317
329
 
318
330
 
319
- def _normalize_minified_fx_gm(fx_gm: torch.fx.GraphModule, inputs: Tuple[torch.Tensor]):
331
+ def _normalize_minified_fx_gm(
332
+ fx_gm: torch.fx.GraphModule, inputs: Tuple[torch.Tensor]
333
+ ):
320
334
  fx_gm, inputs = _erase_unused_inputs(fx_gm, inputs)
321
335
  fx_gm = _lift_dead_ops_to_outputs(fx_gm)
322
336
  fx_gm, _ = aot_autograd.aot_export_module(fx_gm, inputs, trace_joint=False)
@@ -357,16 +371,15 @@ def _search_model(
357
371
  """Finds subgraphs in the torch model that satify a certain predicate function provided by the users.
358
372
 
359
373
  Args:
360
- predicate_f: a predicate function the users specify.
361
- It takes a FX (sub)graph and the inputs to this graph,
362
- return True if the graph satisfies the predicate,
363
- return False otherwise.
374
+ predicate_f: a predicate function the users specify. It takes a FX
375
+ (sub)graph and the inputs to this graph, return True if the graph
376
+ satisfies the predicate, return False otherwise.
364
377
  model: model in which to search subgraph.
365
- export_args: A set of args to trace the model with,
366
- i.e. model(*args) must run.
367
- max_granularity - FX minifier arg. The maximum granularity (number of nodes)
368
- in the returned ATen FX subgraph of the culprit.
369
- enable_fx_minifier_logging: If true, allows the underlying FX minifier to log the progress.
378
+ export_args: A set of args to trace the model with, i.e. model(*args) must
379
+ run. max_granularity - FX minifier arg. The maximum granularity (number of
380
+ nodes) in the returned ATen FX subgraph of the culprit.
381
+ enable_fx_minifier_logging: If true, allows the underlying FX minifier to
382
+ log the progress.
370
383
  """
371
384
 
372
385
  if isinstance(model, torch.nn.Module):
@@ -374,7 +387,8 @@ def _search_model(
374
387
  ep = torch.export.export(model, export_args)
375
388
  except Exception as err:
376
389
  raise ValueError(
377
- "Your model is not exportable by torch.export.export. Please modify your model to be torch-exportable first."
390
+ "Your model is not exportable by torch.export.export. Please modify"
391
+ " your model to be torch-exportable first."
378
392
  ) from err
379
393
  else:
380
394
  ep = model
@@ -382,26 +396,37 @@ def _search_model(
382
396
  fx_gm, fx_inputs = utils.exported_program_to_fx_graph_module_and_inputs(ep)
383
397
  fx_gm = _normalize_getitem_nodes(fx_gm)
384
398
 
385
- # HACK: temporarily disable XLA_HLO_DEBUG so that fx_minifier won't dump
386
- # intermediate stablehlo files to storage.
399
+ # HACK: temporarily disable XLA_HLO_DEBUG and create_minified_hlo_graph so that
400
+ # fx_minifier won't dump intermediate stablehlo files to storage.
387
401
  # https://github.com/pytorch/pytorch/blob/main/torch/_functorch/fx_minifier.py#L440
388
402
  @contextlib.contextmanager
389
- def disable_xla_hlo_debug():
403
+ def disable_minifier_xla_debug():
390
404
  xla_hlo_debug_value = None
391
405
  if "XLA_HLO_DEBUG" in os.environ:
392
406
  xla_hlo_debug_value = os.environ["XLA_HLO_DEBUG"]
393
407
  del os.environ["XLA_HLO_DEBUG"]
394
408
 
409
+ create_minified_hlo_graph = (
410
+ torch._functorch.fx_minifier.create_minified_hlo_graph
411
+ )
412
+ torch._functorch.fx_minifier.create_minified_hlo_graph = (
413
+ lambda *args, **kwargs: None
414
+ )
415
+
395
416
  try:
396
- yield None
417
+ yield
397
418
  finally:
398
419
  if xla_hlo_debug_value is not None:
399
420
  os.environ["XLA_HLO_DEBUG"] = xla_hlo_debug_value
400
421
 
422
+ torch._functorch.fx_minifier.create_minified_hlo_graph = (
423
+ create_minified_hlo_graph
424
+ )
425
+
401
426
  found_culprits_num = 0
402
427
  while True:
403
428
  try:
404
- with disable_xla_hlo_debug(), open(os.devnull, "w") as devnull:
429
+ with disable_minifier_xla_debug(), open(os.devnull, "w") as devnull:
405
430
  with contextlib.nullcontext() if enable_fx_minifier_logging else utils.redirect_stdio(
406
431
  stdout=devnull,
407
432
  stderr=devnull,
@@ -413,7 +438,9 @@ def _search_model(
413
438
  max_granularity=max_granularity,
414
439
  )
415
440
 
416
- min_fx_gm, min_inputs = _normalize_minified_fx_gm(raw_min_fx_gm, raw_min_inputs)
441
+ min_fx_gm, min_inputs = _normalize_minified_fx_gm(
442
+ raw_min_fx_gm, raw_min_inputs
443
+ )
417
444
  found_culprits_num += 1
418
445
  yield SearchResult(min_fx_gm, min_inputs)
419
446
 
@@ -422,7 +449,10 @@ def _search_model(
422
449
  )
423
450
 
424
451
  except RuntimeError as e:
425
- if str(e) == "Input graph did not fail the tester" and found_culprits_num > 0:
452
+ if (
453
+ str(e) == "Input graph did not fail the tester"
454
+ and found_culprits_num > 0
455
+ ):
426
456
  break
427
457
  raise e
428
458
 
@@ -439,13 +469,13 @@ def find_culprits(
439
469
 
440
470
  Args:
441
471
  torch_model: model to export and save
442
- args: A set of args to trace the model with, i.e.
443
- torch_model(*args) must run
444
- max_granularity - FX minifier arg. The maximum granularity (number of nodes)
445
- in the returned ATen FX subgraph of the culprit.
446
- runtime_errors: If true, find culprits for Python runtime errors
447
- with converted model.
448
- enable_fx_minifier_logging: If true, allows the underlying FX minifier to log the progress.
472
+ args: A set of args to trace the model with, i.e. torch_model(*args) must
473
+ run max_granularity - FX minifier arg. The maximum granularity (number of
474
+ nodes) in the returned ATen FX subgraph of the culprit.
475
+ runtime_errors: If true, find culprits for Python runtime errors with
476
+ converted model.
477
+ enable_fx_minifier_logging: If true, allows the underlying FX minifier to
478
+ log the progress.
449
479
  """
450
480
 
451
481
  fx_minifier_checker = functools.partial(
@@ -460,5 +490,7 @@ def find_culprits(
460
490
  enable_fx_minifier_logging=enable_fx_minifier_logging,
461
491
  ):
462
492
  yield Culprit(
463
- search_result.graph_module, search_result.inputs, _runtime_errors=runtime_errors
493
+ search_result.graph_module,
494
+ search_result.inputs,
495
+ _runtime_errors=runtime_errors,
464
496
  )
@@ -17,18 +17,20 @@
17
17
  import ast
18
18
  import io
19
19
  import sys
20
- import unittest
21
20
 
21
+ from ai_edge_torch.debug import find_culprits
22
22
  import torch
23
23
 
24
- from ai_edge_torch.debug import find_culprits
24
+ from absl.testing import absltest as googletest
25
25
 
26
26
  _test_culprit_lib = torch.library.Library("test_culprit", "DEF")
27
27
 
28
28
  _test_culprit_lib.define("non_lowerable_op(Tensor x) -> Tensor")
29
29
 
30
30
 
31
- @torch.library.impl(_test_culprit_lib, "non_lowerable_op", "CompositeExplicitAutograd")
31
+ @torch.library.impl(
32
+ _test_culprit_lib, "non_lowerable_op", "CompositeExplicitAutograd"
33
+ )
32
34
  def non_lowerable_op(x):
33
35
  if x.max() > 10.0:
34
36
  return x + 1.0
@@ -48,7 +50,7 @@ class BadModel(torch.nn.Module):
48
50
  return x
49
51
 
50
52
 
51
- class TestCulprit(unittest.TestCase):
53
+ class TestCulprit(googletest.TestCase):
52
54
 
53
55
  def test_find_culprits(self):
54
56
  model = BadModel().eval()
@@ -130,4 +132,4 @@ class TestCulprit(unittest.TestCase):
130
132
 
131
133
 
132
134
  if __name__ == "__main__":
133
- unittest.main()
135
+ googletest.main()
@@ -12,16 +12,15 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Tests for search_model."""
15
16
 
16
-
17
- import unittest
18
-
17
+ from ai_edge_torch.debug import _search_model
19
18
  import torch
20
19
 
21
- from ai_edge_torch.debug import _search_model
20
+ from absl.testing import absltest as googletest
22
21
 
23
22
 
24
- class TestSearchModel(unittest.TestCase):
23
+ class TestSearchModel(googletest.TestCase):
25
24
 
26
25
  def test_search_model_with_ops(self):
27
26
  class MultipleOpsModel(torch.nn.Module):
@@ -43,8 +42,10 @@ class TestSearchModel(unittest.TestCase):
43
42
 
44
43
  results = list(_search_model(find_subgraph_with_sub, model, args))
45
44
  self.assertEqual(len(results), 2)
46
- self.assertIn(torch.ops.aten.sub.Tensor, [n.target for n in results[0].graph.nodes])
45
+ self.assertIn(
46
+ torch.ops.aten.sub.Tensor, [n.target for n in results[0].graph.nodes]
47
+ )
47
48
 
48
49
 
49
50
  if __name__ == "__main__":
50
- unittest.main()
51
+ googletest.main()
@@ -12,16 +12,18 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
+ """Utils for debugging."""
16
+
15
17
  import contextlib
16
18
  import sys
17
19
 
18
20
  import torch
19
- from torch.export.graph_signature import InputKind
20
- import torch.fx._pytree as fx_pytree
21
21
  from torch.utils import _pytree as pytree
22
22
 
23
23
 
24
- def exported_program_to_fx_graph_module_and_inputs(ep: torch.export.ExportedProgram):
24
+ def exported_program_to_fx_graph_module_and_inputs(
25
+ ep: torch.export.ExportedProgram,
26
+ ):
25
27
  fx_gm = ep.graph_module
26
28
  fx_inputs = pytree.tree_map(
27
29
  torch.tensor, ep._graph_module_flat_inputs(*ep.example_inputs)
@@ -31,6 +33,15 @@ def exported_program_to_fx_graph_module_and_inputs(ep: torch.export.ExportedProg
31
33
 
32
34
  @contextlib.contextmanager
33
35
  def redirect_stdio(stdout, stderr):
36
+ """Redirects stdout and stderr to the given file objects.
37
+
38
+ Args:
39
+ stdout: A file object to redirect stdout to.
40
+ stderr: A file object to redirect stderr to.
41
+
42
+ Yields:
43
+ The file objects that stdout and stderr were redirected to.
44
+ """
34
45
  old_stdout = sys.stdout
35
46
  old_stderr = sys.stderr
36
47
 
@@ -0,0 +1,101 @@
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 abc
17
+ import collections
18
+ from typing import Sequence, Union
19
+
20
+ import torch
21
+ from torch.fx.passes.infra.pass_base import PassBase
22
+ from torch.fx.passes.infra.pass_base import PassResult
23
+ from torch.fx.passes.infra.pass_manager import pass_result_wrapper
24
+ import torch.utils._pytree as pytree
25
+
26
+ FxPassBase = PassBase
27
+ FxPassResult = PassResult
28
+ ExportedProgramPassResult = collections.namedtuple(
29
+ "ExportedProgramPassResult", ["exported_program", "modified"]
30
+ )
31
+
32
+
33
+ class ExportedProgramPassBase(abc.ABC):
34
+
35
+ def __call__(
36
+ self, exported_program: torch.export.ExportedProgram
37
+ ) -> ExportedProgramPassResult:
38
+ self.requires(exported_program)
39
+ res = self.call(exported_program)
40
+ self.ensures(exported_program)
41
+ return res
42
+
43
+ @abc.abstractmethod
44
+ def call(
45
+ self, exported_program: torch.export.ExportedProgram
46
+ ) -> ExportedProgramPassResult:
47
+ pass
48
+
49
+ def requires(self, exported_program: torch.export.ExportedProgram) -> None:
50
+ pass
51
+
52
+ def ensures(self, exported_program: torch.export.ExportedProgram) -> None:
53
+ pass
54
+
55
+
56
+ # TODO(cnchan): make a PassManager class.
57
+ def run_passes(
58
+ exported_program: torch.export.ExportedProgram,
59
+ passes: Sequence[Union[ExportedProgramPassBase, FxPassBase]],
60
+ ) -> torch.export.ExportedProgram:
61
+ passes, _ = pytree.tree_flatten(passes)
62
+ for pass_ in passes:
63
+ if not isinstance(pass_, ExportedProgramPassBase):
64
+ pass_ = pass_result_wrapper(pass_)
65
+ if isinstance(pass_, ExportedProgramPassBase):
66
+ exported_program = pass_(exported_program).exported_program
67
+ else:
68
+ gm = exported_program.graph_module
69
+ gm, modified = pass_(gm)
70
+ if modified and gm is not exported_program.graph_module:
71
+ exported_program = torch.export.ExportedProgram(
72
+ root=gm,
73
+ graph=gm.graph,
74
+ graph_signature=exported_program.graph_signature,
75
+ state_dict=exported_program.state_dict,
76
+ range_constraints=exported_program.range_constraints,
77
+ module_call_graph=exported_program.module_call_graph,
78
+ example_inputs=exported_program.example_inputs,
79
+ verifier=exported_program.verifier,
80
+ constants=exported_program.constants,
81
+ )
82
+ return exported_program
83
+
84
+
85
+ class CanonicalizePass(ExportedProgramPassBase):
86
+
87
+ # A dummy decomp table for running ExportedProgram.run_decompositions without
88
+ # any op decompositions but just aot_export_module. Due to the check in
89
+ # run_decompositions, if None or an empty dict is passed as decomp_table,
90
+ # it will run the default aten-coreaten decompositions. Therefore a non-empty
91
+ # dummy decomp table is needed.
92
+ # Ref: https://github.com/pytorch/pytorch/blob/db895ace1d36726e64781774f53b3d3098206116/torch/export/exported_program.py#L543
93
+ _DUMMY_DECOMP_TABLE = {
94
+ torch._ops.OperatorBase(): lambda: None,
95
+ }
96
+
97
+ def call(self, exported_program: torch.export.ExportedProgram):
98
+ exported_program = exported_program.run_decompositions(
99
+ self._DUMMY_DECOMP_TABLE
100
+ )
101
+ return ExportedProgramPassResult(exported_program, True)
@@ -0,0 +1,68 @@
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
+ """Example of converting a Gemma1 model to multi-signature tflite model."""
17
+
18
+ import os
19
+ import pathlib
20
+
21
+ from absl import app
22
+ from absl import flags
23
+ from ai_edge_torch.generative.examples.gemma import gemma1
24
+ from ai_edge_torch.generative.utilities import converter
25
+
26
+ _CHECKPOINT_PATH = flags.DEFINE_string(
27
+ 'checkpoint_path',
28
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/gemma-2b'),
29
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
30
+ )
31
+ _TFLITE_PATH = flags.DEFINE_string(
32
+ 'tflite_path',
33
+ '/tmp/',
34
+ 'The tflite file path to export.',
35
+ )
36
+ _PREFILL_SEQ_LEN = flags.DEFINE_integer(
37
+ 'prefill_seq_len',
38
+ 1024,
39
+ 'The maximum size of prefill input tensor.',
40
+ )
41
+ _KV_CACHE_MAX_LEN = flags.DEFINE_integer(
42
+ 'kv_cache_max_len',
43
+ 1280,
44
+ 'The maximum size of KV cache buffer, including both prefill and decode.',
45
+ )
46
+ _QUANTIZE = flags.DEFINE_bool(
47
+ 'quantize',
48
+ True,
49
+ 'Whether the model should be quantized.',
50
+ )
51
+
52
+
53
+ def main(_):
54
+ pytorch_model = gemma1.build_2b_model(
55
+ _CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
56
+ )
57
+ quant_suffix = 'q8' if _QUANTIZE.value else 'f32'
58
+ output_filename = f'gemma_{quant_suffix}_seq{_PREFILL_SEQ_LEN.value}_ekv{_KV_CACHE_MAX_LEN.value}.tflite'
59
+ converter.convert_to_tflite(
60
+ pytorch_model,
61
+ tflite_path=os.path.join(_TFLITE_PATH.value, output_filename),
62
+ prefill_seq_len=_PREFILL_SEQ_LEN.value,
63
+ quantize=_QUANTIZE.value,
64
+ )
65
+
66
+
67
+ if __name__ == '__main__':
68
+ app.run(main)
@@ -0,0 +1,68 @@
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
+ """Example of converting a Gemma2 model to multi-signature tflite model."""
17
+
18
+ import os
19
+ import pathlib
20
+
21
+ from absl import app
22
+ from absl import flags
23
+ from ai_edge_torch.generative.examples.gemma import gemma2
24
+ from ai_edge_torch.generative.utilities import converter
25
+
26
+ _CHECKPOINT_PATH = flags.DEFINE_string(
27
+ 'checkpoint_path',
28
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/gemma2-2b'),
29
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
30
+ )
31
+ _TFLITE_PATH = flags.DEFINE_string(
32
+ 'tflite_path',
33
+ '/tmp/',
34
+ 'The tflite file path to export.',
35
+ )
36
+ _PREFILL_SEQ_LEN = flags.DEFINE_integer(
37
+ 'prefill_seq_len',
38
+ 1024,
39
+ 'The maximum size of prefill input tensor.',
40
+ )
41
+ _KV_CACHE_MAX_LEN = flags.DEFINE_integer(
42
+ 'kv_cache_max_len',
43
+ 1280,
44
+ 'The maximum size of KV cache buffer, including both prefill and decode.',
45
+ )
46
+ _QUANTIZE = flags.DEFINE_bool(
47
+ 'quantize',
48
+ True,
49
+ 'Whether the model should be quantized.',
50
+ )
51
+
52
+
53
+ def main(_):
54
+ pytorch_model = gemma2.build_2b_model(
55
+ _CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
56
+ )
57
+ quant_suffix = 'q8' if _QUANTIZE.value else 'f32'
58
+ output_filename = f'gemma2_{quant_suffix}_seq{_PREFILL_SEQ_LEN.value}_ekv{_KV_CACHE_MAX_LEN.value}.tflite'
59
+ converter.convert_to_tflite(
60
+ pytorch_model,
61
+ tflite_path=os.path.join(_TFLITE_PATH.value, output_filename),
62
+ prefill_seq_len=_PREFILL_SEQ_LEN.value,
63
+ quantize=_QUANTIZE.value,
64
+ )
65
+
66
+
67
+ if __name__ == '__main__':
68
+ app.run(main)