[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-24 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r383583660
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1026 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+# pylint: disable=import-outside-toplevel, simplifiable-if-expression, 
unnecessary-comprehension
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+from tvm.ir import module as _module
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-24 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r383575129
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1026 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+# pylint: disable=import-outside-toplevel, simplifiable-if-expression, 
unnecessary-comprehension
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+from tvm.ir import module as _module
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-24 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r383572402
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1026 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+# pylint: disable=import-outside-toplevel, simplifiable-if-expression, 
unnecessary-comprehension
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+from tvm.ir import module as _module
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-17 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r380334499
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1026 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+# pylint: disable=import-outside-toplevel, simplifiable-if-expression, 
unnecessary-comprehension
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+from tvm.ir import module as _module
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-12 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r378438728
 
 

 ##
 File path: tests/python/frontend/pytorch/test_forward.py
 ##
 @@ -0,0 +1,766 @@
+# 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.
+# pylint: disable=import-self, invalid-name, unused-argument
+"""Unit tests for various models and operators"""
+from time import time
+import os
+import sys
+from tempfile import TemporaryDirectory
+from scipy.stats import t as tdistr
+import numpy as np
+import torch
+from torch.nn import Module
+import tvm
+import torchvision
+
+from tvm import relay
+from tvm.contrib import graph_runtime
+from tvm.relay.testing.config import ctx_list
+
+sys.setrecursionlimit(1)
+
+def _vectorize(ten):
+return ten.reshape(-1)
+
+def atol(tru, est):
+def _atol_elt(tru, est):
+return abs(tru - est)
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_atol_elt(x, y) for x, y in zip(tru, est)])
+
+def rtol(tru, est):
+def _rtol_elt(tru, est):
+return abs(tru - est) / min(abs(tru), abs(est))
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_rtol_elt(x, y) for x, y in zip(tru, est)])
+
+def assert_shapes_match(tru, est):
+if tru.shape != est.shape:
+msg = "Output shapes {} and {} don't match"
+raise AssertionError(msg.format(tru.shape, est.shape))
+
+def load_torchvision(model_name):
+"""Given a model name, returns a Torchvision model in eval mode as well
+as an example input."""
+with torch.no_grad():
+if model_name.startswith("inception"):
+height = width = 299
+mean = [0.5, 0.5, 0.5]
+std = [0.5, 0.5, 0.5]
+else:
+height = width = 224
+mean = [0.485, 0.456, 0.406]
+std = [0.229, 0.224, 0.225]
+input_shape = [1, 3, height, width]
+input_data = torch.randn(input_shape).float()
+for channel in range(3):
+input_data[:, channel] -= mean[channel]
+input_data[:, channel] /= std[channel]
+model = getattr(torchvision.models, model_name)(pretrained=True)
+model = model.float().eval()
+return model, input_data
+
+def load_pretrainedmodels(model_name):
+"""Given a model name, returns a pretrainedmodels.pytorch model in eval
+mode as well as an example input."""
+import pretrainedmodels # 
https://github.com/Cadene/pretrained-models.pytorch
+model = getattr(pretrainedmodels, model_name)().float().eval()
+input_shape = [1, *model.input_size]
+input_data = torch.rand(input_shape).float() * 256
+for channel in range(3):
+input_data[:, channel] -= model.mean[channel]
+input_data[:, channel] /= model.std[channel]
+return model, input_data
+
+def load_model(model_name):
+"""Given a model name, returns a model as well as an example input."""
+if hasattr(torchvision.models, model_name):
+return load_torchvision(model_name)
+try:
+if hasattr(pretrainedmodels, model_name):
+return load_pretrainedmodels(model_name)
+except ModuleNotFoundError:
+raise ModuleNotFoundError("Please install pretrainedmodels.pytorch")
+raise RuntimeError("Model not supported")
+
+
+def confidence_interval(mean, stdev, count, alpha=.01):
+"""Returns the lower and upper bounds of the confidence interval of a 
random
+variable. Confidence is 1 - alpha (default confidence is 99%)."""
+stdval = tdistr.ppf(1 - alpha / 2, count - 1)
+lower, upper = mean + np.array([-1, 1]) * stdval * stdev / np.sqrt(count)
+return lower, upper
+
+def measure_latency(model, input_shapes, output_shapes, thresh, dryruns=40):
+"""Compute the latency of the given model"""
+latencies = []
+count = 0
+while True:
+if isinstance(model, torch.nn.Module):
+input_data = [torch.rand(shape).float() for shape in input_shapes]
+if torch.cuda.is_available():
+input_data = list(map(lambda x: x.cuda(), input_data))
+model = model.cuda()
+t_start = time()
+with 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-07 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376657697
 
 

 ##
 File path: tests/python/frontend/pytorch/test_forward.py
 ##
 @@ -0,0 +1,767 @@
