ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl → 0.3.0.dev20240926__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (169) hide show
  1. ai_edge_torch/__init__.py +5 -4
  2. ai_edge_torch/_convert/conversion.py +112 -0
  3. ai_edge_torch/_convert/conversion_utils.py +64 -0
  4. ai_edge_torch/{convert → _convert}/converter.py +94 -48
  5. ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
  6. ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
  7. ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
  8. ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
  9. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
  10. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
  11. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
  12. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
  13. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
  14. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
  15. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
  16. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
  17. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
  18. ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
  19. ai_edge_torch/_convert/signature.py +66 -0
  20. ai_edge_torch/_convert/test/test_convert.py +495 -0
  21. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  22. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  23. ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
  24. ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
  25. ai_edge_torch/config.py +27 -0
  26. ai_edge_torch/conftest.py +20 -0
  27. ai_edge_torch/debug/culprit.py +72 -40
  28. ai_edge_torch/debug/test/test_culprit.py +7 -5
  29. ai_edge_torch/debug/test/test_search_model.py +8 -7
  30. ai_edge_torch/debug/utils.py +14 -3
  31. ai_edge_torch/fx_pass_base.py +101 -0
  32. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
  33. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
  34. ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
  35. ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
  36. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  37. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
  38. ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
  39. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
  40. ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
  41. ai_edge_torch/generative/examples/openelm/verify.py +64 -0
  42. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  43. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
  44. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
  45. ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
  46. ai_edge_torch/generative/examples/phi/phi3.py +286 -0
  47. ai_edge_torch/generative/examples/phi/verify.py +65 -0
  48. ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
  49. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  50. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
  51. ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
  52. ai_edge_torch/generative/examples/smollm/verify.py +62 -0
  53. ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
  54. ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
  55. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
  56. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
  57. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
  58. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
  59. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
  60. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
  61. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
  62. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
  63. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
  64. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
  65. ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
  66. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
  67. ai_edge_torch/generative/examples/t5/t5.py +208 -159
  68. ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
  69. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  70. ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
  71. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
  72. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  73. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
  74. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
  75. ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
  76. ai_edge_torch/generative/fx_passes/__init__.py +4 -5
  77. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
  78. ai_edge_torch/generative/layers/attention.py +141 -102
  79. ai_edge_torch/generative/layers/attention_utils.py +53 -12
  80. ai_edge_torch/generative/layers/builder.py +37 -7
  81. ai_edge_torch/generative/layers/feed_forward.py +39 -14
  82. ai_edge_torch/generative/layers/kv_cache.py +162 -50
  83. ai_edge_torch/generative/layers/model_config.py +84 -30
  84. ai_edge_torch/generative/layers/normalization.py +185 -7
  85. ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
  86. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
  87. ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
  88. ai_edge_torch/generative/layers/unet/builder.py +7 -4
  89. ai_edge_torch/generative/layers/unet/model_config.py +17 -15
  90. ai_edge_torch/generative/quantize/example.py +7 -8
  91. ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
  92. ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
  93. ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
  94. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  95. ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
  96. ai_edge_torch/generative/test/test_model_conversion.py +124 -188
  97. ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
  98. ai_edge_torch/generative/test/test_quantize.py +76 -60
  99. ai_edge_torch/generative/test/utils.py +54 -0
  100. ai_edge_torch/generative/utilities/converter.py +82 -0
  101. ai_edge_torch/generative/utilities/loader.py +120 -57
  102. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
  103. ai_edge_torch/generative/utilities/t5_loader.py +110 -81
  104. ai_edge_torch/generative/utilities/verifier.py +247 -0
  105. ai_edge_torch/hlfb/__init__.py +1 -1
  106. ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
  107. ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
  108. ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
  109. ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
  110. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
  111. ai_edge_torch/lowertools/__init__.py +18 -0
  112. ai_edge_torch/lowertools/_shim.py +80 -0
  113. ai_edge_torch/lowertools/common_utils.py +142 -0
  114. ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
  115. ai_edge_torch/lowertools/test_utils.py +60 -0
  116. ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
  117. ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
  118. ai_edge_torch/model.py +53 -18
  119. ai_edge_torch/odml_torch/__init__.py +20 -0
  120. ai_edge_torch/odml_torch/_torch_future.py +61 -0
  121. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  122. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  123. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  124. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  125. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  126. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  127. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  128. ai_edge_torch/odml_torch/export.py +357 -0
  129. ai_edge_torch/odml_torch/export_utils.py +168 -0
  130. ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
  131. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
  132. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  133. ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
  134. ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
  135. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  136. ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
  137. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
  138. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
  139. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  140. ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
  141. ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
  142. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  143. ai_edge_torch/odml_torch/tf_integration.py +194 -0
  144. ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
  145. ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
  146. ai_edge_torch/quantize/quant_config.py +13 -9
  147. ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
  148. ai_edge_torch/version.py +16 -0
  149. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
  150. ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
  151. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
  152. ai_edge_torch/convert/conversion.py +0 -117
  153. ai_edge_torch/convert/conversion_utils.py +0 -400
  154. ai_edge_torch/convert/fx_passes/__init__.py +0 -59
  155. ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
  156. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
  157. ai_edge_torch/convert/test/test_convert.py +0 -311
  158. ai_edge_torch/convert/test/test_convert_composites.py +0 -192
  159. ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
  160. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
  161. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
  162. ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
  163. ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
  164. ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
  165. /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
  166. /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
  167. /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
  168. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
  169. {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/top_level.txt +0 -0
@@ -12,20 +12,18 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- # Common building blocks for Attention layer.
16
15
 
17
- from typing import Optional, Tuple
16
+ """Common building blocks for Attention layer."""
18
17
 
19
- import torch
20
- from torch import nn
21
- import torch.nn.functional as F
18
+ from typing import Optional, Tuple, Union
22
19
 
23
- import ai_edge_torch.generative.layers.builder as builder
24
- from ai_edge_torch.generative.layers.kv_cache import KVCache
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 scaled_dot_product_attention as sdpa
25
23
  import ai_edge_torch.generative.layers.model_config as cfg
26
24
  import ai_edge_torch.generative.layers.rotary_position_embedding as rotary_pos_emb
27
- from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention # NOQA
28
- from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention_with_hlfb # NOQA
25
+ import torch
26
+ from torch import nn
29
27
 
30
28
 
31
29
  def _embed_rope(
@@ -57,29 +55,35 @@ def _embed_rope(
57
55
 
58
56
  class TransformerBlock(nn.Module):
59
57
 
60
- def __init__(self, config: cfg.ModelConfig) -> None:
58
+ def __init__(
59
+ self,
60
+ config: cfg.TransformerBlockConfig,
61
+ model_config: cfg.ModelConfig,
62
+ ) -> None:
61
63
  """Initialize an instance of the TransformerBlock.
62
64
 
63
65
  Args:
64
- config (cfg.ModelConfig): the configuration object
65
- for this transformer block.
66
+ config (cfg.TransformerBlockConfig): the configuration object for this
67
+ transformer block.
68
+ model_config (cfg.ModelConfig): the configuration object for the model
69
+ this transformer block belongs to.
66
70
  """
67
-
68
71
  super().__init__()
69
72
  self.pre_atten_norm = builder.build_norm(
70
- config.embedding_dim, config.pre_attention_norm_config
73
+ model_config.embedding_dim,
74
+ config.pre_attention_norm_config,
71
75
  )
72
76
  self.atten_func = CausalSelfAttention(
73
- config.batch_size,
74
- config.embedding_dim,
77
+ model_config.batch_size,
78
+ model_config.embedding_dim,
75
79
  config.attn_config,
76
- config.kv_cache_max,
77
- config.enable_hlfb,
80
+ model_config.enable_hlfb,
78
81
  )
79
- self.pre_ff_norm = builder.build_norm(
80
- config.embedding_dim, config.pre_ff_norm_config
82
+ self.post_atten_norm = builder.build_norm(
83
+ model_config.embedding_dim,
84
+ config.post_attention_norm_config,
81
85
  )
82
- self.ff = builder.build_ff(config.embedding_dim, config.ff_config)
86
+ self.ff = builder.build_ff(model_config.embedding_dim, config.ff_config)
83
87
  self.config = config
84
88
 
85
89
  def forward(
@@ -88,7 +92,8 @@ class TransformerBlock(nn.Module):
88
92
  rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
89
93
  mask: Optional[torch.Tensor] = None,
90
94
  input_pos: Optional[torch.Tensor] = None,
91
- ) -> torch.Tensor:
95
+ kv_cache: kv_utils.KVCacheEntry = None,
96
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
92
97
  """Forward function of the TransformerBlock.
93
98
 
94
99
  Args:
@@ -96,24 +101,34 @@ class TransformerBlock(nn.Module):
96
101
  rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
97
102
  mask (torch.Tensor): the optional mask tensor.
98
103
  input_pos (torch.Tensor): the optional input position tensor.
104
+ kv_cache (KVCacheEntry): the optional kv cache entry.
99
105
 
100
106
  Returns:
101
- output activation from this transformer block.
107
+ output activation from this transformer block, and updated kv cache (if
108
+ passed in).
102
109
  """
103
-
110
+ kv = None
104
111
  if self.config.parallel_residual:
105
112
  x_norm = self.pre_atten_norm(x)
106
- attn_out = self.atten_func(x_norm, rope, mask, input_pos)
113
+ atten_func_out = self.atten_func(x_norm, rope, mask, input_pos, kv_cache)
114
+ if kv_cache is None:
115
+ attn_out = atten_func_out
116
+ else:
117
+ attn_out, kv = atten_func_out
107
118
  ff_out = self.ff(x_norm)
108
119
  output = x + attn_out + ff_out
109
120
  else:
110
121
  x_norm = self.pre_atten_norm(x)
111
- attn_out = self.atten_func(x_norm, rope, mask, input_pos)
122
+ atten_func_out = self.atten_func(x_norm, rope, mask, input_pos, kv_cache)
123
+ if kv_cache is None:
124
+ attn_out = atten_func_out
125
+ else:
126
+ attn_out, kv = atten_func_out
112
127
  x = x + attn_out
113
- x_norm = self.pre_ff_norm(x)
128
+ x_norm = self.post_atten_norm(x)
114
129
  output = x + self.ff(x_norm)
115
130
 
116
- return output
131
+ return output if kv is None else (output, kv)
117
132
 
118
133
 
119
134
  class CausalSelfAttention(nn.Module):
@@ -123,7 +138,6 @@ class CausalSelfAttention(nn.Module):
123
138
  batch_size: int,
124
139
  dim: int,
125
140
  config: cfg.AttentionConfig,
126
- kv_cache_max: int,
127
141
  enable_hlfb: bool,
128
142
  ) -> None:
129
143
  """Initialize an instance of CausalSelfAttention.
@@ -132,33 +146,31 @@ class CausalSelfAttention(nn.Module):
132
146
  batch_size (int): batch size of the input tensor.
133
147
  dim (int): causal attention's input/output dimmension.
134
148
  config (cfg.AttentionConfig): attention specific configurations.
135
- kv_cache_max (int): determines the size of the KV Cache buffer, if enabled.
136
149
  enable_hlfb (bool): whether hlfb is enabled or not.
137
150
  """
138
151
  super().__init__()
139
- self.head_dim = dim // config.num_heads
140
- shape = (config.num_heads + 2 * config.num_query_groups) * self.head_dim
141
- # Key, query, value projections for all heads.
142
- self.qkv_projection = nn.Linear(dim, shape, bias=config.qkv_use_bias)
143
- self.output_projection = nn.Linear(dim, dim, bias=config.output_proj_use_bias)
144
- self.config = config
145
152
  self.kv_cache = None
146
153
  self.batch_size = batch_size
147
-
148
- # Build a k/v cache with size (batch_size, kv_cache_max, n_heads, head_dim).
149
- if config.enable_kv_cache:
150
- self.kv_cache = KVCache(
151
- batch_size,
152
- kv_cache_max,
153
- config.num_query_groups,
154
- self.head_dim,
155
- enable_hlfb,
156
- )
157
-
158
- if enable_hlfb:
159
- self.sdpa_func = scaled_dot_product_attention_with_hlfb
160
- else:
161
- self.sdpa_func = scaled_dot_product_attention
154
+ qkv_shape = (
155
+ config.num_heads + 2 * config.num_query_groups
156
+ ) * config.head_dim
157
+ output_shape = config.num_heads * config.head_dim
158
+ # Key, query, value projections for all heads.
159
+ self.qkv_projection = nn.Linear(dim, qkv_shape, bias=config.qkv_use_bias)
160
+ self.output_projection = nn.Linear(
161
+ output_shape, dim, bias=config.output_proj_use_bias
162
+ )
163
+ self.query_norm = builder.build_norm(
164
+ config.head_dim, config.query_norm_config
165
+ )
166
+ self.key_norm = builder.build_norm(config.head_dim, config.key_norm_config)
167
+ self.config = config
168
+ self.enable_hlfb = enable_hlfb
169
+ self.sdpa_func = (
170
+ sdpa.scaled_dot_product_attention_with_hlfb
171
+ if enable_hlfb
172
+ else sdpa.scaled_dot_product_attention
173
+ )
162
174
 
163
175
  def forward(
164
176
  self,
@@ -166,8 +178,10 @@ class CausalSelfAttention(nn.Module):
166
178
  rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
167
179
  mask: Optional[torch.Tensor] = None,
168
180
  input_pos: Optional[torch.Tensor] = None,
169
- ) -> torch.Tensor:
181
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
182
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
170
183
  """Forward function of the CausalSelfAttention layer, which can support
184
+
171
185
  MQA, GQA and MHA.
172
186
 
173
187
  Args:
@@ -175,15 +189,18 @@ class CausalSelfAttention(nn.Module):
175
189
  rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
176
190
  mask (torch.Tensor): the optional mask tensor.
177
191
  input_pos (torch.Tensor): the optional input position tensor.
192
+ kv_cache (KVCacheEntry): The KV cache entry corresponding to this module.
178
193
 
179
194
  Returns:
180
- output activation from this self attention layer.
195
+ output activation from this self attention layer, and the updated
196
+ KV Cach Entry (if passed in).
181
197
  """
182
198
  # Batch size, sequence length, embedding dimensionality.
183
199
  B, T, E = x.size()
184
- assert (
185
- B == self.batch_size
186
- ), "batch size of input tensor must match with the batch size specified in the model configuration."
200
+ assert B == self.batch_size, (
201
+ "batch size of input tensor must match with the batch size specified in"
202
+ " the model configuration."
203
+ )
187
204
 
188
205
  qkv = self.qkv_projection(x)
189
206
 
@@ -191,7 +208,7 @@ class CausalSelfAttention(nn.Module):
191
208
  q_per_kv = self.config.num_heads // self.config.num_query_groups
192
209
  # Each group has >=1 queries, 1 key, and 1 value.
193
210
  if self.config.qkv_transpose_before_split:
194
- qkv = qkv.view(B, T, -1, self.head_dim)
211
+ qkv = qkv.view(B, T, -1, self.config.head_dim)
195
212
  q, k, v = qkv.split(
196
213
  (
197
214
  q_per_kv * self.config.num_query_groups,
@@ -203,27 +220,44 @@ class CausalSelfAttention(nn.Module):
203
220
  else:
204
221
  qkv = qkv.view(B, T, self.config.num_query_groups, -1)
205
222
  q, k, v = qkv.split(
206
- (q_per_kv * self.head_dim, self.head_dim, self.head_dim), dim=-1
223
+ (
224
+ q_per_kv * self.config.head_dim,
225
+ self.config.head_dim,
226
+ self.config.head_dim,
227
+ ),
228
+ dim=-1,
207
229
  )
208
230
 
209
- q = q.reshape(B, T, -1, self.head_dim)
210
- k = k.reshape(B, T, -1, self.head_dim)
211
- v = v.reshape(B, T, -1, self.head_dim)
231
+ q = self.query_norm(q)
232
+ k = self.key_norm(k)
233
+
234
+ q = q.reshape(B, T, -1, self.config.head_dim)
235
+ k = k.reshape(B, T, -1, self.config.head_dim)
236
+ v = v.reshape(B, T, -1, self.config.head_dim)
212
237
 
213
238
  # Compute rotary positional embedding for query and key.
214
- n_elem = int(self.config.rotary_percentage * self.head_dim)
239
+ n_elem = int(self.config.rotary_percentage * self.config.head_dim)
215
240
  q, k = _embed_rope(q, k, n_elem, rope)
216
241
 
217
- if self.kv_cache is not None:
218
- # TODO(haoliang): Handle when execeeding max sequence length.
219
- k, v = self.kv_cache.update_cache(input_pos, k, v)
220
-
221
- y = self.sdpa_func(q, k, v, self.head_dim, mask=mask)
222
- y = y.reshape(B, T, E)
242
+ if kv_cache is not None:
243
+ kv_cache = kv_utils.update(
244
+ kv_cache, input_pos, k, v, enable_hlfb=self.enable_hlfb
245
+ )
246
+ k, v = kv_cache.k_cache, kv_cache.v_cache
247
+
248
+ y = self.sdpa_func(
249
+ q,
250
+ k,
251
+ v,
252
+ self.config.head_dim,
253
+ mask=mask,
254
+ softcap=self.config.logit_softcap,
255
+ )
256
+ y = y.reshape(B, T, -1)
223
257
 
224
258
  # Compute the output projection.
225
259
  y = self.output_projection(y)
226
- return y
260
+ return y if kv_cache is None else (y, kv_cache)
227
261
 
228
262
 
229
263
  class SelfAttention(CausalSelfAttention):
@@ -234,16 +268,19 @@ class SelfAttention(CausalSelfAttention):
234
268
  x: torch.Tensor,
235
269
  rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
236
270
  input_pos: Optional[torch.Tensor] = None,
237
- ) -> torch.Tensor:
271
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
272
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, kv_utils.KVCacheEntry]]:
238
273
  """Forward function of the SelfAttention layer, which can support MQA, GQA and MHA.
239
274
 
240
275
  Args:
241
276
  x (torch.Tensor): the input tensor.
242
277
  rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
243
278
  input_pos (torch.Tensor): the optional input position tensor.
279
+ kv_cache (KVCacheEntry): The KV cache entry corresponding to this module.
244
280
 
245
281
  Returns:
246
- output activation from this self attention layer.
282
+ output activation from this self attention layer, and the updated
283
+ KV Cach Entry (if passed in).
247
284
  """
248
285
  B, T, _ = x.size()
249
286
  return super().forward(
@@ -261,46 +298,43 @@ class CrossAttention(nn.Module):
261
298
  batch_size: int,
262
299
  query_dim: int,
263
300
  cross_dim: int,
301
+ hidden_dim: int,
302
+ output_dim: int,
264
303
  config: cfg.AttentionConfig,
265
- kv_cache_max: int,
266
304
  enable_hlfb: bool,
267
- ) -> None:
305
+ ):
268
306
  """Initialize an instance of CrossAttention.
269
307
 
270
308
  Args:
271
309
  batch_size (int): batch size of the input tensor.
272
310
  query_dim (int): query tensor's dimension.
273
311
  cross_dim (int): cross attention's dimensions, for key and value tensors.
312
+ hidden_dim (int): hidden dimension that q, k, v tensors project to.
313
+ output_dim (int): output tensor's dimension.
274
314
  config (cfg.AttentionConfig): attention specific configurations.
275
- kv_cache_max (int): determines the size of the KV Cache buffer, if enabled.
276
315
  enable_hlfb (bool): whether hlfb is enabled or not.
277
316
  """
278
317
  super().__init__()
279
318
  self.config = config
280
- self.head_dim = query_dim // config.num_heads
281
319
  self.n_heads = config.num_heads
282
- self.q_projection = nn.Linear(query_dim, query_dim, bias=config.qkv_use_bias)
283
- self.k_projection = nn.Linear(cross_dim, query_dim, bias=config.qkv_use_bias)
284
- self.v_projection = nn.Linear(cross_dim, query_dim, bias=config.qkv_use_bias)
320
+ self.q_projection = nn.Linear(
321
+ query_dim, hidden_dim, bias=config.qkv_use_bias
322
+ )
323
+ self.k_projection = nn.Linear(
324
+ cross_dim, hidden_dim, bias=config.qkv_use_bias
325
+ )
326
+ self.v_projection = nn.Linear(
327
+ cross_dim, hidden_dim, bias=config.qkv_use_bias
328
+ )
285
329
  self.output_projection = nn.Linear(
286
- query_dim, query_dim, bias=config.output_proj_use_bias
330
+ hidden_dim, output_dim, bias=config.output_proj_use_bias
287
331
  )
288
332
 
289
- self.kv_cache = None
290
- # Build a k/v cache with size (batch_size, kv_cache_max, n_heads, head_dim).
291
- if config.enable_kv_cache:
292
- self.kv_cache = KVCache(
293
- batch_size,
294
- kv_cache_max,
295
- config.num_query_groups,
296
- self.head_dim,
297
- enable_hlfb,
298
- )
299
-
300
- if enable_hlfb:
301
- self.sdpa_func = scaled_dot_product_attention_with_hlfb
302
- else:
303
- self.sdpa_func = scaled_dot_product_attention
333
+ self.sdpa_func = (
334
+ sdpa.scaled_dot_product_attention_with_hlfb
335
+ if enable_hlfb
336
+ else sdpa.scaled_dot_product_attention
337
+ )
304
338
 
305
339
  def forward(
306
340
  self,
@@ -309,6 +343,7 @@ class CrossAttention(nn.Module):
309
343
  rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
310
344
  mask: Optional[torch.Tensor] = None,
311
345
  input_pos: Optional[torch.Tensor] = None,
346
+ kv_cache: Optional[kv_utils.KVCacheEntry] = None,
312
347
  ):
313
348
  """Forward function of the CrossAttention layer.
314
349
 
@@ -316,8 +351,10 @@ class CrossAttention(nn.Module):
316
351
  x (torch.Tensor): the target tensor, with shape [B, target_seq_len, ...].
317
352
  y (torch.Tensor): the source tensor, with shape [B, source_seq_len, ...].
318
353
  rope (Tuple[torch.Tensor, torch.Tensor]): the optional input rope tensor.
319
- mask (torch.Tensor): the optional mask tensor can be broadcaseted to shape [B, n_heads, target_seq_len, source_seq_len].
354
+ mask (torch.Tensor): the optional mask tensor can be broadcaseted to shape
355
+ [B, n_heads, target_seq_len, source_seq_len].
320
356
  input_pos (torch.Tensor): the optional input position tensor.
357
+ kv_cache (KVCacheEntry): The KV cache entry corresponding to this module.
321
358
 
322
359
  Returns:
323
360
  output activation from this cross attention layer.
@@ -330,25 +367,27 @@ class CrossAttention(nn.Module):
330
367
  k = self.k_projection(y)
331
368
  v = self.v_projection(y)
332
369
 
333
- interim_shape = (batch_size, -1, self.n_heads, self.head_dim)
370
+ interim_shape = (batch_size, -1, self.n_heads, self.config.head_dim)
334
371
  q = q.view(interim_shape)
335
372
  k = k.view(interim_shape)
336
373
  v = v.view(interim_shape)
337
374
 
338
375
  # Compute rotary positional embedding for query and key.
339
- n_elem = int(self.config.rotary_percentage * self.head_dim)
376
+ n_elem = int(self.config.rotary_percentage * self.config.head_dim)
340
377
  q, k = _embed_rope(q, k, n_elem, rope)
341
378
 
342
- if self.kv_cache is not None:
343
- # TODO(haoliang): Handle when execeeding max sequence length.
344
- k, v = self.kv_cache.update_cache(input_pos, k, v)
379
+ if kv_cache is not None:
380
+ kv_cache = kv_utils.update(
381
+ kv_cache, input_pos, k, v, enable_hlfb=self.enable_hlfb
382
+ )
383
+ k, v = kv_cache.k_cache, kv_cache.v_cache
345
384
  if mask is None:
346
385
  mask = torch.zeros(
347
386
  (batch_size, 1, target_seq_len, source_seq_len), dtype=torch.float32
348
387
  )
349
- y = self.sdpa_func(q, k, v, self.head_dim, mask=mask)
388
+ y = self.sdpa_func(q, k, v, self.config.head_dim, mask=mask)
350
389
  y = y.reshape(batch_size, target_seq_len, -1)
351
390
 
352
391
  # Compute the output projection.
353
392
  y = self.output_projection(y)
354
- return y
393
+ return y if kv_cache is None else (y, kv_cache)
@@ -28,7 +28,9 @@ def build_rope_cache(
28
28
  dtype: torch.dtype = torch.float32,
29
29
  device: torch.device = None,
30
30
  ) -> Tuple[torch.Tensor, torch.Tensor]:
31
- """Precompute Rotary Positional Embedding Sin and Cos values for quick lookups
31
+ """Precomputes Rotary Positional Embeddings.
32
+
33
+ Precompute Rotary Positional Embedding Sin and Cos values for quick lookup
32
34
  during the inference.
33
35
 
34
36
  Args:
@@ -72,28 +74,64 @@ def build_causal_mask_cache(
72
74
  Returns:
73
75
  torch.Tensor: Causal attention mask.
74
76
  """
77
+
75
78
  if device is None:
76
79
  device = torch.device('cpu')
77
80
  mask = torch.full((size, size), float('-inf'), dtype=dtype, device=device)
78
81
  return torch.triu(mask, diagonal=1).unsqueeze(0).unsqueeze(0)
79
82
 
80
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, -2.3819763e38)
111
+
112
+
81
113
  def relative_position_bucket(
82
114
  relative_position: torch.Tensor,
83
115
  bidirectional: bool,
84
116
  num_buckets: int,
85
117
  max_distance: int,
86
118
  ) -> torch.Tensor:
