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,91 @@
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 Llama 3.2 1B 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.llama import llama
24
+ from ai_edge_torch.generative.utilities import converter
25
+ from ai_edge_torch.generative.utilities.model_builder import ExportConfig
26
+
27
+ _MODEL_SIZE = flags.DEFINE_enum(
28
+ 'model_size',
29
+ '1b',
30
+ ['1b', '3b'],
31
+ 'The size of the model to verify.',
32
+ )
33
+ _CHECKPOINT_PATH = flags.DEFINE_string(
34
+ 'checkpoint_path',
35
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/llama'),
36
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
37
+ )
38
+ _OUTPUT_PATH = flags.DEFINE_string(
39
+ 'output_path',
40
+ '/tmp/',
41
+ 'The path to export the tflite model.',
42
+ )
43
+ _OUTPUT_NAME_PREFIX = flags.DEFINE_string(
44
+ 'output_name_prefix',
45
+ 'llama',
46
+ 'The prefix of the output tflite model name.',
47
+ )
48
+ _PREFILL_SEQ_LENS = flags.DEFINE_multi_integer(
49
+ 'prefill_seq_lens',
50
+ (8, 64, 128, 256, 512, 1024),
51
+ 'List of the maximum sizes of prefill input tensors.',
52
+ )
53
+ _KV_CACHE_MAX_LEN = flags.DEFINE_integer(
54
+ 'kv_cache_max_len',
55
+ 1280,
56
+ 'The maximum size of KV cache buffer, including both prefill and decode.',
57
+ )
58
+ _QUANTIZE = flags.DEFINE_bool(
59
+ 'quantize',
60
+ True,
61
+ 'Whether the model should be quantized.',
62
+ )
63
+ _LORA_RANKS = flags.DEFINE_multi_integer(
64
+ 'lora_ranks',
65
+ None,
66
+ 'If set, the model will be converted with the provided list of LoRA ranks.',
67
+ )
68
+
69
+ _BUILDER = {
70
+ '1b': llama.build_1b_model,
71
+ '3b': llama.build_3b_model,
72
+ }
73
+
74
+
75
+ def main(_):
76
+ pytorch_model = _BUILDER[_MODEL_SIZE.value](
77
+ _CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
78
+ )
79
+ converter.convert_to_tflite(
80
+ pytorch_model,
81
+ output_path=_OUTPUT_PATH.value,
82
+ output_name_prefix=_OUTPUT_NAME_PREFIX.value,
83
+ prefill_seq_len=_PREFILL_SEQ_LENS.value,
84
+ quantize=_QUANTIZE.value,
85
+ lora_ranks=_LORA_RANKS.value,
86
+ export_config=ExportConfig(),
87
+ )
88
+
89
+
90
+ if __name__ == '__main__':
91
+ app.run(main)
@@ -0,0 +1,196 @@
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 Llama 3.2 models."""
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 torch
25
+
26
+ TENSOR_NAMES = model_builder.TENSOR_NAMES
27
+
28
+
29
+ def _build_llama3_rope_cache(
30
+ input_pos: torch.Tensor,
31
+ n_elem: int,
32
+ base: int,
33
+ condense_ratio: int,
34
+ dtype: torch.dtype,
35
+ device: torch.device,
36
+ factor: float,
37
+ low_freq_factor: float,
38
+ high_freq_factor: float,
39
+ max_seq_len: int,
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ """Computes Rotary Positional Embeddings for Llama 3.2 model.
42
+
43
+ It's a modified version of attn_utils.build_rope_cache with additional
44
+ arguments for Llama 3.2 model. It precomputes Rotary Positional Embedding Sin
45
+ and Cos values with scaling factors for quick lookup during the inference.
46
+
47
+ Reference:
48
+ https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_rope_utils.py#L307
49
+
50
+ Args:
51
+ input_pos (torch.Tensor): the given input sequence positions
52
+ n_elem (int): Each sequence's dimmension.
53
+ base (int): Rope base value.
54
+ condense_ratio (int): The ratio by which sequence indicies are condensed.
55
+ dtype (torch.dtype): Output tensor's data type.
56
+ device (torch.device): Output tensor's data type.
57
+ factor (float): Factor to scale theta down for tokens in long range in the
58
+ sequence.
59
+ low_freq_factor (float): Factor to determine if tokens are in long range
60
+ in the sequence.
61
+ high_freq_factor (float): Factor to determine if tokens are in short range
62
+ in the sequence.
63
+ max_seq_len (int): The original token sequence length before extending
64
+ ROPE to support longer sequence.
65
+
66
+ Returns:
67
+ Tuple[torch.Tensor, torch.Tensor]: Rope's Cosine and Sine waves.
68
+ """
69
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2).float() / n_elem))
70
+ low_freq_wavelen = max_seq_len / low_freq_factor
71
+ high_freq_wavelen = max_seq_len / high_freq_factor
72
+ wavelen = 2 * math.pi / theta
73
+ # wavelen < high_freq_wavelen: do nothing
74
+ # wavelen > low_freq_wavelen: divide by factor
75
+ theta = torch.where(wavelen > low_freq_wavelen, theta / factor, theta)
76
+ # otherwise: interpolate between the two, using a smooth factor
77
+ smooth_factor = (max_seq_len / wavelen - low_freq_factor) / (
78
+ high_freq_factor - low_freq_factor
79
+ )
80
+ smoothed_theta = (1 - smooth_factor) * theta / factor + smooth_factor * theta
81
+ is_medium = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)
82
+ theta = torch.where(is_medium, smoothed_theta, theta)
83
+
84
+ seq_idx = input_pos / condense_ratio
85
+ idx_theta = torch.outer(seq_idx, theta)
86
+ cos = torch.cos(idx_theta).to(dtype=dtype, device=device)
87
+ sin = torch.sin(idx_theta).to(dtype=dtype, device=device)
88
+ return cos, sin
89
+
90
+
91
+ class Llama(model_builder.DecoderOnlyModel):
92
+ """A Llama model built from the Edge Generative API layers.
93
+
94
+ Llama 3.2 shares the same architecture as TinyLlama except ROPE calculation.
95
+ """
96
+
97
+ def __init__(self, config: cfg.ModelConfig):
98
+ super().__init__(config)
99
+ attn_config = self.config.block_config(0).attn_config
100
+
101
+
102
+ def get_1b_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
103
+ """Returns the model config for a Llama 3.2-1B model.
104
+
105
+ Args:
106
+ kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
107
+ is 1024.
108
+
109
+ Returns:
110
+ The model config for a SmolLM model.
111
+ """
112
+ attn_config = cfg.AttentionConfig(
113
+ num_heads=32,
114
+ head_dim=64,
115
+ num_query_groups=8,
116
+ rotary_base=500000,
117
+ rotary_percentage=1.0,
118
+ )
119
+ ff_config = cfg.FeedForwardConfig(
120
+ type=cfg.FeedForwardType.GATED,
121
+ activation=cfg.ActivationConfig(cfg.ActivationType.SILU),
122
+ intermediate_size=8192,
123
+ )
124
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
125
+ block_config = cfg.TransformerBlockConfig(
126
+ attn_config=attn_config,
127
+ ff_config=ff_config,
128
+ pre_attention_norm_config=norm_config,
129
+ post_attention_norm_config=norm_config,
130
+ )
131
+
132
+ max_seq_len = 8192
133
+ # Create the RoPE callable
134
+ build_rope = partial(
135
+ _build_llama3_rope_cache,
136
+ condense_ratio=1,
137
+ dtype=torch.float32,
138
+ device=torch.device("cpu"),
139
+ factor=32.0,
140
+ low_freq_factor=1.0,
141
+ high_freq_factor=4.0,
142
+ max_seq_len=max_seq_len,
143
+ )
144
+
145
+ config = cfg.ModelConfig(
146
+ vocab_size=128256,
147
+ num_layers=16,
148
+ max_seq_len=max_seq_len,
149
+ embedding_dim=2048,
150
+ kv_cache_max_len=kv_cache_max_len,
151
+ block_configs=block_config,
152
+ final_norm_config=norm_config,
153
+ enable_hlfb=True,
154
+ build_rope=build_rope,
155
+ )
156
+ return config
157
+
158
+
159
+ def get_3b_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
160
+ """Returns the model config for a Llama 3.2-3B model."""
161
+ config = get_1b_model_config(kv_cache_max_len)
162
+ # Llama 3.2 has only one block config.
163
+ attn_config = config.block_config(0).attn_config
164
+ attn_config.num_heads = 24
165
+ attn_config.head_dim = 128
166
+ config.num_layers = 28
167
+ config.embedding_dim = 3072
168
+ return config
169
+
170
+
171
+ def get_fake_model_config(**kwargs) -> cfg.ModelConfig:
172
+ config = get_1b_model_config(**kwargs)
173
+ config.vocab_size = 128
174
+ config.num_layers = 2
175
+ # SmolLM has only one block config.
176
+ config.block_config(0).ff_config.intermediate_size = 64
177
+ return config
178
+
179
+
180
+ def _build_model(
181
+ checkpoint_path: str, config: cfg.ModelConfig
182
+ ) -> torch.nn.Module:
183
+ return model_builder.build_decoder_only_model(
184
+ checkpoint_path=checkpoint_path,
185
+ config=config,
186
+ tensor_names=TENSOR_NAMES,
187
+ model_class=Llama,
188
+ )
189
+
190
+
191
+ def build_1b_model(checkpoint_path: str, **kwargs) -> torch.nn.Module:
192
+ return _build_model(checkpoint_path, get_1b_model_config(**kwargs))
193
+
194
+
195
+ def build_3b_model(checkpoint_path: str, **kwargs) -> torch.nn.Module:
196
+ return _build_model(checkpoint_path, get_3b_model_config(**kwargs))
@@ -0,0 +1,88 @@
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 Llama 3.2-1B model."""
17
+
18
+ import logging
19
+ import pathlib
20
+
21
+ from absl import app
22
+ from absl import flags
23
+ from ai_edge_torch.generative.examples.llama import llama
24
+ from ai_edge_torch.generative.utilities import transformers_verifier
25
+ from ai_edge_torch.generative.utilities import verifier
26
+ import transformers
27
+
28
+ _MODEL_SIZE = flags.DEFINE_enum(
29
+ "model_size",
30
+ "1b",
31
+ ["1b", "3b"],
32
+ "The size of the model to verify.",
33
+ )
34
+ _PROMPTS = flags.DEFINE_multi_string(
35
+ "prompts",
36
+ "What is the meaning of life?",
37
+ "The input prompts to generate answers.",
38
+ )
39
+ _MAX_NEW_TOKENS = flags.DEFINE_integer(
40
+ "max_new_tokens",
41
+ 30,
42
+ "The maximum size of the generated tokens.",
43
+ )
44
+
45
+ _CHECKPOINT = {
46
+ "1b": "meta-llama/Llama-3.2-1B-Instruct",
47
+ "3b": "meta-llama/Llama-3.2-3B-Instruct",
48
+ }
49
+
50
+ _BUILDER = {
51
+ "1b": llama.build_1b_model,
52
+ "3b": llama.build_3b_model,
53
+ }
54
+
55
+
56
+ def main(_):
57
+ checkpoint = _CHECKPOINT[_MODEL_SIZE.value]
58
+ logging.info("Loading the original model from: %s", checkpoint)
59
+ original_model = transformers.AutoModelForCausalLM.from_pretrained(checkpoint)
60
+
61
+ # Locate the cached dir.
62
+ cached_config_file = transformers.utils.cached_file(
63
+ checkpoint, transformers.utils.CONFIG_NAME
64
+ )
65
+ reauthored_checkpoint = pathlib.Path(cached_config_file).parent
66
+ logging.info("Building the reauthored model from: %s", reauthored_checkpoint)
67
+ reauthored_model = _BUILDER[_MODEL_SIZE.value](reauthored_checkpoint)
68
+
69
+ logging.info("Loading the tokenizer from: %s", checkpoint)
70
+ # Llama tokenizer_config.json sets a fast tokenizer class explicitly,
71
+ # "PreTrainedTokenizerFast". It works only when the fast tokenizer is
72
+ # available.
73
+ tokenizer = transformers.AutoTokenizer.from_pretrained(checkpoint)
74
+
75
+ verifier.verify_reauthored_model(
76
+ original_model=transformers_verifier.TransformersModelWrapper(
77
+ original_model
78
+ ),
79
+ reauthored_model=verifier.ReauthoredModelWrapper(reauthored_model),
80
+ tokenizer=verifier.TokenizerWrapper(tokenizer),
81
+ generate_prompts=_PROMPTS.value,
82
+ max_new_tokens=_MAX_NEW_TOKENS.value,
83
+ atol=1e-04,
84
+ )
85
+
86
+
87
+ if __name__ == "__main__":
88
+ 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,50 @@
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 Moonshine 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
+ import ai_edge_torch
24
+ from ai_edge_torch.generative.examples.moonshine import moonshine
25
+ from ai_edge_torch.generative.utilities import converter
26
+ import torch
27
+
28
+ _CHECKPOINT_PATH = flags.DEFINE_string(
29
+ 'checkpoint_path',
30
+ os.path.join(pathlib.Path.home(), 'Downloads/llm_data/moonshine'),
31
+ 'The path to the model checkpoint, or directory holding the checkpoint.',
32
+ )
33
+ _TFLITE_PATH = flags.DEFINE_string(
34
+ 'tflite_path',
35
+ '/tmp/',
36
+ 'The tflite file path to export.',
37
+ )
38
+
39
+
40
+ def main(_):
41
+ p_model = moonshine.build_preprocessor(_CHECKPOINT_PATH.value)
42
+ output_filename = f'moonshine_preprocessor.tflite'
43
+ _input = torch.randn((1, 1, 159414), dtype=torch.float)
44
+ edge_model = ai_edge_torch.convert(p_model, (_input,), quant_config=None)
45
+ tflite_path = os.path.join(_TFLITE_PATH.value, output_filename)
46
+ edge_model.export(tflite_path)
47
+
48
+
49
+ if __name__ == '__main__':
50
+ app.run(main)
@@ -0,0 +1,103 @@
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 the Moonshine model."""
17
+
18
+ import os
19
+ import pathlib
20
+ from typing import Optional, Tuple
21
+ from absl import app
22
+ from ai_edge_torch.generative.layers import attention
23
+ from ai_edge_torch.generative.layers import builder
24
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
25
+ import ai_edge_torch.generative.layers.attention_utils as attn_utils
26
+ import ai_edge_torch.generative.layers.model_config as cfg
27
+ import ai_edge_torch.generative.layers.normalization as normalization
28
+ import ai_edge_torch.generative.utilities.moonshine_loader as loading_utils
29
+ import h5py
30
+ import torch
31
+ from torch import nn
32
+ import torch.nn as nn
33
+
34
+ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
35
+ conv1D_0="layers/sequential/layers/conv1d/vars",
36
+ conv1D_1="layers/sequential/layers/conv1d_1/vars",
37
+ conv1D_2="layers/sequential/layers/conv1d_2/vars",
38
+ group_norm="layers/sequential/layers/group_normalization/vars",
39
+ )
40
+
41
+
42
+ class AudioPreprocessor(nn.Module):
43
+
44
+ def __init__(self, dim):
45
+ super(AudioPreprocessor, self).__init__()
46
+ self.conv1 = nn.Conv1d(
47
+ in_channels=1, out_channels=dim, kernel_size=127, stride=64, bias=False
48
+ )
49
+ self.tanh = nn.Tanh()
50
+ self.group_norm = normalization.GroupNorm(group_num=1, dim=dim, eps=1e-5)
51
+ self.conv2 = nn.Conv1d(
52
+ in_channels=dim,
53
+ out_channels=2 * dim,
54
+ kernel_size=7,
55
+ stride=3,
56
+ padding=0, # Equivalent to padding="valid"
57
+ )
58
+ self.gelu1 = nn.GELU()
59
+ self.conv3 = nn.Conv1d(
60
+ in_channels=2 * dim,
61
+ out_channels=dim,
62
+ kernel_size=3,
63
+ stride=2,
64
+ padding=0, # Equivalent to padding="valid"
65
+ )
66
+ self.gelu2 = nn.GELU()
67
+
68
+ def forward(self, inputs):
69
+ x = self.conv1(inputs)
70
+ x = self.tanh(x)
71
+ x = self.group_norm(x)
72
+ x = self.conv2(x)
73
+ x = self.gelu1(x)
74
+ x = self.conv3(x)
75
+ x = self.gelu2(x)
76
+ return x
77
+
78
+
79
+ def build_preprocessor(checkpoint_path: str, **kwargs) -> nn.Module:
80
+ ap = AudioPreprocessor(dim=416)
81
+ loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
82
+ loader.load(ap, strict=True)
83
+ return ap
84
+
85
+
86
+ def main(_):
87
+ # TODO(b/375421767) Remove golden checks once full model is implemented.
88
+ HF_PATH = os.path.join(pathlib.Path.home(), "Downloads/llm_data/moonshine")
89
+
90
+ test_data_path = pathlib.Path(__file__).parent.resolve()
91
+ INPUT_PATH = test_data_path / "data" / "pp_input.pt")
92
+ GOLDEN_PATH = test_data_path / "data" / "pp_output.pt")
93
+
94
+ ap = build_preprocessor(HF_PATH)
95
+ ap.eval()
96
+ inputs = torch.load(INPUT_PATH).reshape((1, 1, 159414))
97
+ out = ap(inputs)
98
+ golden = torch.load(GOLDEN_PATH).transpose(1, 2)
99
+ assert torch.allclose(out, golden, atol=1e-4, rtol=1e-4)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ 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 OpenELM 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.openelm import openelm
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/openelm'),
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
+ 'openelm',
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 = openelm.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)