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.
- ai_edge_torch/__init__.py +5 -4
- ai_edge_torch/_convert/conversion.py +112 -0
- ai_edge_torch/_convert/conversion_utils.py +64 -0
- ai_edge_torch/{convert → _convert}/converter.py +94 -48
- ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
- ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
- ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
- ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
- ai_edge_torch/_convert/signature.py +66 -0
- ai_edge_torch/_convert/test/test_convert.py +495 -0
- ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
- ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
- ai_edge_torch/{convert → _convert}/test/test_to_channel_last_io.py +5 -5
- ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
- ai_edge_torch/config.py +27 -0
- ai_edge_torch/conftest.py +20 -0
- ai_edge_torch/debug/culprit.py +72 -40
- ai_edge_torch/debug/test/test_culprit.py +7 -5
- ai_edge_torch/debug/test/test_search_model.py +8 -7
- ai_edge_torch/debug/utils.py +14 -3
- ai_edge_torch/fx_pass_base.py +101 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
- ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
- ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
- ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
- ai_edge_torch/generative/examples/openelm/verify.py +64 -0
- ai_edge_torch/generative/examples/phi/__init__.py +14 -0
- ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
- ai_edge_torch/generative/examples/phi/phi3.py +286 -0
- ai_edge_torch/generative/examples/phi/verify.py +65 -0
- ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
- ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
- ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
- ai_edge_torch/generative/examples/smollm/verify.py +62 -0
- ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
- ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
- ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
- ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
- ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
- ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
- ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
- ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
- ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
- ai_edge_torch/generative/examples/t5/t5.py +208 -159
- ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
- ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
- ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
- ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
- ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
- ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
- ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
- ai_edge_torch/generative/fx_passes/__init__.py +4 -5
- ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
- ai_edge_torch/generative/layers/attention.py +141 -102
- ai_edge_torch/generative/layers/attention_utils.py +53 -12
- ai_edge_torch/generative/layers/builder.py +37 -7
- ai_edge_torch/generative/layers/feed_forward.py +39 -14
- ai_edge_torch/generative/layers/kv_cache.py +162 -50
- ai_edge_torch/generative/layers/model_config.py +84 -30
- ai_edge_torch/generative/layers/normalization.py +185 -7
- ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
- ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
- ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
- ai_edge_torch/generative/layers/unet/builder.py +7 -4
- ai_edge_torch/generative/layers/unet/model_config.py +17 -15
- ai_edge_torch/generative/quantize/example.py +7 -8
- ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
- ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
- ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
- ai_edge_torch/generative/test/test_kv_cache.py +120 -0
- ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
- ai_edge_torch/generative/test/test_model_conversion.py +124 -188
- ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
- ai_edge_torch/generative/test/test_quantize.py +76 -60
- ai_edge_torch/generative/test/utils.py +54 -0
- ai_edge_torch/generative/utilities/converter.py +82 -0
- ai_edge_torch/generative/utilities/loader.py +120 -57
- ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
- ai_edge_torch/generative/utilities/t5_loader.py +110 -81
- ai_edge_torch/generative/utilities/verifier.py +247 -0
- ai_edge_torch/hlfb/__init__.py +1 -1
- ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
- ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
- ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
- ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
- ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
- ai_edge_torch/lowertools/__init__.py +18 -0
- ai_edge_torch/lowertools/_shim.py +80 -0
- ai_edge_torch/lowertools/common_utils.py +142 -0
- ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
- ai_edge_torch/lowertools/test_utils.py +60 -0
- ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
- ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
- ai_edge_torch/model.py +53 -18
- ai_edge_torch/odml_torch/__init__.py +20 -0
- ai_edge_torch/odml_torch/_torch_future.py +61 -0
- ai_edge_torch/odml_torch/_torch_library.py +19 -0
- ai_edge_torch/odml_torch/composite/__init__.py +16 -0
- ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
- ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
- ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
- ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
- ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
- ai_edge_torch/odml_torch/export.py +357 -0
- ai_edge_torch/odml_torch/export_utils.py +168 -0
- ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
- ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
- ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
- ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
- ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
- ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
- ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
- ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
- ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
- ai_edge_torch/odml_torch/lowerings/context.py +42 -0
- ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
- ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
- ai_edge_torch/odml_torch/passes/__init__.py +38 -0
- ai_edge_torch/odml_torch/tf_integration.py +194 -0
- ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
- ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
- ai_edge_torch/quantize/quant_config.py +13 -9
- ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
- ai_edge_torch/version.py +16 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
- ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
- ai_edge_torch/convert/conversion.py +0 -117
- ai_edge_torch/convert/conversion_utils.py +0 -400
- ai_edge_torch/convert/fx_passes/__init__.py +0 -59
- ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
- ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
- ai_edge_torch/convert/test/test_convert.py +0 -311
- ai_edge_torch/convert/test/test_convert_composites.py +0 -192
- ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
- ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
- ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
- ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
- ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
- ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
- /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
- /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
- /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
- {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
@@ -16,16 +16,14 @@
|
|
16
16
|
|
17
17
|
from typing import Optional, Tuple
|
18
18
|
|
19
|
-
import torch
|
20
|
-
from torch import nn
|
21
|
-
import torch.nn.functional as F
|
22
|
-
|
23
19
|
from ai_edge_torch.generative.layers.attention import CrossAttention
|
24
20
|
import ai_edge_torch.generative.layers.builder as builder
|
25
21
|
from ai_edge_torch.generative.layers.kv_cache import KVCache
|
26
22
|
import ai_edge_torch.generative.layers.model_config as cfg
|
27
23
|
from ai_edge_torch.generative.layers.scaled_dot_product_attention import scaled_dot_product_attention # NOQA
|
28
24
|
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
|
BATCH_SIZE = 1
|
31
29
|
|
@@ -33,46 +31,52 @@ BATCH_SIZE = 1
|
|
33
31
|
class EncoderDecoderBlock(nn.Module):
|
34
32
|
|
35
33
|
def __init__(
|
36
|
-
self,
|
34
|
+
self,
|
35
|
+
config: cfg.TransformerBlockConfig,
|
36
|
+
model_config: cfg.ModelConfig,
|
37
|
+
has_relative_attention_bias: bool = False,
|
37
38
|
) -> None:
|
38
39
|
"""Initialize an instance of the EncoderDecoderBlock.
|
39
40
|
|
40
41
|
Args:
|
41
|
-
config (cfg.
|
42
|
-
|
43
|
-
|
44
|
-
|
42
|
+
config (cfg.TransformerBlockConfig): the configuration object for this
|
43
|
+
transformer block.
|
44
|
+
model_config (cfg.ModelConfig): the configuration object for the model
|
45
|
+
this transformer block belongs to.
|
46
|
+
has_relative_attention_bias (bool): whether the self attention block has
|
47
|
+
relative bias.
|
45
48
|
"""
|
46
49
|
|
47
50
|
super().__init__()
|
48
51
|
self.atten_func = T5Attention(
|
49
52
|
BATCH_SIZE,
|
50
|
-
|
53
|
+
model_config.embedding_dim,
|
51
54
|
config.attn_config,
|
52
55
|
config.pre_attention_norm_config,
|
53
|
-
|
54
|
-
|
56
|
+
model_config.kv_cache_max,
|
57
|
+
model_config.enable_hlfb,
|
55
58
|
has_relative_attention_bias=has_relative_attention_bias,
|
56
59
|
)
|
57
60
|
# For a decoder, we add a cross attention.
|
58
|
-
if
|
61
|
+
if model_config.is_decoder:
|
59
62
|
self.cross_atten_func = T5Attention(
|
60
63
|
BATCH_SIZE,
|
61
|
-
|
64
|
+
model_config.embedding_dim,
|
62
65
|
config.attn_config,
|
63
66
|
config.pre_attention_norm_config,
|
64
|
-
|
65
|
-
|
67
|
+
model_config.kv_cache_max,
|
68
|
+
model_config.enable_hlfb,
|
66
69
|
# Cross Attention does not have relative attention bias.
|
67
70
|
has_relative_attention_bias=False,
|
68
71
|
)
|
69
72
|
else:
|
70
73
|
self.cross_atten_func = None
|
71
74
|
|
72
|
-
self.
|
73
|
-
|
75
|
+
self.post_atten_norm = builder.build_norm(
|
76
|
+
model_config.embedding_dim,
|
77
|
+
config.post_attention_norm_config,
|
74
78
|
)
|
75
|
-
self.ff = builder.build_ff(
|
79
|
+
self.ff = builder.build_ff(model_config.embedding_dim, config.ff_config)
|
76
80
|
self.config = config
|
77
81
|
|
78
82
|
def forward(
|
@@ -119,7 +123,7 @@ class EncoderDecoderBlock(nn.Module):
|
|
119
123
|
)
|
120
124
|
attn_out = hidden_states + attn_out
|
121
125
|
|
122
|
-
forwarded = self.
|
126
|
+
forwarded = self.post_atten_norm(attn_out)
|
123
127
|
forwarded = self.ff(forwarded)
|
124
128
|
hidden_states = attn_out + forwarded
|
125
129
|
|
@@ -144,8 +148,10 @@ class T5Attention(CrossAttention):
|
|
144
148
|
Args:
|
145
149
|
dim (int): causal attention's input/output dimmension.
|
146
150
|
config (cfg.AttentionConfig): attention specific configurations.
|
147
|
-
norm_config (cfg.NormalizationConfig): normalization configure before
|
148
|
-
|
151
|
+
norm_config (cfg.NormalizationConfig): normalization configure before
|
152
|
+
attention.
|
153
|
+
kv_cache_max (int): determines the size of the KV Cache buffer, if
|
154
|
+
enabled.
|
149
155
|
enable_hlfb (bool): whether hlfb is enabled or not.
|
150
156
|
has_relative_attention_bias (bool): whether we compute relative bias.
|
151
157
|
"""
|
@@ -181,9 +187,13 @@ class T5Attention(CrossAttention):
|
|
181
187
|
"""
|
182
188
|
|
183
189
|
x = self.pre_atten_norm(x)
|
184
|
-
B, T, C =
|
190
|
+
B, T, C = (
|
191
|
+
x.size()
|
192
|
+
) # batch size, sequence length, embedding dimensionality (n_embd)
|
185
193
|
query_states = self.q_projection(x)
|
186
|
-
query_states = query_states.reshape(
|
194
|
+
query_states = query_states.reshape(
|
195
|
+
B, T, -1, self.config.head_dim
|
196
|
+
) # (B, T, nh_q, hs)
|
187
197
|
|
188
198
|
if key_value_states is not None:
|
189
199
|
(
|
@@ -195,13 +205,13 @@ class T5Attention(CrossAttention):
|
|
195
205
|
) # batch size, sequence length, embedding dimensionality (n_embd)
|
196
206
|
key_states = self.k_projection(key_value_states)
|
197
207
|
value_states = self.v_projection(key_value_states)
|
198
|
-
key_states = key_states.reshape(kvB, kvT, -1, self.head_dim)
|
199
|
-
value_states = value_states.reshape(kvB, kvT, -1, self.head_dim)
|
208
|
+
key_states = key_states.reshape(kvB, kvT, -1, self.config.head_dim)
|
209
|
+
value_states = value_states.reshape(kvB, kvT, -1, self.config.head_dim)
|
200
210
|
else:
|
201
211
|
key_states = self.k_projection(x)
|
202
212
|
value_states = self.v_projection(x)
|
203
|
-
key_states = key_states.reshape(B, T, -1, self.head_dim)
|
204
|
-
value_states = value_states.reshape(B, T, -1, self.head_dim)
|
213
|
+
key_states = key_states.reshape(B, T, -1, self.config.head_dim)
|
214
|
+
value_states = value_states.reshape(B, T, -1, self.config.head_dim)
|
205
215
|
|
206
216
|
if key_value_states is None and self.kv_cache is not None:
|
207
217
|
key_states, value_states = self.kv_cache.update_cache(
|
@@ -218,12 +228,17 @@ class T5Attention(CrossAttention):
|
|
218
228
|
0
|
219
229
|
) # shape (1, num_heads, query_length, key_length)
|
220
230
|
else:
|
221
|
-
# position_bias = torch.zeros(B, self.n_heads, T, self.head_dim, dtype=torch.float32)
|
231
|
+
# position_bias = torch.zeros(B, self.n_heads, T, self.config.head_dim, dtype=torch.float32)
|
222
232
|
position_bias = torch.zeros_like(mask, dtype=torch.float32)
|
223
233
|
|
224
234
|
mask = mask + position_bias
|
225
235
|
y = self.sdpa_func(
|
226
|
-
query_states,
|
236
|
+
query_states,
|
237
|
+
key_states,
|
238
|
+
value_states,
|
239
|
+
self.config.head_dim,
|
240
|
+
mask=mask,
|
241
|
+
scale=1.0,
|
227
242
|
)
|
228
243
|
y = y.reshape(B, T, C) # re-assemble all head outputs side by side
|
229
244
|
# output projection
|
@@ -0,0 +1,105 @@
|
|
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
|
+
# A toy example which has a single-layer transformer block.
|
16
|
+
from absl import app
|
17
|
+
import ai_edge_torch
|
18
|
+
from ai_edge_torch import lowertools
|
19
|
+
from ai_edge_torch.generative.examples.test_models import toy_model
|
20
|
+
from ai_edge_torch.generative.examples.test_models import toy_model_with_kv_cache
|
21
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
22
|
+
import torch
|
23
|
+
|
24
|
+
KV_CACHE_MAX_LEN = 100
|
25
|
+
|
26
|
+
|
27
|
+
def convert_toy_model(_) -> None:
|
28
|
+
"""Converts a toy model to tflite."""
|
29
|
+
model = toy_model.ToySingleLayerModel(toy_model.get_model_config())
|
30
|
+
idx = torch.unsqueeze(torch.arange(0, KV_CACHE_MAX_LEN), 0)
|
31
|
+
input_pos = torch.arange(0, KV_CACHE_MAX_LEN)
|
32
|
+
print('running an inference')
|
33
|
+
print(
|
34
|
+
model.forward(
|
35
|
+
idx,
|
36
|
+
input_pos,
|
37
|
+
)
|
38
|
+
)
|
39
|
+
|
40
|
+
# Convert model to tflite.
|
41
|
+
print('converting model to tflite')
|
42
|
+
edge_model = ai_edge_torch.convert(
|
43
|
+
model,
|
44
|
+
(
|
45
|
+
idx,
|
46
|
+
input_pos,
|
47
|
+
),
|
48
|
+
)
|
49
|
+
edge_model.export('/tmp/toy_model.tflite')
|
50
|
+
|
51
|
+
|
52
|
+
def _export_stablehlo_mlir(model, args):
|
53
|
+
ep = torch.export.export(model, args)
|
54
|
+
return lowertools.exported_program_to_mlir_text(ep)
|
55
|
+
|
56
|
+
|
57
|
+
def convert_toy_model_with_kv_cache(_) -> None:
|
58
|
+
"""Converts a toy model with kv cache to tflite."""
|
59
|
+
dump_mlir = False
|
60
|
+
|
61
|
+
config = toy_model_with_kv_cache.get_model_config()
|
62
|
+
model = toy_model_with_kv_cache.ToyModelWithKVCache(config)
|
63
|
+
model.eval()
|
64
|
+
print('running an inference')
|
65
|
+
kv = kv_utils.KVCache.from_model_config(config)
|
66
|
+
|
67
|
+
tokens, input_pos = toy_model_with_kv_cache.get_sample_prefill_inputs()
|
68
|
+
decode_token, decode_input_pos = (
|
69
|
+
toy_model_with_kv_cache.get_sample_decode_inputs()
|
70
|
+
)
|
71
|
+
print(model.forward(tokens, input_pos, kv))
|
72
|
+
|
73
|
+
if dump_mlir:
|
74
|
+
mlir_text = _export_stablehlo_mlir(model, (tokens, input_pos, kv))
|
75
|
+
with open('/tmp/toy_model_with_external_kv.stablehlo.mlir', 'w') as f:
|
76
|
+
f.write(mlir_text)
|
77
|
+
|
78
|
+
# Convert model to tflite with 2 signatures (prefill + decode).
|
79
|
+
print('converting toy model to tflite with 2 signatures (prefill + decode)')
|
80
|
+
edge_model = (
|
81
|
+
ai_edge_torch.signature(
|
82
|
+
'prefill',
|
83
|
+
model,
|
84
|
+
sample_kwargs={
|
85
|
+
'tokens': tokens,
|
86
|
+
'input_pos': input_pos,
|
87
|
+
'kv_cache': kv,
|
88
|
+
},
|
89
|
+
)
|
90
|
+
.signature(
|
91
|
+
'decode',
|
92
|
+
model,
|
93
|
+
sample_kwargs={
|
94
|
+
'tokens': decode_token,
|
95
|
+
'input_pos': decode_input_pos,
|
96
|
+
'kv_cache': kv,
|
97
|
+
},
|
98
|
+
)
|
99
|
+
.convert()
|
100
|
+
)
|
101
|
+
edge_model.export('/tmp/toy_external_kv_cache.tflite')
|
102
|
+
|
103
|
+
|
104
|
+
if __name__ == '__main__':
|
105
|
+
app.run(convert_toy_model)
|
@@ -15,15 +15,12 @@
|
|
15
15
|
# A toy example which has a single-layer transformer block.
|
16
16
|
from typing import Tuple
|
17
17
|
|
18
|
-
|
19
|
-
import torch
|
20
|
-
import torch.nn as nn
|
21
|
-
|
22
|
-
import ai_edge_torch
|
18
|
+
from ai_edge_torch.generative.layers import builder
|
23
19
|
from ai_edge_torch.generative.layers.attention import TransformerBlock
|
24
20
|
import ai_edge_torch.generative.layers.attention_utils as attn_utils
|
25
|
-
import ai_edge_torch.generative.layers.builder as builder
|
26
21
|
import ai_edge_torch.generative.layers.model_config as cfg
|
22
|
+
import torch
|
23
|
+
from torch import nn
|
27
24
|
|
28
25
|
RoPECache = Tuple[torch.Tensor, torch.Tensor]
|
29
26
|
KV_CACHE_MAX_LEN = 100
|
@@ -37,14 +34,16 @@ class ToySingleLayerModel(torch.nn.Module):
|
|
37
34
|
config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
|
38
35
|
)
|
39
36
|
self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
|
40
|
-
self.transformer_block = TransformerBlock(config)
|
37
|
+
self.transformer_block = TransformerBlock(config.block_config(0), config)
|
41
38
|
self.final_norm = builder.build_norm(
|
42
39
|
config.embedding_dim,
|
43
40
|
config.final_norm_config,
|
44
41
|
)
|
42
|
+
# Toy model has only one block config.
|
43
|
+
attn_config = config.block_config(0).attn_config
|
45
44
|
self.rope_cache = attn_utils.build_rope_cache(
|
46
45
|
size=config.max_seq_len,
|
47
|
-
dim=int(
|
46
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
48
47
|
base=10_000,
|
49
48
|
condense_ratio=1,
|
50
49
|
dtype=torch.float32,
|
@@ -70,9 +69,63 @@ class ToySingleLayerModel(torch.nn.Module):
|
|
70
69
|
return self.lm_head(x)
|
71
70
|
|
72
71
|
|
72
|
+
class ToySingleLayerModelWeightSharing(torch.nn.Module):
|
73
|
+
|
74
|
+
def __init__(self, config: cfg.ModelConfig) -> None:
|
75
|
+
super().__init__()
|
76
|
+
self.lm_head = nn.Linear(
|
77
|
+
config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
|
78
|
+
)
|
79
|
+
self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
|
80
|
+
self.lm_head = nn.Linear(
|
81
|
+
config.embedding_dim,
|
82
|
+
config.vocab_size,
|
83
|
+
bias=config.lm_head_use_bias,
|
84
|
+
)
|
85
|
+
self.lm_head.weight.data = self.tok_embedding.weight.data
|
86
|
+
self.transformer_block = TransformerBlock(config.block_config(0), config)
|
87
|
+
self.final_norm = builder.build_norm(
|
88
|
+
config.embedding_dim,
|
89
|
+
config.final_norm_config,
|
90
|
+
)
|
91
|
+
# Toy model has only one block config.
|
92
|
+
attn_config = config.block_config(0).attn_config
|
93
|
+
self.rope_cache = attn_utils.build_rope_cache(
|
94
|
+
size=config.max_seq_len,
|
95
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
96
|
+
base=10_000,
|
97
|
+
condense_ratio=1,
|
98
|
+
dtype=torch.float32,
|
99
|
+
device=torch.device('cpu'),
|
100
|
+
)
|
101
|
+
self.mask_cache = attn_utils.build_causal_mask_cache(
|
102
|
+
size=config.max_seq_len, dtype=torch.float32, device=torch.device('cpu')
|
103
|
+
)
|
104
|
+
self.config = config
|
105
|
+
|
106
|
+
@torch.inference_mode
|
107
|
+
def forward(self, idx: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
|
108
|
+
x = self.tok_embedding(idx)
|
109
|
+
cos, sin = self.rope_cache
|
110
|
+
|
111
|
+
cos = cos.index_select(0, input_pos)
|
112
|
+
sin = sin.index_select(0, input_pos)
|
113
|
+
mask = self.mask_cache.index_select(2, input_pos)
|
114
|
+
mask = mask[:, :, :, : self.config.max_seq_len]
|
115
|
+
|
116
|
+
x = self.transformer_block(x, (cos, sin), mask, input_pos)
|
117
|
+
x = self.final_norm(x)
|
118
|
+
res = self.lm_head(x)
|
119
|
+
return res
|
120
|
+
|
121
|
+
|
73
122
|
def get_model_config() -> cfg.ModelConfig:
|
74
123
|
attn_config = cfg.AttentionConfig(
|
75
|
-
num_heads=32,
|
124
|
+
num_heads=32,
|
125
|
+
head_dim=4,
|
126
|
+
num_query_groups=4,
|
127
|
+
rotary_percentage=1.0,
|
128
|
+
enable_kv_cache=False,
|
76
129
|
)
|
77
130
|
ff_config = cfg.FeedForwardConfig(
|
78
131
|
type=cfg.FeedForwardType.GATED,
|
@@ -80,43 +133,18 @@ def get_model_config() -> cfg.ModelConfig:
|
|
80
133
|
intermediate_size=256,
|
81
134
|
)
|
82
135
|
norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
|
136
|
+
block_config = cfg.TransformerBlockConfig(
|
137
|
+
attn_config=attn_config,
|
138
|
+
ff_config=ff_config,
|
139
|
+
pre_attention_norm_config=norm_config,
|
140
|
+
post_attention_norm_config=norm_config,
|
141
|
+
)
|
83
142
|
config = cfg.ModelConfig(
|
84
143
|
vocab_size=400,
|
85
144
|
num_layers=1,
|
86
145
|
max_seq_len=KV_CACHE_MAX_LEN,
|
87
146
|
embedding_dim=128,
|
88
|
-
|
89
|
-
ff_config=ff_config,
|
90
|
-
pre_attention_norm_config=norm_config,
|
91
|
-
pre_ff_norm_config=norm_config,
|
147
|
+
block_configs=block_config,
|
92
148
|
final_norm_config=norm_config,
|
93
149
|
)
|
94
150
|
return config
|
95
|
-
|
96
|
-
|
97
|
-
def define_and_run() -> None:
|
98
|
-
model = ToySingleLayerModel(get_model_config())
|
99
|
-
idx = torch.unsqueeze(torch.arange(0, KV_CACHE_MAX_LEN), 0)
|
100
|
-
input_pos = torch.arange(0, KV_CACHE_MAX_LEN)
|
101
|
-
print('running an inference')
|
102
|
-
print(
|
103
|
-
model.forward(
|
104
|
-
idx,
|
105
|
-
input_pos,
|
106
|
-
)
|
107
|
-
)
|
108
|
-
|
109
|
-
# Convert model to tflite.
|
110
|
-
print('converting model to tflite')
|
111
|
-
edge_model = ai_edge_torch.convert(
|
112
|
-
model,
|
113
|
-
(
|
114
|
-
idx,
|
115
|
-
input_pos,
|
116
|
-
),
|
117
|
-
)
|
118
|
-
edge_model.export('/tmp/toy_model.tflite')
|
119
|
-
|
120
|
-
|
121
|
-
if __name__ == '__main__':
|
122
|
-
define_and_run()
|
@@ -12,24 +12,24 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
|
-
# A toy example which has basic transformer block (w/ KV-Cache).
|
16
|
-
from typing import List, Tuple
|
17
15
|
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
import torch_xla
|
16
|
+
"""A toy example which has basic transformer block (w/ externalized KV-Cache)."""
|
17
|
+
|
18
|
+
from typing import Tuple
|
22
19
|
|
23
|
-
import
|
24
|
-
from ai_edge_torch.generative.layers
|
20
|
+
from absl import app
|
21
|
+
from ai_edge_torch.generative.layers import attention
|
22
|
+
from ai_edge_torch.generative.layers import builder
|
23
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
25
24
|
import ai_edge_torch.generative.layers.attention_utils as attn_utils
|
26
|
-
import ai_edge_torch.generative.layers.builder as builder
|
27
25
|
import ai_edge_torch.generative.layers.model_config as cfg
|
26
|
+
import torch
|
27
|
+
from torch import nn
|
28
28
|
|
29
29
|
RoPECache = Tuple[torch.Tensor, torch.Tensor]
|
30
30
|
|
31
31
|
|
32
|
-
class
|
32
|
+
class ToyModelWithKVCache(torch.nn.Module):
|
33
33
|
|
34
34
|
def __init__(self, config: cfg.ModelConfig) -> None:
|
35
35
|
super().__init__()
|
@@ -37,16 +37,20 @@ class ToyModelWithKV(torch.nn.Module):
|
|
37
37
|
config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
|
38
38
|
)
|
39
39
|
self.tok_embedding = nn.Embedding(config.vocab_size, config.embedding_dim)
|
40
|
+
# Toy model has only one block config.
|
41
|
+
block_config = config.block_config(0)
|
40
42
|
self.transformer_blocks = nn.ModuleList(
|
41
|
-
TransformerBlock(
|
43
|
+
attention.TransformerBlock(block_config, config)
|
44
|
+
for _ in range(config.num_layers)
|
42
45
|
)
|
43
46
|
self.final_norm = builder.build_norm(
|
44
47
|
config.embedding_dim,
|
45
48
|
config.final_norm_config,
|
46
49
|
)
|
50
|
+
attn_config = block_config.attn_config
|
47
51
|
self.rope_cache = attn_utils.build_rope_cache(
|
48
52
|
size=config.max_seq_len,
|
49
|
-
dim=int(
|
53
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
50
54
|
base=10_000,
|
51
55
|
condense_ratio=1,
|
52
56
|
dtype=torch.float32,
|
@@ -57,29 +61,37 @@ class ToyModelWithKV(torch.nn.Module):
|
|
57
61
|
)
|
58
62
|
self.config = config
|
59
63
|
|
60
|
-
|
61
|
-
|
62
|
-
|
64
|
+
def forward(
|
65
|
+
self,
|
66
|
+
tokens: torch.Tensor,
|
67
|
+
input_pos: torch.Tensor,
|
68
|
+
kv_cache: kv_utils.KVCache,
|
69
|
+
) -> Tuple[torch.Tensor, kv_utils.KVCache]:
|
70
|
+
x = self.tok_embedding(tokens)
|
63
71
|
cos, sin = self.rope_cache
|
64
72
|
cos = cos.index_select(0, input_pos)
|
65
73
|
sin = sin.index_select(0, input_pos)
|
66
74
|
mask = self.mask_cache.index_select(2, input_pos)
|
67
75
|
mask = mask[:, :, :, : self.config.max_seq_len]
|
68
|
-
for i, block in enumerate(self.transformer_blocks):
|
69
|
-
x = block(x, (cos, sin), mask, input_pos)
|
70
|
-
x = self.final_norm(x)
|
71
|
-
return self.lm_head(x)
|
72
76
|
|
77
|
+
updated_kv_entires = []
|
78
|
+
for i, block in enumerate(self.transformer_blocks):
|
79
|
+
kv_entry = kv_cache.caches[i] if kv_cache else None
|
80
|
+
x, kv_entry = block(x, (cos, sin), mask, input_pos, kv_entry)
|
81
|
+
if kv_entry:
|
82
|
+
updated_kv_entires.append(kv_entry)
|
73
83
|
|
74
|
-
|
75
|
-
|
76
|
-
|
77
|
-
return stablehlo_gm.get_stablehlo_text()
|
84
|
+
x = self.final_norm(x)
|
85
|
+
updated_kv_cache = kv_utils.KVCache(tuple(updated_kv_entires))
|
86
|
+
return {'logits': self.lm_head(x), 'kv_cache': updated_kv_cache}
|
78
87
|
|
79
88
|
|
80
89
|
def get_model_config() -> cfg.ModelConfig:
|
81
90
|
attn_config = cfg.AttentionConfig(
|
82
|
-
num_heads=32,
|
91
|
+
num_heads=32,
|
92
|
+
head_dim=4,
|
93
|
+
num_query_groups=4,
|
94
|
+
rotary_percentage=1.0,
|
83
95
|
)
|
84
96
|
ff_config = cfg.FeedForwardConfig(
|
85
97
|
type=cfg.FeedForwardType.GATED,
|
@@ -87,15 +99,18 @@ def get_model_config() -> cfg.ModelConfig:
|
|
87
99
|
intermediate_size=256,
|
88
100
|
)
|
89
101
|
norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
|
102
|
+
block_config = cfg.TransformerBlockConfig(
|
103
|
+
attn_config=attn_config,
|
104
|
+
ff_config=ff_config,
|
105
|
+
pre_attention_norm_config=norm_config,
|
106
|
+
post_attention_norm_config=norm_config,
|
107
|
+
)
|
90
108
|
config = cfg.ModelConfig(
|
91
109
|
vocab_size=150,
|
92
110
|
num_layers=2,
|
93
|
-
max_seq_len=
|
111
|
+
max_seq_len=100,
|
94
112
|
embedding_dim=128,
|
95
|
-
|
96
|
-
ff_config=ff_config,
|
97
|
-
pre_attention_norm_config=norm_config,
|
98
|
-
pre_ff_norm_config=norm_config,
|
113
|
+
block_configs=block_config,
|
99
114
|
final_norm_config=norm_config,
|
100
115
|
enable_hlfb=True,
|
101
116
|
)
|
@@ -103,41 +118,12 @@ def get_model_config() -> cfg.ModelConfig:
|
|
103
118
|
|
104
119
|
|
105
120
|
def get_sample_prefill_inputs() -> Tuple[torch.Tensor, torch.Tensor]:
|
106
|
-
|
107
|
-
input_pos = torch.arange(0, 100)
|
108
|
-
return
|
121
|
+
tokens = torch.unsqueeze(torch.arange(0, 100, dtype=torch.int), 0)
|
122
|
+
input_pos = torch.arange(0, 100, dtype=torch.int)
|
123
|
+
return tokens, input_pos
|
109
124
|
|
110
125
|
|
111
126
|
def get_sample_decode_inputs() -> Tuple[torch.Tensor, torch.Tensor]:
|
112
|
-
|
113
|
-
input_pos = torch.tensor([10]
|
114
|
-
return
|
115
|
-
|
116
|
-
|
117
|
-
def define_and_run() -> None:
|
118
|
-
dump_mlir = False
|
119
|
-
|
120
|
-
config = get_model_config()
|
121
|
-
model = ToyModelWithKV(config)
|
122
|
-
print('running an inference')
|
123
|
-
idx, input_pos = get_sample_prefill_inputs()
|
124
|
-
decode_idx, decode_input_pos = get_sample_decode_inputs()
|
125
|
-
print(model.forward(idx, input_pos))
|
126
|
-
|
127
|
-
if dump_mlir:
|
128
|
-
mlir_text = _export_stablehlo_mlir(model, (idx, input_pos))
|
129
|
-
with open('/tmp/toy_model_with_kv.stablehlo.mlir', 'w') as f:
|
130
|
-
f.write(mlir_text)
|
131
|
-
|
132
|
-
# Convert model to tflite with 2 signatures (prefill + decode).
|
133
|
-
print('converting toy model to tflite with 2 signatures (prefill + decode)')
|
134
|
-
edge_model = (
|
135
|
-
ai_edge_torch.signature('prefill', model, (idx, input_pos))
|
136
|
-
.signature('decode', model, (decode_idx, decode_input_pos))
|
137
|
-
.convert()
|
138
|
-
)
|
139
|
-
edge_model.export('/tmp/toy_kv_cache.tflite')
|
140
|
-
|
141
|
-
|
142
|
-
if __name__ == '__main__':
|
143
|
-
define_and_run()
|
127
|
+
tokens = torch.tensor([[1]], dtype=torch.int)
|
128
|
+
input_pos = torch.tensor([10])
|
129
|
+
return tokens, input_pos
|
@@ -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
|
+
# ==============================================================================
|