aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/resize_area_op_test.cc
blob: 84ff090b5469291712eb97aa19734e7d194771b8 (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
190
191
192
193
194
195
196
197
198
/* 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 "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {

class ResizeAreaOpTest : public OpsTestBase {
 protected:
  ResizeAreaOpTest() {
    TF_EXPECT_OK(NodeDefBuilder("resize_area_op", "ResizeArea")
                     .Input(FakeInput(DT_FLOAT))
                     .Input(FakeInput(DT_INT32))
                     .Attr("align_corners", false)
                     .Finalize(node_def()));
    TF_EXPECT_OK(InitOp());
  }

  const Tensor* SetRandomImageInput(const TensorShape& shape) {
    inputs_.clear();

    CHECK_EQ(shape.dims(), 4) << "All images must have 4 dimensions.";
    bool is_ref = IsRefType(input_types_[inputs_.size()]);
    Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
                               DataTypeToEnum<float>::v(), shape);
    input->flat<float>().setRandom();
    tensors_.push_back(input);
    if (is_ref) {
      CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
               DataTypeToEnum<float>::v());
      inputs_.push_back({&lock_for_refs_, input});
    } else {
      CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<float>::v());
      inputs_.push_back({nullptr, input});
    }
    return input;
  }

 private:
  // This is the unoptimized implementation of ResizeArea.
  // We use this to confirm that the optimized version is exactly identical.
  void ResizeAreaBaseline(TTypes<float, 4>::ConstTensor input_data,
                          TTypes<float, 4>::Tensor output_data) {
    const int batch_size = input_data.dimension(0);
    const int64 in_height = input_data.dimension(1);
    const int64 in_width = input_data.dimension(2);
    const int channels = input_data.dimension(3);

    ASSERT_EQ(batch_size, output_data.dimension(0));
    ASSERT_EQ(channels, output_data.dimension(3));

    const int64 out_height = output_data.dimension(1);
    const int64 out_width = output_data.dimension(2);

    const float height_scale = in_height / static_cast<float>(out_height);
    const float width_scale = in_width / static_cast<float>(out_width);

    // A temporary tensor for computing the sum.
    Tensor sum_tensor(DT_FLOAT, TensorShape({channels}));
    typename TTypes<float, 1>::Tensor sum_data = sum_tensor.vec<float>();

    // When using this algorithm for downsizing, the target pixel value is the
    // weighted average of all the source pixels. The weight is determined by
    // the contribution percentage of the source pixel.
    //
    // Let "scale" be "target_image_size/source_image_size". If 1/n of the
    // source pixel contributes to the target pixel, then the weight is (1/n *
    // scale); if the complete source pixel contributes to the target pixel,
    // then the weight is scale.
    //
    // To visualize the implementation, use one dimension as an example:
    // Resize in[4] to out[3].
    //   scale = 3/4 = 0.75
    //   out[0]: in[0] and 1/3 of in[1]
    //   out[1]: 2/3 of in[1] and 2/3 of in[2]
    //   out[2]: 1/3 of in[2] and in[1]
    // Hence, the output pixel values are:
    //   out[0] = (in[0] * 1.0 + in[1] * 1/3) * scale
    //   out[1] = (in[1] * 2/3 + in[2] * 2/3 * scale
    //   out[2] = (in[3] * 1/3 + in[3] * 1.0) * scale
    float scale = 1.0 / (height_scale * width_scale);
    for (int64 b = 0; b < batch_size; ++b) {
      for (int64 y = 0; y < out_height; ++y) {
        const float in_y = y * height_scale;
        const float in_y1 = (y + 1) * height_scale;
        // The start and end height indices of all the cells that could
        // contribute to the target cell.
        int64 y_start = floor(in_y);
        int64 y_end = ceil(in_y1);

        for (int64 x = 0; x < out_width; ++x) {
          const float in_x = x * width_scale;
          const float in_x1 = (x + 1) * width_scale;
          // The start and end width indices of all the cells that could
          // contribute to the target cell.
          int64 x_start = floor(in_x);
          int64 x_end = ceil(in_x1);

          sum_data.setConstant(0.0);
          for (int64 i = y_start; i < y_end; ++i) {
            float scale_y = i < in_y
                                ? (i + 1 > in_y1 ? height_scale : i + 1 - in_y)
                                : (i + 1 > in_y1 ? in_y1 - i : 1.0);
            for (int64 j = x_start; j < x_end; ++j) {
              float scale_x = j < in_x
                                  ? (j + 1 > in_x1 ? width_scale : j + 1 - in_x)
                                  : (j + 1 > in_x1 ? in_x1 - j : 1.0);
              for (int64 c = 0; c < channels; ++c) {
#define BOUND(val, limit) \
  std::min(((limit)-int64{1}), (std::max(int64{0}, (val))))
                sum_data(c) +=
                    static_cast<float>(input_data(b, BOUND(i, in_height),
                                                  BOUND(j, in_width), c)) *
                    scale_y * scale_x * scale;
#undef BOUND
              }
            }
          }
          for (int64 c = 0; c < channels; ++c) {
            output_data(b, y, x, c) = sum_data(c);
          }
        }
      }
    }
  }

 protected:
  void RunRandomTest(int in_height, int in_width, int target_height,
                     int target_width, int channels) {
    const Tensor* input =
        SetRandomImageInput(TensorShape({1, in_height, in_width, channels}));
    AddInputFromArray<int32>(TensorShape({2}), {target_height, target_width});

    TF_ASSERT_OK(RunOpKernel());
    std::unique_ptr<Tensor> expected(
        new Tensor(device_->GetAllocator(AllocatorAttributes()),
                   DataTypeToEnum<float>::v(),
                   TensorShape({1, target_height, target_width, channels})));
    ResizeAreaBaseline(input->tensor<float, 4>(), expected->tensor<float, 4>());
    test::ExpectTensorNear<float>(*expected, *GetOutput(0), 0.00001);
  }

  void RunManyRandomTests(int channels) {
    for (int in_w : {2, 4, 7, 20, 165}) {
      for (int in_h : {1, 3, 5, 8, 100, 233}) {
        for (int target_height : {1, 2, 3, 50, 113}) {
          for (int target_width : {target_height, target_height / 2 + 1}) {
            RunRandomTest(in_h, in_w, target_height, target_width, channels);
          }
        }
      }
    }
  }
};

TEST_F(ResizeAreaOpTest, TestAreaRandom141x186) {
  RunRandomTest(141, 186, 299, 299, 3 /* channels */);
}

TEST_F(ResizeAreaOpTest, TestAreaRandom183x229) {
  RunRandomTest(183, 229, 299, 299, 3 /* channels */);
}

TEST_F(ResizeAreaOpTest, TestAreaRandom749x603) {
  RunRandomTest(749, 603, 299, 299, 3 /* channels */);
}

TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes1Channel) {
  RunManyRandomTests(1);
}

TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes3Channels) {
  RunManyRandomTests(3);
}

TEST_F(ResizeAreaOpTest, TestAreaRandomDataSeveralInputsSizes4Channels) {
  RunManyRandomTests(4);
}

}  // namespace tensorflow