+# 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.
+# pylint: disable=import-self, invalid-name, unused-argument
+"""Unit tests for various models and operators"""
+from time import time
+import os
+import sys
+from tempfile import TemporaryDirectory
+from scipy.stats import t as tdistr
+import numpy as np
+import torch
+from torch.nn import Module
+import tvm
+import torchvision
+
+from tvm import relay
+from tvm.contrib import graph_runtime
+from tvm.relay.testing.config import ctx_list
+
+sys.setrecursionlimit(1)
+
+def _vectorize(ten):
+return ten.reshape(-1)
+
+def atol(tru, est):
+def _atol_elt(tru, est):
+return abs(tru - est)
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_atol_elt(x, y) for x, y in zip(tru, est)])
+
+def rtol(tru, est):
+def _rtol_elt(tru, est):
+return abs(tru - est) / min(abs(tru), abs(est))
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_rtol_elt(x, y) for x, y in zip(tru, est)])
+
+def assert_shapes_match(tru, est):
+if tru.shape != est.shape:
+msg = "Output shapes {} and {} don't match"
+raise AssertionError(msg.format(tru.shape, est.shape))
+
+def load_torchvision(model_name):
+"""Given a model name, returns a Torchvision model in eval mode as well
+as an example input."""
+with torch.no_grad():
+if model_name.startswith("inception"):
+height = width = 299
+mean = [0.5, 0.5, 0.5]
+std = [0.5, 0.5, 0.5]
+else:
+height = width = 224
+mean = [0.485, 0.456, 0.406]
+std = [0.229, 0.224, 0.225]
+input_shape = [1, 3, height, width]
+input_data = torch.randn(input_shape).float()
+for channel in range(3):
+input_data[:, channel] -= mean[channel]
+input_data[:, channel] /= std[channel]
+model = getattr(torchvision.models, model_name)(pretrained=True)
+model = model.float().eval()
+return model, input_data
+
+def load_pretrainedmodels(model_name):
+"""Given a model name, returns a pretrainedmodels.pytorch model in eval
+mode as well as an example input."""
+import pretrainedmodels # 
https://github.com/Cadene/pretrained-models.pytorch
+model = getattr(pretrainedmodels, model_name)().float().eval()
+input_shape = [1, *model.input_size]
+input_data = torch.rand(input_shape).float() * 256
+for channel in range(3):
+input_data[:, channel] -= model.mean[channel]
+input_data[:, channel] /= model.std[channel]
+return model, input_data
+
+def load_model(model_name):
+"""Given a model name, returns a model as well as an example input."""
+if hasattr(torchvision.models, model_name):
+return load_torchvision(model_name)
+try:
+if hasattr(pretrainedmodels, model_name):
+return load_pretrainedmodels(model_name)
+except ModuleNotFoundError:
+raise ModuleNotFoundError("Please install pretrainedmodels.pytorch")
+raise RuntimeError("Model not supported")
+
+
+def confidence_interval(mean, stdev, count, alpha=.01):
+"""Returns the lower and upper bounds of the confidence interval of a 
random
+variable. Confidence is 1 - alpha (default confidence is 99%)."""
+stdval = tdistr.ppf(1 - alpha / 2, count - 1)
+lower, upper = mean + np.array([-1, 1]) * stdval * stdev / np.sqrt(count)
+return lower, upper
+
+def measure_latency(model, input_shapes, output_shapes, thresh, dryruns=40):
+"""Compute the latency of the given model"""
+latencies = []
+count = 0
+while True:
+if isinstance(model, torch.nn.Module):
+input_data = [torch.rand(shape).float() for shape in input_shapes]
+if torch.cuda.is_available():
+input_data = list(map(lambda x: x.cuda(), input_data))
+model = model.cuda()
+t_start = time()
+with 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376135176
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1045 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376135103
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1045 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in ones op" % (type(data))
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+data = inputs[0]
+
+import torch
+if isinstance(data, _expr.Expr):
+shape = _infer_shape(data)
+elif isinstance(data, list):
+shape = data
+elif isinstance(data, (torch.Tensor, np.ndarray)):
+shape = data.shape
+else:
+assert "data type {} could not be parsed in zeros op" % 
(type(data))
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376030507
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376018652
 
 

 ##
 File path: tests/python/frontend/pytorch/test_forward.py
 ##
 @@ -0,0 +1,792 @@
