Caffe2 - C++ API
A deep learning, cross platform ML framework
p99.cc
1 #include "caffe2/core/logging.h"
2 #include "l2_minimization.h"
3 
4 #include <cassert>
5 #include <cmath>
6 
7 namespace dnnlowp {
8 
9 TensorQuantizationParams P99::ChooseQuantizationParams(
10  const Histogram& hist,
11  bool preserve_sparsity,
12  int /*precision*/) {
13  assert(preserve_sparsity); // only support preserve_sparsity
14 
15  const std::vector<uint64_t> bins = *hist.GetHistogram();
16  int nbins = bins.size();
17  float min = hist.Min(), max = hist.Max();
18  assert(min <= 0.f);
19  assert(max >= 0.f);
20  float bin_width = (max - min) / nbins;
21  int zero_bin = ceil(-min / bin_width);
22 
23  int best_width = 0;
24  double total_sum = 0;
25  for (int i = 0; i < nbins; ++i) {
26  total_sum += bins[i];
27  }
28 
29  for (int width = 0; width < nbins; ++width) {
30  int i_begin, i_end;
31  if (min == 0) {
32  i_begin = 0;
33  i_end = width - 1;
34  } else {
35  i_begin = std::max(0, zero_bin - width);
36  i_end = std::min(nbins - 1, zero_bin + width);
37  }
38 
39  double selected_sum = 0;
40  for (int i = i_begin; i <= i_end; ++i) {
41  selected_sum += bins[i];
42  }
43 
44  if (selected_sum / total_sum >= 0.99) {
45  best_width = width;
46  break;
47  }
48  }
49 
50  if (min == 0) {
51  min = hist.Min();
52  max = hist.Min() + bin_width * best_width;
53  } else {
54  min = hist.Min() + bin_width * (zero_bin - best_width);
55  max = hist.Min() + bin_width * (zero_bin + best_width + 1);
56  }
57 
58  QuantizationFactory* qfactory = QuantizationFactory::GetDefaultInstance();
59  return qfactory->ChooseQuantizationParams(min, max);
60 } // ChooseQuantizationParams
61 
62 } // namespace dnnlowp
static QuantizationFactory * GetDefaultInstance()
Get the default factory whose policy is determined by gflags.
Definition: dnnlowp.cc:100