aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_fake_quant.cc
blob: f5f2f77460c7624298d8e49a0ea30527a45bd960 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/graph_transformations/quantization_util.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

template <ArrayDataType A>
void GetBoundsForQuantizedDataType(float* min, float* max) {
  using limits = std::numeric_limits<DataType<A>>;
  *min = limits::min();
  *max = limits::max();
}

void GetBoundsForQuantizedDataType(ArrayDataType quantized_data_type,
                                   float* min, float* max) {
  // It is important for matching accuracy between TF training and TFLite
  // inference, that the min and max values are float to match TF's
  // FakeQuantWithMinMaxVarsFunctor.
  switch (quantized_data_type) {
    case ArrayDataType::kUint8:
      return GetBoundsForQuantizedDataType<ArrayDataType::kUint8>(min, max);
    case ArrayDataType::kInt8:
      return GetBoundsForQuantizedDataType<ArrayDataType::kInt8>(min, max);
    case ArrayDataType::kUint16:
      return GetBoundsForQuantizedDataType<ArrayDataType::kUint16>(min, max);
    case ArrayDataType::kInt16:
      return GetBoundsForQuantizedDataType<ArrayDataType::kInt16>(min, max);
    case ArrayDataType::kUint32:
      return GetBoundsForQuantizedDataType<ArrayDataType::kUint32>(min, max);
    case ArrayDataType::kInt32:
      return GetBoundsForQuantizedDataType<ArrayDataType::kInt32>(min, max);
    case ArrayDataType::kUint64:
      return GetBoundsForQuantizedDataType<ArrayDataType::kUint64>(min, max);
    case ArrayDataType::kInt64:
      return GetBoundsForQuantizedDataType<ArrayDataType::kInt64>(min, max);
    default:
      LOG(FATAL) << "unhandled quantized data type";
  }
}

bool ResolveConstantFakeQuant::Run(Model* model, std::size_t op_index) {
  const auto fakequant_it = model->operators.begin() + op_index;
  const auto* fakequant_base_op = fakequant_it->get();
  if (fakequant_base_op->type != OperatorType::kFakeQuant) {
    return false;
  }

  const auto* fakequant_op =
      static_cast<const FakeQuantOperator*>(fakequant_base_op);

  // Yield until the fakequant MinMax has been resolved.
  if (!fakequant_op->minmax) {
    return false;
  }

  // This transformation only applies when the input array is constant.
  if (!IsConstantParameterArray(*model, fakequant_op->inputs[0])) {
    return false;
  }

  const auto& input_array = model->GetArray(fakequant_op->inputs[0]);
  CHECK(input_array.data_type == ArrayDataType::kFloat);

  // Determine the final data type in the same way as PropagateFakeQuantNumBits.
  ArrayDataType quantized_data_type = input_array.final_data_type;
  if (!InferQuantizedDataTypeFromFakeQuant(*fakequant_op,
                                           &quantized_data_type)) {
    AddMessageF("Unsupported FakeQuant num_bits=%d", fakequant_op->num_bits);
    return false;
  }

  AddMessageF("Resolving constant %s", LogName(*fakequant_op));

  auto& output_array = model->GetArray(fakequant_op->outputs[0]);
  CHECK(input_array.data_type == ArrayDataType::kFloat);
  output_array.data_type = ArrayDataType::kFloat;

  // We'll set the final data type to what the fake quant indicates we should
  // have (and would have been set if this stayed around until
  // PropagateFakeQuantNumBits).
  if (propagate_fake_quant_num_bits()) {
    output_array.final_data_type = quantized_data_type;
  }

  CHECK(!output_array.buffer);
  const auto& input_buffer = input_array.GetBuffer<ArrayDataType::kFloat>();
  output_array.GetOrCreateMinMax() = *fakequant_op->minmax;
  auto& output_buffer = output_array.GetMutableBuffer<ArrayDataType::kFloat>();
  const int size = input_buffer.data.size();
  output_buffer.data.resize(size);
  QuantizationParams qparams;
  ChooseQuantizationParamsForArrayAndQuantizedDataType(
      output_array, quantized_data_type, &qparams);
  float quantized_min, quantized_max;
  GetBoundsForQuantizedDataType(quantized_data_type, &quantized_min,
                                &quantized_max);
  if (fakequant_op->narrow_range) {
    quantized_min++;
    output_array.narrow_range = true;
  }

  // It is important for matching accuracy between TF training and TFLite
  // inference, that the following variables are float to match TF's
  // FakeQuantWithMinMaxVarsFunctor.
  const float scale = qparams.scale;
  const float nudged_min = (quantized_min - qparams.zero_point) * scale;
  const float nudged_max = (quantized_max - qparams.zero_point) * scale;
  tflite::FakeQuantizeArray(scale, nudged_min, nudged_max,
                            input_buffer.data.data(), output_buffer.data.data(),
                            size);

  if (IsDiscardableArray(*model, fakequant_op->inputs[0]) &&
      CountOpsWithInput(*model, fakequant_op->inputs[0]) == 1) {
    model->EraseArray(fakequant_op->inputs[0]);
  }
  model->operators.erase(fakequant_it);

  return true;
}

}  // namespace toco