1 /* Copyright 2019 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_CALIBRATION_LOGGER_H_ 16 #define TENSORFLOW_LITE_TOOLS_OPTIMIZE_CALIBRATION_CALIBRATION_LOGGER_H_ 17 18 #include <limits> 19 20 #include "absl/container/flat_hash_map.h" 21 #include "tensorflow/lite/c/common.h" 22 #include "tensorflow/lite/core/api/error_reporter.h" 23 24 namespace tflite { 25 namespace optimize { 26 namespace calibration { 27 28 class MinMax { 29 public: 30 TfLiteStatus Update(const float* values, size_t tensor_size, 31 ErrorReporter* error_reporter); 32 HasValues()33 bool HasValues() const { return has_values_; } 34 Get(float * min_val,float * max_val)35 TfLiteStatus Get(float* min_val, float* max_val) const { 36 if (!has_values_) return kTfLiteError; 37 *min_val = min_; 38 *max_val = max_; 39 return kTfLiteOk; 40 } 41 42 private: 43 bool has_values_ = false; 44 float min_ = std::numeric_limits<float>::max(); 45 float max_ = std::numeric_limits<float>::min(); 46 }; 47 48 // Captures min max values for tensors. 49 class Logger { 50 public: 51 // Log the value for tensor at |tensor_index| which has |tensor_values| LogTensorValue(int subgraph_index,int tensor_index,const float * tensor_values,size_t tensor_size,ErrorReporter * error_reporter)52 TfLiteStatus LogTensorValue(int subgraph_index, int tensor_index, 53 const float* tensor_values, size_t tensor_size, 54 ErrorReporter* error_reporter) { 55 std::tuple<int, int> key{subgraph_index, tensor_index}; 56 return tensor_id_to_stats_map_[key].Update(tensor_values, tensor_size, 57 error_reporter); 58 } 59 60 // Returns a map from tensor_index -> observed min max values. 61 const absl::flat_hash_map<std::tuple<int, int>, MinMax>& GetCalibrationValues()62 GetCalibrationValues() const { 63 return tensor_id_to_stats_map_; 64 } 65 66 private: 67 absl::flat_hash_map<std::tuple<int, int>, MinMax> tensor_id_to_stats_map_; 68 }; 69 70 } // namespace calibration 71 } // namespace optimize 72 } // namespace tflite 73 74 #endif // TENSORFLOW_LITE_TOOLS_OPTIMIZE_CALIBRATION_CALIBRATION_LOGGER_H_ 75