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
@@ -13,54 +13,56 @@
|
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
15
|
|
16
|
-
|
17
|
-
from pathlib import Path
|
16
|
+
"""Example of converting TinyLlama model to multi-signature tflite model."""
|
18
17
|
|
19
|
-
import
|
18
|
+
import os
|
19
|
+
import pathlib
|
20
20
|
|
21
|
-
import
|
21
|
+
from absl import app
|
22
|
+
from absl import flags
|
22
23
|
from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
|
23
|
-
from ai_edge_torch.generative.
|
24
|
+
from ai_edge_torch.generative.utilities import converter
|
24
25
|
|
26
|
+
_CHECKPOINT_PATH = flags.DEFINE_string(
|
27
|
+
'checkpoint_path',
|
28
|
+
os.path.join(pathlib.Path.home(), 'Downloads/llm_data/tiny_llama'),
|
29
|
+
'The path to the model checkpoint, or directory holding the checkpoint.',
|
30
|
+
)
|
31
|
+
_TFLITE_PATH = flags.DEFINE_string(
|
32
|
+
'tflite_path',
|
33
|
+
'/tmp/',
|
34
|
+
'The tflite file path to export.',
|
35
|
+
)
|
36
|
+
_PREFILL_SEQ_LEN = flags.DEFINE_integer(
|
37
|
+
'prefill_seq_len',
|
38
|
+
1024,
|
39
|
+
'The maximum size of prefill input tensor.',
|
40
|
+
)
|
41
|
+
_KV_CACHE_MAX_LEN = flags.DEFINE_integer(
|
42
|
+
'kv_cache_max_len',
|
43
|
+
1280,
|
44
|
+
'The maximum size of KV cache buffer, including both prefill and decode.',
|
45
|
+
)
|
46
|
+
_QUANTIZE = flags.DEFINE_bool(
|
47
|
+
'quantize',
|
48
|
+
True,
|
49
|
+
'Whether the model should be quantized.',
|
50
|
+
)
|
25
51
|
|
26
|
-
def convert_tiny_llama_to_tflite(
|
27
|
-
checkpoint_path: str,
|
28
|
-
prefill_seq_len: int = 512,
|
29
|
-
kv_cache_max_len: int = 1024,
|
30
|
-
quantize: bool = True,
|
31
|
-
):
|
32
|
-
"""An example method for converting TinyLlama model to multi-signature
|
33
|
-
tflite model.
|
34
52
|
|
35
|
-
|
36
|
-
checkpoint_path (str): The filepath to the model checkpoint, or directory holding the checkpoint.
|
37
|
-
prefill_seq_len (int, optional): The maximum size of prefill input tensor.
|
38
|
-
Defaults to 512.
|
39
|
-
kv_cache_max_len (int, optional): The maximum size of KV cache buffer,
|
40
|
-
including both prefill and decode. Defaults to 1024.
|
41
|
-
quantize (bool, optional): Whether the model should be quanized.
|
42
|
-
Defaults to True.
|
43
|
-
"""
|
53
|
+
def main(_):
|
44
54
|
pytorch_model = tiny_llama.build_model(
|
45
|
-
|
55
|
+
_CHECKPOINT_PATH.value, kv_cache_max_len=_KV_CACHE_MAX_LEN.value
|
46
56
|
)
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
edge_model = (
|
55
|
-
ai_edge_torch.signature(
|
56
|
-
'prefill', pytorch_model, (prefill_tokens, prefill_input_pos)
|
57
|
-
)
|
58
|
-
.signature('decode', pytorch_model, (decode_token, decode_input_pos))
|
59
|
-
.convert(quant_config=quant_config)
|
57
|
+
quant_suffix = 'q8' if _QUANTIZE.value else 'f32'
|
58
|
+
output_filename = f'tinyllama_{quant_suffix}_seq{_PREFILL_SEQ_LEN.value}_ekv{_KV_CACHE_MAX_LEN.value}.tflite'
|
59
|
+
converter.convert_to_tflite(
|
60
|
+
pytorch_model,
|
61
|
+
tflite_path=os.path.join(_TFLITE_PATH.value, output_filename),
|
62
|
+
prefill_seq_len=_PREFILL_SEQ_LEN.value,
|
63
|
+
quantize=_QUANTIZE.value,
|
60
64
|
)
|
61
|
-
edge_model.export(f'/tmp/tiny_llama_seq{prefill_seq_len}_kv{kv_cache_max_len}.tflite')
|
62
65
|
|
63
66
|
|
64
67
|
if __name__ == '__main__':
|
65
|
-
|
66
|
-
convert_tiny_llama_to_tflite(checkpoint_path)
|
68
|
+
app.run(main)
|
@@ -12,20 +12,17 @@
|
|
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 TinyLlama model from the Edge Generative API layers.
|
16
15
|
|
17
|
-
|
18
|
-
from pathlib import Path
|
16
|
+
"""Example of building a TinyLlama 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",
|
@@ -36,19 +33,19 @@ TENSOR_NAMES = loading_utils.ModelLoader.TensorNames(
|
|
36
33
|
attn_value_proj="model.layers.{}.self_attn.v_proj",
|
37
34
|
attn_output_proj="model.layers.{}.self_attn.o_proj",
|
38
35
|
pre_attn_norm="model.layers.{}.input_layernorm",
|
39
|
-
|
36
|
+
post_attn_norm="model.layers.{}.post_attention_layernorm",
|
40
37
|
embedding="model.embed_tokens",
|
41
38
|
final_norm="model.norm",
|
42
39
|
lm_head="lm_head",
|
43
40
|
)
|
44
41
|
|
45
42
|
|
46
|
-
class
|
43
|
+
class TinyLlama(nn.Module):
|
44
|
+
"""A TinyLlama model built from the Edge Generative API layers."""
|
47
45
|
|
48
46
|
def __init__(self, config: cfg.ModelConfig):
|
49
47
|
super().__init__()
|
50
48
|
|
51
|
-
self.config = config
|
52
49
|
# Construct model layers.
|
53
50
|
self.lm_head = nn.Linear(
|
54
51
|
config.embedding_dim, config.vocab_size, bias=config.lm_head_use_bias
|
@@ -56,35 +53,48 @@ class TinyLLamma(nn.Module):
|
|
56
53
|
self.tok_embedding = nn.Embedding(
|
57
54
|
config.vocab_size, config.embedding_dim, padding_idx=0
|
58
55
|
)
|
56
|
+
# TinyLlama has only one block config.
|
57
|
+
block_config = config.block_config(0)
|
59
58
|
self.transformer_blocks = nn.ModuleList(
|
60
|
-
TransformerBlock(
|
59
|
+
attention.TransformerBlock(block_config, config)
|
60
|
+
for _ in range(config.num_layers)
|
61
61
|
)
|
62
62
|
self.final_norm = builder.build_norm(
|
63
63
|
config.embedding_dim,
|
64
64
|
config.final_norm_config,
|
65
65
|
)
|
66
|
+
attn_config = block_config.attn_config
|
66
67
|
self.rope_cache = attn_utils.build_rope_cache(
|
67
68
|
size=config.kv_cache_max,
|
68
|
-
dim=int(
|
69
|
+
dim=int(attn_config.rotary_percentage * attn_config.head_dim),
|
69
70
|
base=10_000,
|
70
71
|
condense_ratio=1,
|
71
72
|
dtype=torch.float32,
|
72
73
|
device=torch.device("cpu"),
|
73
74
|
)
|
74
75
|
self.mask_cache = attn_utils.build_causal_mask_cache(
|
75
|
-
size=config.kv_cache_max,
|
76
|
+
size=config.kv_cache_max,
|
77
|
+
dtype=torch.float32,
|
78
|
+
device=torch.device("cpu"),
|
76
79
|
)
|
77
80
|
self.config = config
|
78
81
|
|
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
82
|
@torch.inference_mode
|
83
|
-
def forward(
|
84
|
-
|
85
|
-
|
86
|
-
|
87
|
-
|
83
|
+
def forward(
|
84
|
+
self,
|
85
|
+
tokens: torch.Tensor,
|
86
|
+
input_pos: torch.Tensor,
|
87
|
+
kv_cache: kv_utils.KVCache,
|
88
|
+
) -> dict[torch.Tensor, kv_utils.KVCache]:
|
89
|
+
_, seq_len = tokens.size()
|
90
|
+
assert self.config.max_seq_len >= seq_len, (
|
91
|
+
f"Cannot forward sequence of length {seq_len}, max seq length is only"
|
92
|
+
f" {self.config.max_seq_len}"
|
93
|
+
)
|
94
|
+
assert len(self.transformer_blocks) == len(kv_cache.caches), (
|
95
|
+
"The number of transformer blocks and the number of KV cache entries"
|
96
|
+
" must be the same."
|
97
|
+
)
|
88
98
|
|
89
99
|
cos, sin = self.rope_cache
|
90
100
|
cos = cos.index_select(0, input_pos)
|
@@ -92,21 +102,35 @@ class TinyLLamma(nn.Module):
|
|
92
102
|
mask = self.mask_cache.index_select(2, input_pos)
|
93
103
|
mask = mask[:, :, :, : self.config.kv_cache_max]
|
94
104
|
|
95
|
-
#
|
96
|
-
x = self.tok_embedding(
|
105
|
+
# token embeddings of shape (b, t, n_embd)
|
106
|
+
x = self.tok_embedding(tokens)
|
97
107
|
|
108
|
+
updated_kv_entires = []
|
98
109
|
for i, block in enumerate(self.transformer_blocks):
|
99
|
-
|
110
|
+
kv_entry = kv_cache.caches[i] if kv_cache else None
|
111
|
+
x, kv_entry = block(x, (cos, sin), mask, input_pos, kv_entry)
|
112
|
+
if kv_entry:
|
113
|
+
updated_kv_entires.append(kv_entry)
|
114
|
+
updated_kv_cache = kv_utils.KVCache(tuple(updated_kv_entires))
|
100
115
|
|
101
116
|
x = self.final_norm(x)
|
102
|
-
|
103
|
-
|
104
|
-
return res
|
117
|
+
logits = self.lm_head(x) # (b, t, vocab_size)
|
118
|
+
return {"logits": logits, "kv_cache": updated_kv_cache}
|
105
119
|
|
106
120
|
|
107
121
|
def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
|
122
|
+
"""Returns the model config for a TinyLlama model.
|
123
|
+
|
124
|
+
Args:
|
125
|
+
kv_cache_max_len (int): The maximum sequence length of the KV cache. Default
|
126
|
+
is 1024.
|
127
|
+
|
128
|
+
Returns:
|
129
|
+
The model config for a TinyLlama model.
|
130
|
+
"""
|
108
131
|
attn_config = cfg.AttentionConfig(
|
109
132
|
num_heads=32,
|
133
|
+
head_dim=64,
|
110
134
|
num_query_groups=4,
|
111
135
|
rotary_percentage=1.0,
|
112
136
|
)
|
@@ -116,49 +140,38 @@ def get_model_config(kv_cache_max_len: int = 1024) -> cfg.ModelConfig:
|
|
116
140
|
intermediate_size=5632,
|
117
141
|
)
|
118
142
|
norm_config = cfg.NormalizationConfig(type=cfg.NormalizationType.RMS_NORM)
|
143
|
+
block_config = cfg.TransformerBlockConfig(
|
144
|
+
attn_config=attn_config,
|
145
|
+
ff_config=ff_config,
|
146
|
+
pre_attention_norm_config=norm_config,
|
147
|
+
post_attention_norm_config=norm_config,
|
148
|
+
)
|
119
149
|
config = cfg.ModelConfig(
|
120
150
|
vocab_size=32000,
|
121
151
|
num_layers=22,
|
122
152
|
max_seq_len=2048,
|
123
153
|
embedding_dim=2048,
|
124
154
|
kv_cache_max_len=kv_cache_max_len,
|
125
|
-
|
126
|
-
ff_config=ff_config,
|
127
|
-
pre_attention_norm_config=norm_config,
|
128
|
-
pre_ff_norm_config=norm_config,
|
155
|
+
block_configs=block_config,
|
129
156
|
final_norm_config=norm_config,
|
130
157
|
enable_hlfb=True,
|
131
158
|
)
|
132
159
|
return config
|
133
160
|
|
134
161
|
|
135
|
-
def
|
136
|
-
config = get_model_config()
|
162
|
+
def get_fake_model_config(**kwargs) -> cfg.ModelConfig:
|
163
|
+
config = get_model_config(**kwargs)
|
137
164
|
config.vocab_size = 128
|
138
165
|
config.num_layers = 2
|
139
|
-
config.
|
166
|
+
# TinyLlama has only one block config.
|
167
|
+
config.block_config(0).ff_config.intermediate_size = 64
|
140
168
|
return config
|
141
169
|
|
142
170
|
|
143
|
-
def build_model(checkpoint_path, **kwargs) -> nn.Module:
|
171
|
+
def build_model(checkpoint_path: str, **kwargs) -> nn.Module:
|
144
172
|
config = get_model_config(**kwargs)
|
145
|
-
model =
|
173
|
+
model = TinyLlama(config)
|
146
174
|
loader = loading_utils.ModelLoader(checkpoint_path, TENSOR_NAMES)
|
147
175
|
loader.load(model)
|
176
|
+
model.eval()
|
148
177
|
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,64 @@
|
|
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 TinyLlama-1.1B model."""
|
17
|
+
|
18
|
+
import logging
|
19
|
+
import pathlib
|
20
|
+
|
21
|
+
from absl import app
|
22
|
+
from absl import flags
|
23
|
+
from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
|
24
|
+
from ai_edge_torch.generative.utilities import verifier
|
25
|
+
import transformers
|
26
|
+
|
27
|
+
|
28
|
+
_PROMPTS = flags.DEFINE_multi_string(
|
29
|
+
"prompts",
|
30
|
+
"Show me the program to add 2 and 3.",
|
31
|
+
"The input prompts to generate answers.",
|
32
|
+
)
|
33
|
+
|
34
|
+
|
35
|
+
def main(_):
|
36
|
+
checkpoint = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
37
|
+
logging.info("Loading the original model from: %s", checkpoint)
|
38
|
+
wrapper_model = verifier.ModelWrapper(
|
39
|
+
model=transformers.AutoModelForCausalLM.from_pretrained(
|
40
|
+
checkpoint, trust_remote_code=True
|
41
|
+
),
|
42
|
+
)
|
43
|
+
# Locate the cached dir.
|
44
|
+
cached_config_file = transformers.utils.cached_file(
|
45
|
+
checkpoint, transformers.utils.CONFIG_NAME
|
46
|
+
)
|
47
|
+
reauthored_checkpoint = pathlib.Path(cached_config_file).parent
|
48
|
+
logging.info("Building the reauthored model from: %s", reauthored_checkpoint)
|
49
|
+
reauthored_model = tiny_llama.build_model(reauthored_checkpoint)
|
50
|
+
|
51
|
+
logging.info("Loading the tokenizer from: %s", checkpoint)
|
52
|
+
tokenizer = transformers.AutoTokenizer.from_pretrained(checkpoint)
|
53
|
+
|
54
|
+
verifier.verify_reauthored_model(
|
55
|
+
original_model=wrapper_model,
|
56
|
+
reauthored_model=reauthored_model,
|
57
|
+
tokenizer=tokenizer,
|
58
|
+
generate_prompts=_PROMPTS.value,
|
59
|
+
atol=1e-04,
|
60
|
+
)
|
61
|
+
|
62
|
+
|
63
|
+
if __name__ == "__main__":
|
64
|
+
app.run(main)
|
@@ -12,17 +12,16 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
|
+
from ai_edge_torch import fx_pass_base
|
16
|
+
from ai_edge_torch.fx_pass_base import CanonicalizePass
|
17
|
+
from ai_edge_torch.generative.fx_passes.remove_sdpa_zero_mask_pass import RemoveSDPACompositeZeroMaskPass
|
15
18
|
import torch
|
16
19
|
|
17
|
-
from ai_edge_torch.convert.fx_passes import CanonicalizePass
|
18
|
-
from ai_edge_torch.convert.fx_passes import run_passes
|
19
|
-
from ai_edge_torch.generative.fx_passes.remove_sdpa_zero_mask_pass import RemoveSDPACompositeZeroMaskPass # NOQA
|
20
|
-
|
21
20
|
|
22
21
|
def run_generative_passes(
|
23
22
|
exported_program: torch.export.ExportedProgram,
|
24
23
|
) -> torch.export.ExportedProgram:
|
25
|
-
return run_passes(
|
24
|
+
return fx_pass_base.run_passes(
|
26
25
|
exported_program,
|
27
26
|
[
|
28
27
|
RemoveSDPACompositeZeroMaskPass(),
|
@@ -12,13 +12,12 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
# ==============================================================================
|
15
|
+
from ai_edge_torch import fx_pass_base
|
16
|
+
from ai_edge_torch import lowertools
|
15
17
|
import torch
|
16
18
|
|
17
|
-
from ai_edge_torch.convert.fx_passes._pass_base import ExportedProgramPassBase
|
18
|
-
from ai_edge_torch.convert.fx_passes._pass_base import ExportedProgramPassResult # NOQA
|
19
19
|
|
20
|
-
|
21
|
-
class RemoveSDPACompositeZeroMaskPass(ExportedProgramPassBase):
|
20
|
+
class RemoveSDPACompositeZeroMaskPass(fx_pass_base.ExportedProgramPassBase):
|
22
21
|
|
23
22
|
def is_zero_tensor_node(self, node: torch.fx.Node):
|
24
23
|
return node.target == torch.ops.aten.zeros.default
|
@@ -28,7 +27,7 @@ class RemoveSDPACompositeZeroMaskPass(ExportedProgramPassBase):
|
|
28
27
|
for node in graph.nodes:
|
29
28
|
if not (
|
30
29
|
node.op == "call_function"
|
31
|
-
and node.target ==
|
30
|
+
and node.target == lowertools.mark_tensor_op
|
32
31
|
):
|
33
32
|
continue
|
34
33
|
|
@@ -36,7 +35,11 @@ class RemoveSDPACompositeZeroMaskPass(ExportedProgramPassBase):
|
|
36
35
|
# Composite info:
|
37
36
|
# - name: odml.scaled_dot_product_attention
|
38
37
|
# - inputs: q, k, v, mask
|
39
|
-
if
|
38
|
+
if (
|
39
|
+
name == "odml.scaled_dot_product_attention"
|
40
|
+
and is_input
|
41
|
+
and io_position == 3
|
42
|
+
):
|
40
43
|
if self.is_zero_tensor_node(source):
|
41
44
|
# Remove the mark_tensor call on the mask input by
|
42
45
|
# replacing the target with an identity function.
|
@@ -44,4 +47,4 @@ class RemoveSDPACompositeZeroMaskPass(ExportedProgramPassBase):
|
|
44
47
|
|
45
48
|
exported_program.graph_module.graph.lint()
|
46
49
|
exported_program.graph_module.recompile()
|
47
|
-
return ExportedProgramPassResult(exported_program, True)
|
50
|
+
return fx_pass_base.ExportedProgramPassResult(exported_program, True)
|