ai-edge-torch-nightly 0.1.dev202405131930__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ai-edge-torch-nightly might be problematic. Click here for more details.

Files changed (91) hide show
  1. ai_edge_torch/__init__.py +30 -0
  2. ai_edge_torch/convert/__init__.py +14 -0
  3. ai_edge_torch/convert/conversion.py +117 -0
  4. ai_edge_torch/convert/conversion_utils.py +330 -0
  5. ai_edge_torch/convert/converter.py +171 -0
  6. ai_edge_torch/convert/fx_passes/__init__.py +59 -0
  7. ai_edge_torch/convert/fx_passes/_pass_base.py +49 -0
  8. ai_edge_torch/convert/fx_passes/build_aten_composite_pass.py +192 -0
  9. ai_edge_torch/convert/fx_passes/build_upsample_bilinear2d_composite_pass.py +84 -0
  10. ai_edge_torch/convert/fx_passes/canonicalize_pass.py +37 -0
  11. ai_edge_torch/convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
  12. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
  13. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +215 -0
  14. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +48 -0
  15. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +17 -0
  16. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +59 -0
  17. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +196 -0
  18. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +400 -0
  19. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
  20. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +286 -0
  21. ai_edge_torch/convert/fx_passes/optimize_layout_transposes_pass/utils.py +62 -0
  22. ai_edge_torch/convert/test/__init__.py +14 -0
  23. ai_edge_torch/convert/test/test_convert.py +273 -0
  24. ai_edge_torch/convert/test/test_convert_composites.py +171 -0
  25. ai_edge_torch/convert/test/test_convert_multisig.py +139 -0
  26. ai_edge_torch/debug/__init__.py +16 -0
  27. ai_edge_torch/debug/culprit.py +423 -0
  28. ai_edge_torch/debug/test/__init__.py +14 -0
  29. ai_edge_torch/debug/test/test_culprit.py +133 -0
  30. ai_edge_torch/debug/utils.py +48 -0
  31. ai_edge_torch/experimental/__init__.py +14 -0
  32. ai_edge_torch/generative/__init__.py +14 -0
  33. ai_edge_torch/generative/examples/__init__.py +14 -0
  34. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  35. ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +66 -0
  36. ai_edge_torch/generative/examples/gemma/gemma.py +174 -0
  37. ai_edge_torch/generative/examples/phi2/__init__.py +14 -0
  38. ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +64 -0
  39. ai_edge_torch/generative/examples/phi2/phi2.py +164 -0
  40. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +135 -0
  42. ai_edge_torch/generative/examples/t5/t5.py +608 -0
  43. ai_edge_torch/generative/examples/t5/t5_attention.py +255 -0
  44. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  45. ai_edge_torch/generative/examples/test_models/toy_model.py +119 -0
  46. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +143 -0
  47. ai_edge_torch/generative/examples/tiny_llama/__init__.py +0 -0
  48. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +66 -0
  49. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +164 -0
  50. ai_edge_torch/generative/layers/__init__.py +14 -0
  51. ai_edge_torch/generative/layers/attention.py +288 -0
  52. ai_edge_torch/generative/layers/attention_utils.py +169 -0
  53. ai_edge_torch/generative/layers/builder.py +103 -0
  54. ai_edge_torch/generative/layers/feed_forward.py +95 -0
  55. ai_edge_torch/generative/layers/kv_cache.py +83 -0
  56. ai_edge_torch/generative/layers/model_config.py +135 -0
  57. ai_edge_torch/generative/layers/normalization.py +62 -0
  58. ai_edge_torch/generative/layers/rotary_position_embedding.py +36 -0
  59. ai_edge_torch/generative/quantize/__init__.py +14 -0
  60. ai_edge_torch/generative/quantize/example.py +45 -0
  61. ai_edge_torch/generative/quantize/quant_attrs.py +66 -0
  62. ai_edge_torch/generative/quantize/quant_recipe.py +106 -0
  63. ai_edge_torch/generative/quantize/quant_recipe_utils.py +51 -0
  64. ai_edge_torch/generative/quantize/quant_recipes.py +48 -0
  65. ai_edge_torch/generative/quantize/supported_schemes.py +31 -0
  66. ai_edge_torch/generative/test/__init__.py +14 -0
  67. ai_edge_torch/generative/test/test_model_conversion.py +201 -0
  68. ai_edge_torch/generative/test/test_quantize.py +109 -0
  69. ai_edge_torch/generative/utilities/__init__.py +15 -0
  70. ai_edge_torch/generative/utilities/loader.py +290 -0
  71. ai_edge_torch/generative/utilities/t5_loader.py +467 -0
  72. ai_edge_torch/hlfb/__init__.py +16 -0
  73. ai_edge_torch/hlfb/mark_pattern/__init__.py +139 -0
  74. ai_edge_torch/hlfb/mark_pattern/passes.py +42 -0
  75. ai_edge_torch/hlfb/mark_pattern/pattern.py +260 -0
  76. ai_edge_torch/hlfb/test/__init__.py +14 -0
  77. ai_edge_torch/hlfb/test/test_mark_pattern.py +133 -0
  78. ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +270 -0
  79. ai_edge_torch/model.py +134 -0
  80. ai_edge_torch/quantize/__init__.py +16 -0
  81. ai_edge_torch/quantize/pt2e_quantizer.py +438 -0
  82. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1041 -0
  83. ai_edge_torch/quantize/quant_config.py +85 -0
  84. ai_edge_torch/testing/__init__.py +14 -0
  85. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  86. ai_edge_torch/testing/model_coverage/model_coverage.py +126 -0
  87. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/LICENSE +202 -0
  88. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/METADATA +38 -0
  89. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/RECORD +91 -0
  90. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/WHEEL +5 -0
  91. ai_edge_torch_nightly-0.1.dev202405131930.dist-info/top_level.txt +1 -0
