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,399 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Common building blocks for Attention layer."""
17
+
18
+ from typing import Optional, Tuple, Union
19
+
20
+ from ai_edge_torch.generative.layers import builder
21
+ from ai_edge_torch.generative.layers import kv_cache as kv_utils
22
+ from ai_edge_torch.generative.layers import lora as lora_utils
23
+ from ai_edge_torch.generative.layers import scaled_dot_product_attention as sdpa
24
+ import ai_edge_torch.generative.layers.model_config as cfg
25
+ import ai_edge_torch.generative.layers.rotary_position_embedding as rotary_pos_emb
26
+ import torch
27
+ from torch import nn
28
+
29
+
30
+ class TransformerBlock(nn.Module):
31
+
32
+ def __init__(
33
+ self,
34
+ config: cfg.TransformerBlockConfig,
35
+ model_config: cfg.ModelConfig,
36
+ ) -> None:
37
+ """Initialize an instance of the TransformerBlock.
38
+
39
+ Args:
40
+ config (cfg.TransformerBlockConfig): the configuration object for this
41
+ transformer block.
42
+ model_config (cfg.ModelConfig): the configuration object for the model
43
+ this transformer block belongs to.
44
+ """
45
+ super().__init__()
46
+ self.pre_atten_norm = builder.build_norm(
47
+ model_config.embedding_dim,
48
+ config.pre_attention_norm_config,
49
+ )
50
+ self.atten_func = CausalSelfAttention(
51
+ model_config.batch_size,
52
+ model_config.embedding_dim,
53
+ config.attn_config,
54
+ model_config.enable_hlfb,
55
+ )
56
+ self.post_atten_norm = builder.build_norm(
57
+ model_config.embedding_dim,
58
+ config.post_attention_norm_config,
59
+ )
60
+ self.ff = builder.build_ff(model_config.embedding_dim, config.ff_config)
61
+ self.config = config
62
+
63
+ def forward(
64
+ self,
65
+ x: torch.Tensor,
66
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
67
+ mask: Optional[torch.Tensor] = None,
68
+ input_pos: Optional[torch.Tensor] = None,
69
+ kv_cache: kv_utils.KVCacheEntry = None,
70
+ lora: Optional[lora_utils.LoRAEntry] = None,
71
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
72
+ """Forward function of the TransformerBlock.
73
+
74
+ Args:
75
+ x (torch.Tensor): the input tensor.
76
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
77
+ mask (torch.Tensor): the optional mask tensor.
78
+ input_pos (torch.Tensor): the optional input position tensor.
79
+ kv_cache (KVCacheEntry): the optional kv cache entry.
80
+ lora (LoRAEntry): the optional lora entry.
81
+
82
+ Returns:
83
+ output activation from this transformer block, and updated kv cache (if
84
+ passed in).
85
+ """
86
+ kv = None
87
+ if self.config.parallel_residual:
88
+ x_norm = self.pre_atten_norm(x)
89
+ atten_func_out = self.atten_func(
90
+ x_norm, rope, mask, input_pos, kv_cache, lora
91
+ )
92
+ if kv_cache is None:
93
+ attn_out = atten_func_out
94
+ else:
95
+ attn_out, kv = atten_func_out
96
+ ff_out = self.ff(x_norm)
97
+ output = x + attn_out + ff_out
98
+ else:
99
+ x_norm = self.pre_atten_norm(x)
100
+ atten_func_out = self.atten_func(
101
+ x_norm, rope, mask, input_pos, kv_cache, lora
102
+ )
103
+ if kv_cache is None:
104
+ attn_out = atten_func_out
105
+ else:
106
+ attn_out, kv = atten_func_out
107
+ x = x + attn_out
108
+ x_norm = self.post_atten_norm(x)
109
+ output = x + self.ff(x_norm)
110
+
111
+ return output if kv is None else (output, kv)
112
+
113
+
114
+ class CausalSelfAttention(nn.Module):
115
+
116
+ def __init__(
117
+ self,
118
+ batch_size: int,
119
+ dim: int,
120
+ config: cfg.AttentionConfig,
121
+ enable_hlfb: bool,
122
+ ) -> None:
123
+ """Initialize an instance of CausalSelfAttention.
124
+
125
+ Args:
126
+ batch_size (int): batch size of the input tensor.
127
+ dim (int): causal attention's input/output dimmension.
128
+ config (cfg.AttentionConfig): attention specific configurations.
129
+ enable_hlfb (bool): whether hlfb is enabled or not.
130
+ """
131
+ super().__init__()
132
+ self.kv_cache = None
133
+ self.batch_size = batch_size
134
+ qkv_shape = (
135
+ config.num_heads + 2 * config.num_query_groups
136
+ ) * config.head_dim
137
+ output_shape = config.num_heads * config.head_dim
138
+ # Key, query, value projections for all heads.
139
+ self.qkv_projection = nn.Linear(dim, qkv_shape, bias=config.qkv_use_bias)
140
+ self.output_projection = nn.Linear(
141
+ output_shape, dim, bias=config.output_proj_use_bias
142
+ )
143
+ self.query_norm = builder.build_norm(
144
+ config.head_dim, config.query_norm_config
145
+ )
146
+ self.key_norm = builder.build_norm(config.head_dim, config.key_norm_config)
147
+ self.config = config
148
+ self.enable_hlfb = enable_hlfb
149
+ self.sdpa_func = (
150
+ sdpa.scaled_dot_product_attention_with_hlfb
151
+ if enable_hlfb
152
+ else sdpa.scaled_dot_product_attention
153
+ )
154
+
155
+ def forward(
156
+ self,
157
+ x: torch.Tensor,
158
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
159
+ mask: Optional[torch.Tensor] = None,
160
+ input_pos: Optional[torch.Tensor] = None,
161
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
162
+ lora: Optional[lora_utils.LoRAEntry] = None,
163
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
164
+ """Forward function of the CausalSelfAttention layer, which can support
165
+
166
+ MQA, GQA and MHA.
167
+
168
+ Args:
169
+ x (torch.Tensor): the input tensor.
170
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
171
+ mask (torch.Tensor): the optional mask tensor.
172
+ input_pos (torch.Tensor): the optional input position tensor.
173
+ kv_cache (KVCacheEntry): the KV cache entry corresponding to this module.
174
+ lora (LoRAEntry): the optional lora entry.
175
+
176
+ Returns:
177
+ output activation from this self attention layer, and the updated
178
+ KV Cach Entry (if passed in).
179
+ """
180
+ # Batch size, sequence length, embedding dimensionality.
181
+ B, T, E = x.size()
182
+ assert B == self.batch_size, (
183
+ "batch size of input tensor must match with the batch size specified in"
184
+ " the model configuration."
185
+ )
186
+
187
+ qkv = self.qkv_projection(x)
188
+
189
+ # Assemble into a number of query groups to support MHA, MQA and GQA.
190
+ q_per_kv = self.config.num_heads // self.config.num_query_groups
191
+ # Each group has >=1 queries, 1 key, and 1 value.
192
+ if self.config.qkv_transpose_before_split:
193
+ qkv = qkv.view(B, T, -1, self.config.head_dim)
194
+ q, k, v = qkv.split(
195
+ (
196
+ q_per_kv * self.config.num_query_groups,
197
+ self.config.num_query_groups,
198
+ self.config.num_query_groups,
199
+ ),
200
+ dim=-2,
201
+ )
202
+ else:
203
+ qkv = qkv.view(B, T, self.config.num_query_groups, -1)
204
+ q, k, v = qkv.split(
205
+ (
206
+ q_per_kv * self.config.head_dim,
207
+ self.config.head_dim,
208
+ self.config.head_dim,
209
+ ),
210
+ dim=-1,
211
+ )
212
+
213
+ if lora is not None:
214
+ q += lora_utils.apply_lora(x, lora.attention.query, shape=q.shape)
215
+ k += lora_utils.apply_lora(x, lora.attention.key, shape=k.shape)
216
+ v += lora_utils.apply_lora(x, lora.attention.value, shape=v.shape)
217
+
218
+ q = self.query_norm(q)
219
+ k = self.key_norm(k)
220
+
221
+ q = q.reshape(B, T, -1, self.config.head_dim)
222
+ k = k.reshape(B, T, -1, self.config.head_dim)
223
+ v = v.reshape(B, T, -1, self.config.head_dim)
224
+
225
+ if rope is not None:
226
+ # Compute rotary positional embedding for query and key.
227
+ n_elem = int(self.config.rotary_percentage * self.config.head_dim)
228
+ cos, sin = rope
229
+ q, k = rotary_pos_emb.apply_rope_inline(q, k, cos, sin)
230
+
231
+ if kv_cache is not None:
232
+ kv_cache = kv_utils.update(kv_cache, input_pos, k, v)
233
+ k, v = kv_cache.k_cache, kv_cache.v_cache
234
+
235
+ sdpa_out = self.sdpa_func(
236
+ q,
237
+ k,
238
+ v,
239
+ self.config.head_dim,
240
+ mask=mask,
241
+ softcap=self.config.logit_softcap,
242
+ )
243
+ sdpa_out = sdpa_out.reshape(B, T, -1)
244
+
245
+ # Compute the output projection.
246
+ y = self.output_projection(sdpa_out)
247
+ if lora is not None:
248
+ y += lora_utils.apply_lora(sdpa_out, lora.attention.output)
249
+
250
+ return y if kv_cache is None else (y, kv_cache)
251
+
252
+
253
+ class SelfAttention(CausalSelfAttention):
254
+ """Non-causal Self Attention module, which is equivalent to CausalSelfAttention without mask."""
255
+
256
+ def forward(
257
+ self,
258
+ x: torch.Tensor,
259
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
260
+ input_pos: Optional[torch.Tensor] = None,
261
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
262
+ lora: Optional[lora_utils.LoRAEntry] = None,
263
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
264
+ """Forward function of the SelfAttention layer, which can support MQA, GQA and MHA.
265
+
266
+ Args:
267
+ x (torch.Tensor): the input tensor.
268
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
269
+ input_pos (torch.Tensor): the optional input position tensor.
270
+ kv_cache (KVCacheEntry): the KV cache entry corresponding to this module.
271
+ lora (LoRAEntry): the optional lora entry.
272
+
273
+ Returns:
274
+ output activation from this self attention layer, and the updated
275
+ KV Cach Entry (if passed in).
276
+ """
277
+ B, T, _ = x.size()
278
+ assert (
279
+ kv_cache is None
280
+ ), "KV cache is not supported in non-causal SelfAttention."
281
+ return super().forward(
282
+ x,
283
+ rope=rope,
284
+ mask=torch.zeros((B, 1, T, T), dtype=torch.float32),
285
+ input_pos=input_pos,
286
+ lora=lora,
287
+ )
288
+
289
+
290
+ class CrossAttention(nn.Module):
291
+
292
+ def __init__(
293
+ self,
294
+ batch_size: int,
295
+ query_dim: int,
296
+ cross_dim: int,
297
+ hidden_dim: int,
298
+ output_dim: int,
299
+ config: cfg.AttentionConfig,
300
+ enable_hlfb: bool,
301
+ ):
302
+ """Initialize an instance of CrossAttention.
303
+
304
+ Args:
305
+ batch_size (int): batch size of the input tensor.
306
+ query_dim (int): query tensor's dimension.
307
+ cross_dim (int): cross attention's dimensions, for key and value tensors.
308
+ hidden_dim (int): hidden dimension that q, k, v tensors project to.
309
+ output_dim (int): output tensor's dimension.
310
+ config (cfg.AttentionConfig): attention specific configurations.
311
+ enable_hlfb (bool): whether hlfb is enabled or not.
312
+ """
313
+ super().__init__()
314
+ self.config = config
315
+ self.n_heads = config.num_heads
316
+ self.q_projection = nn.Linear(
317
+ query_dim, hidden_dim, bias=config.qkv_use_bias
318
+ )
319
+ self.k_projection = nn.Linear(
320
+ cross_dim, hidden_dim, bias=config.qkv_use_bias
321
+ )
322
+ self.v_projection = nn.Linear(
323
+ cross_dim, hidden_dim, bias=config.qkv_use_bias
324
+ )
325
+ self.output_projection = nn.Linear(
326
+ hidden_dim, output_dim, bias=config.output_proj_use_bias
327
+ )
328
+
329
+ self.sdpa_func = (
330
+ sdpa.scaled_dot_product_attention_with_hlfb
331
+ if enable_hlfb
332
+ else sdpa.scaled_dot_product_attention
333
+ )
334
+
335
+ def forward(
336
+ self,
337
+ x: torch.Tensor,
338
+ y: torch.Tensor,
339
+ rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
340
+ mask: Optional[torch.Tensor] = None,
341
+ input_pos: Optional[torch.Tensor] = None,
342
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
343
+ lora: Optional[lora_utils.LoRAEntry] = None,
344
+ ):
345
+ """Forward function of the CrossAttention layer.
346
+
347
+ Args:
348
+ x (torch.Tensor): the target tensor, with shape [B, target_seq_len, ...].
349
+ y (torch.Tensor): the source tensor, with shape [B, source_seq_len, ...].
350
+ rope (Tuple[torch.Tensor, torch.Tensor]): the optional input rope tensor.
351
+ mask (torch.Tensor): the optional mask tensor can be broadcaseted to shape
352
+ [B, n_heads, target_seq_len, source_seq_len].
353
+ input_pos (torch.Tensor): the optional input position tensor.
354
+ kv_cache (KVCacheEntry): the KV cache entry corresponding to this module.
355
+ lora (LoRAEntry): the optional lora entry.
356
+
357
+ Returns:
358
+ output activation from this cross attention layer.
359
+ """
360
+ batch_size = x.size()[0]
361
+ target_seq_len = x.size()[1]
362
+ source_seq_len = y.size()[1]
363
+
364
+ q = self.q_projection(x)
365
+ k = self.k_projection(y)
366
+ v = self.v_projection(y)
367
+
368
+ if lora is not None:
369
+ q += lora_utils.apply_lora(x, lora.attention.query, shape=q.shape)
370
+ k += lora_utils.apply_lora(x, lora.attention.key, shape=k.shape)
371
+ v += lora_utils.apply_lora(x, lora.attention.value, shape=v.shape)
372
+
373
+ interim_shape = (batch_size, -1, self.n_heads, self.config.head_dim)
374
+ q = q.view(interim_shape)
375
+ k = k.view(interim_shape)
376
+ v = v.view(interim_shape)
377
+
378
+ if rope is not None:
379
+ # Compute rotary positional embedding for query and key.
380
+ n_elem = int(self.config.rotary_percentage * self.config.head_dim)
381
+ cos, sin = rope
382
+ q, k = rotary_pos_emb.apply_rope_inline(q, k, cos, sin)
383
+
384
+ if kv_cache is not None:
385
+ kv_cache = kv_utils.update(kv_cache, input_pos, k, v)
386
+ k, v = kv_cache.k_cache, kv_cache.v_cache
387
+ if mask is None:
388
+ mask = torch.zeros(
389
+ (batch_size, 1, target_seq_len, source_seq_len), dtype=torch.float32
390
+ )
391
+ y = self.sdpa_func(q, k, v, self.config.head_dim, mask=mask)
392
+ y = y.reshape(batch_size, target_seq_len, -1)
393
+
394
+ # Compute the output projection.
395
+ y = self.output_projection(y)
396
+ if lora is not None:
397
+ y += lora_utils.apply_lora(y, lora.attention.output)
398
+
399
+ return y if kv_cache is None else (y, kv_cache)
@@ -0,0 +1,210 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # Common utility functions used with attention module.
16
+
17
+ import math
18
+ from typing import Tuple
19
+
20
+ import torch
21
+
22
+
23
+ def build_rope_cache(
24
+ size: int,
25
+ dim: int,
26
+ base: int = 10000,
27
+ condense_ratio: int = 1,
28
+ dtype: torch.dtype = torch.float32,
29
+ device: torch.device = None,
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """Precomputes Rotary Positional Embeddings.
32
+
33
+ Precompute Rotary Positional Embedding Sin and Cos values for quick lookup
34
+ during the inference.
35
+
36
+ Args:
37
+ size (int): The size of the built cache.
38
+ dim (int): Each sequence's dimmension.
39
+ base (int, optional): Rope base value. Defaults to 10000.
40
+ condense_ratio (int, optional): The ratio by which sequence indicies are
41
+ condensed. Defaults to 1.
42
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
43
+ torch.float32.
44
+ device (torch.device, optional): Output tensor's data type. Defaults to
45
+ None in which case "cpu" is used.
46
+
47
+ Returns:
48
+ Tuple[torch.Tensor, torch.Tensor]: Rope's Cosine and Sine waves.
49
+ """
50
+ if device is None:
51
+ device = torch.device('cpu')
52
+ theta = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
53
+ seq_idx = torch.arange(size) / condense_ratio
54
+ idx_theta = torch.outer(seq_idx, theta)
55
+ cos = torch.cos(idx_theta).to(dtype=dtype, device=device)
56
+ sin = torch.sin(idx_theta).to(dtype=dtype, device=device)
57
+ return cos, sin
58
+
59
+
60
+ def build_causal_mask_cache(
61
+ size: int,
62
+ dtype: torch.dtype = torch.float32,
63
+ device: torch.device = None,
64
+ ) -> torch.Tensor:
65
+ """Build a cache for causal attention mask.
66
+
67
+ Args:
68
+ size (int): The size of the built mask cache.
69
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
70
+ torch.float32.
71
+ device (torch.device, optional): Output tensor's data type. Defaults to
72
+ None in which case "cpu" is used.
73
+
74
+ Returns:
75
+ torch.Tensor: Causal attention mask.
76
+ """
77
+
78
+ if device is None:
79
+ device = torch.device('cpu')
80
+ mask = torch.full((size, size), float('-inf'), dtype=dtype, device=device)
81
+ return torch.triu(mask, diagonal=1).unsqueeze(0).unsqueeze(0)
82
+
83
+
84
+ def build_sliding_window_mask_cache(
85
+ size: int,
86
+ window_size: int,
87
+ dtype: torch.dtype = torch.float32,
88
+ device: torch.device = None,
89
+ ) -> torch.Tensor:
90
+ """Build a cache for a sliding window mask.
91
+
92
+ Args:
93
+ size (int): The size of the built mask cache.
94
+ window_size (int): The window size that is "seen" by a token.
95
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
96
+ torch.float32.
97
+ device (torch.device, optional): Output tensor's data type. Defaults to
98
+ None in which case "cpu" is used.
99
+
100
+ Returns:
101
+ torch.Tensor: Causal attention mask.
102
+ """
103
+
104
+ mask = build_causal_mask_cache(size, dtype, device)
105
+ all_ones = torch.ones_like(mask)
106
+ window_size = min(size, window_size)
107
+ sliding_mask = torch.triu(all_ones, -1 * window_size + 1) * torch.tril(
108
+ all_ones, window_size - 1
109
+ )
110
+ return torch.where(sliding_mask == 1, mask, float('-inf'))
111
+
112
+
113
+ def relative_position_bucket(
114
+ relative_position: torch.Tensor,
115
+ bidirectional: bool,
116
+ num_buckets: int,
117
+ max_distance: int,
118
+ ) -> torch.Tensor:
119
+ """Adapted from Mesh Tensorflow:
120
+
121
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
122
+
123
+ Translate relative position to a bucket number for relative attention. The
124
+ relative position is defined as
125
+ memory_position - query_position, i.e. the distance in tokens from the
126
+ attending position to the attended-to
127
+ position. If bidirectional=False, then positive relative positions are
128
+ invalid. We use smaller buckets for
129
+ small absolute relative_position and larger buckets for larger absolute
130
+ relative_positions. All relative
131
+ positions >=max_distance map to the same bucket. All relative positions
132
+ <=-max_distance map to the same bucket.
133
+ This should allow for more graceful generalization to longer sequences than
134
+ the model has been trained on
135
+
136
+ Args:
137
+ relative_position: an int32 Tensor
138
+ bidirectional: a boolean - whether the attention is bidirectional
139
+ num_buckets: an integer for number of buckets.
140
+ max_distance: an integer for max distance.
141
+
142
+ Returns:
143
+ a Tensor with the same shape as relative_position, containing int32 values
144
+ in the range [0, num_buckets)
145
+ """
146
+ relative_buckets = 0
147
+ if bidirectional:
148
+ num_buckets //= 2
149
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
150
+ relative_position = torch.abs(relative_position)
151
+ else:
152
+ relative_position = -torch.min(
153
+ relative_position, torch.zeros_like(relative_position)
154
+ )
155
+ # now relative_position is in the range [0, inf)
156
+
157
+ # half of the buckets are for exact increments in positions
158
+ max_exact = num_buckets // 2
159
+ is_small = relative_position < max_exact
160
+
161
+ # The other half of the buckets are for logarithmically bigger bins in
162
+ # positions up to max_distance
163
+ relative_position_if_large = max_exact + (
164
+ torch.log(relative_position.float() / max_exact)
165
+ / math.log(max_distance / max_exact)
166
+ * (num_buckets - max_exact)
167
+ ).to(torch.long)
168
+ relative_position_if_large = torch.min(
169
+ relative_position_if_large,
170
+ torch.full_like(relative_position_if_large, num_buckets - 1),
171
+ )
172
+
173
+ relative_buckets += torch.where(
174
+ is_small, relative_position, relative_position_if_large
175
+ )
176
+ return relative_buckets
177
+
178
+
179
+ def build_relative_position_buckets(
180
+ query_length: int,
181
+ key_length: int,
182
+ bidirectional: bool = True,
183
+ num_buckets: int = 32,
184
+ max_distance: int = 128,
185
+ ) -> torch.Tensor:
186
+ """Relative position buckets for computing bias.
187
+
188
+ Args:
189
+ query_length: an integer of length of current query tensor.
190
+ key_length: an integer of length of current key tensor.
191
+ bidirectional: a boolean - whether the attention is bidirectional, default
192
+ is True.
193
+ num_buckets: an integer for number of buckets, default is 32.
194
+ max_distance: an integer for max distance, default is 128.
195
+
196
+ Returns:
197
+ A torch.Tensor of computed relative position buckets.
198
+ """
199
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
200
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
201
+ relative_position = (
202
+ memory_position - context_position
203
+ ) # shape (query_length, key_length)
204
+ rel_pos_bucket = relative_position_bucket(
205
+ relative_position, # shape (query_length, key_length)
206
+ bidirectional=bidirectional,
207
+ num_buckets=num_buckets,
208
+ max_distance=max_distance,
209
+ )
210
+ return rel_pos_bucket.unsqueeze(0).unsqueeze(0)