quantize.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 "tflite/kernels/internal/common.h"
  15. #include "tflite/kernels/internal/cppmath.h"
  16. #include "tflite/kernels/internal/types.h"
  17. namespace tflite {
  18. namespace reference_ops {
  19. template <typename InputT, typename OutputT>
  20. inline void AffineQuantize(const tflite::QuantizationParams& op_params,
  21. const RuntimeShape& input_shape,
  22. const InputT* input_data,
  23. const RuntimeShape& output_shape,
  24. OutputT* output_data) {
  25. const int32 zero_point = op_params.zero_point;
  26. const double scale = op_params.scale;
  27. const int flat_size = MatchingFlatSize(input_shape, output_shape);
  28. static constexpr int32 min_val = std::numeric_limits<OutputT>::min();
  29. static constexpr int32 max_val = std::numeric_limits<OutputT>::max();
  30. for (int i = 0; i < flat_size; i++) {
  31. const InputT val = input_data[i];
  32. int32 unclamped =
  33. static_cast<int32>(TfLiteRound(val / static_cast<float>(scale))) +
  34. zero_point;
  35. int32 clamped = std::min(std::max(unclamped, min_val), max_val);
  36. output_data[i] = clamped;
  37. }
  38. }
  39. } // namespace reference_ops
  40. } // namespace tflite
  41. #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_QUANTIZE_H_