nn_blocks.py 8.96 KB
Newer Older
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Gunho Park's avatar
Gunho Park committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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.

15
16
"""Contains common building blocks for BasNet model."""

Gunho Park's avatar
Gunho Park committed
17
18
19
20
21
22
23
24
25
26
27
28
import tensorflow as tf

from official.modeling import tf_utils


@tf.keras.utils.register_keras_serializable(package='Vision')
class ConvBlock(tf.keras.layers.Layer):
  """A (Conv+BN+Activation) block."""

  def __init__(self,
               filters,
               strides,
Gunho Park's avatar
Gunho Park committed
29
               dilation_rate=1,
Gunho Park's avatar
Gunho Park committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
               kernel_size=3,
               kernel_initializer='VarianceScaling',
               kernel_regularizer=None,
               bias_regularizer=None,
               activation='relu',
               use_bias=False,
               use_sync_bn=False,
               norm_momentum=0.99,
               norm_epsilon=0.001,
               **kwargs):
    """A vgg block with BN after convolutions.

    Args:
      filters: `int` number of filters for the first two convolutions. Note that
        the third and final convolution will use 4 times as many filters.
      strides: `int` block stride. If greater than 1, this block will ultimately
        downsample the input.
47
48
      dilation_rate: `int`, dilation rate for conv layers.
      kernel_size: `int`, kernel size of conv layers.
Gunho Park's avatar
Gunho Park committed
49
50
51
52
53
54
      kernel_initializer: kernel_initializer for convolutional layers.
      kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D.
                          Default to None.
      bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d.
                        Default to None.
      activation: `str` name of the activation function.
55
      use_bias: `bool`, whether or not use bias in conv layers.
Gunho Park's avatar
Gunho Park committed
56
57
58
59
60
61
62
      use_sync_bn: if True, use synchronized batch normalization.
      norm_momentum: `float` normalization omentum for the moving average.
      norm_epsilon: `float` small float added to variance to avoid dividing by
        zero.
      **kwargs: keyword arguments to be passed.
    """
    super(ConvBlock, self).__init__(**kwargs)
Gunho Park's avatar
Gunho Park committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    self._config_dict = {
        'filters': filters,
        'kernel_size': kernel_size,
        'strides': strides,
        'dilation_rate': dilation_rate,
        'kernel_initializer': kernel_initializer,
        'kernel_regularizer': kernel_regularizer,
        'bias_regularizer': bias_regularizer,
        'activation': activation,
        'use_sync_bn': use_sync_bn,
        'use_bias': use_bias,
        'norm_momentum': norm_momentum,
        'norm_epsilon': norm_epsilon
    }
Gunho Park's avatar
Gunho Park committed
77
78
79
80
81
82
83
84
85
86
87
    if use_sync_bn:
      self._norm = tf.keras.layers.experimental.SyncBatchNormalization
    else:
      self._norm = tf.keras.layers.BatchNormalization
    if tf.keras.backend.image_data_format() == 'channels_last':
      self._bn_axis = -1
    else:
      self._bn_axis = 1
    self._activation_fn = tf_utils.get_activation(activation)

  def build(self, input_shape):
Gunho Park's avatar
Gunho Park committed
88
    conv_kwargs = {
89
90
91
92
93
        'padding': 'same',
        'use_bias': self._config_dict['use_bias'],
        'kernel_initializer': self._config_dict['kernel_initializer'],
        'kernel_regularizer': self._config_dict['kernel_regularizer'],
        'bias_regularizer': self._config_dict['bias_regularizer'],
Gunho Park's avatar
Gunho Park committed
94
95
    }

Gunho Park's avatar
Gunho Park committed
96
    self._conv0 = tf.keras.layers.Conv2D(
Gunho Park's avatar
Gunho Park committed
97
98
99
100
101
        filters=self._config_dict['filters'],
        kernel_size=self._config_dict['kernel_size'],
        strides=self._config_dict['strides'],
        dilation_rate=self._config_dict['dilation_rate'],
        **conv_kwargs)
Gunho Park's avatar
Gunho Park committed
102
103
    self._norm0 = self._norm(
        axis=self._bn_axis,
Gunho Park's avatar
Gunho Park committed
104
105
        momentum=self._config_dict['norm_momentum'],
        epsilon=self._config_dict['norm_epsilon'])
Gunho Park's avatar
Gunho Park committed
106
107
108
109

    super(ConvBlock, self).build(input_shape)

  def get_config(self):
Gunho Park's avatar
Gunho Park committed
110
    return self._config_dict
Gunho Park's avatar
Gunho Park committed
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

  def call(self, inputs, training=None):
    x = self._conv0(inputs)
    x = self._norm0(x)
    x = self._activation_fn(x)

    return x


