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 "absl/memory/memory.h"
18 
19 namespace tflite {
20 namespace optimize {
21 namespace calibration {
GetTensorStatsAsMap(std::unordered_map<int,CalibrationStats> * tensor_id_to_stats_map) const22 TfLiteStatus CalibrationReader::GetTensorStatsAsMap(
23     std::unordered_map<int, CalibrationStats>* tensor_id_to_stats_map) const {
24   tensor_id_to_stats_map->clear();
25   for (const auto& tensorid_stat : logger_->GetCalibrationValues()) {
26     auto minmax = tensorid_stat.second;
27     CalibrationReader::CalibrationStats stats;
28     TF_LITE_ENSURE_STATUS(minmax.Get(&stats.min, &stats.max));
29     tensor_id_to_stats_map->insert({tensorid_stat.first, stats});
30   }
31 
32   return kTfLiteOk;
33 }
34 
AddCalibrationToModel(ModelT * model) const35 TfLiteStatus CalibrationReader::AddCalibrationToModel(ModelT* model) const {
36   if (!model || model->subgraphs.empty()) {
37     return kTfLiteError;
38   }
39   const auto& subgraph = model->subgraphs[0];
40   for (const auto& tensorid_stat : logger_->GetCalibrationValues()) {
41     auto minmax = tensorid_stat.second;
42     float min, max;
43     TF_LITE_ENSURE_STATUS(minmax.Get(&min, &max));
44     auto quant_params = absl::make_unique<tflite::QuantizationParametersT>();
45     quant_params->min.push_back(min);
46     quant_params->max.push_back(max);
47     subgraph->tensors[tensorid_stat.first]->quantization =
48         std::move(quant_params);
49   }
50 
51   return kTfLiteOk;
52 }
53 }  // namespace calibration
54 }  // namespace optimize
55 }  // namespace tflite
56