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 09:24:42 UTC

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

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



##########
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):
+        super().__init__(require_type=True)
+        self.params_class = params_class
+        self.pattern = pattern
+
+    def callback(
+        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map
+    ) -> tvm.relay.Expr:
+        params = self.params_class(post.op.body)
+        params.ifm.tensor = post.args[0]
+
+        if str(params.ofm.layout) != "NHWC":

Review comment:
       IIRC we agreed to remove these checks, please ignore if not

##########
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):
+        super().__init__(require_type=True)
+        self.params_class = params_class
+        self.pattern = pattern
+
+    def callback(
+        self, pre: tvm.relay.Expr, post: tvm.relay.Expr, node_map: tvm.ir.container.Map
+    ) -> tvm.relay.Expr:
+        params = self.params_class(post.op.body)
+        params.ifm.tensor = post.args[0]
+
+        if str(params.ofm.layout) != "NHWC":
+            raise UnsupportedLayout(str(params.ofm.layout))
+
+        activation_map = {"clip": "CLIP"}
+        if params.activation:
+            activation = activation_map[params.activation.op.name]
+            clip_min = int(params.activation.attrs.a_min)
+            clip_max = int(params.activation.attrs.a_max)
+        else:
+            activation = "NONE"
+            clip_min = 0
+            clip_max = 0
+
+        # We don't yet support activation functions that use LUT.
+        lut = relay.const([], dtype="int8")
+
+        unary_input_shape = params.ifm.shape
+        # If the input tensor is not 4D, enter reshapes before and after the unary operator
+        if len(params.ifm.shape) == 4:
+            unary_input = params.ifm.tensor
+        else:
+            while len(unary_input_shape) < 4:
+                unary_input_shape = [1] + unary_input_shape

Review comment:
       ```suggestion
               pad_size = 4 - len(unary_input_shape)
               unary_input_shape = ([1] * pad_size) + unary_input_shape
   ```

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

Review comment:
       Better to make these `const`

