Skip to content

Commit e406740

Browse files
committed
[FRONTEND][TENSORFLOW] Support Unstack and SplitV
1 parent 45f88e2 commit e406740

2 files changed

Lines changed: 108 additions & 60 deletions

File tree

nnvm/python/nnvm/frontend/tensorflow.py

Lines changed: 67 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -787,13 +787,55 @@ def _impl(inputs, attr, params):
787787
)(inputs, attr)
788788
return _impl
789789

790-
def _split():
790+
def _split(has_size_vector):
791+
# TF documentation https://www.tensorflow.org/api_docs/python/tf/split
791792
def _impl(inputs, attr, params):
792-
axis = params.pop(inputs[0].list_output_names()[0])
793-
return AttrCvt(
794-
op_name="split", ignores=['T'],
795-
transforms={'num_split': 'indices_or_sections'},
796-
extras={'axis': axis.asnumpy()[0]})(inputs[1], attr)
793+
try:
794+
# order and number of inputs are different:
795+
# if has_size_vector:
796+
# https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/split-v
797+
# else:
798+
# https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/split
799+
800+
# in addition, `axis` and `num_or_size_splits` can be tensors in TensorFlow,
801+
# we can only support constants
802+
if has_size_vector:
803+
input_node_index = 0
804+
input_axis_index = 2
805+
size_splits_input_name = inputs[1].list_output_names()[0]
806+
size_splits = params[size_splits_input_name].asnumpy()
807+
section_beginnings = np.cumsum(size_splits)[:-1]
808+
indices_or_sections = tuple(section_beginnings)
809+
else:
810+
input_node_index = 1
811+
input_axis_index = 0
812+
indices_or_sections = attr['num_split']
813+
input_node = inputs[input_node_index]
814+
axis_input_name = inputs[input_axis_index].list_output_names()[0]
815+
axis_input_value = params[axis_input_name].asnumpy()[0]
816+
except (IndexError, KeyError):
817+
raise TypeError( \
818+
"Unsupported argument for split: `axis` and `num_or_size_splits` " \
819+
"should be constants")
820+
return _sym.split(input_node,
821+
indices_or_sections=indices_or_sections,
822+
axis=axis_input_value)
823+
return _impl
824+
825+
def _unpack():
826+
def _impl(inputs, attr, params):
827+
input_node = inputs[0]
828+
axis = attr['axis']
829+
input_shape = attr['_input_shapes'][input_node][0]
830+
axis_length = input_shape[axis]
831+
if axis_length < 0:
832+
raise TypeError("Unstack with unknown axis length")
833+
splitted = _sym.split(input_node,
834+
indices_or_sections=axis_length,
835+
axis=axis,
836+
name=attr.get('_node_name', 'unstack'))
837+
838+
return _sym.Group([_sym.squeeze(split_item, axis=axis) for split_item in splitted])
797839
return _impl
798840

799841
# compatible operators that do NOT require any conversion.
@@ -863,7 +905,9 @@ def _impl(inputs, attr, params):
863905
'GreaterEqual' : _broadcast('greater_equal'),
864906
'Equal' : _broadcast('equal'),
865907
'NotEqual' : _broadcast('not_equal'),
866-
'Split' : _split(),
908+
'Split' : _split(False),
909+
'SplitV' : _split(True),
910+
'Unpack' : _unpack(),
867911
}
868912

