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
@@ -12,43 +12,38 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
|
-
# Example of building a Gemma model.
|
16
15
|
|
17
|
-
|
18
|
-
from pathlib import Path
|
16
|
+
"""Example of building a Gemma1 model."""
|
19
17
|
|
20
|
-
|
21
|
-
import
|
22
|
-
|
23
|
-
|
24
|
-
from ai_edge_torch.generative.layers.attention import TransformerBlock
|
18
|
+
from ai_edge_torch.generative.layers import attention
|
19
|
+
from ai_edge_torch.generative.layers import builder
|
20
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
25
21
|
import ai_edge_torch.generative.layers.attention_utils as attn_utils
|
26
|
-
import ai_edge_torch.generative.layers.builder as builder
|
27
22
|
import ai_edge_torch.generative.layers.model_config as cfg
|
28
23
|
import ai_edge_torch.generative.utilities.loader as loading_utils
|
24
|
+
import torch
|
25
|
+
from torch import nn
|
29
26
|
|
30
27
|
TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
|
31
28
|
ff_up_proj="model.layers.{}.mlp.up_proj",
|
32
29
|
ff_down_proj="model.layers.{}.mlp.down_proj",
|
33
30
|
ff_gate_proj="model.layers.{}.mlp.gate_proj",
|
34
|
-
|
35
|
-
attn_key_proj="model.layers.{}.self_attn.k_proj",
|
36
|
-
attn_value_proj="model.layers.{}.self_attn.v_proj",
|
31
|
+
attn_fused_qkv_proj="model.layers.{}.self_attn.qkv_proj",
|
37
32
|
attn_output_proj="model.layers.{}.self_attn.o_proj",
|
38
33
|
pre_attn_norm="model.layers.{}.input_layernorm",
|
39
|
-
|
40
|
-
embedding="
|
34
|
+
post_attn_norm="model.layers.{}.post_attention_layernorm",
|
35
|
+
embedding="embedder",
|
41
36
|
final_norm="model.norm",
|
42
37
|
lm_head=None,
|
43
38
|
)
|
44
39
|
|
45
40
|
|
46
41
|
class Gemma(nn.Module):
|
42
|
+
"""A Gemma model built from the Edge Generative API layers."""
|
47
43
|
|
48
44
|
def __init__(self, config: cfg.ModelConfig):
|
49
45
|
super().__init__()
|
50
46
|
|
51
|
-
self.config = config
|
52
47
|
# Construct model layers.
|
53
48
|
self.tok_embedding = nn.Embedding(
|
54
49
|
config.vocab_size, config.embedding_dim, padding_idx=0
|
@@ -60,35 +55,48 @@ class Gemma(nn.Module):
|
|
60
55
|
)
|
61
56
|
# Gemma re-uses the embedding as the head projection layer.
|
62
57
|
self.lm_head.weight.data = self.tok_embedding.weight.data
|
58
|
+
# Gemma has only one block config.
|
59
|
+
block_config = config.block_config(0)
|
63
60
|
self.transformer_blocks = nn.ModuleList(
|
64
|
-
TransformerBlock(
|
61
|
+
attention.TransformerBlock(block_config, config)
|
62
|
+
for _ in range(config.num_layers)
|
65
63
|
)
|
66
64
|
self.final_norm = builder.build_norm(
|
67
65
|
config.embedding_dim,
|
68
66
|
config.final_norm_config,
|
69
67
|
)
|
68
|
+
attn_config = block_config.attn_config
|
70
69
|
self.rope_cache = attn_utils.build_rope_cache(
|
71
70
|
size=config.kv_cache_max,
|
72
|
-
dim=int(
|
71
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
73
72
|
base=10_000,
|
74
73
|
condense_ratio=1,
|
75
74
|
dtype=torch.float32,
|
76
75
|
device=torch.device("cpu"),
|
77
76
|
)
|
78
77
|
self.mask_cache = attn_utils.build_causal_mask_cache(
|
79
|
-
size=config.kv_cache_max,
|
78
|
+
size=config.kv_cache_max,
|
79
|
+
dtype=torch.float32,
|
80
|
+
device=torch.device("cpu"),
|
80
81
|
)
|
81
82
|
self.config = config
|
82
83
|
|
83
|
-
# The model's forward function takes in additional k/v cache tensors
|
84
|
-
# and returns the updated k/v cache tensors to the caller.
|
85
|
-
# This can be eliminated if we handle k/v cache updates inside the model itself.
|
86
84
|
@torch.inference_mode
|
87
|
-
def forward(
|
88
|
-
|
89
|
-
|
90
|
-
|
91
|
-
|
85
|
+
def forward(
|
86
|
+
self,
|
87
|
+
tokens: torch.Tensor,
|
88
|
+
input_pos: torch.Tensor,
|
89
|
+
kv_cache: kv_utils.KVCache,
|
90
|
+
) -> dict[torch.Tensor, kv_utils.KVCache]:
|
91
|
+
_, seq_len = tokens.size()
|
92
|
+
assert self.config.max_seq_len >= seq_len, (
|
93
|
+
f"Cannot forward sequence of length {seq_len}, max seq length is only"
|
94
|
+
f" {self.config.max_seq_len}"
|
95
|
+
)
|
96
|
+
assert len(self.transformer_blocks) == len(kv_cache.caches), (
|
97
|
+
"The number of transformer blocks and the number of KV cache entries"
|
98
|
+
" must be the same."
|
99
|
+
)
|
92
100
|
|
93
101
|
cos, sin = self.rope_cache
|
94
102
|
cos = cos.index_select(0, input_pos)
|
@@ -97,20 +105,35 @@ class Gemma(nn.Module):
|
|
97
105
|
mask = mask[:, :, :, : self.config.kv_cache_max]
|
98
106
|
|
99
107
|
# token embeddings of shape (b, t, n_embd)
|
100
|
-
x = self.tok_embedding(
|
108
|
+
x = self.tok_embedding(tokens)
|
101
109
|
x = x * (self.config.embedding_dim**0.5)
|
102
110
|
|
111
|
+
updated_kv_entires = []
|
103
112
|
for i, block in enumerate(self.transformer_blocks):
|
104
|
-
|
113
|
+
kv_entry = kv_cache.caches[i] if kv_cache else None
|
114
|
+
x, kv_entry = block(x, (cos, sin), mask, input_pos, kv_entry)
|
115
|
+
if kv_entry:
|
116
|
+
updated_kv_entires.append(kv_entry)
|
117
|
+
updated_kv_cache = kv_utils.KVCache(tuple(updated_kv_entires))
|
105
118
|
|
106
119
|
x = self.final_norm(x)
|
107
|
-
|
108
|
-
return
|
120
|
+
logits = self.lm_head(x) # (b, t, vocab_size)
|
121
|
+
return {"logits": logits, "kv_cache": updated_kv_cache}
|
109
122
|
|
110
123
|
|
111
124
|
def get_model_config_2b(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
|
125
|
+
"""Returns the model config for a Gemma 2B model.
|
126
|
+
|
127
|
+
Args:
|
128
|
+
kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
|
129
|
+
is 1024.
|
130
|
+
|
131
|
+
Returns:
|
132
|
+
The model config for a Gemma 2B model.
|
133
|
+
"""
|
112
134
|
attn_config = cfg.AttentionConfig(
|
113
135
|
num_heads=8,
|
136
|
+
head_dim=256,
|
114
137
|
num_query_groups=1,
|
115
138
|
rotary_percentage=1.0,
|
116
139
|
)
|
@@ -124,51 +147,42 @@ def get_model_config_2b(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
|
|
124
147
|
epsilon=1e-6,
|
125
148
|
zero_centered=True,
|
126
149
|
)
|
150
|
+
block_config = cfg.TransformerBlockConfig(
|
151
|
+
attn_config=attn_config,
|
152
|
+
ff_config=ff_config,
|
153
|
+
pre_attention_norm_config=norm_config,
|
154
|
+
post_attention_norm_config=norm_config,
|
155
|
+
)
|
127
156
|
config = cfg.ModelConfig(
|
128
157
|
vocab_size=256000,
|
129
158
|
num_layers=18,
|
130
159
|
max_seq_len=8192,
|
131
160
|
embedding_dim=2048,
|
132
161
|
kv_cache_max_len=kv_cache_max_len,
|
133
|
-
|
134
|
-
ff_config=ff_config,
|
135
|
-
pre_attention_norm_config=norm_config,
|
136
|
-
pre_ff_norm_config=norm_config,
|
162
|
+
block_configs=block_config,
|
137
163
|
final_norm_config=norm_config,
|
138
|
-
parallel_residual=False,
|
139
164
|
lm_head_use_bias=False,
|
140
165
|
enable_hlfb=True,
|
141
166
|
)
|
142
167
|
return config
|
143
168
|
|
144
169
|
|
145
|
-
def
|
146
|
-
config = get_model_config_2b()
|
170
|
+
def get_fake_model_config(kv_cache_max_len: int = 128) -> cfg.ModelConfig:
|
171
|
+
config = get_model_config_2b(kv_cache_max_len)
|
172
|
+
# Gemma has only one block config.
|
173
|
+
config.block_config(0).ff_config.intermediate_size = 128
|
174
|
+
config.vocab_size = 128
|
147
175
|
config.num_layers = 2
|
176
|
+
config.max_seq_len = 2 * kv_cache_max_len
|
148
177
|
return config
|
149
178
|
|
150
179
|
|
151
|
-
def build_2b_model(checkpoint_path, **kwargs) -> nn.Module:
|
180
|
+
def build_2b_model(checkpoint_path: str, **kwargs) -> nn.Module:
|
152
181
|
config = get_model_config_2b(**kwargs)
|
153
182
|
model = Gemma(config)
|
154
183
|
loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
|
155
|
-
#
|
184
|
+
# Since embedding and lm-head use the same weight, we need to set strict
|
156
185
|
# to False.
|
157
186
|
loader.load(model, strict=False)
|
187
|
+
model.eval()
|
158
188
|
return model
|
159
|
-
|
160
|
-
|
161
|
-
def define_and_run_2b() -> None:
|
162
|
-
kv_cache_max_len = 1024
|
163
|
-
checkpoint_path = os.path.join(Path.home(), "Downloads/llm_data/gemma-2b")
|
164
|
-
model = build_2b_model(checkpoint_path, kv_cache_max_len=kv_cache_max_len)
|
165
|
-
idx = torch.from_numpy(np.array([[1, 2, 3, 4]]))
|
166
|
-
tokens = torch.full((1, kv_cache_max_len), 0, dtype=torch.long, device="cpu")
|
167
|
-
tokens[0, :4] = idx
|
168
|
-
input_pos = torch.arange(0, kv_cache_max_len)
|
169
|
-
print("running an inference")
|
170
|
-
print(model.forward(tokens, input_pos))
|
171
|
-
|
172
|
-
|
173
|
-
if __name__ == "__main__":
|
174
|
-
define_and_run_2b()
|
@@ -0,0 +1,267 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
"""Example of building a Gemma2 model."""
|
17
|
+
|
18
|
+
import os
|
19
|
+
from typing import Optional, Tuple
|
20
|
+
|
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
|
24
|
+
import ai_edge_torch.generative.layers.attention_utils as attn_utils
|
25
|
+
import ai_edge_torch.generative.layers.model_config as cfg
|
26
|
+
import ai_edge_torch.generative.utilities.loader as loading_utils
|
27
|
+
import torch
|
28
|
+
from torch import nn
|
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_fused_qkv_proj="model.layers.{}.self_attn.qkv_proj",
|
35
|
+
attn_output_proj="model.layers.{}.self_attn.o_proj",
|
36
|
+
pre_attn_norm="model.layers.{}.input_layernorm",
|
37
|
+
post_attn_norm="model.layers.{}.post_attention_layernorm",
|
38
|
+
pre_ff_norm="model.layers.{}.pre_feedforward_layernorm",
|
39
|
+
post_ff_norm="model.layers.{}.post_feedforward_layernorm",
|
40
|
+
embedding="embedder",
|
41
|
+
final_norm="model.norm",
|
42
|
+
lm_head=None,
|
43
|
+
)
|
44
|
+
|
45
|
+
|
46
|
+
class Gemma2Block(attention.TransformerBlock):
|
47
|
+
|
48
|
+
def forward(
|
49
|
+
self,
|
50
|
+
x: torch.Tensor,
|
51
|
+
rope: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
52
|
+
mask: Optional[torch.Tensor] = None,
|
53
|
+
input_pos: Optional[torch.Tensor] = None,
|
54
|
+
kv_cache: kv_utils.KVCacheEntry = None,
|
55
|
+
) -> Tuple[torch.Tensor, Optional[kv_utils.KVCacheEntry]]:
|
56
|
+
"""Forward function of the Gemma2Block.
|
57
|
+
|
58
|
+
Exactly the same as TransformerBlock but we call the post-attention norm
|
59
|
+
immediately after attention and not after the residual pointwise addition.
|
60
|
+
|
61
|
+
Args:
|
62
|
+
x (torch.Tensor): the input tensor.
|
63
|
+
rope (Tuple[torch.Tensor, torch.Tensor]): the input rope tensor.
|
64
|
+
mask (torch.Tensor): the optional mask tensor.
|
65
|
+
input_pos (torch.Tensor): the optional input position tensor.
|
66
|
+
kv_cache (KVCacheEntry): the optional kv cache entry.
|
67
|
+
|
68
|
+
Returns:
|
69
|
+
output activation from this transformer block, and updated kv cache (if
|
70
|
+
passed in).
|
71
|
+
"""
|
72
|
+
|
73
|
+
x_norm = self.pre_atten_norm(x)
|
74
|
+
attn_out, kv = self.atten_func(x_norm, rope, mask, input_pos, kv_cache)
|
75
|
+
attn_out_norm = self.post_atten_norm(attn_out)
|
76
|
+
x = x + attn_out_norm
|
77
|
+
output = x + self.ff(x)
|
78
|
+
return output, kv
|
79
|
+
|
80
|
+
|
81
|
+
class Gemma2(nn.Module):
|
82
|
+
"""A Gemma2 model built from the Edge Generative API layers."""
|
83
|
+
|
84
|
+
def __init__(self, config: cfg.ModelConfig):
|
85
|
+
super().__init__()
|
86
|
+
|
87
|
+
# Construct model layers.
|
88
|
+
self.tok_embedding = nn.Embedding(
|
89
|
+
config.vocab_size, config.embedding_dim, padding_idx=0
|
90
|
+
)
|
91
|
+
self.lm_head = nn.Linear(
|
92
|
+
config.embedding_dim,
|
93
|
+
config.vocab_size,
|
94
|
+
bias=config.lm_head_use_bias,
|
95
|
+
)
|
96
|
+
# Gemma2 re-uses the embedding as the head projection layer.
|
97
|
+
self.lm_head.weight.data = self.tok_embedding.weight.data
|
98
|
+
self.transformer_blocks = nn.ModuleList(
|
99
|
+
Gemma2Block(config.block_config(idx), config)
|
100
|
+
for idx in range(config.num_layers)
|
101
|
+
)
|
102
|
+
self.final_norm = builder.build_norm(
|
103
|
+
config.embedding_dim,
|
104
|
+
config.final_norm_config,
|
105
|
+
)
|
106
|
+
# Gemma2 has same hyper parameters for each layer except for attention
|
107
|
+
# types. Use the first layer.
|
108
|
+
attn_config = config.block_config(0).attn_config
|
109
|
+
self.rope_cache = attn_utils.build_rope_cache(
|
110
|
+
size=config.kv_cache_max,
|
111
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
112
|
+
base=10_000,
|
113
|
+
condense_ratio=1,
|
114
|
+
dtype=torch.float32,
|
115
|
+
device=torch.device("cpu"),
|
116
|
+
)
|
117
|
+
self.mask_cache = attn_utils.build_causal_mask_cache(
|
118
|
+
size=config.kv_cache_max,
|
119
|
+
dtype=torch.float32,
|
120
|
+
device=torch.device("cpu"),
|
121
|
+
)
|
122
|
+
self.sliding_window_mask_cache = attn_utils.build_sliding_window_mask_cache(
|
123
|
+
size=config.kv_cache_max,
|
124
|
+
window_size=attn_config.sliding_window_size,
|
125
|
+
dtype=torch.float32,
|
126
|
+
device=torch.device("cpu"),
|
127
|
+
)
|
128
|
+
self.config = config
|
129
|
+
|
130
|
+
def get_attention_mask(
|
131
|
+
self, attn_type: cfg.AttentionType, input_pos: torch.Tensor
|
132
|
+
) -> torch.Tensor:
|
133
|
+
if attn_type == cfg.AttentionType.LOCAL_SLIDING:
|
134
|
+
return self.sliding_window_mask_cache.index_select(2, input_pos)
|
135
|
+
return self.mask_cache.index_select(2, input_pos)
|
136
|
+
|
137
|
+
@torch.inference_mode
|
138
|
+
def forward(
|
139
|
+
self,
|
140
|
+
tokens: torch.Tensor,
|
141
|
+
input_pos: torch.Tensor,
|
142
|
+
kv_cache: kv_utils.KVCache,
|
143
|
+
) -> dict[torch.Tensor, kv_utils.KVCache]:
|
144
|
+
_, seq_len = tokens.size()
|
145
|
+
assert self.config.max_seq_len >= seq_len, (
|
146
|
+
f"Cannot forward sequence of length {seq_len}, max seq length is only"
|
147
|
+
f" {self.config.max_seq_len}"
|
148
|
+
)
|
149
|
+
assert len(self.transformer_blocks) == len(kv_cache.caches), (
|
150
|
+
"The number of transformer blocks and the number of KV cache entries"
|
151
|
+
" must be the same."
|
152
|
+
)
|
153
|
+
|
154
|
+
cos, sin = self.rope_cache
|
155
|
+
cos = cos.index_select(0, input_pos)
|
156
|
+
sin = sin.index_select(0, input_pos)
|
157
|
+
|
158
|
+
# token embeddings of shape (b, t, n_embd)
|
159
|
+
x = self.tok_embedding(tokens)
|
160
|
+
x = x * (self.config.embedding_dim**0.5)
|
161
|
+
|
162
|
+
updated_kv_entires = []
|
163
|
+
for i, block in enumerate(self.transformer_blocks):
|
164
|
+
mask = self.get_attention_mask(
|
165
|
+
block.config.attn_config.attn_type, input_pos
|
166
|
+
)
|
167
|
+
kv_entry = kv_cache.caches[i] if kv_cache else None
|
168
|
+
x, kv_entry = block(x, (cos, sin), mask, input_pos, kv_entry)
|
169
|
+
if kv_entry:
|
170
|
+
updated_kv_entires.append(kv_entry)
|
171
|
+
updated_kv_cache = kv_utils.KVCache(tuple(updated_kv_entires))
|
172
|
+
|
173
|
+
x = self.final_norm(x)
|
174
|
+
res = self.lm_head(x) # (b, t, vocab_size)
|
175
|
+
if self.config.final_logit_softcap is not None:
|
176
|
+
res = res / self.config.final_logit_softcap
|
177
|
+
res = torch.tanh(res)
|
178
|
+
res = res * self.config.final_logit_softcap
|
179
|
+
|
180
|
+
return {"logits": res, "kv_cache": updated_kv_cache}
|
181
|
+
|
182
|
+
|
183
|
+
def get_model_config_2b(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
|
184
|
+
"""Returns the model config for a Gemma2 2B model.
|
185
|
+
|
186
|
+
Args:
|
187
|
+
kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
|
188
|
+
is 1024.
|
189
|
+
|
190
|
+
Returns:
|
191
|
+
The model config for a Gemma 2B model.
|
192
|
+
"""
|
193
|
+
norm_config = cfg.NormalizationConfig(
|
194
|
+
type=cfg.NormalizationType.RMS_NORM,
|
195
|
+
epsilon=1e-6,
|
196
|
+
zero_centered=True,
|
197
|
+
)
|
198
|
+
ff_config = cfg.FeedForwardConfig(
|
199
|
+
type=cfg.FeedForwardType.GATED,
|
200
|
+
activation=cfg.ActivationConfig(cfg.ActivationType.GELU_TANH),
|
201
|
+
intermediate_size=9216,
|
202
|
+
pre_ff_norm_config=norm_config,
|
203
|
+
post_ff_norm_config=norm_config,
|
204
|
+
)
|
205
|
+
|
206
|
+
def get_block_config(idx: int) -> cfg.TransformerBlockConfig:
|
207
|
+
attn_config = cfg.AttentionConfig(
|
208
|
+
num_heads=8,
|
209
|
+
head_dim=256,
|
210
|
+
num_query_groups=4,
|
211
|
+
rotary_percentage=1.0,
|
212
|
+
qkv_transpose_before_split=True,
|
213
|
+
logit_softcap=50.0,
|
214
|
+
sliding_window_size=4096,
|
215
|
+
attn_type=(
|
216
|
+
cfg.AttentionType.GLOBAL
|
217
|
+
if idx % 2 == 0
|
218
|
+
else cfg.AttentionType.LOCAL_SLIDING
|
219
|
+
),
|
220
|
+
)
|
221
|
+
return cfg.TransformerBlockConfig(
|
222
|
+
attn_config=attn_config,
|
223
|
+
ff_config=ff_config,
|
224
|
+
pre_attention_norm_config=norm_config,
|
225
|
+
post_attention_norm_config=norm_config,
|
226
|
+
)
|
227
|
+
|
228
|
+
num_layers = 26
|
229
|
+
config = cfg.ModelConfig(
|
230
|
+
vocab_size=256000,
|
231
|
+
num_layers=num_layers,
|
232
|
+
max_seq_len=8192,
|
233
|
+
embedding_dim=2304,
|
234
|
+
kv_cache_max_len=kv_cache_max_len,
|
235
|
+
block_configs=[get_block_config(i) for i in range(num_layers)],
|
236
|
+
final_norm_config=norm_config,
|
237
|
+
lm_head_use_bias=False,
|
238
|
+
enable_hlfb=True,
|
239
|
+
final_logit_softcap=30.0,
|
240
|
+
)
|
241
|
+
return config
|
242
|
+
|
243
|
+
|
244
|
+
def get_fake_model_config(kv_cache_max_len: int = 128) -> cfg.ModelConfig:
|
245
|
+
config = get_model_config_2b(kv_cache_max_len)
|
246
|
+
config.vocab_size = 128
|
247
|
+
config.num_layers = 2
|
248
|
+
config.max_seq_len = 2 * kv_cache_max_len
|
249
|
+
config.embedding_dim = 128
|
250
|
+
config.block_configs = config.block_configs[: config.num_layers]
|
251
|
+
for block_config in config.block_configs:
|
252
|
+
block_config.attn_config.num_heads = 4
|
253
|
+
block_config.attn_config.head_dim = 64
|
254
|
+
block_config.attn_config.sliding_window_size = 64
|
255
|
+
block_config.ff_config.intermediate_size = 128
|
256
|
+
return config
|
257
|
+
|
258
|
+
|
259
|
+
def build_2b_model(checkpoint_path: str, **kwargs) -> nn.Module:
|
260
|
+
config = get_model_config_2b(**kwargs)
|
261
|
+
model = Gemma2(config)
|
262
|
+
loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
|
263
|
+
# Since embedding and lm-head use the same weight, we need to set strict
|
264
|
+
# to False.
|
265
|
+
loader.load(model, strict=False)
|
266
|
+
model.eval()
|
267
|
+
return model
|
@@ -0,0 +1,56 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
"""Verifies the reauthored Gemma1 model."""
|
17
|
+
|
18
|
+
import logging
|
19
|
+
from absl import app
|
20
|
+
from absl import flags
|
21
|
+
from ai_edge_torch.generative.examples.gemma import gemma1
|
22
|
+
from ai_edge_torch.generative.examples.gemma import verify_util
|
23
|
+
import kagglehub
|
24
|
+
|
25
|
+
|
26
|
+
_PROMPTS = flags.DEFINE_multi_string(
|
27
|
+
"prompts",
|
28
|
+
"What is the meaning of life?",
|
29
|
+
"The input prompts to generate answers.",
|
30
|
+
)
|
31
|
+
_MAX_NEW_TOKENS = flags.DEFINE_integer(
|
32
|
+
"max_new_tokens",
|
33
|
+
30,
|
34
|
+
"The maximum size of the generated tokens.",
|
35
|
+
)
|
36
|
+
|
37
|
+
|
38
|
+
def main(_):
|
39
|
+
checkpoint = kagglehub.model_download("google/gemma/pyTorch/2b-it")
|
40
|
+
|
41
|
+
logging.info("Building the reauthored model from: %s", checkpoint)
|
42
|
+
reauthored_model = gemma1.build_2b_model(checkpoint)
|
43
|
+
|
44
|
+
verify_util.verify_reauthored_gemma_model(
|
45
|
+
checkpoint=checkpoint,
|
46
|
+
variant="2b",
|
47
|
+
reauthored_model=reauthored_model,
|
48
|
+
weight_filename="gemma-2b-it.ckpt",
|
49
|
+
generate_prompts=_PROMPTS.value,
|
50
|
+
forward_input_ids=[[1, 2, 3, 4]],
|
51
|
+
max_new_tokens=_MAX_NEW_TOKENS.value,
|
52
|
+
)
|
53
|
+
|
54
|
+
|
55
|
+
if __name__ == "__main__":
|
56
|
+
app.run(main)
|
@@ -0,0 +1,57 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
"""Verifies the reauthored Gemma2 model."""
|
17
|
+
|
18
|
+
import logging
|
19
|
+
from absl import app
|
20
|
+
from absl import flags
|
21
|
+
from ai_edge_torch.generative.examples.gemma import gemma2
|
22
|
+
from ai_edge_torch.generative.examples.gemma import verify_util
|
23
|
+
from ai_edge_torch.generative.utilities import verifier
|
24
|
+
import kagglehub
|
25
|
+
|
26
|
+
|
27
|
+
_PROMPTS = flags.DEFINE_multi_string(
|
28
|
+
"prompts",
|
29
|
+
"What is the meaning of life?",
|
30
|
+
"The input prompts to generate answers.",
|
31
|
+
)
|
32
|
+
_MAX_NEW_TOKENS = flags.DEFINE_integer(
|
33
|
+
"max_new_tokens",
|
34
|
+
30,
|
35
|
+
"The maximum size of the generated tokens.",
|
36
|
+
)
|
37
|
+
|
38
|
+
|
39
|
+
def main(_):
|
40
|
+
checkpoint = kagglehub.model_download("google/gemma-2/pyTorch/gemma-2-2b-it")
|
41
|
+
|
42
|
+
logging.info("Building the reauthored model from: %s", checkpoint)
|
43
|
+
reauthored_model = gemma2.build_2b_model(checkpoint)
|
44
|
+
|
45
|
+
verify_util.verify_reauthored_gemma_model(
|
46
|
+
checkpoint=checkpoint,
|
47
|
+
variant="2b-v2",
|
48
|
+
reauthored_model=reauthored_model,
|
49
|
+
generate_prompts=_PROMPTS.value,
|
50
|
+
forward_input_ids=[[2, 651, 9456, 576, 573, 3520, 3858, 603, 235248]],
|
51
|
+
max_new_tokens=_MAX_NEW_TOKENS.value,
|
52
|
+
atol=1e-04,
|
53
|
+
)
|
54
|
+
|
55
|
+
|
56
|
+
if __name__ == "__main__":
|
57
|
+
app.run(main)
|