blob: b3b0631e1877a4d1a885c7ebfd072a1f587551d0 [file] [log] [blame]
telsoa014fcda012018-03-09 14:13:49 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
5#pragma once
6
7#include <armnn/ArmNN.hpp>
8#include <armnn/TypesUtils.hpp>
9
10#include <initializer_list>
11#include <iterator>
12#include <vector>
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010013
telsoa014fcda012018-03-09 14:13:49 +000014#include <boost/core/ignore_unused.hpp>
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010015#include <boost/numeric/conversion/cast.hpp>
telsoa014fcda012018-03-09 14:13:49 +000016
17template<typename T, bool DoQuantize=true>
18struct SelectiveQuantizer
19{
20 static T Quantize(float value, float scale, int32_t offset)
21 {
22 return armnn::Quantize<T>(value, scale, offset);
23 }
24
25 static float Dequantize(T value, float scale, int32_t offset)
26 {
27 return armnn::Dequantize(value, scale, offset);
28 }
29};
30
31template<typename T>
32struct SelectiveQuantizer<T, false>
33{
34 static T Quantize(float value, float scale, int32_t offset)
35 {
36 boost::ignore_unused(scale, offset);
37 return value;
38 }
39
40 static float Dequantize(T value, float scale, int32_t offset)
41 {
42 boost::ignore_unused(scale, offset);
43 return value;
44 }
45};
46
47template<typename T>
48T SelectiveQuantize(float value, float scale, int32_t offset)
49{
50 return SelectiveQuantizer<T, armnn::IsQuantizedType<T>()>::Quantize(value, scale, offset);
51};
52
53template<typename T>
54float SelectiveDequantize(T value, float scale, int32_t offset)
55{
56 return SelectiveQuantizer<T, armnn::IsQuantizedType<T>()>::Dequantize(value, scale, offset);
57};
58
59template<typename ItType>
60struct IsFloatingPointIterator
61{
62 static constexpr bool value=std::is_floating_point<typename std::iterator_traits<ItType>::value_type>::value;
63};
64
65template <typename T, typename FloatIt,
telsoa01c577f2c2018-08-31 09:22:23 +010066typename std::enable_if<IsFloatingPointIterator<FloatIt>::value, int>::type=0 // Makes sure fp iterator is valid.
telsoa014fcda012018-03-09 14:13:49 +000067>
68std::vector<T> QuantizedVector(float qScale, int32_t qOffset, FloatIt first, FloatIt last)
69{
70 std::vector<T> quantized;
71 quantized.reserve(boost::numeric_cast<size_t>(std::distance(first, last)));
72
73 for (auto it = first; it != last; ++it)
74 {
75 auto f = *it;
76 T q =SelectiveQuantize<T>(f, qScale, qOffset);
77 quantized.push_back(q);
78 }
79
80 return quantized;
81}
82
83template<typename T>
84std::vector<T> QuantizedVector(float qScale, int32_t qOffset, const std::vector<float>& array)
85{
86 return QuantizedVector<T>(qScale, qOffset, array.begin(), array.end());
87}
88
89template<typename T>
90std::vector<T> QuantizedVector(float qScale, int32_t qOffset, std::initializer_list<float> array)
91{
92 return QuantizedVector<T>(qScale, qOffset, array.begin(), array.end());
93}