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,335 @@
|
|
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
|
+
"""Common utility functions to verify the reauthored models."""
|
17
|
+
|
18
|
+
import logging
|
19
|
+
from typing import Any, List, Optional
|
20
|
+
|
21
|
+
from ai_edge_torch.generative.layers import kv_cache as kv_utils
|
22
|
+
from ai_edge_torch.generative.utilities.model_builder import ExportConfig
|
23
|
+
import torch
|
24
|
+
|
25
|
+
|
26
|
+
class ModelWrapper(torch.nn.Module):
|
27
|
+
"""A wrapper for the model to be verified.
|
28
|
+
|
29
|
+
It unifies the interface of forward() and generate() of models for the
|
30
|
+
verification to call.
|
31
|
+
"""
|
32
|
+
|
33
|
+
def __init__(self, model: torch.nn.Module):
|
34
|
+
"""Initializes the wrapper.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
model (torch.nn.Module): The model which might have different interfaces
|
38
|
+
of forward() and generate(). It could be a model built from HuggingFace
|
39
|
+
transformers, a regular PyTorch model, or a model re-authored with
|
40
|
+
ai_edge_torch Generative API.
|
41
|
+
"""
|
42
|
+
super().__init__()
|
43
|
+
self.model = model
|
44
|
+
self.export_config = ExportConfig(output_logits_on_prefill=True)
|
45
|
+
|
46
|
+
def forward(
|
47
|
+
self, tokens: torch.Tensor, pixel_values: torch.Tensor = None
|
48
|
+
) -> torch.Tensor:
|
49
|
+
"""Gets output logits by forwarding the input tokens.
|
50
|
+
|
51
|
+
Args:
|
52
|
+
tokens (torch.Tensor): The input tokens to forward. Its dimension is
|
53
|
+
expected to be (batch_size=1, kv_cache_max_len).
|
54
|
+
|
55
|
+
Returns:
|
56
|
+
The output logits.
|
57
|
+
"""
|
58
|
+
raise NotImplementedError("forward() is not implemented.")
|
59
|
+
|
60
|
+
def generate(
|
61
|
+
self,
|
62
|
+
prompts: torch.Tensor,
|
63
|
+
max_new_tokens: int,
|
64
|
+
pixel_values: torch.Tensor = None,
|
65
|
+
) -> torch.IntTensor:
|
66
|
+
"""Returns the response token IDs to the given prompts tensor.
|
67
|
+
|
68
|
+
The maximum number of tokens to generate might be set by subclasses.
|
69
|
+
|
70
|
+
Args:
|
71
|
+
prompts (torch.Tensor): The input token IDs to generate with. Its shape is
|
72
|
+
expected to be (batch_size=1, input_ids_len).
|
73
|
+
max_new_tokens (int): The maximum number of response token IDs to
|
74
|
+
generate.
|
75
|
+
|
76
|
+
Returns:
|
77
|
+
The tensor of response token IDs with shape of (batch_size=1,
|
78
|
+
response_ids_len).
|
79
|
+
"""
|
80
|
+
raise NotImplementedError("generate() is not implemented.")
|
81
|
+
|
82
|
+
|
83
|
+
class ReauthoredModelWrapper(ModelWrapper):
|
84
|
+
"""A wrapper for the model reauthored with ai_edge_torch Generative API."""
|
85
|
+
|
86
|
+
def _init_kv_cache(self):
|
87
|
+
"""Returns an initialized KV cache."""
|
88
|
+
return kv_utils.KVCache.from_model_config(self.model.config)
|
89
|
+
|
90
|
+
def _get_extra_args_for_forward(self) -> dict[str, Any]:
|
91
|
+
"""Returns extra arguments for the forward() method."""
|
92
|
+
return {}
|
93
|
+
|
94
|
+
def _forward_with_kv_cache(
|
95
|
+
self,
|
96
|
+
tokens: torch.Tensor,
|
97
|
+
input_pos: torch.Tensor,
|
98
|
+
kv_cache: kv_utils.KVCache,
|
99
|
+
pixel_values: torch.Tensor,
|
100
|
+
) -> tuple[torch.Tensor, kv_utils.KVCache]:
|
101
|
+
"""Forwards the model and updates an external KV cache.
|
102
|
+
|
103
|
+
Args:
|
104
|
+
tokens (torch.Tensor): The input tokens to forward.
|
105
|
+
input_pos (torch.Tensor): The input positions to forward.
|
106
|
+
kv_cache (KVCache): The KV cache to forward.
|
107
|
+
pixel_values (torch.Tensor): The input pixel values to forward.
|
108
|
+
|
109
|
+
Returns:
|
110
|
+
The output logits and the updated KV cache.
|
111
|
+
"""
|
112
|
+
extra_args = self._get_extra_args_for_forward()
|
113
|
+
if self.export_config is not None:
|
114
|
+
# Verification requires logit outputs on prefill for comparison.
|
115
|
+
if not self.export_config.output_logits_on_prefill:
|
116
|
+
raise ValueError("Verifier requires logit output on prefill.")
|
117
|
+
extra_args["export_config"] = self.export_config
|
118
|
+
if pixel_values is not None:
|
119
|
+
extra_args["pixel_values"] = pixel_values
|
120
|
+
output = self.model.forward(tokens, input_pos, kv_cache, **extra_args)
|
121
|
+
return output["logits"], output["kv_cache"]
|
122
|
+
|
123
|
+
def forward(
|
124
|
+
self, tokens: torch.Tensor, pixel_values: torch.Tensor = None
|
125
|
+
) -> torch.Tensor:
|
126
|
+
input_pos = torch.arange(0, tokens.shape[1], dtype=torch.int)
|
127
|
+
logits, _ = self._forward_with_kv_cache(
|
128
|
+
tokens, input_pos, self._init_kv_cache(), pixel_values
|
129
|
+
)
|
130
|
+
return logits
|
131
|
+
|
132
|
+
def generate(
|
133
|
+
self,
|
134
|
+
prompts: torch.Tensor,
|
135
|
+
max_new_tokens: int,
|
136
|
+
pixel_values: torch.Tensor = None,
|
137
|
+
eos_token_id: Optional[int] = None,
|
138
|
+
) -> torch.IntTensor:
|
139
|
+
input_ids = prompts[0].int().tolist()
|
140
|
+
tokens = torch.tensor([input_ids])
|
141
|
+
input_pos = torch.arange(0, tokens.shape[1], dtype=torch.int)
|
142
|
+
kv_cache = self._init_kv_cache()
|
143
|
+
for _ in range(max_new_tokens):
|
144
|
+
logits, kv_cache = self._forward_with_kv_cache(
|
145
|
+
tokens, input_pos, kv_cache, pixel_values
|
146
|
+
)
|
147
|
+
generated_token = logits[0][-1].argmax().item()
|
148
|
+
input_ids.append(generated_token)
|
149
|
+
if eos_token_id is not None and generated_token == eos_token_id:
|
150
|
+
break
|
151
|
+
tokens = torch.tensor([[generated_token]])
|
152
|
+
input_pos = torch.tensor([len(input_ids) - 1])
|
153
|
+
pixel_values = None # Pass only for the first time.
|
154
|
+
return torch.tensor([input_ids])
|
155
|
+
|
156
|
+
|
157
|
+
class TokenizerWrapper(torch.nn.Module):
|
158
|
+
"""A wrapper for the tokenizer used for verification."""
|
159
|
+
|
160
|
+
def __init__(self, tokenizer: torch.nn.Module):
|
161
|
+
"""Initializes the wrapper.
|
162
|
+
|
163
|
+
Args:
|
164
|
+
tokenizer (torch.nn.Module): The tokenizer to wrap.
|
165
|
+
"""
|
166
|
+
super().__init__()
|
167
|
+
self.tokenizer = tokenizer
|
168
|
+
|
169
|
+
def encode(self, prompts: str) -> torch.Tensor:
|
170
|
+
"""Encodes the prompts to token IDs."""
|
171
|
+
return self.tokenizer.encode(prompts, return_tensors="pt")
|
172
|
+
|
173
|
+
def decode(self, token_ids: torch.Tensor) -> str:
|
174
|
+
"""Decodes the token IDs to a string."""
|
175
|
+
return self.tokenizer.decode(token_ids)
|
176
|
+
|
177
|
+
|
178
|
+
def verify_with_input_ids(
|
179
|
+
original_model: ModelWrapper,
|
180
|
+
reauthored_model: ReauthoredModelWrapper,
|
181
|
+
input_ids: List[int],
|
182
|
+
kv_cache_max_len: int = 1024,
|
183
|
+
rtol: float = 1e-05,
|
184
|
+
atol: float = 1e-05,
|
185
|
+
):
|
186
|
+
"""Verifies if the model reauthored generates the same output of the oringal.
|
187
|
+
|
188
|
+
It compares only one outputs from the original and the reauthored model.
|
189
|
+
|
190
|
+
Args:
|
191
|
+
original_model (ModelWrapper): The original model.
|
192
|
+
reauthored_model (ReauthoredModelWrapper): The model reauthored with
|
193
|
+
ai_edge_torch Generative API.
|
194
|
+
input_ids (List[int]): The input token IDs to forward with.
|
195
|
+
kv_cache_max_len (int): The maximum sequence length of the KV cache.
|
196
|
+
rtol (float): The relative tolerance for the comparison.
|
197
|
+
atol (float): The absolute tolerance for the comparison.
|
198
|
+
|
199
|
+
Raises:
|
200
|
+
AssertError if the model reauthored fails to generate the same output of the
|
201
|
+
original.
|
202
|
+
"""
|
203
|
+
tokens = torch.full((1, kv_cache_max_len), 0, dtype=torch.int, device="cpu")
|
204
|
+
tokens[0, : len(input_ids)] = torch.tensor([input_ids]).int()
|
205
|
+
|
206
|
+
logging.info("Forwarding the original model...")
|
207
|
+
outputs_original = original_model.forward(tokens)
|
208
|
+
logits_original = outputs_original[0, len(input_ids) - 1, :]
|
209
|
+
logging.info("logits_original: %s", logits_original)
|
210
|
+
|
211
|
+
logging.info("Forwarding the reauthored model...")
|
212
|
+
outputs_reauthored = reauthored_model.forward(tokens)
|
213
|
+
logits_reauthored = outputs_reauthored[0, len(input_ids) - 1, :]
|
214
|
+
logging.info("logits_reauthored: %s", logits_reauthored)
|
215
|
+
|
216
|
+
assert torch.allclose(
|
217
|
+
logits_original, logits_reauthored, rtol=rtol, atol=atol
|
218
|
+
)
|
219
|
+
|
220
|
+
|
221
|
+
def verify_model_with_prompts(
|
222
|
+
original_model: ModelWrapper,
|
223
|
+
reauthored_model: ReauthoredModelWrapper,
|
224
|
+
tokenizer: TokenizerWrapper,
|
225
|
+
prompts: str,
|
226
|
+
max_new_tokens: int,
|
227
|
+
):
|
228
|
+
"""Verifies if the model reauthored generates the same answer of the oringal.
|
229
|
+
|
230
|
+
It compares an answer, i.e. multiple continuous outputs generated by the
|
231
|
+
original and the reauthored model.
|
232
|
+
|
233
|
+
Args:
|
234
|
+
original_model (ModelWrapper): The original model.
|
235
|
+
reauthored_model (ReauthoredModelWrapper): The model reauthored with
|
236
|
+
ai_edge_torch Generative API.
|
237
|
+
tokenizer (TokenizerWrapper): The tokenizer.
|
238
|
+
prompts (str): The input prompts to generate answers.
|
239
|
+
max_new_tokens (int): The maximum number of new tokens to generate.
|
240
|
+
|
241
|
+
Raises:
|
242
|
+
AssertError if the model reauthored fails to generate the same answer of the
|
243
|
+
original.
|
244
|
+
"""
|
245
|
+
prompt_tokens = tokenizer.encode(prompts)
|
246
|
+
|
247
|
+
logging.info("Generating answer with the original model...")
|
248
|
+
outputs_original = original_model.generate(prompt_tokens, max_new_tokens)
|
249
|
+
response_original = tokenizer.decode(outputs_original[0])
|
250
|
+
logging.info("outputs_from_original_model: [[%s]]", response_original)
|
251
|
+
|
252
|
+
logging.info("Generating answer with the reauthored model...")
|
253
|
+
outputs_reauthored = reauthored_model.generate(
|
254
|
+
prompt_tokens,
|
255
|
+
max_new_tokens,
|
256
|
+
eos_token_id=getattr(tokenizer.tokenizer, "eos_token_id", None),
|
257
|
+
)
|
258
|
+
response_reauthored = tokenizer.decode(outputs_reauthored[0])
|
259
|
+
logging.info("outputs from reauthored model: [[%s]]", response_reauthored)
|
260
|
+
|
261
|
+
assert response_original == response_reauthored
|
262
|
+
|
263
|
+
|
264
|
+
def verify_reauthored_model(
|
265
|
+
original_model: ModelWrapper,
|
266
|
+
reauthored_model: ReauthoredModelWrapper,
|
267
|
+
tokenizer: TokenizerWrapper,
|
268
|
+
generate_prompts: List[str],
|
269
|
+
max_new_tokens: int = 30,
|
270
|
+
forward_input_ids: List[List[int]] = [[1, 2, 3, 4]],
|
271
|
+
rtol: float = 1e-05,
|
272
|
+
atol: float = 1e-05,
|
273
|
+
continue_on_failure: bool = False,
|
274
|
+
) -> bool:
|
275
|
+
"""Verifies the reauthored model against the original model.
|
276
|
+
|
277
|
+
It verifies the reauthored model with two methods:
|
278
|
+
1. It compares the output of the original and the reauthored model with an
|
279
|
+
arbitrary input.
|
280
|
+
2. It compares the answer generated by the original and the reauthored model
|
281
|
+
with a prompt.
|
282
|
+
|
283
|
+
It prints out "PASS" or "FAILED" to the console. It returns True if all
|
284
|
+
verification passes, False otherwise.
|
285
|
+
|
286
|
+
Args:
|
287
|
+
original_model (ModelWrapper): The original model.
|
288
|
+
reauthored_model (ReauthoredModelWrapper): The model reauthored with
|
289
|
+
ai_edge_torch Generative API.
|
290
|
+
tokenizer (TokenizerWrapper): The tokenizer.
|
291
|
+
generate_prompts (List[str]): List of the input prompts to generate answers.
|
292
|
+
max_new_tokens (int): The maximum number of new tokens to generate.
|
293
|
+
forward_input_ids (List[torch.Tensor]): List if ihe input token IDs to
|
294
|
+
forward with.
|
295
|
+
rtol (float): The relative tolerance for the comparison.
|
296
|
+
atol (float): The absolute tolerance for the comparison.
|
297
|
+
continue_on_failure (bool): If True, it continues to verify the next prompt
|
298
|
+
or input IDs even if a previous one fails.
|
299
|
+
"""
|
300
|
+
failure_count = 0
|
301
|
+
|
302
|
+
for input_ids in forward_input_ids:
|
303
|
+
logging.info("Verifying the reauthored model with input IDs: %s", input_ids)
|
304
|
+
try:
|
305
|
+
verify_with_input_ids(
|
306
|
+
original_model, reauthored_model, input_ids, rtol=rtol, atol=atol
|
307
|
+
)
|
308
|
+
except AssertionError as e:
|
309
|
+
logging.error("*** FAILED *** verify with input IDs: %s", input_ids)
|
310
|
+
failure_count += 1
|
311
|
+
if not continue_on_failure:
|
312
|
+
return False
|
313
|
+
else:
|
314
|
+
logging.info("*** PASSED *** verify with input IDs: %s", input_ids)
|
315
|
+
|
316
|
+
for prompts in generate_prompts:
|
317
|
+
logging.info("Verifying the reauthored model with prompts: %s", prompts)
|
318
|
+
try:
|
319
|
+
verify_model_with_prompts(
|
320
|
+
original_model, reauthored_model, tokenizer, prompts, max_new_tokens
|
321
|
+
)
|
322
|
+
except AssertionError as e:
|
323
|
+
logging.error("*** FAILED *** verify with prompts: %s", prompts)
|
324
|
+
failure_count += 1
|
325
|
+
if not continue_on_failure:
|
326
|
+
return False
|
327
|
+
else:
|
328
|
+
logging.info("*** PASSED *** verify with prompts: %s", prompts)
|
329
|
+
|
330
|
+
if failure_count == 0:
|
331
|
+
logging.info("*** PASSED *** verify_reauthored_model")
|
332
|
+
return True
|
333
|
+
else:
|
334
|
+
logging.error("*** FAILED *** verify_reauthored_model")
|
335
|
+
return False
|
@@ -0,0 +1,16 @@
|
|
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
|
+
from ai_edge_torch.lowertools import StableHLOCompositeBuilder
|
@@ -0,0 +1,153 @@
|
|
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
|
+
import copy
|
16
|
+
from typing import Any
|
17
|
+
import uuid
|
18
|
+
|
19
|
+
from ai_edge_torch import lowertools
|
20
|
+
from ai_edge_torch.hlfb.mark_pattern import fx_utils
|
21
|
+
from ai_edge_torch.hlfb.mark_pattern import pattern as pattern_module
|
22
|
+
import torch
|
23
|
+
|
24
|
+
|
25
|
+
@torch._dynamo.assume_constant_result
|
26
|
+
def _get_uuid() -> str:
|
27
|
+
return uuid.uuid4().hex
|
28
|
+
|
29
|
+
|
30
|
+
# TODO: Move to a general fx utils file.
|
31
|
+
def _prepose_placeholder_nodes(graph: torch.fx.Graph):
|
32
|
+
nodes = [node for node in graph.nodes if node.op == "placeholder"] + [
|
33
|
+
node for node in graph.nodes if node.op != "placeholder"
|
34
|
+
]
|
35
|
+
|
36
|
+
for a, b in zip(nodes, nodes[1:]):
|
37
|
+
if a.next is not b:
|
38
|
+
a.append(b)
|
39
|
+
return graph
|
40
|
+
|
41
|
+
|
42
|
+
def _insert_marker(
|
43
|
+
graph_module: torch.fx.GraphModule,
|
44
|
+
node: torch.fx.Node,
|
45
|
+
name: str,
|
46
|
+
pos: int,
|
47
|
+
id: str,
|
48
|
+
is_input: bool,
|
49
|
+
attr: dict[str, Any] = None,
|
50
|
+
):
|
51
|
+
attr = lowertools.serialize_composite_attr(attr) if attr else None
|
52
|
+
with graph_module.graph.inserting_after(node):
|
53
|
+
new_node = graph_module.graph.call_function(
|
54
|
+
lowertools.mark_tensor_op,
|
55
|
+
args=(node,),
|
56
|
+
kwargs={
|
57
|
+
"name": name,
|
58
|
+
"pos": pos,
|
59
|
+
"id": id,
|
60
|
+
"is_input": is_input,
|
61
|
+
"attr": attr,
|
62
|
+
},
|
63
|
+
)
|
64
|
+
|
65
|
+
new_node.meta = node.meta
|
66
|
+
return new_node
|
67
|
+
|
68
|
+
|
69
|
+
def mark_pattern(
|
70
|
+
graph_module: torch.fx.GraphModule,
|
71
|
+
pattern: pattern_module.Pattern,
|
72
|
+
) -> torch.fx.GraphModule:
|
73
|
+
"""Mark all existences of pattern graph in the GraphModule with fx pattern matching.
|
74
|
+
|
75
|
+
The marked subgraphs will be lowered in StableHLO composite ops.
|
76
|
+
|
77
|
+
Args:
|
78
|
+
graph_module (torch.fx.GraphModule): GraphModule to be matched and marked.
|
79
|
+
pattern (ai_edge_torch.hlfb.mark_pattern.Pattern): Pattern to match.
|
80
|
+
|
81
|
+
Returns:
|
82
|
+
The modified graph_module with additional marker ops in graph.
|
83
|
+
"""
|
84
|
+
# Create a copy of graph_module and sanitize it for pattern matching.
|
85
|
+
graph_module_to_match = copy.deepcopy(graph_module)
|
86
|
+
for n, m in zip(graph_module.graph.nodes, graph_module_to_match.graph.nodes):
|
87
|
+
m.meta["ORIGINAL_NODE"] = n
|
88
|
+
|
89
|
+
# Sanitize graph_module to match in the same way as pattern's graph_module.
|
90
|
+
graph_module_to_match = fx_utils.remove_clone_ops(graph_module_to_match)
|
91
|
+
|
92
|
+
match_with_attrs = pattern.match(graph_module_to_match)
|
93
|
+
|
94
|
+
for match, attr in match_with_attrs:
|
95
|
+
match_id = _get_uuid()
|
96
|
+
|
97
|
+
# NOTE: Current graph rewriter (_insert_marker) does not work perfectly
|
98
|
+
# with continuous matches e.g. matching (a + b) on (w + x + y + z). The
|
99
|
+
# rewritten results may be undetermined with false negative - some
|
100
|
+
# matches may not be marked in the lowering, while the marked ones would
|
101
|
+
# always be correct.
|
102
|
+
# TODO(cnchan): completely support mark_pattern on continuous matches.
|
103
|
+
for i, pattern_input_node in enumerate(pattern.input_nodes):
|
104
|
+
input_node = match.nodes_map[pattern_input_node]
|
105
|
+
new_input_node = _insert_marker(
|
106
|
+
graph_module,
|
107
|
+
input_node.meta["ORIGINAL_NODE"],
|
108
|
+
name=pattern.name,
|
109
|
+
pos=i,
|
110
|
+
id=match_id,
|
111
|
+
is_input=True,
|
112
|
+
)
|
113
|
+
|
114
|
+
# Only replace input by the marker node for those nodes used in the
|
115
|
+
# pattern.
|
116
|
+
in_pattern_nodes = set(match.nodes_map.values())
|
117
|
+
for user in input_node.users.keys():
|
118
|
+
if user not in in_pattern_nodes:
|
119
|
+
continue
|
120
|
+
|
121
|
+
user.meta["ORIGINAL_NODE"].replace_input_with(
|
122
|
+
input_node.meta["ORIGINAL_NODE"], new_input_node
|
123
|
+
)
|
124
|
+
# Pattern matching graph sanitization may remove clone ops, which means
|
125
|
+
# the user's input in the original graph may be a clone op. When
|
126
|
+
# replacing the input with the marker node, we need to further try
|
127
|
+
# replacing the input of the clone op that connects to the user.
|
128
|
+
for original_user_input in user.meta["ORIGINAL_NODE"].all_input_nodes:
|
129
|
+
if fx_utils.is_clone_op(original_user_input):
|
130
|
+
original_user_input.replace_input_with(
|
131
|
+
input_node.meta["ORIGINAL_NODE"], new_input_node
|
132
|
+
)
|
133
|
+
|
134
|
+
for i, pattern_output_node in enumerate(pattern.output_nodes):
|
135
|
+
output_node = match.nodes_map[pattern_output_node]
|
136
|
+
new_output_node = _insert_marker(
|
137
|
+
graph_module,
|
138
|
+
output_node.meta["ORIGINAL_NODE"],
|
139
|
+
name=pattern.name,
|
140
|
+
pos=i,
|
141
|
+
id=match_id,
|
142
|
+
is_input=False,
|
143
|
+
attr=attr, # torch_xla internal: only output marker needs attr.
|
144
|
+
)
|
145
|
+
output_node.meta["ORIGINAL_NODE"].replace_all_uses_with(new_output_node)
|
146
|
+
new_output_node.update_arg(0, output_node.meta["ORIGINAL_NODE"])
|
147
|
+
|
148
|
+
graph_module.graph.eliminate_dead_code()
|
149
|
+
_prepose_placeholder_nodes(graph_module.graph)
|
150
|
+
|
151
|
+
graph_module.graph.lint()
|
152
|
+
graph_module.recompile()
|
153
|
+
return graph_module
|
@@ -0,0 +1,69 @@
|
|
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
|
+
"""FX graph utilities for pattern matching clean ups."""
|
16
|
+
|
17
|
+
import torch
|
18
|
+
|
19
|
+
|
20
|
+
def is_clone_op(node: torch.fx.Node) -> bool:
|
21
|
+
"""Checks if the node is a clone op."""
|
22
|
+
return (
|
23
|
+
node.op == "call_function" and node.target == torch.ops.aten.clone.default
|
24
|
+
)
|
25
|
+
|
26
|
+
|
27
|
+
def remove_clone_ops(gm: torch.fx.GraphModule):
|
28
|
+
"""Removes clone ops from the graph.
|
29
|
+
|
30
|
+
torch export adds additional aten.clone nodes to produce contiguous in memory
|
31
|
+
tensors depending on tensor sizes for runtime efficiency. However, these
|
32
|
+
unpredictable clone nodes can break the pattern matching. Thus remove all
|
33
|
+
clones in model and pattern graphs.
|
34
|
+
|
35
|
+
Args:
|
36
|
+
gm: The graph module to remove clone ops from.
|
37
|
+
|
38
|
+
Returns:
|
39
|
+
The graph module with clone ops removed.
|
40
|
+
"""
|
41
|
+
for node in gm.graph.nodes:
|
42
|
+
if is_clone_op(node):
|
43
|
+
node.replace_all_uses_with(node.args[0])
|
44
|
+
gm.graph.erase_node(node)
|
45
|
+
|
46
|
+
gm.graph.lint()
|
47
|
+
gm.recompile()
|
48
|
+
return gm
|
49
|
+
|
50
|
+
|
51
|
+
def remove_dangling_args(gm: torch.fx.GraphModule):
|
52
|
+
"""Removes dangling args from the graph.
|
53
|
+
|
54
|
+
Args:
|
55
|
+
gm: The graph module to remove dangling args from.
|
56
|
+
|
57
|
+
Returns:
|
58
|
+
The graph module with dangling args removed.
|
59
|
+
"""
|
60
|
+
nodes_to_erase = []
|
61
|
+
for node in gm.graph.nodes:
|
62
|
+
if node.op == "placeholder" and len(node.users) == 0:
|
63
|
+
nodes_to_erase.append(node)
|
64
|
+
for node in nodes_to_erase:
|
65
|
+
gm.graph.erase_node(node)
|
66
|
+
|
67
|
+
gm.graph.lint()
|
68
|
+
gm.recompile()
|
69
|
+
return gm
|