lhutton1 commented on a change in pull request #9442: URL: https://github.com/apache/tvm/pull/9442#discussion_r744649855
########## File path: python/tvm/relay/backend/contrib/ethosu/te/binary_elementwise.py ########## @@ -0,0 +1,169 @@ +# 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=invalid-name,unused-argument +"""Tensor Expressions for binary_elementwise""" +import operator +from tvm import te +from .dma import dma_ofm_compute, dma_ifm_compute + + +def binary_elementwise_compute( + ifm: te.Tensor, + ifm2: te.Tensor, + lut: te.Tensor, + operator_type: str, + ifm_scale: float, + ifm_zero_point: int, + ifm2_scale: float, + ifm2_zero_point: int, + ofm_scale: float, + ofm_zero_point: int, + ofm_channels: int, + reversed_operands: bool, + activation: str, + clip_min: int, + clip_max: int, + ifm_layout: str, + ifm2_layout: str, + ofm_layout: str, +) -> te.Tensor: + """A compute operator representing the capabilities of binary_elementwise for the NPU. + + Parameters + ---------- + ifm : te.Tensor + The Input Feature Map tensor (IFM). + ifm2 : te.Tensor + The Input Feature Map tensor 1 (IFM2). Review comment: ```suggestion The Input Feature Map tensor 2 (IFM2). ``` ########## File path: python/tvm/relay/backend/contrib/ethosu/te/binary_elementwise.py ########## @@ -0,0 +1,169 @@ +# 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=invalid-name,unused-argument +"""Tensor Expressions for binary_elementwise""" +import operator +from tvm import te +from .dma import dma_ofm_compute, dma_ifm_compute + + +def binary_elementwise_compute( + ifm: te.Tensor, + ifm2: te.Tensor, + lut: te.Tensor, + operator_type: str, + ifm_scale: float, + ifm_zero_point: int, + ifm2_scale: float, + ifm2_zero_point: int, + ofm_scale: float, + ofm_zero_point: int, + ofm_channels: int, + reversed_operands: bool, + activation: str, + clip_min: int, + clip_max: int, + ifm_layout: str, + ifm2_layout: str, + ofm_layout: str, +) -> te.Tensor: + """A compute operator representing the capabilities of binary_elementwise for the NPU. + + Parameters + ---------- + ifm : te.Tensor + The Input Feature Map tensor (IFM). + ifm2 : te.Tensor + The Input Feature Map tensor 1 (IFM2). + lut : te.Tensor + The look-up table values to use if activation = "LUT". + operator_type: str + The type of the binary elementwise operator. + "ADD" + "SUB" + "MUL" + "MIN" + "MAX" + "SHR" + "SHL" + ifm_scale : float + The quantization scale for the Input Feature Map tensor. + ifm_zero_point : int + The quantization zero point for the Input Feature Map tensor. + ifm2_scale : float + The quantization scale for the Input Feature Map tensor 2. + ifm2_zero_point : int + The quantization zero point for the Input Feature Map tensor 1. + ofm_scale : float + The quantization scale for the Output Feature Map tensor. + ofm_zero_point : int + The quantization zero point for the Output Feature Map tensor. + ofm_channels : int + The number of the Output Feature Map channels. + reversed_operands : bool + True if IFM2 is the first operand and IFM is the second operand. + activation : str + 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. + Available activations for activation type: + {int8, uint8}: "NONE", "CLIP", "TANH", "SIGMOID", "LUT" + {int32}: "NONE" + clip_min : int + The minimum clipping value if activation = "CLIP". + clip_max : int + The maximum clipping value if activation = "CLIP". + ifm_layout : str, optional + The layout of the Input Feature Map tensor. Can be "NHWC" or "NHCWB16". + ifm2_layout : str, optional + The layout of the Input Feature Map tensor 1. Can be "NHWC" or "NHCWB16". + ofm_layout : str, optional + The layout of the Output Feature Map tensor. Can be "NHWC" or "NHCWB16". + + Returns + ------- + te.Tensor + The OFM tensor. Review comment: Nit: Output Feature Map ########## File path: python/tvm/relay/backend/contrib/ethosu/op/binary_elementwise.py ########## @@ -0,0 +1,206 @@ +# 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 operators for binary elementwise operators 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 binary_elementwise_compute + + +def _extract_ethosu_binary_elementwise_params(attrs, args): + """Get the parameters necessary to construct a ethosu_binary_elementwise compute TE + from a ethosu_binary_elementwise Relay call.""" + ifm = args[0] + ifm2 = args[1] + lut = args[2] + operator_type = attrs.operator_type + ifm_scale = attrs.ifm_scale + ifm_zero_point = attrs.ifm_zero_point + ifm2_scale = attrs.ifm2_scale + ifm2_zero_point = attrs.ifm2_zero_point + ofm_scale = attrs.ofm_scale + ofm_zero_point = attrs.ofm_zero_point + ofm_channels = attrs.ofm_channels + reversed_operands = attrs.reversed_operands + activation = attrs.activation + clip_min = attrs.clip_min + clip_max = attrs.clip_max + ifm_layout = attrs.ifm_layout + ifm2_layout = attrs.ifm2_layout + ofm_layout = attrs.ofm_layout + + return ( + ifm, + ifm2, + lut, + operator_type, + ifm_scale, + ifm_zero_point, + ifm2_scale, + ifm2_zero_point, + ofm_scale, + ofm_zero_point, + ofm_channels, + reversed_operands, + activation, + clip_min, + clip_max, + ifm_layout, + ifm2_layout, + ofm_layout, + ) + + [email protected]_op_attr("contrib.ethosu.binary_elementwise", "FTVMCompute") +def create_ethosu_binary_elementwise_compute(attrs, args, out_type): + """Create an ethosu_binary_elementwise compute op.""" + params = _extract_ethosu_binary_elementwise_params(attrs, args) + op = binary_elementwise_compute(*params) + return [op] + + [email protected]_op_attr("contrib.ethosu.binary_elementwise", "FTVMStrategy") +def binary_elementwise_strategy_ethosu(attrs, inputs, out_type, target): + strategy = OpStrategy() + strategy.add_implementation( + create_ethosu_binary_elementwise_compute, + _strategy.wrap_topi_schedule(schedule_injective), + name="ethosu_binary_elementwise", + ) + return strategy + + +def ethosu_binary_elementwise( + ifm: tvm.relay.Expr, + ifm2: tvm.relay.Expr, + lut: tvm.relay.Expr, + operator_type: str, + ifm_scale: float, + ifm_zero_point: int, + ifm2_scale: float, + ifm2_zero_point: int, + ofm_scale: float, + ofm_zero_point: int, + ofm_channels: int, + reversed_operands: bool, + ofm_dtype: str, + activation: str = "NONE", + clip_min: int = 0, + clip_max: int = 0, + ifm_layout: str = "NHWC", + ifm2_layout: str = "NHWC", + ofm_layout: str = "NHWC", Review comment: Nit: Optional[type] ########## File path: python/tvm/relay/backend/contrib/ethosu/te/binary_elementwise.py ########## @@ -0,0 +1,169 @@ +# 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=invalid-name,unused-argument +"""Tensor Expressions for binary_elementwise""" +import operator +from tvm import te +from .dma import dma_ofm_compute, dma_ifm_compute + + +def binary_elementwise_compute( + ifm: te.Tensor, + ifm2: te.Tensor, + lut: te.Tensor, + operator_type: str, + ifm_scale: float, + ifm_zero_point: int, + ifm2_scale: float, + ifm2_zero_point: int, + ofm_scale: float, + ofm_zero_point: int, + ofm_channels: int, + reversed_operands: bool, + activation: str, + clip_min: int, + clip_max: int, + ifm_layout: str, + ifm2_layout: str, + ofm_layout: str, +) -> te.Tensor: + """A compute operator representing the capabilities of binary_elementwise for the NPU. + + Parameters + ---------- + ifm : te.Tensor + The Input Feature Map tensor (IFM). + ifm2 : te.Tensor + The Input Feature Map tensor 1 (IFM2). + lut : te.Tensor + The look-up table values to use if activation = "LUT". + operator_type: str + The type of the binary elementwise operator. + "ADD" + "SUB" + "MUL" + "MIN" + "MAX" + "SHR" + "SHL" + ifm_scale : float + The quantization scale for the Input Feature Map tensor. + ifm_zero_point : int + The quantization zero point for the Input Feature Map tensor. + ifm2_scale : float + The quantization scale for the Input Feature Map tensor 2. + ifm2_zero_point : int + The quantization zero point for the Input Feature Map tensor 1. + ofm_scale : float + The quantization scale for the Output Feature Map tensor. + ofm_zero_point : int + The quantization zero point for the Output Feature Map tensor. + ofm_channels : int + The number of the Output Feature Map channels. + reversed_operands : bool + True if IFM2 is the first operand and IFM is the second operand. + activation : str + 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. + Available activations for activation type: + {int8, uint8}: "NONE", "CLIP", "TANH", "SIGMOID", "LUT" + {int32}: "NONE" + clip_min : int + The minimum clipping value if activation = "CLIP". + clip_max : int + The maximum clipping value if activation = "CLIP". + ifm_layout : str, optional + The layout of the Input Feature Map tensor. Can be "NHWC" or "NHCWB16". + ifm2_layout : str, optional + The layout of the Input Feature Map tensor 1. Can be "NHWC" or "NHCWB16". Review comment: ```suggestion The layout of the Input Feature Map tensor 2. Can be "NHWC" or "NHCWB16". ``` ########## File path: src/relay/op/contrib/ethosu/binary_elementwise.cc ########## @@ -0,0 +1,299 @@ +/* + * 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/binary_elementwise.cc + * \brief Binary elementwise operators definitions for the Arm(R) Ethos(TM)-U NPU. + */ +#include <tvm/relay/op.h> + +#include "common.h" + +namespace tvm { +namespace relay { +namespace op { +namespace contrib { +namespace ethosu { + +/*! \brief Attributes used by the Ethos(TM)-U NPU binary elementwise operators */ +struct EthosuBinaryElementwiseAttrs : public tvm::AttrsNode<EthosuBinaryElementwiseAttrs> { + String operator_type; + double ifm_scale; + int ifm_zero_point; + double ifm2_scale; + int ifm2_zero_point; + double ofm_scale; + int ofm_zero_point; + IndexExpr ofm_channels; + bool reversed_operands; + String activation; + int clip_min; + int clip_max; + String ifm_layout; + String ifm2_layout; + String ofm_layout; + String ofm_dtype; + + TVM_DECLARE_ATTRS(EthosuBinaryElementwiseAttrs, "relay.attrs.EthosuBinaryElementwiseAttrs") { + TVM_ATTR_FIELD(operator_type) + .describe( + "The type of the binary elementwise operator." + "'ADD'" + "'SUB'" + "'MUL'" + "'MIN'" + "'MAX'" + "'SHR'" + "'SHL'"); + 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(ifm2_scale) + .describe("The quantization scale for the Input Feature Map tensor 2."); + TVM_ATTR_FIELD(ifm2_zero_point) + .describe("The quantization zero point for the Input Feature Map tensor 2."); + 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 the Output Feature Map channels."); + TVM_ATTR_FIELD(reversed_operands) + .describe("True if IFM2 is the first operand and IFM is the second operand.") + .set_default(false); + 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." + "Available activations for activation type:" + "{int8, uint8}: 'NONE', 'CLIP', 'TANH', 'SIGMOID', 'LUT'" + "{int32}: 'NONE'") + .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(ifm2_layout) + .describe("The layout of the Input Feature Map tensor 2. 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_ATTR_FIELD(ofm_dtype) + .describe( + "The Output Feature Map tensor type." + "MUL, ADD, SUB {IFM}->{OFM}:" + " {uint8, int8 int32} -> {uint8, int8, int32}, any pairing" + "MAX, MIN:" + " IFM and OFM must be of the same type, one of:" + " {int8, uint8}" + "SHR {IFM}->{OFM}:" + " {int32}->{int8, uint8, int32}, any pairing" + "SHL:" + " {int32}->{int32} only") + .set_default("NHWC"); + } +}; + +TVM_REGISTER_NODE_TYPE(EthosuBinaryElementwiseAttrs); + +bool EthosuBinaryElementwiseRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, + const TypeReporter& reporter) { + int ifm_index = 0; + int ifm2_index = 1; + int result_index = 3; + ICHECK_EQ(types.size(), result_index + 1); + + const auto* ifm = types[ifm_index].as<TensorTypeNode>(); + const auto* ifm2 = types[ifm2_index].as<TensorTypeNode>(); + if (ifm == nullptr) return false; + if (ifm2 == nullptr) return false; + + const auto* param = attrs.as<EthosuBinaryElementwiseAttrs>(); + ICHECK(param != nullptr) << "EthosuBinaryElementwiseAttrs cannot be nullptr."; + + String operator_type = param->operator_type; + auto ifm_dtype = ifm->dtype; + auto ifm2_dtype = ifm2->dtype; + DataType ofm_dtype; + + if (param->ofm_dtype == "int8") { + ofm_dtype = DataType::Int(8); + } else if (param->ofm_dtype == "uint8") { + ofm_dtype = DataType::UInt(8); + } else if (param->ofm_dtype == "int32") { + ofm_dtype = DataType::Int(32); + } + + if (ifm_dtype != ifm2_dtype) { + reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " + << "type for ifm2 be the same of ifm but was " << ifm2_dtype + << " instead of " << ifm_dtype); + return false; + } + + if (operator_type == "ADD" || operator_type == "SUB" || operator_type == "MUL") { + if (ifm_dtype != DataType::UInt(8) && ifm_dtype != DataType::Int(8) && + ifm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal( + Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " << operator_type + << " type(uint8) or type(int8) or type(int32) for ifm but was " << ifm_dtype); + return false; + } + if (ofm_dtype != DataType::UInt(8) && ofm_dtype != DataType::Int(8) && + ofm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal( + Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " << operator_type + << " type(uint8) or type(int8) or type(int32) for ofm but was " << ofm_dtype); + return false; + } + } else if (operator_type == "MIN" || operator_type == "MAX") { + if (ifm_dtype != DataType::UInt(8) && ifm_dtype != DataType::Int(8)) { + reporter->GetDiagCtx().EmitFatal( + Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " << operator_type + << " type(uint8) or type(int8) for ifm but was " << ifm_dtype); + return false; + } + if (ifm_dtype != ofm_dtype) { + reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " + << operator_type + << " type for ofm be the same of ifm but was " << ofm_dtype + << " instead of " << ifm_dtype); + return false; + } + } else if (operator_type == "SHR") { + if (ifm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " + << operator_type << " type(int32) for ifm but was " + << ifm_dtype); + return false; + } + if (ofm_dtype != DataType::UInt(8) && ofm_dtype != DataType::Int(8) && + ofm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal( + Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " << operator_type + << " type(uint8) or type(int8) or type(int32) for ofm but was " << ofm_dtype); + return false; + } + } else if (operator_type == "SHL") { + if (ifm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " + << operator_type << " type(int32) for ifm but was " + << ifm_dtype); + + return false; + } + if (ofm_dtype != DataType::Int(32)) { + reporter->GetDiagCtx().EmitFatal(Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise " + << operator_type << " type(int32) for ofm but was " + << ofm_dtype); + return false; + } + } else { + reporter->GetDiagCtx().EmitFatal( + Diagnostic::Error(reporter->GetSpan()) + << "Invalid operator: expected ethosu_binary_elementwise 'ADD' or 'SUB' or 'MUL' or " + << "'MIN' or 'MAX' or 'SHR' or 'SHL' for operator_type but was " << param->operator_type); + return false; + } + + // 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, ofm_dtype)); + return true; +} + +Expr MakeEthosuBinaryElementwise(Expr ifm, Expr ifm2, Expr lut, String operator_type, + double ifm_scale, int ifm_zero_point, double ifm2_scale, + int ifm2_zero_point, double ofm_scale, int ofm_zero_point, + IndexExpr ofm_channels, bool reversed_operands, String activation, + int clip_min, int clip_max, String ifm_layout, String ifm2_layout, + String ofm_layout, String ofm_dtype) { + auto attrs = make_object<EthosuBinaryElementwiseAttrs>(); + + attrs->operator_type = std::move(operator_type); + attrs->ifm_scale = ifm_scale; + attrs->ifm_zero_point = ifm_zero_point; + attrs->ifm2_scale = ifm2_scale; + attrs->ifm2_zero_point = ifm2_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_codegen.py ########## @@ -343,5 +343,256 @@ def representative_dataset(): infra.verify_source(compiled_models, accel_type) [email protected]("accel_type", ACCEL_TYPES) [email protected]("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX"]) [email protected]( + "ifm_shape, ifm2_shape", + [ + ([1, 2, 3, 4], [1, 2, 3, 4]), + ([1, 2, 3, 4], [1, 1, 3, 1]), + ([1, 1, 3, 1], [1, 2, 3, 4]), + ], +) [email protected]("activation_function", ["NONE", "RELU"]) +def test_ethosu_binary_elementwise( + accel_type, + operator_type, + ifm_shape, + ifm2_shape, + activation_function, +): + dtype = "int8" + + def create_tflite_graph(): + tf.config.run_functions_eagerly(True) Review comment: Just curious, why do we need to enable eager execution? ########## File path: src/relay/op/contrib/ethosu/binary_elementwise.cc ########## @@ -0,0 +1,299 @@ +/* + * 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/binary_elementwise.cc + * \brief Binary elementwise operators definitions for the Arm(R) Ethos(TM)-U NPU. + */ +#include <tvm/relay/op.h> + +#include "common.h" + +namespace tvm { +namespace relay { +namespace op { +namespace contrib { +namespace ethosu { + +/*! \brief Attributes used by the Ethos(TM)-U NPU binary elementwise operators */ +struct EthosuBinaryElementwiseAttrs : public tvm::AttrsNode<EthosuBinaryElementwiseAttrs> { + String operator_type; + double ifm_scale; + int ifm_zero_point; + double ifm2_scale; + int ifm2_zero_point; + double ofm_scale; + int ofm_zero_point; + IndexExpr ofm_channels; + bool reversed_operands; + String activation; + int clip_min; + int clip_max; + String ifm_layout; + String ifm2_layout; + String ofm_layout; + String ofm_dtype; + + TVM_DECLARE_ATTRS(EthosuBinaryElementwiseAttrs, "relay.attrs.EthosuBinaryElementwiseAttrs") { + TVM_ATTR_FIELD(operator_type) + .describe( + "The type of the binary elementwise operator." + "'ADD'" + "'SUB'" + "'MUL'" + "'MIN'" + "'MAX'" + "'SHR'" + "'SHL'"); + 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(ifm2_scale) + .describe("The quantization scale for the Input Feature Map tensor 2."); + TVM_ATTR_FIELD(ifm2_zero_point) + .describe("The quantization zero point for the Input Feature Map tensor 2."); + 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 the Output Feature Map channels."); + TVM_ATTR_FIELD(reversed_operands) + .describe("True if IFM2 is the first operand and IFM is the second operand.") + .set_default(false); + 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." + "Available activations for activation type:" + "{int8, uint8}: 'NONE', 'CLIP', 'TANH', 'SIGMOID', 'LUT'" + "{int32}: 'NONE'") + .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(ifm2_layout) + .describe("The layout of the Input Feature Map tensor 2. 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_ATTR_FIELD(ofm_dtype) + .describe( + "The Output Feature Map tensor type." + "MUL, ADD, SUB {IFM}->{OFM}:" + " {uint8, int8 int32} -> {uint8, int8, int32}, any pairing" + "MAX, MIN:" + " IFM and OFM must be of the same type, one of:" + " {int8, uint8}" + "SHR {IFM}->{OFM}:" + " {int32}->{int8, uint8, int32}, any pairing" + "SHL:" + " {int32}->{int32} only") + .set_default("NHWC"); + } +}; + +TVM_REGISTER_NODE_TYPE(EthosuBinaryElementwiseAttrs); + +bool EthosuBinaryElementwiseRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, + const TypeReporter& reporter) { + int ifm_index = 0; + int ifm2_index = 1; + int result_index = 3; Review comment: Can these be made `const`? ########## File path: tests/python/contrib/test_ethosu/test_codegen.py ########## @@ -343,5 +343,256 @@ def representative_dataset(): infra.verify_source(compiled_models, accel_type) [email protected]("accel_type", ACCEL_TYPES) [email protected]("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX"]) [email protected]( + "ifm_shape, ifm2_shape", + [ + ([1, 2, 3, 4], [1, 2, 3, 4]), + ([1, 2, 3, 4], [1, 1, 3, 1]), + ([1, 1, 3, 1], [1, 2, 3, 4]), + ], +) [email protected]("activation_function", ["NONE", "RELU"]) +def test_ethosu_binary_elementwise( + accel_type, + operator_type, + ifm_shape, + ifm2_shape, + activation_function, +): + dtype = "int8" + + def create_tflite_graph(): + tf.config.run_functions_eagerly(True) + + class Model(tf.Module): + @tf.function + def tf_function(self, lhs, rhs): + if operator_type == "ADD": + op = tf.math.add(lhs, rhs) + elif operator_type == "SUB": + op = tf.math.subtract(lhs, rhs) + elif operator_type == "MUL": + op = tf.math.multiply(lhs, rhs) + elif operator_type == "MIN": + op = tf.math.minimum(lhs, rhs) + elif operator_type == "MAX": + op = tf.math.maximum(lhs, rhs) + if activation_function == "RELU": + op = tf.nn.relu(op) + return op + + model = Model() + concrete_func = model.tf_function.get_concrete_function( + tf.TensorSpec(ifm_shape, dtype=tf.float32), tf.TensorSpec(ifm2_shape, dtype=tf.float32) + ) + + # Convert the model + def representative_dataset(): + for _ in range(100): + data = np.random.rand(*tuple(ifm_shape)) + data2 = np.random.rand(*tuple(ifm2_shape)) * 2 + yield [data.astype(np.float32), data2.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 + + tflite_graph = create_tflite_graph() + tflite_model = tflite.Model.Model.GetRootAsModel(tflite_graph, 0) + + mod, params = relay.frontend.from_tflite( + tflite_model, + shape_dict={"ifm": ifm_shape, "ifm2": ifm2_shape}, + dtype_dict={"ifm": dtype, "ifm2": dtype}, + ) + mod = partition_for_ethosu(mod, params) + + # Generate reference data + input_data, output_data = infra.generate_ref_data_tflite(tflite_graph) + + compiled_models = infra.build_source( + mod, + input_data, + output_data, + accel_type, + output_tolerance=1 if operator_type == "MAX" else 0, + ) + + # Assumes only two runtime.Modules are created -- i.e. single offload module + imported_modules = compiled_models[0].executor_factory.lib.imported_modules + assert len(imported_modules) == 2 + ethosu_module = imported_modules[0] + + # Verify generated C source + get_cs = tvm._ffi.get_global_func("runtime.module.ethosu.getcs") + cmms = get_cs(ethosu_module) + cmms = bytes.fromhex(cmms) + + infra.print_payload(cmms) + infra.verify_source(compiled_models, accel_type) + + [email protected]("accel_type", ACCEL_TYPES) [email protected]( + "ifm_shape, ifm2_shape", + [ + ([1, 2, 3, 4], [1, 2, 3, 4]), + ([1, 2, 3, 4], [1, 1, 3, 1]), + ([1, 1, 3, 1], [1, 2, 3, 4]), + ], +) +def test_ethosu_left_shift_binary_elemwise( + accel_type, + ifm_shape, + ifm2_shape, +): + dtype = "int32" + + def create_model(): + ifm = relay.var("ifm", shape=ifm_shape, dtype=dtype) + ifm2 = relay.var("ifm2", shape=ifm2_shape, dtype=dtype) + c1 = relay.left_shift(ifm, ifm2) + f = relay.Function([ifm, ifm2], c1) + mod = tvm.IRModule() + mod["main"] = f + return mod + + relay_mod = create_model() + mod = partition_for_ethosu(relay_mod) + + # Generate reference data + in_min, in_max = util.get_range_for_dtype_str(dtype) + input_data = { + "ifm": np.random.randint(in_min, high=in_max, size=ifm_shape, dtype=dtype), + "ifm2": np.random.randint(0, high=32, size=ifm2_shape, dtype=dtype), + } + output_data = generate_ref_data(relay_mod, input_data) + + compiled_models = infra.build_source( + mod, + input_data, + output_data, + accel_type, + ) + + # Assumes only two runtime.Modules are created -- i.e. single offload module + imported_modules = compiled_models[0].executor_factory.lib.imported_modules + assert len(imported_modules) == 2 + ethosu_module = imported_modules[0] + + # Verify generated C source + get_cs = tvm._ffi.get_global_func("runtime.module.ethosu.getcs") + cmms = get_cs(ethosu_module) + cmms = bytes.fromhex(cmms) + + infra.print_payload(cmms) + infra.verify_source(compiled_models, accel_type) + + [email protected]("accel_type", ACCEL_TYPES) [email protected]( + "ifm_shape, ifm2_shape, reversed_operands", + [ + ([1, 2, 3, 4], [1, 2, 3, 4], False), + ([1, 2, 3, 1], [1, 1, 3, 1], False), + ([1, 1, 3, 1], [1, 2, 3, 1], True), + ], +) +def test_ethosu_right_shift_binary_elemwise(ifm_shape, ifm2_shape, reversed_operands, accel_type): + dtype = "int32" Review comment: Is it possible to test the other datatype combinations? e.g. int32 -> int8 -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
