Skip to content

Commit

Permalink
[Relay] add ShapeFunc for one_hot op (apache#7490)
Browse files Browse the repository at this point in the history
* [Relay] add ShapeFunc for one_hot op

* fix pylint

* add test for shapefunc of one_hot op
  • Loading branch information
monklof authored and Trevor Morris committed May 6, 2021
1 parent 6dd6cdc commit 14d6c17
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion 3rdparty/vta-hw
25 changes: 25 additions & 0 deletions python/tvm/relay/op/_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,31 @@ def strided_slice_shape_func(attrs, inputs, _):
]


@script
def _one_hot_shape_func(indices_shape, depth, axis):
in_ndim = indices_shape.shape[0]
out_ndim = in_ndim + 1
true_axis = in_ndim if axis == -1 else axis
indices_i = 0
out = output_tensor((out_ndim,), "int64")
for i in range(out_ndim):
if i == true_axis:
out[i] = int64(depth)
else:
out[i] = int64(indices_shape[indices_i])
indices_i += 1
return out


@_reg.register_shape_func("one_hot", False)
def one_hot_shape_func(attrs, inputs, _):
"""
Shape func for one_hot
"""
shape_func = [_one_hot_shape_func(inputs[0], convert(attrs.depth), convert(attrs.axis))]
return shape_func


@script
def _concatenate_shape_func(inputs, axis):
ndim = inputs[0].shape[0]
Expand Down
22 changes: 22 additions & 0 deletions tests/python/relay/test_any.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,28 @@ def test_any_reshape():
verify_any_reshape(any_dims(3), (-4, 2, -1, -2), (6, 3, 4), (2, 3, 3, 4))


def verify_any_one_hot(indices_shape, indices_np_shape, depth, on_value, off_value, axis, dtype):
indices = relay.var("indices", shape=indices_shape, dtype="int32")
on_value_const = relay.const(on_value, dtype)
off_value_const = relay.const(off_value, dtype)
y = relay.one_hot(indices, on_value_const, off_value_const, depth, axis=axis, dtype=dtype)
params = [indices]
mod = tvm.IRModule()
mod["main"] = relay.Function(params, y)

indices_npy = np.random.randint(0, depth, size=indices_np_shape).astype("int32")
out_npy = tvm.topi.testing.one_hot(indices_npy, on_value, off_value, depth, axis, dtype)
args = [indices_npy]
check_result(args, mod, out_npy)


@tvm.testing.uses_gpu
def test_any_one_hot():
verify_any_one_hot(any_dims(1), (3,), 3, 1, 0, -1, "int32")
verify_any_one_hot(any_dims(2), (2, 2), 5, 0.5, -0.5, 1, "float32")
verify_any_one_hot(any_dims(4), (3, 2, 4, 5), 6, 1.0, 0.0, 0, "float32")


def verify_any_argwhere(x_shape, x_np_shape, dtype="bool"):
x = relay.var("x", shape=x_shape, dtype=dtype)
y = relay.argwhere(x)
Expand Down

0 comments on commit 14d6c17

Please sign in to comment.