+# 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.
+# pylint: disable=import-self, invalid-name, unused-argument
+"""Unit tests for various models and operators"""
+from time import time
+import os
+import sys
+from tempfile import TemporaryDirectory
+from scipy.stats import t as tdistr
+import numpy as np
+import torch
+from torch.nn import Module
+import tvm
+import torchvision
+
+from tvm import relay
+from tvm.contrib import graph_runtime
+from tvm.relay.testing.config import ctx_list
+
+sys.setrecursionlimit(1)
+
+def _vectorize(ten):
+return ten.reshape(-1)
+
+def atol(tru, est):
+def _atol_elt(tru, est):
+return abs(tru - est)
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_atol_elt(x, y) for x, y in zip(tru, est)])
+
+def rtol(tru, est):
+def _rtol_elt(tru, est):
+return abs(tru - est) / min(abs(tru), abs(est))
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_rtol_elt(x, y) for x, y in zip(tru, est)])
+
+def assert_shapes_match(tru, est):
+if tru.shape != est.shape:
+msg = "Output shapes {} and {} don't match"
+raise AssertionError(msg.format(tru.shape, est.shape))
+
+def load_torchvision(model_name):
+"""Given a model name, returns a Torchvision model in eval mode as well
+as an example input."""
+with torch.no_grad():
+if model_name.startswith("inception"):
+height = width = 299
+mean = [0.5, 0.5, 0.5]
+std = [0.5, 0.5, 0.5]
+else:
+height = width = 224
+mean = [0.485, 0.456, 0.406]
+std = [0.229, 0.224, 0.225]
+input_shape = [1, 3, height, width]
+input_data = torch.randn(input_shape).float()
+for channel in range(3):
+input_data[:, channel] -= mean[channel]
+input_data[:, channel] /= std[channel]
+model = getattr(torchvision.models, model_name)(pretrained=True)
+model = model.float().eval()
+return model, input_data
+
+def load_pretrainedmodels(model_name):
+"""Given a model name, returns a pretrainedmodels.pytorch model in eval
+mode as well as an example input."""
+import pretrainedmodels # 
https://github.com/Cadene/pretrained-models.pytorch
+model = getattr(pretrainedmodels, model_name)().float().eval()
+input_shape = [1, *model.input_size]
+input_data = torch.rand(input_shape).float() * 256
+for channel in range(3):
+input_data[:, channel] -= model.mean[channel]
+input_data[:, channel] /= model.std[channel]
+return model, input_data
+
+def load_model(model_name):
+"""Given a model name, returns a model as well as an example input."""
+if hasattr(torchvision.models, model_name):
+return load_torchvision(model_name)
+try:
+if hasattr(pretrainedmodels, model_name):
+return load_pretrainedmodels(model_name)
+except ModuleNotFoundError:
+raise ModuleNotFoundError("Please install pretrainedmodels.pytorch")
+raise RuntimeError("Model not supported")
+
+
+def confidence_interval(mean, stdev, count, alpha=.01):
+"""Returns the lower and upper bounds of the confidence interval of a 
random
+variable. Confidence is 1 - alpha (default confidence is 99%)."""
+stdval = tdistr.ppf(1 - alpha / 2, count - 1)
+lower, upper = mean + np.array([-1, 1]) * stdval * stdev / np.sqrt(count)
+return lower, upper
+
+def measure_latency(model, input_shapes, output_shapes, thresh, dryruns=40):
+"""Compute the latency of the given model"""
+latencies = []
+count = 0
+while True:
+if isinstance(model, torch.nn.Module):
+input_data = [torch.rand(shape).float() for shape in input_shapes]
+if torch.cuda.is_available():
+input_data = list(map(lambda x: x.cuda(), input_data))
+model = model.cuda()
+t_start = time()
+with 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376018125
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
 
 Review comment:
   I was thinking either torch.tensor or np.array or something similar. You are 
