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,246 @@
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
+ # Attention modules for the T5 encoder-decoder model family.
16
+
17
+ from typing import Optional, Tuple
18
+
19
+ from ai_edge_torch.generative.layers.attention import CrossAttention
20
+ import ai_edge_torch.generative.layers.builder as builder
21
+ from ai_edge_torch.generative.layers.kv_cache import KVCache
22
+ import ai_edge_torch.generative.layers.model_config as cfg
23
+ from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention # NOQA
24
+ from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention_with_hlfb # NOQA
25
+ import torch
26
+ from torch import nn
27
+
28
+ BATCH_SIZE = 1
29
+
30
+
31
+ class EncoderDecoderBlock(nn.Module):
32
+
33
+ def __init__(
34
+ self,
35
+ config: cfg.TransformerBlockConfig,
36
+ model_config: cfg.ModelConfig,
37
+ has_relative_attention_bias: bool = False,
38
+ ) -> None:
39
+ """Initialize an instance of the EncoderDecoderBlock.
40
+
41
+ Args:
42
+ config (cfg.TransformerBlockConfig): the configuration object for this
43
+ transformer block.
44
+ model_config (cfg.ModelConfig): the configuration object for the model
45
+ this transformer block belongs to.
46
+ has_relative_attention_bias (bool): whether the self attention block has
47
+ relative bias.
48
+ """
49
+
50
+ super().__init__()
51
+ self.atten_func = T5Attention(
52
+ BATCH_SIZE,
53
+ model_config.embedding_dim,
54
+ config.attn_config,
55
+ config.pre_attention_norm_config,
56
+ model_config.kv_cache_max,
57
+ model_config.enable_hlfb,
58
+ has_relative_attention_bias=has_relative_attention_bias,
59
+ )
60
+ # For a decoder, we add a cross attention.
61
+ if model_config.is_decoder:
62
+ self.cross_atten_func = T5Attention(
63
+ BATCH_SIZE,
64
+ model_config.embedding_dim,
65
+ config.attn_config,
66
+ config.pre_attention_norm_config,
67
+ model_config.kv_cache_max,
68
+ model_config.enable_hlfb,
69
+ # Cross Attention does not have relative attention bias.
70
+ has_relative_attention_bias=False,
71
+ )
72
+ else:
73
+ self.cross_atten_func = None
74
+
75
+ self.post_atten_norm = builder.build_norm(
76
+ model_config.embedding_dim,
77
+ config.post_attention_norm_config,
78
+ )
79
+ self.ff = builder.build_ff(model_config.embedding_dim, config.ff_config)
80
+ self.config = config
81
+
82
+ def forward(
83
+ self,
84
+ x: torch.Tensor,
85
+ input_pos: Optional[torch.Tensor] = None,
86
+ mask: Optional[torch.Tensor] = None,
87
+ relative_position: Optional[torch.Tensor] = None,
88
+ position_bias: Optional[torch.Tensor] = None,
89
+ encoder_hidden_states: Optional[torch.Tensor] = None,
90
+ encoder_attention_mask: Optional[torch.Tensor] = None,
91
+ encoder_decoder_position_bias: Optional[torch.Tensor] = None,
92
+ ) -> torch.Tensor:
93
+ """Forward function of the EncoderDecoderBlock.
94
+
95
+ Args:
96
+ x (torch.Tensor): the input tensor.
97
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
98
+ mask (torch.Tensor): the optional mask tensor.
99
+ input_pos (torch.Tensor): the optional input position tensor.
100
+
101
+ Returns:
102
+ output activation from this transformer block.
103
+ """
104
+
105
+ hidden_states, position_bias = self.atten_func(
106
+ x,
107
+ input_pos=input_pos,
108
+ mask=mask,
109
+ relative_position=relative_position,
110
+ position_bias=position_bias,
111
+ )
112
+
113
+ attn_out = hidden_states + x
114
+
115
+ if self.cross_atten_func:
116
+ hidden_states, encoder_decoder_position_bias = self.cross_atten_func(
117
+ attn_out,
118
+ input_pos=input_pos,
119
+ key_value_states=encoder_hidden_states,
120
+ mask=encoder_attention_mask,
121
+ relative_position=relative_position,
122
+ position_bias=encoder_decoder_position_bias,
123
+ )
124
+ attn_out = hidden_states + attn_out
125
+
126
+ forwarded = self.post_atten_norm(attn_out)
127
+ forwarded = self.ff(forwarded)
128
+ hidden_states = attn_out + forwarded
129
+
130
+ # encoder_deocder_position_bias is from CrossAttention
131
+ return hidden_states, position_bias, encoder_decoder_position_bias
132
+
133
+
134
+ class T5Attention(CrossAttention):
135
+
136
+ def __init__(
137
+ self,
138
+ batch: int,
139
+ dim: int,
140
+ config: cfg.AttentionConfig,
141
+ norm_config: cfg.NormalizationConfig,
142
+ kv_cache_max: int,
143
+ enable_hlfb: bool,
144
+ has_relative_attention_bias=False,
145
+ ) -> None:
146
+ """Initialize an instance of T5Attention.
147
+
148
+ Args:
149
+ dim (int): causal attention's input/output dimmension.
150
+ config (cfg.AttentionConfig): attention specific configurations.
151
+ norm_config (cfg.NormalizationConfig): normalization configure before
152
+ attention.
153
+ kv_cache_max (int): determines the size of the KV Cache buffer, if
154
+ enabled.
155
+ enable_hlfb (bool): whether hlfb is enabled or not.
156
+ has_relative_attention_bias (bool): whether we compute relative bias.
157
+ """
158
+ super().__init__(batch, dim, dim, config, kv_cache_max, enable_hlfb)
159
+ self.pre_atten_norm = builder.build_norm(dim, norm_config)
160
+
161
+ self.has_relative_attention_bias = has_relative_attention_bias
162
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
163
+ if self.has_relative_attention_bias:
164
+ self.relative_attention_bias = nn.Embedding(
165
+ self.relative_attention_num_buckets, self.n_heads
166
+ )
167
+
168
+ def forward(
169
+ self,
170
+ x: torch.Tensor,
171
+ input_pos: Optional[torch.Tensor] = None,
172
+ key_value_states: Optional[torch.Tensor] = None,
173
+ mask: Optional[torch.Tensor] = None,
174
+ relative_position: Optional[torch.Tensor] = None,
175
+ position_bias: Optional[torch.Tensor] = None,
176
+ ) -> torch.Tensor:
177
+ """Forward function of the T5Attention layer.
178
+
179
+ Args:
180
+ x (torch.Tensor): the input tensor.
181
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
182
+ mask (torch.Tensor): the optional mask tensor.
183
+ input_pos (torch.Tensor): the optional input position tensor.
184
+
185
+ Returns:
186
+ output activation from this self attention layer.
187
+ """
188
+
189
+ x = self.pre_atten_norm(x)
190
+ B, T, C = (
191
+ x.size()
192
+ ) # batch size, sequence length, embedding dimensionality (n_embd)
193
+ query_states = self.q_projection(x)
194
+ query_states = query_states.reshape(
195
+ B, T, -1, self.config.head_dim
196
+ ) # (B, T, nh_q, hs)
197
+
198
+ if key_value_states is not None:
199
+ (
200
+ kvB,
201
+ kvT,
202
+ kvC,
203
+ ) = (
204
+ key_value_states.size()
205
+ ) # batch size, sequence length, embedding dimensionality (n_embd)
206
+ key_states = self.k_projection(key_value_states)
207
+ value_states = self.v_projection(key_value_states)
208
+ key_states = key_states.reshape(kvB, kvT, -1, self.config.head_dim)
209
+ value_states = value_states.reshape(kvB, kvT, -1, self.config.head_dim)
210
+ else:
211
+ key_states = self.k_projection(x)
212
+ value_states = self.v_projection(x)
213
+ key_states = key_states.reshape(B, T, -1, self.config.head_dim)
214
+ value_states = value_states.reshape(B, T, -1, self.config.head_dim)
215
+
216
+ if key_value_states is None and self.kv_cache is not None:
217
+ key_states, value_states = self.kv_cache.update_cache(
218
+ input_pos, key_states, value_states
219
+ )
220
+
221
+ if position_bias is None:
222
+ # handle the encoder case first
223
+ if self.has_relative_attention_bias:
224
+ position_bias = self.relative_attention_bias(
225
+ relative_position
226
+ ) # shape (query_length, key_length, num_heads)
227
+ position_bias = position_bias.permute([0, 1, 4, 2, 3]).squeeze(
228
+ 0
229
+ ) # shape (1, num_heads, query_length, key_length)
230
+ else:
231
+ # position_bias = torch.zeros(B, self.n_heads, T, self.config.head_dim, dtype=torch.float32)
232
+ position_bias = torch.zeros_like(mask, dtype=torch.float32)
233
+
234
+ mask = mask + position_bias
235
+ y = self.sdpa_func(
236
+ query_states,
237
+ key_states,
238
+ value_states,
239
+ self.config.head_dim,
240
+ mask=mask,
241
+ scale=1.0,
242
+ )
243
+ y = y.reshape(B, T, C) # re-assemble all head outputs side by side
244
+ # output projection
245
+ y = self.output_projection(y)
246
+ return y, position_bias
@@ -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,105 @@
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
+ # A toy example which has a single-layer transformer block.
16
+ from absl import app
17
+ import ai_edge_torch
18
+ from ai_edge_torch import lowertools
19
+ from ai_edge_torch.generative.examples.test_models import toy_model
20
+ from ai_edge_torch.generative.examples.test_models import toy_model_with_kv_cache
21
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
22
+ import torch
23
+
24
+ KV_CACHE_MAX_LEN = 100
25
+
26
+
27
+ def convert_toy_model(_) -> None:
28
+ """Converts a toy model to tflite."""
29
+ model = toy_model.ToySingleLayerModel(toy_model.get_model_config())
30
+ idx = torch.unsqueeze(torch.arange(0, KV_CACHE_MAX_LEN), 0)
31
+ input_pos = torch.arange(0, KV_CACHE_MAX_LEN)
32
+ print('running an inference')
33
+ print(
34
+ model.forward(
35
+ idx,
36
+ input_pos,
37
+ )
38
+ )
39
+
40
+ # Convert model to tflite.
41
+ print('converting model to tflite')
42
+ edge_model = ai_edge_torch.convert(
43
+ model,
44
+ (
45
+ idx,
46
+ input_pos,
47
+ ),
48
+ )
49
+ edge_model.export('/tmp/toy_model.tflite')
50
+
51
+
52
+ def _export_stablehlo_mlir(model, args):
53
+ ep = torch.export.export(model, args)
54
+ return lowertools.exported_program_to_mlir_text(ep)
55
+
56
+
57
+ def convert_toy_model_with_kv_cache(_) -> None:
58
+ """Converts a toy model with kv cache to tflite."""
59
+ dump_mlir = False
60
+
61
+ config = toy_model_with_kv_cache.get_model_config()
62
+ model = toy_model_with_kv_cache.ToyModelWithKVCache(config)
63
+ model.eval()
64
+ print('running an inference')
65
+ kv = kv_utils.KVCache.from_model_config(config)
66
+
67
+ tokens, input_pos = toy_model_with_kv_cache.get_sample_prefill_inputs()
68
+ decode_token, decode_input_pos = (
69
+ toy_model_with_kv_cache.get_sample_decode_inputs()
70
+ )
71
+ print(model.forward(tokens, input_pos, kv))
72
+
73
+ if dump_mlir:
74
+ mlir_text = _export_stablehlo_mlir(model, (tokens, input_pos, kv))
75
+ with open('/tmp/toy_model_with_external_kv.stablehlo.mlir', 'w') as f:
76
+ f.write(mlir_text)
77
+
78
+ # Convert model to tflite with 2 signatures (prefill + decode).
79
+ print('converting toy model to tflite with 2 signatures (prefill + decode)')
80
+ edge_model = (
81
+ ai_edge_torch.signature(
82
+ 'prefill',
83
+ model,
84
+ sample_kwargs={
85
+ 'tokens': tokens,
86
+ 'input_pos': input_pos,
87
+ 'kv_cache': kv,
88
+ },
89
+ )
90
+ .signature(
91
+ 'decode',
92
+ model,
93
+ sample_kwargs={
94
+ 'tokens': decode_token,
95
+ 'input_pos': decode_input_pos,
96
+ 'kv_cache': kv,
97
+ },
98
+ )
99
+ .convert()
100
+ )
101
+ edge_model.export('/tmp/toy_external_kv_cache.tflite')
102
+
103
+
104
+ if __name__ == '__main__':
105
+ app.run(convert_toy_model)
@@ -0,0 +1,156 @@
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
+ # A toy example which has a single-layer transformer block.
16
+ from typing import Optional, Tuple
17
+
18
+ from ai_edge_torch.generative.layers import builder
19
+ from ai_edge_torch.generative.layers.attention import TransformerBlock
20
+ import ai_edge_torch.generative.layers.attention_utils as attn_utils
21
+ import ai_edge_torch.generative.layers.model_config as cfg
22
+ import torch
23
+ from torch import nn
24
+
25
+ RoPECache = Tuple[torch.Tensor, torch.Tensor]
26
+ KV_CACHE_MAX_LEN = 100
27
+
28
+
29
+ class ToySingleLayerModel(torch.nn.Module):
30
+
31
+ def __init__(self, config: cfg.ModelConfig) -> None:
32
+ super().__init__()
33
+ self.lm_head = nn.Linear(
34
+ config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
35
+ )
36
+ self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
37
+ self.transformer_block = TransformerBlock(config.block_config(0), config)
38
+ self.final_norm = builder.build_norm(
39
+ config.embedding_dim,
40
+ config.final_norm_config,
41
+ )
42
+ # Toy model has only one block config.
43
+ attn_config = config.block_config(0).attn_config
44
+ self.rope_cache = attn_utils.build_rope_cache(
45
+ size=config.max_seq_len,
46
+ dim=int(attn_config.rotary_percentage * attn_config.head_dim),
47
+ base=attn_config.rotary_base,
48
+ )
49
+ self.mask_cache = attn_utils.build_causal_mask_cache(
50
+ size=config.max_seq_len,
51
+ )
52
+ self.config = config
53
+
54
+ @torch.inference_mode
55
+ def forward(
56
+ self,
57
+ idx: torch.Tensor,
58
+ input_pos: torch.Tensor,
59
+ mask: Optional[torch.Tensor] = None,
60
+ ) -> torch.Tensor:
61
+ x = self.tok_embedding(idx)
62
+ cos, sin = self.rope_cache
63
+
64
+ cos = cos.index_select(0, input_pos)
65
+ sin = sin.index_select(0, input_pos)
66
+ if mask is None:
67
+ mask = self.mask_cache.index_select(2, input_pos)
68
+ mask = mask[:, :, :, : self.config.max_seq_len]
69
+
70
+ x = self.transformer_block(x, (cos, sin), mask, input_pos)
71
+ x = self.final_norm(x)
72
+ return self.lm_head(x)
73
+
74
+
75
+ class ToySingleLayerModelWeightSharing(torch.nn.Module):
76
+
77
+ def __init__(self, config: cfg.ModelConfig) -> None:
78
+ super().__init__()
79
+ self.lm_head = nn.Linear(
80
+ config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
81
+ )
82
+ self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
83
+ self.lm_head = nn.Linear(
84
+ config.embedding_dim,
85
+ config.vocab_size,
86
+ bias=config.lm_head_use_bias,
87
+ )
88
+ self.lm_head.weight.data = self.tok_embedding.weight.data
89
+ self.transformer_block = TransformerBlock(config.block_config(0), config)
90
+ self.final_norm = builder.build_norm(
91
+ config.embedding_dim,
92
+ config.final_norm_config,
93
+ )
94
+ # Toy model has only one block config.
95
+ attn_config = config.block_config(0).attn_config
96
+ self.rope_cache = attn_utils.build_rope_cache(
97
+ size=config.max_seq_len,
98
+ dim=int(attn_config.rotary_percentage * attn_config.head_dim),
99
+ base=attn_config.rotary_base,
100
+ )
101
+ self.mask_cache = attn_utils.build_causal_mask_cache(
102
+ size=config.max_seq_len,
103
+ )
104
+ self.config = config
105
+
106
+ @torch.inference_mode
107
+ def forward(
108
+ self,
109
+ idx: torch.Tensor,
110
+ input_pos: torch.Tensor,
111
+ mask: Optional[torch.Tensor] = None,
112
+ ) -> torch.Tensor:
113
+ x = self.tok_embedding(idx)
114
+ cos, sin = self.rope_cache
115
+
116
+ cos = cos.index_select(0, input_pos)
117
+ sin = sin.index_select(0, input_pos)
118
+ mask = self.mask_cache.index_select(2, input_pos)
119
+ mask = mask[:, :, :, : self.config.max_seq_len]
120
+
121
+ x = self.transformer_block(x, (cos, sin), mask, input_pos)
122
+ x = self.final_norm(x)
123
+ res = self.lm_head(x)
124
+ return res
125
+
126
+
127
+ def get_model_config() -> cfg.ModelConfig:
128
+ attn_config = cfg.AttentionConfig(
129
+ num_heads=32,
130
+ head_dim=4,
131
+ num_query_groups=4,
132
+ rotary_base=10000,
133
+ rotary_percentage=1.0,
134
+ enable_kv_cache=False,
135
+ )
136
+ ff_config = cfg.FeedForwardConfig(
137
+ type=cfg.FeedForwardType.GATED,
138
+ activation=cfg.ActivationConfig(cfg.ActivationType.SILU),
139
+ intermediate_size=256,
140
+ )
141
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
142
+ block_config = cfg.TransformerBlockConfig(
143
+ attn_config=attn_config,
144
+ ff_config=ff_config,
145
+ pre_attention_norm_config=norm_config,
146
+ post_attention_norm_config=norm_config,
147
+ )
148
+ config = cfg.ModelConfig(
149
+ vocab_size=400,
150
+ num_layers=1,
151
+ max_seq_len=KV_CACHE_MAX_LEN,
152
+ embedding_dim=128,
153
+ block_configs=block_config,
154
+ final_norm_config=norm_config,
155
+ )
156
+ return config
@@ -0,0 +1,138 @@
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
+ """A toy example which has basic transformer block (w/ externalized KV-Cache)."""
17
+
18
+ from typing import Optional, Tuple
19
+
20
+ from ai_edge_torch.generative.layers import attention
21
+ from ai_edge_torch.generative.layers import builder
22
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
23
+ import ai_edge_torch.generative.layers.attention_utils as attn_utils
24
+ import ai_edge_torch.generative.layers.model_config as cfg
25
+ from ai_edge_torch.generative.utilities.model_builder import ExportConfig
26
+ import torch
27
+ from torch import nn
28
+
29
+ RoPECache = Tuple[torch.Tensor, torch.Tensor]
30
+
31
+
32
+ class ToyModelWithKVCache(torch.nn.Module):
33
+
34
+ def __init__(self, config: cfg.ModelConfig) -> None:
35
+ super().__init__()
36
+ self.lm_head = nn.Linear(
37
+ config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
38
+ )
39
+ self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
40
+ # Toy model has only one block config.
41
+ block_config = config.block_config(0)
42
+ self.transformer_blocks = nn.ModuleList(
43
+ attention.TransformerBlock(block_config, config)
44
+ for _ in range(config.num_layers)
45
+ )
46
+ self.final_norm = builder.build_norm(
47
+ config.embedding_dim,
48
+ config.final_norm_config,
49
+ )
50
+ attn_config = block_config.attn_config
51
+ self.rope_cache = attn_utils.build_rope_cache(
52
+ size=config.max_seq_len,
53
+ dim=int(attn_config.rotary_percentage * attn_config.head_dim),
54
+ base=attn_config.rotary_base,
55
+ )
56
+ self.mask_cache = attn_utils.build_causal_mask_cache(
57
+ size=config.max_seq_len,
58
+ )
59
+ self.config = config
60
+
61
+ def forward(
62
+ self,
63
+ tokens: torch.Tensor,
64
+ input_pos: torch.Tensor,
65
+ kv_cache: kv_utils.KVCache,
66
+ mask: Optional[torch.Tensor] = None,
67
+ export_config: Optional[ExportConfig] = None,
68
+ ) -> Tuple[torch.Tensor, kv_utils.KVCache]:
69
+ x = self.tok_embedding(tokens)
70
+ cos, sin = self.rope_cache
71
+ cos = cos.index_select(0, input_pos)
72
+ sin = sin.index_select(0, input_pos)
73
+ if mask is None:
74
+ mask = self.mask_cache.index_select(2, input_pos)
75
+ mask = mask[:, :, :, : self.config.max_seq_len]
76
+
77
+ updated_kv_entries = []
78
+ for i, block in enumerate(self.transformer_blocks):
79
+ kv_entry = kv_cache.caches[i] if kv_cache else None
80
+ x, kv_entry = block(x, (cos, sin), mask, input_pos, kv_entry)
81
+ if kv_entry:
82
+ updated_kv_entries.append(kv_entry)
83
+
84
+ updated_kv_cache = kv_utils.KVCache(tuple(updated_kv_entries))
85
+
86
+ if export_config is not None:
87
+ if (
88
+ torch.numel(input_pos) > 1
89
+ and not export_config.output_logits_on_prefill
90
+ ):
91
+ return {'kv_cache': updated_kv_cache}
92
+
93
+ x = self.final_norm(x)
94
+ return {'logits': self.lm_head(x), 'kv_cache': updated_kv_cache}
95
+
96
+
97
+ def get_model_config() -> cfg.ModelConfig:
98
+ attn_config = cfg.AttentionConfig(
99
+ num_heads=32,
100
+ head_dim=4,
101
+ num_query_groups=4,
102
+ rotary_base=10000,
103
+ rotary_percentage=1.0,
104
+ )
105
+ ff_config = cfg.FeedForwardConfig(
106
+ type=cfg.FeedForwardType.GATED,
107
+ activation=cfg.ActivationConfig(cfg.ActivationType.SILU),
108
+ intermediate_size=256,
109
+ )
110
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
111
+ block_config = cfg.TransformerBlockConfig(
112
+ attn_config=attn_config,
113
+ ff_config=ff_config,
114
+ pre_attention_norm_config=norm_config,
115
+ post_attention_norm_config=norm_config,
116
+ )
117
+ config = cfg.ModelConfig(
118
+ vocab_size=150,
119
+ num_layers=2,
120
+ max_seq_len=100,
121
+ embedding_dim=128,
122
+ block_configs=block_config,
123
+ final_norm_config=norm_config,
124
+ enable_hlfb=True,
125
+ )
126
+ return config
127
+
128
+
129
+ def get_sample_prefill_inputs() -> Tuple[torch.Tensor, torch.Tensor]:
130
+ tokens = torch.unsqueeze(torch.arange(0, 100, dtype=torch.int), 0)
131
+ input_pos = torch.arange(0, 100, dtype=torch.int)
132
+ return tokens, input_pos
133
+
134
+
135
+ def get_sample_decode_inputs() -> Tuple[torch.Tensor, torch.Tensor]:
136
+ tokens = torch.tensor([[1]], dtype=torch.int)
137
+ input_pos = torch.tensor([10])
138
+ return tokens, input_pos
@@ -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
+ # ==============================================================================