You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2021/11/22 11:21:17 UTC

[GitHub] [tvm] NicolaLancellotti commented on a change in pull request #9530: [microNPU] Add unary elementwise operator infrastructure with ABS

NicolaLancellotti commented on a change in pull request #9530:
URL: https://github.com/apache/tvm/pull/9530#discussion_r754163167



##########
File path: python/tvm/relay/op/contrib/ethosu.py
##########
@@ -852,6 +854,60 @@ def strided_slice_pattern():
     return pattern
 
 
+class AbsParams:
+    """
+    A class to extract and store parameters of Abs in an NPU friendly way
+    """

Review comment:
       The docstring should follow the same convention adopted with the other ```*Parms``` classes.

##########
File path: python/tvm/relay/backend/contrib/ethosu/legalize.py
##########
@@ -741,6 +741,96 @@ def __call__(self, *args, **kwargs):
         pass
 
 
+class UnaryElementwiseRewriter(DFPatternCallback):
+    """
+    Convert ethosu unary elementwise composite function to
+    ethosu_unary_elementwise operators
+    """
+
+    def __init__(self, params_class, pattern):

Review comment:
       ```suggestion
       def __init__(self, params_class: Type, pattern: CallPattern):
   ```

##########
File path: tests/python/contrib/test_ethosu/test_replace_unary_elementwise.py
##########
@@ -0,0 +1,158 @@
+# 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.
+
+import tvm
+import tvm.script
+from tvm import relay
+from tvm.relay.testing import run_opt_pass
+from tvm.relay.backend.contrib.ethosu.tir import spec
+from tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_tir
+from .infra import make_ethosu_unary_elementwise
+
+import pytest

Review comment:
       ```suggestion
   import pytest
   
   pytest.importorskip("ethosu.vela")
   
   import tvm
   import tvm.script
   from tvm import relay
   from tvm.relay.testing import run_opt_pass
   from tvm.relay.backend.contrib.ethosu.tir import spec
   from tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_tir
   from .infra import make_ethosu_unary_elementwise
   ```