@@ -0,0 +1,164 @@
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
+ # Example of building a TinyLlama model from the Edge Generative API layers.
16
+
17
+ import os
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from ai_edge_torch.generative.layers.attention import TransformerBlock
25
+ import ai_edge_torch.generative.layers.attention_utils as attn_utils
26
+ import ai_edge_torch.generative.layers.builder as builder
27
+ import ai_edge_torch.generative.layers.model_config as cfg
28
+ import ai_edge_torch.generative.utilities.loader as loading_utils
29
+
30
+ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
31
+ ff_up_proj="model.layers.{}.mlp.up_proj",
32
+ ff_down_proj="model.layers.{}.mlp.down_proj",
33
+ ff_gate_proj="model.layers.{}.mlp.gate_proj",
34
+ attn_query_proj="model.layers.{}.self_attn.q_proj",
35
+ attn_key_proj="model.layers.{}.self_attn.k_proj",
36
+ attn_value_proj="model.layers.{}.self_attn.v_proj",
37
+ attn_output_proj="model.layers.{}.self_attn.o_proj",
38
+ pre_attn_norm="model.layers.{}.input_layernorm",
39
+ pre_ff_norm="model.layers.{}.post_attention_layernorm",
40
+ embedding="model.embed_tokens",
41
+ final_norm="model.norm",
42
+ lm_head="lm_head",
43
+ )
44
+
45
+
46
+ class TinyLLamma(nn.Module):
47
+
48
+ def __init__(self, config: cfg.ModelConfig):
49
+ super().__init__()
50
+
51
+ self.config = config
52
+ # Construct model layers.
53
+ self.lm_head = nn.Linear(
54
+ config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
55
+ )
56
+ self.tok_embedding = nn.Embedding(
57
+ config.vocab_size, config.embedding_dim, padding_idx=0
58
+ )
59
+ self.transformer_blocks = nn.ModuleList(
60
+ TransformerBlock(config) for _ in range(config.num_layers)
61
+ )
62
+ self.final_norm = builder.build_norm(
63
+ config.embedding_dim,
64
+ config.final_norm_config,
65
+ )
66
+ self.rope_cache = attn_utils.build_rope_cache(
67
+ size=config.kv_cache_max,
68
+ dim=int(config.attn_config.rotary_percentage * config.head_dim),
69
+ base=10_000,
70
+ condense_ratio=1,
71
+ dtype=torch.float32,
72
+ device=torch.device("cpu"),
73
+ )
74
+ self.mask_cache = attn_utils.build_causal_mask_cache(
75
+ size=config.kv_cache_max, dtype=torch.float32, device=torch.device("cpu")
76
+ )
77
+ self.config = config
78
+
79
+ # The model's forward function takes in additional k/v cache tensors
80
+ # and returns the updated k/v cache tensors to the caller.
81
+ # This can be eliminated if we handle k/v cache updates inside the model itself.
82
+ @torch.inference_mode
83
+ def forward(self, idx: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
84
+ B, T = idx.size()
85
+ assert (
86
+ self.config.max_seq_len >= T
87
+ ), f"Cannot forward sequence of length {T}, max seq length is only {self.config.max_seq_len}"
88
+
89
+ cos, sin = self.rope_cache
90
+ cos = cos.index_select(0, input_pos)
91
+ sin = sin.index_select(0, input_pos)
92
+ mask = self.mask_cache.index_select(2, input_pos)
93
+ mask = mask[:, :, :, : self.config.kv_cache_max]
94
+
95
+ # forward the model itself
96
+ x = self.tok_embedding(idx) # token embeddings of shape (b, t, n_embd)
97
+
98
+ for i, block in enumerate(self.transformer_blocks):
99
+ x = block(x, (cos, sin), mask, input_pos)
100
+
101
+ x = self.final_norm(x)
102
+
103
+ res = self.lm_head(x) # (b, t, vocab_size)
104
+ return res
105
+
106
+
107
+ def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
108
+ attn_config = cfg.AttentionConfig(
109
+ num_heads=32,
110
+ num_query_groups=4,
111
+ rotary_percentage=1.0,
112
+ )
113
+ ff_config = cfg.FeedForwardConfig(
114
+ type=cfg.FeedForwardType.GATED,
115
+ activation=cfg.ActivationType.SILU,
116
+ intermediate_size=5632,
117
+ )
118
+ norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
119
+ config = cfg.ModelConfig(
120
+ vocab_size=32000,
121
+ num_layers=22,
122
+ max_seq_len=2048,
123
+ embedding_dim=2048,
124
+ kv_cache_max_len=kv_cache_max_len,
125
+ attn_config=attn_config,
126
+ ff_config=ff_config,
127
+ pre_attention_norm_config=norm_config,
128
+ pre_ff_norm_config=norm_config,
129
+ final_norm_config=norm_config,
130
+ enable_hlfb=True,
131
+ )
132
+ return config
133
+
134
+
135
+ def get_fake_model_config_for_test() -> cfg.ModelConfig:
136
+ config = get_model_config()
137
+ config.vocab_size = 128
138
+ config.num_layers = 2
139
+ config.ff_config.intermediate_size = 256
140
+ return config
141
+
142
+
143
+ def build_model(checkpoint_path, **kwargs) -> nn.Module:
144
+ config = get_model_config(**kwargs)
145
+ model = TinyLLamma(config)
146
+ loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
147
+ loader.load(model)
148
+ return model
149
+
150
+
151
+ def define_and_run() -> None:
152
+ kv_cache_max_len = 1024
153
+ checkpoint_path = os.path.join(Path.home(), "Downloads/llm_data/tiny_llama")
154
+ model = build_model(checkpoint_path, kv_cache_max_len=kv_cache_max_len)
155
+ idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
156
+ tokens = torch.full((1, kv_cache_max_len), 0, dtype=torch.long, device="cpu")
157
+ tokens[0, :4] = idx
158
+ input_pos = torch.arange(0, kv_cache_max_len)
159
+ print("running an inference")
160
+ print(model.forward(tokens, input_pos))
161
+
162
+
163
+ if __name__ == "__main__":
164
+ define_and_run()
@@ -0,0 +1,14 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
@@ -0,0 +1,288 @@
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 Attention layer.
16
+
17
+ import math
18
+ from typing import Optional, Tuple
19
+
20
+ import torch
21
+ from torch import nn
22
+ import torch.nn.functional as F
23
+
24
+ import ai_edge_torch.generative.layers.builder as builder
25
+ from ai_edge_torch.generative.layers.kv_cache import KVCache
26
+ import ai_edge_torch.generative.layers.model_config as cfg
27
+ import ai_edge_torch.generative.layers.rotary_position_embedding as rotary_pos_emb
28
+ from ai_edge_torch.hlfb import StableHLOCompositeBuilder
29
+
30
+
31
+ def scaled_dot_product_attention(
32
+ q: torch.Tensor,
33
+ k: torch.Tensor,
34
+ v: torch.Tensor,
35
+ head_size: int,
36
+ mask: Optional[torch.Tensor] = None,
37
+ scale: Optional[float] = None,
38
+ ):
39
+ """Scaled dot product attention.
40
+
41
+ Args:
42
+ q (torch.Tensor): Query tensor, with shape [B, T, N, H].
43
+ k (torch.Tensor): Key tensor, with shape [B, T, KV_LEN, H].
44
+ v (torch.Tensor): Value tensor, with shape [B, T, KV_LEN, H].
45
+ head_size (int): head dimension.
46
+ mask (torch.Tensor): the optional mask tensor.
47
+
48
+ Returns:
49
+ The output tensor of scaled_dot_product_attention.
50
+ """
51
+
52
+ if scale is None:
53
+ scale = 1.0 / math.sqrt(head_size)
54
+
55
+ q = q.transpose(1, 2)
56
+ k = k.transpose(1, 2)
57
+ v = v.transpose(1, 2)
58
+ if q.size() != k.size():
59
+ # Handle the GQA case, where q.shape[1] % k.shape[1] == 0.
60
+ k = k.repeat_interleave(q.shape[1] // k.shape[1], dim=1)
61
+ v = v.repeat_interleave(q.shape[1] // v.shape[1], dim=1)
62
+ y = F.scaled_dot_product_attention(
63
+ q,
64
+ k,
65
+ v,
66
+ attn_mask=mask,
67
+ dropout_p=0.0,
68
+ is_causal=mask is None,
69
+ scale=scale,
70
+ )
71
+ return y.transpose(1, 2)
72
+
73
+
74
+ def scaled_dot_product_attention_with_hlfb(
75
+ q: torch.Tensor,
76
+ k: torch.Tensor,
77
+ v: torch.Tensor,
78
+ head_size: int,
79
+ mask: Optional[torch.Tensor] = None,
80
+ scale: Optional[float] = None,
81
+ ):
82
+ """Scaled dot product attention with high-level function boundary enabled.
83
+
84
+ Args:
85
+ q (torch.Tensor): Query tensor, with shape [B, T, N, H].
86
+ k (torch.Tensor): Key tensor, with shape [B, T, KV_LEN, H].
87
+ v (torch.Tensor): Value tensor, with shape [B, T, KV_LEN, H].
88
+ head_size (int): head dimension.
89
+ mask (torch.Tensor): the optional mask tensor.
90
+
91
+ Returns:
92
+ The output tensor of scaled_dot_product_attention.
93
+ """
94
+
95
+ if scale is None:
96
+ scale = 1.0 / math.sqrt(head_size)
97
+
98
+ builder = StableHLOCompositeBuilder(
99
+ name="odml.scaled_dot_product_attention", attr={"scale": scale}
100
+ )
101
+ q, k, v, mask = builder.mark_inputs(q, k, v, mask)
102
+
103
+ q = q.transpose(1, 2)
104
+ k = k.transpose(1, 2)
105
+ v = v.transpose(1, 2)
106
+ if q.size() != k.size():
107
+ # Handle the GQA case, where q.shape[1] % k.shape[1] == 0.
108
+ k = k.repeat_interleave(q.shape[1] // k.shape[1], dim=1)
109
+ v = v.repeat_interleave(q.shape[1] // v.shape[1], dim=1)
110
+ y = F.scaled_dot_product_attention(
111
+ q,
112
+ k,
113
+ v,
114
+ attn_mask=mask,
115
+ dropout_p=0.0,
116
+ is_causal=mask is None,
117
+ scale=scale,
118
+ )
119
+
120
+ result = y.transpose(1, 2)
121
+ result = builder.mark_outputs(result)
122
+ return result
123
+
124
+
125
+ class TransformerBlock(nn.Module):
126
+
127
+ def __init__(self, config: cfg.ModelConfig) -> None:
128
+ """Initialize an instance of the TransformerBlock.
129
+
130
+ Args:
131
+ config (cfg.ModelConfig): the configuration object
132
+ for this transformer block.
133
+ """
134
+
135
+ super().__init__()
136
+ self.pre_atten_norm = builder.build_norm(
137
+ config.embedding_dim, config.pre_attention_norm_config
138
+ )
139
+ self.atten_func = CausalSelfAttention(
140
+ config.embedding_dim,
141
+ config.attn_config,
142
+ config.kv_cache_max,
143
+ config.enable_hlfb,
144
+ )
145
+ self.pre_ff_norm = builder.build_norm(
146
+ config.embedding_dim, config.pre_ff_norm_config
147
+ )
148
+ self.ff = builder.build_ff(config.embedding_dim, config.ff_config)
149
+ self.config = config
150
+
151
+ def forward(
152
+ self,
153
+ x: torch.Tensor,
154
+ rope: Tuple[torch.Tensor, torch.Tensor],
155
+ mask: Optional[torch.Tensor] = None,
156
+ input_pos: Optional[torch.Tensor] = None,
157
+ ) -> torch.Tensor:
158
+ """Forward function of the TransformerBlock.
159
+
160
+ Args:
161
+ x (torch.Tensor): the input tensor.
162
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
163
+ mask (torch.Tensor): the optional mask tensor.
164
+ input_pos (torch.Tensor): the optional input position tensor.
165
+
166
+ Returns:
167
+ output activation from this transformer block.
168
+ """
169
+
170
+ if self.config.parallel_residual:
171
+ x_norm = self.pre_atten_norm(x)
172
+ attn_out = self.atten_func(x_norm, rope, mask, input_pos)
173
+ ff_out = self.ff(x_norm)
174
+ output = x + attn_out + ff_out
175
+ else:
176
+ x_norm = self.pre_atten_norm(x)
177
+ attn_out = self.atten_func(x_norm, rope, mask, input_pos)
178
+ x = x + attn_out
179
+ x_norm = self.pre_ff_norm(x)
180
+ output = x + self.ff(x_norm)
181
+
182
+ return output
183
+
184
+
185
+ # CausalSelfAttention which can support MHQ, MQA or GQA.
186
+ class CausalSelfAttention(nn.Module):
187
+
188
+ def __init__(
189
+ self,
190
+ dim: int,
191
+ config: cfg.AttentionConfig,
192
+ kv_cache_max: int,
193
+ enable_hlfb: bool,
194
+ ) -> None:
195
+ """Initialize an instance of CausalSelfAttention.
196
+
197
+ Args:
198
+ dim (int): causal attention's input/output dimmension.
199
+ config (cfg.AttentionConfig): attention specific configurations.
200
+ kv_cache_max (int): determines the size of the KV Cache buffer, if enabled.
201
+ enable_hlfb (bool): whether hlfb is enabled or not.
202
+ """
203
+ super().__init__()
204
+ self.head_dim = dim // config.num_heads
205
+ shape = (config.num_heads + 2 * config.num_query_groups) * self.head_dim
206
+ # Key, query, value projections for all heads.
207
+ self.qkv_projection = nn.Linear(dim, shape, bias=config.qkv_use_bias)
208
+ self.output_projection = nn.Linear(dim, dim, bias=config.output_proj_use_bias)
209
+ self.config = config
210
+ self.kv_cache = None
211
+
212
+ # Build a k/v cache with size (batch_size, kv_cache_max, n_heads, head_dim).
213
+ # Now only supports batch_size of 1.
214
+ # TODO(haoliang): support batch_size greater than 1.
215
+ if config.enable_kv_cache:
216
+ self.kv_cache = KVCache(
217
+ 1,
218
+ kv_cache_max,
219
+ config.num_query_groups,
220
+ self.head_dim,
221
+ enable_hlfb,
222
+ )
223
+
224
+ if enable_hlfb:
225
+ self.sdpa_func = scaled_dot_product_attention_with_hlfb
226
+ else:
227
+ self.sdpa_func = scaled_dot_product_attention
228
+
229
+ def forward(
230
+ self,
231
+ x: torch.Tensor,
232
+ rope: Tuple[torch.Tensor, torch.Tensor],
233
+ mask: Optional[torch.Tensor] = None,
234
+ input_pos: Optional[torch.Tensor] = None,
235
+ ) -> torch.Tensor:
236
+ """Forward function of the CausalSelfAttention layer.
237
+
238
+ Args:
239
+ x (torch.Tensor): the input tensor.
240
+ rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
241
+ mask (torch.Tensor): the optional mask tensor.
242
+ input_pos (torch.Tensor): the optional input position tensor.
243
+
244
+ Returns:
245
+ output activation from this self attention layer.
246
+ """
247
+ # Batch size, sequence length, embedding dimensionality.
248
+ B, T, E = x.size()
249
+ assert B == 1, "Currently only batch_size = 1 is supported."
250
+
251
+ qkv = self.qkv_projection(x)
252
+
253
+ # Assemble into a number of query groups to support MHA, MQA and GQA.
254
+ q_per_kv = self.config.num_heads // self.config.num_query_groups
255
+ total_qkv = q_per_kv + 2 # Each group has >=1 queries, 1 key, and 1 value.
256
+ qkv = qkv.view(
257
+ B, T, self.config.num_query_groups, total_qkv, self.head_dim
258
+ ) # (B, T, num_query_groups, total_qkv, head_dim)
259
+
260
+ # Split batched computation into three.
261
+ q, k, v = qkv.split((q_per_kv, 1, 1), dim=-2)
262
+
263
+ q = q.reshape(B, T, -1, self.head_dim)
264
+ k = k.reshape(B, T, -1, self.head_dim)
265
+ v = v.reshape(B, T, -1, self.head_dim)
266
+
267
+ # Compute rotary positional embedding for query and key.
268
+ n_elem = int(self.config.rotary_percentage * self.head_dim)
269
+ cos, sin = rope
270
+ q_roped = rotary_pos_emb.apply_rope(
271
+ q[..., :n_elem], cos.repeat(1, 2), sin.repeat(1, 2)
272
+ )
273
+ k_roped = rotary_pos_emb.apply_rope(
274
+ k[..., :n_elem], cos.repeat(1, 2), sin.repeat(1, 2)
275
+ )
276
+ q = torch.cat((q_roped, q[..., n_elem:]), dim=-1)
277
+ k = torch.cat((k_roped, k[..., n_elem:]), dim=-1)
278
+
279
+ if self.kv_cache is not None:
280
+ # TODO(haoliang): Handle when execeeding max sequence length.
281
+ k, v = self.kv_cache.update_cache(input_pos, k, v)
282
+
283
+ y = self.sdpa_func(q, k, v, self.head_dim, mask=mask)
284
+ y = y.reshape(B, T, E)
285
+
286
+ # Compute the output projection.
287
+ y = self.output_projection(y)
288
+ return y
@@ -0,0 +1,169 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ # Common utility functions used with attention module.
16
+
17
+ import math
18
+ from typing import Tuple
19
+
20
+ import torch
21
+
22
+
23
+ def build_rope_cache(
24
+ size: int,
25
+ dim: int,
26
+ base: int = 10000,
27
+ condense_ratio: int = 1,
28
+ dtype: torch.dtype = torch.float32,
29
+ device: torch.device = None,
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """Precompute Rotary Positional Embedding Sin and Cos values for quick lookups
32
+ during the inference.
33
+
34
+ Args:
35
+ size (int): The size of the built cache.
36
+ dim (int): Each sequence's dimmension.
37
+ base (int, optional): Rope base value. Defaults to 10000.
38
+ condense_ratio (int, optional): The ratio by which sequence indicies are
39
+ condensed. Defaults to 1.
40
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
41
+ torch.float32.
42
+ device (torch.device, optional): Output tensor's data type. Defaults to
43
+ None in which case "cpu" is used.
44
+
45
+ Returns:
46
+ Tuple[torch.Tensor, torch.Tensor]: Rope's Cosine and Sine waves.
47
+ """
48
+ if device is None:
49
+ device = torch.device('cpu')
50
+ theta = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
51
+ seq_idx = torch.arange(size) / condense_ratio
52
+ idx_theta = torch.outer(seq_idx, theta)
53
+ cos = torch.cos(idx_theta).to(dtype=dtype, device=device)
54
+ sin = torch.sin(idx_theta).to(dtype=dtype, device=device)
55
+ return cos, sin
56
+
57
+
58
+ def build_causal_mask_cache(
59
+ size: int,
60
+ dtype: torch.dtype = torch.float32,
61
+ device: torch.device = None,
62
+ ) -> torch.Tensor:
63
+ """Build a cache for causal attention mask.
64
+
65
+ Args:
66
+ size (int): The size of the built mask cache.
67
+ dtype (torch.dtype, optional): Output tensor's data type. Defaults to
68
+ torch.float32.
69
+ device (torch.device, optional): Output tensor's data type. Defaults to
70
+ None in which case "cpu" is used.
71
+
72
+ Returns:
73
+ torch.Tensor: Causal attention mask.
74
+ """
75
+ if device is None:
76
+ device = torch.device('cpu')
77
+ mask = torch.full((size, size), float('-inf'), dtype=dtype, device=device)
78
+ return torch.triu(mask, diagonal=1).unsqueeze(0).unsqueeze(0)
79
+
80
+
81
+ def relative_position_bucket(
82
+ relative_position: torch.Tensor,
83
+ bidirectional: bool,
84
+ num_buckets: int,
85
+ max_distance: int,
86
+ ) -> torch.Tensor:
87
+ """
88
+ Adapted from Mesh Tensorflow:
89
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
90
+
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
97
+
98
+ Args:
99
+ relative_position: an int32 Tensor
100
+ bidirectional: a boolean - whether the attention is bidirectional
101
+ num_buckets: an integer for number of buckets.
102
+ max_distance: an integer for max distance.
103
+
104
+ Returns:
105
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
106
+ """
107
+ relative_buckets = 0
108
+ if bidirectional:
109
+ num_buckets //= 2
110
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
111
+ relative_position = torch.abs(relative_position)
112
+ else:
113
+ relative_position = -torch.min(
114
+ relative_position, torch.zeros_like(relative_position)
115
+ )
116
+ # now relative_position is in the range [0, inf)
117
+
118
+ # half of the buckets are for exact increments in positions
119
+ max_exact = num_buckets // 2
120
+ is_small = relative_position < max_exact
121
+
122
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
123
+ relative_position_if_large = max_exact + (
124
+ torch.log(relative_position.float() / max_exact)
125
+ / math.log(max_distance / max_exact)
126
+ * (num_buckets - max_exact)
127
+ ).to(torch.long)
128
+ relative_position_if_large = torch.min(
129
+ relative_position_if_large,
130
+ torch.full_like(relative_position_if_large, num_buckets - 1),
131
+ )
132
+
133
+ relative_buckets += torch.where(
134
+ is_small, relative_position, relative_position_if_large
135
+ )
136
+ return relative_buckets
137
+
138
+
139
+ def build_relative_position_buckets(
140
+ query_length: int,
141
+ key_length: int,
142
+ bidirectional: bool = True,
143
+ num_buckets: int = 32,
144
+ max_distance: int = 128,
145
+ ) -> torch.Tensor:
146
+ """Relative position buckets for computing bias.
147
+
148
+ Args:
149
+ query_length: an integer of length of current query tensor.
150
+ key_length: an integer of length of current key tensor.
151
+ bidirectional: a boolean - whether the attention is bidirectional, default is True.
152
+ num_buckets: an integer for number of buckets, default is 32.
153
+ max_distance: an integer for max distance, default is 128.
154
+
155
+ Returns:
156
+ A torch.Tensor of computed relative position buckets.
157
+ """
158
+ context_position = torch.arange(query_length, dtype=torch.long)[:, None]
159
+ memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
160
+ relative_position = (
161
+ memory_position - context_position
162
+ ) # shape (query_length, key_length)
163
+ rel_pos_bucket = relative_position_bucket(
164
+ relative_position, # shape (query_length, key_length)
165
+ bidirectional=bidirectional,
166
+ num_buckets=num_buckets,
167
+ max_distance=max_distance,
168
+ )
169
+ return rel_pos_bucket.unsqueeze(0).unsqueeze(0)