xref: /aosp_15_r20/external/tensorflow/tensorflow/lite/delegates/gpu/common/object_reader.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_LITE_DELEGATES_GPU_COMMON_OBJECT_READER_H_
17 #define TENSORFLOW_LITE_DELEGATES_GPU_COMMON_OBJECT_READER_H_
18 
19 #include <cstdint>
20 #include <vector>
21 
22 #include "fp16.h"  // from @FP16
23 #include "absl/container/flat_hash_map.h"
24 #include "tensorflow/lite/c/common.h"
25 #include "tensorflow/lite/delegates/gpu/common/model.h"
26 #include "tensorflow/lite/delegates/gpu/common/model_builder_helper.h"
27 #include "tensorflow/lite/delegates/gpu/common/status.h"
28 #include "tensorflow/lite/kernels/internal/utils/sparsity_format_converter.h"
29 #include "tensorflow/lite/kernels/kernel_util.h"
30 
31 namespace tflite {
32 namespace gpu {
33 
34 // If quantized tensors exist in the graph & quant_conversion_map is non-null,
35 // the mapping between the original tensors (fixed-point) & GPU values (fp) is
36 // stored in quant_conversion_map.
37 class ObjectReader {
38  public:
39   static absl::Status ReadNonConstantTensor(
40       TfLiteContext* context, absl::flat_hash_map<int, Value*>* tensor_to_value,
41       absl::flat_hash_map<int, int>* quant_conversion_map, GraphFloat32* graph,
42       uint32_t tensor_idx, Value** value = nullptr);
43 
44   ObjectReader(GraphFloat32* graph, TfLiteContext* context,
45                const TfLiteNode* node,
46                absl::flat_hash_map<int, Value*>* tensor_to_value,
47                absl::flat_hash_map<int, int>* quant_conversion_map = nullptr)
graph_(graph)48       : graph_(graph),
49         context_(context),
50         node_(node),
51         tensor_to_value_(tensor_to_value),
52         quant_conversion_map_(quant_conversion_map) {}
53 
54   absl::Status ReadValue(uint32_t idx, Value** value);
55 
56   absl::Status ReadValueByTensorIdx(uint32_t tensor_idx, Value** value);
57 
58   int GetNumberOfRuntimeInputs() const;
59 
60   absl::Status GetTensorId(uint32_t input_id, int* tensor_id) const;
61 
62   absl::Status GetTensorDims(uint32_t idx, TfLiteIntArray* dimensions) const;
63 
64   template <typename TensorT>
ReadTensor(uint32_t index,TensorT * tensor)65   absl::Status ReadTensor(uint32_t index, TensorT* tensor) const {
66     if (index < 0 || index >= node_->inputs->size) {
67       // If larger, this can be an older model with fewer input tensors than the
68       // current implementation.
69       return absl::OutOfRangeError("Invalid data index found.");
70     }
71     const int32_t tensor_id = node_->inputs->data[index];
72     if (tensor_id < 0) {
73       return absl::InvalidArgumentError(
74           "Invalid data index found. Possibly an unset optional tensor is "
75           "being read.");
76     }
77     const TfLiteTensor* tflite_tensor = context_->tensors + tensor_id;
78     tensor->data.resize(NumElements(tflite_tensor));
79     if (tflite_tensor->sparsity) {
80       std::vector<int> dims;
81       dims.reserve(tflite_tensor->dims->size);
82       for (int i = 0; i < tflite_tensor->dims->size; ++i) {
83         dims.push_back(tflite_tensor->dims->data[i]);
84       }
85       switch (tflite_tensor->type) {
86         case kTfLiteFloat32: {
87           internal::sparsity::FormatConverter<float> converter(
88               dims, *tflite_tensor->sparsity);
89           converter.SparseToDense(
90               static_cast<const float*>(tflite_tensor->data.data));
91           const std::vector<float> out = converter.GetData();
92           std::memcpy(&tensor->data[0], out.data(), out.size() * sizeof(float));
93           break;
94         }
95         case kTfLiteFloat16: {
96           internal::sparsity::FormatConverter<Eigen::half> converter(
97               dims, *tflite_tensor->sparsity);
98           converter.SparseToDense(
99               static_cast<const Eigen::half*>(tflite_tensor->data.data));
100           const std::vector<Eigen::half> out = converter.GetData();
101           std::transform(out.begin(), out.end(), tensor->data.begin(),
102                          [](const Eigen::half& x) {
103                            return fp16_ieee_to_fp32_value(
104                                Eigen::numext::bit_cast<uint16_t>(x));
105                          });
106           break;
107         }
108         default: {
109           return absl::InvalidArgumentError(
110               "Unexpected data type in sparse tensor");
111         }
112       }
113     } else {
114       RETURN_IF_ERROR(CreateVectorCopyData(*tflite_tensor, &tensor->data[0]));
115     }
116 
117     // Axis and data layout depend on operation this tensor is used in. So,
118     // postpone resolutions until operations are parsed.
119     tensor->id = tensor_id;
120     return SetAllDimensions(tflite_tensor->dims, &tensor->shape);
121   }
122 
123   absl::Status AddOutput(const Node* node, int id);
124 
125   absl::Status AddOutputs(const Node* node);
126 
127   absl::Status AddInput(const Node* node, uint32_t idx);
128 
129   absl::Status AddUpdate(const Node* node, uint32_t idx);
130 
131   TfLiteTensor* GetInputTensor(int index) const;
132 
133   TfLiteTensor* GetOutputTensor(int index) const;
134 
135   absl::Status VerifyInputsConstsOutputs(const TfLiteNode* node,
136                                          int runtime_inputs, int const_inputs,
137                                          int outputs);
138 
139  private:
140   GraphFloat32* graph_;
141   TfLiteContext* context_;
142   const TfLiteNode* node_;
143   absl::flat_hash_map<int, Value*>* tensor_to_value_;
144   absl::flat_hash_map<int, int>* quant_conversion_map_;
145 };
146 
147 }  // namespace gpu
148 }  // namespace tflite
149 
150 #endif  // TENSORFLOW_LITE_DELEGATES_GPU_COMMON_OBJECT_READER_H_
151