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,160 @@
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
+ # Builder class for individual components.
16
+ from typing import Callable
17
+
18
+ import ai_edge_torch.generative.layers.feed_forward as feed_forward
19
+ import ai_edge_torch.generative.layers.model_config as cfg
20
+ import ai_edge_torch.generative.layers.normalization as normalization
21
+ import torch
22
+ from torch import nn
23
+ import torch.nn.functional as F
24
+
25
+
26
+ class GeGLU(nn.Module):
27
+ """GeGLU is an activation function which is a variant of GELU.
28
+
29
+ GeGLU(x) = (xW+b) * GELU(xV+c)
30
+ See: https://arxiv.org/abs/2002.05202v1
31
+ """
32
+
33
+ def __init__(self, d_in: int, d_out: int):
34
+ super().__init__()
35
+ self.proj = nn.Linear(d_in, d_out * 2)
36
+
37
+ def forward(self, x: torch.Tensor):
38
+ x, gate = self.proj(x).chunk(2, dim=-1)
39
+ return x * F.gelu(gate)
40
+
41
+
42
+ class SwiGLU(nn.Module):
43
+ """SwiGLU is an activation function which is a variant of GLU.
44
+
45
+ SwiGLU is same as SiLU_GLU, because The SiLU function is also known as the
46
+ swish function.
47
+
48
+ SwiGLU(x) = Swish(xW+b) * (xV+c)
49
+ See: https://paperswithcode.com/method/swiglu
50
+ """
51
+
52
+ def forward(self, x: torch.Tensor):
53
+ x, y = x.chunk(2, dim=-1)
54
+ return F.silu(x) * y
55
+
56
+
57
+ def build_norm(dim: int, config: cfg.NormalizationConfig):
58
+ """Builder function for normalizers.
59
+
60
+ Args:
61
+ dim (int): dimension of the input tensor.
62
+ config (`NormalizationConfig` object): the normalization configuration.
63
+
64
+ Returns:
65
+ The constructed `nn.Module` normalization layer.
66
+
67
+ Raises:
68
+ ValueError: If config's `layer_norm_type` is not supported.
69
+ """
70
+ if config.type == cfg.NormalizationType.NONE:
71
+ return lambda x: x
72
+ elif config.type == cfg.NormalizationType.RMS_NORM:
73
+ return normalization.RMSNorm(
74
+ dim,
75
+ eps=config.epsilon,
76
+ zero_centered_gamma=config.zero_centered,
77
+ enable_hlfb=config.enable_hlfb,
78
+ )
79
+ elif config.type == cfg.NormalizationType.LAYER_NORM:
80
+ return normalization.LayerNorm(dim, config.epsilon, config.enable_hlfb)
81
+ elif config.type == cfg.NormalizationType.GROUP_NORM:
82
+ return normalization.GroupNorm(
83
+ config.group_num, dim, config.epsilon, config.enable_hlfb
84
+ )
85
+ else:
86
+ raise ValueError("Unsupported norm type.")
87
+
88
+
89
+ def build_ff(dim: int, config: cfg.FeedForwardConfig):
90
+ """Builder function for Feed Forward. Supports `Sequential` and `Gated`.
91
+
92
+ Args:
93
+ dim (int): dimension of the input tensor.
94
+ config (`FeedForwardConfig` object): the model configuration.
95
+
96
+ Returns:
97
+ The constructed `nn.Module` feedforward layer.
98
+
99
+ Raises:
100
+ ValueError: If config's `ff_type` is not supported.
101
+ """
102
+ ff_type = config.type
103
+ if ff_type == cfg.FeedForwardType.SEQUENTIAL:
104
+ ff_module = feed_forward.SequentialFeedForward
105
+ elif ff_type == cfg.FeedForwardType.GATED:
106
+ ff_module = feed_forward.GatedFeedForward
107
+ else:
108
+ raise ValueError("Unsupported feedforward type.")
109
+
110
+ activation = get_activation(config.activation)
111
+
112
+ pre_ff_norm = build_norm(dim, config.pre_ff_norm_config)
113
+ post_ff_norm = build_norm(dim, config.post_ff_norm_config)
114
+
115
+ return ff_module(
116
+ dim=dim,
117
+ hidden_dim=config.intermediate_size,
118
+ activation=activation,
119
+ use_bias=config.use_bias,
120
+ use_glu=(
121
+ config.activation.type == cfg.ActivationType.GE_GLU
122
+ or config.activation.type == cfg.ActivationType.SILU_GLU
123
+ ),
124
+ pre_ff_norm=pre_ff_norm,
125
+ post_ff_norm=post_ff_norm,
126
+ )
127
+
128
+
129
+ def get_activation(config: cfg.ActivationConfig):
130
+ """Get pytorch callable activation from the activation config.
131
+
132
+ Args:
133
+ config (cfg.ActivationConfig): activation config.
134
+
135
+ Returns:
136
+ Activation function.
137
+
138
+ Raises:
139
+ ValueError: If activation config is not supported.
140
+ """
141
+ if config.type == cfg.ActivationType.LINEAR:
142
+ return lambda x: x
143
+ elif config.type == cfg.ActivationType.SILU:
144
+ return F.silu
145
+ elif config.type == cfg.ActivationType.GELU:
146
+ return F.gelu
147
+ elif config.type == cfg.ActivationType.GELU_TANH:
148
+ return lambda x: F.gelu(x, approximate="tanh")
149
+ elif config.type == cfg.ActivationType.GELU_QUICK:
150
+ # GELU approximation that is fast but somewhat inaccurate.
151
+ # See: https://github.com/hendrycks/GELUs
152
+ return lambda x: x * F.sigmoid(1.702 * x)
153
+ elif config.type == cfg.ActivationType.GE_GLU:
154
+ return GeGLU(config.dim_in, config.dim_out)
155
+ elif config.type == cfg.ActivationType.RELU:
156
+ return F.relu
157
+ elif config.type == cfg.ActivationType.SILU_GLU:
158
+ return SwiGLU()
159
+ else:
160
+ raise ValueError("Unsupported activation type.")
@@ -0,0 +1,120 @@
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 building blocks for FeedForward layers.
16
+
17
+ from typing import Callable, Optional
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+
23
+ class SequentialFeedForward(nn.Module):
24
+ """Vanilla sequential Feedforward with customizable activation."""
25
+
26
+ def __init__(
27
+ self,
28
+ dim: int,
29
+ hidden_dim: int,
30
+ activation: Callable[[torch.Tensor], torch.Tensor],
31
+ use_bias=False,
32
+ use_glu=False,
33
+ pre_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
34
+ post_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
35
+ ):
36
+ """Init function for feedforward layer.
37
+
38
+ Args:
39
+ dim (int): embedding size.
40
+ hidden_dim (int): hidden dim size of the feedforward layer.
41
+ activation (Callable): activation function used in this block.
42
+ use_bias (Boolean): whether to use bias. Default is false.
43
+ use_glu (Boolean): whether to use glu in activation. Default is false.
44
+ pre_ff_norm (Callable): pre feedforward norm. Default is None.
45
+ post_ff_norm (Callable): post feedforward norm. Default is None.
46
+ """
47
+ super().__init__()
48
+ self.act = activation
49
+ if use_glu:
50
+ self.w1 = nn.Linear(dim, hidden_dim * 2, bias=use_bias)
51
+ else:
52
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
53
+ self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
54
+ self.pre_ff_norm = pre_ff_norm if pre_ff_norm else lambda x: x
55
+ self.post_ff_norm = post_ff_norm if post_ff_norm else lambda x: x
56
+
57
+ def forward(self, x):
58
+ """Forward pass for Feedforward layer.
59
+
60
+ Args:
61
+ x (torch.Tensor): the input tensor.
62
+
63
+ Returns:
64
+ torch.Tensor: output tensor after feedforward.
65
+ """
66
+ x_norm = self.pre_ff_norm(x)
67
+ out = self.w2(self.act(self.w1(x_norm)))
68
+ return self.post_ff_norm(out)
69
+
70
+
71
+ class GatedFeedForward(nn.Module):
72
+ """Gated Feedforward with customizable activation.
73
+
74
+ https://arxiv.org/pdf/2002.05202v1.pdf
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ dim: int,
80
+ hidden_dim: int,
81
+ activation: Callable[[torch.Tensor], torch.Tensor],
82
+ use_bias=False,
83
+ use_glu=False,
84
+ pre_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
85
+ post_ff_norm: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
86
+ ):
87
+ """Init function for feedforward layer.
88
+
89
+ Args:
90
+ dim (int): embedding size.
91
+ hidden_dim (int): hidden dim size of the feedforward layer.
92
+ activation (Callable): activation function used in this block.
93
+ use_bias (Boolean): whether to use bias. Default is false.
94
+ use_glu (Boolean): whether to use glu in activation. Default is false.
95
+ pre_ff_norm (Callable): pre feedforward norm. Default is None.
96
+ post_ff_norm (Callable): post feedforward norm. Default is None.
97
+ """
98
+ super().__init__()
99
+ self.act = activation
100
+ if use_glu:
101
+ self.w1 = nn.Linear(dim, hidden_dim * 2, bias=use_bias)
102
+ else:
103
+ self.w1 = nn.Linear(dim, hidden_dim, bias=use_bias)
104
+ self.w2 = nn.Linear(hidden_dim, dim, bias=use_bias)
105
+ self.w3 = nn.Linear(dim, hidden_dim, bias=use_bias)
106
+ self.pre_ff_norm = pre_ff_norm if pre_ff_norm else lambda x: x
107
+ self.post_ff_norm = post_ff_norm if post_ff_norm else lambda x: x
108
+
109
+ def forward(self, x):
110
+ """Forward pass for Feedforward layer.
111
+
112
+ Args:
113
+ x (torch.Tensor): the input tensor.
114
+
115
+ Returns:
116
+ torch.Tensor: output tensor after feedforward.
117
+ """
118
+ x_norm = self.pre_ff_norm(x)
119
+ out = self.w2(self.act(self.w1(x_norm)) * self.w3(x_norm))
120
+ return self.post_ff_norm(out)
@@ -0,0 +1,204 @@
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
+ """Utility functions for externalized KV Cache."""
17
+
18
+ import dataclasses
19
+ from typing import List, Tuple
20
+
21
+ from ai_edge_torch import hlfb
22
+ from ai_edge_torch.generative.layers import model_config
23
+ from ai_edge_torch.generative.utilities.dynamic_update_slice import dynamic_update_slice
24
+ import torch
25
+ import torch.utils._pytree as pytree
26
+
27
+ BATCH_SIZE = 1
28
+
29
+
30
+ @dataclasses.dataclass
31
+ class KVCacheEntry:
32
+ """A single cache entry that includes K and V caches.
33
+
34
+ The chaches are built based on the provided config with the shape of
35
+ (batch_size=1, kv_cache_max, num_query_groups, head_dim).
36
+ """
37
+
38
+ k_cache: torch.Tensor
39
+ v_cache: torch.Tensor
40
+
41
+ @classmethod
42
+ def from_model_config(
43
+ cls,
44
+ kv_cache_max: int,
45
+ config: model_config.AttentionConfig,
46
+ dtype: torch.dtype = torch.float32,
47
+ device: torch.device = None,
48
+ ) -> "KVCacheEntry":
49
+ """Build an instance of the class based on model config."""
50
+ shape = (BATCH_SIZE, kv_cache_max, config.num_query_groups, config.head_dim)
51
+ k = torch.zeros(shape, dtype=dtype, device=device)
52
+ v = torch.zeros(shape, dtype=dtype, device=device)
53
+ obj = cls(k_cache=k, v_cache=v)
54
+ return obj
55
+
56
+
57
+ @dataclasses.dataclass
58
+ class KVCache:
59
+ """A utility class for holding KV cache entries per layer."""
60
+
61
+ caches: Tuple[KVCacheEntry, ...]
62
+
63
+ @classmethod
64
+ def from_model_config(
65
+ cls,
66
+ config: model_config.ModelConfig,
67
+ dtype: torch.dtype = torch.float32,
68
+ device: torch.device = None,
69
+ ) -> "KVCache":
70
+ """Build an instance of the class based on model config.
71
+
72
+ Args:
73
+ config (ModelConfig): Model config used for building the cache.
74
+ dtype (torch.dtype, optional): The data type of the cache tensor.
75
+ Defaults to torch.float32.
76
+ device (torch.device, optional): The device placement of the cache
77
+ tensors. Defaults to None.
78
+
79
+ Returns:
80
+ KVCache: The created cache object.
81
+ """
82
+ caches = [
83
+ KVCacheEntry.from_model_config(
84
+ config.kv_cache_max,
85
+ config.block_config(idx).attn_config,
86
+ dtype,
87
+ device,
88
+ )
89
+ for idx in range(config.num_layers)
90
+ ]
91
+ obj = cls(caches=tuple(caches))
92
+ return obj
93
+
94
+ def flatten(self) -> List[torch.Tensor]:
95
+ """Flatten the cache entries into a list of tensors with order k_i, v_i."""
96
+ flattened, _ = _flatten_kvc(self)
97
+ return flattened
98
+
99
+
100
+ def _flatten_kvc(kvc: KVCache) -> Tuple[List[str], List[str]]:
101
+ flattened = []
102
+ flat_names = []
103
+ none_names = []
104
+ for i, kv_entry in enumerate(kvc.caches):
105
+ flattened.append(kv_entry.k_cache)
106
+ flat_names.append(f"k_{i}")
107
+ flattened.append(kv_entry.v_cache)
108
+ flat_names.append(f"v_{i}")
109
+ return flattened, [flat_names, none_names]
110
+
111
+
112
+ def _flatten_kvc_with_keys(kvc: KVCache) -> Tuple[List, List]:
113
+ flattened, (flat_names, none_names) = _flatten_kvc(kvc)
114
+ return [
115
+ (pytree.MappingKey(k), v) for k, v in zip(flat_names, flattened)
116
+ ], flat_names
117
+
118
+
119
+ def _unflatten_kvc(
120
+ values: List[torch.Tensor], context: Tuple[List, List]
121
+ ) -> KVCache:
122
+ assert len(values) % 2 == 0, "Found odd number of K and V entries."
123
+ num_layers = len(values) // 2
124
+ flat_names = context[0]
125
+ kv_entries = []
126
+ for i in range(num_layers):
127
+ k_cache_idx = flat_names.index(f"k_{i}")
128
+ v_cache_idx = flat_names.index(f"v_{i}")
129
+ kv_entries.append(
130
+ KVCacheEntry(k_cache=values[k_cache_idx], v_cache=values[v_cache_idx])
131
+ )
132
+ obj = KVCache(tuple(kv_entries))
133
+ return obj
134
+
135
+
136
+ pytree.register_pytree_node(
137
+ KVCache,
138
+ _flatten_kvc,
139
+ _unflatten_kvc,
140
+ flatten_with_keys_fn=_flatten_kvc_with_keys,
141
+ serialized_type_name="",
142
+ )
143
+
144
+
145
+ def update(
146
+ cache: KVCacheEntry,
147
+ input_pos: torch.Tensor,
148
+ k_slice: torch.Tensor,
149
+ v_slice: torch.Tensor,
150
+ use_dus: bool = True,
151
+ ) -> KVCacheEntry:
152
+ """Out of place update of Cache buffer.
153
+
154
+ Args:
155
+ cache (KVCacheEntry): The original cache buffer.
156
+ input_pos (torch.Tensor): The update slice positions.
157
+ k_slice (torch.Tensor): The K slice to be updated in the new cache.
158
+ v_slice (torch.Tensor): The V slice to be updated in the new cache.
159
+
160
+ Returns:
161
+ KVCacheEntry: The updated KVCache entry based on the passed inputs.
162
+ """
163
+ update_kv_cache = _update_kv_impl if use_dus else _update_kv_base_impl
164
+ return update_kv_cache(cache, input_pos, k_slice, v_slice)
165
+
166
+
167
+ def _update_kv_base_impl(
168
+ cache: KVCacheEntry,
169
+ input_pos: torch.Tensor,
170
+ k_slice: torch.Tensor,
171
+ v_slice: torch.Tensor,
172
+ ) -> KVCacheEntry:
173
+ """Update the cache buffer without High Level Function Boundary annotation."""
174
+ k = cache.k_cache.index_copy(1, input_pos.to(torch.long), k_slice)
175
+ v = cache.v_cache.index_copy(1, input_pos.to(torch.long), v_slice)
176
+ updated_cache = KVCacheEntry(k, v)
177
+ return updated_cache
178
+
179
+
180
+ def _get_slice_indices(positions: torch.Tensor) -> torch.Tensor:
181
+ """Dynamic Update Slice updates are a variadic sequence of 0-rank tensors."""
182
+
183
+ zero = torch.zeros([]).int()
184
+ positions = positions.int()[0].reshape([])
185
+ return [zero, positions, zero, zero]
186
+
187
+
188
+ def _update_kv_impl(
189
+ cache: KVCacheEntry,
190
+ input_pos: torch.Tensor,
191
+ k_slice: torch.Tensor,
192
+ v_slice: torch.Tensor,
193
+ ) -> KVCacheEntry:
194
+ """Update the cache buffer for K and V caches."""
195
+ # NB: Here assume that input_pos == range(input_pos[0], len(input_pos))
196
+
197
+ k_slice_indices = _get_slice_indices(input_pos)
198
+ v_slice_indices = _get_slice_indices(input_pos)
199
+
200
+ k = dynamic_update_slice(cache.k_cache, k_slice, k_slice_indices)
201
+ v = dynamic_update_slice(cache.v_cache, v_slice, v_slice_indices)
202
+
203
+ updated_cache = KVCacheEntry(k, v)
204
+ return updated_cache