Skip to content

Commit ddf63c0

Browse files
ekaldakevinthesun
authored andcommitted
Add support for quantized multiply to Relay (apache#4141)
This patch adds multiply operator for quantized tensors. The details of the quantized multiplication are outlined in the code. This builds on pull request 3927 and includes the changes Animesh mentions in the comments on that request. Change-Id: I555715b53d0266a91d5c03dc3dfe8fc31e7ce4e1
1 parent 866a7cb commit ddf63c0

File tree

3 files changed

+387
-0
lines changed

3 files changed

+387
-0
lines changed

python/tvm/relay/qnn/op/qnn.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,3 +349,45 @@ def dense(data,
349349
input_zero_point,
350350
kernel_zero_point,
351351
out_dtype)
352+
353+
354+
def mul(lhs, rhs, lhs_scale, lhs_zero_point, rhs_scale, rhs_zero_point,
355+
output_scale, output_zero_point):
356+
"""Quantized multiplication with numpy-style broadcasting.
357+
358+
Parameters
359+
----------
360+
lhs : relay.Expr
361+
The left hand side quantized input data.
362+
363+
rhs : relay.Expr
364+
The right hand side quantized input data.
365+
366+
lhs_scale: float
367+
The scale of the lhs quantized expr.
368+
369+
lhs_zero_point: int
370+
The zero point of lhs quantized expr.
371+
372+
rhs_scale: float
373+
The scale of the rhs quantized expr.
374+
375+
rhs_zero_point: int
376+
The zero point of rhs quantized expr.
377+
378+
output_scale: float
379+
The scale of the output quantized expr.
380+
381+
output_zero_point: int
382+
The zero point of output quantized expr.
383+
384+
Returns
385+
-------
386+
result : relay.Expr
387+
The computed result.
388+
389+
"""
390+
return _make.mul(lhs, rhs,
391+
lhs_scale, lhs_zero_point,
392+
rhs_scale, rhs_zero_point,
393+
output_scale, output_zero_point)

src/relay/qnn/op/mul.cc

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
/*!
21+
* Copyright (c) 2019 by Contributors
22+
* \file src/relay/qnn/op/mul.cc
23+
* \brief QNN mul operator.
24+
*/
25+
#include <tvm/relay/analysis.h>
26+
#include <tvm/relay/op_attr_types.h>
27+
#include <tvm/relay/qnn/attrs.h>
28+
#include "../../pass/pattern_util.h"
29+
#include "../util.h"
30+
#include "op_common.h"
31+
32+
namespace tvm {
33+
namespace relay {
34+
namespace qnn {
35+
36+
/*
37+
* \brief Canonicalizes the QNN mul op.
38+
* \param attrs The QNN concatenate attrs.
39+
* \param new_args The new mutated args to the call node.
40+
* \param arg_types The types of input and output.
41+
* \return The sequence of Relay ops for mul op.
42+
*/
43+
Expr QnnMulCanonicalize(const Attrs& attrs, const Array<Expr>& new_args,
44+
const Array<tvm::relay::Type>& arg_types) {
45+
// Get the attrs.
46+
CHECK_EQ(new_args.size(), 2);
47+
auto& lhs = new_args[0];
48+
auto& rhs = new_args[1];
49+
const auto* binary_op_attrs = attrs.as<QnnBinaryOpAttrs>();
50+
CHECK(binary_op_attrs != nullptr);
51+
auto lhs_scale = binary_op_attrs->lhs_scale;
52+
auto lhs_zero_point = binary_op_attrs->lhs_zero_point;
53+
auto rhs_scale = binary_op_attrs->rhs_scale;
54+
auto rhs_zero_point = binary_op_attrs->rhs_zero_point;
55+
auto output_scale = binary_op_attrs->output_scale;
56+
auto output_zero_point = binary_op_attrs->output_zero_point;
57+
58+
// Get the input dtype and shape.
59+
CHECK_EQ(arg_types.size(), 3);
60+
auto tensor_type = arg_types[0].as<TensorTypeNode>();
61+
auto input_dtype = tensor_type->dtype;
62+
auto input_shape = tensor_type->shape;
63+
64+
/*
65+
A tensor multiplication c = a * b can be written in terms of respective
66+
quantized tensors, scales and zero points as
67+
S_c * (Q_c - zp_c) = S_a * (Q_a - zp_a) * S_b * (Q_b - zp_b).
68+
69+
We can consider the product (Q_a - zp_a) * (Q_b - zp_b) as a different
70+
quantized tensor of c, Q', with corresponding scale S' = S_a * S_b and zp' =
71+
0. The quantized multiplication then becomes
72+
Q_c = S'/S_c Q' + z_c,
73+
which is essentially a requantization of tensor Q' into tensor Q_c.
74+
*/
75+
76+
auto lhs_shifted = Cast(lhs, Int(32));
77+
auto rhs_shifted = Cast(rhs, Int(32));
78+
79+
if (lhs_zero_point != 0) {
80+
auto lhs_zp = MakeConstantScalar(Int(32), lhs_zero_point);
81+
lhs_shifted = Subtract(lhs_shifted, lhs_zp);
82+
}
83+
84+
if (rhs_zero_point != 0) {
85+
auto rhs_zp = MakeConstantScalar(Int(32), rhs_zero_point);
86+
rhs_shifted = Subtract(rhs_shifted, rhs_zp);
87+
}
88+
89+
// Create a new tensor Q'
90+
auto output = Multiply(lhs_shifted, rhs_shifted);
91+
92+
auto scale_new = rhs_scale * lhs_scale;
93+
94+
// Requantize to get Q_c
95+
output = Requantize(output, input_shape, scale_new, 0, output_scale,
96+
output_zero_point, input_dtype);
97+
98+
return output;
99+
}
100+
101+
// QNN Multiplication operator.
102+
QNN_REGISTER_BINARY_OP("mul")
103+
.describe("Elementwise mul with with broadcasting for quantized tensors.")
104+
.set_support_level(11)
105+
.set_attr<FTVMLegalize>("FTVMQnnCanonicalize", QnnMulCanonicalize);
106+
107+
} // namespace qnn
108+
} // namespace relay
109+
} // namespace tvm

tests/python/relay/test_qnn_mul.py

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
18+
import tvm
19+
import numpy as np
20+
from tvm import relay
21+
from tvm.contrib import graph_runtime
22+
import topi.testing
23+
24+
# "unquantize" a quantized tensor
25+
def recover(data, scale, zp):
26+
return scale * (np.asarray(data) - zp)
27+
28+
29+
def generate_golden_output(x_recovered, y_recovered, scale, zp):
30+
mul = x_recovered * y_recovered
31+
output = np.around(mul / scale + zp)
32+
33+
q_min = np.iinfo(np.uint8).min
34+
q_max = np.iinfo(np.uint8).max
35+
return np.clip(output, q_min, q_max)
36+
37+
38+
def test_tflite_same_io_qnn_params():
39+
data_dtype = "uint8"
40+
41+
lhs_scale = rhs_scale = output_scale = 0.00784314
42+
lhs_zero_point = rhs_zero_point = output_zero_point = 127
43+
44+
x = relay.var("x", shape=(1, 4), dtype=data_dtype)
45+
y = relay.var("y", shape=(1, 4), dtype=data_dtype)
46+
z = relay.qnn.op.mul(lhs=x, rhs=y,
47+
lhs_scale=lhs_scale,
48+
lhs_zero_point=lhs_zero_point,
49+
rhs_scale=rhs_scale,
50+
rhs_zero_point=rhs_zero_point,
51+
output_scale=output_scale,
52+
output_zero_point=output_zero_point)
53+
54+
func = relay.Function([x, y], z)
55+
mod = relay.Module.from_expr(func)
56+
mod = relay.qnn.transform.CanonicalizeOps()(mod)
57+
func = mod["main"]
58+
59+
x_datas = [
60+
np.array((1, 153, 2, 178)).reshape((1, 4)),
61+
np.array((25, 1, 178, 216)).reshape((1, 4)),
62+
np.array((25, 153, 1, 165)).reshape((1, 4)),
63+
]
64+
y_datas = [
65+
np.array((204, 178, 1, 8)).reshape((1, 4)),
66+
np.array((204, 178, 191, 1)).reshape((1, 4)),
67+
np.array((204, 178, 1, 191)).reshape((1, 4)),
68+
]
69+
70+
for i in range(0, 3):
71+
x_data = x_datas[i]
72+
y_data = y_datas[i]
73+
74+
x_rec = recover(x_data, lhs_scale, lhs_zero_point)
75+
y_rec = recover(y_data, rhs_scale, rhs_zero_point)
76+
golden = generate_golden_output(x_rec, y_rec, output_scale,
77+
output_zero_point)
78+
79+
intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm")
80+
op_res = intrp.evaluate(func)(x_data, y_data)
81+
82+
np.testing.assert_equal(op_res.asnumpy(), np.uint8(golden))
83+
84+
85+
def test_tflite_different_io_qnn_params():
86+
data_dtype = "uint8"
87+
88+
lhs_scale = 0.0156863
89+
lhs_zero_point = 127
90+
rhs_scale = 0.0117647
91+
rhs_zero_point = 85
92+
output_scale = 0.0235294
93+
output_zero_point = 128
94+
95+
x = relay.var("x", shape=(1, 4), dtype=data_dtype)
96+
y = relay.var("y", shape=(1, 4), dtype=data_dtype)
97+
z = relay.qnn.op.mul(lhs=x, rhs=y,
98+
lhs_scale=lhs_scale,
99+
lhs_zero_point=lhs_zero_point,
100+
rhs_scale=rhs_scale,
101+
rhs_zero_point=rhs_zero_point,
102+
output_scale=output_scale,
103+
output_zero_point=output_zero_point)
104+
105+
func = relay.Function([x, y], z)
106+
mod = relay.Module.from_expr(func)
107+
mod = relay.qnn.transform.CanonicalizeOps()(mod)
108+
func = mod["main"]
109+
110+
x_datas = [
111+
np.array((76, 140, 153, 172)).reshape((1, 4)),
112+
np.array((133, 140, 146, 153)).reshape((1, 4)),
113+
np.array((76, 140, 172, 146)).reshape((1, 4)),
114+
]
115+
y_datas = [
116+
np.array((136, 119, 128, 17)).reshape((1, 4)),
117+
np.array((136, 119, 111, 94)).reshape((1, 4)),
118+
np.array((136, 119, 17, 128)).reshape((1, 4)),
119+
]
120+
121+
for i in range(0, 3):
122+
x_data = x_datas[i]
123+
y_data = y_datas[i]
124+
125+
x_rec = recover(x_data, lhs_scale, lhs_zero_point)
126+
y_rec = recover(y_data, rhs_scale, rhs_zero_point)
127+
golden = generate_golden_output(x_rec, y_rec, output_scale,
128+
output_zero_point)
129+
130+
intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm")
131+
op_res = intrp.evaluate(func)(x_data, y_data)
132+
np.testing.assert_equal(op_res.asnumpy(), np.uint8(golden))
133+
134+
135+
def test_saturation():
136+
# Same params
137+
data_dtype = "uint8"
138+
lhs_scale = rhs_scale = output_scale = 0.125
139+
lhs_zero_point = rhs_zero_point = output_zero_point = 0
140+
141+
x = relay.var("x", shape=(1, 4), dtype=data_dtype)
142+
y = relay.var("y", shape=(1, 4), dtype=data_dtype)
143+
z = relay.qnn.op.mul(lhs=x, rhs=y,
144+
lhs_scale=lhs_scale,
145+
lhs_zero_point=lhs_zero_point,
146+
rhs_scale=rhs_scale,
147+
rhs_zero_point=rhs_zero_point,
148+
output_scale=output_scale,
149+
output_zero_point=output_zero_point)
150+
151+
func = relay.Function([x, y], z)
152+
mod = relay.Module.from_expr(func)
153+
mod = relay.qnn.transform.CanonicalizeOps()(mod)
154+
func = mod["main"]
155+
156+
x_data = np.array((255, 1, 1, 0)).reshape((1, 4))
157+
y_data = np.array((255, 255, 128, 0)).reshape((1, 4))
158+
159+
x_rec = recover(x_data, lhs_scale, lhs_zero_point)
160+
y_rec = recover(y_data, rhs_scale, rhs_zero_point)
161+
162+
golden = generate_golden_output(x_rec, y_rec, output_scale,
163+
output_zero_point)
164+
165+
intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm")
166+
op_res = intrp.evaluate(func)(x_data, y_data)
167+
np.testing.assert_equal(op_res.asnumpy(), np.uint8(golden))
168+
169+
# Same params, different scale
170+
171+
lhs_scale = rhs_scale = 0.125
172+
output_scale = 0.25
173+
174+
z = relay.qnn.op.mul(lhs=x, rhs=y,
175+
lhs_scale=lhs_scale,
176+
lhs_zero_point=lhs_zero_point,
177+
rhs_scale=rhs_scale,
178+
rhs_zero_point=rhs_zero_point,
179+
output_scale=output_scale,
180+
output_zero_point=output_zero_point)
181+
182+
func = relay.Function([x, y], z)
183+
mod = relay.Module.from_expr(func)
184+
mod = relay.qnn.transform.CanonicalizeOps()(mod)
185+
func = mod["main"]
186+
187+
x_data = np.array((255, 1, 1, 0)).reshape((1, 4))
188+
y_data = np.array((255, 255, 127, 0)).reshape((1, 4))
189+
190+
x_rec = recover(x_data, lhs_scale, lhs_zero_point)
191+
y_rec = recover(y_data, rhs_scale, rhs_zero_point)
192+
193+
golden = generate_golden_output(x_rec, y_rec, output_scale,
194+
output_zero_point)
195+
196+
intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm")
197+
op_res = intrp.evaluate(func)(x_data, y_data)
198+
np.testing.assert_equal(op_res.asnumpy(), np.uint8(golden))
199+
200+
# All params different
201+
202+
lhs_scale = 0.5
203+
rhs_scale = 0.25
204+
output_scale = 0.125
205+
206+
z = relay.qnn.op.mul(lhs=x, rhs=y,
207+
lhs_scale=lhs_scale,
208+
lhs_zero_point=lhs_zero_point,
209+
rhs_scale=rhs_scale,
210+
rhs_zero_point=rhs_zero_point,
211+
output_scale=output_scale,
212+
output_zero_point=output_zero_point)
213+
214+
func = relay.Function([x, y], z)
215+
mod = relay.Module.from_expr(func)
216+
mod = relay.qnn.transform.CanonicalizeOps()(mod)
217+
func = mod["main"]
218+
219+
x_data = np.array((255, 0, 1, 0)).reshape((1, 4))
220+
y_data = np.array((0, 128, 64, 0)).reshape((1, 4))
221+
222+
x_rec = recover(x_data, lhs_scale, lhs_zero_point)
223+
y_rec = recover(y_data, rhs_scale, rhs_zero_point)
224+
225+
golden = generate_golden_output(x_rec, y_rec, output_scale,
226+
output_zero_point)
227+
228+
intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm")
229+
op_res = intrp.evaluate(func)(x_data, y_data)
230+
np.testing.assert_equal(op_res.asnumpy(), np.uint8(golden))
231+
232+
233+
if __name__ == "__main__":
234+
test_tflite_same_io_qnn_params()
235+
test_tflite_different_io_qnn_params()
236+
test_saturation()

0 commit comments

Comments
 (0)