@tf.keras.utils.register_keras_serializable(package='Vision')
class ResBlock(tf.keras.layers.Layer):
  """A residual block."""

  def __init__(self,
               filters,
               strides,
               use_projection=False,
               kernel_initializer='VarianceScaling',
               kernel_regularizer=None,
               bias_regularizer=None,
               activation='relu',
               use_sync_bn=False,
               use_bias=False,
               norm_momentum=0.99,
               norm_epsilon=0.001,
               **kwargs):
    """Initializes a residual block with BN after convolutions.

    Args:
      filters: An `int` number of filters for the first two convolutions. Note
        that the third and final convolution will use 4 times as many filters.
      strides: An `int` block stride. If greater than 1, this block will
        ultimately downsample the input.
      use_projection: A `bool` for whether this block should use a projection
        shortcut (versus the default identity shortcut). This is usually `True`
        for the first block of a block group, which may change the number of
        filters and the resolution.
      kernel_initializer: A `str` of kernel_initializer for convolutional
        layers.
      kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
        Conv2D. Default to None.
      bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2d.
        Default to None.
      activation: A `str` name of the activation function.
      use_sync_bn: A `bool`. If True, use synchronized batch normalization.
      use_bias: A `bool`. If True, use bias in conv2d.
      norm_momentum: A `float` of normalization momentum for the moving average.
      norm_epsilon: A `float` added to variance to avoid dividing by zero.
      **kwargs: Additional keyword arguments to be passed.
    """
    super(ResBlock, self).__init__(**kwargs)
Gunho Park's avatar
Gunho Park committed
162
163
164
165
166
167
168
169
170
171
172
173
174
    self._config_dict = {
        'filters': filters,
        'strides': strides,
        'use_projection': use_projection,
        'kernel_initializer': kernel_initializer,
        'kernel_regularizer': kernel_regularizer,
        'bias_regularizer': bias_regularizer,
        'activation': activation,
        'use_sync_bn': use_sync_bn,
        'use_bias': use_bias,
        'norm_momentum': norm_momentum,
        'norm_epsilon': norm_epsilon
    }
Gunho Park's avatar
Gunho Park committed
175
176
177
178
179
180
181
182
183
184
185
    if use_sync_bn:
      self._norm = tf.keras.layers.experimental.SyncBatchNormalization
    else:
      self._norm = tf.keras.layers.BatchNormalization
    if tf.keras.backend.image_data_format() == 'channels_last':
      self._bn_axis = -1
    else:
      self._bn_axis = 1
    self._activation_fn = tf_utils.get_activation(activation)

  def build(self, input_shape):
Gunho Park's avatar
Gunho Park committed
186
    conv_kwargs = {
187
188
189
190
191
192
        'filters': self._config_dict['filters'],
        'padding': 'same',
        'use_bias': self._config_dict['use_bias'],
        'kernel_initializer': self._config_dict['kernel_initializer'],
        'kernel_regularizer': self._config_dict['kernel_regularizer'],
        'bias_regularizer': self._config_dict['bias_regularizer'],
Gunho Park's avatar
Gunho Park committed
193
194
195
    }

    if self._config_dict['use_projection']:
Gunho Park's avatar
Gunho Park committed
196
      self._shortcut = tf.keras.layers.Conv2D(
Gunho Park's avatar
Gunho Park committed
197
          filters=self._config_dict['filters'],
Gunho Park's avatar
Gunho Park committed
198
          kernel_size=1,
Gunho Park's avatar
Gunho Park committed
199
200
201
202
203
          strides=self._config_dict['strides'],
          use_bias=self._config_dict['use_bias'],
          kernel_initializer=self._config_dict['kernel_initializer'],
          kernel_regularizer=self._config_dict['kernel_regularizer'],
          bias_regularizer=self._config_dict['bias_regularizer'])
Gunho Park's avatar
Gunho Park committed
204
205
      self._norm0 = self._norm(
          axis=self._bn_axis,
Gunho Park's avatar
Gunho Park committed
206
207
          momentum=self._config_dict['norm_momentum'],
          epsilon=self._config_dict['norm_epsilon'])
Gunho Park's avatar
Gunho Park committed
208
209
210

    self._conv1 = tf.keras.layers.Conv2D(
        kernel_size=3,
Gunho Park's avatar
Gunho Park committed
211
212
        strides=self._config_dict['strides'],
        **conv_kwargs)
Gunho Park's avatar
Gunho Park committed
213
214
    self._norm1 = self._norm(
        axis=self._bn_axis,
Gunho Park's avatar
Gunho Park committed
215
216
        momentum=self._config_dict['norm_momentum'],
        epsilon=self._config_dict['norm_epsilon'])
Gunho Park's avatar
Gunho Park committed
217
218
219
220

    self._conv2 = tf.keras.layers.Conv2D(
        kernel_size=3,
        strides=1,
Gunho Park's avatar
Gunho Park committed
221
        **conv_kwargs)
Gunho Park's avatar
Gunho Park committed
222
223
    self._norm2 = self._norm(
        axis=self._bn_axis,
Gunho Park's avatar
Gunho Park committed
224
225
        momentum=self._config_dict['norm_momentum'],
        epsilon=self._config_dict['norm_epsilon'])
Gunho Park's avatar
Gunho Park committed
226
227
228
229

    super(ResBlock, self).build(input_shape)

  def get_config(self):
Gunho Park's avatar
Gunho Park committed
230
    return self._config_dict
Gunho Park's avatar
Gunho Park committed
231
232
233

  def call(self, inputs, training=None):
    shortcut = inputs
Gunho Park's avatar
Gunho Park committed
234
    if self._config_dict['use_projection']:
Gunho Park's avatar
Gunho Park committed
235
236
237
238
239
240
241
242
243
244
245
      shortcut = self._shortcut(shortcut)
      shortcut = self._norm0(shortcut)

    x = self._conv1(inputs)
    x = self._norm1(x)
    x = self._activation_fn(x)

    x = self._conv2(x)
    x = self._norm2(x)

    return self._activation_fn(x + shortcut)