Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QNN quantize and dequantize operators. #3745

Merged
merged 13 commits into from
Aug 16, 2019
32 changes: 32 additions & 0 deletions include/tvm/relay/qnn/attrs.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,38 @@ struct RequantizeAttrs : public tvm::AttrsNode<RequantizeAttrs> {
}
};

/*! \brief Attribute for quantize operator */
struct QuantizeAttrs : public tvm::AttrsNode<QuantizeAttrs> {
int32_t output_zero_point;
double output_scale;
DataType out_dtype;

TVM_DECLARE_ATTRS(QuantizeAttrs, "relay.attrs.QuantizeAttrs") {
TVM_ATTR_FIELD(out_dtype)
.describe("Output data type, can be one of [int8 or uint8].");

TVM_ATTR_FIELD(output_zero_point)
.describe("The zero_point for the activation of this op.");

TVM_ATTR_FIELD(output_scale)
.describe("The scale for the activation of this op.");
}
};

/*! \brief Attribute for dequantize operator */
struct DequantizeAttrs : public tvm::AttrsNode<DequantizeAttrs> {
int32_t input_zero_point;
double input_scale;

TVM_DECLARE_ATTRS(QuantizeAttrs, "relay.attrs.QuantizeAttrs") {
TVM_ATTR_FIELD(input_zero_point)
.describe("The zero_point for the input tensor of this op.");

TVM_ATTR_FIELD(input_scale)
.describe("The scale for the input tensor of this op.");
}
};

} // namespace qnn
} // namespace relay
} // namespace tvm
Expand Down
47 changes: 47 additions & 0 deletions python/tvm/relay/qnn/op/qnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,50 @@ def requantize(data,
output_zero_point,
rounding,
out_dtype)


def quantize(input_data, output_zero_point, output_scale, out_dtype='int8'):
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
r""" Quantize op
This operator takes float32 as input and produces quantized int8 or unit8 as output.
The input tensor can be of any shape. The output shape is the same as input shape.
..math::
\mbox{out}[x] =
\mbox{clamp(round(input_tensor/output_scale) + output_zero_point);
out_dtype::min, out_dtype::max}
Parameters
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
----------
input_data : tvm.relay.Expr
The input tensor to be quantized. Can be of type float32.
output_zero_point :
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
The output zero_point.
output_scale:
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
The output scale.
input_dtype:
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
The data type of the input tensor. Can be [int8, uint8]
Returns
-------
result : tvm.relay.Expr
The computed result.
"""
return _make.quantize(input_data, output_zero_point, output_scale, out_dtype)


def dequantize(input_data, input_zero_point, input_scale):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comments for the dequantize as for quantize

  • scale and zero point reordering
  • missing types in the description

r""" Dequantize op
This operator takes quantized int8 and unit8 as input and produces
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
dequantized float32 as output. The output shape is the same as input shape. The input
tensor can be of any shape.
Parameters
----------
input_data : tvm.relay.Expr
The input tensor to be dequantized. Can be of type [int8, uint8].
input_zero_point :
The output zero_point.
input_scale:
The output scale.
Returns
-------
result : tvm.relay.Expr
The computed result.
"""
return _make.dequantize(input_data, input_zero_point, input_scale)
105 changes: 105 additions & 0 deletions src/relay/qnn/op/dequantize.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* 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.
*/

/*!
* Copyright (c) 2019 by Contributors
* \file src/relay/qnn/op/dequantize.cc
* \brief QNN dequantize operator. Dequantize operator converts from quantized
* domain to unquantized domain.
*/

#include <tvm/relay/analysis.h>
//#include <tvm/relay/op.h>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove?

#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/qnn/attrs.h>
#include "../../pass/pattern_util.h"
#include "../util.h"