869913
# _convert_map_rnn defines maps of rnn operator name to
@@ -1162,19 +1206,21 @@ def from_tensorflow(self, graph, layout="NHWC", shape=None, outputs=None):
11621206
# Fill shapes for all inputs in a list
11631207
inputs = []
11641208
for i in node.input:
1165-
#ToDo: Some of the tensorflow operators internaly maintain
1166-
#execution layers and its output name will the layer number along with
1167-
#graph node name.eg: Node name:- 'Model/RNN/cell_0/RnnCell', but the
1168-
#output name will be 'Model/RNN/cell_0/RnnCell:0'. In this case,
1169-
#the digit has to be ignored.
1209+
# Some TensorFlow operators internally maintain execution layers
1210+
# and their output name includes the layer number along with
1211+
# graph node name. E.g. the node name is 'Model/RNN/cell_0/RnnCell', but the
1212+
# output tensor name is 'Model/RNN/cell_0/RnnCell:0'. In this case,
1213+
# the number has to be ignored for single-output nodes.
1214+
# On the other hand, for multi-output nodes the number is the output index,
1215+
# and the lack of the number implies 0.
11701216
tensor_name = i.split(':')
11711217
node_name = tensor_name[0]
11721218
if node_name in self._nodes:
11731219
in_sym = self._nodes[node_name]
11741220
if len(in_sym.list_output_names()) > 1:
11751221
tensor_slot = int(tensor_name[1]) if len(tensor_name) > 1 else 0
11761222
in_sym = in_sym[tensor_slot]
1177-
input_shape = (self._output_shapes[node_name])[tensor_slot]
1223+
input_shape = self._output_shapes[node_name][tensor_slot]
11781224
else:
11791225
input_shape = self._output_shapes[node_name][0]
11801226
inputs.append(in_sym)
@@ -1207,15 +1253,21 @@ def from_tensorflow(self, graph, layout="NHWC", shape=None, outputs=None):
12071253
if outputs is None:
12081254
out.append(final_op)
12091255
else:
1210-
out = [self._nodes[out_name] for out_name in outputs]
1256+
for out_name in outputs:
1257+
if ":" in out_name:
1258+
out_name, out_num = out_name.split(":")
1259+
out_num = int(out_num)
1260+
out.append(self._nodes[out_name][out_num])
1261+
else:
1262+
out.append(self._nodes[out_name])
12111263

12121264
#Add the RNN outputs also with 'head' nodes of the nnvm graph
12131265
if self._num_rnn_layer:
12141266
out_rnn = _sym.concatenate(*self._out_rnn, axis=0)
12151267
out.append(out_rnn)
12161268

12171269
if isinstance(out, list):
1218-
out = _sym.Group(out)
1270+
out = _sym.Group(out) if len(out) > 1 else out[0]
12191271

12201272
return out, self._params
12211273

nnvm/tests/python/frontend/tensorflow/test_forward.py

Lines changed: 41 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,8 @@ def compare_tf_with_tvm(in_data, in_name, out_name, init_global_variables=False,
124124
if no_gpu and device == 'cuda':
125125
continue
126126

127-
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node, target=device)
127+
tvm_output = run_tvm_graph(final_graph_def, in_data, in_node,
128+
num_output=len(out_node), target=device, out_names=out_name)
128129
# since the names from tensorflow and nnvm runs are not exactly same,
129130
# first len(tf_output) will be compared
130131
for i in range(len(tf_output)):
@@ -506,14 +507,24 @@ def test_forward_gather():
506507
# Split
507508
# -----
508509

509-
def _test_split(in_shape, axis, num_split, dtype):
510+
def _test_split(in_shape, axis, num_or_size_splits, dtype):
511+
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
512+
510513
""" One iteration of a Split """
514+
tf.reset_default_graph()
515+
in_data = tf.placeholder(dtype, in_shape, name="in_data")
516+
num_split = len(num_or_size_splits) if isinstance(num_or_size_splits, list) else num_or_size_splits
517+
tf.split(in_data, num_or_size_splits, axis=axis)
511518

512-
with tf.Graph().as_default():
513-
in_data = tf.placeholder(dtype, in_shape, name="in_data")
514-
tf.split(in_data, num_split, axis)
515-
np_data = np.random.uniform(size=in_shape).astype(dtype)
516-
compare_tf_with_tvm(np_data, 'in_data:0', 'split:0')
519+
compare_tf_with_tvm([np_data], ['in_data:0'], [f'split:{n}' for n in range(num_split)])
520+
521+
# and now test together with concat
522+
tf.reset_default_graph()
523+
in_data = tf.placeholder(dtype, in_shape, name="in_data")
524+
splitted = tf.split(in_data, num_or_size_splits, axis=axis)
525+
tf.concat(splitted, axis)
526+
527+
compare_tf_with_tvm([np_data], 'in_data:0', 'concat:0')
517528

