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
ai_edge_torch/model.py CHANGED
@@ -15,17 +15,21 @@
15
15
 
16
16
  """Represents an ai_edge_torch model.
17
17
 
18
- PyTorch models can be converted to this representation through `ai_edge_torch.convert`.
18
+ PyTorch models can be converted to this representation through
19
+ `ai_edge_torch.convert`.
19
20
  """
20
21
  from __future__ import annotations
21
22
 
22
23
  import abc
24
+ import re
25
+ from typing import Callable
23
26
 
24
- import numpy as np
25
27
  import numpy.typing as npt
26
28
  import tensorflow as tf
27
29
 
28
- from ai_edge_torch.convert import conversion_utils as cutils
30
+ from ai_edge_litert import interpreter as tfl_interpreter # pylint: disable=g-direct-tensorflow-import
31
+
32
+ DEFAULT_SIGNATURE_NAME = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY
29
33
 
30
34
 
31
35
  class Model(abc.ABC):
@@ -35,7 +39,7 @@ class Model(abc.ABC):
35
39
  def __call__(
36
40
  self,
37
41
  *args: npt.ArrayLike,
38
- signature_name: str = cutils.DEFAULT_SIGNATURE_NAME,
42
+ signature_name: str = DEFAULT_SIGNATURE_NAME,
39
43
  **kwargs,
40
44
  ) -> npt.ArrayLike | tuple[npt.ArrayLike]:
41
45
  raise NotImplementedError()
@@ -63,28 +67,49 @@ class TfLiteModel(Model):
63
67
  tflite_model: A TFlite serialized object.
64
68
  """
65
69
  self._tflite_model = tflite_model
70
+ self._interpreter_builder = lambda: tfl_interpreter.Interpreter(
71
+ model_content=self._tflite_model,
72
+ experimental_default_delegate_latest_features=True,
73
+ )
74
+
75
+ def tflite_model(self) -> bytes:
76
+ """Returns the wrapped tflite model."""
77
+ return self._tflite_model
78
+
79
+ def set_interpreter_builder(
80
+ self, builder: Callable[[], tfl_interpreter.Interpreter]
81
+ ) -> None:
82
+ """Sets a custom interpreter builder.
83
+
84
+ Args:
85
+ builder: A function that returns a `tfl_interpreter.Interpreter` or its
86
+ subclass.
87
+ """
88
+ self._interpreter_builder = builder
66
89
 
67
90
  def __call__(
68
91
  self,
69
92
  *args: npt.ArrayLike,
70
- signature_name: str = cutils.DEFAULT_SIGNATURE_NAME,
93
+ signature_name: str = DEFAULT_SIGNATURE_NAME,
71
94
  **kwargs,
72
95
  ) -> npt.ArrayLike | tuple[npt.ArrayLike]:
73
96
  """Runs inference on the edge model using the provided arguments.
74
97
 
75
98
  Args:
76
99
  *args: The arguments to be passed to the model for inference.