namespace tvm {
namespace relay {
namespace qnn {

TVM_REGISTER_NODE_TYPE(DequantizeAttrs);

bool DequantizeRel(const Array<Type>& types,
int num_inputs,
const Attrs& attrs,
const TypeReporter& reporter) {
CHECK_EQ(types.size(), 2);
const auto* data = types[0].as<TensorTypeNode>();
const auto input_dtype = data->dtype;
CHECK(input_dtype == Int(8) || input_dtype == UInt(8))
<< "Input type should be one of the quantized types [unit8, int8] but was " << input_dtype;
const Array<tvm::Expr> oshape = data->shape;
// assign output type, output will always be float 32.
reporter->Assign(types[1], TensorTypeNode::make(oshape, Float(32)));
return true;
}

Expr MakeDequantize(Expr data,
int32_t input_zero_point,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reorder suggestions. For consistency and python-to-C binding.

double input_scale) {
auto attrs = make_node<DequantizeAttrs>();
attrs->input_scale = input_scale;
attrs->input_zero_point = input_zero_point;
static const Op& op = Op::Get("qnn.dequantize");
return CallNode::make(op, {data}, Attrs(attrs), {});
}

Expr DequantizeLower(const Expr& input_tensor, const DequantizeAttrs* param) {
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
const auto input_zero_point = MakeConstantScalar(Int(32), param->input_zero_point);
const auto input_scale = MakeConstantScalar(Float(32), param->input_scale);
auto shift = Subtract(Cast(input_tensor, Int(32)), input_zero_point);
auto scaled_output = Multiply(Cast(shift, Float(32)), input_scale);
return scaled_output;
}

Expr DequantizeLegalize(const Attrs& attrs, const Array<Expr>& new_args,
const Array<tvm::relay::Type>& arg_types) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Align

CHECK_EQ(new_args.size(), 1);
auto& data = new_args[0];
const auto* param = attrs.as<DequantizeAttrs>();
CHECK(param != nullptr);

CHECK_EQ(arg_types.size(), 1);
auto input_dtype = arg_types[0];
auto input_tensor_type = input_dtype.as<TensorTypeNode>();
CHECK(input_tensor_type != nullptr) << "Type information missing."
<< " Please run infer_type pass.";
return DequantizeLower(data, param);
}

RELAY_REGISTER_OP("qnn.dequantize")
.describe(R"code(Dequantizes the input and produces float32 output.
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
The input is always quantized (int8, uint8) and will be converted to float32 given input scale and zero_point.
- **data**: Quantized tensor of any shape to dequantize. The input data can be of floating point
)code" TVM_ADD_FILELINE)
.set_attrs_type_key("relay.attrs.DequantizeAttrs")
.set_num_inputs(1)
.add_argument("data", "Tensor", "The tensor to dequantize.")
.set_support_level(11)
.add_type_rel("Dequantize", DequantizeRel)
.set_attr<FTVMLegalize>("FTVMLegalize", DequantizeLegalize);

TVM_REGISTER_API("relay.qnn.op._make.dequantize")
.set_body_typed(MakeDequantize);

} // namespace qnn
} // namespace relay
} // namespace tvm
123 changes: 123 additions & 0 deletions src/relay/qnn/op/quantize_op.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* 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.
*/

/*!
* Copyright (c) 2019 by Contributors
* \file src/relay/qnn/op/quantize_op.cc
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
* \brief QNN dequantize operator. Dequantize operator converts from quantized
* domain to unquantized domain.
*/

#include <tvm/relay/analysis.h>
//#include <tvm/relay/op.h>
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/qnn/attrs.h>
#include "../../pass/pattern_util.h"
#include "../util.h"

