Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions tests/python/frontend/nnvm_to_relay/test_alter_conv2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# 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.
"""Test alter conv2d layout pass"""
import tvm
import nnvm

from tvm import relay
from tvm import autotvm
from tvm.relay.ir_pass import infer_type, alpha_equal


def test_alter_layout_conv2d():
"""Additional layout transformations should occour on the graph.
"""

def convnet():
"""Alternating layout of simple convnet (from image super-resolution).
"""
bias1 = relay.var('bias1', shape=(64,))
bias2 = relay.var('bias2', shape=(64,))
bias3 = relay.var('bias3', shape=(64,))
bias4 = relay.var('bias4', shape=(64,))
weight1 = relay.var('weight1', shape=(64, 1, 5, 5))
weight2 = relay.var('weight2', shape=(64, 64, 3, 3))
weight3 = relay.var('weight3', shape=(64, 64, 3, 3))
weight4 = relay.var('weight4', shape=(64, 64, 3, 3))
data = relay.var("x", shape=(1, 1, 224, 224))
n00 = relay.nn.conv2d(data, weight1, padding=[2, 2], kernel_size=[5, 5])
n01 = relay.expand_dims(bias1, axis=1, num_newaxis=2)
n02 = relay.add(n00, n01)
n03 = relay.nn.relu(n02)
n04 = relay.nn.conv2d(n03, weight2, padding=[1, 1], kernel_size=[3, 3])
n05 = relay.expand_dims(bias2, axis=1, num_newaxis=2)
n06 = relay.add(n04, n05)
n07 = relay.nn.relu(n06)
n08 = relay.nn.conv2d(n07, weight3, padding=[1, 1], kernel_size=[3, 3])
n09 = relay.expand_dims(bias3, axis=1, num_newaxis=2)
n10 = relay.add(n08, n09)
n11 = relay.nn.relu(n10)
n12 = relay.nn.conv2d(n11, weight4, padding=[1, 1], kernel_size=[3, 3])
n13 = relay.expand_dims(bias4, axis=1, num_newaxis=2)
n14 = relay.add(n12, n13)
n15 = relay.reshape(n14, newshape=[1, 1, 3, 3, 224, 224])
n16 = relay.transpose(n15, axes=[0, 1, 4, 2, 5, 3])
net = relay.reshape(n16, newshape=[1, 1, 672, 672])
args = relay.ir_pass.free_vars(net)
return relay.Function(args, net)

# orig net
N = convnet()
N = infer_type(N)

# trigger a test
# for each known alter_conv2d
targets=['cuda',
'opencl -device=mali',
'opencl -device=intel_graphics',
'llvm -device=arm_cpu',
'llvm -device=core-avx-ii']

for tgt in targets:
with tvm.target.create(tgt) as target:
with relay.build_config(opt_level=-1, add_pass='AlterOpLayout'):
with autotvm.tophub.context(target):
O = relay.optimize(N, target, params=None)
O = relay.ir_pass.infer_type(O)

# graph should differ
assert not relay.ir_pass.alpha_equal(N, O)

if __name__ == "__main__":
np.random.seed(42)
test_alter_layout_conv2d()
4 changes: 4 additions & 0 deletions topi/python/topi/arm_cpu/conv2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,10 @@ def _alter_conv2d_layout_arm(attrs, inputs, tinfos, F):

new_attrs = {k: attrs[k] for k in attrs.keys()}

if F == tvm.relay.op:
# Derive channels for frontends (e.g ONNX) that miss "channel" field.
new_attrs["channels"] = inputs[1].checked_type.shape[attrs['kernel_layout'].index('O')]

dilation = attrs.get_int_tuple("dilation")
strides = attrs.get_int_tuple("strides")
padding = attrs.get_int_tuple("padding")
Expand Down
4 changes: 4 additions & 0 deletions topi/python/topi/cuda/conv2d_winograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,10 @@ def _alter_conv2d_layout(attrs, inputs, tinfos, F):
copy_inputs = [s for s in inputs]
new_attrs = {k: attrs[k] for k in attrs.keys()}

if F == tvm.relay.op:
# Derive channels for frontends (e.g ONNX) that miss "channel" field.
new_attrs["channels"] = inputs[1].checked_type.shape[attrs['kernel_layout'].index('O')]

strides = attrs.get_int_tuple("strides")
padding = attrs.get_int_tuple("padding")
dilation = attrs.get_int_tuple("dilation")
Expand Down
6 changes: 5 additions & 1 deletion topi/python/topi/intel_graphics/conv2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ def _alter_conv2d_layout(attrs, inputs, tinfos, F):
break

new_attrs = {k: attrs[k] for k in attrs.keys()}
new_attrs['kernel_layout'] = 'OIHW%do' % (oc_bn)
new_attrs["kernel_layout"] = 'OIHW%do' % (oc_bn)

if F == tvm.relay.op:
# Derive channels for frontends (e.g ONNX) that miss "channel" field.
new_attrs["channels"] = inputs[1].checked_type.shape[attrs['kernel_layout'].index('O')]

