You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by tk...@apache.org on 2023/05/19 17:48:23 UTC
[tvm] branch tkonolige/relax_pad_etc_new created (now c342da8052)
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a change to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
at c342da8052 Fix RewriteDataflowReshape to no rewrite when buffer shapes are not the same
This branch includes the following new commits:
new f62d3277ab Add einsum, gelu, pad support to relax
new a54064659b working
new eb4b473ba2 trying data dependent dynamic slice
new cb458f8332 data dependent strided slice
new 9896c6a394 fix tuning, comparisons
new b1c5c6a662 save metadata to file
new 82e6162f23 bad rebase
new c342da8052 Fix RewriteDataflowReshape to no rewrite when buffer shapes are not the same
The 8 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
[tvm] 07/08: bad rebase
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 82e6162f23c2a406d2e371d739038bb3df137b2a
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Wed May 17 20:19:08 2023 +0000
bad rebase
---
python/tvm/relax/frontend/torch/fx_translator.py | 3 ---
1 file changed, 3 deletions(-)
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index 6222b11432..fcbe3574e1 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -1222,7 +1222,6 @@ class TorchFXImporter:
)
)
-<<<<<<< HEAD
def _scaled_dot_product_attention(self, node: fx.node.Node) -> relax.Var:
assert len(node.args) <= 4, "Dropout, and causal masking are not supported."
transpose_S_H = lambda tensor: relax.op.permute_dims(tensor, [0, 2, 1, 3])
@@ -1240,8 +1239,6 @@ class TorchFXImporter:
return self.block_builder.emit(attn)
-||||||| parent of 97e234777 (Add einsum, gelu, pad support to relax)
-=======
def _pad_common(self, mode, pad_value, inputs):
data = self.env[inputs[0]]
pad_list = inputs[1]
[tvm] 05/08: fix tuning, comparisons
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit 9896c6a39464fcefadfa9b7e99801de89b830db7
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Mon May 15 23:14:36 2023 +0000
fix tuning, comparisons
---
python/tvm/relax/frontend/torch/fx_translator.py | 19 +++++++++++++++++--
python/tvm/relax/utils.py | 2 +-
src/relax/ir/emit_te.cc | 2 +-
src/tir/analysis/estimate_flops.cc | 15 ++++++++++++---
4 files changed, 31 insertions(+), 7 deletions(-)
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index bdf2c3375f..6222b11432 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -376,6 +376,18 @@ class TorchFXImporter:
lhs, rhs = self.retrieve_args(node)
return self._call_binary_op(relax.op.less, lhs, rhs)
+ def _le(self, node: fx.node.Node) -> relax.Expr:
+ lhs, rhs = self.retrieve_args(node)
+ return self._call_binary_op(relax.op.less_equal, lhs, rhs)
+
+ def _gt(self, node: fx.node.Node) -> relax.Expr:
+ lhs, rhs = self.retrieve_args(node)
+ return self._call_binary_op(relax.op.greater, lhs, rhs)
+
+ def _ge(self, node: fx.node.Node) -> relax.Expr:
+ lhs, rhs = self.retrieve_args(node)
+ return self._call_binary_op(relax.op.greater_equal, lhs, rhs)
+
def _eq(self, node: fx.node.Node) -> relax.Expr:
lhs, rhs = self.retrieve_args(node)
return self._call_binary_op(relax.op.equal, lhs, rhs)
@@ -1154,8 +1166,8 @@ class TorchFXImporter:
from torch import fx
if any([isinstance(s, fx.node.Node) for s in size]):
- size = relax.op.concat([self.env[s] for s in size])
- # import IPython; IPython.embed()
+ size = relax.op.tensor_to_shape(relax.op.concat([self.env[s] for s in size]))
+ print(type(size))
if method.startswith("nearest"):
method = "nearest_neighbor"
@@ -1426,6 +1438,9 @@ class TorchFXImporter:
"sqrt": self._sqrt,
"round": self._round,
"lt": self._lt,
+ "le": self._le,
+ "gt": self._gt,
+ "ge": self._ge,
"eq": self._eq,
"ne": self._ne,
"truediv": self._truediv,
diff --git a/python/tvm/relax/utils.py b/python/tvm/relax/utils.py
index 02dd941080..8593af7b16 100644
--- a/python/tvm/relax/utils.py
+++ b/python/tvm/relax/utils.py
@@ -368,7 +368,7 @@ def gen_call_tir_inputs(
if isinstance(arg.struct_info, ShapeStructInfo):
assert isinstance(
arg, ShapeExpr
- ), "For Expr having ShapeStructInfo, emit_te now only supports ShapeExpr"
+ ), f"For Expr having ShapeStructInfo, emit_te now only supports ShapeExpr (got {type(arg)}). You may need to run tvm.relax.transform.DecomposeOpsForInference first."
return [_convert_te_arg_helper(val) for val in arg.values]
if isinstance(arg.struct_info, PrimStructInfo):
return arg.value
diff --git a/src/relax/ir/emit_te.cc b/src/relax/ir/emit_te.cc
index bfb5896c99..23b840b8ca 100644
--- a/src/relax/ir/emit_te.cc
+++ b/src/relax/ir/emit_te.cc
@@ -60,7 +60,7 @@ te::Tensor TETensor(Expr value, Map<tir::Var, PrimExpr> tir_var_map, std::string
}
ICHECK(value->struct_info_.defined()) << "value must be normalized and contain StructInfo";
auto* tensor_sinfo = GetStructInfoAs<TensorStructInfoNode>(value);
- ICHECK(tensor_sinfo) << "Value must be a tensor";
+ ICHECK(tensor_sinfo) << "Value must be a tensor but it is a " << value->GetTypeKey();
auto* shape_expr = tensor_sinfo->shape.as<ShapeExprNode>();
CHECK(shape_expr)
<< "ValueError: Expression does not have an known symbolic shape, please consider use "
diff --git a/src/tir/analysis/estimate_flops.cc b/src/tir/analysis/estimate_flops.cc
index 1c427e5fd9..59274f9c45 100644
--- a/src/tir/analysis/estimate_flops.cc
+++ b/src/tir/analysis/estimate_flops.cc
@@ -69,6 +69,13 @@ struct TResult {
return *this;
}
+ TResult SetInvalid() {
+ for (auto& kv : data_) {
+ kv.second = -1;
+ }
+ return *this;
+ }
+
TResult MaxWith(const TResult& rhs) {
for (const auto& kv : rhs.data_) {
double& v = data_[kv.first];
@@ -140,9 +147,11 @@ class FlopEstimator : private ExprFunctor<TResult(const PrimExpr& n)>,
TResult VisitStmt_(const ForNode* loop) override {
TResult result = VisitStmt(loop->body);
const auto* int_imm = loop->extent.as<IntImmNode>();
- ICHECK(int_imm) << "TypeError: Expect the extent of a loop to be IntImm, but gets: "
- << loop->extent->GetTypeKey();
- result *= int_imm->value;
+ if(int_imm == nullptr) {
+ result.SetInvalid();
+ } else {
+ result *= int_imm->value;
+ }
return result;
}
[tvm] 02/08: working
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit a54064659bd6e1239ec612864130428f78503bc3
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Fri May 12 21:48:50 2023 +0000
working
---
include/tvm/relax/attrs/index.h | 8 +
python/tvm/relax/expr.py | 2 +-
python/tvm/relax/frontend/torch/fx_translator.py | 204 +++++++++++++++++++++--
src/relax/op/tensor/index.cc | 1 -
4 files changed, 203 insertions(+), 12 deletions(-)
diff --git a/include/tvm/relax/attrs/index.h b/include/tvm/relax/attrs/index.h
index c95395a803..e31a334bf3 100644
--- a/include/tvm/relax/attrs/index.h
+++ b/include/tvm/relax/attrs/index.h
@@ -56,6 +56,14 @@ struct StridedSliceAttrs : public tvm::AttrsNode<StridedSliceAttrs> {
}
}; // struct StridedSliceAttrs
+/*! \brief Attributes used in strided_slice operator */
+struct DataDependentStridedSliceAttrs : public tvm::AttrsNode<DataDependentStridedSliceAttrs> {
+ Array<Integer> axes;
+ TVM_DECLARE_ATTRS(DataDependentStridedSliceAttrs, "relax.attrs.DataDependentStridedSliceAttrs") {
+ TVM_ATTR_FIELD(axes).describe("Axes along which slicing is applied.");
+ }
+};
+
} // namespace relax
} // namespace tvm
diff --git a/python/tvm/relax/expr.py b/python/tvm/relax/expr.py
index fdf98c179b..d3550741f7 100644
--- a/python/tvm/relax/expr.py
+++ b/python/tvm/relax/expr.py
@@ -652,7 +652,7 @@ def const(
value = _nd.array(value)
if not isinstance(value, _nd.NDArray):
- raise ValueError("value has to be scalar or NDArray")
+ raise ValueError(f"value has to be scalar or NDArray but it is {type(value)}")
return Constant(value)
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index 7166b312a0..2d94b246de 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -23,7 +23,105 @@ from functools import reduce
import tvm
from tvm import relax
-
+import numpy as np
+
+def _pytorch_result_type(dtypes, non_tensor_inputs):
+ """This promotes TVM dtypes like PyTorch would"""
+ import torch
+
+ dtype_map = {
+ "float64": torch.float64,
+ "float32": torch.float32,
+ "float16": torch.float16,
+ "bfloat16": torch.bfloat16,
+ "int64": torch.int64,
+ "int32": torch.int32,
+ "int16": torch.int16,
+ "int8": torch.int8,
+ "uint8": torch.uint8,
+ "bool": torch.bool,
+ }
+ if len(dtypes) > 0:
+ result_type = dtypes[0]
+ for dt in dtypes[1:]:
+ if dt != result_type: # we don't want to work with same types as we
+ # don't do quantized here (which cannot be promoted?)
+ result_type = _convert_data_type(
+ str(
+ torch.result_type(
+ torch.zeros((), dtype=dtype_map[result_type]),
+ torch.zeros((), dtype=dtype_map[dt]),
+ )
+ )
+ )
+ else:
+ result_type = "bool" # this is the smallest type...
+ for inp in non_tensor_inputs:
+ result_type = _convert_data_type(
+ str(torch.result_type(torch.zeros((), dtype=dtype_map[result_type]), inp))
+ )
+ return result_type
+
+
+# Helper functions for operator implementation
+def _convert_dtype_value(val):
+ """converts a PyTorch the PyTorch numeric type id to a torch scalar type."""
+ convert_torch_dtype_map = {
+ 11: "torch.bool",
+ 7: "torch.float64",
+ 6: "torch.float32",
+ 5: "torch.float16",
+ 4: "torch.int64",
+ 3: "torch.int32",
+ 2: "torch.int16",
+ 1: "torch.int8",
+ 0: "torch.uint8",
+ None: "torch.int64",
+ } # Default is torch.int64
+ if val in convert_torch_dtype_map:
+ return _convert_data_type(convert_torch_dtype_map[val])
+ else:
+ msg = "Torch data type value %d is not handled yet." % (val)
+ raise NotImplementedError(msg)
+
+
+def _convert_data_type(input_type, default_dtype=None):
+ """converts the PyTorch scalar type input_type to a TVM dtype.
+ optionally, default_dtype can be a TVM dtype that is used
+ if input_type is None (but not when it is unknown)"""
+ if input_type is None and default_dtype is not None:
+ return default_dtype
+
+ input_type = input_type.lower()
+ if input_type in ["double", "float64", "torch.float64"]:
+ return "float64"
+ elif input_type in ["float", "float32", "torch.float32"]:
+ return "float32"
+ elif input_type in ["half", "float16", "torch.float16"]:
+ return "float16"
+ elif input_type in ["long", "int64", "torch.int64"]:
+ return "int64"
+ elif input_type in ["int", "int32", "torch.int32"]:
+ return "int32"
+ elif input_type in ["short", "int16", "torch.int16"]:
+ return "int16"
+ elif input_type in ["char", "int8", "torch.int8"]:
+ return "int8"
+ elif input_type in ["byte", "uint8", "torch.uint8"]:
+ return "uint8"
+ elif input_type in ["quint8", "torch.quint8"]:
+ return "quint8"
+ elif input_type in ["qint8", "torch.qint8"]:
+ return "qint8"
+ elif input_type in ["qint32", "torch.qint32"]:
+ return "qint32"
+ elif input_type in ["bool", "torch.bool"]:
+ return "bool"
+ elif input_type in ["str"]:
+ return "str"
+ else:
+ raise NotImplementedError("input_type {} is not handled yet".format(input_type))
+ return "float32" # Never reached
class TorchFXImporter:
"""An importer from PyTorch FX to Relax."""
@@ -86,6 +184,23 @@ class TorchFXImporter:
dtype = TorchFXImporter._convert_data_type(str(tensor.data.dtype))
return relax.const(tensor.data.numpy(), dtype)
+ @staticmethod
+ def _promote_types(inputs):
+ """This promotes TVM inputs with TVM dtypes passed like PyTorch would"""
+ dtypes = [inp.struct_info.dtype for inp in inputs]
+ tensor_dtypes = [dt for inp, dt in zip(inputs, dtypes) if not np.isscalar(inp)]
+ non_tensor_inputs = [inp for inp in inputs if np.isscalar(inp)]
+ result_type = _pytorch_result_type(tensor_dtypes, non_tensor_inputs)
+ results = []
+ for inp, dt in zip(inputs, dtypes):
+ if np.isscalar(inp):
+ results.append(relax.const(inp, dtype=result_type))
+ elif dt == result_type:
+ results.append(inp)
+ else:
+ results.append(relax.op.astype(inp, result_type))
+ return results
+
@staticmethod
def shape_of(tensor):
"""Get the shape of a tensor."""
@@ -119,7 +234,8 @@ class TorchFXImporter:
@staticmethod
def _promote_binary_op_args(lhs, rhs):
if isinstance(lhs, relax.Expr) and isinstance(rhs, relax.Expr):
- return lhs, rhs
+ lhs_, rhs_ = TorchFXImporter._promote_types((lhs, rhs))
+ return lhs_, rhs_
elif isinstance(lhs, relax.Expr):
assert isinstance(lhs.struct_info, relax.TensorStructInfo)
return lhs, relax.const(rhs, lhs.struct_info.dtype)
@@ -151,6 +267,8 @@ class TorchFXImporter:
arg = self.env[node.args[0]]
if isinstance(arg, (int, float)):
arg = relax.const(arg, "float32")
+ if isinstance(arg, (tvm.tir.FloatImm, tvm.tir.IntImm)):
+ arg = relax.const(arg.value, "float32")
return self.block_builder.emit(relax.op.sqrt(arg))
def _rsqrt(self, node: fx.node.Node) -> relax.Expr:
@@ -180,9 +298,8 @@ class TorchFXImporter:
return lhs + rhs
def _max(self, node: fx.node.Node) -> relax.Expr:
- lhs, rhs = self.retrieve_args(node)
- if isinstance(lhs, relax.Var) or isinstance(rhs, relax.Var):
- return self._call_binary_op(relax.op.maximum, lhs, rhs)
+ lhs, = self.retrieve_args(node)
+ return self.block_builder.emit(relax.op.max(lhs))
def _floordiv(self, node: fx.node.Node) -> relax.Expr:
lhs, rhs = self.retrieve_args(node)
@@ -190,6 +307,10 @@ class TorchFXImporter:
return self._call_binary_op(relax.op.floor_divide, lhs, rhs)
return lhs // rhs
+ def _floor(self, node: fx.node.Node) -> relax.Expr:
+ lhs, = self.retrieve_args(node)
+ return self.block_builder.emit(relax.op.floor(lhs))
+
def _mul(self, node: fx.node.Node) -> relax.Expr:
lhs, rhs = self.retrieve_args(node)
if isinstance(lhs, relax.Var) or isinstance(rhs, relax.Var):
@@ -248,6 +369,10 @@ class TorchFXImporter:
lhs, rhs = self.retrieve_args(node)
return self._call_binary_op(relax.op.equal, lhs, rhs)
+ def _ne(self, node: fx.node.Node) -> relax.Expr:
+ lhs, rhs = self.retrieve_args(node)
+ return self._call_binary_op(relax.op.not_equal, lhs, rhs)
+
########## Creation ##########
def _arange(self, node: fx.node.Node) -> relax.Var:
@@ -501,7 +626,13 @@ class TorchFXImporter:
def _expand(self, node: fx.node.Node) -> relax.Var:
args = self.retrieve_args(node)
- return self.block_builder.emit(relax.op.broadcast_to(args[0], args[1:]))
+ # -1 indicates dimension remains the same
+ fixed_dims = [args[0].struct_info.shape[i] if d == -1 else d for i, d in enumerate(args[1:])]
+ return self.block_builder.emit(relax.op.broadcast_to(args[0], fixed_dims))
+
+ def _expand_as(self, node: fx.node.Node) -> relax.Var:
+ args = self.retrieve_args(node)
+ return self.block_builder.emit(relax.op.broadcast_to(args[0], self.shape_of(args[1])))
def _flatten(self, node: fx.node.Node) -> relax.Var:
x = self.env[node.args[0]]
@@ -574,6 +705,19 @@ class TorchFXImporter:
dim = None
return self.block_builder.emit(relax.op.squeeze(x, dim))
+ def _repeat_interleave(self, node: fx.node.Node) -> relax.Var:
+ data, repeats = self.retrieve_args(node)
+ if not "dim" in node.kwargs:
+ data = relax.op.reshape(args[0], [-1])
+ axis = 0
+ else:
+ axis = node.kwargs["dim"]
+ return self.block_builder.emit(relax.op.repeat(data, repeats=repeats.value, axis=axis))
+
+ def _stack(self, node: fx.node.Node) -> relax.Var:
+ args = [self.env[x] for x in node.args[0]]
+ return self.block_builder.emit(relax.op.concat(args, node.kwargs["dim"]))
+
def _cumsum(self, node: fx.node.Node) -> relax.Var:
x = self.env[node.args[0]]
@@ -711,6 +855,34 @@ class TorchFXImporter:
return self.block_builder.emit(relax.op.add(conv2d, bias))
+ def _convtranpose2d(self, node: fx.node.Node) -> relax.Var:
+ x = self.env[node.args[0]]
+ module = self.named_modules[node.target]
+ weight = self.params[module.weight]
+
+ conv2d = self.block_builder.emit(
+ relax.op.nn.conv2d_transpose(
+ x,
+ weight,
+ strides=module.stride,
+ padding=module.padding,
+ dilation=module.dilation,
+ groups=module.groups,
+ data_layout="NCHW",
+ kernel_layout="IOHW",
+ out_dtype="float32",
+ )
+ )
+
+ if module.bias is None:
+ return conv2d
+
+ bias = self.params[module.bias]
+ assert len(self.shape_of(bias)) == 1
+ bias = relax.op.reshape(bias, (1, -1, 1, 1))
+
+ return self.block_builder.emit(relax.op.add(conv2d, bias))
+
def _max_pool2d(self, node: fx.node.Node) -> relax.Var:
x = self.env[node.args[0]]
if node.target in self.named_modules:
@@ -1135,10 +1307,11 @@ class TorchFXImporter:
i = 0
shape = self.shape_of(x)
non_ellipsis_cnt = 0
- for index in node.args[1]:
+ idxs = [node.args[1]] if isinstance(node.args[1], int) else node.args[1]
+ for index in idxs:
if isinstance(index, (int, slice)):
non_ellipsis_cnt += 1
- for index in node.args[1]:
+ for index in idxs:
if isinstance(index, int):
begin.append(index)
end.append(index + 1)
@@ -1147,7 +1320,12 @@ class TorchFXImporter:
i = i + 1
elif isinstance(index, slice):
begin.append(0 if index.start is None else index.start)
- end.append(shape[i] if index.stop is None else index.stop)
+ if index.stop is None:
+ end.append(shape[i])
+ elif isinstance(index.stop, fx.node.Node):
+ end.append(self.env[index.stop])
+ else:
+ end.append(index.stop)
stride.append(1 if index.step is None else index.step)
axes.append(i)
i = i + 1
@@ -1168,6 +1346,7 @@ class TorchFXImporter:
stride.append(1)
axes.append(i)
i += 1
+ print([type(x) for x in axes], [type(x) for x in begin], [type(x) for x in end], [type(x) for x in stride])
sliced = self.block_builder.emit(relax.op.strided_slice(x, axes, begin, end, stride))
sliced_shape = list(self.shape_of(sliced))
for i in expand_dim:
@@ -1181,7 +1360,6 @@ class TorchFXImporter:
dtype = x.struct_info.dtype
return relax.const(x.data.numpy()[node.args[1]], dtype)
else:
- import IPython;IPython.embed()
raise ValueError(f"Unsupported type {type(x)} for _getitem, should be list, tuple, ShapeExpr, Tuple, Var, or Constant")
def create_convert_map(self):
@@ -1193,6 +1371,7 @@ class TorchFXImporter:
nn.Linear: self._linear,
nn.Conv1d: self._conv1d,
nn.Conv2d: self._conv2d,
+ nn.ConvTranspose2d: self._convtranpose2d,
nn.MaxPool2d: self._max_pool2d,
nn.AvgPool2d: self._avg_pool2d,
nn.AdaptiveAvgPool2d: self._adaptive_avg_pool2d(is_module=True),
@@ -1218,6 +1397,7 @@ class TorchFXImporter:
"iadd": self._add,
"add": self._add,
"floordiv": self._floordiv,
+ "floor": self._floor,
"mul": self._mul,
"sub": self._sub,
"pow": self._pow,
@@ -1226,6 +1406,7 @@ class TorchFXImporter:
"round": self._round,
"lt": self._lt,
"eq": self._eq,
+ "ne": self._ne,
"truediv": self._truediv,
"fill_": self._inplace_fill,
"new_ones": self._new_ones,
@@ -1265,6 +1446,8 @@ class TorchFXImporter:
"unsqueeze": lambda node: self.block_builder.emit(
relax.op.expand_dims(self.env[node.args[0]], node.args[1])
),
+ "repeat_interleave": self._repeat_interleave,
+ "stack": self._stack,
"view": self._reshape,
"argmax": self._argmax_argmin(relax.op.argmax),
"argmin": self._argmax_argmin(relax.op.argmin),
@@ -1298,6 +1481,7 @@ class TorchFXImporter:
"pad": self._pad,
"unbind": self._unbind,
"einsum": self._einsum,
+ "expand_as": self._expand_as,
}
def from_fx(
diff --git a/src/relax/op/tensor/index.cc b/src/relax/op/tensor/index.cc
index c3d38db4e1..d3bb34d21a 100644
--- a/src/relax/op/tensor/index.cc
+++ b/src/relax/op/tensor/index.cc
@@ -312,6 +312,5 @@ TVM_REGISTER_OP("relax.dynamic_strided_slice")
.add_argument("end", "Tensor", "Indices indicating end of the slice.")
.add_argument("strides", "Tensor", "The stride values.")
.set_attr<FInferStructInfo>("FInferStructInfo", InferStructInfoDynStridedSlice);
-
} // namespace relax
} // namespace tvm
[tvm] 06/08: save metadata to file
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit b1c5c6a66253540237a56766f932d7ad328b9b30
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Wed May 17 20:11:11 2023 +0000
save metadata to file
---
src/relax/backend/vm/vm_shape_lower.cc | 2 +-
src/script/printer/utils.h | 1 +
2 files changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/relax/backend/vm/vm_shape_lower.cc b/src/relax/backend/vm/vm_shape_lower.cc
index f4b272979b..5b314117b3 100644
--- a/src/relax/backend/vm/vm_shape_lower.cc
+++ b/src/relax/backend/vm/vm_shape_lower.cc
@@ -370,7 +370,7 @@ class VMShapeLowerMutator
}
void VisitBinding_(const MatchCastNode* binding) final {
- Expr value = ExprMutator::VisitExpr(binding->value);
+ Expr value = ExprMutator::VisitExpr(binding->value);
std::vector<MatchShapeTodoItem> match_todos;
std::ostringstream err_ctx;
err_ctx << "ErrorContext(match_cast, struct_info=" << binding->struct_info << ") ";
diff --git a/src/script/printer/utils.h b/src/script/printer/utils.h
index 2a2f469082..906c139d25 100644
--- a/src/script/printer/utils.h
+++ b/src/script/printer/utils.h
@@ -80,6 +80,7 @@ inline std::string Docsify(const ObjectRef& obj, const IRDocsifier& d, const Fra
std::ostringstream os;
if (!d->metadata.empty()) {
if (d->cfg->show_meta) {
+ // std::ofstream("metadata.json") << SaveJSON(Map<String, ObjectRef>(d->metadata.begin(), d->metadata.end()));
os << "metadata = tvm.ir.load_json(\""
<< support::StrEscape(
SaveJSON(Map<String, ObjectRef>(d->metadata.begin(), d->metadata.end())))
[tvm] 03/08: trying data dependent dynamic slice
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit eb4b473ba27bcfcc5c6a62345a20bb65462054b8
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Mon May 15 16:30:21 2023 +0000
trying data dependent dynamic slice
---
python/tvm/relax/frontend/torch/fx_translator.py | 6 ++++-
src/relax/op/tensor/index.cc | 32 ++++++++++++++++++++++++
2 files changed, 37 insertions(+), 1 deletion(-)
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index 2d94b246de..2af651bb97 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -1347,7 +1347,11 @@ class TorchFXImporter:
axes.append(i)
i += 1
print([type(x) for x in axes], [type(x) for x in begin], [type(x) for x in end], [type(x) for x in stride])
- sliced = self.block_builder.emit(relax.op.strided_slice(x, axes, begin, end, stride))
+ if any([isinstance(x, relax.Var) for x in begin]) or any([isinstance(x, relax.Var) for x in end]):
+ print(end)
+ sliced = self.block_builder.emit(relax.op.data_dependent_strided_slice(x, axes, begin, relax.const(np.array(end, dtype=int))))
+ else:
+ sliced = self.block_builder.emit(relax.op.strided_slice(x, axes, begin, end, stride))
sliced_shape = list(self.shape_of(sliced))
for i in expand_dim:
sliced_shape.insert(i, 1)
diff --git a/src/relax/op/tensor/index.cc b/src/relax/op/tensor/index.cc
index d3bb34d21a..6510967992 100644
--- a/src/relax/op/tensor/index.cc
+++ b/src/relax/op/tensor/index.cc
@@ -239,6 +239,7 @@ TVM_REGISTER_OP("relax.strided_slice")
.set_attr<FRelaxInferLayout>("FRelaxInferLayout", InferLayoutStridedSlice)
.set_attr<TMixedPrecisionPolicy>("TMixedPrecisionPolicy", MixedPrecisionPolicyKind::kFollow);
+<<<<<<< HEAD
/* relax.dynamic_strided_slice */
Expr dynamic_strided_slice(Expr x, //
Expr begin, //
@@ -246,6 +247,37 @@ Expr dynamic_strided_slice(Expr x, //
Expr strides) {
static const Op& op = Op::Get("relax.dynamic_strided_slice");
return Call(op, {std::move(x), std::move(begin), std::move(end), std::move(strides)}, {});
+||||||| parent of f322af441 (trying data dependent dynamic slice)
+/* relax.data_dependent_strided_slice */
+// TODO: support dynamic number of axes
+TVM_REGISTER_NODE_TYPE(DataDependentStridedSliceAttrs);
+
+Expr data_dependent_strided_slice(Expr x, //
+ Array<Integer> axes, //
+ Expr begin, //
+ Expr end) {
+ int n_axis = axes.size();
+
+ ObjectPtr<DataDependentStridedSliceAttrs> attrs = make_object<DataDependentStridedSliceAttrs>();
+ attrs->axes = std::move(axes);
+
+ static const Op& op = Op::Get("relax.data_dependent_strided_slice");
+ return Call(op, {std::move(x), std::move(begin), std::move(end)}, Attrs(attrs), {});
+=======
+/* relax.data_dependent_strided_slice */
+// TODO: support dynamic number of axes
+TVM_REGISTER_NODE_TYPE(DataDependentStridedSliceAttrs);
+
+Expr data_dependent_strided_slice(Expr x, //
+ Array<Integer> axes, //
+ Expr begin, //
+ Expr end) {
+ ObjectPtr<DataDependentStridedSliceAttrs> attrs = make_object<DataDependentStridedSliceAttrs>();
+ attrs->axes = std::move(axes);
+
+ static const Op& op = Op::Get("relax.data_dependent_strided_slice");
+ return Call(op, {std::move(x), std::move(begin), std::move(end)}, Attrs(attrs), {});
+>>>>>>> f322af441 (trying data dependent dynamic slice)
}
TVM_REGISTER_GLOBAL("relax.op.dynamic_strided_slice").set_body_typed(dynamic_strided_slice);
[tvm] 08/08: Fix RewriteDataflowReshape to no rewrite when buffer shapes are not the same
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit c342da80525124a18b231ac9fb1c04068e2cbac0
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Thu May 18 23:47:07 2023 +0000
Fix RewriteDataflowReshape to no rewrite when buffer shapes are not the same
Before only read and written indices were compared to see if an op could
be rewritten to a reshape. Now the buffers shape is checked for
compatibility too.
---
src/relax/analysis/tir_op_pattern_kind.cc | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
diff --git a/src/relax/analysis/tir_op_pattern_kind.cc b/src/relax/analysis/tir_op_pattern_kind.cc
index 950e6a10e0..38f411ae50 100644
--- a/src/relax/analysis/tir_op_pattern_kind.cc
+++ b/src/relax/analysis/tir_op_pattern_kind.cc
@@ -23,7 +23,18 @@
#include <tvm/tir/function.h>
#include <tvm/tir/stmt_functor.h>
+
namespace tvm {
+namespace {
+// Helper function for flatten and reshape.
+PrimExpr ComputeShapeProduct(const Array<PrimExpr>& shape_values) {
+ PrimExpr shape_prod = IntImm(DataType::Int(64), 1);
+ for (PrimExpr value : shape_values) {
+ shape_prod *= value;
+ }
+ return shape_prod;
+}
+}
namespace relax {
using namespace tir;
@@ -433,8 +444,8 @@ bool HasReshapePattern(const PrimFunc& func) {
PrimExpr src_idx = f_calc_flattened_idx(src_buffer_, buffer_load->indices);
PrimExpr dst_idx = f_calc_flattened_idx(dst_buffer_, buffer_store->indices);
- // Step 4. Check if we can prove the equality of flattened indices.
- if (ana_.CanProveEqual(src_idx, dst_idx)) {
+ // Step 4. Check if we can prove the equality of flattened indices and that the output buffer shape is equivalent to the input.
+ if (ana_.CanProveEqual(src_idx, dst_idx) && ana_.CanProveEqual(ComputeShapeProduct(src_buffer_->shape), ComputeShapeProduct(dst_buffer_->shape))) {
this->is_reshape_ = true;
}
}
[tvm] 01/08: Add einsum, gelu, pad support to relax
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit f62d3277abe093c3923099579bec0b2e2c0a88ee
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Thu May 11 16:23:18 2023 +0000
Add einsum, gelu, pad support to relax
---
include/tvm/relax/attrs/nn.h | 32 +++
python/tvm/relax/frontend/torch/fx_translator.py | 101 ++++++++-
python/tvm/relax/op/nn/nn.py | 28 ++-
python/tvm/relax/transform/legalize_ops/nn.py | 6 +
src/relax/op/nn/pad.cc | 250 +++++++++++++++++++++++
src/relax/op/op_common.cc | 2 +-
src/tir/op/op.cc | 2 +-
7 files changed, 415 insertions(+), 6 deletions(-)
diff --git a/include/tvm/relax/attrs/nn.h b/include/tvm/relax/attrs/nn.h
index c1ca468fc9..8c5666d62b 100644
--- a/include/tvm/relax/attrs/nn.h
+++ b/include/tvm/relax/attrs/nn.h
@@ -320,6 +320,38 @@ struct AttentionAttrs : public tvm::AttrsNode<AttentionAttrs> {
}
}; // struct AttentionAttrs
+/*! \brief Attributes used for the padding operator */
+struct PadAttrs : public tvm::AttrsNode<PadAttrs> {
+ Array<Array<Integer>> pad_width;
+ tvm::String pad_mode;
+
+ TVM_DECLARE_ATTRS(PadAttrs, "relay.attrs.PadAttrs") {
+ TVM_ATTR_FIELD(pad_width).describe(
+ "Number of values padded to the edges of each axis, "
+ "in the format of ((before_1, after_1), ..., (before_N, after_N))");
+ TVM_ATTR_FIELD(pad_mode)
+ .set_default("constant")
+ .describe(
+ "Padding type to use. \"constant\" pads with constant_value, "
+ "\"edge\" pads using the edge values of the input array, "
+ "\"reflect\" pads by reflecting values with respect to the edges.");
+ }
+};
+
+/*! \brief Attributes used for the MirrorPadding operator */
+struct MirrorPadAttrs : public tvm::AttrsNode<MirrorPadAttrs> {
+ std::string mode;
+ Array<Array<PrimExpr>> pad_width;
+
+ TVM_DECLARE_ATTRS(MirrorPadAttrs, "relay.attrs.MirrorPadAttrs") {
+ TVM_ATTR_FIELD(mode)
+ .set_default("SYMMETRIC")
+ .describe("Specifies how mirroring should be performed.");
+ TVM_ATTR_FIELD(pad_width).describe(
+ "Number of values padded to the edges of each axis, "
+ "in the format of ((before_1, after_1), ..., (before_N, after_N))");
+ }
+};
} // namespace relax
} // namespace tvm
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index a29070a325..7166b312a0 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -194,6 +194,10 @@ class TorchFXImporter:
lhs, rhs = self.retrieve_args(node)
if isinstance(lhs, relax.Var) or isinstance(rhs, relax.Var):
return self._call_binary_op(relax.op.multiply, lhs, rhs)
+ if isinstance(rhs, (int, float)):
+ rhs = relax.const(rhs)
+ if isinstance(lhs, (int, float)):
+ lhs = relax.const(lhs)
return lhs * rhs
def _pow(self, node: fx.node.Node) -> relax.Expr:
@@ -417,6 +421,18 @@ class TorchFXImporter:
def _half(self, node: fx.node.Node) -> relax.Var:
return self.block_builder.emit(relax.op.astype(self.env[node.args[0]], "float16"))
+ def _long(self, node: fx.node.Node) -> relax.Var:
+ return self.block_builder.emit(relax.op.astype(self.env[node.args[0]], "int64"))
+
+ def _int(self, node: fx.node.Node) -> relax.Var:
+ return self.block_builder.emit(relax.op.astype(self.env[node.args[0]], "int32"))
+
+ def _short(self, node: fx.node.Node) -> relax.Var:
+ return self.block_builder.emit(relax.op.astype(self.env[node.args[0]], "int16"))
+
+ def _int8(self, node: fx.node.Node) -> relax.Var:
+ return self.block_builder.emit(relax.op.astype(self.env[node.args[0]], "int8"))
+
def _type(self, node: fx.node.Node) -> relax.Var:
x = self.env[node.args[0]]
dtype = TorchFXImporter._convert_data_type(node.args[1], self.env)
@@ -576,6 +592,10 @@ class TorchFXImporter:
return self.block_builder.emit(relax.op.cumsum(x, dim, dtype))
+ def _einsum(self, node: fx.node.Node) -> relax.Var:
+ operands = [self.env[x] for x in node.args[1:]]
+ return self.block_builder.emit(relax.op.einsum(operands, node.args[0]))
+
def _index_select(self, node: fx.node.Node) -> relax.Var:
x = self.env[node.args[0]]
dim = node.args[1]
@@ -1002,6 +1022,7 @@ class TorchFXImporter:
)
)
+<<<<<<< HEAD
def _scaled_dot_product_attention(self, node: fx.node.Node) -> relax.Var:
assert len(node.args) <= 4, "Dropout, and causal masking are not supported."
transpose_S_H = lambda tensor: relax.op.permute_dims(tensor, [0, 2, 1, 3])
@@ -1019,6 +1040,62 @@ class TorchFXImporter:
return self.block_builder.emit(attn)
+||||||| parent of 97e234777 (Add einsum, gelu, pad support to relax)
+=======
+ def _pad_common(self, mode, pad_value, inputs):
+ data = self.env[inputs[0]]
+ pad_list = inputs[1]
+
+ # initialize paddings based on input len
+ pad_len = len(data.struct_info.shape) * 2
+ paddings = [0] * pad_len
+
+ if len(pad_list) >= 2:
+ paddings[-1] = pad_list[1]
+ paddings[-2] = pad_list[0]
+ if len(pad_list) >= 4:
+ paddings[-3] = pad_list[3]
+ paddings[-4] = pad_list[2]
+ if len(pad_list) >= 6:
+ paddings[-5] = pad_list[5]
+ paddings[-6] = pad_list[4]
+
+ # group into tuple of 2 ints
+ paddings = [paddings[i : i + 2] for i in range(0, len(paddings), 2)]
+
+ if mode == "constant":
+ return self.block_builder.emit(relax.op.nn.pad(data, paddings, pad_value=relax.const(pad_value), pad_mode=mode))
+ else:
+ return self.block_builder.emit(relax.op.nn.pad(data, paddings, pad_mode=mode))
+
+ def _pad(self, node: fx.node.Node) -> relax.Expr:
+ if len(node.args) > 2 and node.args[2] is not None:
+ mode = node.args[2]
+ else:
+ mode = 'constant'
+
+ if len(node.args) == 4 and node.args[3] is not None:
+ pad_value = node.args[3]
+ else:
+ pad_value = 0
+ return self._pad_common(mode, pad_value, node.args)
+
+ def _unbind(self, node: fx.node.Node) -> relax.Expr:
+ data = self.env[node.args[0]]
+ shape = data.struct_info.shape
+ if len(node.args) == 2 and node.args[1] is not None:
+ axis = node.args[1]
+ else:
+ axis = 0
+
+ selections = shape[axis]
+ res_split = relax.op.split(data, selections, axis)
+ ret = []
+ for i in range(selections.value):
+ ret.append(relax.op.squeeze(res_split[i], axis=[axis]))
+ return self.block_builder.emit(relax.expr.Tuple(ret))
+
+
########## Others ##########
def _size(self, node: fx.node.Node) -> relax.Expr:
@@ -1040,6 +1117,8 @@ class TorchFXImporter:
return getattr(self.env[node.args[0]], node.args[1])
def _getitem(self, node: fx.node.Node) -> relax.Var:
+ from torch import fx
+
x = self.env[node.args[0]]
if isinstance(x, (list, tuple, relax.ShapeExpr, relax.Tuple)):
return x[node.args[1]]
@@ -1095,10 +1174,15 @@ class TorchFXImporter:
sliced_shape.insert(i, 1)
return self.block_builder.emit(relax.op.reshape(sliced, sliced_shape))
elif isinstance(x, relax.Constant):
- dtype = x.struct_info.dtype
- return relax.const(x.data.numpy()[node.args[1]], dtype)
+ if isinstance(node.args[1], fx.node.Node):
+ idx = self.env[node.args[1]]
+ return self.block_builder.emit(relax.op.take(x,idx,axis=0))
+ else:
+ dtype = x.struct_info.dtype
+ return relax.const(x.data.numpy()[node.args[1]], dtype)
else:
- assert False
+ import IPython;IPython.embed()
+ raise ValueError(f"Unsupported type {type(x)} for _getitem, should be list, tuple, ShapeExpr, Tuple, Var, or Constant")
def create_convert_map(self):
from torch import nn
@@ -1118,6 +1202,7 @@ class TorchFXImporter:
relax.op.clip(self.env[node.args[0]], 0, 6)
),
nn.SiLU: lambda node: self.block_builder.emit(relax.op.nn.silu(self.env[node.args[0]])),
+ nn.GELU: lambda node: self.block_builder.emit(relax.op.nn.gelu(self.env[node.args[0]])),
nn.Flatten: self._flatten,
nn.BatchNorm2d: self._batch_norm_2d,
nn.LayerNorm: self._layer_norm,
@@ -1154,6 +1239,13 @@ class TorchFXImporter:
"sum": self._sum,
"float": self._float,
"half": self._half,
+ "long": self._long,
+ "int64": self._long,
+ "int": self._int,
+ "int32": self._int,
+ "short": self._short,
+ "int16": self._short,
+ "int8": self._int8,
"type": self._type,
"astype": self._type,
"matmul": self._matmul,
@@ -1203,6 +1295,9 @@ class TorchFXImporter:
"max": self._max,
"cross_entropy": self._cross_entropy,
"scaled_dot_product_attention": self._scaled_dot_product_attention,
+ "pad": self._pad,
+ "unbind": self._unbind,
+ "einsum": self._einsum,
}
def from_fx(
diff --git a/python/tvm/relax/op/nn/nn.py b/python/tvm/relax/op/nn/nn.py
index fb5e0736ff..5c58cc5966 100644
--- a/python/tvm/relax/op/nn/nn.py
+++ b/python/tvm/relax/op/nn/nn.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
# under the License.
"""Relax Neural Network (NN) operators"""
-from typing import List, Optional, Tuple, Union
+from typing import List, Optional, Tuple, Union, Sequence
from tvm import DataType
from tvm.tir import FloatImm
@@ -1022,3 +1022,29 @@ def attention(
(batch_size, seq_len, num_head, head_dim_v).
"""
return _ffi_api.attention(query, key, value, bias, scale) # type: ignore
+
+def pad(data: Expr, pad_width: Sequence[Sequence[int]], pad_value: Union[Expr, float]=0., pad_mode: str="constant"):
+ r"""Padding
+
+ This operator takes in a tensor and pads each axis by the specified
+ widths using the specified value.
+
+ Parameters
+ ----------
+ data: relax.Expr
+ The input data to the operator
+ pad_width: tuple of <tuple of <int>>, required
+ Number of values padded to the edges of each axis, in the format
+ of ((before_1, after_1), ..., (before_N, after_N))
+ pad_value: float, or tvm.relay.Expr, optional, default=0
+ The value used for padding
+ pad_mode: 'constant', 'edge', 'reflect'
+ 'constant' pads with constant_value pad_value
+ 'edge' pads using the edge values of the input array
+ 'reflect' pads by reflecting values with respect to the edge
+ Returns
+ -------
+ result : relax.Expr
+ The computed result.
+ """
+ return _ffi_api.pad(data, pad_width, pad_value, pad_mode)
diff --git a/python/tvm/relax/transform/legalize_ops/nn.py b/python/tvm/relax/transform/legalize_ops/nn.py
index 9c98682e32..b362660561 100644
--- a/python/tvm/relax/transform/legalize_ops/nn.py
+++ b/python/tvm/relax/transform/legalize_ops/nn.py
@@ -397,3 +397,9 @@ def _nn_nll_loss(bb: BlockBuilder, call: Call) -> Expr:
reduction=call.attrs.reduction,
ignore_index=call.attrs.ignore_index,
)
+
+@register_legalize("relax.nn.pad")
+def _pad(bb: BlockBuilder, call: Call) -> Expr:
+ assert call.attrs.pad_mode == "constant"
+ # return bb.call_te(topi.nn.pad, call.args[0], [x[0] for x in call.attrs.pad_width], [x[1] for x in call.attrs.pad_width], call.args[1])
+ return bb.call_te(topi.nn.pad, call.args[0], [x[0] for x in call.attrs.pad_width], [x[1] for x in call.attrs.pad_width], tir.const(call.args[1].data.numpy()[()]))
diff --git a/src/relax/op/nn/pad.cc b/src/relax/op/nn/pad.cc
new file mode 100644
index 0000000000..224ff7cb51
--- /dev/null
+++ b/src/relax/op/nn/pad.cc
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file pad.cc
+ * \brief Implementation of operator pad
+ */
+#include <tvm/relax/attrs/nn.h>
+#include <tvm/tir/data_layout.h>
+#include <tvm/tir/op.h>
+#include <tvm/topi/elemwise.h>
+#include <tvm/topi/nn.h>
+
+#include <vector>
+
+#include "../op_common.h"
+
+namespace tvm {
+namespace relax {
+
+// relax.nn.pad
+TVM_REGISTER_NODE_TYPE(PadAttrs);
+
+InferLayoutOutput PadInferLayout(const Call& call,
+ const Map<String, Array<String>>& desired_layouts,
+ const VarLayoutMap& var_layout_map) {
+
+ LayoutDecision exisiting_layout = GetLayoutDecision(var_layout_map, call->args[0]);
+ return InferLayoutOutput({exisiting_layout},
+ {exisiting_layout},
+ Attrs(call->attrs));
+ // TODO: handle layout changes for pad
+ // const auto* attrs_ptr = call->attrs.as<PadAttrs>();
+ // CHECK(attrs_ptr);
+ // ObjectPtr<PadAttrs> params = make_object<PadAttrs>(*attrs_ptr);
+ //
+ // Layout ret_data;
+ // // If new_in_layouts are defined, this code tries to modify the layout.
+ // bool is_layout_modified = new_in_layouts.defined();
+ // if (new_in_layouts.defined()) {
+ // // Create a map of axis to param_width. For the new layout, a new param_width is generated using
+ // // the map. The new layout is rejected, if the padding is happening along the axis which was
+ // // split.
+ //
+ // // 1) Create a map from axis to param_width using old layout.
+ // std::map<std::string, tvm::Array<Integer>> axis_pad_width;
+ // int index_counter = 0;
+ // ICHECK_EQ(new_in_layouts.size(), 2);
+ // ICHECK_EQ(old_in_layouts.size(), 2);
+ // for (auto iter_var : old_in_layouts[0]->axes) {
+ // const auto& old_layout_axis = LayoutAxis::Get(iter_var);
+ // axis_pad_width.emplace(old_layout_axis.name(), params->pad_width[index_counter]);
+ // index_counter++;
+ // }
+ //
+ // // 2) Create new pad width by walking over the new layout and using the map.
+ // tvm::Array<tvm::Array<Integer>> new_pad_width;
+ // for (auto iter_var : new_in_layouts[0]->axes) {
+ // const auto& new_layout_axis = LayoutAxis::Get(iter_var);
+ // auto axis_name = new_layout_axis.name();
+ // if (axis_pad_width.count(axis_name) != 0 && new_layout_axis.IsPrimal()) {
+ // // This is primal axis. So, directly use the original pad_width.
+ // new_pad_width.push_back(axis_pad_width.at(axis_name));
+ // } else {
+ // // This is the axis that got split. So, check that pad_width was [0, 0] originally.
+ // const auto& dual_axis = new_layout_axis.ToPrimal();
+ // auto dual_axis_name = dual_axis.name();
+ // ICHECK(axis_pad_width.count(dual_axis_name))
+ // << "Missing axis " << dual_axis << " in " << old_in_layouts[0].name();
+ // new_pad_width.push_back(axis_pad_width.at(dual_axis_name));
+ //
+ // // If any pad_width element is not zero, do not change the layout.
+ // for (auto width : axis_pad_width.at(dual_axis_name)) {
+ // if (auto* width_imm = width.as<IntImmNode>()) {
+ // if (width_imm->value != 0) {
+ // is_layout_modified = false;
+ // }
+ // } else {
+ // is_layout_modified = false;
+ // }
+ // }
+ // }
+ // }
+ //
+ // // If the above conditions satisfied, we can set the newly created pad_width and use the new
+ // // layout.
+ // if (is_layout_modified) {
+ // ret_data = new_in_layouts[0];
+ // params->pad_width = new_pad_width;
+ // }
+ // }
+ //
+ // if (!is_layout_modified) {
+ // if (old_in_layouts.defined()) {
+ // ICHECK_EQ(old_in_layouts.size(), 2);
+ // ret_data = old_in_layouts[0];
+ // } else {
+ // ret_data = Layout::Undef();
+ // }
+ // }
+ //
+ // // The pad value is always a scalar
+ // Layout ret_pad_value = Layout("1");
+ // return InferLayoutOutput({ret_data, ret_pad_value}, {ret_data}, Attrs(params));
+}
+
+StructInfo InferStructInfoPad(const Call& call, const BlockBuilder& ctx) {
+ auto infos = GetInputTensorStructInfo(call, ctx);
+ TensorStructInfo data_sinfo = infos[0];
+ const auto* attrs = call->attrs.as<PadAttrs>();
+
+ const auto* data_shape = data_sinfo->shape.as<ShapeExprNode>();
+ ICHECK_EQ(data_shape->values.size(), attrs->pad_width.size()) << "Data shape and padding should be the same size";
+
+ Array<PrimExpr> padded_shape;
+ for(size_t i = 0; i < data_shape->values.size(); i++) {
+ padded_shape.push_back(data_shape->values[i] + attrs->pad_width[i][0] + attrs->pad_width[i][1]);
+ }
+ return TensorStructInfo(ShapeExpr(padded_shape), data_sinfo->dtype);
+}
+
+Array<te::Tensor> PadCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
+ const Type& out_type) {
+ const auto* param = attrs.as<PadAttrs>();
+ ICHECK(param != nullptr);
+
+ auto pad_width = param->pad_width;
+ ICHECK(pad_width.size() == inputs[0].ndim() && pad_width[0].size() == 2) << "Illegal pad_width";
+ Array<PrimExpr> pad_before;
+ for (size_t i = 0; i < pad_width.size(); ++i) {
+ pad_before.push_back(pad_width[i][0]);
+ }
+ Array<PrimExpr> pad_after;
+ for (size_t i = 0; i < pad_width.size(); ++i) {
+ pad_after.push_back(pad_width[i][1]);
+ }
+ te::Tensor cast_pad_value = topi::cast(inputs[1], inputs[0]->dtype);
+ const PrimExpr& pad_value = cast_pad_value(Array<PrimExpr>(inputs[1]->shape.size(), 0));
+ return Array<te::Tensor>{topi::pad(inputs[0], pad_before, pad_after, pad_value, "T_pad",
+ topi::kElementWise, param->pad_mode)};
+}
+
+// Handler to create a call to the padding op used by front-end FFI
+Expr MakePad(Expr data, Array<Array<Integer>> pad_width, Expr pad_value, String pad_mode) {
+ auto attrs = make_object<PadAttrs>();
+ attrs->pad_width = std::move(pad_width);
+ attrs->pad_mode = std::move(pad_mode);
+ static const Op& op = Op::Get("relax.nn.pad");
+ return Call(op, {data, pad_value}, Attrs(attrs), {});
+}
+
+TVM_REGISTER_GLOBAL("relax.op.nn.pad").set_body_typed(MakePad);
+
+TVM_REGISTER_OP("relax.nn.pad")
+ .describe(R"code(Pad for n-D tensor.
+
+)code" TVM_ADD_FILELINE)
+ .set_attrs_type<PadAttrs>()
+ .set_num_inputs(2)
+ .add_argument("data", "Tensor", "The input tensor.")
+ .add_argument("pad_val", "Tensor", "The value to fill the padded area with")
+ .set_support_level(2)
+ .set_attr<FInferStructInfo>("FInferStructInfo", InferStructInfoPad)
+ .set_attr<FRelaxInferLayout>("FRelaxInferLayout", PadInferLayout);
+ // .set_attr<TOpPattern>("TOpPattern", kInjective)
+ // .set_attr<FTVMCompute>("FTVMCompute", PadCompute);
+
+// relax.nn.mirror_pad
+TVM_REGISTER_NODE_TYPE(MirrorPadAttrs);
+
+bool MirrorPadRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
+ const TypeReporter& reporter) {
+ ICHECK_EQ(types.size(), 2);
+ const auto* data = types[0].as<TensorTypeNode>();
+ if (data == nullptr) return false;
+
+ const MirrorPadAttrs* param = attrs.as<MirrorPadAttrs>();
+ ICHECK(param != nullptr);
+
+ // check that pad widths match lengths
+ ICHECK(data->shape.size() == param->pad_width.size())
+ << "There should be as many pad width pairs as shape dimensions "
+ << "but the shape has " << data->shape.size() << " dimensions "
+ << "and there are " << param->pad_width.size() << " pad width pairs.";
+
+ // each pad width element should be a pair of positive integers
+ std::vector<PrimExpr> oshape;
+ for (size_t i = 0; i < param->pad_width.size(); i++) {
+ ICHECK(param->pad_width[i].size() == 2)
+ << "Each pad width element should be a pair but at index " << i << " there are "
+ << param->pad_width[i].size() << " elements.";
+
+ auto width1 = tir::as_const_int(param->pad_width[i][0]);
+ auto width2 = tir::as_const_int(param->pad_width[i][1]);
+ ICHECK(width1 != nullptr);
+ ICHECK(width2 != nullptr);
+
+ ICHECK(*width1 >= 0) << "Param width elements should be positive but first pad width at "
+ << "index " << i << " is " << *width1 << ".";
+ ICHECK(*width2 >= 0) << "Param width elements should be positive but first pad width at "
+ << "index " << i << " is " << *width2 << ".";
+
+ auto padding = tir::make_const(data->shape[i].dtype(), *width1 + *width2);
+ oshape.push_back(data->shape[i] + padding);
+ }
+
+ reporter->Assign(types[1], TensorType(Array<PrimExpr>(oshape), data->dtype));
+ return true;
+}
+
+// Handler to create a call to the padding op used by front-end FFI
+Expr MakeMirrorPad(Expr data, Array<Array<PrimExpr>> pad_width, String mode) {
+ auto attrs = make_object<MirrorPadAttrs>();
+ attrs->mode = mode;
+ attrs->pad_width = std::move(pad_width);
+ static const Op& op = Op::Get("nn.mirror_pad");
+ return Call(op, {data}, Attrs(attrs), {});
+}
+
+TVM_REGISTER_GLOBAL("relax.op.nn._make.mirror_pad").set_body_typed(MakeMirrorPad);
+
+TVM_REGISTER_OP("nn.mirror_pad")
+ .describe(R"code(MirrorPad for n-D tensor.
+
+)code" TVM_ADD_FILELINE)
+ .set_attrs_type<MirrorPadAttrs>()
+ .set_num_inputs(1)
+ .add_argument("data", "Tensor", "The input tensor.")
+ .set_support_level(2);
+ // .add_type_rel("MirrorPad", MirrorPadRel)
+ // .set_attr<TOpPattern>("TOpPattern", kInjective);
+
+} // namespace relax
+} // namespace tvm
diff --git a/src/relax/op/op_common.cc b/src/relax/op/op_common.cc
index 7428fd66fc..fa550f415d 100644
--- a/src/relax/op/op_common.cc
+++ b/src/relax/op/op_common.cc
@@ -29,7 +29,7 @@ Array<TensorStructInfo> GetInputTensorStructInfo(const Call& call, const BlockBu
int n_input = op->arguments.size();
if (static_cast<int>(call->args.size()) != n_input) {
ctx->ReportFatal(Diagnostic::Error(call)
- << op << " op should have " << n_input << " arguments");
+ << op << " op should have " << n_input << " arguments" << " but it got " << call->args.size());
}
Array<TensorStructInfo> input_tensor_sinfo;
input_tensor_sinfo.reserve(n_input);
diff --git a/src/tir/op/op.cc b/src/tir/op/op.cc
index 4439a9c3d7..4b3a0f5a7a 100644
--- a/src/tir/op/op.cc
+++ b/src/tir/op/op.cc
@@ -937,7 +937,7 @@ TVM_REGISTER_GLOBAL("node._const").set_body([](TVMArgs args, TVMRetValue* ret) {
} else if (args[0].type_code() == kDLFloat) {
*ret = tir::make_const(args[1], args[0].operator double(), args[2]);
} else {
- LOG(FATAL) << "only accept int or float"; // FIXME
+ LOG(FATAL) << "Constant must be int or float but got " << tvm::runtime::ArgTypeCode2Str(args[0].type_code()); // FIXME
}
});
[tvm] 04/08: data dependent strided slice
Posted by tk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
tkonolige pushed a commit to branch tkonolige/relax_pad_etc_new
in repository https://gitbox.apache.org/repos/asf/tvm.git
commit cb458f833253b319122e9618e13e58c109f8b4e2
Author: Tristan Konolige <tk...@octoml.ai>
AuthorDate: Mon May 15 18:00:50 2023 +0000
data dependent strided slice
---
python/tvm/relax/frontend/torch/fx_translator.py | 29 ++++++++++++++++-----
src/relax/op/tensor/index.cc | 32 ------------------------
2 files changed, 23 insertions(+), 38 deletions(-)
diff --git a/python/tvm/relax/frontend/torch/fx_translator.py b/python/tvm/relax/frontend/torch/fx_translator.py
index 2af651bb97..bdf2c3375f 100644
--- a/python/tvm/relax/frontend/torch/fx_translator.py
+++ b/python/tvm/relax/frontend/torch/fx_translator.py
@@ -18,7 +18,7 @@
# pylint: disable=invalid-name, inconsistent-return-statements, unidiomatic-typecheck
# pylint: disable=import-outside-toplevel
"""PyTorch FX frontend of Relax."""
-from typing import Callable, Dict, List, Optional, Tuple, Union
+from typing import Callable, Dict, List, Optional, Tuple, Union, Sequence
from functools import reduce
import tvm
@@ -123,6 +123,17 @@ def _convert_data_type(input_type, default_dtype=None):
raise NotImplementedError("input_type {} is not handled yet".format(input_type))
return "float32" # Never reached
+def _constify_array(ary: Sequence[Union[int, tvm.tir.IntImm, relax.Var]]) -> relax.Expr:
+ const = []
+ for i in ary:
+ if isinstance(i, int):
+ const.append(relax.const(tvm.nd.array([i])))
+ elif isinstance(i, tvm.tir.IntImm):
+ const.append(relax.const(tvm.nd.array([i.value])))
+ else:
+ const.append(i)
+ return relax.op.concat(const)
+
class TorchFXImporter:
"""An importer from PyTorch FX to Relax."""
@@ -1141,6 +1152,11 @@ class TorchFXImporter:
assert isinstance(shape, relax.ShapeExpr)
size = tuple(int(shape[i].value * scale_factor) for i in range(2, len(shape)))
+ from torch import fx
+ if any([isinstance(s, fx.node.Node) for s in size]):
+ size = relax.op.concat([self.env[s] for s in size])
+ # import IPython; IPython.embed()
+
if method.startswith("nearest"):
method = "nearest_neighbor"
elif method[0:2] == "bi":
@@ -1346,13 +1362,14 @@ class TorchFXImporter:
stride.append(1)
axes.append(i)
i += 1
- print([type(x) for x in axes], [type(x) for x in begin], [type(x) for x in end], [type(x) for x in stride])
- if any([isinstance(x, relax.Var) for x in begin]) or any([isinstance(x, relax.Var) for x in end]):
- print(end)
- sliced = self.block_builder.emit(relax.op.data_dependent_strided_slice(x, axes, begin, relax.const(np.array(end, dtype=int))))
+ # Handle case where slice is data dependent
+ if any([isinstance(y, relax.Var) for y in begin]) or any([isinstance(y, relax.Var) for y in end]) or any([isinstance(y, relax.Var) for y in stride]):
+ assert len(axes) == len(x.struct_info.shape), f"Dynamic strided slice must be provided with all the axes ({len(x.struct_info.shape)}) of the sliced tensor ({len(axes)} provided)"
+ sliced = self.block_builder.emit(relax.op.dynamic_strided_slice(x, _constify_array(begin), _constify_array(end), _constify_array(stride)))
+ sliced_shape = list(self.shape_of(x))
else:
sliced = self.block_builder.emit(relax.op.strided_slice(x, axes, begin, end, stride))
- sliced_shape = list(self.shape_of(sliced))
+ sliced_shape = list(self.shape_of(sliced))
for i in expand_dim:
sliced_shape.insert(i, 1)
return self.block_builder.emit(relax.op.reshape(sliced, sliced_shape))
diff --git a/src/relax/op/tensor/index.cc b/src/relax/op/tensor/index.cc
index 6510967992..d3bb34d21a 100644
--- a/src/relax/op/tensor/index.cc
+++ b/src/relax/op/tensor/index.cc
@@ -239,7 +239,6 @@ TVM_REGISTER_OP("relax.strided_slice")
.set_attr<FRelaxInferLayout>("FRelaxInferLayout", InferLayoutStridedSlice)
.set_attr<TMixedPrecisionPolicy>("TMixedPrecisionPolicy", MixedPrecisionPolicyKind::kFollow);
-<<<<<<< HEAD
/* relax.dynamic_strided_slice */
Expr dynamic_strided_slice(Expr x, //
Expr begin, //
@@ -247,37 +246,6 @@ Expr dynamic_strided_slice(Expr x, //
Expr strides) {
static const Op& op = Op::Get("relax.dynamic_strided_slice");
return Call(op, {std::move(x), std::move(begin), std::move(end), std::move(strides)}, {});
-||||||| parent of f322af441 (trying data dependent dynamic slice)
-/* relax.data_dependent_strided_slice */
-// TODO: support dynamic number of axes
-TVM_REGISTER_NODE_TYPE(DataDependentStridedSliceAttrs);
-
-Expr data_dependent_strided_slice(Expr x, //
- Array<Integer> axes, //
- Expr begin, //
- Expr end) {
- int n_axis = axes.size();
-
- ObjectPtr<DataDependentStridedSliceAttrs> attrs = make_object<DataDependentStridedSliceAttrs>();
- attrs->axes = std::move(axes);
-
- static const Op& op = Op::Get("relax.data_dependent_strided_slice");
- return Call(op, {std::move(x), std::move(begin), std::move(end)}, Attrs(attrs), {});
-=======
-/* relax.data_dependent_strided_slice */
-// TODO: support dynamic number of axes
-TVM_REGISTER_NODE_TYPE(DataDependentStridedSliceAttrs);
-
-Expr data_dependent_strided_slice(Expr x, //
- Array<Integer> axes, //
- Expr begin, //
- Expr end) {
- ObjectPtr<DataDependentStridedSliceAttrs> attrs = make_object<DataDependentStridedSliceAttrs>();
- attrs->axes = std::move(axes);
-
- static const Op& op = Op::Get("relax.data_dependent_strided_slice");
- return Call(op, {std::move(x), std::move(begin), std::move(end)}, Attrs(attrs), {});
->>>>>>> f322af441 (trying data dependent dynamic slice)
}
TVM_REGISTER_GLOBAL("relax.op.dynamic_strided_slice").set_body_typed(dynamic_strided_slice);