aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/quantized_instance_norm_test.cc
blob: 896fe046e7ef2a99e8f854340c4c786095679a6e (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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/* Copyright 2015 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.
==============================================================================*/

#define EIGEN_USE_THREADS

#include <vector>

#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/core/framework/tensor_testutil.h"

namespace tensorflow {
namespace ops {
namespace {

void ReferenceImpl(const quint8* inp, float inp_min, float inp_max,
                   const TensorShape& shape, float var_eps, float* out) {
  int N = shape.dim_size(0);
  int H = shape.dim_size(1);
  int W = shape.dim_size(2);
  int C = shape.dim_size(3);

  int total = N * H * W * C;
  float inp_scale = (inp_max - inp_min) / 255.0f;
  std::unique_ptr<float[]> dequantized(new float[total]);

  for (int i = 0; i < total; ++i) {
    dequantized[i] = inp_min + inp_scale * static_cast<float>(inp[i]);
  }

  std::unique_ptr<float[]> inp_mean(new float[N * C]);
  std::unique_ptr<float[]> inp_var(new float[N * C]);

  float img_size = static_cast<float>(H) * static_cast<float>(W);

  // Compute mean
  for (int n = 0; n < N; ++n) {
    for (int c = 0; c < C; ++c) {
      float sum = 0.0;
      for (int i = 0; i < H * W; ++i) {
        sum += dequantized[n * H * W * C + i * C + c];
      }
      inp_mean[n * C + c] = sum / img_size;
    }
  }

  // Compute var
  for (int n = 0; n < N; ++n) {
    for (int c = 0; c < C; ++c) {
      float sum = 0.0;
      for (int i = 0; i < H * W; ++i) {
        float tmp =
            dequantized[n * H * W * C + i * C + c] - inp_mean[n * C + c];
        sum += tmp * tmp;
      }
      inp_var[n * C + c] = sum / img_size;
    }
  }

  for (int n = 0; n < N; ++n) {
    for (int c = 0; c < C; ++c) {
      for (int i = 0; i < H * W; ++i) {
        out[n * H * W * C + i * C + c] =
            (dequantized[n * H * W * C + i * C + c] - inp_mean[n * C + c]) /
            std::sqrt(inp_var[n * C + c] + var_eps);
      }
    }
  }
}

void Expect(const Tensor& input, float x_min, float x_max,
            bool output_range_given, float give_y_min, float given_y_max) {
  Scope root = Scope::NewRootScope();

  auto input_ph = Placeholder(root, DT_QUINT8);

  const float variance_eps = 1e-5;
  auto instance_norm = QuantizedInstanceNorm(
      root, input_ph, x_min, x_max,
      QuantizedInstanceNorm::Attrs().VarianceEpsilon(variance_eps));

  Status s = root.status();
  EXPECT_TRUE(s.ok());

  ClientSession session(root);
  std::vector<Tensor> outputs;

  s = session.Run({{input_ph, input}},
                  {instance_norm.y, instance_norm.y_min, instance_norm.y_max},
                  &outputs);

  EXPECT_TRUE(s.ok());
  Tensor expected(DT_FLOAT, input.shape());

  ReferenceImpl(input.flat<quint8>().data(), x_min, x_max, input.shape(),
                variance_eps, expected.flat<float>().data());

  auto out = outputs[0].flat<quint8>();

  float out_min = outputs[1].flat<float>()(0);
  float out_max = outputs[2].flat<float>()(0);
  float out_scale = (out_max - out_min) / 255.0f;

  Eigen::Tensor<float, 0, Eigen::RowMajor> max_diff =
      (expected.flat<float>() - (out_min + out_scale * out.cast<float>()))
          .abs()
          .maximum();
  EXPECT_LE(max_diff(), 0.1);
  LOG(INFO) << "max diff " << max_diff();
}

void TestBasic() {
  Tensor input_tensor(DT_QUINT8, {1, 4, 4, 32});
  auto input = input_tensor.flat<quint8>();
  // Random input
  input = input.random(Eigen::internal::UniformRandomGenerator<quint8>());

  Expect(input_tensor, 0.0f, 1.0f, false, 0.0f, 0.0f);
}

void TestZeroInput() {
  Tensor input_tensor(DT_QUINT8, {1, 4, 4, 32});
  auto input = input_tensor.flat<quint8>();
  // Zero input, but input min > 0. Tests that output min and max should be
  // properly separated.
  input = input.setConstant(0);

  Expect(input_tensor, 2.0f, 3.0f, false, 0.0f, 0.0f);
}

void TestMaxInput() {
  Tensor input_tensor(DT_QUINT8, {1, 1, 2, 16});
  auto input = input_tensor.flat<quint8>();
  // Inputs are all FLT_MAX / (number of inputs).
  input = input.setConstant(255);

  Expect(input_tensor, 0.0f,
         std::numeric_limits<float>::max() / static_cast<float>(2 * 16), false,
         0.0f, 0.0f);
}

void TestOutputRangeGiven() {
  Tensor input_tensor(DT_QUINT8, {1, 4, 4, 32});
  auto input = input_tensor.flat<quint8>();
  input = input.random(Eigen::internal::UniformRandomGenerator<quint8>());

  Expect(input_tensor, -10.0f, 10.0f, true, -1.0f, 1.0f);
}

void TestClamp() {
  Tensor input_tensor(DT_QUINT8, {1, 4, 4, 32});
  auto input = input_tensor.flat<quint8>();
  input = input.random(Eigen::internal::UniformRandomGenerator<quint8>());

  // Tests that negative outputs are clamped at 0.0, as the output range is
  // given to be (0.0, 1.0).
  Expect(input_tensor, -10.0f, 10.0f, true, 0.0f, 1.0f);
}

}  // namespace
}  // namespace ops
}  // namespace tensorflow

#define RUN_TEST(t) \
  TEST(QuantizedInstanceNormTest, t) { tensorflow::ops::t(); }

RUN_TEST(TestBasic);
RUN_TEST(TestZeroInput);
RUN_TEST(TestMaxInput);
RUN_TEST(TestOutputRangeGiven);
RUN_TEST(TestClamp);

int main(int argc, char** argv) {
  // On Linux, add: FLAGS_logtostderr = true;
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}