right in that we shouldn't just generically use shape attribute when unsure if 
it has it.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-06 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r376015202
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375563704
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375549738
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375549738
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375549738
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1023 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ["from_pytorch"]
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], _expr.Expr):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], _expr.Expr):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, _expr.Expr):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+if isinstance(data, _expr.Expr):
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = inferred_shape
+end = list(end)
+else:
+end = data.shape
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype="int32"), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Expr):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return _impl
+
+def _adaptive_max_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_max_pool2d(
+data,
+ 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375519693
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1093 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ['from_pytorch']
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = _infer_shape(data)
+end = list(end)
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype='int32'), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Var):
+shape = _infer_shape(inputs[0])
+elif isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem)):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Var):
+shape = _infer_shape(inputs[0])
+elif isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem)):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375513751
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1093 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ['from_pytorch']
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = _infer_shape(data)
+end = list(end)
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype='int32'), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Var):
+shape = _infer_shape(inputs[0])
+elif isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem)):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(1), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _zeros():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Var):
+shape = _infer_shape(inputs[0])
+elif isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem)):
+shape = _infer_shape(inputs[0])
+else:
+shape = inputs[0].shape
+
+return _op.full(_expr.const(0), shape, 
dtype=_convert_data_type(input_types[0]))
+return _impl
+
+def _relu():
+def _impl(inputs, input_types):
+data = inputs[0]
+return _op.nn.relu(data)
+return _impl
+
+def _adaptive_avg_2d():
+def _impl(inputs, input_types):
+data = inputs[0]
+output_size = _infer_shape(inputs[1])
+
+return _op.contrib.contrib.adaptive_avg_pool2d(
+data,
+output_size=output_size)
+return 

[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375513313
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1093 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ['from_pytorch']
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, (_expr.Call, _expr.TupleGetItem, _expr.Var)):
 
 Review comment:
   Previously was handling constants differently. Moved to just catching any 
expr now.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375513469
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1093 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ['from_pytorch']
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
 
 Review comment:
   Change to use existing inferred shape.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375513644
 
 

 ##
 File path: python/tvm/relay/frontend/pytorch.py
 ##
 @@ -0,0 +1,1093 @@