87
- """
88
- Adapted from Mesh Tensorflow:
119
+ """Adapted from Mesh Tensorflow:
120
+
89
121
  https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
90
122
 
91
- Translate relative position to a bucket number for relative attention. The relative position is defined as
92
- memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
93
- position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
94
- small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
95
- positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
96
- This should allow for more graceful generalization to longer sequences than the model has been trained on
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
97
135
 
98
136
  Args:
99
137
  relative_position: an int32 Tensor
@@ -102,7 +140,8 @@ def relative_position_bucket(
102
140
  max_distance: an integer for max distance.
103
141
 
104
142
  Returns:
105
- a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
143
+ a Tensor with the same shape as relative_position, containing int32 values
144
+ in the range [0, num_buckets)
106
145
  """
107
146
  relative_buckets = 0
108
147
  if bidirectional:
@@ -119,7 +158,8 @@ def relative_position_bucket(
119
158
  max_exact = num_buckets // 2
120
159
  is_small = relative_position < max_exact
121
160
 
122
- # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
161
+ # The other half of the buckets are for logarithmically bigger bins in
162
+ # positions up to max_distance
123
163
  relative_position_if_large = max_exact + (
124
164
  torch.log(relative_position.float() / max_exact)
125
165
  / math.log(max_distance / max_exact)
@@ -148,7 +188,8 @@ def build_relative_position_buckets(
148
188
  Args:
149
189
  query_length: an integer of length of current query tensor.
150
190
  key_length: an integer of length of current key tensor.
151
- bidirectional: a boolean - whether the attention is bidirectional, default is True.
191
+ bidirectional: a boolean - whether the attention is bidirectional, default
192
+ is True.
152
193
  num_buckets: an integer for number of buckets, default is 32.
153
194
  max_distance: an integer for max distance, default is 128.
154
195
 
@@ -13,13 +13,14 @@
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
15
  # Builder class for individual components.
16
- import torch
17
- from torch import nn
18
- import torch.nn.functional as F
16
+ from typing import Callable
19
17
 
20
18
  import ai_edge_torch.generative.layers.feed_forward as feed_forward
21
19
  import ai_edge_torch.generative.layers.model_config as cfg
22
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
23
24
 
24
25
 
25
26
  class GeGLU(nn.Module):
@@ -27,7 +28,6 @@ class GeGLU(nn.Module):
27
28
 
28
29
  GeGLU(x) = (xW+b) * GELU(xV+c)
29
30
  See: https://arxiv.org/abs/2002.05202v1
30
-
31
31
  """
32
32
 
33
33
  def __init__(self, d_in: int, d_out: int):
@@ -39,6 +39,21 @@ class GeGLU(nn.Module):
39
39
  return x * F.gelu(gate)
40
40
 
41
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
+
42
57
  def build_norm(dim: int, config: cfg.NormalizationConfig):
43
58
  """Builder function for normalizers.
44
59
 
@@ -61,9 +76,13 @@ def build_norm(dim: int, config: cfg.NormalizationConfig):
61
76
  zero_centered_gamma=config.zero_centered,
62
77
  )
63
78
  elif config.type == cfg.NormalizationType.LAYER_NORM:
64
- return nn.LayerNorm(dim, eps=config.epsilon)
79
+ return normalization.LayerNorm(
80
+ dim, config.epsilon, config.enable_hlfb, config.use_input_shape
81
+ )
65
82
  elif config.type == cfg.NormalizationType.GROUP_NORM:
66
- return nn.GroupNorm(config.group_num, dim, config.epsilon)
83
+ return normalization.GroupNorm(
84
+ config.group_num, dim, config.epsilon, config.enable_hlfb
85
+ )
67
86
  else:
68
87
  raise ValueError("Unsupported norm type.")
69
88
 
@@ -73,7 +92,7 @@ def build_ff(dim: int, config: cfg.FeedForwardConfig):
73
92
 
74
93
  Args:
75
94
  dim (int): dimension of the input tensor.
76
- config (`ModelConfig` object): the model configuration.
95
+ config (`FeedForwardConfig` object): the model configuration.
77
96
 
78
97
  Returns:
79
98
  The constructed `nn.Module` feedforward layer.
@@ -91,11 +110,20 @@ def build_ff(dim: int, config: cfg.FeedForwardConfig):
91
110
 
92
111
  activation = get_activation(config.activation)
93
112
 
113
+ pre_ff_norm = build_norm(dim, config.pre_ff_norm_config)
114
+ post_ff_norm = build_norm(dim, config.post_ff_norm_config)
115
+
94
116
  return ff_module(
95
117
  dim=dim,
96
118
  hidden_dim=config.intermediate_size,
97
119
  activation=activation,
98
120
  use_bias=config.use_bias,
121
+ use_glu=(
122
+ config.activation.type == cfg.ActivationType.GE_GLU
123
+ or config.activation.type == cfg.ActivationType.SILU_GLU
124
+ ),
125
+ pre_ff_norm=pre_ff_norm,
126
+ post_ff_norm=post_ff_norm,
99
127
  )
100
128
 
101
129
 
@@ -127,5 +155,7 @@ def get_activation(config: cfg.ActivationConfig):
127
155
  return GeGLU(config.dim_in, config.dim_out)
128
156
  elif config.type == cfg.ActivationType.RELU:
129
157
  return F.relu
158
+ elif config.type == cfg.ActivationType.SILU_GLU:
159
+ return SwiGLU()
130
160
  else:
131
161
  raise ValueError("Unsupported activation type.")