77
- **kwargs: The arguments with specific names to be passed to the model for inference.
78
- signature_name: The name of the signature to be used for inference.
79
- The default signature is used if not provided.
100
+ **kwargs: The arguments with specific names to be passed to the model for
101
+ inference.
102
+ signature_name: The name of the signature to be used for inference. The
103
+ default signature is used if not provided.
80
104
  """
81
- interpreter = tf.lite.Interpreter(model_content=self._tflite_model)
105
+ interpreter = self._interpreter_builder()
82
106
  interpreter.allocate_tensors()
83
107
 
84
108
  signature_list = interpreter.get_signature_list()
85
109
  if signature_name not in signature_list:
86
110
  raise ValueError(
87
- f"Invalid signature name provided. Available signatures: {', '.join(signature_list.keys())}"
111
+ 'Invalid signature name provided. Available signatures:'
112
+ f' {", ".join(signature_list.keys())}'
88
113
  )
89
114
 
90
115
  try:
@@ -92,14 +117,17 @@ class TfLiteModel(Model):
92
117
  except ValueError as exception:
93
118
  if 'Invalid signature_key provided.' in str(exception):
94
119
  raise ValueError(
95
- f'Invalid signature key provided. Available signatures: {list(signature_list.keys())}'
120
+ 'Invalid signature key provided. Available signatures:'
121
+ f' {list(signature_list.keys())}'
96
122
  )
97
123
  else:
98
124
  raise exception
99
125
 
100
126
  if len(signature_list[signature_name]['inputs']) != len(args) + len(kwargs):
101
127
  raise ValueError(
102
- f"The model requires {len(signature_list[signature_name]['inputs'])} arguments but {len(args)} was provided."
128
+ 'The model requires'
129
+ f' {len(signature_list[signature_name]["inputs"])} arguments but'
130
+ f' {len(args)} was provided.'
103
131
  )
104
132
 
105
133
  # Gather the input dictionary based on the signature.
@@ -107,11 +135,18 @@ class TfLiteModel(Model):
107
135
  inputs = {**inputs, **kwargs}
108
136
  outputs = runner(**inputs)
109
137
 
110
- return (
111
- outputs['output_0']
112
- if len(outputs) == 1
113
- else [outputs[f'output_{idx}'] for idx in range(len(outputs))]
114
- )
138
+ # When attempting to run a model, check if all the output tensors are named
139
+ # output_<number>. If so, assume the pytorch model returned a tuple and not
140
+ # a dictionary.
141
+ output_heuristic = lambda key: bool(re.search(r'output_\d+', key))
142
+ if all(output_heuristic(key) for key in outputs.keys()):
143
+ return (
144
+ outputs['output_0']
145
+ if len(outputs) == 1
146
+ else [outputs[f'output_{idx}'] for idx in range(len(outputs))]
147
+ )
148
+
149
+ return outputs
115
150
 
116
151
  def export(self, path: str) -> None:
117
152
  """Serializes the edge model to disk.
@@ -134,7 +169,7 @@ class TfLiteModel(Model):
134
169
 
135
170
  # Check if this is indeed a tflite model:
136
171
  try:
137
- interpreter = tf.lite.Interpreter(model_content=model_content)
172
+ interpreter = tfl_interpreter.Interpreter(model_content=model_content)
138
173
  interpreter.get_signature_list()
139
174
  except:
140
175
  return None