+# 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.
+# pylint: disable=import-self, too-many-lines, len-as-condition, 
no-else-return, unused-variable, too-many-nested-blocks
+# pylint: disable=consider-iterating-dictionary, invalid-name, 
unused-argument, unused-variable, broad-except
+"""PT: PyTorch frontend."""
+import numpy as np
+
+import tvm
+
+from .. import analysis as _analysis
+from .. import expr as _expr
+from .. import module as _module
+from .. import op as _op
+from .common import get_relay_op
+from .common import infer_shape as _infer_shape
+
+__all__ = ['from_pytorch']
+
+# operator implementation
+def _elemwise(name):
+def _impl(inputs, input_types):
+# TODO: Figure out a better way to get typing to work for tensor + 
scalar
+type0 = input_types[0]
+if isinstance(inputs[1], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type0 = input_types[1]
+
+type1 = input_types[1]
+if isinstance(inputs[0], (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+type1 = input_types[0]
+
+data0 = _convert_elemwise_input(inputs[0], type0)
+data1 = _convert_elemwise_input(inputs[1], type1)
+
+return get_relay_op(name)(data0, data1)
+return _impl
+
+def _unsqueeze():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+return _op.transform.expand_dims(data, int(axis), 1)
+return _impl
+
+def _concatenate():
+def _impl(inputs, input_types):
+data = inputs[0]
+axis = inputs[1]
+
+if isinstance(data, (_expr.Call, _expr.TupleGetItem, _expr.Var)):
+data = [data]
+
+return _op.tensor.concatenate(data, int(axis))
+return _impl
+
+def _slice():
+def _impl(inputs, input_types):
+data = inputs[0]
+strides = []
+
+inferred_shape = _infer_shape(data)
+end = []
+for infer in inferred_shape:
+end.append(int(infer))
+if isinstance(data, _expr.Var):
+end = _infer_shape(data)
+end = list(end)
+
+begin = [0]*len(end)
+dim = int(inputs[1])
+begin[dim] = int(inputs[2])
+
+if isinstance(inputs[3], str) and inputs[3].isdigit():
+end[dim] = min(end[dim], int(inputs[3]))
+else:
+end[dim] = inputs[3]
+
+strides.append(int(inputs[4]))
+return _op.transform.strided_slice(data, begin, end, strides)
+return _impl
+
+def _select():
+def _impl(inputs, input_types):
+data = inputs[0]
+dim = int(inputs[1])
+index = int(inputs[2])
+
+return _op.transform.take(data, _expr.const(index, dtype='int32'), 
axis=dim)
+return _impl
+
+def _ones():
+def _impl(inputs, input_types):
+if isinstance(inputs[0], _expr.Var):
 
 Review comment:
   Moved together.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-tvm] alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to Relay Parser

2020-02-05 Thread GitBox
alexwong commented on a change in pull request #4497: [Relay] Add a PyTorch to 
Relay Parser
URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r375512544
 
 

 ##
 File path: tests/python/frontend/pytorch/test_forward.py
 ##
 @@ -0,0 +1,851 @@
+# 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.
+# pylint: disable=import-self, invalid-name, unused-argument
+"""Unit tests for various models and operators"""
+from time import time
+import os
+import sys
+from tempfile import TemporaryDirectory
+from scipy.stats import t as tdistr
+import numpy as np
+import torch
+from torch.nn import Module
+import tvm
+import torchvision
+
+from tvm import relay
+from tvm.contrib import graph_runtime
+from tvm.relay.testing.config import ctx_list
+
+sys.setrecursionlimit(1)
+
+def _vectorize(ten):
+return ten.reshape(-1)
+
+def atol(tru, est):
+def _atol_elt(tru, est):
+return abs(tru - est)
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_atol_elt(x, y) for x, y in zip(tru, est)])
+
+def rtol(tru, est):
+def _rtol_elt(tru, est):
+return abs(tru - est) / min(abs(tru), abs(est))
+tru = _vectorize(tru)
+est = _vectorize(est)
+return max([_rtol_elt(x, y) for x, y in zip(tru, est)])
+
+def assert_shapes_match(tru, est):
+if tru.shape != est.shape:
+msg = "Output shapes {} and {} don't match"
+raise AssertionError(msg.format(tru.shape, est.shape))
+
+def load_torchvision(model_name):
+"""Given a model name, returns a Torchvision model in eval mode as well
+as an example input."""
+with torch.no_grad():
+if model_name.startswith('inception'):
+height = width = 299
+mean = [0.5, 0.5, 0.5]
+std = [0.5, 0.5, 0.5]
+else:
+height = width = 224
+mean = [0.485, 0.456, 0.406]
+std = [0.229, 0.224, 0.225]
+input_shape = [1, 3, height, width]
+input_data = torch.randn(input_shape).float()
+for channel in range(3):
+input_data[:, channel] -= mean[channel]
+input_data[:, channel] /= std[channel]
+model = getattr(torchvision.models, model_name)(pretrained=True)
+model = model.float().eval()
+return model, input_data
+
+def load_pretrainedmodels(model_name):
+"""Given a model name, returns a pretrainedmodels.pytorch model in eval
+mode as well as an example input."""
+import pretrainedmodels # 
https://github.com/Cadene/pretrained-models.pytorch
+model = getattr(pretrainedmodels, model_name)().float().eval()
+input_shape = [1, *model.input_size]
+input_data = torch.rand(input_shape).float() * 256
+for channel in range(3):
+input_data[:, channel] -= model.mean[channel]
+input_data[:, channel] /= model.std[channel]
+return model, input_data
+
+def load_model(model_name):
+"""Given a model name, returns a model as well as an example input."""
+if hasattr(torchvision.models, model_name):
+return load_torchvision(model_name)
+try:
+if hasattr(pretrainedmodels, model_name):
+return load_pretrainedmodels(model_name)
+except ModuleNotFoundError:
+raise ModuleNotFoundError('Please install pretrainedmodels.pytorch')
+raise RuntimeError('Model not supported')
+
+
+def confidence_interval(mean, stdev, count, alpha=.01):
+"""Returns the lower and upper bounds of the confidence interval of a 
random
+variable. Confidence is 1 - alpha (default confidence is 99%)."""
+stdval = tdistr.ppf(1 - alpha / 2, count - 1)
+lower, upper = mean + np.array([-1, 1]) * stdval * stdev / np.sqrt(count)
+return lower, upper
+
+def measure_latency(model, input_shapes, output_shapes, thresh, dryruns=40):
+"""Compute the latency of the given model"""
+latencies = []
+count = 0
+while True:
+if isinstance(model, torch.nn.Module):
+input_data = [torch.rand(shape).float() for shape in input_shapes]
+if torch.cuda.is_available():
+input_data = list(map(lambda x: x.cuda(), input_data))
+model = model.cuda()
+t_start = time()
+