NicolaLancellotti commented on a change in pull request #9384:
URL: https://github.com/apache/tvm/pull/9384#discussion_r740305018
##########
File path: tests/python/contrib/test_ethosu/test_legalize.py
##########
@@ -458,7 +458,102 @@ def verify(ext_func):
mod = partition_ethosu_by_table(mod, depthwise_pattern_table)
mod["tvmgen_default_ethosu_main_0"] = dataflow_pattern.rewrite(
- legalize.EthosuDepthwiseConv2DRewriter(),
mod["tvmgen_default_ethosu_main_0"]
+ legalize.DepthwiseConv2DRewriter(), mod["tvmgen_default_ethosu_main_0"]
+ )
+ verify(mod["tvmgen_default_ethosu_main_0"])
+
+
[email protected]("pooling_type", ["MAX", "AVG"])
[email protected]("ifm_shape", [[1, 9, 12, 3], [1, 10, 20, 2]])
[email protected]("strides", [[1, 2], [2, 3]])
[email protected]("pool_shape", [[1, 2], [2, 3]])
[email protected]("activation_function", ["NONE", "RELU"])
[email protected]("padding", ["SAME", "VALID"])
+def test_tflite_pool2d_legalize(
+ ifm_shape, pooling_type, strides, pool_shape, activation_function, padding
+):
+ dtype = "int8"
+
+ def create_tflite_graph():
+ class Model(tf.Module):
+ @tf.function
+ def tf_function(self, x):
+ if pooling_type == "MAX":
+ op = tf.nn.max_pool(x, pool_shape, strides, padding)
+ elif pooling_type == "AVG":
+ op = tf.nn.avg_pool(x, pool_shape, strides, padding)
+ 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)
+ )
+
+ # 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):
+ ofm_shape = infra.compute_ofm_shape(ifm_shape, padding, pool_shape,
strides)
+ op = ext_func.body
+ assert list(op.args[0].checked_type.shape) == ifm_shape
+ assert op.args[0].checked_type.dtype == dtype
+ assert list(op.checked_type.shape) == ofm_shape
+ assert op.checked_type.dtype == dtype
+ assert op.attrs.pooling_type == pooling_type
+ assert list(op.attrs.strides) == strides
+ assert list(op.attrs.padding) == infra.compute_padding_shape(
+ ifm_shape, ofm_shape, padding, pool_shape, strides
+ )
+ assert list(op.attrs.pool_shape) == pool_shape
+ assert op.attrs.ofm_channels == ifm_shape[3]
+ if activation_function == "RELU":
+ assert str(op.attrs.activation) == "CLIP"
+
+ if pooling_type == "MAX":
+ rewriter = legalize.MaxPoolingRewriter()
+ pattern_table = [
+ (
+ ethosu.MaxPool2DParams.composite_name,
+ ethosu.qnn_maxpool2d_pattern(),
+ lambda pat: ethosu.MaxPool2DParams(pat).is_valid(),
+ ),
+ ]
+ elif pooling_type == "AVG":
+ rewriter = legalize.AvgPoolingRewriter()
+ pattern_table = [
+ (
+ ethosu.AvgPool2DParams.composite_name,
+ ethosu.qnn_avgpool2d_pattern(),
+ lambda pat: ethosu.AvgPool2DParams(pat).is_valid(),
+ ),
+ ]
Review comment:
Thinking about it, it should be ok to have only one test, that because
`MAX` and `AVG` are the two possible values of the `pooling_type` attribute of
the Ethos(TM)-U Pooling operator. We are not testing two different operators in
one test, but different parameters of the same operator.
##########
File path: src/relay/op/contrib/ethosu/pooling.cc
##########
@@ -0,0 +1,185 @@
+/*
+ * 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/pooling.cc
+ * \brief Pooling operators definitions for the Arm(R) Ethos(TM)-U NPU
convolution ops.
+ */
+#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 pooling operator */
+struct EthosuPoolingAttrs : public tvm::AttrsNode<EthosuPoolingAttrs> {
+ String pooling_type;
+ double ifm_scale;
+ int ifm_zero_point;
+ double ofm_scale;
+ int ofm_zero_point;
+ Array<IndexExpr> pool_shape;
+ IndexExpr ofm_channels;
+ Array<IndexExpr> strides;
+ Array<IndexExpr> padding;
+ String activation;
+ int clip_min;
+ int clip_max;
+ String upscale;
+ String ifm_layout;
+ String ofm_layout;
+
+ TVM_DECLARE_ATTRS(EthosuPoolingAttrs, "relay.attrs.EthosuPoolingAttrs") {
+ TVM_ATTR_FIELD(pooling_type)
+ .describe("The type of the pooling. 'AVG' - average pool, 'MAX' - max
pool.");
+ 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(pool_shape)
+ .describe("The 2 dimensional pool shape as (pool_shape_height,
pool_shape_width).")
+ .set_default(NullValue<Array<IndexExpr> >());
+ TVM_ATTR_FIELD(ofm_channels)
+ .describe(" The number of the Output Feature Map channels.")
+ .set_default(NullValue<IndexExpr>());
+ TVM_ATTR_FIELD(strides)
+ .set_default(Array<IndexExpr>({1, 1}))
+ .describe("The 2 dimensional strides as (stride_height,
stride_width).");
+ TVM_ATTR_FIELD(padding)
+ .describe("The 4 dimensional padding as (pad_top, pad_left,
pad_bottom, pad_right).")
+ .set_default(Array<IndexExpr>({0, 0, 0, 0}));
+ 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(upscale)
+ .describe(
+ "The 2x2 upscaling mode to apply to the Input Feature Map tensor. "
+ "'NONE' - no upscaling. "
+ "'NEAREST' - upscale using nearest neighbour. "
+ "'ZEROS' - upscale using zeros.")
+ .set_default("NONE");
+ 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(EthosuPoolingAttrs);
+
+bool EthosuPoolingRel(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<EthosuPoolingAttrs>();
+ ICHECK(param != nullptr) << "EthosuPoolingAttrs cannot be nullptr.";
+
+ ICHECK(param->pooling_type == "AVG" || param->pooling_type == "MAX")
Review comment:
Done
##########
File path: src/relay/op/contrib/ethosu/pooling.cc
##########
@@ -0,0 +1,185 @@
+/*
+ * 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/pooling.cc
+ * \brief Pooling operators definitions for the Arm(R) Ethos(TM)-U NPU
convolution ops.
+ */
+#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 pooling operator */
+struct EthosuPoolingAttrs : public tvm::AttrsNode<EthosuPoolingAttrs> {
+ String pooling_type;
+ double ifm_scale;
+ int ifm_zero_point;
+ double ofm_scale;
+ int ofm_zero_point;
+ Array<IndexExpr> pool_shape;
+ IndexExpr ofm_channels;
+ Array<IndexExpr> strides;
+ Array<IndexExpr> padding;
+ String activation;
+ int clip_min;
+ int clip_max;
+ String upscale;
+ String ifm_layout;
+ String ofm_layout;
+
+ TVM_DECLARE_ATTRS(EthosuPoolingAttrs, "relay.attrs.EthosuPoolingAttrs") {
+ TVM_ATTR_FIELD(pooling_type)
+ .describe("The type of the pooling. 'AVG' - average pool, 'MAX' - max
pool.");
+ 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(pool_shape)
+ .describe("The 2 dimensional pool shape as (pool_shape_height,
pool_shape_width).")
+ .set_default(NullValue<Array<IndexExpr> >());
+ TVM_ATTR_FIELD(ofm_channels)
+ .describe(" The number of the Output Feature Map channels.")
+ .set_default(NullValue<IndexExpr>());
+ TVM_ATTR_FIELD(strides)
+ .set_default(Array<IndexExpr>({1, 1}))
+ .describe("The 2 dimensional strides as (stride_height,
stride_width).");
+ TVM_ATTR_FIELD(padding)
+ .describe("The 4 dimensional padding as (pad_top, pad_left,
pad_bottom, pad_right).")
+ .set_default(Array<IndexExpr>({0, 0, 0, 0}));
+ 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(upscale)
+ .describe(
+ "The 2x2 upscaling mode to apply to the Input Feature Map tensor. "
+ "'NONE' - no upscaling. "
+ "'NEAREST' - upscale using nearest neighbour. "
+ "'ZEROS' - upscale using zeros.")
+ .set_default("NONE");
+ 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(EthosuPoolingAttrs);
+
+bool EthosuPoolingRel(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<EthosuPoolingAttrs>();
+ ICHECK(param != nullptr) << "EthosuPoolingAttrs cannot be nullptr.";
+
+ ICHECK(param->pooling_type == "AVG" || param->pooling_type == "MAX")
+ << "Expected pooling_type 'AVG' or 'MAX' but was" << param->pooling_type;
+
+ ICHECK(ifm->dtype == DataType::UInt(8) || ifm->dtype == DataType::Int(8))
Review comment:
Done
##########
File path: tests/python/contrib/test_ethosu/test_replace_pooling.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 pytest
+
+pytest.importorskip("ethosu.vela")
+
+import tvm
+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_pooling, get_pooling_args
+
+
[email protected](
+ "ifm_shape, ofm_channels, ifm_layout, ofm_layout",
+ [
+ ((1, 5, 9, 3), 3, "NHWC", "NHWC"),
+ ((1, 8, 3, 9, 16), 40, "NHCWB16", "NHCWB16"),
+ ((1, 8, 3, 9, 16), 40, "NHCWB16", "NHWC"),
+ ((1, 8, 9, 40), 40, "NHWC", "NHCWB16"),
+ ],
+)
[email protected]("pooling_type", ["AVG", "MAX"])
[email protected]("activation", ["NONE", "CLIP", "TANH", "SIGMOID"])
+def test_pooling_single(
+ ifm_shape,
+ ofm_channels,
+ ifm_layout,
+ ofm_layout,
+ pooling_type,
+ activation,
+):
+ pool_shape = (3, 2)
+ strides = (1, 2)
+ padding = (1, 1, 1, 0)
+ ifm = relay.var("ifm", shape=ifm_shape, dtype="int8")
+ pooling = make_ethosu_pooling(
+ ifm,
+ pooling_type,
+ pool_shape,
+ ofm_channels,
+ strides,
+ padding,
+ activation,
+ ifm_layout,
+ ofm_layout,
+ )
+ func = relay.Function(relay.analysis.free_vars(pooling), pooling)
+ func = run_opt_pass(func, relay.transform.InferType())
+ mod, _ = lower_to_tir(func)
+ data = []
+
+ def _visit(stmt):
+ if isinstance(stmt, tvm.tir.Call):
+ data.append(get_pooling_args(stmt))
+
+ tvm.tir.stmt_functor.post_order_visit(mod["main"].body, _visit)
+ if ifm_layout == "NHWC":
+ ifm_stride_c = 1
+ ifm_stride_w = ifm_shape[3]
+ ifm_stride_h = ifm_shape[2] * ifm_shape[3]
+ ofm_height = (ifm_shape[1] - pool_shape[0] + padding[0] + padding[0])
// strides[0] + 1
+ ofm_width = (ifm_shape[2] - pool_shape[1] + padding[1] + padding[1])
// strides[1] + 1
+ else:
+ ifm_stride_w = 16
+ ifm_stride_c = 16 * ifm_shape[3]
+ ifm_stride_h = 16 * ifm_shape[2] * ifm_shape[3]
+ ofm_height = (ifm_shape[1] - pool_shape[0] + padding[0] + padding[0])
// strides[0] + 1
+ ofm_width = (ifm_shape[3] - pool_shape[1] + padding[1] + padding[1])
// strides[1] + 1
+
+ if ofm_layout == "NHWC":
+ ofm_stride_c = 1
+ ofm_stride_w = ofm_channels if ofm_width > 1 else 1
+ ofm_stride_h = ofm_channels * ofm_width if ofm_height > 1 else 1
+ else:
+ ofm_stride_w = 16
+ ofm_stride_c = 16 * ofm_width
+ ofm_stride_h = 16 * ofm_width * ((ofm_channels - 1) // 16 + 1)
+
+ serial_pooling = spec.SerialPooling(
+ ifm=spec.SerialFeatureMap(
+ data_type="int8",
+ height=ifm_shape[1],
+ width=ifm_shape[2] if ifm_layout == "NHWC" else ifm_shape[3],
+ channels=ofm_channels,
+ tile_height_0=ifm_shape[1],
+ tile_height_1=0,
+ tile_width_0=ifm_shape[2] if ifm_layout == "NHWC" else
ifm_shape[3],
+ tile_address_0=0,
+ tile_address_1=0,
+ tile_address_2=0,
+ tile_address_3=0,
+ scale=1.0,
+ zero_point=0,
+ layout=ifm_layout,
+ stride_h=ifm_stride_h,
+ stride_w=ifm_stride_w,
+ stride_c=ifm_stride_c,
+ ),
+ ofm=spec.SerialFeatureMap(
+ data_type="int8",
+ height=ofm_height,
+ width=ofm_width,
+ channels=ofm_channels,
+ tile_height_0=ofm_height,
+ tile_height_1=0,
+ tile_width_0=ofm_width,
+ tile_address_0=0,
+ tile_address_1=0,
+ tile_address_2=0,
+ tile_address_3=0,
+ scale=1.0,
+ zero_point=0,
+ layout=ofm_layout,
+ stride_h=ofm_stride_h,
+ stride_w=ofm_stride_w,
+ stride_c=ofm_stride_c,
+ ),
+ pooling_type=pooling_type,
+ pool_shape=spec.SerialKernel(
+ width=pool_shape[1],
+ height=pool_shape[0],
+ stride_w=strides[1],
+ stride_h=strides[0],
+ dilation_w=1,
+ dilation_h=1,
+ ),
+ padding=spec.SerialPadding(
+ top=padding[0], left=padding[1], bottom=padding[2],
right=padding[3]
+ ),
+ activation=spec.SerialActivation(
+ op=activation,
+ clip_min=10 if activation == "CLIP" else 0,
+ clip_max=100 if activation == "CLIP" else 0,
+ ),
Review comment:
I re-added the `NONE` test
--
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]