1 /* Copyright 2018 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 #include "tensorflow/lite/tools/optimize/calibration/calibration_reader.h"
16
17 #include <memory>
18 #include <utility>
19
20 #include "absl/memory/memory.h"
21
22 namespace tflite {
23 namespace optimize {
24 namespace calibration {
GetTensorStatsAsMap(absl::flat_hash_map<std::tuple<int,int>,CalibrationStats> * tensor_id_to_stats_map) const25 TfLiteStatus CalibrationReader::GetTensorStatsAsMap(
26 absl::flat_hash_map<std::tuple<int, int>, CalibrationStats>*
27 tensor_id_to_stats_map) const {
28 tensor_id_to_stats_map->clear();
29 for (const auto& tensorid_stat : logger_->GetCalibrationValues()) {
30 auto minmax = tensorid_stat.second;
31 CalibrationReader::CalibrationStats stats;
32 TF_LITE_ENSURE_STATUS(minmax.Get(&stats.min, &stats.max));
33 tensor_id_to_stats_map->insert({tensorid_stat.first, stats});
34 }
35
36 return kTfLiteOk;
37 }
38
AddCalibrationToModel(ModelT * model,bool update) const39 TfLiteStatus CalibrationReader::AddCalibrationToModel(ModelT* model,
40 bool update) const {
41 if (!model || model->subgraphs.empty()) {
42 return kTfLiteError;
43 }
44 for (const auto& tensorid_stat : logger_->GetCalibrationValues()) {
45 int subgraph_index, tensor_index;
46 std::tie(subgraph_index, tensor_index) = tensorid_stat.first;
47 const auto& subgraph = model->subgraphs[subgraph_index];
48 auto minmax = tensorid_stat.second;
49 float min, max;
50 TfLiteStatus status = minmax.Get(&min, &max);
51 if (status != kTfLiteOk) continue;
52 if (update) {
53 auto tensor = subgraph->tensors[tensor_index].get();
54 if (tensor->quantization) {
55 if (!tensor->quantization->min.empty()) {
56 const float existing_min = tensor->quantization->min[0];
57 min = min < existing_min ? min : existing_min;
58 }
59 if (!tensor->quantization->max.empty()) {
60 const float existing_max = tensor->quantization->max[0];
61 max = max > existing_max ? max : existing_max;
62 }
63 }
64 }
65 auto quant_params = std::make_unique<tflite::QuantizationParametersT>();
66 quant_params->min.push_back(min);
67 quant_params->max.push_back(max);
68 subgraph->tensors[tensor_index]->quantization = std::move(quant_params);
69 }
70
71 return kTfLiteOk;
72 }
73 } // namespace calibration
74 } // namespace optimize
75 } // namespace tflite
76