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 "CpuOperationUtils.h"
22 #include "HalInterfaces.h"
23 #include "OperationResolver.h"
24 
25 #include <tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h>
26 #include <tensorflow/lite/kernels/internal/reference/reference_ops.h>
27 
28 #include "Tracing.h"
29 
30 namespace android {
31 namespace nn {
32 namespace transpose {
33 
34 constexpr char kOperationName[] = "TRANSPOSE";
35 
36 constexpr uint32_t kNumInputs = 2;
37 constexpr uint32_t kInputTensor = 0;
38 constexpr uint32_t kPermTensor = 1;
39 
40 constexpr uint32_t kNumOutputs = 1;
41 constexpr uint32_t kOutputTensor = 0;
42 
43 namespace {
44 
45 using namespace hal;
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 
validate(const IOperationValidationContext * context)76 bool validate(const IOperationValidationContext* context) {
77     NN_RET_CHECK_EQ(context->getNumInputs(), kNumInputs);
78     NN_RET_CHECK_EQ(context->getNumOutputs(), kNumOutputs);
79 
80     const OperandType inputType = context->getInputType(kInputTensor);
81     if (inputType == OperandType::TENSOR_FLOAT32 || inputType == OperandType::TENSOR_QUANT8_ASYMM) {
82         NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_1));
83     } else if (inputType == OperandType::TENSOR_FLOAT16) {
84         NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_2));
85     } else if (inputType == OperandType::TENSOR_QUANT8_ASYMM_SIGNED) {
86         NN_RET_CHECK(validateHalVersion(context, HalVersion::V1_3));
87     } else {
88         NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
89     }
90     const Shape& input = context->getInputShape(kInputTensor);
91     if (hasKnownRank(input)) {
92         NN_RET_CHECK_LE(getNumberOfDimensions(input), 4);
93     }
94     return validateInputTypes(context, {inputType, OperandType::TENSOR_INT32}) &&
95            validateOutputTypes(context, {inputType});
96 }
97 
prepare(IOperationExecutionContext * context)98 bool prepare(IOperationExecutionContext* context) {
99     // Only the permutation tensor can be omitted.
100     NN_RET_CHECK(!context->isOmittedInput(kInputTensor));
101     NN_RET_CHECK(!context->isOmittedOutput(kOutputTensor));
102 
103     const Shape& input = context->getInputShape(kInputTensor);
104     uint32_t numInputDims = getNumberOfDimensions(input);
105     Shape output = context->getOutputShape(kOutputTensor);
106     output.type = input.type;
107     output.offset = input.offset;
108     output.scale = input.scale;
109 
110     // permData can be NO_VALUE representing a regular 2D matrix transpose
111     if (context->isOmittedInput(kPermTensor)) {
112         NN_RET_CHECK_EQ(numInputDims, 2);
113         output.dimensions = {getSizeOfDimension(input, 1), getSizeOfDimension(input, 0)};
114     } else {
115         const Shape& permShape = context->getInputShape(kPermTensor);
116         const int32_t* permData = context->getInputBuffer<int32_t>(kPermTensor);
117 
118         // Transpose op only supports 1D-4D input arrays.
119         NN_RET_CHECK_LE(numInputDims, 4);
120 
121         // perm need to be provided as a 1-D int32 tensor.
122         NN_RET_CHECK(permShape.type == OperandType::TENSOR_INT32);
123         NN_RET_CHECK_EQ(getNumberOfDimensions(permShape), 1);
124         NN_RET_CHECK_EQ(numInputDims, getSizeOfDimension(permShape, 0));
125 
126         std::vector<uint32_t> outDims(numInputDims);
127         for (int32_t idx = 0; idx < static_cast<int32_t>(numInputDims); ++idx) {
128             NN_RET_CHECK(permData[idx] >= 0 && permData[idx] < static_cast<int32_t>(numInputDims));
129             outDims[idx] = getSizeOfDimension(input, permData[idx]);
130         }
131         output.dimensions = outDims;
132     }
133     return context->setOutputShape(kOutputTensor, output);
134 }
135 
execute(IOperationExecutionContext * context)136 bool execute(IOperationExecutionContext* context) {
137     // Bypass execution in the case of zero-sized input.
138     if (getNumberOfElements(context->getOutputShape(kOutputTensor)) == 0) return true;
139 
140     switch (context->getInputType(kInputTensor)) {
141         case OperandType::TENSOR_FLOAT32:
142             return transposeGeneric(context->getInputBuffer<float>(kInputTensor),
143                                     context->getInputShape(kInputTensor),
144                                     context->getInputBuffer<int32_t>(kPermTensor),
145                                     context->getInputShape(kPermTensor),
146                                     context->getOutputBuffer<float>(kOutputTensor),
147                                     context->getOutputShape(kOutputTensor));
148         case OperandType::TENSOR_FLOAT16:
149             return transposeGeneric(context->getInputBuffer<_Float16>(kInputTensor),
150                                     context->getInputShape(kInputTensor),
151                                     context->getInputBuffer<int32_t>(kPermTensor),
152                                     context->getInputShape(kPermTensor),
153                                     context->getOutputBuffer<_Float16>(kOutputTensor),
154                                     context->getOutputShape(kOutputTensor));
155         case OperandType::TENSOR_QUANT8_ASYMM:
156             return transposeGeneric(context->getInputBuffer<uint8_t>(kInputTensor),
157                                     context->getInputShape(kInputTensor),
158                                     context->getInputBuffer<int32_t>(kPermTensor),
159                                     context->getInputShape(kPermTensor),
160                                     context->getOutputBuffer<uint8_t>(kOutputTensor),
161                                     context->getOutputShape(kOutputTensor));
162         case OperandType::TENSOR_QUANT8_ASYMM_SIGNED:
163             return transposeGeneric(context->getInputBuffer<int8_t>(kInputTensor),
164                                     context->getInputShape(kInputTensor),
165                                     context->getInputBuffer<int32_t>(kPermTensor),
166                                     context->getInputShape(kPermTensor),
167                                     context->getOutputBuffer<int8_t>(kOutputTensor),
168                                     context->getOutputShape(kOutputTensor));
169         default:
170             NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName;
171     }
172 }
173 
174 }  // namespace transpose
175 
176 NN_REGISTER_OPERATION(TRANSPOSE, transpose::kOperationName, transpose::validate, transpose::prepare,
177                       transpose::execute, .allowOmittedOperand = true, .allowZeroSizedInput = true);
178 
179 }  // namespace nn
180 }  // namespace android
181