namespace tvm {
namespace relay {
namespace qnn {

TVM_REGISTER_NODE_TYPE(QuantizeAttrs);

bool QuantizeRel(const Array<Type>& types,
int num_inputs,
const Attrs& attrs,
const TypeReporter& reporter) {
CHECK_EQ(types.size(), 2);
const auto* data = types[0].as<TensorTypeNode>();
const auto input_dtype = data->dtype;
CHECK(input_dtype == Float(32))
<< "Input type should be one of float32 but was " << input_dtype;
const auto* param = attrs.as<QuantizeAttrs>();
const Array<tvm::Expr> oshape = data->shape;
const DataType out_dtype = param->out_dtype;
CHECK(out_dtype == Int(8) || out_dtype == UInt(8))
<< "Output type should be one of [int8, unit8 ] but was " << out_dtype;
// assign output type
reporter->Assign(types[1], TensorTypeNode::make(oshape, out_dtype));
return true;
}

Expr MakeQuantize(Expr data,
int32_t output_zero_point,
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
double output_scale,
DataType out_dtype) {
auto attrs = make_node<QuantizeAttrs>();
attrs->output_scale = output_scale;
attrs->output_zero_point = output_zero_point;
attrs->out_dtype = std::move(out_dtype);
static const Op& op = Op::Get("qnn.quantize");
return CallNode::make(op, {data}, Attrs(attrs), {});
}

shoubhik marked this conversation as resolved.
Show resolved Hide resolved
Expr QuantizeLower(const Expr& input_tensor, const QuantizeAttrs* param) {
const auto out_dtype = param->out_dtype;
const auto output_zero_point = MakeConstantScalar(Int(32), param->output_zero_point);
const auto scale = MakeConstantScalar(Float(32), param->output_scale);
const int32_t min_val = GetQmin(out_dtype);
const int32_t max_val = GetQmax(out_dtype);
auto scale_data = Cast(Round(Divide(input_tensor, scale)), Int(32));
// we are trying to do - std::min(std::max(unclamped, min_val), max_val);
auto add_zero_point = Add(scale_data, output_zero_point);
auto clamped_output = Clip(add_zero_point, min_val, max_val);
auto clamp_out_dtype = Cast(clamped_output, out_dtype);
return clamp_out_dtype;
}

Expr QuantizeLegalize(const Attrs& attrs, const Array<Expr>& new_args,
const Array<tvm::relay::Type>& arg_types) {
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
CHECK_EQ(new_args.size(), 1);
auto& data = new_args[0];
const auto* param = attrs.as<QuantizeAttrs>();
CHECK(param != nullptr);

CHECK_EQ(arg_types.size(), 1);
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
auto input_dtype = arg_types[0];
auto input_tensor_type = input_dtype.as<TensorTypeNode>();
CHECK(input_tensor_type != nullptr) << "Type information missing."
<< " Please run infer_type pass.";
return QuantizeLower(data, param);
}

RELAY_REGISTER_OP("qnn.quantize")
.describe(R"code(Quantizes the input and produces quantized output.
The input can be either float or quantized(int8, unit8). If the input is float,
this op takes scale and zero point and quantize the float value to
quantized output, in int8 or uint8 format. If the input is quantized value,
the op requantize the input (of a certain type, with a given scale and zero
point) to the output of the same or different type with a same or different
scale and zero point.
- **data**: Tensor of any shape to quantize. The input data can be of floating point
or quantized.
)code" TVM_ADD_FILELINE)
.set_attrs_type_key("relay.attrs.QuantizeAttrs")
.set_num_inputs(1)
.add_argument("data", "Tensor", "The tensor to quantize.")
.set_support_level(11)
.add_type_rel("Quantize", QuantizeRel)
.set_attr<FTVMLegalize>("FTVMLegalize", QuantizeLegalize);

TVM_REGISTER_API("relay.qnn.op._make.quantize")
.set_body_typed(MakeQuantize);

} // namespace qnn
} // namespace relay
} // namespace tvm
6 changes: 3 additions & 3 deletions src/relay/qnn/op/requantize.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

/*!
* Copyright (c) 2019 by Contributors
* \file requantize.cc
* \file src/relay/qnn/op/requantize.cc
* \brief QNN requantize operator.
*/

Expand Down Expand Up @@ -228,14 +228,14 @@ bool RequantizeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const auto* data = types[0].as<TensorTypeNode>();
const auto in_dtype = data->dtype;
CHECK(in_dtype == Int(8) || in_dtype == UInt(8) || in_dtype == Int(32))
<< "Input type should be an integer but was " << in_dtype;
<< "Input type should be one of [int8, uint8, int32] but was " << in_dtype;

const Array<tvm::Expr> oshape = data->shape;
// assign output type
const RequantizeAttrs* param = attrs.as<RequantizeAttrs>();
auto out_dtype = param->out_dtype;
CHECK(out_dtype == Int(8) || out_dtype == UInt(8) || out_dtype == Int(32))
<< "Output type should be an integer but was " << out_dtype;
<< "Output type should be one of [int8, uint8, int32] integer but was " << out_dtype;
shoubhik marked this conversation as resolved.
Show resolved Hide resolved
reporter->Assign(types[1], TensorTypeNode::make(oshape, out_dtype));
return true;
}
Expand Down
Loading