-
Notifications
You must be signed in to change notification settings - Fork 21.3k
/
qadd.cpp
306 lines (270 loc) · 11.7 KB
/
qadd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#include <ATen/ATen.h>
#include <torch/library.h>
#include <ATen/cpu/vec256/vec256.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/cpu/Loops.h>
#include <ATen/quantized/Quantizer.h>
#include <ATen/native/quantized/cpu/quantized_ops.h>
#include <ATen/native/quantized/cpu/init_qnnpack.h>
#include <ATen/native/quantized/cpu/qnnpack_utils.h>
#include <caffe2/utils/threadpool/pthreadpool-cpp.h>
#include <algorithm>
namespace at {
namespace native {
DEFINE_DISPATCH(qadd_relu_stub);
DEFINE_DISPATCH(qadd_stub);
DEFINE_DISPATCH(qadd_scalar_relu_stub);
DEFINE_DISPATCH(qadd_scalar_stub);
namespace {
inline void check_inputs(const Tensor& qa, const Tensor& qb) {
TORCH_CHECK(
qa.qscheme() == kPerTensorAffine,
"Only per tensor quantization is suported in Add.");
TORCH_CHECK(
qa.qscheme() == qb.qscheme(),
"Both inputs to Add must have the same quantization shceme.");
TORCH_CHECK(qa.numel() == qb.numel(), "Add operands must be the same size!");
TORCH_CHECK(
qa.scalar_type() == qb.scalar_type(),
"Add operands should have same data type.");
}
// Note: out is assumed to be the same size as self and other.
// Note: Addition is only supported when self, other, out are of the same dtype.
template <bool ReLUFused = false>
Tensor _add_out(Tensor& out, const Tensor& self, const Tensor& other) {
if (ReLUFused) {
qadd_relu_stub(self.device().type(), out, self, other);
} else {
qadd_stub(self.device().type(), out, self, other);
}
return out;
}
template <bool ReLUFused = false>
Tensor _add_scalar_out(Tensor& out, const Tensor& self, Scalar other) {
TORCH_CHECK(
self.qscheme() == kPerTensorAffine,
"Only per tensor affine is supported for now!!");
// To implement tensor-scalar addition in quantized space, we simply
// adjust the quantization parameters based on the following rules:
//
// Let s = scale, z = zero point, c = other.toFloat(), c_q = round(c/s)
// q_min = lowest representable value of scalar type
// q_max = highest representable value of scalar type
//
// Let s' = the calculated scale or the output
// z' = the calculated zero-point for the output
//
// If q_min > z - c_q
// s' = [(q_max - (z - c_q)]/[q_max - q_min] * s
// z' = q_min
// Xq' = at::requantize_from_int(Xq - z + c_q, s/s', z')
// If q_max < z - c_q
// s' = [z - c_q -q_min]/[q_max - q_min] * s
// z' = q_max
// Xq' = at::requantize_from_int(Xq - z + c_q, s/s', z')
// Else
// s' = s
// z' = z - c_q
AT_DISPATCH_QINT_TYPES(self.scalar_type(), "qadd_scalar", [&]() {
double s = self.q_scale();
int64_t z = self.q_zero_point();
double c = other.toDouble();
int64_t q_min = std::numeric_limits<underlying_t>::min();
int64_t q_max = std::numeric_limits<underlying_t>::max();
int64_t c_q = std::nearbyint(c / s);
double s_prime;
int64_t z_prime;
if (q_min > z - c_q) {
s_prime = (((double)q_max - (z - c_q))) / ((double)q_max - q_min) * s;
z_prime = q_min;
out.set_quantizer_(make_per_tensor_affine_quantizer(
s_prime, z_prime, self.scalar_type()));
if (ReLUFused) {
qadd_scalar_relu_stub(self.device().type(), out, self, c_q);
} else {
qadd_scalar_stub(self.device().type(), out, self, c_q);
}
} else if (q_max < z - c_q) {
s_prime = ((double)(z - c_q) - q_min) / ((double)q_max - q_min) * s;
z_prime = q_max;
out.set_quantizer_(make_per_tensor_affine_quantizer(
s_prime, z_prime, self.scalar_type()));
if (ReLUFused) {
qadd_scalar_relu_stub(self.device().type(), out, self, c_q);
} else {
qadd_scalar_stub(self.device().type(), out, self, c_q);
}
} else {
s_prime = s;
z_prime = z - c_q;
out.copy_(self);
out.set_quantizer_(make_per_tensor_affine_quantizer(
s_prime, z_prime, self.scalar_type()));
if (ReLUFused) {
at::native::relu_quantized_cpu_(out);
}
}
});
return out;
}
#ifdef USE_PYTORCH_QNNPACK
template <bool ReLUFused = false>
Tensor qnnpack_add(Tensor qa, Tensor qb, double scale, int64_t zero_point) {
TORCH_CHECK(qa.ndimension() > 0, "qnnpack_add(): Got empty input tensor.");
Tensor qa_contig = qa.contiguous(qa.suggest_memory_format());
// Reason for use qa's memory format for qb is that for the underlying
// kernel can flatten all the dims and iterate over both the tensors.
// In most cases, both qa and qb are in same memory format.
// When they are not there is a copy overhead to make it contiguous
// in qa's memory format.
Tensor qb_contig = qb.contiguous(qa.suggest_memory_format());
const auto a_zero_point = qa_contig.q_zero_point();
const auto b_zero_point = qb_contig.q_zero_point();
const auto a_scale = qa_contig.q_scale();
const auto b_scale = qb_contig.q_scale();
Tensor qy = at::native::empty_affine_quantized(
qa_contig.sizes(),
at::device(kCPU).dtype(kQUInt8).memory_format(qa.suggest_memory_format()),
scale,
zero_point,
c10::nullopt);
if (qa_contig.size(0) == 0) {
return qy;
}
initQNNPACK();
pytorch_qnnp_operator_t qnnpack_operator{nullptr};
size_t num_elems = qa_contig.numel() / qa_contig.size(0);
auto output_min = ReLUFused
? activationLimits(scale, zero_point, Activation::RELU)
.first
: std::numeric_limits<uint8_t>::min();
auto output_max = ReLUFused
? activationLimits(scale, zero_point, Activation::RELU)
.second
: std::numeric_limits<uint8_t>::max();
const pytorch_qnnp_status createStatus = pytorch_qnnp_create_add_nc_q8(
num_elems /* input size */,
a_zero_point /* a zero_point */,
a_scale /* a scale */,
b_zero_point /* b zero_point */,
b_scale /* b scale */,
static_cast<uint8_t>(zero_point) /* sum zero_point */,
scale /* sum scale */,
output_min /* output min */,
output_max /* output max */,
0 /* flags */,
&qnnpack_operator);
TORCH_INTERNAL_ASSERT(
createStatus == pytorch_qnnp_status_success,
"failed to create QNNPACK Add operator");
std::unique_ptr<pytorch_qnnp_operator, QnnpackOperatorDeleter>
qnnpack_uniq_ptr(qnnpack_operator);
const pytorch_qnnp_status setupStatus = pytorch_qnnp_setup_add_nc_q8(
qnnpack_operator /* add op */,
qa_contig.size(0) /* batch size */,
(uint8_t*)qa_contig.data_ptr<c10::quint8>() /* a data */,
num_elems /* A stride */,
(uint8_t*)qb_contig.data_ptr<c10::quint8>() /* b data */,
num_elems /* B stride */,
(uint8_t*)qy.data_ptr<c10::quint8>() /* output data */,
num_elems /* sum stride */);
TORCH_INTERNAL_ASSERT(
setupStatus == pytorch_qnnp_status_success,
"failed to setup QNNPACK Add operator");
pthreadpool_t threadpool = caffe2::pthreadpool_();
const pytorch_qnnp_status runStatus =
pytorch_qnnp_run_operator(qnnpack_operator, threadpool);
TORCH_INTERNAL_ASSERT(
runStatus == pytorch_qnnp_status_success,
"failed to run QNNPACK Add operator");
return qy;
}
#endif
template <bool ReLUFused = false>
Tensor qadd(Tensor qa, Tensor qb, double scale, int64_t zero_point) {
check_inputs(qa, qb);
#ifdef USE_PYTORCH_QNNPACK
if (at::globalContext().qEngine() == at::QEngine::QNNPACK &&
qa.scalar_type() == kQUInt8 && qb.scalar_type() == kQUInt8) {
return qnnpack_add<ReLUFused>(qa, qb, scale, zero_point);
}
#endif
auto qc = at::_empty_affine_quantized(
qa.sizes(),
at::device(kCPU)
.dtype(qa.scalar_type())
.memory_format(qa.suggest_memory_format()),
scale,
zero_point,
c10::nullopt);
return _add_out<ReLUFused>(qc, qa, qb);
}
template <bool ReLUFused = false>
Tensor qadd_out(Tensor qa, Tensor qb, Tensor out) {
check_inputs(qa, qb);
check_inputs(qa, out);
return _add_out<ReLUFused>(out, qa, qb);
}
template <bool ReLUFused = false>
Tensor qadd_scalar(Tensor qa, Scalar b) {
TORCH_CHECK(qa.qscheme() == kPerTensorAffine ||
qa.qscheme() == kPerTensorSymmetric,
"Only per tensor quantization is supported in Add.");
auto qc = at::empty_like(qa, qa.suggest_memory_format());
return _add_scalar_out<ReLUFused>(qc, qa, b);
}
template <bool ReLUFused = false>
Tensor qadd_scalar2(Scalar b, Tensor qa) {
TORCH_CHECK(qa.qscheme() == kPerTensorAffine ||
qa.qscheme() == kPerTensorSymmetric,
"Only per tensor quantization is supported in Add.");
auto qc = at::empty_like(qa, qa.suggest_memory_format());
return _add_scalar_out<ReLUFused>(qc, qa, b);
}
template <bool ReLUFused = false>
Tensor qadd_scalar_out(Tensor qa, Scalar b, Tensor out) {
check_inputs(qa, out);
return _add_scalar_out<ReLUFused>(out, qa, b);
}
// `torch.jit.trace` will trace Scalar as Tensor
// This can be removed after broadcast is supported and
// all variations of `quantized::add` is merged into `quantized::add`
template <bool ReLUFused = false>
Tensor qadd_scalar_tensor(Tensor qa, Tensor b) {
return qadd_scalar(qa, b.item());
}
// `torch.jit.trace` will trace Scalar as Tensor
// This can be removed after broadcast is supported and
// all variations of `quantized::add` is merged into `quantized::add`
template <bool ReLUFused = false>
Tensor qadd_scalar_tensor_out(Tensor qa, Tensor b, Tensor out) {
return qadd_scalar_out(qa, b.item(), out);
}
TORCH_LIBRARY_IMPL(quantized, QuantizedCPU, m) {
m.impl(TORCH_SELECTIVE_NAME("quantized::add"), TORCH_FN(qadd</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add.out"), TORCH_FN(qadd_out</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add.Scalar"), TORCH_FN(qadd_scalar</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add.Scalar2"), TORCH_FN(qadd_scalar2</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add.Scalar_out"), TORCH_FN(qadd_scalar_out</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu"), TORCH_FN(qadd</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu.out"), TORCH_FN(qadd_out</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu.Scalar"), TORCH_FN(qadd_scalar</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu.Scalar2"), TORCH_FN(qadd_scalar2</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu.Scalar_out"), TORCH_FN(qadd_scalar_out</*ReLUFused=*/true>));
// deprecated functions, kept for backward compatibility
m.impl(TORCH_SELECTIVE_NAME("quantized::add_out"), TORCH_FN(qadd_out</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_relu_out"), TORCH_FN(qadd_out</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar"), TORCH_FN(qadd_scalar</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_relu"), TORCH_FN(qadd_scalar</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_out"), TORCH_FN(qadd_scalar_out</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_relu_out"), TORCH_FN(qadd_scalar_out</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar.Tensor"), TORCH_FN(qadd_scalar_tensor</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_relu.Tensor"), TORCH_FN(qadd_scalar_tensor</*ReLUFused=*/true>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_out.Tensor"), TORCH_FN(qadd_scalar_tensor_out</*ReLUFused=*/false>));
m.impl(TORCH_SELECTIVE_NAME("quantized::add_scalar_relu_out.Tensor"), TORCH_FN(qadd_scalar_tensor_out</*ReLUFused=*/true>));
}
TORCH_LIBRARY_IMPL(_quantized, QuantizedCPU, m) {
m.impl(TORCH_SELECTIVE_NAME("_quantized::add"), TORCH_FN(qadd</*ReLUFused=*/false>));
}
} // namespace
}} // namespace at::native