1 /*
2  * Copyright (C) 2019 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 <vector>
20 
21 #include "OperationResolver.h"
22 #include "Tracing.h"
23 
24 #ifdef NN_INCLUDE_CPU_IMPLEMENTATION
25 #include <tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h>
26 #include <tensorflow/lite/kernels/internal/reference/reference_ops.h>
27 
28 #include "CpuOperationUtils.h"
29 #endif  // NN_INCLUDE_CPU_IMPLEMENTATION
30 
31 namespace android {
32 namespace nn {
33 namespace transpose {
34 
35 constexpr char kOperationName[] = "TRANSPOSE";
36 
37 constexpr uint32_t kNumInputs = 2;
38 constexpr uint32_t kInputTensor = 0;
39 constexpr uint32_t kPermTensor = 1;
40 
41 constexpr uint32_t kNumOutputs = 1;
42 constexpr uint32_t kOutputTensor = 0;
43 
44 #ifdef NN_INCLUDE_CPU_IMPLEMENTATION
45 namespace {
46 
47 template <typename T>
transposeGeneric(const T * inputData,const Shape & inputShape,const int32_t * perm,const Shape & permShape,T * outputData,const Shape & outputShape)48 bool transposeGeneric(const T* inputData, const Shape& inputShape, const int32_t* perm,
49                       const Shape& permShape, T* outputData, const Shape& outputShape) {
50     NNTRACE_TRANS("transposeGeneric");
51     // Reverse the permuted axes and convert to 4D due to the way Dims are
52     // constructed.
53     const int32_t kOutputDimensionNum = 4;
54 
55     // permData can be NO_VALUE representing a regular 2D matrix transpose
56     int32_t permSize = perm == nullptr ? 2 : static_cast<int32_t>(getSizeOfDimension(permShape, 0));
57     int32_t perm_tmp[2] = {1, 0};
58     if (perm == nullptr) {
59         perm = perm_tmp;
60     }
61     int32_t reversed_perm[kOutputDimensionNum];
62     for (int32_t output_k = 0, input_k = permSize - 1; output_k < permSize; ++output_k, --input_k) {
63         reversed_perm[output_k] = permSize - perm[input_k] - 1;
64     }
65     for (int32_t k = permSize; k < kOutputDimensionNum; ++k) {
66         reversed_perm[k] = k;
67     }
68     NNTRACE_COMP_SWITCH("reference_ops::Transpose");
69     tflite::reference_ops::Transpose(inputData, convertShapeToDims(inputShape), outputData,
70                                      convertShapeToDims(outputShape), reversed_perm);
71     return true;
72 }
73 
74 }  // namespace
75 #endif  // NN_INCLUDE_CPU_IMPLEMENTATION
76 
validate(const IOperationValidationContext * context)77 Result<Version> validate(const IOperationValidationContext* context) {
78     NN_RET_CHECK_EQ(context->getNumInputs(), kNumInputs);
79     NN_RET_CHECK_EQ(context->getNumOutputs(), kNumOutputs);
80 
81     const OperandType inputType = context->getInputType(kInputTensor);
82     auto minSupportedVersion = Version::ANDROID_OC_MR1;
83     if (inputType == OperandType::TENSOR_FLOAT32 || inputType == OperandType::TENSOR_QUANT8_ASYMM) {
84         minSupportedVersion = Version::ANDROID_P;
85     } else if (inputType == OperandType::TENSOR_FLOAT16) {
86         minSupportedVersion = Version::ANDROID_Q;
87     } else if (inputType == OperandType::TENSOR_QUANT8_ASYMM_SIGNED) {
88         minSupportedVersion = Version::ANDROID_R;
89     } else {
90         NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
91     }
92     const Shape& input = context->getInputShape(kInputTensor);
93     if (hasKnownRank(input)) {
94         NN_RET_CHECK_LE(getNumberOfDimensions(input), 4);
95     }
96     NN_RET_CHECK(validateInputTypes(context, {inputType, OperandType::TENSOR_INT32}));
97     NN_RET_CHECK(validateOutputTypes(context, {inputType}));
98     return minSupportedVersion;
99 }
100 
101 #ifdef NN_INCLUDE_CPU_IMPLEMENTATION
prepare(IOperationExecutionContext * context)102 bool prepare(IOperationExecutionContext* context) {
103     // Only the permutation tensor can be omitted.
104     NN_RET_CHECK(!context->isOmittedInput(kInputTensor));
105     NN_RET_CHECK(!context->isOmittedOutput(kOutputTensor));
106 
107     const Shape& input = context->getInputShape(kInputTensor);
108     uint32_t numInputDims = getNumberOfDimensions(input);
109     Shape output = context->getOutputShape(kOutputTensor);
110     output.type = input.type;
111     output.offset = input.offset;
112     output.scale = input.scale;
113 
114     // permData can be NO_VALUE representing a regular 2D matrix transpose
115     if (context->isOmittedInput(kPermTensor)) {
116         NN_RET_CHECK_EQ(numInputDims, 2);
117         output.dimensions = {getSizeOfDimension(input, 1), getSizeOfDimension(input, 0)};
118     } else {
119         const Shape& permShape = context->getInputShape(kPermTensor);
120         const int32_t* permData = context->getInputBuffer<int32_t>(kPermTensor);
121 
122         // Transpose op only supports 1D-4D input arrays.
123         NN_RET_CHECK_LE(numInputDims, 4);
124 
125         // perm need to be provided as a 1-D int32 tensor.
126         NN_RET_CHECK(permShape.type == OperandType::TENSOR_INT32);
127         NN_RET_CHECK_EQ(getNumberOfDimensions(permShape), 1);
128         NN_RET_CHECK_EQ(numInputDims, getSizeOfDimension(permShape, 0));
129 
130         std::vector<uint32_t> outDims(numInputDims);
131         for (int32_t idx = 0; idx < static_cast<int32_t>(numInputDims); ++idx) {
132             NN_RET_CHECK(permData[idx] >= 0 && permData[idx] < static_cast<int32_t>(numInputDims));
133             outDims[idx] = getSizeOfDimension(input, permData[idx]);
134         }
135         output.dimensions = outDims;
136     }
137     return context->setOutputShape(kOutputTensor, output);
138 }
139 
execute(IOperationExecutionContext * context)140 bool execute(IOperationExecutionContext* context) {
141     // Bypass execution in the case of zero-sized input.
142     if (getNumberOfElements(context->getOutputShape(kOutputTensor)) == 0) return true;
143 
144     switch (context->getInputType(kInputTensor)) {
145         case OperandType::TENSOR_FLOAT32:
146             return transposeGeneric(context->getInputBuffer<float>(kInputTensor),
147                                     context->getInputShape(kInputTensor),
148                                     context->getInputBuffer<int32_t>(kPermTensor),
149                                     context->getInputShape(kPermTensor),
150                                     context->getOutputBuffer<float>(kOutputTensor),
151                                     context->getOutputShape(kOutputTensor));
152         case OperandType::TENSOR_FLOAT16:
153             return transposeGeneric(context->getInputBuffer<_Float16>(kInputTensor),
154                                     context->getInputShape(kInputTensor),
155                                     context->getInputBuffer<int32_t>(kPermTensor),
156                                     context->getInputShape(kPermTensor),
157                                     context->getOutputBuffer<_Float16>(kOutputTensor),
158                                     context->getOutputShape(kOutputTensor));
159         case OperandType::TENSOR_QUANT8_ASYMM:
160             return transposeGeneric(context->getInputBuffer<uint8_t>(kInputTensor),
161                                     context->getInputShape(kInputTensor),
162                                     context->getInputBuffer<int32_t>(kPermTensor),
163                                     context->getInputShape(kPermTensor),
164                                     context->getOutputBuffer<uint8_t>(kOutputTensor),
165                                     context->getOutputShape(kOutputTensor));
166         case OperandType::TENSOR_QUANT8_ASYMM_SIGNED:
167             return transposeGeneric(context->getInputBuffer<int8_t>(kInputTensor),
168                                     context->getInputShape(kInputTensor),
169                                     context->getInputBuffer<int32_t>(kPermTensor),
170                                     context->getInputShape(kPermTensor),
171                                     context->getOutputBuffer<int8_t>(kOutputTensor),
172                                     context->getOutputShape(kOutputTensor));
173         default:
174             NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
175     }
176 }
177 #endif  // NN_INCLUDE_CPU_IMPLEMENTATION
178 
179 }  // namespace transpose
180 
181 NN_REGISTER_OPERATION(TRANSPOSE, transpose::kOperationName, transpose::validate, transpose::prepare,
182                       transpose::execute, .allowOmittedOperand = true, .allowZeroSizedInput = true);
183 
184 }  // namespace nn
185 }  // namespace android
186