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,238 @@
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
+ """Model configuration class."""
17
+
18
+ import dataclasses
19
+ import enum
20
+ from typing import Callable, Optional, Sequence, Union
21
+ from ai_edge_torch.generative.layers import rotary_position_embedding
22
+
23
+ @enum.unique
24
+ class ActivationType(enum.Enum):
25
+ """Different activation functions supported by the default builder."""
26
+
27
+ LINEAR = enum.auto()
28
+ SILU = enum.auto()
29
+ GELU = enum.auto()
30
+ GELU_TANH = enum.auto()
31
+ GELU_QUICK = enum.auto()
32
+ GE_GLU = enum.auto()
33
+ RELU = enum.auto()
34
+ SILU_GLU = enum.auto()
35
+
36
+
37
+ @enum.unique
38
+ class NormalizationType(enum.Enum):
39
+ """Different normalization functions."""
40
+
41
+ # No normalization is applied.
42
+ NONE = enum.auto()
43
+ RMS_NORM = enum.auto()
44
+ LAYER_NORM = enum.auto()
45
+ GROUP_NORM = enum.auto()
46
+
47
+
48
+ @enum.unique
49
+ class FeedForwardType(enum.Enum):
50
+ """Different variations of the Feed Forward module."""
51
+
52
+ # `output = linear(act(linear(x)))`.
53
+ SEQUENTIAL = enum.auto()
54
+ # `output = linear_2(act(linear_1(x)) * lienar_3(x))`.
55
+ GATED = enum.auto()
56
+
57
+
58
+ class AttentionType(enum.Enum):
59
+ GLOBAL = enum.auto()
60
+ LOCAL_SLIDING = enum.auto()
61
+
62
+
63
+ @dataclasses.dataclass
64
+ class NormalizationConfig:
65
+ """Normalizater parameters."""
66
+
67
+ type: NormalizationType = NormalizationType.NONE
68
+ enable_hlfb: bool = False
69
+ epsilon: float = 1e-5
70
+ zero_centered: bool = False
71
+ # Number of groups used in group normalization.
72
+ group_num: Optional[float] = None
73
+
74
+
75
+ @dataclasses.dataclass
76
+ class AttentionConfig:
77
+ """Attention model's parameters."""
78
+
79
+ num_heads: int
80
+ head_dim: int
81
+ # Used to determine number of groups in grouped query attention (GQA)
82
+ # https://arxiv.org/pdf/2305.13245.pdf
83
+ num_query_groups: Optional[int]
84
+ # Base of rotary positional embedding.
85
+ rotary_base: int = 10_000
86
+ # Percentage of Rotary Positional Embedding added Q and K projections.
87
+ rotary_percentage: Optional[float] = None
88
+ # Whether to transpose the query groups of qkv bundled tensor before
89
+ # splitting into separated tensors.
90
+ qkv_transpose_before_split: bool = False
91
+ # Whether to use bias with Query, Key, and Value projection.
92
+ qkv_use_bias: bool = False
93
+ # Whether the fused q, k, v projection weights interleaves q, k, v heads.
94
+ # If True, the projection weights are in format:
95
+ # `[q_head_0, k_head_0, v_head_0, q_head_1, k_head_1, v_head_1, ...]`
96
+ # If False, the projection weights are in format:
97
+ # `[q_head_0, q_head_1, ..., k_head_0, k_head_1, ... v_head_0, v_head_1, ...]`
98
+ qkv_fused_interleaved: bool = True
99
+ # Whether to use bias with attention output projection.
100
+ output_proj_use_bias: bool = False
101
+ enable_kv_cache: bool = True
102
+ # The normalization applied to query projection's output.
103
+ query_norm_config: NormalizationConfig = dataclasses.field(
104
+ default_factory=NormalizationConfig
105
+ )
106
+ # The normalization applied to key projection's output.
107
+ key_norm_config: NormalizationConfig = dataclasses.field(
108
+ default_factory=NormalizationConfig
109
+ )
110
+ relative_attention_num_buckets: int = 0
111
+ relative_attention_max_distance: int = 0
112
+ # Softcap on the output logits.
113
+ logit_softcap: Optional[float] = None
114
+ # The type of attention.
115
+ attn_type: Optional[AttentionType] = None
116
+ # The size of the sliding window used for local attention.
117
+ sliding_window_size: Optional[int] = None
118
+
119
+
120
+ @dataclasses.dataclass
121
+ class ActivationConfig:
122
+ type: ActivationType = ActivationType.LINEAR
123
+ # Dimension of input and output, used in GeGLU.
124
+ dim_in: Optional[int] = None
125
+ dim_out: Optional[int] = None
126
+
127
+
128
+ @dataclasses.dataclass
129
+ class FeedForwardConfig:
130
+ """FeedForward module's parameters."""
131
+
132
+ type: FeedForwardType
133
+ activation: ActivationConfig
134
+ intermediate_size: int
135
+ use_bias: bool = False
136
+ # The normalization applied to feed forward's input.
137
+ pre_ff_norm_config: NormalizationConfig = dataclasses.field(
138
+ default_factory=NormalizationConfig
139
+ )
140
+ # The normalization applied to feed forward's output.
141
+ post_ff_norm_config: NormalizationConfig = dataclasses.field(
142
+ default_factory=NormalizationConfig
143
+ )
144
+
145
+
146
+ @dataclasses.dataclass
147
+ class TransformerBlockConfig:
148
+ """TransformerBlock module's parameters."""
149
+
150
+ attn_config: AttentionConfig
151
+ ff_config: FeedForwardConfig
152
+ # The normalization applied to attention's input.
153
+ pre_attention_norm_config: NormalizationConfig = dataclasses.field(
154
+ default_factory=NormalizationConfig
155
+ )
156
+ # The normalization applied to attentions's output.
157
+ post_attention_norm_config: NormalizationConfig = dataclasses.field(
158
+ default_factory=NormalizationConfig
159
+ )
160
+ # If set to True, only attn_config.pre_attention_norm is applied to the input
161
+ # and the decode's output is computed as `output = input + attn_out + ff_out`
162
+ # where attention and feed forward are called with pre_attention_norm's
163
+ # output.
164
+ parallel_residual: bool = False
165
+ # The Attention computation will include relative positional bias.
166
+ relative_attention: bool = False
167
+
168
+
169
+ @dataclasses.dataclass
170
+ class ImageEmbeddingConfig:
171
+ """Image embedding parameters."""
172
+
173
+ channels: int
174
+ # All images should be normalized to the size of [image_size * image_size].
175
+ image_size: int
176
+ patch_size: int
177
+
178
+
179
+ @dataclasses.dataclass
180
+ class ModelConfig:
181
+ """Base configurations for building a transformer architecture."""
182
+
183
+ vocab_size: int
184
+ num_layers: int
185
+ max_seq_len: int
186
+ embedding_dim: int
187
+
188
+ # TransformerBlockConfig for each layer block. If a single
189
+ # TransformerBlockConfig is provided, it will be used for all layers.
190
+ block_configs: Union[TransformerBlockConfig, Sequence[TransformerBlockConfig]]
191
+
192
+ # The normalization applied before LM head.
193
+ final_norm_config: NormalizationConfig = dataclasses.field(
194
+ default_factory=NormalizationConfig
195
+ )
196
+
197
+ # Scale factor of the embedding.
198
+ embedding_scale: Optional[float] = None
199
+ # Use bias term within embedding.
200
+ embedding_use_bias: bool = False
201
+ # Image embedding parameters.
202
+ image_embedding: Optional[ImageEmbeddingConfig] = None
203
+
204
+ # Use bias term within LLM's HEAD.
205
+ lm_head_use_bias: bool = False
206
+ # Whether LLM's HEAD shares the weight of the embedding.
207
+ lm_head_share_weight_with_embedding: bool = True
208
+
209
+ # Whether to turn on high-level function boundary.
210
+ enable_hlfb: bool = False
211
+
212
+ # The maximum sequence length of the KV cache. Should not exceed max_seq_len.
213
+ kv_cache_max_len: int = 0
214
+
215
+ # Default batch size of the exported model. Default value is 1.
216
+ batch_size: int = 1
217
+
218
+ # Softcap on the model output logits.
219
+ final_logit_softcap: Optional[float] = None
220
+
221
+ # The function to call to create the RoPE sin and cos vectors during the
222
+ # forward pass. Defaults to a standard implementation.
223
+ build_rope: Callable = rotary_position_embedding.build_rope
224
+
225
+ @property
226
+ def kv_cache_max(self) -> int:
227
+ if self.kv_cache_max_len > 0:
228
+ return self.kv_cache_max_len
229
+ return self.max_seq_len
230
+
231
+ def block_config(self, idx: int) -> TransformerBlockConfig:
232
+ if isinstance(self.block_configs, TransformerBlockConfig):
233
+ return self.block_configs
234
+ if idx < 0 or idx >= len(self.block_configs):
235
+ raise ValueError(
236
+ f"Index {idx} is out of range for layer configs: {self.block_configs}"
237
+ )
238
+ return self.block_configs[idx]
@@ -0,0 +1,222 @@
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 normalization layers.
16
+
17
+ from ai_edge_torch.hlfb import StableHLOCompositeBuilder
18
+ import torch
19
+ from torch import nn
20
+ import torch.nn.functional as F
21
+
22
+
23
+ # Implementation for RMSNorm from: https://arxiv.org/abs/1910.07467
24
+ class RMSNorm(torch.nn.Module):
25
+
26
+ def __init__(
27
+ self,
28
+ dim: int,
29
+ eps: float = 1e-6,
30
+ zero_centered_gamma=False,
31
+ enable_hlfb: bool = False,
32
+ ):
33
+ """Initialize the RMSNorm layer.
34
+
35
+ Args:
36
+ dim (int): dimension of the input tensor.
37
+ eps (float): A small float value to ensure numerical stability (default:
38
+ 1e-6).
39
+ zero_centered_gamma (bool): Whether or not gamma has an offset.
40
+ enable_hlfb (bool): use HLFB in the op.
41
+ """
42
+ super().__init__()
43
+ self.enable_hlfb = enable_hlfb
44
+ self.eps = eps
45
+ self.weight = torch.nn.Parameter(torch.ones(dim))
46
+ self.zero_centered_gamma = zero_centered_gamma
47
+
48
+ def _norm(self, x):
49
+ """Apply RMSNorm normalization.
50
+
51
+ Args:
52
+ x (torch.Tensor): input tensor.
53
+
54
+ Returns:
55
+ torch.Tensor: The normalized output tensor.
56
+ """
57
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
58
+
59
+ def forward(self, x):
60
+ """Running the forward pass of RMSNorm layer.
61
+
62
+ Args:
63
+ x (torch.Tensor): input tensor.
64
+
65
+ Returns:
66
+ torch.Tensor: output tensor after applying RMSNorm.
67
+ """
68
+ if self.zero_centered_gamma:
69
+ w = 1 + self.weight
70
+ else:
71
+ w = self.weight
72
+
73
+ if self.enable_hlfb:
74
+ return rms_norm_with_hlfb(
75
+ x,
76
+ w,
77
+ self.eps,
78
+ )
79
+ else:
80
+ output = self._norm(x.float()).type_as(x)
81
+ return output * w
82
+
83
+
84
+ class GroupNorm(torch.nn.Module):
85
+
86
+ def __init__(
87
+ self,
88
+ group_num: int,
89
+ dim: int,
90
+ eps: float = 1e-5,
91
+ enable_hlfb: bool = False,
92
+ ):
93
+ """Initialize the GroupNorm layer.
94
+
95
+ Args:
96
+ group_num (int): Number of groups to separate the channels into.
97
+ dim (int): Dimension of the input tensor.
98
+ eps (float): A small float value to ensure numerical stability (default:
99
+ 1e-5).
100
+ enable_hlfb (bool): Whether to convert this normalization into a single
101
+ op.
102
+ """
103
+ super().__init__()
104
+ self.enable_hlfb = enable_hlfb
105
+ self.group_num = group_num
106
+ self.eps = eps
107
+ self.weight = torch.nn.Parameter(torch.empty(dim))
108
+ self.bias = torch.nn.Parameter(torch.empty(dim))
109
+
110
+ def forward(self, x):
111
+ """Running the forward pass of GroupNorm layer.
112
+
113
+ Args:
114
+ x (torch.Tensor): input tensor.
115
+
116
+ Returns:
117
+ torch.Tensor: output tensor after applying GroupNorm.
118
+ """
119
+ return F.group_norm(x, self.group_num, self.weight, self.bias, self.eps)
120
+
121
+
122
+ class LayerNorm(torch.nn.Module):
123
+
124
+ def __init__(
125
+ self,
126
+ dim: int,
127
+ eps: float = 1e-5,
128
+ enable_hlfb: bool = False,
129
+ ):
130
+ """Initialize the LayerNorm layer.
131
+
132
+ Args:
133
+ dim (int): dimension of the input tensor.
134
+ eps (float): A small float value to ensure numerical stability (default:
135
+ 1e-5).
136
+ enable_hlfb (bool): Whether to convert this normalization into a single
137
+ op.
138
+ """
139
+ super().__init__()
140
+ self.enable_hlfb = enable_hlfb
141
+ self.normalized_shape = (dim,)
142
+ self.eps = eps
143
+ self.weight = torch.nn.Parameter(torch.empty(dim))
144
+ self.bias = torch.nn.Parameter(torch.empty(dim))
145
+
146
+ def forward(self, x):
147
+ """Running the forward pass of LayerNorm layer.
148
+
149
+ Args:
150
+ x (torch.Tensor): input tensor.
151
+
152
+ Returns:
153
+ torch.Tensor: output tensor after applying LayerNorm.
154
+ """
155
+ if self.enable_hlfb:
156
+ return layer_norm_with_hlfb(
157
+ x, self.normalized_shape, self.weight, self.bias, self.eps
158
+ )
159
+ return F.layer_norm(
160
+ x, self.normalized_shape, self.weight, self.bias, self.eps
161
+ )
162
+
163
+
164
+ def rms_norm_with_hlfb(
165
+ x: torch.Tensor,
166
+ w: torch.Tensor,
167
+ eps: float,
168
+ ):
169
+ """RMS Normalization with high-level function boundary enabled.
170
+
171
+ Args:
172
+ x (torch.Tensor): Input tensor for RMS Normalization, with BCHW shape.
173
+ w (torch.Tensor): The learned parameter tensor for normalization.
174
+ eps (float): A small float value to ensure numerical stability.
175
+
176
+ Returns:
177
+ The output tensor of RMS Normalization.
178
+ """
179
+ builder = StableHLOCompositeBuilder(
180
+ name="odml.rms_norm", attr={"epsilon": eps}
181
+ )
182
+
183
+ x, w = builder.mark_inputs(x, w)
184
+
185
+ def _norm(x):
186
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
187
+
188
+ output = _norm(x.float()).type_as(x)
189
+ out = output * w
190
+
191
+ out = builder.mark_outputs(out)
192
+ return out
193
+
194
+
195
+ def layer_norm_with_hlfb(
196
+ x: torch.Tensor,
197
+ normalized_shape: list[int],
198
+ w: torch.Tensor,
199
+ b: torch.Tensor,
200
+ eps: float,
201
+ ):
202
+ """Layer Normalization with high-level function boundary enabled.
203
+
204
+ Args:
205
+ x (torch.Tensor): Input tensor for Layer Normalization, with BCHW shape.
206
+ normalized_shape (list[int]): Input shape from an expected input of size,
207
+ same as https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html.
208
+ w (torch.Tensor): The weight tensor for the normalization.
209
+ b (torch.Tensor): The bias tensor for the normalization.
210
+ eps (float): A small float value to ensure numerical stability.
211
+
212
+ Returns:
213
+ The output tensor of Layer Normalization.
214
+ """
215
+ builder = StableHLOCompositeBuilder(
216
+ name="odml.group_norm",
217
+ attr={"num_groups": 1, "epsilon": eps, "channel_axis": 1},
218
+ )
219
+ x, w, b = builder.mark_inputs(x, w, b)
220
+ y = F.layer_norm(x, normalized_shape, w, b, eps=eps)
221
+ y = builder.mark_outputs(y)
222
+ return y
@@ -0,0 +1,94 @@
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
+ # Implementation for Rotary Position embedding. https://arxiv.org/pdf/2104.09864.pdf
16
+
17
+ from typing import Tuple
18
+ import torch
19
+
20
+
21
+ def apply_rope(
22
+ x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
23
+ ) -> torch.Tensor:
24
+ """Computes rotary positional embedding.
25
+
26
+ Args:
27
+ x: the input tensor.
28
+ cos: cosine value for the rope.
29
+ sin: sin value for the rope.
30
+
31
+ Returns:
32
+ output tensor of RoPE.
33
+ """
34
+ x = x.transpose(1, 2)
35
+ rope_size = cos.size(-1)
36
+ x_splited = torch.split(x, rope_size, dim=-1)
37
+ left = x_splited[0] * cos - x_splited[1] * sin
38
+ right = x_splited[1] * cos + x_splited[0] * sin
39
+ roped = torch.cat((left, right) + x_splited[2:], dim=-1)
40
+ return roped.transpose(1, 2).type_as(x)
41
+
42
+
43
+ def build_rope(
44
+ input_pos: torch.Tensor,
45
+ n_elem: int,
46
+ base: int = 10_000,
47
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
48
+ """Computes rotary positional embedding cosine and sine tensors.
49
+
50
+ Args:
51
+ input_pos: the sequence indices for the query and key
52
+ n_elem: number of elements of the head dimension for RoPE computation
53
+ base: the base of the exponentiated value for RoPE.
54
+
55
+ Returns:
56
+ cos, sin tensors
57
+ """
58
+
59
+ if n_elem <= 0:
60
+ return None, None
61
+
62
+ freq_exponents = (2.0 / n_elem) * torch.arange(
63
+ n_elem // 2, dtype=torch.float32
64
+ )
65
+ timescale = float(base) ** freq_exponents
66
+ radians = input_pos.clone().unsqueeze(0).unsqueeze(-1) / timescale.unsqueeze(
67
+ 0
68
+ ).unsqueeze(0)
69
+ cos = torch.cos(radians)
70
+ sin = torch.sin(radians)
71
+ return cos, sin
72
+
73
+
74
+ def apply_rope_inline(
75
+ q: torch.Tensor,
76
+ k: torch.Tensor,
77
+ cos: torch.Tensor,
78
+ sin: torch.Tensor,
79
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
80
+ """Computes rotary positional embedding inline for a query and key.
81
+
82
+ Args:
83
+ q: the query tensor.
84
+ k: the key tensor.
85
+ cos: the cosine tensor.
86
+ sin: the sine tensor.
87
+
88
+ Returns:
89
+ output the RoPE'd query and key.
90
+ """
91
+
92
+ q_roped = apply_rope(q, cos, sin)
93
+ k_roped = apply_rope(k, cos, sin)
94
+ return q_roped, k_roped
@@ -0,0 +1,144 @@
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
+ # Implements scaled dot product attention.
16
+
17
+ import math
18
+ from typing import Optional
19
+
20
+ from ai_edge_torch.hlfb import StableHLOCompositeBuilder
21
+ import torch
22
+ import torch.nn.functional as F
23
+
24
+
25
+ def scaled_dot_product_attention(
26
+ q: torch.Tensor,
27
+ k: torch.Tensor,
28
+ v: torch.Tensor,
29
+ head_size: int,
30
+ mask: Optional[torch.Tensor] = None,
31
+ scale: Optional[float] = None,
32
+ softcap: Optional[float] = None,
33
+ ):
34
+ """Scaled dot product attention.
35
+
36
+ Args:
37
+ q (torch.Tensor): Query tensor, with shape [B, T, N, H].
38
+ k (torch.Tensor): Key tensor, with shape [B, T, KV_LEN, H].
39
+ v (torch.Tensor): Value tensor, with shape [B, T, KV_LEN, H].
40
+ head_size (int): head dimension.
41
+ mask (torch.Tensor): the optional mask tensor.
42
+
43
+ Returns:
44
+ The output tensor of scaled_dot_product_attention.
45
+ """
46
+
47
+ if scale is None:
48
+ scale = 1.0 / math.sqrt(head_size)
49
+
50
+ q = q.transpose(1, 2)
51
+ k = k.transpose(1, 2)
52
+ v = v.transpose(1, 2)
53
+ if q.size() != k.size():
54
+ # Handle the GQA case, where q.shape[1] % k.shape[1] == 0.
55
+ k = k.repeat_interleave(q.shape[1] // k.shape[1], dim=1)
56
+ v = v.repeat_interleave(q.shape[1] // v.shape[1], dim=1)
57
+ if softcap is None:
58
+ y = F.scaled_dot_product_attention(
59
+ q,
60
+ k,
61
+ v,
62
+ attn_mask=mask,
63
+ dropout_p=0.0,
64
+ is_causal=mask is None,
65
+ scale=scale,
66
+ )
67
+ else:
68
+ q.mul_(scale)
69
+ scores = q @ k.transpose(-1, -2)
70
+ scores = scores / softcap
71
+ scores = torch.tanh(scores)
72
+ scores = scores * softcap
73
+ scores = scores + mask
74
+ out = F.softmax(scores.float(), dim=-1).type_as(q)
75
+ y = torch.matmul(out, v)
76
+
77
+ return y.transpose(1, 2)
78
+
79
+
80
+ def scaled_dot_product_attention_with_hlfb(
81
+ q: torch.Tensor,
82
+ k: torch.Tensor,
83
+ v: torch.Tensor,
84
+ head_size: int,
85
+ mask: Optional[torch.Tensor] = None,
86
+ scale: Optional[float] = None,
87
+ softcap: Optional[float] = None,
88
+ ):
89
+ """Scaled dot product attention with high-level function boundary enabled.
90
+
91
+ Args:
92
+ q (torch.Tensor): Query tensor, with shape [B, T, N, H].
93
+ k (torch.Tensor): Key tensor, with shape [B, T, KV_LEN, H].
94
+ v (torch.Tensor): Value tensor, with shape [B, T, KV_LEN, H].
95
+ head_size (int): head dimension.
96
+ mask (torch.Tensor): the optional mask tensor.
97
+
98
+ Returns:
99
+ The output tensor of scaled_dot_product_attention.
100
+ """
101
+
102
+ if scale is None:
103
+ scale = 1.0 / math.sqrt(head_size)
104
+
105
+ attrs = {"scale": scale}
106
+
107
+ if softcap is not None:
108
+ attrs["logit_cap"] = softcap
109
+
110
+ builder = StableHLOCompositeBuilder(
111
+ name="odml.scaled_dot_product_attention", attr=attrs
112
+ )
113
+ q, k, v, mask = builder.mark_inputs(q, k, v, mask)
114
+
115
+ q = q.transpose(1, 2)
116
+ k = k.transpose(1, 2)
117
+ v = v.transpose(1, 2)
118
+ if q.size() != k.size():
119
+ # Handle the GQA case, where q.shape[1] % k.shape[1] == 0.
120
+ k = k.repeat_interleave(q.shape[1] // k.shape[1], dim=1)
121
+ v = v.repeat_interleave(q.shape[1] // v.shape[1], dim=1)
122
+ if softcap is None:
123
+ y = F.scaled_dot_product_attention(
124
+ q,
125
+ k,
126
+ v,
127
+ attn_mask=mask,
128
+ dropout_p=0.0,
129
+ is_causal=mask is None,
130
+ scale=scale,
131
+ )
132
+ else:
133
+ q.mul_(scale)
134
+ scores = q @ k.transpose(-1, -2)
135
+ scores = scores / softcap
136
+ scores = torch.tanh(scores)
137
+ scores = scores * softcap
138
+ scores = scores + mask
139
+ out = F.softmax(scores.float(), dim=-1).type_as(q)
140
+ y = torch.matmul(out, v)
141
+
142
+ result = y.transpose(1, 2)
143
+ result = builder.mark_outputs(result)
144
+ return result
@@ -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
+ # ==============================================================================