@@ -0,0 +1,20 @@
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 composite
16
+ from . import debuginfo
17
+ from . import export
18
+ from . import export_utils
19
+ from . import lowerings
20
+ from . import passes
@@ -0,0 +1,61 @@
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
+ """Wrappers for latest torch APIs/utilities to maintain backward compatibility with older torch releases."""
16
+
17
+ import torch
18
+ from torch.fx import _pytree as fx_pytree
19
+
20
+
21
+ def graph_module_flat_inputs(ep: torch.export.ExportedProgram, args, kwargs):
22
+ """Transform args, kwargs of __call__ to args for graph_module.
23
+
24
+ self.graph_module takes stuff from state dict as inputs.
25
+ The invariant is for ep: ExportedProgram is
26
+ ep(args, kwargs) ==
27
+ ep.postprocess(ep.graph_module(ep.graph_module_flat_inputs(args, kwargs)))
28
+ """
29
+ if hasattr(ep, "_graph_module_flat_inputs"):
30
+ return ep._graph_module_flat_inputs(args, kwargs)
31
+
32
+ if args is None:
33
+ args = tuple()
34
+ if kwargs is None:
35
+ kwargs = {}
36
+
37
+ flat_args = args
38
+ if (in_spec := ep.call_spec.in_spec) is not None:
39
+ if (
40
+ in_spec.type == tuple
41
+ and len(in_spec.children_specs) == 2
42
+ and in_spec.children_specs[0].type == tuple
43
+ and in_spec.children_specs[1].type == dict
44
+ ):
45
+ # NOTE: this is the case where in_spec is for both args and kwargs
46
+ flat_args = fx_pytree.tree_flatten_spec((args, kwargs), in_spec)
47
+ else:
48
+ flat_args = fx_pytree.tree_flatten_spec(args, in_spec)
49
+
50
+ param_buffer_keys = ep.graph_signature.parameters + ep.graph_signature.buffers
51
+ param_buffer_values = tuple(ep.state_dict[key] for key in param_buffer_keys)
52
+
53
+ if hasattr(ep.graph_signature, "lifted_tensor_constants"):
54
+ ordered_tensor_constants = tuple(
55
+ ep.tensor_constants[name]
56
+ for name in ep.graph_signature.lifted_tensor_constants
57
+ )
58
+ else:
59
+ ordered_tensor_constants = tuple()
60
+
61
+ return (*param_buffer_values, *flat_args, *ordered_tensor_constants)
@@ -0,0 +1,19 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Torch library for registering ODML Torch custom ops."""
16
+
17
+ import torch
18
+
19
+ ODML_TORCH_LIB = torch.library.Library("odml_torch", "DEF")
@@ -0,0 +1,16 @@
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 .mark_tensor import mark_tensor_op
16
+ from .stablehlo_composite_builder import StableHLOCompositeBuilder
@@ -0,0 +1,120 @@
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 json
16
+ from typing import Sequence, Union
17
+
18
+ from jax._src.lib.mlir import ir
19
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
20
+ import torch
21
+
22
+ from .. import _torch_library
23
+ from .. import lowerings
24
+
25
+ CompositeAttrType = dict[
26
+ str,
27
+ Union[
28
+ int,
29
+ float,
30
+ bool,
31
+ str,
32
+ Sequence[int],
33
+ Sequence[float],
34
+ Sequence[bool],
35
+ ],
36
+ ]
37
+
38
+
39
+ def _assert_valid_composite_attr(attr: CompositeAttrType):
40
+ if attr is None:
41
+ return
42
+ if not isinstance(attr, dict):
43
+ raise ValueError("Composite attr must be a Python dictionary.")
44
+
45
+ for k, v in attr.items():
46
+ if not isinstance(k, str):
47
+ raise ValueError("Composite attr name must be a Python str.")
48
+
49
+ invalid_attr_value_error = ValueError(
50
+ "Composite attr value must be either Python str, float, int, bool,"
51
+ " list[int], list[float], list[bool]."
52
+ )
53
+ if isinstance(v, (list, tuple)):
54
+ eltys = {type(el) for el in v}
55
+ if len(eltys) > 1 or next(iter(eltys)) not in (int, float, bool):
56
+ raise invalid_attr_value_error
57
+ elif type(v) not in (str, float, int, bool):
58
+ raise invalid_attr_value_error
59
+
60
+
61
+ @torch._dynamo.assume_constant_result
62
+ def serialize_composite_attr(attr: Union[CompositeAttrType, None]):
63
+ """Serialize the composite attr into a dynamo-tracable value."""
64
+ if attr is None:
65
+ return None
66
+ _assert_valid_composite_attr(attr)
67
+ return tuple(attr.items())
68
+
69
+
70
+ @torch._dynamo.assume_constant_result
71
+ def deserialize_composite_attr(serialized_attr) -> CompositeAttrType:
72
+ """Deserialize dynamo-tracable composite attribute into its raw value."""
73
+ if serialized_attr is None:
74
+ return None
75
+ return dict(serialized_attr)
76
+
77
+
78
+ _torch_library.ODML_TORCH_LIB.define(
79
+ "mark_tensor(Tensor x, str name, int pos, str id, bool is_input, Any?"
80
+ " attr=None) -> Tensor"
81
+ )
82
+
83
+ mark_tensor_op = torch.ops.odml_torch.mark_tensor.default
84
+
85
+
86
+ @torch.library.impl(
87
+ _torch_library.ODML_TORCH_LIB, "mark_tensor", "CompositeExplicitAutograd"
88
+ )
89
+ def mark_tensor(
90
+ x: torch.Tensor, name: str, pos: int, id: str, is_input: bool, attr=None
91
+ ):
92
+ return x
93
+
94
+
95
+ @torch.library.impl(_torch_library.ODML_TORCH_LIB, "mark_tensor", "Meta")
96
+ def mark_tensor_meta(
97
+ x: torch.Tensor, name: str, pos: int, id: str, is_input: bool, attr=None
98
+ ):
99
+ return torch.empty_like(x)
100
+
101
+
102
+ @lowerings.lower(torch.ops.odml_torch.mark_tensor)
103
+ def mark_tensor_lowering(
104
+ lctx, x: ir.Value, name: str, pos: int, id: str, is_input: bool, attr=None
105
+ ):
106
+ attr = deserialize_composite_attr(attr)
107
+ return stablehlo.custom_call(
108
+ [x.type],
109
+ inputs=[x],
110
+ call_target_name="mark_tensor",
111
+ backend_config=ir.StringAttr.get(
112
+ json.dumps({
113
+ "name": name,
114
+ "pos": pos,
115
+ "id": id,
116
+ "is_input": is_input,
117
+ "attr": attr,
118
+ })
119
+ ),
120
+ )
@@ -0,0 +1,106 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ import uuid
16
+
17
+ import torch
18
+
19
+ from . import mark_tensor
20
+
21
+
22
+ @torch._dynamo.assume_constant_result
23
+ def _get_uuid() -> str:
24
+ return uuid.uuid4().hex
25
+
26
+
27
+ class StableHLOCompositeBuilder:
28
+ """Builder class for building a StableHLO composite in the lowering."""
29
+
30
+ def __init__(self, name: str, attr: mark_tensor.CompositeAttrType = None):
31
+ """Helper for building a StableHLO Composite by marking input and output tensors.
32
+
33
+ It should be used with the StableHLO converters from `torch_xla.stablehlo`.
34
+
35
+ Args:
36
+ name (str): The name of the built StableHLO Composite op.
37
+ attr (mark_tensor.CompositeAttrType): Attributes of the StableHLO
38
+ Composite op.
39
+ """
40
+
41
+ self.attr = attr
42
+ self.name = name
43
+ self.id = _get_uuid()
44
+ self._inputs = []
45
+ self._outputs = []
46
+
47
+ def _mark_tensor(self, *tensors: torch.Tensor, is_input: bool):
48
+ """Mark the input/output tensors of the StableHLO Composite."""
49
+ marked_tensors = []
50
+ serialized_attr = (
51
+ mark_tensor.serialize_composite_attr(self.attr)
52
+ if not is_input
53
+ else None
54
+ )
55
+
56
+ for pos, tensor in enumerate(tensors):
57
+ if not isinstance(tensor, torch.Tensor):
58
+ raise ValueError(f"input must be a torch tensor. Got {type(tensor)}.")
59
+ marked_tensors.append(
60
+ mark_tensor.mark_tensor_op(
61
+ tensor,
62
+ name=self.name,
63
+ pos=pos,
64
+ id=self.id,
65
+ is_input=is_input,
66
+ attr=serialized_attr,
67
+ )
68
+ )
69
+
70
+ if len(marked_tensors) == 1:
71
+ return marked_tensors[0]
72
+ return tuple(marked_tensors)
73
+
74
+ def mark_inputs(self, *tensors: torch.Tensor):
75
+ """Mark the input tensors of the StableHLO Composite.
76
+
77
+ This method must only be called once per builder.
78
+
79
+ Args:
80
+ *tensors (torch.Tensor): Torch tensors to mark.
81
+
82
+ Returns:
83
+ marked_tensors (torch.Tensor or Tuple[torch.Tensor]):
84
+ Torch tensors marked as composite inputs. The tensor inputs of this
85
+ method
86
+ should be replaced by the marked tensors in later usages.
87
+ """
88
+
89
+ return self._mark_tensor(*tensors, is_input=True)
90
+
91
+ def mark_outputs(self, *tensors: torch.Tensor):
92
+ """Mark the output tensors of the StableHLO Composite.
93
+
94
+ This method must only be called once per builder.
95
+
96
+ Args:
97
+ *tensors (torch.Tensor): Torch tensors to mark.
98
+
99
+ Returns:
100
+ marked_tensors (torch.Tensor or Tuple[torch.Tensor]):
101
+ Torch tensors marked as composite outputs. The tensor inputs of this
102
+ method
103
+ should be replaced by the marked tensors in later usages.
104
+ """
105
+
106
+ return self._mark_tensor(*tensors, is_input=False)
@@ -0,0 +1,16 @@
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 ._build import build_mlir_debuginfo
16
+ from ._op_polyfill import write_mlir_debuginfo_op
@@ -0,0 +1,43 @@
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 torch
16
+
17
+
18
+ def _class_fullname(cls):
19
+ module = cls.__module__
20
+ if module == "builtins":
21
+ return cls.__qualname__
22
+ return module + "." + cls.__qualname__
23
+
24
+
25
+ def _get_hierarchy(node: torch.fx.Node):
26
+ nn_module_stack = node.meta.get("nn_module_stack", {})
27
+ layers = []
28
+ for name, layer in nn_module_stack.values():
29
+ iid = ("_" + name.split(".")[-1]) if name else ""
30
+ layer_str = layer if isinstance(layer, str) else _class_fullname(layer)
31
+ layers.append(layer_str + iid)
32
+
33
+ hierachy_str = "/".join(layers) + ";"
34
+ return hierachy_str
35
+
36
+
37
+ def build_mlir_debuginfo(node: torch.fx.Node):
38
+ """Build the debuginfo string for the given node's lowerings in MLIR."""
39
+
40
+ if not hasattr(node, "meta") or "nn_module_stack" not in node.meta:
41
+ return None
42
+
43
+ return _get_hierarchy(node)
@@ -0,0 +1,55 @@
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
+ """Polyfill op for torch.ops.xla.write_mlir_debuginfo.
16
+
17
+ In odml-torch, MLIR debuginfo is generated in the lowering framework directly
18
+ without the need of an additional torch op to write. This file register a no-op
19
+ placeholder torch op to replace torch.ops.xla.write_mlir_debuginfo in
20
+ ai-edge-torch.
21
+ """
22
+
23
+ from jax._src.lib.mlir import ir
24
+ import torch
25
+
26
+ from .. import _torch_library
27
+ from .. import lowerings
28
+
29
+
30
+ _torch_library.ODML_TORCH_LIB.define(
31
+ "write_mlir_debuginfo(Tensor x, str data) -> Tensor"
32
+ )
33
+
34
+ write_mlir_debuginfo_op = torch.ops.odml_torch.write_mlir_debuginfo
35
+
36
+
37
+ @torch.library.impl(
38
+ _torch_library.ODML_TORCH_LIB,
39
+ "write_mlir_debuginfo",
40
+ "CompositeExplicitAutograd",
41
+ )
42
+ def write_mlir_debuginfo(x: torch.Tensor, _: str):
43
+ return x
44
+
45
+
46
+ @torch.library.impl(
47
+ _torch_library.ODML_TORCH_LIB, "write_mlir_debuginfo", "Meta"
48
+ )
49
+ def write_mlir_debuginfo_meta(x: torch.Tensor, _: str):
50
+ return torch.empty_like(x)
51
+
52
+
53
+ @lowerings.lower(torch.ops.odml_torch.write_mlir_debuginfo)
54
+ def write_mlir_debuginfo_lowering(lctx, x: ir.Value, _: str):
55
+ return x