ai-edge-torch-nightly 0.2.0.dev20240714__py3-none-any.whl → 0.3.0.dev20240926__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 +5 -4
- ai_edge_torch/_convert/conversion.py +112 -0
- ai_edge_torch/_convert/conversion_utils.py +64 -0
- ai_edge_torch/{convert → _convert}/converter.py +94 -48
- ai_edge_torch/_convert/fx_passes/__init__.py +22 -0
- ai_edge_torch/{convert → _convert}/fx_passes/build_aten_composite_pass.py +107 -44
- ai_edge_torch/{convert → _convert}/fx_passes/build_interpolate_composite_pass.py +23 -20
- ai_edge_torch/{convert → _convert}/fx_passes/inject_mlir_debuginfo_pass.py +5 -6
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/__init__.py +1 -1
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_check.py +39 -9
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_mark.py +2 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +1 -0
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +17 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +9 -8
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +31 -18
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +2 -2
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/pass_body.py +34 -24
- ai_edge_torch/{convert → _convert}/fx_passes/optimize_layout_transposes_pass/utils.py +2 -0
- ai_edge_torch/_convert/signature.py +66 -0
- ai_edge_torch/_convert/test/test_convert.py +495 -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 → _convert}/test/test_to_channel_last_io.py +5 -5
- ai_edge_torch/{convert → _convert}/to_channel_last_io.py +10 -3
- ai_edge_torch/config.py +27 -0
- ai_edge_torch/conftest.py +20 -0
- ai_edge_torch/debug/culprit.py +72 -40
- ai_edge_torch/debug/test/test_culprit.py +7 -5
- ai_edge_torch/debug/test/test_search_model.py +8 -7
- ai_edge_torch/debug/utils.py +14 -3
- ai_edge_torch/fx_pass_base.py +101 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/gemma/{gemma.py → gemma1.py} +69 -55
- ai_edge_torch/generative/examples/gemma/gemma2.py +267 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
- ai_edge_torch/generative/examples/gemma/verify_gemma2.py +57 -0
- ai_edge_torch/generative/examples/gemma/verify_util.py +143 -0
- ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/openelm/openelm.py +206 -0
- ai_edge_torch/generative/examples/openelm/verify.py +64 -0
- ai_edge_torch/generative/examples/phi/__init__.py +14 -0
- ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/phi/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/{phi2 → phi}/phi2.py +70 -51
- ai_edge_torch/generative/examples/phi/phi3.py +286 -0
- ai_edge_torch/generative/examples/phi/verify.py +65 -0
- ai_edge_torch/generative/examples/phi/verify_phi3.py +70 -0
- ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
- ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +68 -0
- ai_edge_torch/generative/examples/smollm/smollm.py +101 -0
- ai_edge_torch/generative/examples/smollm/verify.py +62 -0
- ai_edge_torch/generative/examples/stable_diffusion/attention.py +3 -1
- ai_edge_torch/generative/examples/stable_diffusion/clip.py +83 -13
- ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +27 -14
- ai_edge_torch/generative/examples/stable_diffusion/decoder.py +74 -9
- ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +179 -37
- ai_edge_torch/generative/examples/stable_diffusion/encoder.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +83 -58
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +4 -3
- ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +1 -0
- ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +4 -1
- ai_edge_torch/generative/examples/stable_diffusion/util.py +9 -3
- ai_edge_torch/generative/examples/t5/convert_to_tflite.py +28 -25
- ai_edge_torch/generative/examples/t5/t5.py +208 -159
- ai_edge_torch/generative/examples/t5/t5_attention.py +45 -30
- ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
- ai_edge_torch/generative/examples/test_models/toy_model.py +69 -41
- ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +50 -64
- ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
- ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +41 -39
- ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +67 -54
- ai_edge_torch/generative/examples/tiny_llama/verify.py +64 -0
- ai_edge_torch/generative/fx_passes/__init__.py +4 -5
- ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +10 -7
- ai_edge_torch/generative/layers/attention.py +141 -102
- ai_edge_torch/generative/layers/attention_utils.py +53 -12
- ai_edge_torch/generative/layers/builder.py +37 -7
- ai_edge_torch/generative/layers/feed_forward.py +39 -14
- ai_edge_torch/generative/layers/kv_cache.py +162 -50
- ai_edge_torch/generative/layers/model_config.py +84 -30
- ai_edge_torch/generative/layers/normalization.py +185 -7
- ai_edge_torch/generative/layers/rotary_position_embedding.py +6 -4
- ai_edge_torch/generative/layers/scaled_dot_product_attention.py +48 -21
- ai_edge_torch/generative/layers/unet/blocks_2d.py +136 -77
- ai_edge_torch/generative/layers/unet/builder.py +7 -4
- ai_edge_torch/generative/layers/unet/model_config.py +17 -15
- ai_edge_torch/generative/quantize/example.py +7 -8
- ai_edge_torch/generative/quantize/quant_recipe.py +10 -7
- ai_edge_torch/generative/quantize/quant_recipe_utils.py +12 -1
- ai_edge_torch/generative/quantize/quant_recipes.py +8 -0
- ai_edge_torch/generative/test/test_kv_cache.py +120 -0
- ai_edge_torch/generative/test/{loader_test.py → test_loader.py} +9 -7
- ai_edge_torch/generative/test/test_model_conversion.py +124 -188
- ai_edge_torch/generative/test/test_model_conversion_large.py +251 -0
- ai_edge_torch/generative/test/test_quantize.py +76 -60
- ai_edge_torch/generative/test/utils.py +54 -0
- ai_edge_torch/generative/utilities/converter.py +82 -0
- ai_edge_torch/generative/utilities/loader.py +120 -57
- ai_edge_torch/generative/utilities/stable_diffusion_loader.py +165 -57
- ai_edge_torch/generative/utilities/t5_loader.py +110 -81
- ai_edge_torch/generative/utilities/verifier.py +247 -0
- ai_edge_torch/hlfb/__init__.py +1 -1
- ai_edge_torch/hlfb/mark_pattern/__init__.py +9 -7
- ai_edge_torch/hlfb/mark_pattern/passes.py +23 -3
- ai_edge_torch/hlfb/mark_pattern/pattern.py +39 -30
- ai_edge_torch/hlfb/test/test_mark_pattern.py +46 -20
- ai_edge_torch/hlfb/test/test_stablehlo_composite_builder.py +24 -11
- ai_edge_torch/lowertools/__init__.py +18 -0
- ai_edge_torch/lowertools/_shim.py +80 -0
- ai_edge_torch/lowertools/common_utils.py +142 -0
- ai_edge_torch/lowertools/odml_torch_utils.py +255 -0
- ai_edge_torch/lowertools/test_utils.py +60 -0
- ai_edge_torch/lowertools/torch_xla_utils.py +284 -0
- ai_edge_torch/{generative/quantize/ai_edge_quantizer_glue → lowertools}/translate_recipe.py +29 -14
- ai_edge_torch/model.py +53 -18
- ai_edge_torch/odml_torch/__init__.py +20 -0
- ai_edge_torch/odml_torch/_torch_future.py +61 -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 +357 -0
- ai_edge_torch/odml_torch/export_utils.py +168 -0
- ai_edge_torch/odml_torch/jax_bridge/__init__.py +15 -0
- ai_edge_torch/odml_torch/jax_bridge/_wrap.py +150 -0
- ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
- ai_edge_torch/odml_torch/lowerings/__init__.py +25 -0
- ai_edge_torch/odml_torch/lowerings/_basic.py +258 -0
- ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
- ai_edge_torch/odml_torch/lowerings/_convolution.py +241 -0
- ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +252 -0
- ai_edge_torch/odml_torch/lowerings/_layer_norm.py +78 -0
- ai_edge_torch/odml_torch/lowerings/context.py +42 -0
- ai_edge_torch/odml_torch/lowerings/registry.py +96 -0
- ai_edge_torch/odml_torch/lowerings/utils.py +185 -0
- ai_edge_torch/odml_torch/passes/__init__.py +38 -0
- ai_edge_torch/odml_torch/tf_integration.py +194 -0
- ai_edge_torch/quantize/pt2e_quantizer.py +52 -24
- ai_edge_torch/quantize/pt2e_quantizer_utils.py +43 -23
- ai_edge_torch/quantize/quant_config.py +13 -9
- ai_edge_torch/testing/model_coverage/model_coverage.py +29 -16
- ai_edge_torch/version.py +16 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/METADATA +7 -3
- ai_edge_torch_nightly-0.3.0.dev20240926.dist-info/RECORD +177 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/WHEEL +1 -1
- ai_edge_torch/convert/conversion.py +0 -117
- ai_edge_torch/convert/conversion_utils.py +0 -400
- ai_edge_torch/convert/fx_passes/__init__.py +0 -59
- ai_edge_torch/convert/fx_passes/_pass_base.py +0 -49
- ai_edge_torch/convert/fx_passes/canonicalize_pass.py +0 -37
- ai_edge_torch/convert/test/test_convert.py +0 -311
- ai_edge_torch/convert/test/test_convert_composites.py +0 -192
- ai_edge_torch/convert/test/test_convert_multisig.py +0 -139
- ai_edge_torch/generative/examples/gemma/convert_to_tflite.py +0 -66
- ai_edge_torch/generative/examples/phi2/convert_to_tflite.py +0 -64
- ai_edge_torch/generative/examples/test_models/toy_model_with_external_kv_cache.py +0 -161
- ai_edge_torch/generative/quantize/ai_edge_quantizer_glue/__init__.py +0 -0
- ai_edge_torch_nightly-0.2.0.dev20240714.dist-info/RECORD +0 -121
- /ai_edge_torch/{convert → _convert}/__init__.py +0 -0
- /ai_edge_torch/{convert → _convert}/test/__init__.py +0 -0
- /ai_edge_torch/generative/examples/{phi2 → openelm}/__init__.py +0 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/LICENSE +0 -0
- {ai_edge_torch_nightly-0.2.0.dev20240714.dist-info → ai_edge_torch_nightly-0.3.0.dev20240926.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,75 @@
|
|
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
|
+
"""Utilities for Jax bridge."""
|
16
|
+
|
17
|
+
from ai_edge_torch import odml_torch
|
18
|
+
import jax
|
19
|
+
import jax.numpy as jnp
|
20
|
+
from jax._src.lib.mlir import ir
|
21
|
+
import torch
|
22
|
+
|
23
|
+
|
24
|
+
def t2j_dtype(dtype):
|
25
|
+
return {
|
26
|
+
torch.bfloat16: jnp.bfloat16,
|
27
|
+
torch.half: jnp.float16,
|
28
|
+
torch.float32: jnp.float32,
|
29
|
+
torch.double: jnp.double,
|
30
|
+
torch.long: jnp.int64,
|
31
|
+
torch.int64: jnp.int64,
|
32
|
+
torch.int32: jnp.int32,
|
33
|
+
torch.int16: jnp.int16,
|
34
|
+
torch.int8: jnp.int8,
|
35
|
+
torch.uint8: jnp.uint8,
|
36
|
+
torch.bool: jnp.bool_,
|
37
|
+
torch.complex64: jnp.complex64,
|
38
|
+
torch.complex128: jnp.complex128,
|
39
|
+
}.get(dtype)
|
40
|
+
|
41
|
+
|
42
|
+
def is_ir_variable(value):
|
43
|
+
if isinstance(value, ir.Value):
|
44
|
+
return True
|
45
|
+
if isinstance(value, (list, tuple)):
|
46
|
+
return any(is_ir_variable(x) for x in value)
|
47
|
+
return False
|
48
|
+
|
49
|
+
|
50
|
+
def ir_variable_to_jax(value):
|
51
|
+
if isinstance(value, (list, tuple)):
|
52
|
+
return tuple([ir_variable_to_jax(x) for x in value])
|
53
|
+
elif not isinstance(value, ir.Value):
|
54
|
+
return value
|
55
|
+
elif not isinstance(value.type, ir.RankedTensorType):
|
56
|
+
raise ValueError(
|
57
|
+
f"ir.Value to JAX must be in ir.RankedTensorType, got {value}"
|
58
|
+
)
|
59
|
+
|
60
|
+
return jax.ShapeDtypeStruct(
|
61
|
+
value.type.shape,
|
62
|
+
t2j_dtype(
|
63
|
+
odml_torch.export_utils.ir_element_type_to_torch_dtype(
|
64
|
+
value.type.element_type
|
65
|
+
)
|
66
|
+
),
|
67
|
+
)
|
68
|
+
|
69
|
+
|
70
|
+
def tree_map_list_to_tuple(value):
|
71
|
+
if isinstance(value, dict):
|
72
|
+
return {k: tree_map_list_to_tuple(v) for k, v in value.items()}
|
73
|
+
if isinstance(value, (list, tuple)):
|
74
|
+
return tuple([tree_map_list_to_tuple(v) for v in value])
|
75
|
+
return value
|
@@ -0,0 +1,25 @@
|
|
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
|
+
from . import _basic
|
16
|
+
from . import _batch_norm
|
17
|
+
from . import _convolution
|
18
|
+
from . import _jax_lowerings
|
19
|
+
from . import _layer_norm
|
20
|
+
from . import context
|
21
|
+
from . import registry
|
22
|
+
from . import utils
|
23
|
+
from .registry import decompositions
|
24
|
+
from .registry import lookup
|
25
|
+
from .registry import lower
|
@@ -0,0 +1,258 @@
|
|
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 math
|
16
|
+
from typing import Optional, Union
|
17
|
+
|
18
|
+
from ai_edge_torch.odml_torch.lowerings import utils
|
19
|
+
from jax._src.lib.mlir import ir
|
20
|
+
from jax._src.lib.mlir.dialects import hlo as stablehlo
|
21
|
+
import numpy as np
|
22
|
+
import torch
|
23
|
+
|
24
|
+
from .registry import lower
|
25
|
+
|
26
|
+
|
27
|
+
# add(Tensor self, Tensor other) -> Tensor
|
28
|
+
# @lower(torch.ops.aten.add)
|
29
|
+
def _aten_add(lctx, x: ir.Value, y: ir.Value, alpha=1):
|
30
|
+
x, y = utils.upcast_to_same_type(x, y)
|
31
|
+
x, y = utils.broadcast_args_if_needed(x, y)
|
32
|
+
if alpha == 1:
|
33
|
+
return stablehlo.add(x, y)
|
34
|
+
|
35
|
+
alpha_splat = utils.splat(alpha, y.type.element_type, y.type.shape)
|
36
|
+
return stablehlo.add(x, stablehlo.multiply(y, alpha_splat))
|
37
|
+
|
38
|
+
|
39
|
+
# mul.Tensor(Tensor self, Tensor other) -> Tensor
|
40
|
+
# @lower(torch.ops.aten.mul.Tensor)
|
41
|
+
def _aten_mul_tensor(lctx, self: ir.Value, other: ir.Value):
|
42
|
+
self, other = utils.upcast_to_same_type(self, other)
|
43
|
+
self, other = utils.broadcast_args_if_needed(self, other)
|
44
|
+
|
45
|
+
return stablehlo.multiply(self, other)
|
46
|
+
|
47
|
+
|
48
|
+
# cat(Tensor[] tensors, int dim=0) -> Tensor
|
49
|
+
# @lower(torch.ops.aten.cat)
|
50
|
+
def _aten_cat(lctx, tensors: list[ir.Value], dim: int = 1):
|
51
|
+
return stablehlo.ConcatenateOp(tensors, dim).result
|
52
|
+
|
53
|
+
|
54
|
+
# view(Tensor(a) self, SymInt[] size) -> Tensor(a)
|
55
|
+
# @lower(torch.ops.aten.view)
|
56
|
+
def _aten_view(lctx, self: ir.Value, size: list[int]):
|
57
|
+
return stablehlo.ReshapeOp(
|
58
|
+
ir.RankedTensorType.get(size, self.type.element_type), self
|
59
|
+
).result
|
60
|
+
|
61
|
+
|
62
|
+
# hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor
|
63
|
+
@lower(torch.ops.aten.hardtanh)
|
64
|
+
def _aten_hardtanh(
|
65
|
+
lctx,
|
66
|
+
self: ir.Value,
|
67
|
+
min_val: Union[int, float] = -1.0,
|
68
|
+
max_val: Union[int, float] = 1.0,
|
69
|
+
):
|
70
|
+
elty = self.type.element_type
|
71
|
+
min_val = utils.splat(min_val, elty)
|
72
|
+
max_val = utils.splat(max_val, elty)
|
73
|
+
|
74
|
+
return stablehlo.clamp(min_val, self, max_val)
|
75
|
+
|
76
|
+
|
77
|
+
# mean(Tensor self, *, ScalarType? dtype=None) -> Tensor
|
78
|
+
# mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *,
|
79
|
+
# ScalarType? dtype=None) -> Tensor
|
80
|
+
@lower(torch.ops.aten.mean)
|
81
|
+
@lower(torch.ops.aten.mean.dim)
|
82
|
+
def _aten_mean_dim(
|
83
|
+
lctx,
|
84
|
+
self: ir.Value,
|
85
|
+
dim: Optional[list[int]] = None,
|
86
|
+
keepdim: bool = False,
|
87
|
+
*,
|
88
|
+
dtype=None,
|
89
|
+
):
|
90
|
+
self_shape = self.type.shape
|
91
|
+
self_elty = self.type.element_type
|
92
|
+
if dim is None:
|
93
|
+
dim = list(range(len(self_shape)))
|
94
|
+
dim = [len(self_shape) + d if d < 0 else d for d in dim]
|
95
|
+
dim_ = ir.DenseI64ArrayAttr.get(np.asarray(dim, np.int64))
|
96
|
+
dim_to_keep = [d for d in range(len(self_shape)) if d not in dim]
|
97
|
+
dim_to_keep_ = ir.DenseI64ArrayAttr.get(np.asarray(dim_to_keep, np.int64))
|
98
|
+
|
99
|
+
zero_ = utils.splat(0.0, self_elty)
|
100
|
+
|
101
|
+
reduce_result_shape = [
|
102
|
+
s for d, s in enumerate(self_shape) if d in dim_to_keep
|
103
|
+
]
|
104
|
+
reduce_result_ty = ir.RankedTensorType.get(reduce_result_shape, self_elty)
|
105
|
+
reduce_op = stablehlo.ReduceOp([reduce_result_ty], [self], [zero_], dim_)
|
106
|
+
|
107
|
+
reducer_arg_ty = ir.RankedTensorType.get(tuple(), self_elty)
|
108
|
+
reducer = reduce_op.regions[0].blocks.append(reducer_arg_ty, reducer_arg_ty)
|
109
|
+
with ir.InsertionPoint(reducer):
|
110
|
+
stablehlo.return_(
|
111
|
+
[stablehlo.add(reducer.arguments[0], reducer.arguments[1])]
|
112
|
+
)
|
113
|
+
|
114
|
+
sum_ = reduce_op.result
|
115
|
+
if keepdim:
|
116
|
+
sum_ = stablehlo.broadcast_in_dim(
|
117
|
+
ir.RankedTensorType.get(
|
118
|
+
[s if d in dim_to_keep else 1 for d, s in enumerate(self_shape)],
|
119
|
+
self_elty,
|
120
|
+
),
|
121
|
+
sum_,
|
122
|
+
dim_to_keep_,
|
123
|
+
)
|
124
|
+
|
125
|
+
dim_els = math.prod([s for d, s in enumerate(self_shape) if d in dim])
|
126
|
+
dim_els_ = utils.splat(dim_els, self_elty)
|
127
|
+
div_ = stablehlo.broadcast_in_dim(
|
128
|
+
sum_.type, dim_els_, ir.DenseI64ArrayAttr.get([])
|
129
|
+
)
|
130
|
+
mean_ = stablehlo.divide(sum_, div_)
|
131
|
+
|
132
|
+
return mean_
|
133
|
+
|
134
|
+
|
135
|
+
# https://pytorch.org/docs/stable/generated/torch.clone.html
|
136
|
+
# https://github.com/pytorch/pytorch/blob/a95ceb51a23ae33c00b3a99224143c609b1b3eb3/aten/src/ATen/native/TensorFactories.cpp#L1730
|
137
|
+
@lower(torch.ops.aten.clone)
|
138
|
+
def _aten_clone(lctx, x: ir.Value, *, memory_format=None):
|
139
|
+
return x
|
140
|
+
|
141
|
+
|
142
|
+
# https://pytorch.org/docs/stable/generated/torch.permute.html
|
143
|
+
# https://github.com/pytorch/pytorch/blob/519151a062a9bd4f0d32a9c7c7eae47d7ed847b2/aten/src/ATen/native/TensorShape.cpp#L1448
|
144
|
+
# https://github.com/openxla/stablehlo/blob/main/docs/spec.md#transpose
|
145
|
+
@lower(torch.ops.aten.permute)
|
146
|
+
def _aten_permute(lctx, x: ir.Value, dims: list[int]):
|
147
|
+
dim = len(x.type.shape)
|
148
|
+
return stablehlo.transpose(x, ir.DenseI64ArrayAttr.get(dims))
|
149
|
+
|
150
|
+
|
151
|
+
# https://pytorch.org/docs/stable/generated/torch.mm.html
|
152
|
+
# https://github.com/pytorch/pytorch/blob/ffabb25c489df1dc631a577c12a0c843c8b202f3/aten/src/ATen/native/LinearAlgebra.cpp#L193
|
153
|
+
# https://github.com/openxla/stablehlo/blob/main/docs/spec.md#dot_general
|
154
|
+
@lower(torch.ops.aten.mm)
|
155
|
+
def _aten_mm(mod, mat1: ir.Value, mat2: ir.Value) -> ir.Value:
|
156
|
+
mat1_shape = mat1.type.shape
|
157
|
+
mat2_shape = mat2.type.shape
|
158
|
+
mat1_dims = len(mat1_shape)
|
159
|
+
mat2_dims = len(mat2_shape)
|
160
|
+
|
161
|
+
if mat1_dims != 2 or mat1_dims != 2:
|
162
|
+
raise ValueError(
|
163
|
+
"Both arguments must be 2D matrices, received dimensions %d and %d"
|
164
|
+
% (mat1_dims, mat2_dims)
|
165
|
+
)
|
166
|
+
|
167
|
+
if mat1_shape[1] != mat2_shape[0]:
|
168
|
+
raise ValueError(
|
169
|
+
"mat1 and mat2 shapes cannot be multiplied, received shapes %s and %s"
|
170
|
+
% (mat1_shape, mat2_shape)
|
171
|
+
)
|
172
|
+
|
173
|
+
dot_dnums = stablehlo.DotDimensionNumbers.get(
|
174
|
+
lhs_batching_dimensions=[],
|
175
|
+
rhs_batching_dimensions=[],
|
176
|
+
lhs_contracting_dimensions=(1,),
|
177
|
+
rhs_contracting_dimensions=(0,),
|
178
|
+
)
|
179
|
+
return stablehlo.dot_general(
|
180
|
+
ir.RankedTensorType.get(
|
181
|
+
(mat1.type.shape[0], mat2.type.shape[1]), mat1.type.element_type
|
182
|
+
),
|
183
|
+
mat1,
|
184
|
+
mat2,
|
185
|
+
dot_dnums,
|
186
|
+
)
|
187
|
+
|
188
|
+
|
189
|
+
# https://pytorch.org/docs/stable/generated/torch.div.html
|
190
|
+
# https://openxla.org/stablehlo/spec#divide
|
191
|
+
# TODO: support rounding mode and type promotion (see torch.div spec).
|
192
|
+
# @lower(torch.ops.aten.div)
|
193
|
+
def _aten_div(mod, x, y, *, rounding_mode=None, out=None) -> ir.Value:
|
194
|
+
# By default, PyTorch performs a "true" division like Python 3. This requires
|
195
|
+
# casting integer input types to float to achieve the same semantics using
|
196
|
+
# stablehlo.divide.
|
197
|
+
if isinstance(x.type.element_type, ir.IntegerType):
|
198
|
+
x = utils.convert_int_to_float(x)
|
199
|
+
if isinstance(y.type.element_type, ir.IntegerType):
|
200
|
+
y = utils.convert_int_to_float(y)
|
201
|
+
|
202
|
+
x, y = utils.broadcast_args_if_needed(x, y)
|
203
|
+
|
204
|
+
return stablehlo.divide(x, y)
|
205
|
+
|
206
|
+
|
207
|
+
# Schema:
|
208
|
+
# - aten::slice_scatter(Tensor self, Tensor src, int dim=0, SymInt?
|
209
|
+
# start=None, SymInt? end=None, SymInt step=1) -> Tensor
|
210
|
+
# Torch Reference:
|
211
|
+
# - https://pytorch.org/docs/stable/generated/torch.slice_scatter.html
|
212
|
+
# - https://github.com/pytorch/pytorch/blob/18f9331e5deb4c02ae5c206e133a9b4add49bd97/aten/src/ATen/native/TensorShape.cpp#L4002
|
213
|
+
@lower(torch.ops.aten.slice_scatter)
|
214
|
+
def _aten_slice_scatter(lctx, self, src, dim=0, start=None, end=None, step=1):
|
215
|
+
start = start if start is not None else 0
|
216
|
+
end = end if end is not None else self.type.shape[dim]
|
217
|
+
|
218
|
+
start, end = np.clip(
|
219
|
+
[start, end], -self.type.shape[dim], self.type.shape[dim]
|
220
|
+
)
|
221
|
+
|
222
|
+
if start < 0:
|
223
|
+
start = self.type.shape[dim] + start
|
224
|
+
if end < 0:
|
225
|
+
end = self.type.shape[dim] + end
|
226
|
+
|
227
|
+
if end <= start or np.prod(src.type.shape) == 0:
|
228
|
+
return self
|
229
|
+
|
230
|
+
end = start + step * math.ceil((end - start) / step) - (step - 1)
|
231
|
+
padding_low = start
|
232
|
+
padding_high = self.type.shape[dim] - end
|
233
|
+
interior_padding = step - 1
|
234
|
+
|
235
|
+
rank = len(self.type.shape)
|
236
|
+
src = stablehlo.pad(
|
237
|
+
src,
|
238
|
+
utils.splat(0, src.type.element_type, []),
|
239
|
+
edge_padding_low=[padding_low if i == dim else 0 for i in range(rank)],
|
240
|
+
edge_padding_high=[padding_high if i == dim else 0 for i in range(rank)],
|
241
|
+
interior_padding=[
|
242
|
+
interior_padding if i == dim else 0 for i in range(rank)
|
243
|
+
],
|
244
|
+
)
|
245
|
+
pred = np.ones(self.type.shape, dtype=np.bool_)
|
246
|
+
pred[*[
|
247
|
+
slice(start, end, step) if i == dim else slice(None, None, None)
|
248
|
+
for i in range(rank)
|
249
|
+
]] = False
|
250
|
+
pred = stablehlo.constant(
|
251
|
+
ir.DenseElementsAttr.get(
|
252
|
+
np.packbits(pred, bitorder="little"),
|
253
|
+
type=ir.IntegerType.get_signless(1),
|
254
|
+
shape=pred.shape,
|
255
|
+
)
|
256
|
+
)
|
257
|
+
out = stablehlo.select(pred, self, src)
|
258
|
+
return out
|
@@ -0,0 +1,65 @@
|
|
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
|
+
"""Provides lowering for coreaten to mlir stablehlo op: Convolution"""
|
16
|
+
|
17
|
+
from typing import Optional
|
18
|
+
|
19
|
+
from ai_edge_torch.odml_torch.lowerings import utils
|
20
|
+
from jax._src.lib.mlir import ir
|
21
|
+
from jax._src.lib.mlir.dialects import hlo as stablehlo
|
22
|
+
import torch
|
23
|
+
|
24
|
+
from .registry import lower
|
25
|
+
|
26
|
+
|
27
|
+
# _native_batch_norm_legit_no_training(
|
28
|
+
# Tensor input,
|
29
|
+
# Tensor? weight,
|
30
|
+
# Tensor? bias,
|
31
|
+
# Tensor running_mean,
|
32
|
+
# Tensor running_var,
|
33
|
+
# float momentum,
|
34
|
+
# float eps) -> (Tensor, Tensor, Tensor)
|
35
|
+
@lower(torch.ops.aten._native_batch_norm_legit_no_training)
|
36
|
+
def _native_batch_norm_legit_no_training(
|
37
|
+
lctx,
|
38
|
+
input_tensor: ir.Value,
|
39
|
+
weight: Optional[ir.Value],
|
40
|
+
bias: Optional[ir.Value],
|
41
|
+
running_mean: ir.Value,
|
42
|
+
running_var: ir.Value,
|
43
|
+
momentum: float,
|
44
|
+
eps: float,
|
45
|
+
):
|
46
|
+
if weight is None:
|
47
|
+
weight = utils.splat(
|
48
|
+
1, running_mean.type.element_type, running_mean.type.shape
|
49
|
+
)
|
50
|
+
if bias is None:
|
51
|
+
bias = utils.splat(
|
52
|
+
0, running_mean.type.element_type, running_mean.type.shape
|
53
|
+
)
|
54
|
+
|
55
|
+
return [
|
56
|
+
stablehlo.batch_norm_inference(
|
57
|
+
input_tensor, weight, bias, running_mean, running_var, eps, 1
|
58
|
+
),
|
59
|
+
utils.splat(
|
60
|
+
0, input_tensor.type.element_type
|
61
|
+
), # TODO: return empty array instead
|
62
|
+
utils.splat(
|
63
|
+
0, input_tensor.type.element_type
|
64
|
+
), # TODO: return empty array instead
|
65
|
+
]
|
@@ -0,0 +1,241 @@
|
|
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
|
+
"""Provides lowering for coreaten to stablehlo for Convolution."""
|
16
|
+
|
17
|
+
import math
|
18
|
+
from typing import Optional
|
19
|
+
|
20
|
+
from ai_edge_torch.odml_torch.lowerings import registry
|
21
|
+
from jax._src.lib.mlir import ir
|
22
|
+
from jax._src.lib.mlir.dialects import hlo as stablehlo
|
23
|
+
import torch
|
24
|
+
|
25
|
+
|
26
|
+
def make_padding(padding):
|
27
|
+
"""Change the padding from pytorch to stablehlo style.
|
28
|
+
|
29
|
+
Stablehlo allows start and end padding for each dimension while aten only
|
30
|
+
allows symmetric padding and so only has one number per dimension.
|
31
|
+
|
32
|
+
Args:
|
33
|
+
padding: The padding of the convolution
|
34
|
+
|
35
|
+
Returns:
|
36
|
+
The padding in stablehlo style
|
37
|
+
"""
|
38
|
+
return tuple((p, p) for p in padding)
|
39
|
+
|
40
|
+
|
41
|
+
def create_conv_dimension_numbers(lhs, transposed: bool = False):
|
42
|
+
"""Create the dimension numbers for the convolution.
|
43
|
+
|
44
|
+
Args:
|
45
|
+
lhs: The input tensor
|
46
|
+
transposed: Whether the convolution is transposed
|
47
|
+
|
48
|
+
Returns:
|
49
|
+
The dimension numbers for the convolution
|
50
|
+
"""
|
51
|
+
num_spatial_dims = len(lhs.type.shape) - 2
|
52
|
+
spatial_dimensions = []
|
53
|
+
for i in range(0, num_spatial_dims):
|
54
|
+
spatial_dimensions.append(i + 2)
|
55
|
+
|
56
|
+
# Regular kernels are OIHW
|
57
|
+
# TransposedConv kernels are IOHW
|
58
|
+
dimension_numbers = stablehlo.ConvDimensionNumbers.get(
|
59
|
+
input_batch_dimension=0,
|
60
|
+
input_feature_dimension=1,
|
61
|
+
input_spatial_dimensions=spatial_dimensions,
|
62
|
+
kernel_input_feature_dimension=0 if transposed else 1,
|
63
|
+
kernel_output_feature_dimension=1 if transposed else 0,
|
64
|
+
kernel_spatial_dimensions=spatial_dimensions,
|
65
|
+
output_batch_dimension=0,
|
66
|
+
output_feature_dimension=1,
|
67
|
+
output_spatial_dimensions=spatial_dimensions,
|
68
|
+
)
|
69
|
+
return dimension_numbers
|
70
|
+
|
71
|
+
|
72
|
+
def infer_output_shape(
|
73
|
+
lhs,
|
74
|
+
rhs,
|
75
|
+
stride,
|
76
|
+
dilation,
|
77
|
+
padding,
|
78
|
+
transposed: bool = False,
|
79
|
+
output_padding: list[int] = 0,
|
80
|
+
):
|
81
|
+
"""Infer the output shape of the convolution.
|
82
|
+
|
83
|
+
Args:
|
84
|
+
lhs: The input tensor
|
85
|
+
rhs: The kernel tensor
|
86
|
+
stride: The stride of the convolution (dilation of input in transposed conv)
|
87
|
+
dilation: The kernel dilation of the convolution
|
88
|
+
padding: The padding of the convolution
|
89
|
+
transposed: Whether the convolution is transposed
|
90
|
+
output_padding: The output padding of the convolution
|
91
|
+
|
92
|
+
Returns:
|
93
|
+
The output shape of the convolution
|
94
|
+
"""
|
95
|
+
lhs_type: ir.RankedTensorType = lhs.type
|
96
|
+
lhs_shape: list[int] = lhs_type.shape
|
97
|
+
rhs_shape: list[int] = rhs.type.shape
|
98
|
+
|
99
|
+
# Input layout is: (N)CHW and Kernel layout is: (O)IHW for regular conv
|
100
|
+
# Input layout is: (N)CHW and Kernel layout is: I(O)HW for transposed conv
|
101
|
+
output_shape = (
|
102
|
+
[lhs_shape[0], rhs_shape[1]]
|
103
|
+
if transposed
|
104
|
+
else [lhs_shape[0], rhs_shape[0]]
|
105
|
+
)
|
106
|
+
num_spatial_dims = len(lhs.type.shape) - 2
|
107
|
+
|
108
|
+
# looping over the spatial dims (skipping the first 2 dims which are
|
109
|
+
# batch and features)
|
110
|
+
for spatial_dim in range(0, num_spatial_dims):
|
111
|
+
dim = spatial_dim + 2
|
112
|
+
dim_size = lhs_shape[dim]
|
113
|
+
kernel_dim_size = rhs_shape[dim]
|
114
|
+
|
115
|
+
if transposed:
|
116
|
+
output_dim_size = (
|
117
|
+
(dim_size - 1) * stride[spatial_dim]
|
118
|
+
- 2 * padding[spatial_dim]
|
119
|
+
+ dilation[spatial_dim] * (kernel_dim_size - 1)
|
120
|
+
+ output_padding[spatial_dim]
|
121
|
+
+ 1
|
122
|
+
)
|
123
|
+
else:
|
124
|
+
output_dim_size = math.floor(
|
125
|
+
(
|
126
|
+
(
|
127
|
+
dim_size
|
128
|
+
+ 2 * padding[spatial_dim]
|
129
|
+
- dilation[spatial_dim] * (kernel_dim_size - 1)
|
130
|
+
- 1
|
131
|
+
)
|
132
|
+
/ stride[spatial_dim]
|
133
|
+
)
|
134
|
+
+ 1
|
135
|
+
)
|
136
|
+
|
137
|
+
output_shape.append(output_dim_size)
|
138
|
+
|
139
|
+
return output_shape
|
140
|
+
|
141
|
+
|
142
|
+
def build_transpose_conv(
|
143
|
+
lctx,
|
144
|
+
output_type: ir.RankedTensorType,
|
145
|
+
lhs: ir.Value,
|
146
|
+
rhs: ir.Value,
|
147
|
+
stride: list[int],
|
148
|
+
padding: list[int],
|
149
|
+
dilation: list[int],
|
150
|
+
output_padding: list[int],
|
151
|
+
groups: int,
|
152
|
+
):
|
153
|
+
lhs_type: ir.RankedTensorType = lhs.type
|
154
|
+
num_spatial_dims = len(lhs_type.shape) - 2
|
155
|
+
rhs = stablehlo.reverse(rhs, list(range(2, 2 + num_spatial_dims)))
|
156
|
+
|
157
|
+
kernel_size = rhs.type.shape
|
158
|
+
# We need to additional padding on the input to get the right output size.
|
159
|
+
adjusted_padding = [
|
160
|
+
dilation[dim] * (kernel_size[dim + 2] - 1) - padding[dim]
|
161
|
+
for dim in range(num_spatial_dims)
|
162
|
+
]
|
163
|
+
return stablehlo.convolution(
|
164
|
+
result=output_type,
|
165
|
+
lhs=lhs,
|
166
|
+
rhs=rhs,
|
167
|
+
dimension_numbers=create_conv_dimension_numbers(lhs, True),
|
168
|
+
feature_group_count=groups,
|
169
|
+
batch_group_count=1,
|
170
|
+
padding=make_padding(adjusted_padding),
|
171
|
+
lhs_dilation=stride,
|
172
|
+
rhs_dilation=dilation,
|
173
|
+
)
|
174
|
+
|
175
|
+
|
176
|
+
# convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride,
|
177
|
+
# SymInt[] padding, SymInt[] dilation, bool transposed,
|
178
|
+
# SymInt[] output_padding, SymInt groups) -> Tensor
|
179
|
+
@registry.lower(torch.ops.aten.convolution)
|
180
|
+
def _aten_convolution(
|
181
|
+
lctx,
|
182
|
+
lhs: ir.Value,
|
183
|
+
rhs: ir.Value,
|
184
|
+
bias: Optional[ir.Value],
|
185
|
+
stride: list[int],
|
186
|
+
padding: list[int],
|
187
|
+
dilation: list[int],
|
188
|
+
transposed: bool,
|
189
|
+
output_padding: list[int],
|
190
|
+
groups: int,
|
191
|
+
):
|
192
|
+
|
193
|
+
# TODO(b/365559296) Add support for output_padding
|
194
|
+
if any(output_padding):
|
195
|
+
raise NotImplementedError(
|
196
|
+
"Output padding on convolution is not implemented."
|
197
|
+
)
|
198
|
+
|
199
|
+
lhs_type: ir.RankedTensorType = lhs.type
|
200
|
+
output_shape = infer_output_shape(
|
201
|
+
lhs, rhs, stride, dilation, padding, transposed, output_padding
|
202
|
+
)
|
203
|
+
output_type = ir.RankedTensorType.get(
|
204
|
+
output_shape,
|
205
|
+
lhs_type.element_type,
|
206
|
+
)
|
207
|
+
|
208
|
+
if transposed:
|
209
|
+
res = build_transpose_conv(
|
210
|
+
lctx,
|
211
|
+
output_type,
|
212
|
+
lhs,
|
213
|
+
rhs,
|
214
|
+
stride,
|
215
|
+
padding,
|
216
|
+
dilation,
|
217
|
+
output_padding,
|
218
|
+
groups,
|
219
|
+
)
|
220
|
+
else:
|
221
|
+
res = stablehlo.convolution(
|
222
|
+
result=output_type,
|
223
|
+
lhs=lhs,
|
224
|
+
rhs=rhs,
|
225
|
+
dimension_numbers=create_conv_dimension_numbers(lhs),
|
226
|
+
feature_group_count=groups,
|
227
|
+
batch_group_count=1,
|
228
|
+
window_strides=stride,
|
229
|
+
padding=make_padding(padding),
|
230
|
+
rhs_dilation=dilation,
|
231
|
+
)
|
232
|
+
|
233
|
+
if bias is not None:
|
234
|
+
# broadcast [C] to [NCHW]
|
235
|
+
broadcasted_bias = stablehlo.broadcast_in_dim(output_type, bias, [1])
|
236
|
+
res = stablehlo.add(
|
237
|
+
lhs=res,
|
238
|
+
rhs=broadcasted_bias,
|
239
|
+
)
|
240
|
+
|
241
|
+
return res
|