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 #ifndef TENSORFLOW_LITE_TOOLS_OPTIMIZE_CALIBRATION_LOGGER_H_
16 #define TENSORFLOW_LITE_TOOLS_OPTIMIZE_CALIBRATION_LOGGER_H_
17 
18 #include <unordered_map>
19 
20 #include "tensorflow/lite/c/c_api_internal.h"
21 
22 namespace tflite {
23 namespace optimize {
24 namespace calibration {
25 class MinMax {
26  public:
Update(const float * values,size_t tensor_size)27   void Update(const float* values, size_t tensor_size) {
28     // TODO(shashishekhar): Really slow implementation, optimize
29     if (tensor_size <= 0) return;
30 
31     if (!has_values_) {
32       min_ = max_ = values[0];
33       has_values_ = true;
34       return;
35     }
36 
37     // We are only logging absolute min/max here.
38     // TODO(shashishekhar): Make it possible to use weighted/moving average.
39     for (size_t i = 0; i < tensor_size; i++) {
40       float val = values[i];
41       if (min_ > val) {
42         min_ = val;
43       } else if (max_ < val) {
44         max_ = val;
45       }
46     }
47   }
48 
HasValues()49   bool HasValues() const { return has_values_; }
50 
Get(float * min_val,float * max_val)51   TfLiteStatus Get(float* min_val, float* max_val) const {
52     if (!has_values_) return kTfLiteError;
53     *min_val = min_;
54     *max_val = max_;
55     return kTfLiteOk;
56   }
57 
58  private:
59   bool has_values_;
60   float min_, max_;
61 };
62 
63 // Captures min max values for tensors.
64 class Logger {
65  public:
66   // Log the value for tensor at |tensor_index| which has |tensor_values|
LogTensorValue(int tensor_index,const float * tensor_values,size_t tensor_size)67   void LogTensorValue(int tensor_index, const float* tensor_values,
68                       size_t tensor_size) {
69     tensor_id_to_stats_map_[tensor_index].Update(tensor_values, tensor_size);
70   }
71 
72   // Returns a map from tensor_index -> observed min max values.
GetCalibrationValues()73   const std::unordered_map<int, MinMax>& GetCalibrationValues() const {
74     return tensor_id_to_stats_map_;
75   }
76 
77  private:
78   std::unordered_map<int, MinMax> tensor_id_to_stats_map_;
79 };
80 
81 }  // namespace calibration
82 }  // namespace optimize
83 }  // namespace tflite
84 
85 #endif  // TENSORFLOW_LITE_TOOLS_OPTIMIZE_CALIBRATION_LOGGER_H_
86