ai-edge-torch-nightly 0.3.0.dev20250114__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (213) hide show
  1. ai_edge_torch/__init__.py +32 -0
  2. ai_edge_torch/_config.py +69 -0
  3. ai_edge_torch/_convert/__init__.py +14 -0
  4. ai_edge_torch/_convert/conversion.py +153 -0
  5. ai_edge_torch/_convert/conversion_utils.py +64 -0
  6. ai_edge_torch/_convert/converter.py +270 -0
  7. ai_edge_torch/_convert/fx_passes/__init__.py +23 -0
  8. ai_edge_torch/_convert/fx_passes/build_aten_composite_pass.py +288 -0
  9. ai_edge_torch/_convert/fx_passes/build_interpolate_composite_pass.py +131 -0
  10. ai_edge_torch/_convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
  11. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
  12. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +258 -0
  13. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +50 -0
  14. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +18 -0
  15. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +68 -0
  16. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +216 -0
  17. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +449 -0
  18. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
  19. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +303 -0
  20. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/utils.py +64 -0
  21. ai_edge_torch/_convert/fx_passes/remove_non_user_outputs_pass.py +52 -0
  22. ai_edge_torch/_convert/signature.py +66 -0
  23. ai_edge_torch/_convert/test/__init__.py +14 -0
  24. ai_edge_torch/_convert/test/test_convert.py +558 -0
  25. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  26. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  27. ai_edge_torch/_convert/test/test_to_channel_last_io.py +96 -0
  28. ai_edge_torch/_convert/to_channel_last_io.py +92 -0
  29. ai_edge_torch/conftest.py +20 -0
  30. ai_edge_torch/debug/__init__.py +17 -0
  31. ai_edge_torch/debug/culprit.py +496 -0
  32. ai_edge_torch/debug/test/__init__.py +14 -0
  33. ai_edge_torch/debug/test/test_culprit.py +140 -0
  34. ai_edge_torch/debug/test/test_search_model.py +51 -0
  35. ai_edge_torch/debug/utils.py +59 -0
  36. ai_edge_torch/experimental/__init__.py +14 -0
  37. ai_edge_torch/fx_pass_base.py +110 -0
  38. ai_edge_torch/generative/__init__.py +14 -0
  39. ai_edge_torch/generative/examples/__init__.py +14 -0
  40. ai_edge_torch/generative/examples/amd_llama_135m/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/amd_llama_135m/amd_llama_135m.py +87 -0
  42. ai_edge_torch/generative/examples/amd_llama_135m/convert_to_tflite.py +70 -0
  43. ai_edge_torch/generative/examples/amd_llama_135m/verify.py +72 -0
  44. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  45. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +80 -0
  46. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +80 -0
  47. ai_edge_torch/generative/examples/gemma/gemma1.py +107 -0
  48. ai_edge_torch/generative/examples/gemma/gemma2.py +295 -0
  49. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  50. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +43 -0
  51. ai_edge_torch/generative/examples/gemma/verify_util.py +157 -0
  52. ai_edge_torch/generative/examples/llama/__init__.py +14 -0
  53. ai_edge_torch/generative/examples/llama/convert_to_tflite.py +91 -0
  54. ai_edge_torch/generative/examples/llama/llama.py +196 -0
  55. ai_edge_torch/generative/examples/llama/verify.py +88 -0
  56. ai_edge_torch/generative/examples/moonshine/__init__.py +14 -0
  57. ai_edge_torch/generative/examples/moonshine/convert_moonshine_to_tflite.py +50 -0
  58. ai_edge_torch/generative/examples/moonshine/moonshine.py +103 -0
  59. ai_edge_torch/generative/examples/openelm/__init__.py +14 -0
  60. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +80 -0
  61. ai_edge_torch/generative/examples/openelm/openelm.py +127 -0
  62. ai_edge_torch/generative/examples/openelm/verify.py +71 -0
  63. ai_edge_torch/generative/examples/paligemma/__init__.py +14 -0
  64. ai_edge_torch/generative/examples/paligemma/convert_to_tflite.py +95 -0
  65. ai_edge_torch/generative/examples/paligemma/decoder.py +151 -0
  66. ai_edge_torch/generative/examples/paligemma/decoder2.py +177 -0
  67. ai_edge_torch/generative/examples/paligemma/image_encoder.py +160 -0
  68. ai_edge_torch/generative/examples/paligemma/paligemma.py +179 -0
  69. ai_edge_torch/generative/examples/paligemma/verify.py +161 -0
  70. ai_edge_torch/generative/examples/paligemma/verify_decoder.py +75 -0
  71. ai_edge_torch/generative/examples/paligemma/verify_decoder2.py +72 -0
  72. ai_edge_torch/generative/examples/paligemma/verify_image_encoder.py +99 -0
  73. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  74. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +80 -0
  75. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +80 -0
  76. ai_edge_torch/generative/examples/phi/phi2.py +107 -0
  77. ai_edge_torch/generative/examples/phi/phi3.py +219 -0
  78. ai_edge_torch/generative/examples/phi/verify.py +64 -0
  79. ai_edge_torch/generative/examples/phi/verify_phi3.py +69 -0
  80. ai_edge_torch/generative/examples/qwen/__init__.py +14 -0
  81. ai_edge_torch/generative/examples/qwen/convert_to_tflite.py +93 -0
  82. ai_edge_torch/generative/examples/qwen/qwen.py +134 -0
  83. ai_edge_torch/generative/examples/qwen/verify.py +88 -0
  84. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  85. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +80 -0
  86. ai_edge_torch/generative/examples/smollm/convert_v2_to_tflite.py +71 -0
  87. ai_edge_torch/generative/examples/smollm/smollm.py +125 -0
  88. ai_edge_torch/generative/examples/smollm/verify.py +86 -0
  89. ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
  90. ai_edge_torch/generative/examples/stable_diffusion/attention.py +108 -0
  91. ai_edge_torch/generative/examples/stable_diffusion/clip.py +185 -0
  92. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +173 -0
  93. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +398 -0
  94. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +749 -0
  95. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +119 -0
  96. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +254 -0
  97. ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
  98. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +62 -0
  99. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +66 -0
  100. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +74 -0
  101. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +39 -0
  102. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +111 -0
  103. ai_edge_torch/generative/examples/stable_diffusion/util.py +77 -0
  104. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  105. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +138 -0
  106. ai_edge_torch/generative/examples/t5/t5.py +655 -0
  107. ai_edge_torch/generative/examples/t5/t5_attention.py +246 -0
  108. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  109. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  110. ai_edge_torch/generative/examples/test_models/toy_model.py +156 -0
  111. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +138 -0
  112. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  113. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +80 -0
  114. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +88 -0
  115. ai_edge_torch/generative/examples/tiny_llama/verify.py +72 -0
  116. ai_edge_torch/generative/fx_passes/__init__.py +30 -0
  117. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +50 -0
  118. ai_edge_torch/generative/layers/__init__.py +14 -0
  119. ai_edge_torch/generative/layers/attention.py +399 -0
  120. ai_edge_torch/generative/layers/attention_utils.py +210 -0
  121. ai_edge_torch/generative/layers/builder.py +160 -0
  122. ai_edge_torch/generative/layers/feed_forward.py +120 -0
  123. ai_edge_torch/generative/layers/kv_cache.py +204 -0
  124. ai_edge_torch/generative/layers/lora.py +557 -0
  125. ai_edge_torch/generative/layers/model_config.py +238 -0
  126. ai_edge_torch/generative/layers/normalization.py +222 -0
  127. ai_edge_torch/generative/layers/rotary_position_embedding.py +94 -0
  128. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +144 -0
  129. ai_edge_torch/generative/layers/unet/__init__.py +14 -0
  130. ai_edge_torch/generative/layers/unet/blocks_2d.py +806 -0
  131. ai_edge_torch/generative/layers/unet/builder.py +50 -0
  132. ai_edge_torch/generative/layers/unet/model_config.py +282 -0
  133. ai_edge_torch/generative/quantize/__init__.py +14 -0
  134. ai_edge_torch/generative/quantize/example.py +47 -0
  135. ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
  136. ai_edge_torch/generative/quantize/quant_recipe.py +154 -0
  137. ai_edge_torch/generative/quantize/quant_recipe_utils.py +62 -0
  138. ai_edge_torch/generative/quantize/quant_recipes.py +56 -0
  139. ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
  140. ai_edge_torch/generative/test/__init__.py +14 -0
  141. ai_edge_torch/generative/test/test_custom_dus.py +107 -0
  142. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  143. ai_edge_torch/generative/test/test_loader.py +83 -0
  144. ai_edge_torch/generative/test/test_lora.py +147 -0
  145. ai_edge_torch/generative/test/test_model_conversion.py +191 -0
  146. ai_edge_torch/generative/test/test_model_conversion_large.py +362 -0
  147. ai_edge_torch/generative/test/test_quantize.py +183 -0
  148. ai_edge_torch/generative/test/utils.py +82 -0
  149. ai_edge_torch/generative/utilities/__init__.py +15 -0
  150. ai_edge_torch/generative/utilities/converter.py +215 -0
  151. ai_edge_torch/generative/utilities/dynamic_update_slice.py +56 -0
  152. ai_edge_torch/generative/utilities/loader.py +398 -0
  153. ai_edge_torch/generative/utilities/model_builder.py +180 -0
  154. ai_edge_torch/generative/utilities/moonshine_loader.py +154 -0
  155. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +1032 -0
  156. ai_edge_torch/generative/utilities/t5_loader.py +512 -0
  157. ai_edge_torch/generative/utilities/transformers_verifier.py +42 -0
  158. ai_edge_torch/generative/utilities/verifier.py +335 -0
  159. ai_edge_torch/hlfb/__init__.py +16 -0
  160. ai_edge_torch/hlfb/mark_pattern/__init__.py +153 -0
  161. ai_edge_torch/hlfb/mark_pattern/fx_utils.py +69 -0
  162. ai_edge_torch/hlfb/mark_pattern/pattern.py +288 -0
  163. ai_edge_torch/hlfb/test/__init__.py +14 -0
  164. ai_edge_torch/hlfb/test/test_mark_pattern.py +185 -0
  165. ai_edge_torch/lowertools/__init__.py +18 -0
  166. ai_edge_torch/lowertools/_shim.py +86 -0
  167. ai_edge_torch/lowertools/common_utils.py +142 -0
  168. ai_edge_torch/lowertools/odml_torch_utils.py +260 -0
  169. ai_edge_torch/lowertools/test_utils.py +62 -0
  170. ai_edge_torch/lowertools/torch_xla_utils.py +301 -0
  171. ai_edge_torch/lowertools/translate_recipe.py +163 -0
  172. ai_edge_torch/model.py +177 -0
  173. ai_edge_torch/odml_torch/__init__.py +20 -0
  174. ai_edge_torch/odml_torch/_torch_future.py +88 -0
  175. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  176. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  177. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  178. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  179. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  180. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  181. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  182. ai_edge_torch/odml_torch/export.py +403 -0
  183. ai_edge_torch/odml_torch/export_utils.py +157 -0
  184. ai_edge_torch/odml_torch/jax_bridge/__init__.py +18 -0
  185. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +180 -0
  186. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  187. ai_edge_torch/odml_torch/lowerings/__init__.py +27 -0
  188. ai_edge_torch/odml_torch/lowerings/_basic.py +294 -0
  189. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  190. ai_edge_torch/odml_torch/lowerings/_convolution.py +243 -0
  191. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +285 -0
  192. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +87 -0
  193. ai_edge_torch/odml_torch/lowerings/_quantized_decomposed.py +177 -0
  194. ai_edge_torch/odml_torch/lowerings/_rand.py +142 -0
  195. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  196. ai_edge_torch/odml_torch/lowerings/decomp.py +69 -0
  197. ai_edge_torch/odml_torch/lowerings/registry.py +65 -0
  198. ai_edge_torch/odml_torch/lowerings/utils.py +201 -0
  199. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  200. ai_edge_torch/odml_torch/tf_integration.py +156 -0
  201. ai_edge_torch/quantize/__init__.py +16 -0
  202. ai_edge_torch/quantize/pt2e_quantizer.py +466 -0
  203. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1061 -0
  204. ai_edge_torch/quantize/quant_config.py +85 -0
  205. ai_edge_torch/testing/__init__.py +14 -0
  206. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  207. ai_edge_torch/testing/model_coverage/model_coverage.py +145 -0
  208. ai_edge_torch/version.py +16 -0
  209. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/LICENSE +202 -0
  210. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/METADATA +44 -0
  211. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/RECORD +213 -0
  212. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/WHEEL +5 -0
  213. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/top_level.txt +1 -0
