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,142 @@
|
|
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 logging
|
17
|
+
from typing import List
|
18
|
+
|
19
|
+
from ai_edge_torch._convert import signature as signature_module
|
20
|
+
import tensorflow as tf
|
21
|
+
import torch
|
22
|
+
import torch.utils._pytree as pytree
|
23
|
+
|
24
|
+
|
25
|
+
def _flatten_list(l: List) -> List:
|
26
|
+
flattened = []
|
27
|
+
for item in l:
|
28
|
+
if isinstance(item, list):
|
29
|
+
flattened.extend(_flatten_list(item))
|
30
|
+
else:
|
31
|
+
flattened.append(item)
|
32
|
+
return flattened
|
33
|
+
|
34
|
+
|
35
|
+
def flat_dict_names(
|
36
|
+
tree_spec: pytree.TreeSpec, context: pytree.Context
|
37
|
+
) -> List[str]:
|
38
|
+
"""Given a TreeSpec, this produces a list of names for the leaves.
|
39
|
+
|
40
|
+
The list of names embeddeds the structure of the tree_spec. A nesting level is
|
41
|
+
indicated by an `_` and elements in a list are indicated by `_<index>`.
|
42
|
+
|
43
|
+
TODO b/361601485: The flattening of names is not collision-free and needs to
|
44
|
+
be revised.
|
45
|
+
|
46
|
+
Args:
|
47
|
+
tree_spec: The TreeSpec to extract the names from.
|
48
|
+
context: The context used to check if the provided spec belongs to a
|
49
|
+
dictionary or a list.
|
50
|
+
|
51
|
+
Returns:
|
52
|
+
A list of flattened names.
|
53
|
+
"""
|
54
|
+
flat_names = []
|
55
|
+
if context is None:
|
56
|
+
for i, spec in enumerate(tree_spec):
|
57
|
+
if spec.children_specs:
|
58
|
+
flat_names.extend([
|
59
|
+
f"{i}_{name}"
|
60
|
+
for name in flat_dict_names(spec.children_specs, spec.context)
|
61
|
+
])
|
62
|
+
else:
|
63
|
+
flat_names.append(f"{i}")
|
64
|
+
else:
|
65
|
+
flat_ctx = _flatten_list(context)
|
66
|
+
for prefix, spec in zip(flat_ctx, tree_spec):
|
67
|
+
leaf_flat_names = flat_dict_names(spec.children_specs, spec.context)
|
68
|
+
if leaf_flat_names:
|
69
|
+
flat_names.extend([f"{prefix}_{name}" for name in leaf_flat_names])
|
70
|
+
else:
|
71
|
+
flat_names.append(prefix)
|
72
|
+
|
73
|
+
return flat_names
|
74
|
+
|
75
|
+
|
76
|
+
def _torch_to_tf_variable(torch_tensor: torch.Tensor):
|
77
|
+
if not torch_tensor.is_contiguous():
|
78
|
+
torch_tensor = torch_tensor.contiguous()
|
79
|
+
|
80
|
+
try:
|
81
|
+
dlpack_capsule = torch.utils.dlpack.to_dlpack(torch_tensor)
|
82
|
+
tf_tensor = tf.experimental.dlpack.from_dlpack(dlpack_capsule)
|
83
|
+
except Exception:
|
84
|
+
logging.info(
|
85
|
+
"Can not use dlpack to convert torch tensors. Falling back to numpy."
|
86
|
+
)
|
87
|
+
nparray = torch_tensor.cpu().detach().numpy()
|
88
|
+
tf_tensor = tf.convert_to_tensor(nparray)
|
89
|
+
|
90
|
+
return tf.Variable(tf_tensor, trainable=False)
|
91
|
+
|
92
|
+
|
93
|
+
def _get_states(
|
94
|
+
exported_programs: list[torch.export.ExportedProgram],
|
95
|
+
signatures: list[signature_module.Signature],
|
96
|
+
):
|
97
|
+
for exported_program, signature in zip(exported_programs, signatures):
|
98
|
+
args, _ = exported_program.example_inputs
|
99
|
+
# Calling this to get **all** the state including model buffers.
|
100
|
+
_flat_input_args = exported_program._graph_module_flat_inputs(args, {})
|
101
|
+
for tensor, input_spec in zip(
|
102
|
+
_flat_input_args, exported_program.graph_signature.input_specs
|
103
|
+
):
|
104
|
+
# Only interested in Tensors that are part of the state (and not user input).
|
105
|
+
if (
|
106
|
+
not isinstance(tensor, torch.Tensor)
|
107
|
+
or input_spec.kind
|
108
|
+
== torch.export.graph_signature.InputKind.USER_INPUT
|
109
|
+
):
|
110
|
+
continue
|
111
|
+
yield signature, tensor, input_spec
|
112
|
+
|
113
|
+
|
114
|
+
def _tensor_unique_id(tensor: torch.Tensor):
|
115
|
+
return (
|
116
|
+
str(tensor.device),
|
117
|
+
tensor.shape,
|
118
|
+
tensor.stride(),
|
119
|
+
tensor.untyped_storage().data_ptr(),
|
120
|
+
)
|
121
|
+
|
122
|
+
|
123
|
+
def gather_state_dict(
|
124
|
+
exported_programs: list[torch.export.ExportedProgram],
|
125
|
+
signatures: list[signature_module.Signature],
|
126
|
+
):
|
127
|
+
deduped_tensor_map = {}
|
128
|
+
|
129
|
+
for _, tensor, _ in _get_states(exported_programs, signatures):
|
130
|
+
unique_id = _tensor_unique_id(tensor)
|
131
|
+
deduped_tensor_map[unique_id] = _torch_to_tf_variable(tensor)
|
132
|
+
|
133
|
+
state_dict = {}
|
134
|
+
for signature, tensor, input_spec in _get_states(
|
135
|
+
exported_programs, signatures
|
136
|
+
):
|
137
|
+
unique_id = _tensor_unique_id(tensor)
|
138
|
+
state_dict[signature.name + "_" + input_spec.target] = deduped_tensor_map[
|
139
|
+
unique_id
|
140
|
+
]
|
141
|
+
|
142
|
+
return state_dict, list(deduped_tensor_map.values())
|
@@ -0,0 +1,260 @@
|
|
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 dataclasses
|
17
|
+
import tempfile
|
18
|
+
from typing import Any, Dict, List, Optional, Tuple
|
19
|
+
|
20
|
+
from ai_edge_torch import odml_torch
|
21
|
+
from ai_edge_torch._convert import conversion_utils
|
22
|
+
from ai_edge_torch._convert import signature as signature_module
|
23
|
+
from ai_edge_torch.lowertools import common_utils
|
24
|
+
from ai_edge_torch.lowertools import translate_recipe
|
25
|
+
from ai_edge_torch.odml_torch import export
|
26
|
+
from ai_edge_torch.odml_torch import export_utils
|
27
|
+
from ai_edge_torch.quantize import quant_config as qcfg
|
28
|
+
import tensorflow as tf
|
29
|
+
import torch
|
30
|
+
|
31
|
+
from tensorflow.compiler.tf2xla.python import xla as tfxla
|
32
|
+
from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metadata_fb
|
33
|
+
|
34
|
+
MlirBundle = odml_torch.export.MlirLowered
|
35
|
+
|
36
|
+
|
37
|
+
@dataclasses.dataclass
|
38
|
+
class MergedBundle:
|
39
|
+
"""A bundle of MlirLowered that has been merged."""
|
40
|
+
|
41
|
+
bundles: list[odml_torch.export.MlirLowered]
|
42
|
+
exported_programs: list[torch.export.ExportedProgram]
|
43
|
+
deduped_tf_vars: list[tf.Variable]
|
44
|
+
|
45
|
+
|
46
|
+
def torch_dtype_to_tf(dtype):
|
47
|
+
return {
|
48
|
+
torch.double: tf.float64,
|
49
|
+
torch.float32: tf.float32,
|
50
|
+
torch.half: tf.float16,
|
51
|
+
torch.long: tf.int64,
|
52
|
+
torch.int32: tf.int32,
|
53
|
+
torch.int16: tf.int16,
|
54
|
+
torch.bool: tf.bool,
|
55
|
+
}.get(dtype)
|
56
|
+
|
57
|
+
|
58
|
+
def _get_shape_with_dynamic(signature: export.VariableSignature):
|
59
|
+
return [
|
60
|
+
None if export_utils.is_torch_dynamic(s) else s for s in signature.shape
|
61
|
+
]
|
62
|
+
|
63
|
+
|
64
|
+
def _extract_call_args(
|
65
|
+
bundle: export.MlirLowered,
|
66
|
+
args: Tuple[Any],
|
67
|
+
tf_state_dict: Dict[str, tf.Variable],
|
68
|
+
):
|
69
|
+
call_args = []
|
70
|
+
for sig in bundle.input_signature:
|
71
|
+
if sig.input_spec.is_user_input:
|
72
|
+
call_args.append(args[sig.input_spec.i])
|
73
|
+
elif sig.input_spec.is_parameter:
|
74
|
+
name = sig.input_spec.name
|
75
|
+
call_args.append(tf_state_dict[name])
|
76
|
+
return call_args
|
77
|
+
|
78
|
+
|
79
|
+
def _wrap_as_tf_func(
|
80
|
+
bundle: export.MlirLowered,
|
81
|
+
tf_state_dict: Dict[str, tf.Variable],
|
82
|
+
exported_program: torch.export.ExportedProgram,
|
83
|
+
):
|
84
|
+
def inner(*args):
|
85
|
+
t_outs = [torch_dtype_to_tf(sig.dtype) for sig in bundle.output_signature]
|
86
|
+
s_outs = [_get_shape_with_dynamic(sig) for sig in bundle.output_signature]
|
87
|
+
call_args = _extract_call_args(bundle, args, tf_state_dict)
|
88
|
+
# HACK: In OSS, we use MLIR pybinding and StableHLO dialect from JAX's
|
89
|
+
# build, which may not have the same StableHLO version as what used in
|
90
|
+
# TFLite converter. Therefore we always serialize MLIR module in VHLO.
|
91
|
+
# TODO(b/362798610) Build MLIR pybinding in ai-edge-torch release.
|
92
|
+
call_module_return = tfxla.call_module(
|
93
|
+
tuple(call_args),
|
94
|
+
version=5,
|
95
|
+
Tout=t_outs, # dtype information
|
96
|
+
Sout=s_outs, # Shape information
|
97
|
+
function_list=[],
|
98
|
+
module=bundle.module_bytecode_vhlo,
|
99
|
+
)
|
100
|
+
spec = exported_program.call_spec.out_spec
|
101
|
+
|
102
|
+
# The module returning a flat array.
|
103
|
+
if not spec.context:
|
104
|
+
return call_module_return
|
105
|
+
|
106
|
+
flat_names = common_utils.flat_dict_names(spec.children_specs, spec.context)
|
107
|
+
return {name: value for name, value in zip(flat_names, call_module_return)}
|
108
|
+
|
109
|
+
return inner
|
110
|
+
|
111
|
+
|
112
|
+
def _make_tf_signature(
|
113
|
+
input_signature: list[export.VariableSignature],
|
114
|
+
signature: signature_module.Signature,
|
115
|
+
) -> List[tf.TensorSpec]:
|
116
|
+
input_names = signature.flat_arg_names
|
117
|
+
user_input_signature = sorted(
|
118
|
+
[sig for sig in input_signature if sig.input_spec.is_user_input],
|
119
|
+
key=lambda sig: sig.input_spec.i,
|
120
|
+
)
|
121
|
+
tf_signature = []
|
122
|
+
|
123
|
+
for sig in user_input_signature:
|
124
|
+
shape = _get_shape_with_dynamic(sig)
|
125
|
+
tf_signature.append(
|
126
|
+
tf.TensorSpec(
|
127
|
+
shape=shape,
|
128
|
+
dtype=torch_dtype_to_tf(sig.dtype),
|
129
|
+
name=input_names[sig.input_spec.i],
|
130
|
+
)
|
131
|
+
)
|
132
|
+
return tf_signature
|
133
|
+
|
134
|
+
|
135
|
+
def merged_bundle_to_tfl_model(
|
136
|
+
merged_bundle: MergedBundle,
|
137
|
+
signatures: list[signature_module.Signature],
|
138
|
+
*,
|
139
|
+
quant_config: Optional[qcfg.QuantConfig] = None,
|
140
|
+
_tfl_converter_flags: dict = {},
|
141
|
+
_saved_model_dir: Optional[str] = None,
|
142
|
+
):
|
143
|
+
tf_state_dict = merged_bundle.bundles[0].state_dict
|
144
|
+
|
145
|
+
tf_signatures = [
|
146
|
+
_make_tf_signature(bundle.input_signature, sig)
|
147
|
+
for bundle, sig in zip(merged_bundle.bundles, signatures)
|
148
|
+
]
|
149
|
+
tf_functions = [
|
150
|
+
_wrap_as_tf_func(bundle, tf_state_dict, ep)
|
151
|
+
for bundle, ep in zip(
|
152
|
+
merged_bundle.bundles, merged_bundle.exported_programs
|
153
|
+
)
|
154
|
+
]
|
155
|
+
|
156
|
+
tf_module = tf.Module()
|
157
|
+
tf_module.f = []
|
158
|
+
|
159
|
+
for tf_sig, func in zip(tf_signatures, tf_functions):
|
160
|
+
tf_module.f.append(
|
161
|
+
tf.function(
|
162
|
+
func,
|
163
|
+
input_signature=tf_sig,
|
164
|
+
)
|
165
|
+
)
|
166
|
+
|
167
|
+
tf_module._variables = merged_bundle.deduped_tf_vars
|
168
|
+
|
169
|
+
tf_concrete_funcs = [
|
170
|
+
func.get_concrete_function(*tf_sig)
|
171
|
+
for func, tf_sig in zip(tf_module.f, tf_signatures)
|
172
|
+
]
|
173
|
+
|
174
|
+
# We need to temporarily save since TFLite's from_concrete_functions does not
|
175
|
+
# allow providing names for each of the concrete functions.
|
176
|
+
with tempfile.TemporaryDirectory() as temp_dir_path:
|
177
|
+
if _saved_model_dir is not None:
|
178
|
+
temp_dir_path = _saved_model_dir
|
179
|
+
|
180
|
+
tf.saved_model.save(
|
181
|
+
tf_module,
|
182
|
+
temp_dir_path,
|
183
|
+
signatures={
|
184
|
+
sig.name: tf_concrete_funcs[idx]
|
185
|
+
for idx, sig in enumerate(signatures)
|
186
|
+
},
|
187
|
+
)
|
188
|
+
|
189
|
+
converter = tf.lite.TFLiteConverter.from_saved_model(temp_dir_path)
|
190
|
+
converter._set_original_model_type(conversion_metadata_fb.ModelType.PYTORCH)
|
191
|
+
converter._experimental_enable_composite_direct_lowering = True
|
192
|
+
converter._experimental_enable_dynamic_update_slice = True
|
193
|
+
converter.model_origin_framework = "PYTORCH"
|
194
|
+
|
195
|
+
conversion_utils.set_tfl_converter_quant_flags(converter, quant_config)
|
196
|
+
if (
|
197
|
+
quant_config is not None
|
198
|
+
and quant_config._quantizer_mode
|
199
|
+
== quant_config._QuantizerMode.AI_EDGE_QUANTIZER
|
200
|
+
):
|
201
|
+
translated_recipe = translate_recipe.translate_to_ai_edge_recipe(
|
202
|
+
quant_config.generative_recipe
|
203
|
+
)
|
204
|
+
|
205
|
+
conversion_utils.apply_tfl_converter_flags(converter, _tfl_converter_flags)
|
206
|
+
|
207
|
+
tflite_model = converter.convert()
|
208
|
+
|
209
|
+
if (
|
210
|
+
quant_config is not None
|
211
|
+
and quant_config._quantizer_mode
|
212
|
+
== quant_config._QuantizerMode.AI_EDGE_QUANTIZER
|
213
|
+
):
|
214
|
+
tflite_model = translate_recipe.quantize_model(
|
215
|
+
tflite_model, translated_recipe
|
216
|
+
)
|
217
|
+
|
218
|
+
return tflite_model
|
219
|
+
|
220
|
+
|
221
|
+
def exported_program_to_mlir_text(
|
222
|
+
exported_program: torch.export.ExportedProgram,
|
223
|
+
) -> str:
|
224
|
+
"""Converts a ExportedProgram to a MLIR text."""
|
225
|
+
return odml_torch.export.exported_program_to_mlir(exported_program).get_text(
|
226
|
+
enable_debug_info=True
|
227
|
+
)
|
228
|
+
|
229
|
+
|
230
|
+
def exported_program_to_mlir(
|
231
|
+
exported_program: torch.export.ExportedProgram,
|
232
|
+
sample_args: tuple[torch.Tensor],
|
233
|
+
) -> export.MlirLowered:
|
234
|
+
"""Converts a ExportedProgram to a MlirLowered."""
|
235
|
+
return odml_torch.export.exported_program_to_mlir(exported_program)
|
236
|
+
|
237
|
+
|
238
|
+
def merge_mlir_bundles(
|
239
|
+
bundles: list[export.MlirLowered],
|
240
|
+
signatures: list[signature_module.Signature],
|
241
|
+
exported_programs: list[torch.export.ExportedProgram],
|
242
|
+
) -> MergedBundle:
|
243
|
+
"""Merges a list of MlirLowered into one."""
|
244
|
+
state_dict, deduped_vars = common_utils.gather_state_dict(
|
245
|
+
exported_programs, signatures
|
246
|
+
)
|
247
|
+
|
248
|
+
merged_bundle = MergedBundle(
|
249
|
+
bundles=bundles.copy(),
|
250
|
+
exported_programs=exported_programs,
|
251
|
+
deduped_tf_vars=deduped_vars,
|
252
|
+
)
|
253
|
+
for bundle, signature in zip(merged_bundle.bundles, signatures):
|
254
|
+
bundle.state_dict = state_dict
|
255
|
+
|
256
|
+
for var_sig in bundle.input_signature:
|
257
|
+
if var_sig.input_spec.is_parameter:
|
258
|
+
var_sig.input_spec.name = signature.name + "_" + var_sig.input_spec.name
|
259
|
+
|
260
|
+
return merged_bundle
|
@@ -0,0 +1,62 @@
|
|
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 re
|
17
|
+
from typing import Optional
|
18
|
+
from ai_edge_torch import _config
|
19
|
+
from absl.testing import absltest as googletest
|
20
|
+
|
21
|
+
config = _config.config
|
22
|
+
|
23
|
+
|
24
|
+
def _extract_backend_configs(mlir):
|
25
|
+
mlir = mlir.replace("\\22", '"')
|
26
|
+
configs = []
|
27
|
+
for match in re.finditer(r"backend_config\s*=\s*\"(\{.*\})\"", mlir):
|
28
|
+
configs.append(match.group(1))
|
29
|
+
return "\n".join(configs)
|
30
|
+
|
31
|
+
|
32
|
+
def assert_string_count(
|
33
|
+
test_case: googletest.TestCase,
|
34
|
+
mlir: str,
|
35
|
+
torch_xla_pattern_counter: dict[str, int],
|
36
|
+
odml_torch_pattern_counter: dict[str, int],
|
37
|
+
odml_torch_attr_counter: Optional[dict[str, int]] = None,
|
38
|
+
):
|
39
|
+
|
40
|
+
if odml_torch_attr_counter is None:
|
41
|
+
odml_torch_attr_counter = {}
|
42
|
+
|
43
|
+
if config.use_torch_xla:
|
44
|
+
for key in torch_xla_pattern_counter:
|
45
|
+
test_case.assertEqual(
|
46
|
+
mlir.count(key),
|
47
|
+
torch_xla_pattern_counter[key],
|
48
|
+
)
|
49
|
+
else:
|
50
|
+
for key in odml_torch_pattern_counter:
|
51
|
+
test_case.assertEqual(
|
52
|
+
mlir.count(key),
|
53
|
+
odml_torch_pattern_counter[key],
|
54
|
+
)
|
55
|
+
backend_configs = _extract_backend_configs(mlir)
|
56
|
+
print("backend_configs:")
|
57
|
+
print(backend_configs)
|
58
|
+
for key in odml_torch_attr_counter:
|
59
|
+
test_case.assertEqual(
|
60
|
+
backend_configs.count(key),
|
61
|
+
odml_torch_attr_counter[key],
|
62
|
+
)
|