zhiics 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_r375442471
 
 

 ##########
 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 _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,
+            output_size=output_size)
+    return _impl
+
+def _maxpool_2d():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+
+        pool_size = _infer_shape(inputs[1])
+        strides = _infer_shape(inputs[2])
+        padding = _infer_shape(inputs[3])
+
+        ceil_mode = int(inputs[5])
+
+        return _op.nn.max_pool2d(data, pool_size, strides, padding, "NCHW", 
ceil_mode)
+    return _impl
+
+def _hardtanh():
+    def _impl(inputs, input_types):
+        a = inputs[0]
+        tanh_min = float(inputs[1])
+        tanh_max = float(inputs[2])
+        return _op.tensor.clip(a, tanh_min, tanh_max)
+    return _impl
+
+def _convolution():
+    def _impl(inputs, input_types):
+        # Use transpose or normal
+        use_transpose = False
+        if inputs[6] == '1':
+            use_transpose = True
+
+        use_bias = False
+        if isinstance(inputs[2], _expr.Var):
+            use_bias = True
+
+            data = inputs[0]
+            weight = inputs[1]
+            bias = inputs[2]
+
+            if isinstance(weight, (_expr.Call, _expr.Var, _expr.TupleGetItem)):
+                inferred_shape = _infer_shape(weight)
+                weight_shape = []
+                for infer in inferred_shape:
+                    weight_shape.append(infer)
+            else:
+                weight_shape = weight.shape
+            channels = weight_shape[0]
+
+            strides = inputs[3]
+            padding = inputs[4]
+            dilation = inputs[5]
+
+            kernel_size = weight_shape[2:]
+
+        else:
+            data = inputs[0]
+            weight = inputs[1]
+            bias = inputs[2]
+
+            if isinstance(weight, (_expr.Call, _expr.Var, _expr.TupleGetItem)):
+                inferred_shape = _infer_shape(weight)
+                weight_shape = []
+                for infer in inferred_shape:
+                    weight_shape.append(infer)
+            else:
+                weight_shape = weight.shape
+            channels = weight_shape[0]
+
+            strides = inputs[3]
+            padding = inputs[4]
+            dilation = inputs[5]
+
+            kernel_size = weight_shape[2:]
+
+        if isinstance(strides, _expr.Var):
+            strides = _infer_shape(strides)
+
+        if isinstance(padding, _expr.Var):
+            padding = _infer_shape(padding)
+
+        if isinstance(dilation, _expr.Var):
+            dilation = _infer_shape(dilation)
+
+        groups = int(inputs[8])
+
+        if use_transpose:
+            conv_out = _op.nn.conv2d_transpose(data,
+                                               weight,
+                                               strides=strides,
+                                               padding=padding,
+                                               dilation=dilation,
+                                               groups=groups,
+                                               channels=channels,
+                                               kernel_size=kernel_size,
+                                               data_layout="NCHW",
+                                               kernel_layout="OIHW",
+                                               out_layout="",
+                                               out_dtype="")
+        else:
+            conv_out = _op.nn.conv2d(data,
+                                     weight,
+                                     strides=strides,
+                                     padding=padding,
+                                     dilation=dilation,
+                                     groups=groups,
+                                     channels=channels,
+                                     kernel_size=kernel_size,
+                                     data_layout="NCHW",
+                                     kernel_layout="OIHW",
+                                     out_layout="",
+                                     out_dtype="")
+
+        if use_bias:
+            return _op.nn.bias_add(conv_out, bias)
+        else:
+            return conv_out
+    return _impl
+
+def _softmax():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+        axis = inputs[1]
+        if isinstance(axis, str):
+            axis = int(axis)
+
+        return _op.nn.softmax(data, axis=axis)
+    return _impl
+
+def _threshold():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+        return _op.nn.relu(data)
+    return _impl
+
+def _contiguous():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+        return _op.tensor.copy(data)
+    return _impl
+
+def _batch_norm():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+        data_type = input_types[0]
+
+        channels = _infer_shape(data)
+
+        if isinstance(inputs[1], _expr.Var) and isinstance(inputs[2], 
_expr.Var):
+            scale = center = True
+            weight = inputs[1]
+            beta = inputs[2]
+        else:
+            scale = center = False
+
+        if scale:
+            gamma = weight
+        else:
+            if data_type == 'double':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('float64'))
+            elif data_type == 'float':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('float32'))
+            elif data_type == 'half':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('float16'))
+            elif data_type == 'long':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('int64'))
+            elif data_type == 'int':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('int32'))
+            elif data_type == 'short':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('int16'))
+            elif data_type == 'char':
+                gamma = _expr.const(np.ones([int(channels[1])]).astype('int8'))
+            elif data_type == 'byte':
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('uint8'))
+            else:
+                gamma = 
_expr.const(np.ones([int(channels[1])]).astype('float32'))
+
+        if center:
+            beta = beta
+        else:
+            if data_type == 'double':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('float64'))
+            elif data_type == 'float':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('float32'))
+            elif data_type == 'half':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('float16'))
+            elif data_type == 'long':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('int64'))
+            elif data_type == 'int':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('int32'))
+            elif data_type == 'short':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('int16'))
+            elif data_type == 'char':
+                beta = _expr.const(np.zeros([int(channels[1])]).astype('int8'))
+            elif data_type == 'byte':
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('uint8'))
+            else:
+                beta = 
_expr.const(np.zeros([int(channels[1])]).astype('float32'))
+
+        moving_mean = inputs[3]
+        moving_var = inputs[4]
+        epsilon = float(inputs[7])
+
+        center = center
+        scale = scale
+
+        return _op.nn.batch_norm(data,
+                                 gamma,
+                                 beta,
+                                 moving_mean,
+                                 moving_var,
+                                 axis=1,
+                                 epsilon=epsilon,
+                                 center=center,
+                                 scale=scale)[0]
+    return _impl
+
+def _transpose():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+
+        if isinstance(data, _expr.Var):
+            ndims = len(_infer_shape(data))
+        elif isinstance(data, (_expr.Call, _expr.TupleGetItem)):
+            ndims = _infer_shape(data)
+        else:
+            ndims = data.shape
+
+        if isinstance(data, tvm.ndarray.NDArray):
+            ndims = len(data.shape)
+        axes = list(range(ndims))
+
+        num_inputs = len(inputs)
+
+        if num_inputs == 1:
+            if ndims >= 2:
+                axes[-1] = ndims - 2
+                axes[-2] = ndims - 1
+            if not isinstance(data, _expr.Var):
+                data = _expr.const(data)
+
+        elif num_inputs == 3:
+            parse = lambda i: ndims * (i < 0) + i
+            src, dst = [parse(int(inputs[i])) for i in [1, 2]]
+            axes[src] = dst
+            axes[dst] = src
+        else:
+            axes = inputs[1]
+        return _op.transform.transpose(data, axes)
+    return _impl
+
+def _flatten():
+    def _impl(inputs, input_types):
+        data = inputs[0]
+        return _op.nn.batch_flatten(data)
+    return _impl
+
+def _dense():
+    def _impl(inputs, input_types):
+        use_bias = False
+
+        if isinstance(inputs[0], _expr.Var):
+            use_bias = True
+
+        data = inputs[1]
+        data_type = input_types[1]
+        weight = inputs[2]
+
+        beta = inputs[3]
+        alpha = inputs[4]
+
+        if not isinstance(alpha, (_expr.Var, _expr.Call, _expr.TupleGetItem)):
+            if data_type == 'double':
 
 Review comment:
   ditto

----------------------------------------------------------------
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

Reply via email to