if F == sym:
out = F.contrib.conv2d_NCHWc(*copy_inputs, **new_attrs)
Expand Down
7 changes: 6 additions & 1 deletion topi/python/topi/x86/conv2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,11 +327,16 @@ def _alter_conv2d_layout(attrs, inputs, tinfo, F):

copy_inputs = [s for s in inputs]
new_attrs = {k : attrs[k] for k in attrs.keys()}

if F == tvm.relay.op:
Copy link
Contributor

@apivovarov apivovarov Apr 17, 2019

Choose a reason for hiding this comment

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

@merrymercy @cbalint13 This call fails if user uses nnvm.compiler.build. You need to import relay from tvm first. It fails only for nnvm.compiler.build, not for relay.build

Compile using nnvm...
Traceback (most recent call last):
  File "./compile.py", line 62, in <module>
    graph, lib, params = nnvm.compiler.build(sym, target, shape={"data": data_shape}, dtype=dtype, params=params, target_host=target_host)
  File "/usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/compiler/build_module.py", line 297, in build
    graph = optimize(graph, shape, dtype, layout)
  File "/usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/compiler/build_module.py", line 186, in optimize
    graph = graph.apply(["InferShape", "InferType", "AlterOpLayout"])
  File "/usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/graph.py", line 250, in apply
    check_call(_LIB.NNGraphApplyPasses(self.handle, npass, cpass, ctypes.byref(ghandle)))
  File "/usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/_base.py", line 91, in check_call
    raise NNVMError(py_str(_LIB.NNGetLastError()))
nnvm._base.NNVMError: AttributeError: module 'tvm' has no attribute 'relay'
Stack trace:
    if F == tvm.relay.op:
  File "/usr/local/lib/python3.6/dist-packages/topi-0.6.dev0-py3.6.egg/topi/x86/conv2d.py", line 331, in _alter_conv2d_layout
    return dispatch_dict[k](*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/tvm-0.6.dev0-py3.6-linux-x86_64.egg/tvm/target.py", line 372, in dispatch_func
  File "</usr/local/lib/python3.6/dist-packages/decorator.py:decorator-gen-18>", line 2, in conv2d_alter_layout
    return topi.nn.conv2d_alter_layout(attrs, inputs, tinfos, sym)
  File "/usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/top/nn.py", line 194, in alter_conv2d_layout
  File "tvm/_ffi/_cython/./function.pxi", line 55, in tvm._ffi._cy3.core.tvm_callback
Stack trace:
  [bt] (0) /usr/local/lib/python3.6/dist-packages/tvm-0.6.dev0-py3.6-linux-x86_64.egg/tvm/libtvm.so(+0x8e7f8b) [0x7f2ecdc9af8b]
  [bt] (1) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0x12ab65) [0x7f2ec8404b65]
  [bt] (2) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0xe5623) [0x7f2ec83bf623]
  [bt] (3) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0xe7c93) [0x7f2ec83c1c93]
  [bt] (4) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0xea0c9) [0x7f2ec83c40c9]
  [bt] (5) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0xc0800) [0x7f2ec839a800]
  [bt] (6) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(+0x85a11) [0x7f2ec835fa11]
  [bt] (7) /usr/local/lib/python3.6/dist-packages/nnvm-0.8.0-py3.6.egg/nnvm/libnnvm_compiler.so(NNGraphApplyPasses+0x320) [0x7f2ec833df00]
  [bt] (8) /usr/lib/x86_64-linux-gnu/libffi.so.6(ffi_call_unix64+0x4c) [0x7f2eee480dae]

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@apivovarov ,

  • Could make it in a new PR ?

Copy link
Contributor

Choose a reason for hiding this comment

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

If we had nnvm compilation tests then your PR would not pass CI tests and you needed to fix your code.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@apivovarov ,

Agree.

  • Will add as a new PR today, with testcase using nnvm symbols instead of relay.op
  • I'll keep you on Cc

Copy link
Contributor

Choose a reason for hiding this comment

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

@cbalint13 I'm not sure we want to import relay if user decided to use nnvm.compiler.build.
Can we use string comparison here? e.g.

if F.__name__ == 'tvm.relay.op':

Copy link
Contributor

Choose a reason for hiding this comment

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

continue discussion in
#3044

# Derive channels for frontends (e.g ONNX) that miss "channel" field.
new_attrs["channels"] = inputs[1].checked_type.shape[attrs['kernel_layout'].index('O')]

data, kernel = tinfo[0], tinfo[1]
batch_size, in_channel, height, width = get_const_tuple(data.shape)

groups = attrs.get_int("groups")
out_channel = attrs.get_int("channels") if F == sym else attrs.get_int("channels").value
out_channel = attrs.get_int("channels") if F == sym else new_attrs["channels"]
padding = attrs.get_int_tuple("padding")
strides = attrs.get_int_tuple("strides")
dilation = attrs.get_int_tuple("dilation")
Expand Down