blob: f0bcb0ed7f97f0bfd13d9d4d8b88cbda970131bb [file] [log] [blame]
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OperationsUtils"
18
19#include "OperationsUtils.h"
Lev Proleev0ca95202019-10-23 11:40:41 +010020
21#include <algorithm>
22#include <cmath>
23#include <limits>
24#include <sstream>
25#include <vector>
26
Miao Wangcd67a3c2017-08-02 18:58:17 -070027#include "Operations.h"
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -070028#include "Utils.h"
29
30namespace android {
31namespace nn {
32
Slava Shklyaeva6944252018-11-06 15:32:44 +000033namespace {
34
Michael Butler6bf05b22019-07-11 11:45:01 -070035using namespace hal;
36
Slava Shklyaeva6944252018-11-06 15:32:44 +000037bool validateOperandTypes(const std::vector<OperandType>& expectedTypes, const char* tag,
38 uint32_t operandCount,
39 std::function<OperandType(uint32_t)> getOperandType) {
40 NN_RET_CHECK_EQ(operandCount, expectedTypes.size());
41 for (uint32_t i = 0; i < operandCount; ++i) {
42 OperandType type = getOperandType(i);
43 NN_RET_CHECK(type == expectedTypes[i])
44 << "Invalid " << tag << " tensor type " << toString(type) << " for " << tag << " "
45 << i << ", expected " << toString(expectedTypes[i]);
46 }
47 return true;
48}
49
Lev Proleevbdf58412019-10-23 17:24:57 +010050void CalculateActivationRangeImpl(int32_t activation, const Shape& outputShape, int32_t qmin,
51 int32_t qmax, int32_t* act_min, int32_t* act_max) {
52 const auto scale = outputShape.scale;
53 const auto zero_point = outputShape.offset;
54
55 auto quantize = [scale, zero_point](float f) {
56 return zero_point + static_cast<int32_t>(std::round(f / scale));
57 };
58
59 if (activation == kActivationRelu) {
60 *act_min = std::max(qmin, quantize(0.0));
61 *act_max = qmax;
62 } else if (activation == kActivationRelu6) {
63 *act_min = std::max(qmin, quantize(0.0));
64 *act_max = std::min(qmax, quantize(6.0));
65 } else if (activation == kActivationRelu1) {
66 *act_min = std::max(qmin, quantize(-1.0));
67 *act_max = std::min(qmax, quantize(1.0));
68 } else if (activation == kActivationNone) {
69 *act_min = qmin;
70 *act_max = qmax;
71 } else {
72 LOG(ERROR) << "Unsupported fused activation function.";
73 }
74}
75
Slava Shklyaeva6944252018-11-06 15:32:44 +000076} // namespace
77
78bool validateInputTypes(const IOperationValidationContext* context,
79 const std::vector<OperandType>& expectedTypes) {
80 return validateOperandTypes(expectedTypes, "input", context->getNumInputs(),
81 [context](uint32_t index) { return context->getInputType(index); });
82}
83
84bool validateOutputTypes(const IOperationValidationContext* context,
85 const std::vector<OperandType>& expectedTypes) {
86 return validateOperandTypes(
87 expectedTypes, "output", context->getNumOutputs(),
88 [context](uint32_t index) { return context->getOutputType(index); });
89}
90
91bool validateHalVersion(const IOperationValidationContext* context,
92 HalVersion minSupportedHalVersion) {
93 if (context->getHalVersion() < minSupportedHalVersion) {
Slava Shklyaev57f2c712019-09-30 16:04:43 +010094 std::ostringstream message;
95 message << "Operation " << context->getOperationName() << " with inputs {";
96 for (uint32_t i = 0, n = context->getNumInputs(); i < n; ++i) {
97 if (i != 0) {
98 message << ", ";
99 }
100 message << toString(context->getInputType(i));
101 }
102 message << "} and outputs {";
103 for (uint32_t i = 0, n = context->getNumOutputs(); i < n; ++i) {
104 if (i != 0) {
105 message << ", ";
106 }
107 message << toString(context->getOutputType(i));
108 }
109 message << "} is only supported since " << toString(minSupportedHalVersion)
110 << " (validating using " << toString(context->getHalVersion()) << ")";
111 NN_RET_CHECK_FAIL() << message.str();
Slava Shklyaeva6944252018-11-06 15:32:44 +0000112 }
113 return true;
114}
115
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700116bool SameShape(const Shape& in1, const Shape& in2) {
Miao Wang9d04c2d2017-07-25 17:06:18 -0700117 if (in1.type != in2.type || in1.dimensions.size() != in2.dimensions.size()) {
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700118 return false;
119 }
Miao Wang9d04c2d2017-07-25 17:06:18 -0700120 for (size_t i = 0; i < in1.dimensions.size(); i++) {
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700121 if (in1.dimensions[i] != in2.dimensions[i]) {
122 return false;
123 }
124 }
125 return true;
126}
127
Miao Wang9d04c2d2017-07-25 17:06:18 -0700128bool SetShape(const Shape& in, Shape* out) {
Xusong Wang603ebb62018-11-07 15:03:29 -0800129 if (in.type != out->type) {
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700130 return false;
131 }
Miao Wang9d04c2d2017-07-25 17:06:18 -0700132 out->dimensions = in.dimensions;
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700133 return true;
134}
135
136uint32_t getNumberOfElements(const Shape& shape) {
137 uint32_t count = 1;
Miao Wang9d04c2d2017-07-25 17:06:18 -0700138 for (size_t i = 0; i < shape.dimensions.size(); i++) {
Jean-Luc Brouilleta09d6992017-07-12 01:37:27 -0700139 count *= shape.dimensions[i];
140 }
141 return count;
142}
143
Michael Butlerf20c5b52019-07-22 18:59:46 -0700144uint32_t getNumberOfElements(const Shape& shape, size_t firstAxisInclusive,
Slava Shklyaeva2c9a102018-09-17 11:58:40 +0100145 size_t lastAxisExclusive) {
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100146 nnAssert(0 <= firstAxisInclusive);
147 nnAssert(firstAxisInclusive <= lastAxisExclusive);
148 nnAssert(lastAxisExclusive <= shape.dimensions.size());
Slava Shklyaeva2c9a102018-09-17 11:58:40 +0100149 uint32_t count = 1;
150 for (size_t i = firstAxisInclusive; i < lastAxisExclusive; i++) {
151 count *= shape.dimensions[i];
152 }
153 return count;
154}
155
Jean-Luc Brouillet873c0082017-07-25 00:17:50 -0700156uint32_t getNumberOfDimensions(const Shape& shape) {
Miao Wang9d04c2d2017-07-25 17:06:18 -0700157 return shape.dimensions.size();
Jean-Luc Brouillet873c0082017-07-25 00:17:50 -0700158}
159
160uint32_t getSizeOfDimension(const Shape& shape, uint32_t dimensionIdx) {
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100161 nnAssert(0 <= dimensionIdx && dimensionIdx < shape.dimensions.size());
Jean-Luc Brouillet873c0082017-07-25 00:17:50 -0700162 return shape.dimensions[dimensionIdx];
163}
164
Lev Proleev88a3bba2020-03-18 15:20:46 +0000165uint32_t hasKnownRank(const Shape& shape) {
166 return !shape.dimensions.empty();
167}
168
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100169bool handleNegativeAxis(int32_t numberOfDimensions, int32_t* axis) {
170 NN_CHECK(-numberOfDimensions <= *axis && *axis < numberOfDimensions);
171 if (*axis < 0) {
172 *axis += numberOfDimensions;
Slava Shklyaev39709182018-09-27 18:25:43 +0100173 }
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100174 return true;
Slava Shklyaev9057e9f2018-09-27 15:13:47 +0100175}
176
Lev Proleevbdf58412019-10-23 17:24:57 +0100177bool QuantizeMultiplier(double double_multiplier, int32_t* quantized_multiplier, int32_t* shift) {
Lev Proleev1431a6f2019-03-07 18:02:46 +0000178 if (double_multiplier == 0.) {
179 *quantized_multiplier = 0;
180 *shift = 0;
181 return true;
182 }
183 const double q = std::frexp(double_multiplier, shift);
184 auto q_fixed = static_cast<int64_t>(std::round(q * (1ll << 31)));
185 NN_RET_CHECK(q_fixed <= (1ll << 31));
186 if (q_fixed == (1ll << 31)) {
187 q_fixed /= 2;
188 ++*shift;
189 }
190 NN_RET_CHECK_LE(q_fixed, std::numeric_limits<int32_t>::max());
Viet Dangd0137f72019-12-04 16:18:08 +0000191 // A shift amount smaller than -31 would cause all bits to be shifted out
192 // and thus all results would be zero. We implement that instead with
193 // q_fixed==0, so as to avoid hitting issues with right-shift
194 // operations with shift amounts greater than 31. Note that this happens
195 // roughly when abs(double_multiplier) < 2^-31 and the present handling means
196 // that we're effectively flushing tiny double_multiplier's to zero.
197 // We could conceivably handle values in the range (roughly) [32, 63]
198 // as 'denormals' i.e. (shift==0, q_fixed < 2^30). In that point of view
199 // the present handling is just doing 'flush denormals to zero'. We could
200 // reconsider and actually generate nonzero denormals if a need arises.
201 if (*shift < -31) {
202 *shift = 0;
203 q_fixed = 0;
204 }
Lev Proleev1431a6f2019-03-07 18:02:46 +0000205 *quantized_multiplier = static_cast<int32_t>(q_fixed);
206 return true;
207}
208
Lev Proleevbdf58412019-10-23 17:24:57 +0100209bool QuantizeMultiplierSmallerThanOneExp(double double_multiplier, int32_t* quantized_multiplier,
210 int32_t* left_shift) {
211 NN_RET_CHECK(double_multiplier > 0.);
212 NN_RET_CHECK(double_multiplier < 1.);
213 NN_RET_CHECK(QuantizeMultiplier(double_multiplier, quantized_multiplier, left_shift));
214 NN_RET_CHECK(*left_shift <= 0);
215 return true;
216}
217
Michael Butlerf20c5b52019-07-22 18:59:46 -0700218bool QuantizeMultiplierSmallerThanOne(double double_multiplier, int32_t* quantized_multiplier,
Miao Wangcd67a3c2017-08-02 18:58:17 -0700219 int32_t* right_shift) {
Miao Wang4d96fa42017-09-21 17:04:31 -0700220 NN_OPS_CHECK(double_multiplier >= 0.);
221 NN_OPS_CHECK(double_multiplier < 1.);
Miao Wangcd67a3c2017-08-02 18:58:17 -0700222 if (double_multiplier == 0.) {
223 *quantized_multiplier = 0;
224 *right_shift = 0;
Miao Wang4d96fa42017-09-21 17:04:31 -0700225 return true;
Miao Wangcd67a3c2017-08-02 18:58:17 -0700226 }
Miao Wang4d96fa42017-09-21 17:04:31 -0700227 NN_OPS_CHECK(double_multiplier > 0.);
Miao Wangcd67a3c2017-08-02 18:58:17 -0700228 const double q = std::frexp(double_multiplier, right_shift);
229 *right_shift *= -1;
Chih-Hung Hsiehbafa1382018-12-10 14:08:34 -0800230 int64_t q_fixed = static_cast<int64_t>(std::round(q * (1LL << 31)));
231 NN_OPS_CHECK(q_fixed <= (1LL << 31));
232 if (q_fixed == (1LL << 31)) {
Miao Wangcd67a3c2017-08-02 18:58:17 -0700233 q_fixed /= 2;
234 --*right_shift;
235 }
Miao Wang4d96fa42017-09-21 17:04:31 -0700236 NN_OPS_CHECK(*right_shift >= 0);
237 NN_OPS_CHECK(q_fixed <= std::numeric_limits<int32_t>::max());
Miao Wangcd67a3c2017-08-02 18:58:17 -0700238 *quantized_multiplier = static_cast<int32_t>(q_fixed);
Miao Wang4d96fa42017-09-21 17:04:31 -0700239 return true;
Miao Wangcd67a3c2017-08-02 18:58:17 -0700240}
241
Michael Butlerf20c5b52019-07-22 18:59:46 -0700242bool QuantizeMultiplierGreaterThanOne(double double_multiplier, int32_t* quantized_multiplier,
Miao Wangcd67a3c2017-08-02 18:58:17 -0700243 int* left_shift) {
Miao Wang4d96fa42017-09-21 17:04:31 -0700244 NN_OPS_CHECK(double_multiplier > 1.);
Miao Wangcd67a3c2017-08-02 18:58:17 -0700245 const double q = std::frexp(double_multiplier, left_shift);
Chih-Hung Hsiehbafa1382018-12-10 14:08:34 -0800246 int64_t q_fixed = static_cast<int64_t>(std::round(q * (1LL << 31)));
247 NN_OPS_CHECK(q_fixed <= (1LL << 31));
248 if (q_fixed == (1LL << 31)) {
Miao Wangcd67a3c2017-08-02 18:58:17 -0700249 q_fixed /= 2;
250 ++*left_shift;
251 }
Miao Wang4d96fa42017-09-21 17:04:31 -0700252 NN_OPS_CHECK(*left_shift >= 0);
253 NN_OPS_CHECK(q_fixed <= std::numeric_limits<int32_t>::max());
Miao Wangcd67a3c2017-08-02 18:58:17 -0700254 *quantized_multiplier = static_cast<int32_t>(q_fixed);
Miao Wang4d96fa42017-09-21 17:04:31 -0700255 return true;
Miao Wangcd67a3c2017-08-02 18:58:17 -0700256}
257
Przemyslaw Szczepaniakfdfeec92019-05-02 10:03:44 +0100258bool GetQuantizedConvolutionMultipler(const Shape& inputShape, const Shape& filterShape,
259 const Shape& biasShape, const Shape& outputShape,
260 double* multiplier) {
261 // Upcast bias and input_product to double
262 const double input_product_scale = inputShape.scale * filterShape.scale;
263 const double bias_scale = biasShape.scale;
Miao Wangcd67a3c2017-08-02 18:58:17 -0700264
265 // The following conditions must be guaranteed by the training pipeline.
Miao Wang4d96fa42017-09-21 17:04:31 -0700266 NN_OPS_CHECK(std::abs(input_product_scale - bias_scale) <=
Michael Butlerf20c5b52019-07-22 18:59:46 -0700267 1e-6 * std::min(input_product_scale, bias_scale));
Miao Wang4d96fa42017-09-21 17:04:31 -0700268 NN_OPS_CHECK(input_product_scale >= 0);
Przemyslaw Szczepaniakfdfeec92019-05-02 10:03:44 +0100269 *multiplier = input_product_scale / outputShape.scale;
Miao Wang4d96fa42017-09-21 17:04:31 -0700270 return true;
Miao Wangcd67a3c2017-08-02 18:58:17 -0700271}
272
Michael Butlerf20c5b52019-07-22 18:59:46 -0700273void CalculateActivationRangeUint8(int32_t activation, const Shape& outputShape, int32_t* act_min,
Miao Wangcd67a3c2017-08-02 18:58:17 -0700274 int32_t* act_max) {
275 const int32_t qmin = std::numeric_limits<uint8_t>::min();
276 const int32_t qmax = std::numeric_limits<uint8_t>::max();
277
Lev Proleevbdf58412019-10-23 17:24:57 +0100278 CalculateActivationRangeImpl(activation, outputShape, qmin, qmax, act_min, act_max);
279}
Miao Wangcd67a3c2017-08-02 18:58:17 -0700280
Lev Proleevbdf58412019-10-23 17:24:57 +0100281void CalculateActivationRangeInt8(int32_t activation, const Shape& outputShape, int32_t* act_min,
282 int32_t* act_max) {
283 const int32_t qmin = std::numeric_limits<int8_t>::min();
284 const int32_t qmax = std::numeric_limits<int8_t>::max();
Miao Wangcd67a3c2017-08-02 18:58:17 -0700285
Lev Proleevbdf58412019-10-23 17:24:57 +0100286 CalculateActivationRangeImpl(activation, outputShape, qmin, qmax, act_min, act_max);
Miao Wang658dc372017-12-14 15:01:31 -0800287}
288
Michael Butlerf20c5b52019-07-22 18:59:46 -0700289void CalculateActivationRangeFloat(int32_t activation, float* activation_min,
Miao Wang658dc372017-12-14 15:01:31 -0800290 float* activation_max) {
291 if (activation == kActivationRelu) {
292 *activation_min = 0.f;
293 *activation_max = std::numeric_limits<float>::max();
294 } else if (activation == kActivationRelu6) {
295 *activation_min = 0.f;
296 *activation_max = 6.f;
297 } else if (activation == kActivationRelu1) {
298 *activation_min = -1.f;
299 *activation_max = 1.f;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700300 } else if (activation == kActivationNone) {
Miao Wang658dc372017-12-14 15:01:31 -0800301 *activation_min = std::numeric_limits<float>::lowest();
302 *activation_max = std::numeric_limits<float>::max();
303 } else {
304 LOG(ERROR) << "Unsupported fused activation function.";
Miao Wangcd67a3c2017-08-02 18:58:17 -0700305 }
306}
307
308int32_t CalculateInputRadius(int input_integer_bits, int input_left_shift) {
309 const double max_input_rescaled = 1.0 * ((1 << input_integer_bits) - 1) *
Chih-Hung Hsiehbafa1382018-12-10 14:08:34 -0800310 (1LL << (31 - input_integer_bits)) /
311 (1LL << input_left_shift);
Miao Wangcd67a3c2017-08-02 18:58:17 -0700312 // Tighten bound using floor. Suppose that we could use the exact value.
313 // After scaling the difference, the result would be at the maximum. Thus we
314 // must ensure that our value has lower magnitude.
315 return static_cast<int32_t>(std::floor(max_input_rescaled));
316}
317
Xusong Wangd0cc11f2019-04-12 13:38:49 -0700318void calculateExplicitPaddingImpl(int32_t in_size, int32_t stride, int32_t dilation_factor,
319 int32_t filter_size, int32_t padding_implicit,
320 bool isTransposeConv, int32_t* padding_head,
321 int32_t* padding_tail) {
322 *padding_head = 0;
323 *padding_tail = 0;
324
325 int32_t effective_filter_size = (filter_size - 1) * dilation_factor + 1;
326
327 if (padding_implicit == kPaddingSame) {
328 int32_t out_size = (in_size + stride - 1) / stride;
329 int32_t tmp = (out_size - 1) * stride + effective_filter_size;
330 if (tmp > in_size) {
331 *padding_head = (tmp - in_size) / 2;
332 *padding_tail = (tmp - in_size) - *padding_head;
333 }
334 // For transpose conv, make padding tail fit tightly to the end of the last stride.
335 if (isTransposeConv) {
336 *padding_tail = (tmp - in_size) - *padding_head;
337 }
338 }
339}
340
Lev Proleev8e3e09f2018-10-18 14:33:39 +0100341bool calculateBroadcastedShape(const Shape& in1, const Shape& in2, Shape* out) {
Xusong Wangced4b702019-03-14 13:55:20 -0700342 NN_RET_CHECK(in1.type == in2.type);
Lev Proleev8e3e09f2018-10-18 14:33:39 +0100343 uint32_t numberOfDims1 = getNumberOfDimensions(in1);
344 uint32_t numberOfDims2 = getNumberOfDimensions(in2);
345 uint32_t maxDims = std::max(numberOfDims1, numberOfDims2);
346 out->dimensions = std::vector<uint32_t>(maxDims);
347 for (uint32_t i = 1; i <= maxDims; i++) {
348 uint32_t dim1 = 1;
349 if (i <= numberOfDims1) {
350 dim1 = getSizeOfDimension(in1, numberOfDims1 - i);
351 }
352 uint32_t dim2 = 1;
353 if (i <= numberOfDims2) {
354 dim2 = getSizeOfDimension(in2, numberOfDims2 - i);
355 }
356 if (dim1 != dim2 && dim1 != 1 && dim2 != 1) {
357 LOG(ERROR) << "Dimensions mismatch for broadcast:\n"
358 << "First tensor: dimension " << numberOfDims1 - i << " of size " << dim1
David Gross94597f02020-08-14 15:30:49 -0700359 << "\nSecond tensor: dimension " << numberOfDims2 - i << " of size " << dim2;
Lev Proleev8e3e09f2018-10-18 14:33:39 +0100360 return false;
361 }
Xusong Wangced4b702019-03-14 13:55:20 -0700362 out->dimensions[maxDims - i] = (dim1 == 1) ? dim2 : dim1;
Lev Proleev8e3e09f2018-10-18 14:33:39 +0100363 }
364 return true;
365}
366
Przemyslaw Szczepaniak14c12132019-11-28 11:25:21 +0000367template <>
368uint8_t requantize<uint8_t>(uint8_t value, const Shape& oldShape, const Shape& newShape) {
Lev Proleev5d7c6b42018-12-10 11:47:19 +0000369 double doubleValue = (value - oldShape.offset) * oldShape.scale;
Xusong Wang9a8dde72019-04-24 12:49:07 -0700370 double doubleRet = doubleValue / newShape.scale + newShape.offset;
371 if (doubleRet < 0) return 0;
372 if (doubleRet > 255) return 255;
Xusong Wang7c1bc2c2019-05-30 18:23:33 -0700373 return static_cast<uint8_t>(std::round(doubleRet));
Lev Proleev5d7c6b42018-12-10 11:47:19 +0000374}
375
Przemyslaw Szczepaniak14c12132019-11-28 11:25:21 +0000376template <>
377int8_t requantize<int8_t>(int8_t value, const Shape& oldShape, const Shape& newShape) {
Lev Proleev0ca95202019-10-23 11:40:41 +0100378 double doubleValue = (value - oldShape.offset) * oldShape.scale;
379 double doubleRet = doubleValue / newShape.scale + newShape.offset;
380 if (doubleRet < -128) return -128;
381 if (doubleRet > 127) return 127;
382 return static_cast<int8_t>(std::round(doubleRet));
383}
384
Michael Butlerf20c5b52019-07-22 18:59:46 -0700385bool reshapePrepare(const Shape& input, const int32_t* targetDims, const int32_t targetDimsSize,
Miao Wang13048b92017-09-11 14:16:14 -0700386 Shape* output) {
387 // Reshape allows one of the targetDims components to have the
388 // special -1 value, meaning it will be calculated automatically based on the
389 // input. Here we calculate what that dimension should be so that the number
390 // of output elements in the same as the number of input elements.
Michael Butlerf20c5b52019-07-22 18:59:46 -0700391 int32_t numInputElements = (int32_t)getNumberOfElements(input);
Miao Wang13048b92017-09-11 14:16:14 -0700392
393 std::vector<uint32_t> outDims(targetDimsSize);
394 int32_t numOutputElements = 1;
395 int32_t strechDim = -1;
396 for (int32_t i = 0; i < targetDimsSize; ++i) {
397 int32_t value = targetDims[i];
398 if (value == -1) {
Miao Wang4d96fa42017-09-21 17:04:31 -0700399 NN_OPS_CHECK(strechDim == -1);
Miao Wang13048b92017-09-11 14:16:14 -0700400 strechDim = i;
401 } else {
402 numOutputElements *= value;
403 outDims[i] = (uint32_t)value;
404 }
405 }
406 if (strechDim != -1) {
407 int32_t strechValue = numInputElements / numOutputElements;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700408 outDims[strechDim] = (uint32_t)strechValue;
Miao Wang13048b92017-09-11 14:16:14 -0700409 numOutputElements *= strechValue;
410 }
411
Miao Wang4d96fa42017-09-21 17:04:31 -0700412 NN_OPS_CHECK(numInputElements == numOutputElements);
Miao Wang13048b92017-09-11 14:16:14 -0700413
414 output->type = input.type;
415 output->dimensions = outDims;
416 output->offset = input.offset;
417 output->scale = input.scale;
418
419 return true;
420}
421
Michael Butlerf20c5b52019-07-22 18:59:46 -0700422bool depthToSpacePrepare(const Shape& input, int32_t blockSize, Shape* output) {
Miao Wang4d96fa42017-09-21 17:04:31 -0700423 NN_OPS_CHECK(getNumberOfDimensions(input) == 4);
424 NN_OPS_CHECK(blockSize > 0);
Miao Wang13048b92017-09-11 14:16:14 -0700425
Michael Butlerf20c5b52019-07-22 18:59:46 -0700426 uint32_t batches = getSizeOfDimension(input, 0);
427 uint32_t height = getSizeOfDimension(input, 1);
428 uint32_t width = getSizeOfDimension(input, 2);
Miao Wang13048b92017-09-11 14:16:14 -0700429 uint32_t channels = getSizeOfDimension(input, 3);
430
Miao Wang4d96fa42017-09-21 17:04:31 -0700431 NN_OPS_CHECK(channels % (blockSize * blockSize) == 0);
Miao Wang13048b92017-09-11 14:16:14 -0700432 output->type = input.type;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700433 output->dimensions = {batches, height * blockSize, width * blockSize,
Miao Wang13048b92017-09-11 14:16:14 -0700434 channels / (blockSize * blockSize)};
435 output->offset = input.offset;
436 output->scale = input.scale;
437
438 return true;
439}
440
Michael Butlerf20c5b52019-07-22 18:59:46 -0700441bool spaceToDepthPrepare(const Shape& input, int32_t blockSize, Shape* output) {
Miao Wang4d96fa42017-09-21 17:04:31 -0700442 NN_OPS_CHECK(getNumberOfDimensions(input) == 4);
443 NN_OPS_CHECK(blockSize > 0);
Miao Wang13048b92017-09-11 14:16:14 -0700444
Michael Butlerf20c5b52019-07-22 18:59:46 -0700445 uint32_t batches = getSizeOfDimension(input, 0);
446 uint32_t height = getSizeOfDimension(input, 1);
447 uint32_t width = getSizeOfDimension(input, 2);
Miao Wang13048b92017-09-11 14:16:14 -0700448 uint32_t channels = getSizeOfDimension(input, 3);
449
Miao Wang4d96fa42017-09-21 17:04:31 -0700450 NN_OPS_CHECK(height % blockSize == 0);
451 NN_OPS_CHECK(width % blockSize == 0);
Miao Wang13048b92017-09-11 14:16:14 -0700452
453 output->type = input.type;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700454 output->dimensions = {batches, height / blockSize, width / blockSize,
Miao Wang13048b92017-09-11 14:16:14 -0700455 channels * (blockSize * blockSize)};
456 output->offset = input.offset;
457 output->scale = input.scale;
458
459 return true;
460}
461
Michael Butlerf20c5b52019-07-22 18:59:46 -0700462bool embeddingLookupPrepare(const Shape& valueShape, const Shape& lookupShape, Shape* outputShape) {
Yang Nie3cc73d2017-09-27 10:26:52 -0700463 NN_OPS_CHECK(getNumberOfDimensions(valueShape) >= 2);
464 NN_OPS_CHECK(getNumberOfDimensions(lookupShape) == 1);
465
Michael Butlerf20c5b52019-07-22 18:59:46 -0700466 const uint32_t columns = getSizeOfDimension(valueShape, 1);
Michael Butlerf20c5b52019-07-22 18:59:46 -0700467 const uint32_t lookups = getSizeOfDimension(lookupShape, 0);
Yang Nie3cc73d2017-09-27 10:26:52 -0700468
469 outputShape->type = valueShape.type;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700470 outputShape->dimensions = {lookups, columns};
Yang Nie3cc73d2017-09-27 10:26:52 -0700471 for (uint32_t i = 2; i < getNumberOfDimensions(valueShape); i++) {
Miao Wang0cc32232017-10-09 10:43:21 -0700472 outputShape->dimensions.push_back(getSizeOfDimension(valueShape, i));
Yang Nie3cc73d2017-09-27 10:26:52 -0700473 }
474 outputShape->offset = valueShape.offset;
475 outputShape->scale = valueShape.scale;
476
477 return true;
478}
479
Michael Butlerf20c5b52019-07-22 18:59:46 -0700480bool hashtableLookupPrepare(const Shape& lookupShape, const Shape& keyShape,
481 const Shape& valueShape, Shape* outputShape, Shape* hitShape) {
Yang Nie3cc73d2017-09-27 10:26:52 -0700482 NN_OPS_CHECK(getNumberOfDimensions(lookupShape) == 1);
483 NN_OPS_CHECK(getNumberOfDimensions(keyShape) == 1);
484 NN_OPS_CHECK(getNumberOfDimensions(valueShape) >= 1);
485
Michael Butlerf20c5b52019-07-22 18:59:46 -0700486 const uint32_t lookups = getSizeOfDimension(lookupShape, 0);
Yang Nie3cc73d2017-09-27 10:26:52 -0700487 outputShape->type = valueShape.type;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700488 outputShape->dimensions = {lookups};
Yang Nie3cc73d2017-09-27 10:26:52 -0700489 for (uint32_t i = 1; i < getNumberOfDimensions(valueShape); i++) {
Miao Wang0cc32232017-10-09 10:43:21 -0700490 outputShape->dimensions.push_back(getSizeOfDimension(valueShape, i));
Yang Nie3cc73d2017-09-27 10:26:52 -0700491 }
492 outputShape->offset = valueShape.offset;
493 outputShape->scale = valueShape.scale;
494
495 hitShape->type = OperandType::TENSOR_QUANT8_ASYMM;
Michael Butlerf20c5b52019-07-22 18:59:46 -0700496 hitShape->dimensions = {lookups};
Yang Nie3cc73d2017-09-27 10:26:52 -0700497 hitShape->offset = 0;
498 hitShape->scale = 1.f;
499
500 return true;
501}
502
Michael Butlerf20c5b52019-07-22 18:59:46 -0700503bool padPrepare(const Shape& input, const int32_t* paddingsData, const Shape& paddingsShape,
Miao Wang15395d62018-01-21 02:39:41 -0800504 Shape* output) {
Miao Wang15395d62018-01-21 02:39:41 -0800505 uint32_t numInputDims = getNumberOfDimensions(input);
Miao Wang15395d62018-01-21 02:39:41 -0800506
507 // paddings need to be provided as a 2-D int32 tensor.
508 NN_OPS_CHECK(paddingsShape.type == OperandType::TENSOR_INT32);
509 NN_OPS_CHECK(getNumberOfDimensions(paddingsShape) == 2);
510 NN_OPS_CHECK(getSizeOfDimension(paddingsShape, 0) == numInputDims);
511 NN_OPS_CHECK(getSizeOfDimension(paddingsShape, 1) == 2);
512
513 std::vector<uint32_t> outDims(numInputDims);
514 for (uint32_t i = 0; i < numInputDims; ++i) {
515 int32_t beforePadding = *paddingsData++;
516 int32_t afterPadding = *paddingsData++;
517 // Pad value has to be greater than equal to 0.
518 NN_OPS_CHECK(beforePadding >= 0 && afterPadding >= 0);
519 outDims[i] = beforePadding + getSizeOfDimension(input, i) + afterPadding;
520 }
521 output->type = input.type;
522 output->dimensions = outDims;
523 output->offset = input.offset;
524 output->scale = input.scale;
525
526 return true;
527}
528
Michael Butlerf20c5b52019-07-22 18:59:46 -0700529bool batchToSpacePrepare(const Shape& input, const int32_t* blockSizeData,
530 const Shape& blockSizeShape, Shape* output) {
Miao Wang15395d62018-01-21 02:39:41 -0800531 // Only 4D NHWC tensors are supported.
532 NN_OPS_CHECK(getNumberOfDimensions(input) == 4);
533
534 // blockSize need to be provided as a 1-D int32 tensor.
535 NN_OPS_CHECK(blockSizeShape.type == OperandType::TENSOR_INT32);
536 NN_OPS_CHECK(getNumberOfDimensions(blockSizeShape) == 1);
537 // Only applies to spatial dimensions.
538 NN_OPS_CHECK(getSizeOfDimension(blockSizeShape, 0) == 2);
539
Michael Butlerf20c5b52019-07-22 18:59:46 -0700540 uint32_t batches = getSizeOfDimension(input, 0);
541 uint32_t height = getSizeOfDimension(input, 1);
542 uint32_t width = getSizeOfDimension(input, 2);
Miao Wang15395d62018-01-21 02:39:41 -0800543 uint32_t channels = getSizeOfDimension(input, 3);
544
545 NN_OPS_CHECK(batches % (blockSizeData[0] * blockSizeData[1]) == 0);
546 output->type = input.type;
547 output->dimensions = {batches / (blockSizeData[0] * blockSizeData[1]),
Michael Butlerf20c5b52019-07-22 18:59:46 -0700548 height * blockSizeData[0], width * blockSizeData[1], channels};
Miao Wang15395d62018-01-21 02:39:41 -0800549 output->offset = input.offset;
550 output->scale = input.scale;
551
552 return true;
553}
554
Michael Butlerf20c5b52019-07-22 18:59:46 -0700555bool spaceToBatchPrepare(const Shape& input, const int32_t* blockSizeData,
556 const Shape& blockSizeShape, const int32_t* paddingsData,
557 const Shape& paddingsShape, Shape* output) {
Miao Wang15395d62018-01-21 02:39:41 -0800558 // Only 4D NHWC tensors are supported.
559 NN_OPS_CHECK(getNumberOfDimensions(input) == 4);
560
561 // blockSize need to be provided as a 1-D int32 tensor.
562 NN_OPS_CHECK(blockSizeShape.type == OperandType::TENSOR_INT32);
563 NN_OPS_CHECK(getNumberOfDimensions(blockSizeShape) == 1);
564 // Only applies to spatial dimensions.
565 NN_OPS_CHECK(getSizeOfDimension(blockSizeShape, 0) == 2);
566
567 // paddings need to be provided as a 2-D int32 tensor.
568 NN_OPS_CHECK(paddingsShape.type == OperandType::TENSOR_INT32);
569 NN_OPS_CHECK(getNumberOfDimensions(paddingsShape) == 2);
570 NN_OPS_CHECK(getSizeOfDimension(paddingsShape, 0) == 2);
571 NN_OPS_CHECK(getSizeOfDimension(paddingsShape, 1) == 2);
572
Michael Butlerf20c5b52019-07-22 18:59:46 -0700573 uint32_t batches = getSizeOfDimension(input, 0);
574 uint32_t height = getSizeOfDimension(input, 1);
575 uint32_t width = getSizeOfDimension(input, 2);
Miao Wang15395d62018-01-21 02:39:41 -0800576 uint32_t channels = getSizeOfDimension(input, 3);
577
578 uint32_t paddedHeight = paddingsData[0] + height + paddingsData[1];
579 uint32_t paddedWidth = paddingsData[2] + width + paddingsData[3];
580
581 NN_OPS_CHECK(paddedHeight % blockSizeData[0] == 0);
Miao Wang5fbe3e12018-02-20 14:34:00 -0800582 NN_OPS_CHECK(paddedWidth % blockSizeData[1] == 0);
Miao Wang15395d62018-01-21 02:39:41 -0800583
584 output->type = input.type;
585 output->dimensions = {batches * (blockSizeData[0] * blockSizeData[1]),
Michael Butlerf20c5b52019-07-22 18:59:46 -0700586 paddedHeight / blockSizeData[0], paddedWidth / blockSizeData[1],
Miao Wang15395d62018-01-21 02:39:41 -0800587 channels};
588 output->offset = input.offset;
589 output->scale = input.scale;
590
591 return true;
592}
593
Michael Butlerf20c5b52019-07-22 18:59:46 -0700594bool meanPrepare(const Shape& input, const int32_t* axisData, const Shape& axisShape, bool keepDims,
Miao Wang15395d62018-01-21 02:39:41 -0800595 Shape* output) {
Miao Wang15395d62018-01-21 02:39:41 -0800596 // perm need to be provided as a 1-D int32 tensor.
597 NN_OPS_CHECK(axisShape.type == OperandType::TENSOR_INT32);
598 NN_OPS_CHECK(getNumberOfDimensions(axisShape) == 1);
599
600 int32_t numInputDims = static_cast<int32_t>(getNumberOfDimensions(input));
601 int32_t axisSize = static_cast<int32_t>(getSizeOfDimension(axisShape, 0));
602
603 // Determines size of output tensor.
604 if (keepDims) {
605 std::vector<uint32_t> outDims(numInputDims);
606 for (int32_t idx = 0; idx < numInputDims; ++idx) {
607 bool isAxis = false;
608 for (int32_t axisIdx = 0; axisIdx < axisSize; ++axisIdx) {
609 if (axisData[axisIdx] == idx || axisData[axisIdx] + numInputDims == idx) {
610 isAxis = true;
611 break;
612 }
613 }
614 if (isAxis) {
615 outDims[idx] = 1;
616 } else {
617 outDims[idx] = getSizeOfDimension(input, idx);
618 }
619 }
620 output->dimensions = outDims;
621 } else {
622 // Calculates size of reducing axis.
623 int32_t numReduceAxis = axisSize;
624 for (int32_t i = 0; i < axisSize; ++i) {
625 int32_t current = axisData[i];
626 if (current < 0) {
627 current += numInputDims;
628 }
629 NN_OPS_CHECK(current >= 0 && current < numInputDims);
630 for (int32_t j = 0; j < i; ++j) {
631 int32_t previous = axisData[j];
632 if (previous < 0) {
633 previous += numInputDims;
634 }
635 if (current == previous) {
636 --numReduceAxis;
637 break;
638 }
639 }
640 }
641 // Determines output dimensions.
642 std::vector<uint32_t> outDims(numInputDims - numReduceAxis);
643 int32_t numSkipAxis = 0;
644 for (int32_t idx = 0; idx < numInputDims; ++idx) {
645 bool isAxis = false;
646 for (int32_t axisIdx = 0; axisIdx < axisSize; ++axisIdx) {
647 if (axisData[axisIdx] == idx || axisData[axisIdx] + numInputDims == idx) {
648 ++numSkipAxis;
649 isAxis = true;
650 break;
651 }
652 }
653 if (!isAxis) {
654 outDims[idx - numSkipAxis] = getSizeOfDimension(input, idx);
655 }
656 }
Lev Proleev73910832020-05-05 17:26:26 +0100657 // Handle the case when all dimensions are removed
658 if (outDims.empty()) {
659 outDims.push_back(1);
660 }
Miao Wang15395d62018-01-21 02:39:41 -0800661 output->dimensions = outDims;
662 }
663
664 output->type = input.type;
665 output->offset = input.offset;
666 output->scale = input.scale;
667
668 return true;
669}
670
Slava Shklyaeva2c9a102018-09-17 11:58:40 +0100671bool argMinMaxPrepare(const Shape& input, int32_t axis, Shape* output) {
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100672 NN_CHECK(handleNegativeAxis(input, &axis));
Slava Shklyaeva2c9a102018-09-17 11:58:40 +0100673
674 output->type = OperandType::TENSOR_INT32;
675
676 // Copy the input dimensions, omitting the axis dimension.
677 output->dimensions.clear();
Lev Proleev73910832020-05-05 17:26:26 +0100678 if (getNumberOfDimensions(input) > 1) {
679 output->dimensions.reserve(getNumberOfDimensions(input) - 1);
680 output->dimensions.insert(output->dimensions.end(), input.dimensions.begin(),
681 input.dimensions.begin() + axis);
682 output->dimensions.insert(output->dimensions.end(), input.dimensions.begin() + axis + 1,
683 input.dimensions.end());
684 } else {
685 output->dimensions.push_back(1);
686 }
Slava Shklyaeva2c9a102018-09-17 11:58:40 +0100687
688 return true;
689}
Lev Proleevdfc2f412018-09-13 16:17:58 +0100690
691bool splitPrepare(const Shape& input, int32_t axis, int32_t numOutputs,
692 std::vector<Shape>* output) {
Slava Shklyaeve9e0c432018-10-22 12:04:16 +0100693 NN_CHECK(handleNegativeAxis(input, &axis));
Lev Proleevdfc2f412018-09-13 16:17:58 +0100694
695 const int32_t sizeOfAxisToSplit = input.dimensions[axis];
696 NN_OPS_CHECK(sizeOfAxisToSplit % numOutputs == 0);
697 const int32_t sliceSize = sizeOfAxisToSplit / numOutputs;
698
699 for (int i = 0; i < numOutputs; ++i) {
700 output->at(i).type = input.type;
701 output->at(i).dimensions = input.dimensions;
702 output->at(i).dimensions[axis] = sliceSize;
703 output->at(i).offset = input.offset;
704 output->at(i).scale = input.scale;
705 }
706 return true;
707}
708
Xusong Wang5339dc32018-08-17 15:38:32 -0700709bool groupedConvPrepare(const Shape& input, const Shape& filter, const Shape& bias,
710 int32_t padding_left, int32_t padding_right, int32_t padding_top,
711 int32_t padding_bottom, int32_t stride_width, int32_t stride_height,
712 int32_t numGroups, Shape* output) {
Przemyslaw Szczepaniaka4e6a652018-12-28 11:52:32 +0000713 if (filter.type == OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL) {
Lev Proleev5976d732019-12-18 14:50:37 +0000714 NN_OPS_CHECK(input.type == OperandType::TENSOR_QUANT8_ASYMM ||
715 input.type == OperandType::TENSOR_QUANT8_ASYMM_SIGNED);
Przemyslaw Szczepaniaka4e6a652018-12-28 11:52:32 +0000716 } else {
717 NN_OPS_CHECK(input.type == filter.type);
718 }
Lev Proleev5976d732019-12-18 14:50:37 +0000719 if (input.type == OperandType::TENSOR_QUANT8_ASYMM ||
720 input.type == OperandType::TENSOR_QUANT8_ASYMM_SIGNED) {
Xusong Wang5339dc32018-08-17 15:38:32 -0700721 NN_OPS_CHECK(bias.type == OperandType::TENSOR_INT32);
722 } else {
723 NN_OPS_CHECK(input.type == bias.type);
724 }
725 NN_OPS_CHECK(getNumberOfDimensions(input) == 4);
726 NN_OPS_CHECK(getNumberOfDimensions(filter) == 4);
727 NN_OPS_CHECK(getNumberOfDimensions(bias) == 1);
728
729 NN_OPS_CHECK(getSizeOfDimension(filter, 0) == getSizeOfDimension(bias, 0));
730
731 NN_OPS_CHECK(getSizeOfDimension(filter, 3) * numGroups == getSizeOfDimension(input, 3));
732 NN_OPS_CHECK(getSizeOfDimension(filter, 0) % numGroups == 0);
733
734 uint32_t channels_out = getSizeOfDimension(filter, 0);
735 uint32_t width = getSizeOfDimension(input, 2);
736 uint32_t height = getSizeOfDimension(input, 1);
737 uint32_t filterWidth = getSizeOfDimension(filter, 2);
738 uint32_t filterHeight = getSizeOfDimension(filter, 1);
739 uint32_t batches = getSizeOfDimension(input, 0);
740
Xusong Wangd0cc11f2019-04-12 13:38:49 -0700741 NN_RET_CHECK_GT(static_cast<int32_t>(filterWidth), padding_left);
742 NN_RET_CHECK_GT(static_cast<int32_t>(filterWidth), padding_right);
743 NN_RET_CHECK_GT(static_cast<int32_t>(filterHeight), padding_top);
744 NN_RET_CHECK_GT(static_cast<int32_t>(filterHeight), padding_bottom);
Xusong Wangfa3b9422019-02-27 14:44:14 -0800745
Xusong Wang5339dc32018-08-17 15:38:32 -0700746 uint32_t outWidth =
747 computeOutSize(width, filterWidth, stride_width, padding_left, padding_right);
748 uint32_t outHeight =
749 computeOutSize(height, filterHeight, stride_height, padding_top, padding_bottom);
750
751 output->type = input.type;
752 output->dimensions = {batches, outHeight, outWidth, channels_out};
753 return true;
754}
Xusong Wang4588d3c2018-08-20 14:18:15 -0700755
Michael Butlerf20c5b52019-07-22 18:59:46 -0700756} // namespace nn
757} // namespace android