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,99 @@
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
+ """Verifies the reauthored image encoder of PaliGemma 3B model."""
17
+
18
+ import logging
19
+ import pathlib
20
+ from absl import app
21
+ from absl import flags
22
+ from ai_edge_torch.generative.examples.paligemma import image_encoder
23
+ import kagglehub
24
+ from PIL import Image
25
+ import requests
26
+ import torch
27
+ import transformers
28
+
29
+ _VERSION = flags.DEFINE_enum(
30
+ "version",
31
+ "2",
32
+ ["1", "2"],
33
+ "The version of PaliGemma vision model to verify.",
34
+ )
35
+ _IMAGE_URL = flags.DEFINE_string(
36
+ "image_url",
37
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg?download=true",
38
+ "The image URI to encode.",
39
+ )
40
+
41
+ _CHECKPOINT = {
42
+ "1": "google/paligemma-3b-mix-224",
43
+ "2": "google/paligemma-2/transformers/paligemma2-3b-pt-224",
44
+ }
45
+
46
+
47
+ def main(_):
48
+ if _VERSION.value == "1":
49
+ checkpoint = _CHECKPOINT[_VERSION.value]
50
+ # Locate the cached dir.
51
+ cached_config_file = transformers.utils.cached_file(
52
+ checkpoint, transformers.utils.CONFIG_NAME
53
+ )
54
+ reauthored_checkpoint = pathlib.Path(cached_config_file).parent
55
+ else:
56
+ checkpoint = kagglehub.model_download(_CHECKPOINT[_VERSION.value])
57
+ reauthored_checkpoint = checkpoint
58
+
59
+ logging.info("Loading the original model from: %s", checkpoint)
60
+ original_full_model = (
61
+ transformers.PaliGemmaForConditionalGeneration.from_pretrained(checkpoint)
62
+ )
63
+ original_vision_model = original_full_model.eval().vision_tower
64
+
65
+ logging.info("Building the reauthored model from: %s", reauthored_checkpoint)
66
+ reauthored_model = image_encoder.build_image_encoder(reauthored_checkpoint)
67
+
68
+ logging.info("Loading the processor from: %s", checkpoint)
69
+ # It works only when GemmaTokenizerFast is available. In some environments,
70
+ # use_fast=False doeesn't work either if the tokenizer cannot load the
71
+ # sentencepiece model file properly.
72
+ processor = transformers.AutoProcessor.from_pretrained(checkpoint)
73
+
74
+ logging.info("Loading the image from: %s", _IMAGE_URL.value)
75
+ image = Image.open(requests.get(_IMAGE_URL.value, stream=True).raw)
76
+ pixel_values = processor(images=image, return_tensors="pt")["pixel_values"]
77
+
78
+ logging.info("Forwarding the original model...")
79
+ outputs_original = original_vision_model.forward(pixel_values=pixel_values)
80
+ outputs_original = outputs_original.last_hidden_state
81
+ logging.info("outputs_original: %s", outputs_original)
82
+
83
+ logging.info("Forwarding the reauthored model...")
84
+ outputs_reauthored = reauthored_model.forward(pixel_values=pixel_values)
85
+ logging.info("outputs_reauthored: %s", outputs_reauthored)
86
+
87
+ try:
88
+ assert torch.allclose(
89
+ outputs_original, outputs_reauthored, atol=1e-03, rtol=1e-04
90
+ )
91
+ except AssertionError as e:
92
+ logging.error("*** FAILED *** verify with an image")
93
+ raise e
94
+ else:
95
+ logging.info("*** PASSED *** verify with an image")
96
+
97
+
98
+ if __name__ == "__main__":
99
+ app.run(main)
@@ -0,0 +1,14 @@
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
+ # ==============================================================================
@@ -0,0 +1,80 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Example of converting a Phi-3.5 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.phi import phi3
24
+ from ai_edge_torch.generative.utilities import converter
25
+ from ai_edge_torch.generative.utilities.model_builder import ExportConfig
26
+
27
+ _CHECKPOINT_PATH = flags.DEFINE_string(
28
+ 'checkpoint_path',
29
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/phi3'),
30
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
31
+ )
32
+ _OUTPUT_PATH = flags.DEFINE_string(
33
+ 'output_path',
34
+ '/tmp/',
35
+ 'The path to export the tflite model.',
36
+ )
37
+ _OUTPUT_NAME_PREFIX = flags.DEFINE_string(
38
+ 'output_name_prefix',
39
+ 'phi3',
40
+ 'The prefix of the output tflite model name.',
41
+ )
42
+ _PREFILL_SEQ_LENS = flags.DEFINE_multi_integer(
43
+ 'prefill_seq_lens',
44
+ (8, 64, 128, 256, 512, 1024),
45
+ 'List of the maximum sizes of prefill input tensors.',
46
+ )
47
+ _KV_CACHE_MAX_LEN = flags.DEFINE_integer(
48
+ 'kv_cache_max_len',
49
+ 1280,
50
+ 'The maximum size of KV cache buffer, including both prefill and decode.',
51
+ )
52
+ _QUANTIZE = flags.DEFINE_bool(
53
+ 'quantize',
54
+ True,
55
+ 'Whether the model should be quantized.',
56
+ )
57
+ _LORA_RANKS = flags.DEFINE_multi_integer(
58
+ 'lora_ranks',
59
+ None,
60
+ 'If set, the model will be converted with the provided list of LoRA ranks.',
61
+ )
62
+
63
+
64
+ def main(_):
65
+ pytorch_model = phi3.build_model(
66
+ _CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
67
+ )
68
+ converter.convert_to_tflite(
69
+ pytorch_model,
70
+ output_path=_OUTPUT_PATH.value,
71
+ output_name_prefix=_OUTPUT_NAME_PREFIX.value,
72
+ prefill_seq_len=_PREFILL_SEQ_LENS.value,
73
+ quantize=_QUANTIZE.value,
74
+ lora_ranks=_LORA_RANKS.value,
75
+ export_config=ExportConfig(),
76
+ )
77
+
78
+
79
+ if __name__ == '__main__':
80
+ app.run(main)
@@ -0,0 +1,80 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Example of converting a Phi-2 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.phi import phi2
24
+ from ai_edge_torch.generative.utilities import converter
25
+ from ai_edge_torch.generative.utilities.model_builder import ExportConfig
26
+
27
+ _CHECKPOINT_PATH = flags.DEFINE_string(
28
+ 'checkpoint_path',
29
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/phi2'),
30
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
31
+ )
32
+ _OUTPUT_PATH = flags.DEFINE_string(
33
+ 'output_path',
34
+ '/tmp/',
35
+ 'The path to export the tflite model.',
36
+ )
37
+ _OUTPUT_NAME_PREFIX = flags.DEFINE_string(
38
+ 'output_name_prefix',
39
+ 'phi2',
40
+ 'The prefix of the output tflite model name.',
41
+ )
42
+ _PREFILL_SEQ_LENS = flags.DEFINE_multi_integer(
43
+ 'prefill_seq_lens',
44
+ (8, 64, 128, 256, 512, 1024),
45
+ 'List of the maximum sizes of prefill input tensors.',
46
+ )
47
+ _KV_CACHE_MAX_LEN = flags.DEFINE_integer(
48
+ 'kv_cache_max_len',
49
+ 1280,
50
+ 'The maximum size of KV cache buffer, including both prefill and decode.',
51
+ )
52
+ _QUANTIZE = flags.DEFINE_bool(
53
+ 'quantize',
54
+ True,
55
+ 'Whether the model should be quantized.',
56
+ )
57
+ _LORA_RANKS = flags.DEFINE_multi_integer(
58
+ 'lora_ranks',
59
+ None,
60
+ 'If set, the model will be converted with the provided list of LoRA ranks.',
61
+ )
62
+
63
+
64
+ def main(_):
65
+ pytorch_model = phi2.build_model(
66
+ _CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
67
+ )
68
+ converter.convert_to_tflite(
69
+ pytorch_model,
70
+ output_path=_OUTPUT_PATH.value,
71
+ output_name_prefix=_OUTPUT_NAME_PREFIX.value,
72
+ prefill_seq_len=_PREFILL_SEQ_LENS.value,
73
+ quantize=_QUANTIZE.value,
74
+ lora_ranks=_LORA_RANKS.value,
75
+ export_config=ExportConfig(),
76
+ )
77
+
78
+
79
+ if __name__ == '__main__':
80
+ app.run(main)
@@ -0,0 +1,107 @@
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 building a Phi-2 model."""
17
+
18
+ import ai_edge_torch.generative.layers.model_config as cfg
19
+ from ai_edge_torch.generative.utilities import model_builder
20
+ import ai_edge_torch.generative.utilities.loader as loading_utils
21
+ from torch import nn
22
+
23
+ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
24
+ ff_up_proj="model.layers.{}.mlp.fc1",
25
+ ff_down_proj="model.layers.{}.mlp.fc2",
26
+ attn_query_proj="model.layers.{}.self_attn.q_proj",
27
+ attn_key_proj="model.layers.{}.self_attn.k_proj",
28
+ attn_value_proj="model.layers.{}.self_attn.v_proj",
29
+ attn_output_proj="model.layers.{}.self_attn.dense",
30
+ pre_attn_norm="model.layers.{}.input_layernorm",
31
+ embedding="model.embed_tokens",
32
+ final_norm="model.final_layernorm",
33
+ lm_head="lm_head",
34
+ )
35
+
36
+
37
+ class Phi2(model_builder.DecoderOnlyModel):
38
+ """A Phi-2 model built from the Edge Generative API layers."""
39
+ pass
40
+
41
+
42
+ def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
43
+ """Returns the model config for a Phi-2 model.
44
+
45
+ Args:
46
+ kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
47
+ is 1024.
48
+
49
+ Returns:
50
+ The model config for a Phi-2 model.
51
+ """
52
+ attn_config = cfg.AttentionConfig(
53
+ num_heads=32,
54
+ head_dim=80,
55
+ num_query_groups=32,
56
+ rotary_base=10000,
57
+ rotary_percentage=0.4,
58
+ qkv_use_bias=True,
59
+ output_proj_use_bias=True,
60
+ )
61
+ ff_config = cfg.FeedForwardConfig(
62
+ type=cfg.FeedForwardType.SEQUENTIAL,
63
+ activation=cfg.ActivationConfig(cfg.ActivationType.GELU_TANH),
64
+ intermediate_size=10240,
65
+ use_bias=True,
66
+ )
67
+ norm_config = cfg.NormalizationConfig(
68
+ type=cfg.NormalizationType.LAYER_NORM,
69
+ )
70
+ block_config = cfg.TransformerBlockConfig(
71
+ attn_config=attn_config,
72
+ ff_config=ff_config,
73
+ pre_attention_norm_config=norm_config,
74
+ parallel_residual=True,
75
+ )
76
+ config = cfg.ModelConfig(
77
+ vocab_size=51200,
78
+ num_layers=32,
79
+ max_seq_len=2048,
80
+ kv_cache_max_len=kv_cache_max_len,
81
+ embedding_dim=2560,
82
+ block_configs=block_config,
83
+ final_norm_config=norm_config,
84
+ lm_head_use_bias=True,
85
+ lm_head_share_weight_with_embedding=False,
86
+ enable_hlfb=True,
87
+ )
88
+ return config
89
+
90
+
91
+ def get_fake_model_config(kv_cache_max_len: int = 128) -> cfg.ModelConfig:
92
+ config = get_model_config(kv_cache_max_len)
93
+ config.vocab_size = 128
94
+ config.num_layers = 2
95
+ config.max_seq_len = 2 * kv_cache_max_len
96
+ # Phi-2 has only one block config.
97
+ config.block_config(0).ff_config.intermediate_size = 128
98
+ return config
99
+
100
+
101
+ def build_model(checkpoint_path: str, **kwargs) -> nn.Module:
102
+ return model_builder.build_decoder_only_model(
103
+ checkpoint_path=checkpoint_path,
104
+ config=get_model_config(**kwargs),
105
+ tensor_names=TENSOR_NAMES,
106
+ model_class=Phi2,
107
+ )
@@ -0,0 +1,219 @@
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 building a Phi-3.5 model up to 4K tokens, not to 128K tokens."""
17
+
18
+ from functools import partial
19
+ import math
20
+ from typing import Tuple
21
+
22
+ import ai_edge_torch.generative.layers.model_config as cfg
23
+ from ai_edge_torch.generative.utilities import model_builder
24
+ import ai_edge_torch.generative.utilities.loader as loading_utils
25
+ import torch
26
+
27
+ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
28
+ ff_up_proj="model.layers.{}.mlp.gate_up_proj",
29
+ ff_down_proj="model.layers.{}.mlp.down_proj",
30
+ attn_fused_qkv_proj="model.layers.{}.self_attn.qkv_proj",
31
+ attn_output_proj="model.layers.{}.self_attn.o_proj",
32
+ pre_attn_norm="model.layers.{}.input_layernorm",
33
+ post_attn_norm="model.layers.{}.post_attention_layernorm",
34
+ embedding="model.embed_tokens",
35
+ final_norm="model.norm",
36
+ lm_head="lm_head",
37
+ )
38
+
39
+ # max_position_embeddings / original_max_position_embeddings in Phi-3.5 config.
40
+ ROPE_SCALE_FACTOR = 32
41
+
42
+ # ROPE short factor in Phi-3.5 config. According to LOPE paper and its code in
43
+ # https://github.com/microsoft/LongRoPE, these values had been searched with
44
+ # min=1.0, step-0.01 to optimize the errors of sample dataset.
45
+ ROPE_SHORT_FACTOR = [
46
+ 1.0,
47
+ 1.0199999809265137,
48
+ 1.0299999713897705,
49
+ 1.0299999713897705,
50
+ 1.0499999523162842,
51
+ 1.0499999523162842,
52
+ 1.0499999523162842,
53
+ 1.0499999523162842,
54
+ 1.0499999523162842,
55
+ 1.0699999332427979,
56
+ 1.0999999046325684,
57
+ 1.1099998950958252,
58
+ 1.1599998474121094,
59
+ 1.1599998474121094,
60
+ 1.1699998378753662,
61
+ 1.2899998426437378,
62
+ 1.339999794960022,
63
+ 1.679999828338623,
64
+ 1.7899998426437378,
65
+ 1.8199998140335083,
66
+ 1.8499997854232788,
67
+ 1.8799997568130493,
68
+ 1.9099997282028198,
69
+ 1.9399996995925903,
70
+ 1.9899996519088745,
71
+ 2.0199997425079346,
72
+ 2.0199997425079346,
73
+ 2.0199997425079346,
74
+ 2.0199997425079346,
75
+ 2.0199997425079346,
76
+ 2.0199997425079346,
77
+ 2.0299997329711914,
78
+ 2.0299997329711914,
79
+ 2.0299997329711914,
80
+ 2.0299997329711914,
81
+ 2.0299997329711914,
82
+ 2.0299997329711914,
83
+ 2.0299997329711914,
84
+ 2.0299997329711914,
85
+ 2.0299997329711914,
86
+ 2.0799996852874756,
87
+ 2.0899996757507324,
88
+ 2.189999580383301,
89
+ 2.2199995517730713,
90
+ 2.5899994373321533,
91
+ 2.729999542236328,
92
+ 2.749999523162842,
93
+ 2.8399994373321533,
94
+ ]
95
+
96
+
97
+ def _build_phi3_rope(
98
+ input_pos: int,
99
+ n_elem: int,
100
+ base: int,
101
+ condense_ratio: int,
102
+ dtype: torch.dtype,
103
+ device: torch.device,
104
+ theta_factors: torch.Tensor,
105
+ scale: float,
106
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
107
+ """Computes Rotary Positional Embeddings for Phi-3.5 model.
108
+
109
+ It's a modified version of attn_utils.build_rope_cache with additional
110
+ arguments for Phi-3.5 model. It precompute Rotary Positional Embedding Sin and
111
+ Cos values with scaling factors for quick lookup during the inference.
112
+
113
+ Args:
114
+ input_pos (torch.Tensor): the given input sequence positions
115
+ n_elem (int): Each sequence's dimmension.
116
+ base (int, optional): Rope base value.
117
+ condense_ratio (int, optional): The ratio by which sequence indicies are
118
+ condensed.
119
+ dtype (torch.dtype, optional): Output tensor's data type.
120
+ device (torch.device, optional): Output tensor's data type.
121
+ theta_factors (torch.Tensor, optional): A tensor of shape (n_elem,) used
122
+ to scale the theta values.
123
+ scale (float, optional): A float used to scale the rope values.
124
+
125
+ Returns:
126
+ Tuple[torch.Tensor, torch.Tensor]: Rope's Cosine and Sine waves.
127
+ """
128
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2).float() / n_elem))
129
+ theta = theta / theta_factors
130
+ seq_idx = input_pos / condense_ratio
131
+ idx_theta = torch.outer(seq_idx, theta)
132
+ cos = torch.cos(idx_theta).to(dtype=dtype, device=device) * scale
133
+ sin = torch.sin(idx_theta).to(dtype=dtype, device=device) * scale
134
+ return cos, sin
135
+
136
+
137
+ class Phi3_5Mini(model_builder.DecoderOnlyModel):
138
+ """A Phi-3.5 model built from the Edge Generative API layers."""
139
+
140
+ def __init__(self, config: cfg.ModelConfig):
141
+ super().__init__(config)
142
+ attn_config = self.config.block_config(0).attn_config
143
+
144
+
145
+ def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
146
+ """Returns the model config for a Phi-3.5 model.
147
+
148
+ Args:
149
+ kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
150
+ is 1024.
151
+
152
+ Returns:
153
+ The model config for a Phi-2 model.
154
+ """
155
+ attn_config = cfg.AttentionConfig(
156
+ num_heads=32,
157
+ head_dim=96,
158
+ num_query_groups=32,
159
+ rotary_base=10000,
160
+ rotary_percentage=1.0,
161
+ qkv_transpose_before_split=True,
162
+ )
163
+ ff_config = cfg.FeedForwardConfig(
164
+ type=cfg.FeedForwardType.SEQUENTIAL,
165
+ activation=cfg.ActivationConfig(cfg.ActivationType.SILU_GLU),
166
+ intermediate_size=8192,
167
+ )
168
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
169
+ block_config = cfg.TransformerBlockConfig(
170
+ attn_config=attn_config,
171
+ ff_config=ff_config,
172
+ pre_attention_norm_config=norm_config,
173
+ post_attention_norm_config=norm_config,
174
+ )
175
+
176
+ max_seq_len = 4096
177
+ # Create the RoPE callable
178
+ build_rope = partial(
179
+ _build_phi3_rope,
180
+ condense_ratio=1,
181
+ dtype=torch.float32,
182
+ device=torch.device("cpu"),
183
+ theta_factors=torch.tensor(ROPE_SHORT_FACTOR),
184
+ scale=math.sqrt(1 + math.log(ROPE_SCALE_FACTOR) / math.log(max_seq_len)),
185
+ )
186
+
187
+ config = cfg.ModelConfig(
188
+ vocab_size=32064,
189
+ num_layers=32,
190
+ max_seq_len=max_seq_len,
191
+ kv_cache_max_len=kv_cache_max_len,
192
+ embedding_dim=3072,
193
+ block_configs=block_config,
194
+ final_norm_config=norm_config,
195
+ lm_head_share_weight_with_embedding=False,
196
+ enable_hlfb=True,
197
+ build_rope=build_rope,
198
+ )
199
+ return config
200
+
201
+
202
+ def get_fake_model_config(kv_cache_max_len: int = 128) -> cfg.ModelConfig:
203
+ config = get_model_config(kv_cache_max_len)
204
+ config.vocab_size = 128
205
+ config.num_layers = 2
206
+ config.max_seq_len = 2 * kv_cache_max_len
207
+ # Phi-3.5 has only one block config.
208
+ config.block_config(0).ff_config.intermediate_size = 128
209
+ return config
210
+
211
+
212
+ def build_model(checkpoint_path: str, **kwargs) -> torch.nn.Module:
213
+ """Instantiates the model instance and load checkpoint if provided."""
214
+ return model_builder.build_decoder_only_model(
215
+ checkpoint_path=checkpoint_path,
216
+ config=get_model_config(**kwargs),
217
+ tensor_names=TENSOR_NAMES,
218
+ model_class=Phi3_5Mini,
219
+ )
@@ -0,0 +1,64 @@
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
+ """Verifies the reauthored Phi-2 model."""
17
+ import logging
18
+
19
+ from absl import app
20
+ from absl import flags
21
+ from ai_edge_torch.generative.examples.phi import phi2
22
+ from ai_edge_torch.generative.utilities import transformers_verifier
23
+ from ai_edge_torch.generative.utilities import verifier
24
+ import kagglehub
25
+ import transformers
26
+
27
+
28
+ _PROMPTS = flags.DEFINE_multi_string(
29
+ "prompts",
30
+ "Instruct: Write an email about the weather Output:",
31
+ "The input prompts to generate answers.",
32
+ )
33
+ _MAX_NEW_TOKENS = flags.DEFINE_integer(
34
+ "max_new_tokens",
35
+ 30,
36
+ "The maximum size of the generated tokens.",
37
+ )
38
+
39
+
40
+ def main(_):
41
+ checkpoint = kagglehub.model_download("Microsoft/phi/transformers/2")
42
+ logging.info("Loading the original model from: %s", checkpoint)
43
+ original_model = transformers.AutoModelForCausalLM.from_pretrained(checkpoint)
44
+
45
+ logging.info("Building the reauthored model from: %s", checkpoint)
46
+ reauthored_model = phi2.build_model(checkpoint)
47
+
48
+ logging.info("Loading the tokenizer from: %s", checkpoint)
49
+ tokenizer = transformers.AutoTokenizer.from_pretrained(checkpoint)
50
+
51
+ verifier.verify_reauthored_model(
52
+ original_model=transformers_verifier.TransformersModelWrapper(
53
+ original_model
54
+ ),
55
+ reauthored_model=verifier.ReauthoredModelWrapper(reauthored_model),
56
+ tokenizer=verifier.TokenizerWrapper(tokenizer),
57
+ generate_prompts=_PROMPTS.value,
58
+ max_new_tokens=_MAX_NEW_TOKENS.value,
59
+ atol=1e-03,
60
+ )
61
+
62
+
63
+ if __name__ == "__main__":
64
+ app.run(main)