quantize.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_
  13. #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_
  14. #include <algorithm>
  15. #include <limits>
  16. #include "tensorflow/lite/kernels/internal/common.h"
  17. #include "tensorflow/lite/kernels/internal/compatibility.h"
  18. #include "tensorflow/lite/kernels/internal/cppmath.h"
  19. #include "tensorflow/lite/kernels/internal/types.h"
  20. namespace tflite {
  21. namespace reference_ops {
  22. template <typename InputT, typename OutputT>
  23. inline void AffineQuantize(const tflite::QuantizationParams& op_params,
  24. const RuntimeShape& input_shape,
  25. const InputT* input_data,
  26. const RuntimeShape& output_shape,
  27. OutputT* output_data) {
  28. const int32_t zero_point = op_params.zero_point;
  29. const double scale = op_params.scale;
  30. const int flat_size = MatchingFlatSize(input_shape, output_shape);
  31. static constexpr int32_t min_val = std::numeric_limits<OutputT>::min();
  32. static constexpr int32_t max_val = std::numeric_limits<OutputT>::max();
  33. for (int i = 0; i < flat_size; i++) {
  34. const InputT val = input_data[i];
  35. int32_t unclamped =
  36. static_cast<int32_t>(TfLiteRound(val / static_cast<float>(scale))) +
  37. zero_point;
  38. int32_t clamped = std::min(std::max(unclamped, min_val), max_val);
  39. output_data[i] = clamped;
  40. }
  41. }
  42. } // namespace reference_ops
  43. } // namespace tflite
  44. #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_