karolmajek/maxdeeplab
0
1# coding=utf-82# Copyright 2021 The Deeplab2 Authors.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16"""Tests for utils."""17 18import itertools19 20import numpy as np21import tensorflow as tf22 23from deeplab2.model import utils24 25 26class UtilsTest(tf.test.TestCase):27 28 def test_resize_logits_graph_mode(self):29 @tf.function30 def graph_mode_wrapper(*args):31 return utils.resize_and_rescale_offsets(*args)32 33 resized_logits = graph_mode_wrapper(tf.ones((2, 33, 33, 2)), [65, 65])34 resized_logits_2 = graph_mode_wrapper(tf.ones((2, 33, 33, 2)), [33, 33])35 self.assertListEqual(resized_logits.shape.as_list(), [2, 65, 65, 2])36 self.assertListEqual(resized_logits_2.shape.as_list(), [2, 33, 33, 2])37 38 def test_resize_logits(self):39 offset_logits = tf.convert_to_tensor([[[[2, 2], [2, 1], [2, 0]],40 [[1, 2], [1, 1], [1, 0]],41 [[0, 2], [0, 1], [0, 0]]]],42 dtype=tf.float32)43 target_size = [5, 5]44 resized_logits = utils.resize_and_rescale_offsets(offset_logits,45 target_size)46 47 self.assertListEqual(resized_logits.shape.as_list(), [1, 5, 5, 2])48 for i in range(5):49 for j in range(5):50 np.testing.assert_array_almost_equal(resized_logits.numpy()[0, i, j, :],51 [4 - i, 4 - j])52 53 def test_zero_padding(self):54 input_tensor = tf.ones(shape=(2, 5, 5, 2))55 input_tensor_2 = tf.ones(shape=(5, 5, 2))56 padded_tensor = utils.add_zero_padding(input_tensor, kernel_size=5, rank=4)57 padded_tensor_2 = utils.add_zero_padding(58 input_tensor_2, kernel_size=5, rank=3)59 60 self.assertEqual(tf.reduce_sum(padded_tensor), 100)61 self.assertEqual(tf.reduce_sum(padded_tensor_2), 50)62 self.assertListEqual(padded_tensor.shape.as_list(), [2, 9, 9, 2])63 self.assertListEqual(padded_tensor_2.shape.as_list(), [9, 9, 2])64 # Count zero elements.65 self.assertEqual(tf.reduce_sum(padded_tensor-1), -224)66 self.assertEqual(tf.reduce_sum(padded_tensor_2-1), -112)67 68 def test_resize_function_error(self):69 input_tensor = tf.random.uniform(shape=(2, 10, 10, 2))70 with self.assertRaises(ValueError):71 _ = utils.resize_align_corners(input_tensor, [19, 19],72 method='not_a_valid_method')73 74 def test_resize_function_shape(self):75 input_tensor = tf.random.uniform(shape=(2, 10, 10, 2))76 result_tensor = utils.resize_align_corners(input_tensor, [19, 19])77 78 self.assertListEqual(result_tensor.shape.as_list(), [2, 19, 19, 2])79 80 def test_resize_graph_mode(self):81 @tf.function82 def graph_mode_wrapper(*args):83 return utils.resize_align_corners(*args)84 85 result_tensor = graph_mode_wrapper(tf.ones((2, 33, 33, 2)), [65, 65])86 result_tensor_2 = graph_mode_wrapper(tf.ones((2, 33, 33, 2)), [33, 33])87 self.assertListEqual(result_tensor.shape.as_list(), [2, 65, 65, 2])88 self.assertListEqual(result_tensor_2.shape.as_list(), [2, 33, 33, 2])89 90 def test_resize_function_constant_input(self):91 input_tensor = tf.ones(shape=(2, 10, 10, 2))92 result_tensor = utils.resize_align_corners(input_tensor, [19, 19])93 94 self.assertTrue(tf.keras.backend.all(result_tensor == 1))95 96 def test_resize_function_invalid_rank(self):97 input_tensor = tf.keras.Input(shape=(None, 2))98 with self.assertRaisesRegex(99 ValueError, 'should have rank of 4'):100 _ = utils.resize_align_corners(input_tensor, [19, 19])101 102 def test_resize_function_v1_compatibility(self):103 # Test for odd and even input, and output shapes.104 input_shapes = [(2, 10, 10, 3), (2, 11, 11, 3)]105 target_sizes = [[19, 19], [20, 20]]106 methods = ['bilinear', 'nearest']107 108 for shape, target_size, method in itertools.product(input_shapes,109 target_sizes, methods):110 input_tensor = tf.random.uniform(shape=shape)111 112 result_tensor = utils.resize_align_corners(input_tensor, target_size,113 method)114 if method == 'bilinear':115 expected_tensor = tf.compat.v1.image.resize(116 input_tensor,117 target_size,118 align_corners=True,119 method=tf.compat.v1.image.ResizeMethod.BILINEAR)120 else:121 expected_tensor = tf.compat.v1.image.resize(122 input_tensor,123 target_size,124 align_corners=True,125 method=tf.compat.v1.image.ResizeMethod.NEAREST_NEIGHBOR)126 127 np.testing.assert_equal(result_tensor.numpy(), expected_tensor.numpy())128 129 def test_resize_bilinear_v1_compatibility(self):130 # Test for odd and even input, and output shapes.131 input_shapes = [(2, 10, 10, 3), (2, 11, 11, 3), (1, 11, 11, 64)]132 target_sizes = [[19, 19], [20, 20], [10, 10]]133 134 for shape, target_size in itertools.product(input_shapes, target_sizes):135 input_tensor = tf.random.uniform(shape=shape)136 result_tensor = utils.resize_bilinear(input_tensor, target_size)137 expected_tensor = tf.compat.v1.image.resize(138 input_tensor,139 target_size,140 align_corners=True,141 method=tf.compat.v1.image.ResizeMethod.BILINEAR)142 self.assertAllClose(result_tensor, expected_tensor)143 144 def test_make_divisible(self):145 value, divisor, min_value = 17, 2, 8146 new_value = utils.make_divisible(value, divisor, min_value)147 self.assertAllEqual(new_value, 18)148 149 value, divisor, min_value = 17, 2, 22150 new_value = utils.make_divisible(value, divisor, min_value)151 self.assertAllEqual(new_value, 22)152 153 def test_transpose_and_reshape_for_attention_operation(self):154 images = tf.zeros([2, 8, 11, 2])155 output = utils.transpose_and_reshape_for_attention_operation(images)156 self.assertEqual(output.get_shape().as_list(), [2, 11, 16])157 158 def test_reshape_and_transpose_for_attention_operation(self):159 images = tf.zeros([2, 11, 16])160 output = utils.reshape_and_transpose_for_attention_operation(images,161 num_heads=8)162 self.assertEqual(output.get_shape().as_list(), [2, 8, 11, 2])163 164 def test_safe_setattr_raise_error(self):165 layer = tf.keras.layers.Conv2D(1, 1)166 with self.assertRaises(ValueError):167 utils.safe_setattr(layer, 'filters', 3)168 169 utils.safe_setattr(layer, 'another_conv', tf.keras.layers.Conv2D(1, 1))170 with self.assertRaises(ValueError):171 utils.safe_setattr(layer, 'another_conv', tf.keras.layers.Conv2D(1, 1))172 173 def test_pad_sequence_with_none(self):174 sequence = [1, 2]175 output_2 = utils.pad_sequence_with_none(sequence, target_length=2)176 self.assertEqual(output_2, [1, 2])177 output_3 = utils.pad_sequence_with_none(sequence, target_length=3)178 self.assertEqual(output_3, [1, 2, None])179 180 def test_strided_downsample(self):181 inputs = tf.zeros([2, 11, 11])182 output = utils.strided_downsample(inputs, target_size=[6, 6])183 self.assertEqual(output.get_shape().as_list(), [2, 6, 6])184 185 def test_get_stuff_class_ids(self):186 # num_thing_stuff_classes does not include `void` class.187 num_thing_stuff_classes = 5188 thing_class_ids = [3, 4]189 void_label_list = [5, 0]190 expected_stuff_class_ids_list = [191 [0, 1, 2], [1, 2, 5]192 ]193 for void_label, expected_stuff_class_ids in zip(194 void_label_list, expected_stuff_class_ids_list):195 stuff_class_ids = utils.get_stuff_class_ids(196 num_thing_stuff_classes, thing_class_ids, void_label)197 np.testing.assert_equal(stuff_class_ids,198 expected_stuff_class_ids)199 200if __name__ == '__main__':201 tf.test.main()202 