518529
def test_forward_split():
519530
'''test split layer'''
@@ -523,11 +534,11 @@ def test_forward_split():
523534
_test_split((6,), 0, 3, 'float32')
524535
# rank 2
525536
_test_split((6, 2), 0, 3, 'float32')
526-
_test_split((2, 6), 1, 3, 'float32')
537+
_test_split((2, 6), 1, 6, 'float32')
527538
# rank 3
528-
_test_split((6, 2, 4), 0, 3, 'float32')
539+
_test_split((6, 2, 4), 0, 2, 'int32')
529540
_test_split((2, 6, 4), 1, 3, 'float32')
530-
_test_split((2, 4, 6), 2, 3, 'float32')
541+
_test_split((2, 4, 6), 2, 1, 'float32')
531542
# rank 4
532543
_test_split((6, 1, 3, 5), 0, 3, 'float32')
533544
_test_split((1, 6, 3, 5), 1, 3, 'float32')
@@ -538,45 +549,30 @@ def test_forward_split():
538549
_test_split((1, 6, 3, 5), -3, 3, 'float32')
539550
_test_split((1, 3, 6, 5), -2, 3, 'float32')
540551
_test_split((1, 3, 5, 6), -1, 3, 'float32')
552+
# size_splits list
553+
_test_split((6,), 0, [1, 2, 3], 'int32')
554+
_test_split((3, 6, 4), -2, [1, 4, 1], 'float32')
541555

542556

543557
#######################################################################
544-
# Split followed by concat
545-
# ------------------------
558+
# Unstack
559+
# -------
546560

547-
def _test_split_concat(in_shape, axis, num_split, dtype):
548-
""" One iteration of a split_concat pair"""
561+
def _test_unstack(ip_shape, axis, dtype):
562+
tf.reset_default_graph()
563+
in_data = tf.placeholder(dtype, ip_shape, name="in_data")
564+
tf.unstack(in_data, axis=axis)
565+
np_data = np.random.uniform(-5, 5, size=ip_shape).astype(dtype)
549566

550-
with tf.Graph().as_default():
551-
in_data = tf.placeholder(dtype, in_shape, name="in_data")
552-
splitted = tf.split(in_data, num_split, axis)
553-
tf.concat(splitted, axis)
554-
np_data = np.random.uniform(size=in_shape).astype(dtype)
555-
compare_tf_with_tvm(np_data, 'in_data:0', 'concat:0')
556-
557-
def test_forward_split_concat():
558-
'''test split followed by concat layers'''
559-
# rank 1
560-
_test_split_concat((3,), 0, 1, 'float32')
561-
_test_split_concat((3,), 0, 3, 'float32')
562-
_test_split_concat((6,), 0, 3, 'float32')
563-
# rank 2
564-
_test_split_concat((6, 2), 0, 3, 'float32')
565-
_test_split_concat((2, 6), 1, 3, 'float32')
566-
# rank 3
567-
_test_split_concat((6, 2, 4), 0, 3, 'float32')
568-
_test_split_concat((2, 6, 4), 1, 3, 'float32')
569-
_test_split_concat((2, 4, 6), 2, 3, 'float32')
570-
# rank 4
571-
_test_split((6, 1, 3, 5), 0, 3, 'float32')
572-
_test_split((1, 6, 3, 5), 1, 3, 'float32')
573-
_test_split((1, 3, 6, 5), 2, 3, 'float32')
574-
_test_split((1, 3, 5, 6), 3, 3, 'float32')
575-
# split along negative axis
576-
_test_split((6, 1, 3, 5), -4, 3, 'float32')
577-
_test_split((1, 6, 3, 5), -3, 3, 'float32')
578-
_test_split((1, 3, 6, 5), -2, 3, 'float32')
579-
_test_split((1, 3, 5, 6), -1, 3, 'float32')
567+
compare_tf_with_tvm([np_data], ['in_data:0'], [f'unstack:{n}' for n in range(ip_shape[axis])])
568+
569+
def test_forward_unstack():
570+
'''test unstack layer'''
571+
_test_unstack((6,), 0, 'int32')
572+
_test_unstack((2,6), 1, 'float64')
573+
# negative axis
574+
_test_unstack((1,4), -1, 'int32')
575+
_test_unstack((3,6,4), -2, 'float32')
580576

581577

582578
#######################################################################
@@ -1139,7 +1135,7 @@ def test_forward_rel_ops():
11391135
test_forward_gather()
11401136
test_forward_stridedslice()
11411137
test_forward_split()
1142-
test_forward_split_concat()
1138+
test_forward_unstack()
11431139

11441140
# Activations
11451141
test_forward_sigmoid()

0 commit comments

Comments
 (0)