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,56 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors. All Rights Reserved.
|
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
|
+
"""Helper functions to create common and supported quantization recipes.
|
17
|
+
|
18
|
+
These recipes will work with models created with the Edge Generative API only.
|
19
|
+
Assume Transformer architecture congruent with
|
20
|
+
ai_edge_torch/generative/layers/model_config.py:ModelConfig.
|
21
|
+
|
22
|
+
Typical usage example:
|
23
|
+
|
24
|
+
quant_config = quant_recipes.full_int8_dynamic_recipe()
|
25
|
+
edge_model = ai_edge_torch.convert(
|
26
|
+
model, (tokens, input_pos), quant_config=quant_config
|
27
|
+
)
|
28
|
+
"""
|
29
|
+
|
30
|
+
from ai_edge_torch.generative.quantize import quant_recipe
|
31
|
+
from ai_edge_torch.generative.quantize import quant_recipe_utils
|
32
|
+
from ai_edge_torch.quantize import quant_config
|
33
|
+
|
34
|
+
|
35
|
+
def full_int8_dynamic_recipe() -> quant_config.QuantConfig:
|
36
|
+
return quant_config.QuantConfig(
|
37
|
+
generative_recipe=quant_recipe.GenerativeQuantRecipe(
|
38
|
+
default=quant_recipe_utils.create_layer_quant_int8_dynamic(),
|
39
|
+
)
|
40
|
+
)
|
41
|
+
|
42
|
+
|
43
|
+
def full_int8_weight_only_recipe() -> quant_config.QuantConfig:
|
44
|
+
return quant_config.QuantConfig(
|
45
|
+
generative_recipe=quant_recipe.GenerativeQuantRecipe(
|
46
|
+
default=quant_recipe_utils.create_layer_quant_int8_weight_only(),
|
47
|
+
)
|
48
|
+
)
|
49
|
+
|
50
|
+
|
51
|
+
def full_fp16_recipe() -> quant_config.QuantConfig:
|
52
|
+
return quant_config.QuantConfig(
|
53
|
+
generative_recipe=quant_recipe.GenerativeQuantRecipe(
|
54
|
+
default=quant_recipe_utils.create_layer_quant_fp16()
|
55
|
+
)
|
56
|
+
)
|
@@ -0,0 +1,32 @@
|
|
1
|
+
# Copyright 2024 The AI Edge Torch Authors. All Rights Reserved.
|
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
|
+
|
17
|
+
def get_supported_layer_schemes():
|
18
|
+
"""List of layer-scoped quantization schemes supported in runtime.
|
19
|
+
|
20
|
+
Returns:
|
21
|
+
List of tuple(activation_dtype, weight_dtype, mode, algorithm, granularity).
|
22
|
+
"""
|
23
|
+
from ai_edge_torch.generative.quantize.quant_attrs import Algorithm as _a
|
24
|
+
from ai_edge_torch.generative.quantize.quant_attrs import Dtype as _t
|
25
|
+
from ai_edge_torch.generative.quantize.quant_attrs import Granularity as _g
|
26
|
+
from ai_edge_torch.generative.quantize.quant_attrs import Mode as _m
|
27
|
+
|
28
|
+
return [
|
29
|
+
(_t.FP32, _t.INT8, _m.DYNAMIC_RANGE, _a.MIN_MAX, _g.CHANNELWISE),
|
30
|
+
(_t.FP32, _t.INT8, _m.WEIGHT_ONLY, _a.MIN_MAX, _g.CHANNELWISE),
|
31
|
+
(_t.FP32, _t.FP16, _m.WEIGHT_ONLY, _a.FLOAT_CAST, _g.NONE),
|
32
|
+
]
|
@@ -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,107 @@
|
|
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
|
+
"""A suite of tests to validate the Dynamic Update Slice Custom Op."""
|
17
|
+
|
18
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
19
|
+
import ai_edge_torch.generative.layers.model_config as cfg
|
20
|
+
import torch
|
21
|
+
from torch import nn
|
22
|
+
|
23
|
+
from absl.testing import absltest as googletest, parameterized
|
24
|
+
|
25
|
+
|
26
|
+
def updated_slice_matches(buffer, update, index):
|
27
|
+
indexer = [slice(i, i + d) for i, d in zip(index, update.shape)]
|
28
|
+
buf = buffer[indexer]
|
29
|
+
return torch.allclose(buf, update)
|
30
|
+
|
31
|
+
|
32
|
+
def intT(x):
|
33
|
+
return torch.tensor(x).int()
|
34
|
+
|
35
|
+
|
36
|
+
class DUSMod(nn.Module):
|
37
|
+
|
38
|
+
def forward(self, buffer, update, index):
|
39
|
+
out = dynamic_update_slice(buffer, update, index)
|
40
|
+
out = out * 2
|
41
|
+
return out
|
42
|
+
|
43
|
+
|
44
|
+
@googletest.skip('Enable this when odml_torch is default b/373387583')
|
45
|
+
class TestCustomDUS(parameterized.TestCase):
|
46
|
+
|
47
|
+
@parameterized.named_parameters(
|
48
|
+
(
|
49
|
+
'DUS_whole_buffer',
|
50
|
+
torch.randn(1, 1280, 4, 64),
|
51
|
+
torch.randn([1, 1024, 4, 64]),
|
52
|
+
[intT(0), intT(0), intT(0), intT(0)],
|
53
|
+
),
|
54
|
+
(
|
55
|
+
'DUS_kv_example',
|
56
|
+
torch.randn(2, 1280, 4, 64),
|
57
|
+
torch.randn([2, 1024, 4, 64]),
|
58
|
+
[intT(0), intT(0), intT(0), intT(0)],
|
59
|
+
),
|
60
|
+
(
|
61
|
+
'DUS_3d',
|
62
|
+
torch.randn(2, 256, 4, 64),
|
63
|
+
torch.randn([2, 256, 2, 64]),
|
64
|
+
[intT(0), intT(0), intT(2), intT(0)],
|
65
|
+
),
|
66
|
+
(
|
67
|
+
'DUS_3d_v2',
|
68
|
+
torch.randn(2, 256, 4, 64),
|
69
|
+
torch.randn([2, 256, 3, 64]),
|
70
|
+
[intT(0), intT(0), intT(1), intT(0)],
|
71
|
+
),
|
72
|
+
(
|
73
|
+
'DUS_3d_v3',
|
74
|
+
torch.randn(6, 8, 32),
|
75
|
+
torch.randn([6, 3, 32]),
|
76
|
+
[intT(0), intT(5), intT(0)],
|
77
|
+
),
|
78
|
+
(
|
79
|
+
'DUS_2d',
|
80
|
+
torch.randn(8, 32),
|
81
|
+
torch.randn([8, 12]),
|
82
|
+
[intT(0), intT(20)],
|
83
|
+
),
|
84
|
+
)
|
85
|
+
def test_opcheck_dynamic_update_slice(self, buffer, update, indices):
|
86
|
+
torch.library.opcheck(dynamic_update_slice, (buffer, update, indices))
|
87
|
+
out = dynamic_update_slice(buffer, update, indices)
|
88
|
+
self.assertTrue(updated_slice_matches(out, update, indices))
|
89
|
+
|
90
|
+
def test_exported_program(self):
|
91
|
+
buffer = torch.randn(1, 1280, 4, 64)
|
92
|
+
update = torch.randn([1, 1024, 4, 64])
|
93
|
+
index = [intT(0), intT(0), intT(0), intT(0)]
|
94
|
+
dm = DUSMod()
|
95
|
+
ep = torch.export.export(dm, (buffer, update, index))
|
96
|
+
dus_in_exported_program = False
|
97
|
+
for node in ep.graph.nodes:
|
98
|
+
if node.op == 'call_function':
|
99
|
+
if node.target.__name__.startswith('dynamic_update_slice'):
|
100
|
+
dus_in_exported_program = True
|
101
|
+
break
|
102
|
+
|
103
|
+
self.assertTrue(dus_in_exported_program)
|
104
|
+
|
105
|
+
|
106
|
+
if __name__ == '__main__':
|
107
|
+
googletest.main()
|
@@ -0,0 +1,120 @@
|
|
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
|
+
"""A suite of tests to validate KV Cache layer."""
|
17
|
+
|
18
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
19
|
+
import ai_edge_torch.generative.layers.model_config as cfg
|
20
|
+
import torch
|
21
|
+
|
22
|
+
from absl.testing import absltest as googletest
|
23
|
+
|
24
|
+
|
25
|
+
class TestKVLayers(googletest.TestCase):
|
26
|
+
|
27
|
+
def _get_test_config(
|
28
|
+
self, num_layers, head_dim, num_query_groups, kv_cache_max_len
|
29
|
+
):
|
30
|
+
attn_config = cfg.AttentionConfig(
|
31
|
+
num_heads=1, head_dim=head_dim, num_query_groups=num_query_groups
|
32
|
+
)
|
33
|
+
block_config = cfg.TransformerBlockConfig(
|
34
|
+
attn_config=attn_config, ff_config=None
|
35
|
+
)
|
36
|
+
config = cfg.ModelConfig(
|
37
|
+
kv_cache_max_len=kv_cache_max_len,
|
38
|
+
embedding_dim=head_dim,
|
39
|
+
block_configs=block_config,
|
40
|
+
num_layers=num_layers,
|
41
|
+
max_seq_len=None,
|
42
|
+
vocab_size=None,
|
43
|
+
)
|
44
|
+
return config
|
45
|
+
|
46
|
+
def test_cache_udpate(self):
|
47
|
+
N = 1
|
48
|
+
HEAD_DIM = 2
|
49
|
+
NUM_QG = 1
|
50
|
+
KV_LEN = 4
|
51
|
+
config = self._get_test_config(
|
52
|
+
num_layers=N,
|
53
|
+
head_dim=HEAD_DIM,
|
54
|
+
num_query_groups=NUM_QG,
|
55
|
+
kv_cache_max_len=KV_LEN,
|
56
|
+
)
|
57
|
+
kv = kv_utils.KVCache.from_model_config(config)
|
58
|
+
entry = kv.caches[0]
|
59
|
+
# single-slice update
|
60
|
+
input_pos = torch.tensor([1])
|
61
|
+
k_slice = v_slice = torch.full(
|
62
|
+
(1, 1, NUM_QG, HEAD_DIM), 5, dtype=torch.float
|
63
|
+
)
|
64
|
+
updated_entry = kv_utils.update(entry, input_pos, k_slice, v_slice)
|
65
|
+
self.assertEqual(
|
66
|
+
updated_entry.k_cache.numpy().flatten().tolist(),
|
67
|
+
[0, 0, 5, 5, 0, 0, 0, 0],
|
68
|
+
)
|
69
|
+
self.assertEqual(
|
70
|
+
updated_entry.v_cache.numpy().flatten().tolist(),
|
71
|
+
[0, 0, 5, 5, 0, 0, 0, 0],
|
72
|
+
)
|
73
|
+
# multi-slice update
|
74
|
+
input_pos = torch.tensor([0, 1])
|
75
|
+
k_slice = v_slice = torch.full(
|
76
|
+
(1, 2, NUM_QG, HEAD_DIM), 7, dtype=torch.float
|
77
|
+
)
|
78
|
+
updated_entry = kv_utils.update(entry, input_pos, k_slice, v_slice)
|
79
|
+
self.assertEqual(
|
80
|
+
updated_entry.k_cache.numpy().flatten().tolist(),
|
81
|
+
[7, 7, 7, 7, 0, 0, 0, 0],
|
82
|
+
)
|
83
|
+
self.assertEqual(
|
84
|
+
updated_entry.v_cache.numpy().flatten().tolist(),
|
85
|
+
[7, 7, 7, 7, 0, 0, 0, 0],
|
86
|
+
)
|
87
|
+
|
88
|
+
def test_serialization(self):
|
89
|
+
class TestModel(torch.nn.Module):
|
90
|
+
|
91
|
+
def forward(self, kv: kv_utils.KVCache) -> kv_utils.KVCache:
|
92
|
+
updated_kv_entries = [
|
93
|
+
kv_utils.KVCacheEntry(
|
94
|
+
torch.zeros_like(entry.k_cache), torch.zeros_like(entry.v_cache)
|
95
|
+
)
|
96
|
+
for entry in kv.caches
|
97
|
+
]
|
98
|
+
return kv_utils.KVCache(updated_kv_entries)
|
99
|
+
|
100
|
+
N = 1
|
101
|
+
HEAD_DIM = 2
|
102
|
+
NUM_QG = 1
|
103
|
+
KV_LEN = 4
|
104
|
+
config = self._get_test_config(
|
105
|
+
num_layers=N,
|
106
|
+
head_dim=HEAD_DIM,
|
107
|
+
num_query_groups=NUM_QG,
|
108
|
+
kv_cache_max_len=KV_LEN,
|
109
|
+
)
|
110
|
+
kv = kv_utils.KVCache.from_model_config(config)
|
111
|
+
model = TestModel()
|
112
|
+
exported_program = torch.export.export(model, (kv,))
|
113
|
+
input_specs = exported_program.graph_signature.input_specs
|
114
|
+
self.assertEqual(len(input_specs), 2)
|
115
|
+
self.assertEqual(input_specs[0].arg.name, "kv_k_0")
|
116
|
+
self.assertEqual(input_specs[1].arg.name, "kv_v_0")
|
117
|
+
|
118
|
+
|
119
|
+
if __name__ == "__main__":
|
120
|
+
googletest.main()
|
@@ -0,0 +1,83 @@
|
|
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
|
+
# Testing weight loader utilities.
|
16
|
+
|
17
|
+
import os
|
18
|
+
import tempfile
|
19
|
+
|
20
|
+
from ai_edge_torch.generative.examples.tiny_llama import tiny_llama
|
21
|
+
from ai_edge_torch.generative.utilities import loader as loading_utils
|
22
|
+
from ai_edge_torch.generative.utilities import model_builder
|
23
|
+
import safetensors.torch
|
24
|
+
import torch
|
25
|
+
|
26
|
+
from absl.testing import absltest as googletest
|
27
|
+
|
28
|
+
|
29
|
+
class TestLoader(googletest.TestCase):
|
30
|
+
"""Unit tests that check weight loader."""
|
31
|
+
|
32
|
+
def test_load_safetensors(self):
|
33
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
34
|
+
file_path = os.path.join(temp_dir, "test.safetensors")
|
35
|
+
test_data = {"weight": torch.randn(20, 10), "bias": torch.randn(20)}
|
36
|
+
safetensors.torch.save_file(test_data, file_path)
|
37
|
+
|
38
|
+
loaded_tensors = loading_utils.load_safetensors(file_path)
|
39
|
+
self.assertIn("weight", loaded_tensors)
|
40
|
+
self.assertIn("bias", loaded_tensors)
|
41
|
+
|
42
|
+
def test_load_statedict(self):
|
43
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
44
|
+
file_path = os.path.join(temp_dir, "test.pt")
|
45
|
+
model = torch.nn.Linear(10, 5)
|
46
|
+
state_dict = model.state_dict()
|
47
|
+
torch.save(state_dict, file_path)
|
48
|
+
|
49
|
+
loaded_tensors = loading_utils.load_pytorch_statedict(file_path)
|
50
|
+
self.assertIn("weight", loaded_tensors)
|
51
|
+
self.assertIn("bias", loaded_tensors)
|
52
|
+
|
53
|
+
def test_model_loader(self):
|
54
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
55
|
+
file_path = os.path.join(temp_dir, "test.safetensors")
|
56
|
+
test_weights = {
|
57
|
+
"lm_head.weight": torch.randn((32000, 2048)),
|
58
|
+
"model.embed_tokens.weight": torch.randn((32000, 2048)),
|
59
|
+
"model.layers.0.input_layernorm.weight": torch.randn((2048,)),
|
60
|
+
"model.layers.0.mlp.down_proj.weight": torch.randn((2048, 5632)),
|
61
|
+
"model.layers.0.mlp.gate_proj.weight": torch.randn((5632, 2048)),
|
62
|
+
"model.layers.0.mlp.up_proj.weight": torch.randn((5632, 2048)),
|
63
|
+
"model.layers.0.post_attention_layernorm.weight": torch.randn((
|
64
|
+
2048,
|
65
|
+
)),
|
66
|
+
"model.layers.0.self_attn.k_proj.weight": torch.randn((256, 2048)),
|
67
|
+
"model.layers.0.self_attn.o_proj.weight": torch.randn((2048, 2048)),
|
68
|
+
"model.layers.0.self_attn.q_proj.weight": torch.randn((2048, 2048)),
|
69
|
+
"model.layers.0.self_attn.v_proj.weight": torch.randn((256, 2048)),
|
70
|
+
"model.norm.weight": torch.randn((2048,)),
|
71
|
+
}
|
72
|
+
safetensors.torch.save_file(test_weights, file_path)
|
73
|
+
cfg = tiny_llama.get_model_config()
|
74
|
+
cfg.num_layers = 1
|
75
|
+
model = model_builder.DecoderOnlyModel(cfg)
|
76
|
+
|
77
|
+
loader = loading_utils.ModelLoader(file_path, tiny_llama.TENSOR_NAMES)
|
78
|
+
# if returns successfully, it means all the tensors were initiallized.
|
79
|
+
loader.load(model, strict=True)
|
80
|
+
|
81
|
+
|
82
|
+
if __name__ == "__main__":
|
83
|
+
googletest.main()
|
@@ -0,0 +1,147 @@
|
|
1
|
+
# Copyright 2025 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
|
+
"""A suite of tests to validate LoRA utilities."""
|
17
|
+
|
18
|
+
from ai_edge_torch.generative.layers import lora as lora_utils
|
19
|
+
import ai_edge_torch.generative.layers.model_config as cfg
|
20
|
+
import torch
|
21
|
+
from absl.testing import absltest as googletest
|
22
|
+
from tensorflow.python.platform import resource_loader # pylint: disable=g-direct-tensorflow-import
|
23
|
+
|
24
|
+
|
25
|
+
class TestLora(googletest.TestCase):
|
26
|
+
"""Tests for LoRA utilities."""
|
27
|
+
|
28
|
+
def test_safetensors_builder(self):
|
29
|
+
"""Converts a safetensors file to a LoRA module."""
|
30
|
+
|
31
|
+
tensor_names = lora_utils.LoRATensorNames(
|
32
|
+
attn_query_w_a=(
|
33
|
+
"base_model.model.model.layers.{}.self_attn.q_proj.lora_A.weight"
|
34
|
+
),
|
35
|
+
attn_query_w_b=(
|
36
|
+
"base_model.model.model.layers.{}.self_attn.q_proj.lora_B.weight"
|
37
|
+
),
|
38
|
+
attn_key_w_a=(
|
39
|
+
"base_model.model.model.layers.{}.self_attn.k_proj.lora_A.weight"
|
40
|
+
),
|
41
|
+
attn_key_w_b=(
|
42
|
+
"base_model.model.model.layers.{}.self_attn.k_proj.lora_B.weight"
|
43
|
+
),
|
44
|
+
attn_value_w_a=(
|
45
|
+
"base_model.model.model.layers.{}.self_attn.v_proj.lora_A.weight"
|
46
|
+
),
|
47
|
+
attn_value_w_b=(
|
48
|
+
"base_model.model.model.layers.{}.self_attn.v_proj.lora_B.weight"
|
49
|
+
),
|
50
|
+
attn_output_w_a=(
|
51
|
+
"base_model.model.model.layers.{}.self_attn.o_proj.lora_A.weight"
|
52
|
+
),
|
53
|
+
attn_output_w_b=(
|
54
|
+
"base_model.model.model.layers.{}.self_attn.o_proj.lora_B.weight"
|
55
|
+
),
|
56
|
+
)
|
57
|
+
|
58
|
+
safetensors_file = resource_loader.get_path_to_datafile(
|
59
|
+
"fixtures/test_lora_rank16.safetensors"
|
60
|
+
)
|
61
|
+
config = self._get_test_config(
|
62
|
+
num_layers=1,
|
63
|
+
head_dim=8,
|
64
|
+
num_query_groups=1,
|
65
|
+
kv_cache_max_len=16,
|
66
|
+
)
|
67
|
+
lora = lora_utils.LoRA.from_safetensors(
|
68
|
+
safetensors_file,
|
69
|
+
scale=1.0,
|
70
|
+
lora_tensor_names=tensor_names,
|
71
|
+
config=config,
|
72
|
+
)
|
73
|
+
self.assertEqual(lora.get_rank(), 16)
|
74
|
+
|
75
|
+
def test_torch_export(self):
|
76
|
+
"""Tests the export of the LoRA module."""
|
77
|
+
|
78
|
+
class TestModel(torch.nn.Module):
|
79
|
+
|
80
|
+
def forward(self, x: torch.Tensor, lora: lora_utils.LoRA) -> torch.Tensor:
|
81
|
+
x += lora_utils.apply_lora(x, lora.adapters[0].attention.query)
|
82
|
+
return x
|
83
|
+
|
84
|
+
n = 1
|
85
|
+
head_dim = 2
|
86
|
+
num_query_groups = 1
|
87
|
+
key_length = 4
|
88
|
+
config = self._get_test_config(
|
89
|
+
num_layers=n,
|
90
|
+
head_dim=head_dim,
|
91
|
+
num_query_groups=num_query_groups,
|
92
|
+
kv_cache_max_len=key_length,
|
93
|
+
)
|
94
|
+
inputs = torch.zeros((n, 1, head_dim))
|
95
|
+
lora = lora_utils.LoRA.zeros(rank=16, config=config)
|
96
|
+
model = TestModel()
|
97
|
+
exported_program = torch.export.export(model, (inputs, lora))
|
98
|
+
input_specs = exported_program.graph_signature.input_specs
|
99
|
+
# 9 inputs: 1 for x, 2 for query lora, 2 for key lora, 2 for value lora,
|
100
|
+
# 2 for output lora.
|
101
|
+
self.assertLen(input_specs, 9)
|
102
|
+
self.assertEqual(input_specs[0].arg.name, "x")
|
103
|
+
self.assertEqual(input_specs[1].arg.name, "lora_atten_q_a_prime_weight_0")
|
104
|
+
self.assertEqual(input_specs[2].arg.name, "lora_atten_q_b_prime_weight_0")
|
105
|
+
self.assertEqual(input_specs[3].arg.name, "lora_atten_k_a_prime_weight_0")
|
106
|
+
self.assertEqual(input_specs[4].arg.name, "lora_atten_k_b_prime_weight_0")
|
107
|
+
self.assertEqual(input_specs[5].arg.name, "lora_atten_v_a_prime_weight_0")
|
108
|
+
self.assertEqual(input_specs[6].arg.name, "lora_atten_v_b_prime_weight_0")
|
109
|
+
self.assertEqual(input_specs[7].arg.name, "lora_atten_o_a_prime_weight_0")
|
110
|
+
self.assertEqual(input_specs[8].arg.name, "lora_atten_o_b_prime_weight_0")
|
111
|
+
|
112
|
+
def test_lora_tflite_serialization(self):
|
113
|
+
"""Tests the serialization of the LoRA module."""
|
114
|
+
config = self._get_test_config(
|
115
|
+
num_layers=2,
|
116
|
+
head_dim=8,
|
117
|
+
num_query_groups=1,
|
118
|
+
kv_cache_max_len=16,
|
119
|
+
)
|
120
|
+
lora = lora_utils.LoRA.random(rank=16, config=config)
|
121
|
+
flatbuffer_model = lora.to_tflite()
|
122
|
+
recovered_lora = lora_utils.LoRA.from_flatbuffers(flatbuffer_model)
|
123
|
+
self.assertEqual(lora, recovered_lora)
|
124
|
+
|
125
|
+
def _get_test_config(
|
126
|
+
self, num_layers, head_dim, num_query_groups, kv_cache_max_len
|
127
|
+
):
|
128
|
+
"""Returns a test model config."""
|
129
|
+
attn_config = cfg.AttentionConfig(
|
130
|
+
num_heads=1, head_dim=head_dim, num_query_groups=num_query_groups
|
131
|
+
)
|
132
|
+
block_config = cfg.TransformerBlockConfig(
|
133
|
+
attn_config=attn_config, ff_config=None
|
134
|
+
)
|
135
|
+
config = cfg.ModelConfig(
|
136
|
+
kv_cache_max_len=kv_cache_max_len,
|
137
|
+
embedding_dim=head_dim,
|
138
|
+
block_configs=block_config,
|
139
|
+
num_layers=num_layers,
|
140
|
+
max_seq_len=None,
|
141
|
+
vocab_size=None,
|
142
|
+
)
|
143
|
+
return config
|
144
|
+
|
145
|
+
|
146
|
+
if __name__ == "__main__":
|
147
|
+
googletest.main()
|