ai-edge-torch-nightly 0.3.0.dev20250114__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 +32 -0
- ai_edge_torch/_config.py +69 -0
- ai_edge_torch/_convert/__init__.py +14 -0
- ai_edge_torch/_convert/conversion.py +153 -0
- ai_edge_torch/_convert/conversion_utils.py +64 -0
- ai_edge_torch/_convert/converter.py +270 -0
- ai_edge_torch/_convert/fx_passes/__init__.py +23 -0
- ai_edge_torch/_convert/fx_passes/build_aten_composite_pass.py +288 -0
- ai_edge_torch/_convert/fx_passes/build_interpolate_composite_pass.py +131 -0
- ai_edge_torch/_convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +258 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +50 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +18 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +68 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +216 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +449 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +303 -0
- ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/utils.py +64 -0
- ai_edge_torch/_convert/fx_passes/remove_non_user_outputs_pass.py +52 -0
- ai_edge_torch/_convert/signature.py +66 -0
- ai_edge_torch/_convert/test/__init__.py +14 -0
- ai_edge_torch/_convert/test/test_convert.py +558 -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/test/test_to_channel_last_io.py +96 -0
- ai_edge_torch/_convert/to_channel_last_io.py +92 -0
- ai_edge_torch/conftest.py +20 -0
- ai_edge_torch/debug/__init__.py +17 -0
- ai_edge_torch/debug/culprit.py +496 -0
- ai_edge_torch/debug/test/__init__.py +14 -0
- ai_edge_torch/debug/test/test_culprit.py +140 -0
- ai_edge_torch/debug/test/test_search_model.py +51 -0
- ai_edge_torch/debug/utils.py +59 -0
- ai_edge_torch/experimental/__init__.py +14 -0
- ai_edge_torch/fx_pass_base.py +110 -0
- ai_edge_torch/generative/__init__.py +14 -0
- ai_edge_torch/generative/examples/__init__.py +14 -0
- ai_edge_torch/generative/examples/amd_llama_135m/__init__.py +14 -0
- ai_edge_torch/generative/examples/amd_llama_135m/amd_llama_135m.py +87 -0
- ai_edge_torch/generative/examples/amd_llama_135m/convert_to_tflite.py +70 -0
- ai_edge_torch/generative/examples/amd_llama_135m/verify.py +72 -0
- ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/gemma/gemma1.py +107 -0
- ai_edge_torch/generative/examples/gemma/gemma2.py +295 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma2.py +43 -0
- ai_edge_torch/generative/examples/gemma/verify_util.py +157 -0
- ai_edge_torch/generative/examples/llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/llama/convert_to_tflite.py +91 -0
- ai_edge_torch/generative/examples/llama/llama.py +196 -0
- ai_edge_torch/generative/examples/llama/verify.py +88 -0
- ai_edge_torch/generative/examples/moonshine/__init__.py +14 -0
- ai_edge_torch/generative/examples/moonshine/convert_moonshine_to_tflite.py +50 -0
- ai_edge_torch/generative/examples/moonshine/moonshine.py +103 -0
- ai_edge_torch/generative/examples/openelm/__init__.py +14 -0
- ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/openelm/openelm.py +127 -0
- ai_edge_torch/generative/examples/openelm/verify.py +71 -0
- ai_edge_torch/generative/examples/paligemma/__init__.py +14 -0
- ai_edge_torch/generative/examples/paligemma/convert_to_tflite.py +95 -0
- ai_edge_torch/generative/examples/paligemma/decoder.py +151 -0
- ai_edge_torch/generative/examples/paligemma/decoder2.py +177 -0
- ai_edge_torch/generative/examples/paligemma/image_encoder.py +160 -0
- ai_edge_torch/generative/examples/paligemma/paligemma.py +179 -0
- ai_edge_torch/generative/examples/paligemma/verify.py +161 -0
- ai_edge_torch/generative/examples/paligemma/verify_decoder.py +75 -0
- ai_edge_torch/generative/examples/paligemma/verify_decoder2.py +72 -0
- ai_edge_torch/generative/examples/paligemma/verify_image_encoder.py +99 -0
- ai_edge_torch/generative/examples/phi/__init__.py +14 -0
- ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/phi/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/phi/phi2.py +107 -0
- ai_edge_torch/generative/examples/phi/phi3.py +219 -0
- ai_edge_torch/generative/examples/phi/verify.py +64 -0
- ai_edge_torch/generative/examples/phi/verify_phi3.py +69 -0
- ai_edge_torch/generative/examples/qwen/__init__.py +14 -0
- ai_edge_torch/generative/examples/qwen/convert_to_tflite.py +93 -0
- ai_edge_torch/generative/examples/qwen/qwen.py +134 -0
- ai_edge_torch/generative/examples/qwen/verify.py +88 -0
- ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
- ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/smollm/convert_v2_to_tflite.py +71 -0
- ai_edge_torch/generative/examples/smollm/smollm.py +125 -0
- ai_edge_torch/generative/examples/smollm/verify.py +86 -0
- ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
- ai_edge_torch/generative/examples/stable_diffusion/attention.py +108 -0
- ai_edge_torch/generative/examples/stable_diffusion/clip.py +185 -0
- ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +173 -0
- ai_edge_torch/generative/examples/stable_diffusion/decoder.py +398 -0
- ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +749 -0
- ai_edge_torch/generative/examples/stable_diffusion/encoder.py +119 -0
- ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +254 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +62 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +66 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +74 -0
- ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +39 -0
- ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +111 -0
- ai_edge_torch/generative/examples/stable_diffusion/util.py +77 -0
- ai_edge_torch/generative/examples/t5/__init__.py +14 -0
- ai_edge_torch/generative/examples/t5/convert_to_tflite.py +138 -0
- ai_edge_torch/generative/examples/t5/t5.py +655 -0
- ai_edge_torch/generative/examples/t5/t5_attention.py +246 -0
- ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
- ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
- ai_edge_torch/generative/examples/test_models/toy_model.py +156 -0
- ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +138 -0
- ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +80 -0
- ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +88 -0
- ai_edge_torch/generative/examples/tiny_llama/verify.py +72 -0
- ai_edge_torch/generative/fx_passes/__init__.py +30 -0
- ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +50 -0
- ai_edge_torch/generative/layers/__init__.py +14 -0
- ai_edge_torch/generative/layers/attention.py +399 -0
- ai_edge_torch/generative/layers/attention_utils.py +210 -0
- ai_edge_torch/generative/layers/builder.py +160 -0
- ai_edge_torch/generative/layers/feed_forward.py +120 -0
- ai_edge_torch/generative/layers/kv_cache.py +204 -0
- ai_edge_torch/generative/layers/lora.py +557 -0
- ai_edge_torch/generative/layers/model_config.py +238 -0
- ai_edge_torch/generative/layers/normalization.py +222 -0
- ai_edge_torch/generative/layers/rotary_position_embedding.py +94 -0
- ai_edge_torch/generative/layers/scaled_dot_product_attention.py +144 -0
- ai_edge_torch/generative/layers/unet/__init__.py +14 -0
- ai_edge_torch/generative/layers/unet/blocks_2d.py +806 -0
- ai_edge_torch/generative/layers/unet/builder.py +50 -0
- ai_edge_torch/generative/layers/unet/model_config.py +282 -0
- ai_edge_torch/generative/quantize/__init__.py +14 -0
- ai_edge_torch/generative/quantize/example.py +47 -0
- ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
- ai_edge_torch/generative/quantize/quant_recipe.py +154 -0
- ai_edge_torch/generative/quantize/quant_recipe_utils.py +62 -0
- ai_edge_torch/generative/quantize/quant_recipes.py +56 -0
- ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
- ai_edge_torch/generative/test/__init__.py +14 -0
- ai_edge_torch/generative/test/test_custom_dus.py +107 -0
- ai_edge_torch/generative/test/test_kv_cache.py +120 -0
- ai_edge_torch/generative/test/test_loader.py +83 -0
- ai_edge_torch/generative/test/test_lora.py +147 -0
- ai_edge_torch/generative/test/test_model_conversion.py +191 -0
- ai_edge_torch/generative/test/test_model_conversion_large.py +362 -0
- ai_edge_torch/generative/test/test_quantize.py +183 -0
- ai_edge_torch/generative/test/utils.py +82 -0
- ai_edge_torch/generative/utilities/__init__.py +15 -0
- ai_edge_torch/generative/utilities/converter.py +215 -0
- ai_edge_torch/generative/utilities/dynamic_update_slice.py +56 -0
- ai_edge_torch/generative/utilities/loader.py +398 -0
- ai_edge_torch/generative/utilities/model_builder.py +180 -0
- ai_edge_torch/generative/utilities/moonshine_loader.py +154 -0
- ai_edge_torch/generative/utilities/stable_diffusion_loader.py +1032 -0
- ai_edge_torch/generative/utilities/t5_loader.py +512 -0
- ai_edge_torch/generative/utilities/transformers_verifier.py +42 -0
- ai_edge_torch/generative/utilities/verifier.py +335 -0
- ai_edge_torch/hlfb/__init__.py +16 -0
- ai_edge_torch/hlfb/mark_pattern/__init__.py +153 -0
- ai_edge_torch/hlfb/mark_pattern/fx_utils.py +69 -0
- ai_edge_torch/hlfb/mark_pattern/pattern.py +288 -0
- ai_edge_torch/hlfb/test/__init__.py +14 -0
- ai_edge_torch/hlfb/test/test_mark_pattern.py +185 -0
- ai_edge_torch/lowertools/__init__.py +18 -0
- ai_edge_torch/lowertools/_shim.py +86 -0
- ai_edge_torch/lowertools/common_utils.py +142 -0
- ai_edge_torch/lowertools/odml_torch_utils.py +260 -0
- ai_edge_torch/lowertools/test_utils.py +62 -0
- ai_edge_torch/lowertools/torch_xla_utils.py +301 -0
- ai_edge_torch/lowertools/translate_recipe.py +163 -0
- ai_edge_torch/model.py +177 -0
- ai_edge_torch/odml_torch/__init__.py +20 -0
- ai_edge_torch/odml_torch/_torch_future.py +88 -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 +403 -0
- ai_edge_torch/odml_torch/export_utils.py +157 -0
- ai_edge_torch/odml_torch/jax_bridge/__init__.py +18 -0
- ai_edge_torch/odml_torch/jax_bridge/_wrap.py +180 -0
- ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
- ai_edge_torch/odml_torch/lowerings/__init__.py +27 -0
- ai_edge_torch/odml_torch/lowerings/_basic.py +294 -0
- ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
- ai_edge_torch/odml_torch/lowerings/_convolution.py +243 -0
- ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +285 -0
- ai_edge_torch/odml_torch/lowerings/_layer_norm.py +87 -0
- ai_edge_torch/odml_torch/lowerings/_quantized_decomposed.py +177 -0
- ai_edge_torch/odml_torch/lowerings/_rand.py +142 -0
- ai_edge_torch/odml_torch/lowerings/context.py +42 -0
- ai_edge_torch/odml_torch/lowerings/decomp.py +69 -0
- ai_edge_torch/odml_torch/lowerings/registry.py +65 -0
- ai_edge_torch/odml_torch/lowerings/utils.py +201 -0
- ai_edge_torch/odml_torch/passes/__init__.py +38 -0
- ai_edge_torch/odml_torch/tf_integration.py +156 -0
- ai_edge_torch/quantize/__init__.py +16 -0
- ai_edge_torch/quantize/pt2e_quantizer.py +466 -0
- ai_edge_torch/quantize/pt2e_quantizer_utils.py +1061 -0
- ai_edge_torch/quantize/quant_config.py +85 -0
- ai_edge_torch/testing/__init__.py +14 -0
- ai_edge_torch/testing/model_coverage/__init__.py +16 -0
- ai_edge_torch/testing/model_coverage/model_coverage.py +145 -0
- ai_edge_torch/version.py +16 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/LICENSE +202 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/METADATA +44 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/RECORD +213 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/WHEEL +5 -0
- ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/top_level.txt +1 -0
@@ -0,0 +1,111 @@
|
|
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
|
+
import functools
|
17
|
+
import json
|
18
|
+
import os
|
19
|
+
from typing import List, Tuple
|
20
|
+
import unicodedata
|
21
|
+
|
22
|
+
import regex as re
|
23
|
+
|
24
|
+
|
25
|
+
def create_bytes_table() -> dict:
|
26
|
+
table = {}
|
27
|
+
special_count = 0
|
28
|
+
for byte in range(256):
|
29
|
+
category = unicodedata.category(chr(byte))
|
30
|
+
if category[0] not in [
|
31
|
+
'C',
|
32
|
+
'Z',
|
33
|
+
]: # ith character is NOT control char or space
|
34
|
+
table[byte] = chr(byte)
|
35
|
+
else: # ith character IS control char or space
|
36
|
+
table[byte] = chr(special_count + 256)
|
37
|
+
special_count += 1
|
38
|
+
return table
|
39
|
+
|
40
|
+
|
41
|
+
def pairwise(seq):
|
42
|
+
a = iter(seq)
|
43
|
+
b = iter(seq)
|
44
|
+
next(b)
|
45
|
+
return zip(a, b)
|
46
|
+
|
47
|
+
|
48
|
+
class Tokenizer:
|
49
|
+
|
50
|
+
def __init__(self, vocab_dir: str):
|
51
|
+
with open(os.path.join(vocab_dir, 'vocab.json'), encoding='utf-8') as f:
|
52
|
+
self.vocab = json.load(f)
|
53
|
+
|
54
|
+
with open(os.path.join(vocab_dir, 'merges.txt'), encoding='utf-8') as f:
|
55
|
+
lines = f.read().split('\n')
|
56
|
+
lines = lines[1:-1]
|
57
|
+
self.merges = {tuple(bigram.split()): i for i, bigram in enumerate(lines)}
|
58
|
+
|
59
|
+
self.bos_token = self.vocab['<|startoftext|>']
|
60
|
+
self.eos_token = self.vocab['<|endoftext|>']
|
61
|
+
self.pad_token = self.vocab['<|endoftext|>']
|
62
|
+
self.max_length = 77
|
63
|
+
self.bytes_table = create_bytes_table()
|
64
|
+
self.chunk_pattern = re.compile(
|
65
|
+
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
|
66
|
+
re.IGNORECASE,
|
67
|
+
)
|
68
|
+
|
69
|
+
def encode(self, text: str) -> List[int]:
|
70
|
+
text = unicodedata.normalize('NFC', text)
|
71
|
+
text = re.sub(r'\s+', ' ', text)
|
72
|
+
text = text.strip()
|
73
|
+
text = text.lower()
|
74
|
+
|
75
|
+
tokens = [self.bos_token]
|
76
|
+
for chunk in re.findall(self.chunk_pattern, text):
|
77
|
+
chunk = ''.join(self.bytes_table[byte] for byte in chunk.encode('utf-8'))
|
78
|
+
tokens.extend(self.vocab[word] for word in self.bpe(chunk))
|
79
|
+
tokens.append(self.eos_token)
|
80
|
+
|
81
|
+
tokens = tokens[: self.max_length]
|
82
|
+
token_length = len(tokens)
|
83
|
+
pad_length = self.max_length - token_length
|
84
|
+
tokens += [self.pad_token] * pad_length
|
85
|
+
return tokens
|
86
|
+
|
87
|
+
def encode_batch(self, texts: List[str]) -> List[List[int]]:
|
88
|
+
return [self.encode(text) for text in texts]
|
89
|
+
|
90
|
+
@functools.lru_cache(maxsize=10000)
|
91
|
+
def bpe(self, chunk: str) -> Tuple[str]:
|
92
|
+
words = list(chunk)
|
93
|
+
words[-1] += '</w>'
|
94
|
+
|
95
|
+
while len(words) > 1:
|
96
|
+
valid_pairs = [pair for pair in pairwise(words) if pair in self.merges]
|
97
|
+
if not valid_pairs:
|
98
|
+
break
|
99
|
+
|
100
|
+
bigram = min(valid_pairs, key=lambda pair: self.merges[pair])
|
101
|
+
first, second = bigram
|
102
|
+
|
103
|
+
new_words = []
|
104
|
+
for word in words:
|
105
|
+
if word == second and new_words and new_words[-1] == first:
|
106
|
+
new_words[-1] = first + second
|
107
|
+
else:
|
108
|
+
new_words.append(word)
|
109
|
+
words = new_words
|
110
|
+
|
111
|
+
return tuple(words)
|
@@ -0,0 +1,77 @@
|
|
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
|
+
import os
|
17
|
+
|
18
|
+
import numpy as np
|
19
|
+
import torch
|
20
|
+
|
21
|
+
|
22
|
+
def get_time_embedding(timestep):
|
23
|
+
freqs = torch.pow(
|
24
|
+
10000, -torch.arange(start=0, end=160, dtype=torch.float32) / 160
|
25
|
+
)
|
26
|
+
x = torch.tensor([timestep], dtype=torch.float32)[:, None] * freqs[None]
|
27
|
+
return torch.cat([torch.cos(x), torch.sin(x)], dim=-1)
|
28
|
+
|
29
|
+
|
30
|
+
def get_alphas_cumprod(
|
31
|
+
beta_start=0.00085, beta_end=0.0120, n_training_steps=1000
|
32
|
+
):
|
33
|
+
betas = (
|
34
|
+
np.linspace(
|
35
|
+
beta_start**0.5, beta_end**0.5, n_training_steps, dtype=np.float32
|
36
|
+
)
|
37
|
+
** 2
|
38
|
+
)
|
39
|
+
alphas = 1.0 - betas
|
40
|
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
41
|
+
return alphas_cumprod
|
42
|
+
|
43
|
+
|
44
|
+
def get_file_path(filename, url=None):
|
45
|
+
module_location = os.path.dirname(os.path.abspath(__file__))
|
46
|
+
parent_location = os.path.dirname(module_location)
|
47
|
+
file_location = os.path.join(parent_location, "data", filename)
|
48
|
+
return file_location
|
49
|
+
|
50
|
+
|
51
|
+
def move_channel(image, to):
|
52
|
+
if to == "first":
|
53
|
+
if isinstance(image, torch.Tensor):
|
54
|
+
return image.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
|
55
|
+
if isinstance(image, np.ndarray):
|
56
|
+
return image.transpose(0, 3, 1, 2)
|
57
|
+
elif to == "last":
|
58
|
+
if isinstance(image, torch.Tensor):
|
59
|
+
return image.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
|
60
|
+
if isinstance(image, np.ndarray):
|
61
|
+
return image.transpose(0, 2, 3, 1)
|
62
|
+
else:
|
63
|
+
raise ValueError("to must be one of the following: first, last")
|
64
|
+
|
65
|
+
|
66
|
+
def rescale(x, old_range, new_range, clamp=False):
|
67
|
+
old_min, old_max = old_range
|
68
|
+
new_min, new_max = new_range
|
69
|
+
x -= old_min
|
70
|
+
x *= (new_max - new_min) / (old_max - old_min)
|
71
|
+
x += new_min
|
72
|
+
if clamp:
|
73
|
+
if isinstance(x, torch.Tensor):
|
74
|
+
x = x.clamp(new_min, new_max)
|
75
|
+
elif isinstance(x, np.ndarray):
|
76
|
+
x = x.clip(new_min, new_max)
|
77
|
+
return x
|
@@ -0,0 +1,14 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
@@ -0,0 +1,138 @@
|
|
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
|
+
import os
|
17
|
+
from pathlib import Path
|
18
|
+
|
19
|
+
import ai_edge_torch
|
20
|
+
from ai_edge_torch.generative.examples.t5 import t5
|
21
|
+
from ai_edge_torch.generative.quantize import quant_recipes
|
22
|
+
import numpy as np
|
23
|
+
import torch
|
24
|
+
|
25
|
+
|
26
|
+
# TODO(haoliang): clean this up untile 2-sig model is validated e2e.
|
27
|
+
def convert_t5_to_tflite_singlesig(checkpoint_path: str):
|
28
|
+
pytorch_model = t5.build_t5_model(checkpoint_path)
|
29
|
+
|
30
|
+
# encoder
|
31
|
+
seq_len = 512
|
32
|
+
prefill_e_tokens = torch.full((1, seq_len), 0, dtype=torch.int)
|
33
|
+
prompt_e_token = [1, 2, 3, 4, 5, 6]
|
34
|
+
prefill_e_tokens[0, : len(prompt_e_token)] = torch.tensor(
|
35
|
+
prompt_e_token, dtype=torch.int
|
36
|
+
)
|
37
|
+
prefill_e_input_pos = torch.arange(0, seq_len, dtype=torch.int)
|
38
|
+
prefill_d_tokens = torch.full((1, seq_len), 0, dtype=torch.int)
|
39
|
+
prompt_d_token = [1, 2, 3, 4, 5, 6]
|
40
|
+
prefill_d_tokens[0, : len(prompt_d_token)] = torch.tensor(
|
41
|
+
prompt_d_token, dtype=torch.int
|
42
|
+
)
|
43
|
+
prefill_d_input_pos = torch.arange(0, seq_len, dtype=torch.int)
|
44
|
+
|
45
|
+
# decoder
|
46
|
+
decode_token = torch.tensor([[1]], dtype=torch.int)
|
47
|
+
decode_input_pos = torch.tensor([0], dtype=torch.int)
|
48
|
+
decode_d_token = torch.tensor([[1]], dtype=torch.int)
|
49
|
+
decode_d_input_pos = torch.tensor([0], dtype=torch.int)
|
50
|
+
|
51
|
+
# Pad mask for self attention only on "real" tokens.
|
52
|
+
# Pad with `-inf` for any tokens indices that aren't desired.
|
53
|
+
pad_mask = torch.zeros([seq_len], dtype=torch.float32)
|
54
|
+
|
55
|
+
edge_model = ai_edge_torch.signature(
|
56
|
+
'decode',
|
57
|
+
pytorch_model,
|
58
|
+
(
|
59
|
+
prefill_e_tokens,
|
60
|
+
prefill_e_input_pos,
|
61
|
+
decode_d_token,
|
62
|
+
decode_d_input_pos,
|
63
|
+
pad_mask,
|
64
|
+
),
|
65
|
+
).convert()
|
66
|
+
|
67
|
+
edge_model.export('/tmp/t5_encode_decode.tflite')
|
68
|
+
|
69
|
+
|
70
|
+
def convert_t5_to_tflite_multisig(checkpoint_path: str):
|
71
|
+
config = t5.get_model_config_t5()
|
72
|
+
embedding_layer = torch.nn.Embedding(
|
73
|
+
config.vocab_size, config.embedding_dim, padding_idx=0
|
74
|
+
)
|
75
|
+
t5_encoder_model = t5.build_t5_encoder_model(
|
76
|
+
config, embedding_layer, checkpoint_path
|
77
|
+
)
|
78
|
+
t5_decoder_model = t5.build_t5_decoder_model(
|
79
|
+
config, embedding_layer, checkpoint_path
|
80
|
+
)
|
81
|
+
|
82
|
+
# encoder
|
83
|
+
seq_len = 512
|
84
|
+
prefill_e_tokens = torch.full((1, seq_len), 0, dtype=torch.int)
|
85
|
+
prompt_e_token = [1, 2, 3, 4, 5, 6]
|
86
|
+
prefill_e_tokens[0, : len(prompt_e_token)] = torch.tensor(
|
87
|
+
prompt_e_token, dtype=torch.int
|
88
|
+
)
|
89
|
+
prefill_e_input_pos = torch.arange(0, seq_len, dtype=torch.int)
|
90
|
+
prefill_d_tokens = torch.full((1, seq_len), 0, dtype=torch.int)
|
91
|
+
prompt_d_token = [1, 2, 3, 4, 5, 6]
|
92
|
+
prefill_d_tokens[0, : len(prompt_d_token)] = torch.tensor(
|
93
|
+
prompt_d_token, dtype=torch.int
|
94
|
+
)
|
95
|
+
prefill_d_input_pos = torch.arange(0, seq_len, dtype=torch.int)
|
96
|
+
|
97
|
+
# decoder
|
98
|
+
decode_token = torch.tensor([[1]], dtype=torch.int)
|
99
|
+
decode_input_pos = torch.tensor([0], dtype=torch.int)
|
100
|
+
decode_d_token = torch.tensor([[1]], dtype=torch.int)
|
101
|
+
decode_d_input_pos = torch.tensor([0], dtype=torch.int)
|
102
|
+
|
103
|
+
# Pad mask for self attention only on "real" tokens.
|
104
|
+
# Pad with `-inf` for any tokens indices that aren't desired.
|
105
|
+
pad_mask = torch.zeros([seq_len], dtype=torch.float32)
|
106
|
+
hidden_states = torch.zeros((1, 512, 768), dtype=torch.float32)
|
107
|
+
quant_config = quant_recipes.full_int8_dynamic_recipe()
|
108
|
+
|
109
|
+
edge_model = (
|
110
|
+
ai_edge_torch.signature(
|
111
|
+
'encode',
|
112
|
+
t5_encoder_model,
|
113
|
+
(
|
114
|
+
prefill_e_tokens,
|
115
|
+
prefill_e_input_pos,
|
116
|
+
pad_mask,
|
117
|
+
),
|
118
|
+
)
|
119
|
+
.signature(
|
120
|
+
'decode',
|
121
|
+
t5_decoder_model,
|
122
|
+
(
|
123
|
+
hidden_states,
|
124
|
+
decode_d_token,
|
125
|
+
decode_d_input_pos,
|
126
|
+
pad_mask,
|
127
|
+
),
|
128
|
+
)
|
129
|
+
.convert(quant_config=quant_config)
|
130
|
+
)
|
131
|
+
|
132
|
+
edge_model.export('/tmp/t5_encode_decode_2_sigs.tflite')
|
133
|
+
|
134
|
+
|
135
|
+
if __name__ == '__main__':
|
136
|
+
checkpoint_path = os.path.join(Path.home(), 'Downloads/llm_data/t5')
|
137
|
+
# convert_t5_to_tflite_singlesig(checkpoint_path)
|
138
|
+
convert_t5_to_tflite_multisig(checkpoint_path)
|