##########
File path: src/relay/op/contrib/ethosu/unary_elementwise.cc
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.
+ */
+
+/*!
+ * \file src/relay/op/contrib/ethosu/unary_elementwise.cc
+ * \brief Property def of the Arm(R) Ethos(TM)-U unary elementwise ops.
+ */
+#include <tvm/relay/op.h>
+
+#include "common.h"
+
+namespace tvm {
+namespace relay {
+namespace op {
+namespace contrib {
+namespace ethosu {
+
+/*! \brief Attributes used by the NPU unary elementwise operator */
+struct EthosuUnaryElementwiseAttrs : public tvm::AttrsNode<EthosuUnaryElementwiseAttrs> {
+  String operator_type;
+  double ifm_scale;
+  int ifm_zero_point;
+  double ofm_scale;
+  int ofm_zero_point;
+  IndexExpr ofm_channels;
+  String activation;
+  int clip_min;
+  int clip_max;
+  String ifm_layout;
+  String ofm_layout;
+
+  TVM_DECLARE_ATTRS(EthosuUnaryElementwiseAttrs, "relay.attrs.EthosuUnaryElementwiseAttrs") {
+    TVM_ATTR_FIELD(operator_type)
+        .describe(
+            "The type of the unary elementwise operator."
+            "'ABS'");
+    TVM_ATTR_FIELD(ifm_scale).describe("The quantization scale for the Input Feature Map tensor.");
+    TVM_ATTR_FIELD(ifm_zero_point)
+        .describe("The quantization zero point for the Input Feature Map tensor.");
+    TVM_ATTR_FIELD(ofm_scale).describe("The quantization scale for the Output Feature Map tensor.");
+    TVM_ATTR_FIELD(ofm_zero_point)
+        .describe("The quantization zero point for the Output Feature Map tensor.");
+    TVM_ATTR_FIELD(ofm_channels).describe("The number of OFM channels.");
+    TVM_ATTR_FIELD(activation)
+        .describe(
+            "The activation function to use. "
+            "'NONE' - no activation function. "
+            "'CLIP' - clip the output between clip_min and clip_max. "
+            "'TANH' - tanh activation function. "
+            "'SIGMOID' - sigmoid activation function. "
+            "'LUT' - use a look-up table to perform the activation function.")
+        .set_default("NONE");
+    TVM_ATTR_FIELD(clip_min)
+        .describe("The minimum clipping value if activation = 'CLIP'.")
+        .set_default(0);
+    TVM_ATTR_FIELD(clip_max)
+        .describe("The maximum clipping value if activation = 'CLIP'.")
+        .set_default(0);
+    TVM_ATTR_FIELD(ifm_layout)
+        .describe("The layout of the Input Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.")
+        .set_default("NHWC");
+    TVM_ATTR_FIELD(ofm_layout)
+        .describe("The layout of the Output Feature Map tensor. Can be 'NHWC' or 'NHCWB16'.")
+        .set_default("NHWC");
+  }
+};
+
+TVM_REGISTER_NODE_TYPE(EthosuUnaryElementwiseAttrs);
+
+bool EthosuUnaryElementwiseRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
+                               const TypeReporter& reporter) {
+  int ifm_index = 0;
+  int result_index = 2;
+  ICHECK_EQ(types.size(), result_index + 1);
+
+  const auto* ifm = types[ifm_index].as<TensorTypeNode>();
+  if (ifm == nullptr) return false;
+
+  const auto* param = attrs.as<EthosuUnaryElementwiseAttrs>();
+  ICHECK(param != nullptr) << "EthosuUnaryElementwiseAttrs cannot be nullptr.";
+
+  String operator_type = param->operator_type;
+  bool valid_operator_type = operator_type == "ABS";
+  ICHECK(valid_operator_type) << "Expected ethosu_unary_elementwise 'ABS' for operator_type but was"
+                              << operator_type;
+
+  auto ifm_dtype = ifm->dtype;
+  ICHECK(ifm_dtype == DataType::UInt(8) || ifm_dtype == DataType::Int(8))
+      << "Expected ethosu_unary_elementwise type(uint8) or type(int8) for ifm but was "
+      << ifm_dtype;
+
+  // Assign ofm type
+  auto ofm_shape = EthosuInferBinaryElementwiseOutputShape(ifm->shape, param->ifm_layout,

Review comment:
       We should rename the function ```EthosuInferBinaryElementwiseOutputShape``` if it is used for the unary operators too.

##########
File path: python/tvm/relay/backend/contrib/ethosu/op/unary_elementwise.py
##########
@@ -0,0 +1,153 @@
+# 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=unused-argument
+"""Relay operator for unary elementwise operations for Arm(R) Ethos(TM)-U NPU"""
+import tvm
+from tvm.relay.op import _make
+from tvm.topi.generic import schedule_injective
+from tvm.relay.op.op import OpStrategy
+from tvm.relay.op import strategy as _strategy
+
+from ..te import unary_elementwise_compute
+
+
+def _extract_ethosu_unary_elementwise_params(attrs, args):
+    """Get the parameters necessary to construct a ethosu_unary_elementwise compute TE
+    from a ethosu_unary_elementwise Relay call."""
+    ifm = args[0]
+    lut = args[1]
+    operator_type = attrs.operator_type
+    ifm_scale = attrs.ifm_scale
+    ifm_zero_point = attrs.ifm_zero_point
+    ofm_scale = attrs.ofm_scale
+    ofm_zero_point = attrs.ofm_zero_point
+    ofm_channels = attrs.ofm_channels
+    activation = attrs.activation
+    clip_min = attrs.clip_min
+    clip_max = attrs.clip_max
+    ifm_layout = attrs.ifm_layout
+    ofm_layout = attrs.ofm_layout
+
+    return (
+        ifm,
+        lut,
+        operator_type,
+        ifm_scale,
+        ifm_zero_point,
+        ofm_scale,
+        ofm_zero_point,
+        ofm_channels,
+        activation,
+        clip_min,
+        clip_max,
+        ifm_layout,
+        ofm_layout,
+    )
+
+
+@tvm.ir.register_op_attr("contrib.ethosu.unary_elementwise", "FTVMCompute")
+def create_ethosu_unary_elementwise_compute(attrs, args, out_type):
+    """Create an ethosu_unary_elementwise compute op."""
+    params = _extract_ethosu_unary_elementwise_params(attrs, args)
+    op = unary_elementwise_compute(*params)
+    return [op]
+
+
+@tvm.ir.register_op_attr("contrib.ethosu.unary_elementwise", "FTVMStrategy")
+def unary_elementwise_strategy_ethosu(attrs, inputs, out_type, target):
+    strategy = OpStrategy()
+    strategy.add_implementation(
+        create_ethosu_unary_elementwise_compute,
+        _strategy.wrap_topi_schedule(schedule_injective),
+        name="ethosu_unary_elementwise",
+    )
+    return strategy
+
+
+def ethosu_unary_elementwise(
+    ifm: tvm.relay.Expr,
+    lut: tvm.relay.Expr,
+    operator_type: str,
+    ifm_scale: float,
+    ifm_zero_point: int,
+    ofm_scale: float,
+    ofm_zero_point: int,
+    ofm_channels: int,
+    activation: str = "NONE",
+    clip_min: int = 0,
+    clip_max: int = 0,
+    ifm_layout: str = "NHWC",
+    ofm_layout: str = "NHWC",

Review comment:
       ```suggestion
       activation: Optional[str] = "NONE",
       clip_min: Optional[int] = 0,
       clip_max: Optional[int] = 0,
       ifm_layout: Optional[str] = "NHWC",
       ofm_layout: Optional[str] = "NHWC",
   ```
   The docstring says that they are optional.
   Actually, we can get the same behaviour with the default values and the None value, maybe in a future pr we should have only one way to archive that.




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

To unsubscribe, e-mail: commits-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org