##########
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,
+                                                           param->ofm_layout, param->ofm_channels);
+  reporter->Assign(types[result_index], TensorType(ofm_shape, ifm_dtype));
+  return true;
+}
+
+Expr MakeEthosuUnaryElementwise(Expr ifm, Expr lut, 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) {
+  auto attrs = make_object<EthosuUnaryElementwiseAttrs>();
+
+  attrs->operator_type = operator_type;
+  attrs->ifm_scale = ifm_scale;
+  attrs->ifm_zero_point = ifm_zero_point;
+  attrs->ofm_scale = ofm_scale;
+  attrs->ofm_zero_point = ofm_zero_point;
+  attrs->ofm_channels = ofm_channels;

Review comment:
       ```suggestion
     attrs->ofm_channels = std::move(ofm_channels);
   ```

##########
File path: tests/python/contrib/test_ethosu/test_legalize.py
##########
@@ -890,5 +890,107 @@ def test_relay_strided_slice_legalize(ifm_shape, begin, end):
     assert list(identity.checked_type.shape) == slice_shape
 
 
+@pytest.mark.parametrize("operator_type", ["ABS"])
+@pytest.mark.parametrize(
+    "ifm_shape",
+    [[1, 2, 3, 4], [1, 7, 3], [8, 3, 1], [11, 22], [300]],
+)
+def test_tflite_unary_elemwise_legalize(
+    operator_type,
+    ifm_shape,
+):
+    dtype = "int8"
+
+    def create_tflite_graph():
+        class Model(tf.Module):
+            @tf.function
+            def abs_func(self, x):
+                if operator_type == "ABS":
+                    op = tf.math.abs(x)
+                return op
+
+        model = Model()
+
+        # Save the model
+        concrete_func = model.abs_func.get_concrete_function(
+            tf.TensorSpec(ifm_shape, dtype=tf.float32)
+        )
+
+        # Convert the model
+        def representative_dataset():
+            for _ in range(100):
+                data = np.random.rand(*tuple(ifm_shape))
+                yield [data.astype(np.float32)]
+
+        converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])
+        converter.optimizations = [tf.lite.Optimize.DEFAULT]
+        converter.representative_dataset = representative_dataset
+        converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
+        converter.inference_input_type = tf.int8
+        converter.inference_output_type = tf.int8
+        tflite_model = converter.convert()
+        return tflite_model
+
+    def verify(ext_func):
+        out_shape = ifm_shape
+        func_body = ext_func.body
+
+        # If we legalized the unary elementwise op into 4D
+        if func_body.op.name == "reshape":
+            reshape = func_body
+            unary = func_body.args[0]
+            reshape2 = unary.args[0]
+
+            # Check the input to the reshape
+            reshape2_in_shape = [i for i in reshape2.args[0].checked_type.shape]
+            assert reshape2_in_shape == ifm_shape
+
+            # Check that the unary elementwise operator is 4D after reshape
+            assert len(unary.checked_type.shape) == 4
+            assert unary.args[0].checked_type.dtype == dtype
+
+            # Check that the output of the graph has the same shape as input
+            reshape_out_shape = [i for i in reshape.checked_type.shape]
+            assert reshape_out_shape == ifm_shape
+            assert unary.attrs.operator_type == operator_type
+
+        else:
+            unary = func_body
+
+            # Check the IFM
+            assert list(unary.args[0].checked_type.shape) == ifm_shape
+            assert unary.args[0].checked_type.dtype == dtype
+
+            # Check the OFM
+            assert list(unary.checked_type.shape) == out_shape
+            assert unary.checked_type.dtype == dtype
+
+            # operator type check
+            assert unary.attrs.operator_type == operator_type
+
+    if operator_type == "ABS":
+        rewriter = legalize.AbsRewriter()
+        pattern_table = [
+            (
+                ethosu.AbsParams.composite_name,
+                ethosu.abs_pattern(),
+                lambda pat: ethosu.AbsParams(pat).is_valid(),
+            ),
+        ]
+
+    tflite_graph = create_tflite_graph()
+    tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0)
+    mod, _ = relay.frontend.from_tflite(
+        tflite_model,
+        shape_dict={"input": ifm_shape},
+        dtype_dict={"x": dtype},

Review comment:
       ```suggestion
           dtype_dict={"input": dtype},
   ```

##########
File path: python/tvm/relay/backend/contrib/ethosu/util.py
##########
@@ -90,6 +90,28 @@ class BinaryElementwiseArgs(Enum):
     ofm_zero_point = 7
 
 
+class QuantizeArgs(Enum):
+    """
+    This is a helper enums to access the correct index of
+    quantize arguments
+    """
+
+    ifm = 0

Review comment:
       Looks like we missed this for binary elementwise also... should we follow convention here and use capitals?

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

Review comment:
       Should we use the `TypeReporter` here instead, similar to other operators?

##########
File path: tests/python/contrib/test_ethosu/test_type_inference.py
##########
@@ -374,5 +375,32 @@ def test_ethosu_invalid_dtype():
         run_opt_pass(func, relay.transform.InferType())
 
 
+@pytest.mark.parametrize(
+    "ifm_shape, ifm_layout", [((1, 4, 5, 33), "NHWC"), ((1, 4, 3, 5, 16), "NHCWB16")]
+)
+@pytest.mark.parametrize(
+    "ofm_shape, ofm_layout", [((1, 4, 5, 33), "NHWC"), ((1, 4, 3, 5, 16), "NHCWB16")]
+)
+def test_ethosu_unary_elementwise_type_inference(
+    ifm_shape,
+    ifm_layout,
+    ofm_shape,
+    ofm_layout,
+):
+    ifm = relay.var("ifm", shape=ifm_shape, dtype="int8")
+    operator_type = "ABS"
+    ofm_channels = 33
+    unary_elementwise = make_ethosu_unary_elementwise(
+        ifm,
+        ofm_channels,
+        operator_type,
+        ifm_layout=ifm_layout,
+        ofm_layout=ofm_layout,
+    )
+    f = relay.Function([ifm], unary_elementwise)
+    f = run_opt_pass(f, relay.transform.InferType())
+    assert tuple(f.body.checked_type.shape) == ofm_shape
+
+

Review comment:
       We should also test invalid dtypes/shapes etc here

##########
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,
+                                                           param->ofm_layout, param->ofm_channels);
+  reporter->Assign(types[result_index], TensorType(ofm_shape, ifm_dtype));
+  return true;
+}
+
+Expr MakeEthosuUnaryElementwise(Expr ifm, Expr lut, 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) {
+  auto attrs = make_object<EthosuUnaryElementwiseAttrs>();
+
+  attrs->operator_type = operator_type;

Review comment:
       ```suggestion
     attrs->operator_type = std::move(operator_type);
   ```

##########
File path: python/tvm/relay/backend/contrib/ethosu/tir_to_cs_translator.py
##########
@@ -770,3 +771,49 @@ def _create_npu_op_binary_elementwise(serial_binary_elementwise: spec.SerialBina
     npu_binary_elementwise_op.block_config = block_config
 
     return npu_binary_elementwise_op
+
+
+def translate_ethosu_unary_elementwise(
+    tir_extern_call: tvm.tir.Call,
+) -> vapi.NpuElementWiseOperation:
+    """This function will translate a tir extern_call
+    as produced by Relay to TIR compilation.
+    Parameters

Review comment:
       Nit: insert blank line




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