Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Relay][TF] Make StridedSlice support dynamic input and constant attrs #6024

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions python/tvm/relay/frontend/tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1458,6 +1458,15 @@ def _impl(inputs, attr, params, mod):

return ret

def _dyn():
for d in data_shape:
if not isinstance(d, int):
return True
return False

if _dyn():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to special hand this in tf frontend and skip mask transformation?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because mask transformation needs a concrete shape which doesn't work for dynamic shape input. I think there is more to do to handle mask in dynamic case but I'm afraid it can't support all mask transformation without concrete shape.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use shape_of to get data shape. In this case all shape dim will be relay expression and transform mask should be able to handle them. Anyway I don't think we should silently skip it since the output can be wrong and cause latter type infer error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lixiaoquan Can you simply raise an error here and add a TODO? We can merge this PR so that backend changes can take effect.

return _op.strided_slice(inputs[0], begin, end, stride)

def _transform_mask(stride_dim, ellipsis_mask):
"""Handle mask inputs to create new begin, end, stride and output shape"""
m_begin = [0] * data_dim
Expand Down
13 changes: 12 additions & 1 deletion src/relay/op/tensor/transform.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2146,7 +2146,18 @@ Array<te::Tensor> StridedSliceCompute(const Attrs& attrs, const Array<te::Tensor
const Type& out_type) {
const StridedSliceAttrs* param = attrs.as<StridedSliceAttrs>();
CHECK(param != nullptr);
if (param->begin && param->end && param->strides) {

bool dyn = false;
for (auto& v : out_type.as<TensorTypeNode>()->shape) {
if (const tir::VarNode* var_node = v.as<tir::VarNode>()) {
if (var_node->name_hint == "any_dim") {
dyn = true;
break;
}
}
}

if (param->begin && param->end && param->strides && !dyn) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I printed output_shape in topi::strided_slice and it is (0, 0) for that modified test_any case, which causes an runtime error. Maybe we can fix this bug directly in topi::strided_slice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

topi::strided_slice requires static shape because it will get value from each dim. Should we change this requirement or just use DynamicStrideSlice?

diff --git a/topi/include/topi/transform.h b/topi/include/topi/transform.h
index b5fc02ae7..329a62ce7 100644
--- a/topi/include/topi/transform.h
+++ b/topi/include/topi/transform.h
@@ -610,6 +610,7 @@ inline Tensor strided_slice(const Tensor& x, const Array<Integer>& begin, const
   for (size_t i = 0; i < src_tensor_dim; ++i) {
     int64_t begin_range = stride_vec[i] < 0 ? -1 : 0;
     int64_t dim_i = GetConstInt(x->shape[i]);
+    LOG(INFO) << dim_i; // it is -1 for modified case
     int64_t end_range = stride_vec[i] < 0 ? dim_i - 1 : dim_i;
     // transform negative indices to positive value, clips on the correct range
     auto index_canonicalization = [dim_i, begin_range, end_range](int64_t index) {
@@ -635,6 +636,8 @@ inline Tensor strided_slice(const Tensor& x, const Array<Integer>& begin, const
     out_shape.push_back(slice_size);
   }
 
+//  LOG(INFO) << out_shape;
+
   return compute(
       out_shape,
       [&](const Array<Var>& indices) {

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I think it would be more complicated to fix topi. Probably we can use dynamic stridedslice compute.

Array<Integer> begin, end, strides;
begin = param->begin.value();
end = param->end.value();
Expand Down
23 changes: 18 additions & 5 deletions tests/python/frontend/tensorflow/test_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def run_tf_graph(sess, input_data, input_node, output_node):

def compare_tf_with_tvm(in_data, in_name, out_name, init_global_variables=False,
no_gpu=False, opt_level=3, mode='graph_runtime',
cuda_layout="NCHW"):
cuda_layout="NCHW", ignore_in_shape=False):
"""Generic function to generate and compare tensorflow and TVM output"""
def name_without_num(name):
return name.split(':')[0] if ":" in name else name
Expand Down Expand Up @@ -208,7 +208,7 @@ def name_without_num(name):
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node,
target=device, out_names=out_name,
num_output=len(out_name), opt_level=opt_level, mode=mode,
cuda_layout=cuda_layout)
cuda_layout=cuda_layout, ignore_in_shape=ignore_in_shape)
# since the names from tensorflow and relay runs are not exactly same,
# first len(tf_output) will be compared
for i in range(len(tf_output)):
Expand Down Expand Up @@ -1354,19 +1354,30 @@ def test_forward_batch_matmul():

def _test_stridedslice(ip_shape, begin, end, stride, dtype,
begin_mask=0, end_mask=0, new_axis_mask=0,
shrink_axis_mask=0, ellipsis_mask=0):
shrink_axis_mask=0, ellipsis_mask=0, dynamic_input=False):
""" One iteration of a Stridedslice """

var_shape = ip_shape
if dynamic_input:
# Generate a dynamic shape
assert isinstance(var_shape, tuple)
var_shape = list(var_shape)
var_shape[0] = None

tf.reset_default_graph()
with tf.Graph().as_default():
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
in_data = tf.placeholder(dtype, var_shape, name="in_data")
tf.strided_slice(in_data, begin, end, stride, begin_mask=begin_mask,
end_mask=end_mask, new_axis_mask=new_axis_mask,
shrink_axis_mask=shrink_axis_mask,
ellipsis_mask=ellipsis_mask, name="strided_slice")
np_data = np.random.uniform(size=ip_shape).astype(dtype)

compare_tf_with_tvm(np_data, 'in_data:0', 'strided_slice:0')
if dynamic_input:
compare_tf_with_tvm(np_data, 'in_data:0', 'strided_slice:0', mode="vm",
ignore_in_shape=True)
else:
compare_tf_with_tvm(np_data, 'in_data:0', 'strided_slice:0')


def test_forward_stridedslice():
Expand Down Expand Up @@ -1421,6 +1432,8 @@ def test_forward_stridedslice():
_test_stridedslice((3, 4, 5, 4, 5, 6), [1, 2, 0, -3], [4, 5, 3, 3], [2, 2, 1, 1],
'float32', shrink_axis_mask=8, new_axis_mask=1, ellipsis_mask=2,
begin_mask=5, end_mask=8)
_test_stridedslice((2, 1), [0, 0], [1, 1], [1, 1], 'float32', dynamic_input=True)


#######################################################################
# FloorDiv, RealDiv
Expand Down
1 change: 0 additions & 1 deletion tests/python/relay/test_any.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,6 @@ def verify_any_strided_slice(data_shape, begin_shape, end_shape, strides_shape,
mod = tvm.IRModule()
data = relay.var('data', shape=data_shape, dtype='float32')
if const_attrs:
data = relay.var('data', shape=data_np_shape, dtype='float32')
begin = relay.const(np_begin)
end = relay.const(np_end)
strides = relay.const(np_strides)
Expand Down