1 /*
2 * Copyright (C) 2020 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 "Operations"
18
19 #include <tensorflow/lite/kernels/internal/optimized/optimized_ops.h>
20
21 #include <algorithm>
22 #include <vector>
23
24 #include "CpuOperationUtils.h"
25 #include "HalInterfaces.h"
26 #include "OperationResolver.h"
27 #include "Tracing.h"
28
29 namespace android {
30 namespace nn {
31 namespace local_response_norm {
32
33 constexpr char kOperationName[] = "LOCAL_RESPONSE_NORMALIZATION";
34
35 constexpr uint32_t kNumInputs = 6;
36 constexpr uint32_t kInputTensor = 0;
37 constexpr uint32_t kRadiusScalar = 1;
38 constexpr uint32_t kBiasScalar = 2;
39 constexpr uint32_t kAlphaScalar = 3;
40 constexpr uint32_t kBetaScalar = 4;
41 constexpr uint32_t kAxisScalar = 5;
42
43 constexpr uint32_t kNumOutputs = 1;
44 constexpr uint32_t kOutputTensor = 0;
45
46 namespace {
47
48 using namespace hal;
49
localResponseNormFloat32Impl(const float * inputData,const Shape & inputShape,int32_t radius,float bias,float alpha,float beta,int32_t axis,float * outputData,const Shape & outputShape)50 inline bool localResponseNormFloat32Impl(const float* inputData, const Shape& inputShape,
51 int32_t radius, float bias, float alpha, float beta,
52 int32_t axis, float* outputData,
53 const Shape& outputShape) {
54 NNTRACE_TRANS("localResponseNormFloat32");
55 const uint32_t outerSize = getNumberOfElements(inputShape, 0, axis);
56 const uint32_t axisSize = getSizeOfDimension(inputShape, axis);
57 const uint32_t innerSize =
58 getNumberOfElements(inputShape, axis + 1, getNumberOfDimensions(inputShape));
59 for (uint32_t outer = 0; outer < outerSize; ++outer) {
60 const float* inputBase = inputData + outer * axisSize * innerSize;
61 float* outputBase = outputData + outer * axisSize * innerSize;
62 for (uint32_t inner = 0; inner < innerSize; ++inner, ++inputBase, ++outputBase) {
63 for (int32_t i = 0; i < axisSize; i++) {
64 const int32_t dBegin = std::max(0, i - radius);
65 // Add 1 on dEnd to comply with optimized_ops in TFLite
66 const int32_t dEnd = std::min(static_cast<int32_t>(axisSize), i + radius + 1);
67 float sum = 0.0f;
68 for (int32_t d = dBegin; d < dEnd; d++) {
69 float val = inputBase[d * innerSize];
70 sum += val * val;
71 }
72 float multiplier = std::pow(bias + alpha * sum, -beta);
73 outputBase[i * innerSize] = inputBase[i * innerSize] * multiplier;
74 }
75 }
76 }
77 return true;
78 }
79
80 template <typename T>
81 bool localResponseNorm(const T* inputData, const Shape& inputShape, int32_t radius, T bias, T alpha,
82 T beta, int32_t axis, T* outputData, const Shape& outputShape);
83
84 template <>
localResponseNorm(const float * inputData,const Shape & inputShape,int32_t radius,float bias,float alpha,float beta,int32_t axis,float * outputData,const Shape & outputShape)85 bool localResponseNorm<float>(const float* inputData, const Shape& inputShape, int32_t radius,
86 float bias, float alpha, float beta, int32_t axis, float* outputData,
87 const Shape& outputShape) {
88 int32_t ndim = getNumberOfDimensions(inputShape);
89 NN_CHECK(handleNegativeAxis(inputShape, &axis));
90 // TFLite optimized implementation only supports computation along the last axis
91 if (axis == ndim - 1) {
92 NNTRACE_COMP("optimized_ops::LocalResponseNormalization::float");
93 tflite::LocalResponseNormalizationParams param = {
94 .range = radius, .bias = bias, .alpha = alpha, .beta = beta};
95 tflite::optimized_ops::LocalResponseNormalization(
96 param, convertShapeToTflshape(inputShape), inputData,
97 convertShapeToTflshape(outputShape), outputData);
98 return true;
99 } else {
100 return localResponseNormFloat32Impl(inputData, inputShape, radius, bias, alpha, beta, axis,
101 outputData, outputShape);
102 }
103 }
104
105 template <>
localResponseNorm(const _Float16 * inputData,const Shape & inputShape,int32_t radius,_Float16 bias,_Float16 alpha,_Float16 beta,int32_t axis,_Float16 * outputData,const Shape & outputShape)106 bool localResponseNorm<_Float16>(const _Float16* inputData, const Shape& inputShape, int32_t radius,
107 _Float16 bias, _Float16 alpha, _Float16 beta, int32_t axis,
108 _Float16* outputData, const Shape& outputShape) {
109 NNTRACE_TRANS("localResponseNormFloat16");
110 std::vector<float> inputDataFloat32(getNumberOfElements(inputShape));
111 convertFloat16ToFloat32(inputData, &inputDataFloat32);
112 std::vector<float> outputDataFloat32(getNumberOfElements(outputShape));
113
114 localResponseNorm<float>(inputDataFloat32.data(), inputShape, radius, bias, alpha, beta, axis,
115 outputDataFloat32.data(), outputShape);
116 convertFloat32ToFloat16(outputDataFloat32, outputData);
117
118 return true;
119 }
120
121 template <typename T>
executeTyped(IOperationExecutionContext * context)122 bool executeTyped(IOperationExecutionContext* context) {
123 int32_t axis = context->getNumInputs() == kNumInputs
124 ? context->getInputValue<int32_t>(kAxisScalar)
125 : -1;
126 NN_RET_CHECK(handleNegativeAxis(context->getInputShape(kInputTensor), &axis));
127 return localResponseNorm<T>(
128 context->getInputBuffer<T>(kInputTensor), context->getInputShape(kInputTensor),
129 context->getInputValue<int32_t>(kRadiusScalar), context->getInputValue<T>(kBiasScalar),
130 context->getInputValue<T>(kAlphaScalar), context->getInputValue<T>(kBetaScalar), axis,
131 context->getOutputBuffer<T>(kOutputTensor), context->getOutputShape(kOutputTensor));
132 }
133
134 } // namespace
135
validate(const IOperationValidationContext * context)136 bool validate(const IOperationValidationContext* context) {
137 NN_RET_CHECK(context->getNumInputs() == kNumInputs ||
138 context->getNumInputs() == kNumInputs - 1);
139 NN_RET_CHECK_EQ(context->getNumOutputs(), kNumOutputs);
140
141 const OperandType inputType = context->getInputType(kInputTensor);
142 std::vector<OperandType> inExpectedTypes;
143 std::vector<OperandType> outExpectedTypes;
144 if (inputType == OperandType::TENSOR_FLOAT32) {
145 NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_0));
146 inExpectedTypes = {
147 OperandType::TENSOR_FLOAT32, OperandType::INT32, OperandType::FLOAT32,
148 OperandType::FLOAT32, OperandType::FLOAT32,
149 };
150 outExpectedTypes = {OperandType::TENSOR_FLOAT32};
151 } else if (inputType == OperandType::TENSOR_FLOAT16) {
152 NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
153 inExpectedTypes = {
154 OperandType::TENSOR_FLOAT16, OperandType::INT32, OperandType::FLOAT16,
155 OperandType::FLOAT16, OperandType::FLOAT16,
156 };
157 outExpectedTypes = {OperandType::TENSOR_FLOAT16};
158 } else {
159 NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
160 }
161
162 if (context->getNumInputs() == kNumInputs) {
163 inExpectedTypes.push_back(OperandType::INT32);
164 NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
165 } else if (context->getInputShape(kInputTensor).dimensions.size() != 4) {
166 NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
167 }
168
169 const Shape& input = context->getInputShape(kInputTensor);
170 if (hasKnownRank(input)) {
171 NN_RET_CHECK_LE(getNumberOfDimensions(input), 4);
172 }
173 return validateInputTypes(context, inExpectedTypes) &&
174 validateOutputTypes(context, {inputType});
175 }
176
prepare(IOperationExecutionContext * context)177 bool prepare(IOperationExecutionContext* context) {
178 const Shape& input = context->getInputShape(kInputTensor);
179 int32_t numDimensions = getNumberOfDimensions(input);
180 int32_t axis = context->getNumInputs() == kNumInputs
181 ? context->getInputValue<int32_t>(kAxisScalar)
182 : -1;
183 NN_RET_CHECK_LE(numDimensions, 4);
184 NN_RET_CHECK_GE(axis, -numDimensions);
185 NN_RET_CHECK_LT(axis, numDimensions);
186 return context->setOutputShape(kOutputTensor, input);
187 }
188
execute(IOperationExecutionContext * context)189 bool execute(IOperationExecutionContext* context) {
190 switch (context->getInputType(kInputTensor)) {
191 case OperandType::TENSOR_FLOAT32:
192 return executeTyped<float>(context);
193 case OperandType::TENSOR_FLOAT16:
194 return executeTyped<_Float16>(context);
195 default:
196 NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
197 }
198 }
199
200 } // namespace local_response_norm
201
202 NN_REGISTER_OPERATION(LOCAL_RESPONSE_NORMALIZATION, local_response_norm::kOperationName,
203 local_response_norm::validate, local_response_norm::prepare,
204 local_response_norm::execute);
205
206 } // namespace nn
207 } // namespace android
208