@@ -0,0 +1,183 @@
1
+ # Copyright 2024 The AI Edge Torch Authors. All Rights Reserved.
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 ai_edge_torch
17
+ from ai_edge_torch import config
18
+ from ai_edge_torch.generative.examples.test_models import toy_model # NOQA
19
+ from ai_edge_torch.generative.quantize import quant_recipe
20
+ from ai_edge_torch.generative.quantize import quant_recipe_utils
21
+ from ai_edge_torch.generative.quantize import quant_recipes
22
+ from ai_edge_torch.generative.quantize.quant_attrs import Algorithm
23
+ from ai_edge_torch.generative.quantize.quant_attrs import Dtype
24
+ from ai_edge_torch.generative.quantize.quant_attrs import Granularity
25
+ from ai_edge_torch.generative.quantize.quant_attrs import Mode
26
+ from ai_edge_torch.quantize import quant_config
27
+ from ai_edge_torch.testing import model_coverage
28
+ import torch
29
+
30
+ from absl.testing import absltest as googletest
31
+ from absl.testing import parameterized
32
+
33
+
34
+ class TestVerifyRecipes(parameterized.TestCase):
35
+ """Unit tests that check for model quantization recipes."""
36
+
37
+ @parameterized.parameters([
38
+ (Dtype.FP32, Dtype.FP32),
39
+ (Dtype.INT8, Dtype.INT8),
40
+ (Dtype.INT8, Dtype.FP16),
41
+ (Dtype.FP16, Dtype.INT8),
42
+ (Dtype.FP16, Dtype.FP16),
43
+ ])
44
+ def test_verify_invalid_recipes(
45
+ self,
46
+ activation,
47
+ weight,
48
+ ):
49
+ for m in Mode:
50
+ for a in Algorithm:
51
+ for g in Granularity:
52
+ with self.assertRaises(ValueError):
53
+ quant_recipe.LayerQuantRecipe(activation, weight, m, a, g).verify()
54
+
55
+ @parameterized.parameters([
56
+ (
57
+ Dtype.FP32,
58
+ Dtype.INT8,
59
+ Mode.DYNAMIC_RANGE,
60
+ Algorithm.MIN_MAX,
61
+ Granularity.CHANNELWISE,
62
+ ),
63
+ (
64
+ Dtype.FP32,
65
+ Dtype.INT8,
66
+ Mode.WEIGHT_ONLY,
67
+ Algorithm.MIN_MAX,
68
+ Granularity.CHANNELWISE,
69
+ ),
70
+ (
71
+ Dtype.FP32,
72
+ Dtype.FP16,
73
+ Mode.WEIGHT_ONLY,
74
+ Algorithm.FLOAT_CAST,
75
+ Granularity.NONE,
76
+ ),
77
+ ])
78
+ def test_verify_valid_recipes(
79
+ self,
80
+ activation,
81
+ weight,
82
+ mode,
83
+ algo,
84
+ granularity,
85
+ ):
86
+ quant_recipe.LayerQuantRecipe(
87
+ activation, weight, mode, algo, granularity
88
+ ).verify()
89
+
90
+
91
+ class TestQuantizeConvert(parameterized.TestCase):
92
+ """Test conversion with quantization."""
93
+
94
+ def setUp(self):
95
+ super().setUp()
96
+ torch.manual_seed(0)
97
+ torch._dynamo.reset()
98
+
99
+ def _attention_int8_dynamic_recipe() -> quant_config.QuantConfig:
100
+ return quant_config.QuantConfig(
101
+ generative_recipe=quant_recipe.GenerativeQuantRecipe(
102
+ attention=quant_recipe_utils.create_layer_quant_int8_dynamic(),
103
+ )
104
+ )
105
+
106
+ def _feedforward_int8_dynamic_recipe() -> quant_config.QuantConfig:
107
+ return quant_config.QuantConfig(
108
+ generative_recipe=quant_recipe.GenerativeQuantRecipe(
109
+ feedforward=quant_recipe_utils.create_layer_quant_int8_dynamic(),
110
+ )
111
+ )
112
+
113
+ @parameterized.parameters([
114
+ (quant_recipes.full_fp16_recipe()),
115
+ (quant_recipes.full_int8_dynamic_recipe()),
116
+ (quant_recipes.full_int8_weight_only_recipe()),
117
+ (_attention_int8_dynamic_recipe()),
118
+ (_feedforward_int8_dynamic_recipe()),
119
+ ])
120
+ def test_quantize_convert_toy_sizes(self, quant_config):
121
+ config = toy_model.get_model_config()
122
+ pytorch_model = toy_model.ToySingleLayerModel(config)
123
+ idx = torch.unsqueeze(torch.arange(0, 100, dtype=torch.int), 0)
124
+ input_pos = torch.arange(0, 100, dtype=torch.int)
125
+
126
+ quantized_model = ai_edge_torch.convert(
127
+ pytorch_model, (idx, input_pos), quant_config=quant_config
128
+ )
129
+ float_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
130
+ self.assertLess(
131
+ len(quantized_model._tflite_model),
132
+ len(float_model._tflite_model),
133
+ "Quantized model isn't smaller than F32 model.",
134
+ )
135
+
136
+ def test_quantize_convert_toy_weight_sharing(self):
137
+ config = toy_model.get_model_config()
138
+ pytorch_model = toy_model.ToySingleLayerModelWeightSharing(config)
139
+ idx = torch.unsqueeze(torch.arange(0, 100, dtype=torch.int), 0)
140
+ input_pos = torch.arange(0, 100, dtype=torch.int)
141
+
142
+ quant_config = quant_recipes.full_int8_dynamic_recipe()
143
+ quantized_model = ai_edge_torch.convert(
144
+ pytorch_model, (idx, input_pos), quant_config=quant_config
145
+ )
146
+ float_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
147
+ self.assertLess(
148
+ len(quantized_model._tflite_model),
149
+ len(float_model._tflite_model),
150
+ "Quantized model isn't smaller than F32 model.",
151
+ )
152
+
153
+ def test_quantize_convert_compare_toy(self):
154
+ self.skipTest("b/338288901")
155
+ config = toy_model_with_kv_cache.get_model_config()
156
+ pytorch_model = toy_model_with_kv_cache.ToyModelWithKV(config)
157
+ idx, input_pos = torch.tensor([[1]], dtype=torch.int), torch.tensor(
158
+ [10], dtype=torch.int64
159
+ )
160
+
161
+ quant_config = quant_recipes.full_fp16_recipe()
162
+ quantized_model = ai_edge_torch.convert(
163
+ pytorch_model, (idx, input_pos), quant_config=quant_config
164
+ )
165
+ float_model = ai_edge_torch.convert(pytorch_model, (idx, input_pos))
166
+
167
+ self.assertLess(
168
+ len(quantized_model._tflite_model), len(float_model._tflite_model)
169
+ )
170
+ self.assertTrue(
171
+ model_coverage.compare_tflite_torch(
172
+ quantized_model,
173
+ pytorch_model,
174
+ (idx, input_pos),
175
+ num_valid_inputs=1,
176
+ atol=1e-3,
177
+ rtol=1e-3,
178
+ )
179
+ )
180
+
181
+
182
+ if __name__ == "__main__":
183
+ googletest.main()
@@ -0,0 +1,82 @@
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
+ """Common utils for testing."""
17
+
18
+ import logging
19
+
20
+ from ai_edge_torch import model
21
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
22
+ from ai_edge_torch.lowertools import common_utils
23
+ import numpy as np
24
+ import torch
25
+ from torch.utils import _pytree as pytree
26
+
27
+
28
+ def compare_tflite_torch(
29
+ edge_model: model.Model,
30
+ torch_model: torch.nn.Module,
31
+ tokens: torch.Tensor,
32
+ input_pos: torch.Tensor,
33
+ kv_cache: kv_utils.KVCache,
34
+ signature_name: str,
35
+ atol: float = 1e-5,
36
+ rtol: float = 1e-5,
37
+ **kwargs,
38
+ ) -> bool:
39
+ """Compares torch models and TFLite models."""
40
+ values, spec = pytree.tree_flatten({"kv_cache": kv_cache})
41
+ flat_names = common_utils.flat_dict_names(spec.children_specs, spec.context)
42
+ torch_output = torch_model(tokens, input_pos, kv_cache, **kwargs)
43
+
44
+ if "pixel_values" in kwargs:
45
+ kwargs["pixel_values"] = kwargs["pixel_values"].numpy()
46
+ kwargs.update({k: v.numpy() for k, v in zip(flat_names, values)})
47
+ edge_output = edge_model(
48
+ signature_name=signature_name,
49
+ tokens=tokens.numpy(),
50
+ input_pos=input_pos.numpy(),
51
+ **kwargs,
52
+ )
53
+
54
+ return compare_logits(
55
+ edge_output["logits"], torch_output["logits"].detach().numpy(), atol, rtol
56
+ )
57
+
58
+
59
+ def compare_logits(
60
+ edge_logits: np.ndarray,
61
+ torch_logits: dict[str, torch.Tensor],
62
+ atol: float = 1e-5,
63
+ rtol: float = 1e-5,
64
+ ) -> bool:
65
+ """Compares logits from edge model and torch model."""
66
+ if np.allclose(edge_logits, torch_logits, rtol, atol, equal_nan=True):
67
+ return True
68
+
69
+ logging.info("edge_logits: %s", edge_logits)
70
+ logging.info("torch_logits: %s", torch_logits)
71
+
72
+ orig_atol = atol
73
+ while rtol < 1:
74
+ atol = orig_atol
75
+ while atol < 1:
76
+ if np.allclose(edge_logits, torch_logits, rtol, atol, equal_nan=True):
77
+ logging.info("Got allclose true with atol=%s, rtol=%s", atol, rtol)
78
+ return False
79
+ atol *= 10
80
+ rtol *= 10
81
+ logging.info("allclose failed with reasonable atol and rtol.")
82
+ return False
@@ -0,0 +1,15 @@
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
+ # This module contains common utility functions.
@@ -0,0 +1,215 @@
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
+ """Common utility functions for model conversion."""
17
+
18
+ import os
19
+ from typing import Optional, Union
20
+ from ai_edge_torch._convert import converter as converter_utils
21
+ from ai_edge_torch.generative.layers import lora as lora_utils
22
+ import ai_edge_torch.generative.layers.kv_cache as kv_utils
23
+ import ai_edge_torch.generative.layers.model_config as cfg
24
+ from ai_edge_torch.generative.quantize import quant_recipes
25
+ from ai_edge_torch.generative.utilities.model_builder import ExportConfig
26
+ import torch
27
+
28
+
29
+ class ExportableModule(torch.nn.Module):
30
+
31
+ def __init__(self, module, **extra_kwargs):
32
+ super().__init__()
33
+ self.module = module
34
+ self.extra_kwargs = extra_kwargs
35
+
36
+ def forward(self, *export_args, **export_kwargs):
37
+ full_kwargs = {**export_kwargs, **self.extra_kwargs}
38
+ return self.module(*export_args, **full_kwargs)
39
+
40
+
41
+ def convert_to_tflite(
42
+ pytorch_model: torch.nn.Module,
43
+ output_path: str,
44
+ output_name_prefix: str,
45
+ prefill_seq_len: Union[int, list[int]],
46
+ pixel_values_size: torch.Size = None,
47
+ quantize: bool = True,
48
+ config: cfg.ModelConfig = None,
49
+ lora_ranks: Optional[list[int]] = None,
50
+ export_config: ExportConfig = None,
51
+ ):
52
+ """Converts a nn.Module model to multi-signature tflite model.
53
+
54
+ A PyTorch model will be converted to a tflite model with several signatures:
55
+ * "prefill_[prefill_seq_len]" (or "prefill" if only one prefill_seq_len is
56
+ passed),
57
+ * "prefill_[preill_seq_len]_pixel" (or "prefill_pixel" if only one
58
+ prefill_seq_len is passed) if num_pixel_values > 0, and
59
+ * "decode".
60
+
61
+ "prefill_[prefill_seq_len]" (or "prefill" if only one prefill_seq_len is
62
+ passed) signature takes as a sample input:
63
+ * a tensor of shape [1, prefill_seq_len] of token sequence,
64
+ * a tensor of shape [1, prefill_seq_len] of token positions, and
65
+ * an external KV cache.
66
+
67
+ If num_pixel_values > 0, "prefill_[prefill_seq_len]_pixel" (or "prefill_pixel"
68
+ if only one prefill_seq_len is passed) signature takes as a sample input:
69
+ * a tensor of shape [1, prefill_seq_len] of token sequence,
70
+ * a tensor of shape [1, prefill_seq_len] of token positions,
71
+ * an external KV cache, and
72
+ * a tensor of shape [1, num_pixel_values] of pixel values.
73
+
74
+ "decode" signature takes as a sample input:
75
+ * a tensor of shape [1, 1] of token sequence,
76
+ * a tensor of shape [1, 1] of the token position, and
77
+ * an external KV cache.
78
+
79
+ The final tflite model will be exported to tflite_path.
80
+
81
+ Args:
82
+ pytorch_model (torch.nn.Module): PyTorch model to convert to tflite.
83
+ output_path (str): The path to export the tflite model.
84
+ output_name_prefix (str): The prefix of the tflite model name.
85
+ prefill_seq_len (Union[int, list[int]]): The prefill sequence length to
86
+ use. If a list, the model will have multiple prefill signatures.
87
+ pixel_values_size (torch.Size, optional): The size of pixel values to pass
88
+ to the model. If None, the model is not expected to take pixel values.
89
+ quantize (bool, optional): Whether the model should be quanized. Defaults
90
+ to True.
91
+ config (cfg.ModelConfig, optional): The model config used to configure KV
92
+ cache. If None, it uses the config of the pytorch_model.
93
+ lora_ranks (list[int], optional): The ranks of the LORA layers. If None,
94
+ no LoRA signatures will be added.
95
+ """
96
+ # pylint: disable=protected-access
97
+ torch._dynamo.config.cache_size_limit = 64
98
+
99
+ config = config if config else pytorch_model.config
100
+ prefill_seq_lens = (
101
+ [prefill_seq_len] if isinstance(prefill_seq_len, int) else prefill_seq_len
102
+ )
103
+ loras = [None]
104
+ if lora_ranks is not None:
105
+ for rank in lora_ranks:
106
+ lora = lora_utils.LoRA.zeros(rank, config)
107
+ loras.append(lora)
108
+
109
+ quant_suffix = 'q8' if quantize else 'f32'
110
+ kv_size = config.kv_cache_max_len
111
+ lora_suffix = (
112
+ '' if not lora_ranks else f'_lora{",".join(map(str, lora_ranks))}'
113
+ )
114
+ output_filename = (
115
+ f'{output_name_prefix}_{quant_suffix}_ekv{kv_size}{lora_suffix}.tflite'
116
+ )
117
+ output_file = os.path.join(output_path, output_filename)
118
+
119
+ _export_helper(
120
+ pytorch_model,
121
+ output_file,
122
+ prefill_seq_lens,
123
+ pixel_values_size,
124
+ quantize,
125
+ config,
126
+ loras,
127
+ export_config,
128
+ )
129
+
130
+
131
+ def _export_helper(
132
+ pytorch_model: torch.nn.Module,
133
+ output_file: str,
134
+ prefill_seq_lens: list[int],
135
+ pixel_values_size: torch.Size,
136
+ quantize: bool,
137
+ config: cfg.ModelConfig,
138
+ loras: list[None | lora_utils.LoRA],
139
+ export_config: ExportConfig,
140
+ ):
141
+ """Helper function to export a model to tflite."""
142
+ prefill_tokens_list = []
143
+ prefill_input_pos_list = []
144
+ for seq_len in prefill_seq_lens:
145
+ prefill_tokens_list.append(torch.full((1, seq_len), 0, dtype=torch.int))
146
+ prefill_input_pos_list.append(torch.arange(0, seq_len, dtype=torch.int))
147
+
148
+ prefill_pixel_values = (
149
+ torch.full((1,) + pixel_values_size, 0, dtype=torch.float32)
150
+ if pixel_values_size
151
+ else None
152
+ )
153
+
154
+ decode_token = torch.tensor([[0]], dtype=torch.int)
155
+ decode_input_pos = torch.tensor([0], dtype=torch.int)
156
+ kv = kv_utils.KVCache.from_model_config(config)
157
+
158
+ quant_config = quant_recipes.full_int8_dynamic_recipe() if quantize else None
159
+
160
+ # For export, we create a module that captures any non-exportable,
161
+ # arugments, e.g. the generation config object.
162
+ mod = ExportableModule(pytorch_model, export_config=export_config)
163
+
164
+ converter = converter_utils.Converter()
165
+ for lora in loras:
166
+ for i in range(len(prefill_seq_lens)):
167
+ prefill_seq_len = prefill_seq_lens[i]
168
+ prefill_tokens = prefill_tokens_list[i]
169
+ prefill_input_pos = prefill_input_pos_list[i]
170
+ if i == 0 and len(prefill_seq_lens) == 1:
171
+ prefill_signature_name = 'prefill'
172
+ else:
173
+ prefill_signature_name = f'prefill_{prefill_seq_len}'
174
+
175
+ sample_kwargs = {
176
+ 'tokens': prefill_tokens,
177
+ 'input_pos': prefill_input_pos,
178
+ 'kv_cache': kv,
179
+ }
180
+ if lora is not None:
181
+ prefill_signature_name += f'_lora_r{lora.get_rank()}'
182
+ sample_kwargs['lora'] = lora
183
+
184
+ converter.add_signature(
185
+ prefill_signature_name,
186
+ mod,
187
+ sample_kwargs=sample_kwargs,
188
+ )
189
+
190
+ if prefill_pixel_values is not None:
191
+ converter.add_signature(
192
+ prefill_signature_name + '_pixel',
193
+ mod,
194
+ sample_kwargs={
195
+ **sample_kwargs,
196
+ 'pixel_values': prefill_pixel_values,
197
+ },
198
+ )
199
+
200
+ sample_kwargs = {
201
+ 'tokens': decode_token,
202
+ 'input_pos': decode_input_pos,
203
+ 'kv_cache': kv,
204
+ }
205
+ if lora is not None:
206
+ sample_kwargs['lora'] = lora
207
+
208
+ converter.add_signature(
209
+ 'decode' if lora is None else f'decode_lora_r{lora.get_rank()}',
210
+ mod,
211
+ sample_kwargs=sample_kwargs,
212
+ )
213
+
214
+ edge_model = converter.convert(quant_config=quant_config)
215
+ edge_model.export(output_file)
@@ -0,0 +1,56 @@
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
+ # Common utility functions for data loading etc.
16
+ from dataclasses import dataclass
17
+ import glob
18
+ import os
19
+ from typing import Sequence
20
+ from ai_edge_torch.odml_torch import lowerings
21
+ from jax._src.lib.mlir import ir
22
+ from jax._src.lib.mlir.dialects import hlo as stablehlo
23
+ import torch
24
+
25
+
26
+ # Use torch.library.custom_op to define a new custom operator.
27
+ # TODO: Update impl for multiple non-trivial start_indices
28
+ @torch.library.custom_op("ai_edge_torch::dynamic_update_slice", mutates_args=())
29
+ def dynamic_update_slice(
30
+ in_tensor: torch.Tensor,
31
+ update: torch.Tensor,
32
+ start_indices: Sequence[torch.Tensor],
33
+ ) -> torch.Tensor:
34
+ compare_size = torch.tensor(in_tensor.size()) == torch.tensor(update.size())
35
+ mismatch = torch.nonzero(~compare_size, as_tuple=False)
36
+ dim = mismatch[0].item() if len(mismatch) > 0 else 0
37
+ start = start_indices[dim].item()
38
+ end = start + update.shape[dim]
39
+ indices = torch.arange(start, end).to(torch.long)
40
+ return in_tensor.index_copy(dim, indices, update)
41
+
42
+
43
+ # Use register_fake to add a ``FakeTensor`` kernel for the operator
44
+ @dynamic_update_slice.register_fake
45
+ def _(in_tensor, update, start_indices):
46
+ return in_tensor.clone().detach()
47
+
48
+
49
+ @lowerings.lower(torch.ops.ai_edge_torch.dynamic_update_slice)
50
+ def _dynamic_update_slice_lower(
51
+ lctx,
52
+ in_tensor: ir.Value,
53
+ update: ir.Value,
54
+ start_indices: Sequence[ir.Value],
55
+ ):
56
+ return stablehlo.dynamic_update_slice(in_tensor, update, start_indices)