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,288 @@
|
|
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
|
+
"""Mark pattern."""
|
16
|
+
|
17
|
+
import dataclasses
|
18
|
+
from typing import Any, Callable, Optional, Union
|
19
|
+
|
20
|
+
from ai_edge_torch import fx_pass_base
|
21
|
+
from ai_edge_torch.hlfb.mark_pattern import fx_utils
|
22
|
+
import torch
|
23
|
+
|
24
|
+
Graph = torch.fx.Graph
|
25
|
+
GraphModule = torch.fx.GraphModule
|
26
|
+
TensorArgument = torch.export.graph_signature.TensorArgument
|
27
|
+
InternalMatch = torch.fx.passes.utils.matcher_utils.InternalMatch
|
28
|
+
SubgraphMatcher = torch.fx.passes.utils.matcher_utils.SubgraphMatcher
|
29
|
+
|
30
|
+
|
31
|
+
def _are_equal(x: Any, y: Any) -> bool:
|
32
|
+
if type(x) != type(y):
|
33
|
+
return False
|
34
|
+
if type(x) in [int, str]:
|
35
|
+
return x == y
|
36
|
+
if isinstance(x, float):
|
37
|
+
rel_tol = 1e-07
|
38
|
+
abs_tol = 0.0
|
39
|
+
return abs(x - y) <= max(rel_tol * max(abs(x), abs(y)), abs_tol)
|
40
|
+
if isinstance(x, list):
|
41
|
+
if len(x) != len(y):
|
42
|
+
return False
|
43
|
+
return all([_are_equal(a, b) for a, b in zip(x, y)])
|
44
|
+
|
45
|
+
raise Exception(f"Cannot compare type: {type(x)}")
|
46
|
+
|
47
|
+
|
48
|
+
@dataclasses.dataclass
|
49
|
+
class ScalarAttrTracker:
|
50
|
+
"""ScalarAttrTracker is used to track the occurrence of a pattern's
|
51
|
+
|
52
|
+
scalar arg/attr in the pattern decomposed graph. Since a scalar attr
|
53
|
+
to the pattern can be transformed and turned into a/some ops' scalar
|
54
|
+
arg in the decomposed graph, it would be hard to programmatically get
|
55
|
+
the attr value from the pattern match. With the tracker and tracking info,
|
56
|
+
we could target the position of the decomposed op's scalar arg derived
|
57
|
+
from the pattern arg/attr and retrieve the value from the InternalMatch.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
name (str): name of the attr to track.
|
61
|
+
pattern_arg_pos (int): the index of the attr to track in the pattern's
|
62
|
+
export_args.
|
63
|
+
transform (Callable): the transform function used when targeting the
|
64
|
+
occurrence of the attr value in the decomposed graph. An attr value may be
|
65
|
+
transformed during the decomposition and appear as a derived value.
|
66
|
+
inverse_transform (Callable): the inverse transform function that maps the
|
67
|
+
transformed value back to the original attr value.
|
68
|
+
"""
|
69
|
+
|
70
|
+
attr_name: str
|
71
|
+
pattern_arg_pos: int
|
72
|
+
transform: Callable = lambda x: x
|
73
|
+
inverse_transform: Callable = lambda x: x
|
74
|
+
_source_targets: list[tuple[Any, Any]] = dataclasses.field(
|
75
|
+
default_factory=list
|
76
|
+
)
|
77
|
+
|
78
|
+
def track(self, *sources):
|
79
|
+
"""Register magic values to track the (transformed) attr values in
|
80
|
+
|
81
|
+
the pattern decomposed graph.
|
82
|
+
"""
|
83
|
+
for source in sources:
|
84
|
+
target = self.transform(source)
|
85
|
+
if not _are_equal(self.inverse_transform(target), source):
|
86
|
+
raise Exception(
|
87
|
+
f"Invalid transform/inverse_transform for {self.attr_name}"
|
88
|
+
)
|
89
|
+
self._source_targets.append([source, target])
|
90
|
+
return self
|
91
|
+
|
92
|
+
|
93
|
+
@dataclasses.dataclass
|
94
|
+
class ScalarAttrLocation:
|
95
|
+
attr_name: str
|
96
|
+
node_name: str
|
97
|
+
pos: Union[int, str]
|
98
|
+
_tracker: ScalarAttrTracker
|
99
|
+
|
100
|
+
@property
|
101
|
+
def index(self):
|
102
|
+
return self.pos if isinstance(self.pos, int) else None
|
103
|
+
|
104
|
+
@property
|
105
|
+
def key(self):
|
106
|
+
return self.pos if isinstance(self.pos, str) else None
|
107
|
+
|
108
|
+
|
109
|
+
def _find_scalar_attr(
|
110
|
+
pattern_module: torch.nn.Module,
|
111
|
+
export_args: tuple[Any],
|
112
|
+
tracker: ScalarAttrTracker,
|
113
|
+
decomp_table=None,
|
114
|
+
) -> ScalarAttrLocation:
|
115
|
+
scalar_loc_intersections = None
|
116
|
+
for source, target in tracker._source_targets:
|
117
|
+
track_args = list(export_args)
|
118
|
+
track_args[tracker.pattern_arg_pos] = source
|
119
|
+
ep = torch.export.export(pattern_module, tuple(track_args))
|
120
|
+
if decomp_table is not None:
|
121
|
+
ep = fx_pass_base.run_passes(ep, [fx_pass_base.CanonicalizePass()])
|
122
|
+
ep = ep.run_decompositions(decomp_table)
|
123
|
+
|
124
|
+
scalar_locs = set()
|
125
|
+
nodes = ep.graph_module.graph.nodes
|
126
|
+
for n in nodes:
|
127
|
+
for arg_pos, arg in enumerate(n.args):
|
128
|
+
if type(arg) == type(target) and arg == target:
|
129
|
+
scalar_locs.add((n.name, arg_pos))
|
130
|
+
for attr, val in n.kwargs.items():
|
131
|
+
if type(val) == type(target) and val == target:
|
132
|
+
scalar_locs.add((n.name, attr))
|
133
|
+
|
134
|
+
if scalar_loc_intersections is None:
|
135
|
+
scalar_loc_intersections = scalar_locs
|
136
|
+
else:
|
137
|
+
scalar_loc_intersections = scalar_loc_intersections & scalar_locs
|
138
|
+
|
139
|
+
if not scalar_loc_intersections:
|
140
|
+
break
|
141
|
+
|
142
|
+
if not scalar_loc_intersections:
|
143
|
+
return None
|
144
|
+
# Choose any occurrence as the attr provider
|
145
|
+
node_name, pos = scalar_loc_intersections.pop()
|
146
|
+
return ScalarAttrLocation(tracker.attr_name, node_name, pos, _tracker=tracker)
|
147
|
+
|
148
|
+
|
149
|
+
class Pattern:
|
150
|
+
|
151
|
+
def __init__(
|
152
|
+
self,
|
153
|
+
name: str,
|
154
|
+
module: Union[Callable, torch.nn.Module],
|
155
|
+
export_args: tuple[Any],
|
156
|
+
*,
|
157
|
+
attr_builder: Callable[
|
158
|
+
["Pattern", GraphModule, InternalMatch], Optional[dict[str, Any]]
|
159
|
+
] = None,
|
160
|
+
scalar_attr_trackers: list[ScalarAttrTracker] = None,
|
161
|
+
decomp_table: Optional[dict[torch._ops.OperatorBase, Callable]] = None,
|
162
|
+
):
|
163
|
+
"""The PyTorch computation pattern to match against a model.
|
164
|
+
|
165
|
+
Args:
|
166
|
+
name (str): the name of the pattern. It would be propagated to the `name`
|
167
|
+
attr in StableHLO composite ops for the matched model subgraphs in the
|
168
|
+
lowering.
|
169
|
+
module (torch.nn.Module or Callable): the PyTorch computation.
|
170
|
+
export_args (tuple[Any]): the args used to export the pattern module with
|
171
|
+
torch.export.export. If export_args contains non-tensor Python scalars,
|
172
|
+
there must be a corresponding attr tracker in `scalar_attr_trackers` for
|
173
|
+
each scalar arg. attr_builder (Callable[[Pattern, GraphModule,
|
174
|
+
InternalMatch], Optional[dict[str, Any]]]): the callable that produces
|
175
|
+
the a scalar attrs dict, which would be propagated to `attr` in
|
176
|
+
StableHLO composite ops for the matched model subgraphs in the lowering.
|
177
|
+
scalar_attr_trackers (list[ScalarAttrTracker]): the trackers for scalar
|
178
|
+
args in `export_args`, which are used to track the attr occurrence(s)
|
179
|
+
and retrieve their values from the matched subgraph.
|
180
|
+
decomp_table (Optional[dict[torch._ops.OperatorBase, Callable]]): The
|
181
|
+
decomposition table to be run on the pattern's exported program.
|
182
|
+
"""
|
183
|
+
if not isinstance(module, torch.nn.Module):
|
184
|
+
|
185
|
+
class PatternModule(torch.nn.Module):
|
186
|
+
|
187
|
+
def __init__(self, func):
|
188
|
+
super().__init__()
|
189
|
+
self.func = func
|
190
|
+
|
191
|
+
def forward(self, *args, **kwargs):
|
192
|
+
return self.func(*args, **kwargs)
|
193
|
+
|
194
|
+
module = PatternModule(module).eval()
|
195
|
+
|
196
|
+
self.name = name
|
197
|
+
self.attr_builder = attr_builder
|
198
|
+
self._scalar_attr_trackers = (
|
199
|
+
scalar_attr_trackers if scalar_attr_trackers else []
|
200
|
+
)
|
201
|
+
|
202
|
+
exported_program = torch.export.export(module, export_args)
|
203
|
+
if decomp_table is not None:
|
204
|
+
exported_program = fx_pass_base.run_passes(
|
205
|
+
exported_program, [fx_pass_base.CanonicalizePass()]
|
206
|
+
)
|
207
|
+
exported_program = exported_program.run_decompositions(decomp_table)
|
208
|
+
|
209
|
+
self.exported_program = exported_program
|
210
|
+
self.graph_module = self.exported_program.graph_module
|
211
|
+
|
212
|
+
self._scalar_attr_locations = []
|
213
|
+
for tracker in self._scalar_attr_trackers:
|
214
|
+
self._scalar_attr_locations.append(
|
215
|
+
_find_scalar_attr(
|
216
|
+
module, export_args, tracker, decomp_table=decomp_table
|
217
|
+
)
|
218
|
+
)
|
219
|
+
|
220
|
+
# Sanitize graph_module for more precise pattern matching.
|
221
|
+
# The graph_module to match against this pattern should apply equivalent
|
222
|
+
# sanitization.
|
223
|
+
self.graph_module = fx_utils.remove_clone_ops(self.graph_module)
|
224
|
+
self.graph_module = fx_utils.remove_dangling_args(self.graph_module)
|
225
|
+
|
226
|
+
# Builds list of ordered input and output nodes.
|
227
|
+
self.graph_nodes_map = {}
|
228
|
+
for node in self.graph_module.graph.nodes:
|
229
|
+
self.graph_nodes_map[node.name] = node
|
230
|
+
|
231
|
+
self.input_nodes = tuple(
|
232
|
+
self.graph_nodes_map[spec.arg.name]
|
233
|
+
for spec in self.exported_program.graph_signature.input_specs
|
234
|
+
if isinstance(spec.arg, TensorArgument)
|
235
|
+
)
|
236
|
+
self.output_nodes = tuple(
|
237
|
+
self.graph_nodes_map[spec.arg.name]
|
238
|
+
for spec in self.exported_program.graph_signature.output_specs
|
239
|
+
)
|
240
|
+
|
241
|
+
def register_attr_builder(self, attr_builder):
|
242
|
+
self.attr_builder = attr_builder
|
243
|
+
return attr_builder
|
244
|
+
|
245
|
+
def match(
|
246
|
+
self,
|
247
|
+
graph_module: GraphModule,
|
248
|
+
) -> list[tuple[InternalMatch, dict[str, Any]]]:
|
249
|
+
matcher = SubgraphMatcher(
|
250
|
+
self.graph_module.graph,
|
251
|
+
match_output=False,
|
252
|
+
match_placeholder=False,
|
253
|
+
remove_overlapping_matches=True,
|
254
|
+
ignore_literals=True,
|
255
|
+
)
|
256
|
+
matches = matcher.match(graph_module.graph)
|
257
|
+
|
258
|
+
match_with_attrs = []
|
259
|
+
# Graph traversal must be done in the reverser order (from SubgraphMatcher).
|
260
|
+
for match in matches[::-1]:
|
261
|
+
if self.attr_builder is not None:
|
262
|
+
attrs = self.attr_builder(self, graph_module, match)
|
263
|
+
else:
|
264
|
+
attrs = {}
|
265
|
+
|
266
|
+
for loc in self._scalar_attr_locations:
|
267
|
+
attrs[loc.attr_name] = self._get_attr_value_from_pattern_match(
|
268
|
+
match, loc
|
269
|
+
)
|
270
|
+
|
271
|
+
attrs = attrs if attrs else None
|
272
|
+
match_with_attrs.append((match, attrs))
|
273
|
+
return match_with_attrs
|
274
|
+
|
275
|
+
def _get_attr_value_from_pattern_match(
|
276
|
+
self,
|
277
|
+
match: InternalMatch,
|
278
|
+
loc: ScalarAttrLocation,
|
279
|
+
):
|
280
|
+
matched_val = None
|
281
|
+
for k, v in match.nodes_map.items():
|
282
|
+
if k.name == loc.node_name:
|
283
|
+
if loc.index:
|
284
|
+
matched_val = v.args[loc.index]
|
285
|
+
elif loc.key in v.kwargs.keys():
|
286
|
+
matched_val = v.kwargs[loc.key]
|
287
|
+
attr_val = loc._tracker.inverse_transform(matched_val)
|
288
|
+
return attr_val
|
@@ -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,185 @@
|
|
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
|
+
"""Tests for mark_pattern."""
|
16
|
+
|
17
|
+
from ai_edge_torch import lowertools
|
18
|
+
from ai_edge_torch.hlfb import mark_pattern
|
19
|
+
from ai_edge_torch.hlfb.mark_pattern import pattern as pattern_module
|
20
|
+
import torch
|
21
|
+
|
22
|
+
from absl.testing import absltest as googletest
|
23
|
+
|
24
|
+
|
25
|
+
def _export_stablehlo_mlir(model, args=None):
|
26
|
+
if not isinstance(model, torch.export.ExportedProgram):
|
27
|
+
ep = torch.export.export(model, args)
|
28
|
+
else:
|
29
|
+
ep = model
|
30
|
+
return lowertools.exported_program_to_mlir_text(ep)
|
31
|
+
|
32
|
+
|
33
|
+
class TestMarkPattern(googletest.TestCase):
|
34
|
+
|
35
|
+
def test_mark_pattern(self):
|
36
|
+
|
37
|
+
class TestModel(torch.nn.Module):
|
38
|
+
|
39
|
+
def forward(self, x):
|
40
|
+
return x * x + x + x
|
41
|
+
|
42
|
+
pattern = pattern_module.Pattern(
|
43
|
+
"test.add",
|
44
|
+
lambda a, b: a + b,
|
45
|
+
export_args=(torch.rand(2, 2), torch.rand(2, 2)),
|
46
|
+
)
|
47
|
+
|
48
|
+
model = TestModel().eval()
|
49
|
+
args = (torch.rand(20, 20),)
|
50
|
+
exported_program = torch.export.export(model, args)
|
51
|
+
mark_pattern.mark_pattern(exported_program.graph_module, pattern)
|
52
|
+
mlir = _export_stablehlo_mlir(exported_program)
|
53
|
+
|
54
|
+
lowertools.assert_string_count(
|
55
|
+
self,
|
56
|
+
mlir,
|
57
|
+
{'stablehlo.composite "test.add"': 2},
|
58
|
+
{"stablehlo.custom_call @mark_tensor": 6},
|
59
|
+
)
|
60
|
+
|
61
|
+
def test_mark_pattern_with_clone_inputs(self):
|
62
|
+
|
63
|
+
class TestModel(torch.nn.Module):
|
64
|
+
|
65
|
+
def forward(self, x):
|
66
|
+
return torch.ops.aten.clone.default(x * x) + x
|
67
|
+
|
68
|
+
pattern = pattern_module.Pattern(
|
69
|
+
"test.add",
|
70
|
+
lambda a, b: a + b,
|
71
|
+
export_args=(torch.rand(2, 2), torch.rand(2, 2)),
|
72
|
+
)
|
73
|
+
|
74
|
+
model = TestModel().eval()
|
75
|
+
args = (torch.rand(20, 20),)
|
76
|
+
exported_program = torch.export.export(model, args)
|
77
|
+
mark_pattern.mark_pattern(exported_program.graph_module, pattern)
|
78
|
+
mlir = _export_stablehlo_mlir(exported_program)
|
79
|
+
|
80
|
+
lowertools.assert_string_count(
|
81
|
+
self,
|
82
|
+
mlir,
|
83
|
+
{'stablehlo.composite "test.add"': 1},
|
84
|
+
{"stablehlo.custom_call @mark_tensor": 3},
|
85
|
+
)
|
86
|
+
|
87
|
+
def test_mark_pattern_with_attr_builder(self):
|
88
|
+
class TestModel(torch.nn.Module):
|
89
|
+
|
90
|
+
def forward(self, x):
|
91
|
+
return x * x * x + x - x * x + x
|
92
|
+
|
93
|
+
pattern = pattern_module.Pattern(
|
94
|
+
"test.add",
|
95
|
+
lambda a, b: a + b,
|
96
|
+
export_args=(torch.rand(2, 2), torch.rand(2, 2)),
|
97
|
+
attr_builder=lambda *args: {"alias": "test.test_add"},
|
98
|
+
)
|
99
|
+
|
100
|
+
model = TestModel().eval()
|
101
|
+
args = (torch.rand(20, 20),)
|
102
|
+
exported_program = torch.export.export(model, args)
|
103
|
+
mark_pattern.mark_pattern(exported_program.graph_module, pattern)
|
104
|
+
mlir = _export_stablehlo_mlir(exported_program)
|
105
|
+
|
106
|
+
lowertools.assert_string_count(
|
107
|
+
self,
|
108
|
+
mlir,
|
109
|
+
{
|
110
|
+
'stablehlo.composite "test.add"': 2,
|
111
|
+
'composite_attributes = {alias = "test.test_add"}': 2,
|
112
|
+
},
|
113
|
+
{"stablehlo.custom_call @mark_tensor": 6},
|
114
|
+
{'{"alias": "test.test_add"}': 2},
|
115
|
+
)
|
116
|
+
|
117
|
+
def test_mark_pattern_with_scalar_attr_tracker(self):
|
118
|
+
class TestModel(torch.nn.Module):
|
119
|
+
|
120
|
+
def forward(self, x):
|
121
|
+
r = x
|
122
|
+
for idx in range(5):
|
123
|
+
r = torch.nn.LogSoftmax(dim=idx % 2)(r) * x
|
124
|
+
return r
|
125
|
+
|
126
|
+
pattern = pattern_module.Pattern(
|
127
|
+
"test.log_softmax",
|
128
|
+
lambda x, dim: torch.nn.functional.log_softmax(x, dim=dim),
|
129
|
+
export_args=(torch.rand(10, 10, 10), 1),
|
130
|
+
scalar_attr_trackers=[
|
131
|
+
pattern_module.ScalarAttrTracker("dim", pattern_arg_pos=1)
|
132
|
+
.track(0)
|
133
|
+
.track(1)
|
134
|
+
.track(2),
|
135
|
+
],
|
136
|
+
)
|
137
|
+
|
138
|
+
model = TestModel().eval()
|
139
|
+
args = (torch.rand(10, 10),)
|
140
|
+
exported_program = torch.export.export(model, args)
|
141
|
+
mark_pattern.mark_pattern(exported_program.graph_module, pattern)
|
142
|
+
mlir = _export_stablehlo_mlir(exported_program)
|
143
|
+
|
144
|
+
lowertools.assert_string_count(
|
145
|
+
self,
|
146
|
+
mlir,
|
147
|
+
{
|
148
|
+
'stablehlo.composite "test.log_softmax"': 5,
|
149
|
+
"composite_attributes = {dim = 0 : i64}": 3,
|
150
|
+
"composite_attributes = {dim = 1 : i64}": 2,
|
151
|
+
},
|
152
|
+
{"stablehlo.custom_call @mark_tensor": 10},
|
153
|
+
{'{"dim": 0}': 3, '{"dim": 1}': 2},
|
154
|
+
)
|
155
|
+
|
156
|
+
def test_mark_tangent_model_and_pattern_input(self):
|
157
|
+
class TestModel(torch.nn.Module):
|
158
|
+
|
159
|
+
def forward(self, x, y):
|
160
|
+
z = torch.ops.aten.relu(x)
|
161
|
+
z = z + y
|
162
|
+
return z
|
163
|
+
|
164
|
+
pattern = pattern_module.Pattern(
|
165
|
+
"test.relu",
|
166
|
+
lambda x: torch.ops.aten.relu(x),
|
167
|
+
export_args=(torch.rand(2, 2),),
|
168
|
+
)
|
169
|
+
|
170
|
+
model = TestModel().eval()
|
171
|
+
args = (torch.rand(20, 20), torch.rand(20, 20))
|
172
|
+
exported_program = torch.export.export(model, args)
|
173
|
+
mark_pattern.mark_pattern(exported_program.graph_module, pattern)
|
174
|
+
mlir = _export_stablehlo_mlir(exported_program)
|
175
|
+
|
176
|
+
lowertools.assert_string_count(
|
177
|
+
self,
|
178
|
+
mlir,
|
179
|
+
{'stablehlo.composite "test.relu"': 1},
|
180
|
+
{"stablehlo.custom_call @mark_tensor": 2},
|
181
|
+
)
|
182
|
+
|
183
|
+
|
184
|
+
if __name__ == "__main__":
|
185
|
+
googletest.main()
|
@@ -0,0 +1,18 @@
|
|
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 ._shim import *
|
17
|
+
from .common_utils import flat_dict_names
|
18
|
+
from .test_utils import *
|
@@ -0,0 +1,86 @@
|
|
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 typing import Any, Optional
|
17
|
+
|
18
|
+
from ai_edge_torch import _config
|
19
|
+
from ai_edge_torch._convert import signature
|
20
|
+
from ai_edge_torch.quantize import quant_config as qcfg
|
21
|
+
import torch
|
22
|
+
|
23
|
+
config = _config.config
|
24
|
+
|
25
|
+
# isort: off
|
26
|
+
if config.use_torch_xla:
|
27
|
+
from ai_edge_torch.lowertools import torch_xla_utils as utils
|
28
|
+
from ai_edge_torch.lowertools.torch_xla_utils import exported_program_to_mlir_text
|
29
|
+
from torch_xla.experimental.mark_pattern_utils import StableHLOCompositeBuilder
|
30
|
+
from torch_xla.experimental.xla_marker import serialize_composite_attr
|
31
|
+
# The following imports are needed to register the needed torch_xla ops.
|
32
|
+
import torch_xla.experimental.xla_marker
|
33
|
+
import torch_xla.experimental.xla_mlir_debuginfo
|
34
|
+
|
35
|
+
mark_tensor_op = torch.ops.xla.mark_tensor.default
|
36
|
+
write_mlir_debuginfo_op = torch.ops.xla.write_mlir_debuginfo.default
|
37
|
+
else:
|
38
|
+
from ai_edge_torch.lowertools import odml_torch_utils as utils
|
39
|
+
from ai_edge_torch.lowertools.odml_torch_utils import exported_program_to_mlir_text
|
40
|
+
from ai_edge_torch.odml_torch.composite import StableHLOCompositeBuilder
|
41
|
+
from ai_edge_torch.odml_torch.composite.mark_tensor import serialize_composite_attr
|
42
|
+
from ai_edge_torch.odml_torch.composite.mark_tensor import mark_tensor_op
|
43
|
+
from ai_edge_torch.odml_torch.debuginfo import write_mlir_debuginfo_op
|
44
|
+
# isort: on
|
45
|
+
|
46
|
+
|
47
|
+
def exported_programs_to_tflite(
|
48
|
+
exported_programs: list[torch.export.ExportedProgram],
|
49
|
+
signatures: list[signature.Signature],
|
50
|
+
*,
|
51
|
+
quant_config: Optional[qcfg.QuantConfig] = None,
|
52
|
+
_tfl_converter_flags: Optional[dict[str, Any]] = None,
|
53
|
+
_saved_model_dir: Optional[str] = None
|
54
|
+
):
|
55
|
+
"""Converts a list of ExportedProgram to a TFLite model.
|
56
|
+
|
57
|
+
Args:
|
58
|
+
exported_programs: A list of ExportedProgram.
|
59
|
+
signatures: A list of Signature.
|
60
|
+
quant_config: A QuantConfig.
|
61
|
+
_saved_model_dir: Directory for the intermediate saved model. If not
|
62
|
+
specified, a random temporary directory would be used.
|
63
|
+
_tfl_converter_flags: A dict of flags for TFLiteConverter.
|
64
|
+
|
65
|
+
Returns:
|
66
|
+
A TFLite model.
|
67
|
+
"""
|
68
|
+
if _tfl_converter_flags is None:
|
69
|
+
_tfl_converter_flags = {}
|
70
|
+
|
71
|
+
bundles: list[utils.MlirBundle] = [
|
72
|
+
utils.exported_program_to_mlir(exported, sig.flat_args)
|
73
|
+
for exported, sig in zip(exported_programs, signatures)
|
74
|
+
]
|
75
|
+
|
76
|
+
merged_bundle: utils.MergedBundle = utils.merge_mlir_bundles(
|
77
|
+
bundles, signatures, exported_programs
|
78
|
+
)
|
79
|
+
|
80
|
+
return utils.merged_bundle_to_tfl_model(
|
81
|
+
merged_bundle,
|
82
|
+
signatures,
|
83
|
+
quant_config=quant_config,
|
84
|
+
_tfl_converter_flags=_tfl_converter_flags,
|
85
|
+
_saved_model_dir=_saved_model_dir,
|
86
|
+
)
|