1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15#include <stdint.h>
16
17#include "tensorflow/lite/c/common.h"
18#include "tensorflow/lite/kernels/internal/tensor.h"
19#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
20#include "tensorflow/lite/kernels/kernel_util.h"
21
22namespace tflite {
23namespace ops {
24namespace builtin {
25namespace rank {
26
27constexpr int kInputTensor = 0;
28constexpr int kOutputTensor = 0;
29
30TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
31 TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
32 TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
33
34 const TfLiteTensor* input;
35 TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));
36 TfLiteTensor* output;
37 TF_LITE_ENSURE_OK(context,
38 GetOutputSafe(context, node, kOutputTensor, &output));
39 output->type = kTfLiteInt32;
40
41 // By design, the input shape is always known at the time of Prepare, even
42 // if the preceding op that generates |input| is dynamic. Thus, we can
43 // always compute the rank immediately, without waiting for Eval.
44 SetTensorToPersistentRo(output);
45
46 // Rank produces a 0-D int32 Tensor representing the rank of input.
47 TfLiteIntArray* output_size = TfLiteIntArrayCreate(0);
48 TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));
49
50 TF_LITE_ENSURE_EQ(context, NumDimensions(output), 0);
51
52 // Immediately propagate the known rank to the output tensor. This allows
53 // downstream ops that rely on the value to use it during prepare.
54 if (output->type == kTfLiteInt32) {
55 int32_t* output_data = GetTensorData<int32_t>(output);
56 *output_data = NumDimensions(input);
57 } else {
58 return kTfLiteError;
59 }
60
61 return kTfLiteOk;
62}
63
64TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
65 return kTfLiteOk;
66}
67
68} // namespace rank
69
70TfLiteRegistration* Register_RANK() {
71 static TfLiteRegistration r = {nullptr, nullptr, rank::Prepare, rank::Eval};
72 return &r;
73}
74
75} // namespace builtin
76} // namespace ops
77} // namespace tflite
78