efficientnet.py 11.6 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# 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.
Yeqing Li's avatar
Yeqing Li committed
14

Abdullah Rashwan's avatar
Abdullah Rashwan committed
15
16
17
"""Contains definitions of EfficientNet Networks."""

import math
Fan Yang's avatar
Fan Yang committed
18
19
from typing import Any, List, Tuple

Abdullah Rashwan's avatar
Abdullah Rashwan committed
20
# Import libraries
Fan Yang's avatar
Fan Yang committed
21

Abdullah Rashwan's avatar
Abdullah Rashwan committed
22
import tensorflow as tf
Fan Yang's avatar
Fan Yang committed
23
24

from official.modeling import hyperparams
Abdullah Rashwan's avatar
Abdullah Rashwan committed
25
from official.modeling import tf_utils
Yeqing Li's avatar
Yeqing Li committed
26
from official.vision.beta.modeling.backbones import factory
Abdullah Rashwan's avatar
Abdullah Rashwan committed
27
from official.vision.beta.modeling.layers import nn_blocks
28
from official.vision.beta.modeling.layers import nn_layers
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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

layers = tf.keras.layers

# The fixed EfficientNet-B0 architecture discovered by NAS.
# Each element represents a specification of a building block:
# (block_fn, block_repeats, kernel_size, strides, expand_ratio, in_filters,
# out_filters, is_output)
EN_B0_BLOCK_SPECS = [
    ('mbconv', 1, 3, 1, 1, 32, 16, False),
    ('mbconv', 2, 3, 2, 6, 16, 24, True),
    ('mbconv', 2, 5, 2, 6, 24, 40, True),
    ('mbconv', 3, 3, 2, 6, 40, 80, False),
    ('mbconv', 3, 5, 1, 6, 80, 112, True),
    ('mbconv', 4, 5, 2, 6, 112, 192, False),
    ('mbconv', 1, 3, 1, 6, 192, 320, True),
]

SCALING_MAP = {
    'b0': dict(width_scale=1.0, depth_scale=1.0),
    'b1': dict(width_scale=1.0, depth_scale=1.1),
    'b2': dict(width_scale=1.1, depth_scale=1.2),
    'b3': dict(width_scale=1.2, depth_scale=1.4),
    'b4': dict(width_scale=1.4, depth_scale=1.8),
    'b5': dict(width_scale=1.6, depth_scale=2.2),
    'b6': dict(width_scale=1.8, depth_scale=2.6),
    'b7': dict(width_scale=2.0, depth_scale=3.1),
}


Fan Yang's avatar
Fan Yang committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class BlockSpec():
  """A container class that specifies the block configuration for MnasNet."""

  def __init__(self, block_fn: str, block_repeats: int, kernel_size: int,
               strides: int, expand_ratio: float, in_filters: int,
               out_filters: int, is_output: bool, width_scale: float,
               depth_scale: float):
    self.block_fn = block_fn
    self.block_repeats = round_repeats(block_repeats, depth_scale)
    self.kernel_size = kernel_size
    self.strides = strides
    self.expand_ratio = expand_ratio
    self.in_filters = nn_layers.round_filters(in_filters, width_scale)
    self.out_filters = nn_layers.round_filters(out_filters, width_scale)
    self.is_output = is_output


def round_repeats(repeats: int, multiplier: float, skip: bool = False) -> int:
Fan Yang's avatar
Fan Yang committed
76
  """Returns rounded number of filters based on depth multiplier."""
Abdullah Rashwan's avatar
Abdullah Rashwan committed
77
78
79
80
81
  if skip or not multiplier:
    return repeats
  return int(math.ceil(multiplier * repeats))


Fan Yang's avatar
Fan Yang committed
82
83
def block_spec_decoder(specs: List[Tuple[Any, ...]], width_scale: float,
                       depth_scale: float) -> List[BlockSpec]:
Fan Yang's avatar
Fan Yang committed
84
  """Decodes and returns specs for a block."""
Abdullah Rashwan's avatar
Abdullah Rashwan committed
85
86
87
88
89
90
91
92
93
94
95
96
  decoded_specs = []
  for s in specs:
    s = s + (
        width_scale,
        depth_scale,
    )
    decoded_specs.append(BlockSpec(*s))
  return decoded_specs


@tf.keras.utils.register_keras_serializable(package='Vision')
class EfficientNet(tf.keras.Model):
Fan Yang's avatar
Fan Yang committed
97
98
99
100
101
102
103
  """Creates an EfficientNet family model.

  This implements the EfficientNet model from:
    Mingxing Tan, Quoc V. Le.
    EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks.
    (https://arxiv.org/pdf/1905.11946)
  """
Abdullah Rashwan's avatar
Abdullah Rashwan committed
104
105

  def __init__(self,
Fan Yang's avatar
Fan Yang committed
106
107
108
109
110
111
112
113
114
115
116
117
               model_id: str,
               input_specs: tf.keras.layers.InputSpec = layers.InputSpec(
                   shape=[None, None, None, 3]),
               se_ratio: float = 0.0,
               stochastic_depth_drop_rate: float = 0.0,
               kernel_initializer: str = 'VarianceScaling',
               kernel_regularizer: tf.keras.regularizers.Regularizer = None,
               bias_regularizer: tf.keras.regularizers.Regularizer = None,
               activation: str = 'relu',
               use_sync_bn: bool = False,
               norm_momentum: float = 0.99,
               norm_epsilon: float = 0.001,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
118
               **kwargs):
Fan Yang's avatar
Fan Yang committed
119
    """Initializes an EfficientNet model.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
120
121

    Args:
Fan Yang's avatar
Fan Yang committed
122
123
124
125
126
127
128
129
130
131
      model_id: A `str` of model ID of EfficientNet.
      input_specs: A `tf.keras.layers.InputSpec` of the input tensor.
      se_ratio: A `float` of squeeze and excitation ratio for inverted
        bottleneck blocks.
      stochastic_depth_drop_rate: A `float` of drop rate for drop connect layer.
      kernel_initializer: A `str` for kernel initializer of 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.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
132
        Default to None.
Fan Yang's avatar
Fan Yang committed
133
134
135
136
137
      activation: A `str` of name of the activation function.
      use_sync_bn: If True, use synchronized batch normalization.
      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.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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
    """
    self._model_id = model_id
    self._input_specs = input_specs
    self._se_ratio = se_ratio
    self._stochastic_depth_drop_rate = stochastic_depth_drop_rate
    self._use_sync_bn = use_sync_bn
    self._activation = activation
    self._kernel_initializer = kernel_initializer
    self._norm_momentum = norm_momentum
    self._norm_epsilon = norm_epsilon
    self._kernel_regularizer = kernel_regularizer
    self._bias_regularizer = bias_regularizer
    if use_sync_bn:
      self._norm = layers.experimental.SyncBatchNormalization
    else:
      self._norm = layers.BatchNormalization

    if tf.keras.backend.image_data_format() == 'channels_last':
      bn_axis = -1
    else:
      bn_axis = 1

    # Build EfficientNet.
    inputs = tf.keras.Input(shape=input_specs.shape[1:])
    width_scale = SCALING_MAP[model_id]['width_scale']
    depth_scale = SCALING_MAP[model_id]['depth_scale']

    # Build stem.
    x = layers.Conv2D(
167
        filters=nn_layers.round_filters(32, width_scale),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        kernel_size=3,
        strides=2,
        use_bias=False,
        padding='same',
        kernel_initializer=self._kernel_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer)(
            inputs)
    x = self._norm(
        axis=bn_axis, momentum=norm_momentum, epsilon=norm_epsilon)(
            x)
    x = tf_utils.get_activation(activation)(x)

    # Build intermediate blocks.
    endpoints = {}
    endpoint_level = 2
    decoded_specs = block_spec_decoder(EN_B0_BLOCK_SPECS, width_scale,
                                       depth_scale)

    for i, specs in enumerate(decoded_specs):
      x = self._block_group(
          inputs=x, specs=specs, name='block_group_{}'.format(i))
      if specs.is_output:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
191
        endpoints[str(endpoint_level)] = x
Abdullah Rashwan's avatar
Abdullah Rashwan committed
192
193
194
        endpoint_level += 1

    # Build output specs for downstream tasks.
Tianjian Meng's avatar
Tianjian Meng committed
195
    self._output_specs = {l: endpoints[l].get_shape() for l in endpoints}
Abdullah Rashwan's avatar
Abdullah Rashwan committed
196
197
198

    # Build the final conv for classification.
    x = layers.Conv2D(
199
        filters=nn_layers.round_filters(1280, width_scale),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
200
201
202
203
204
205
206
207
208
209
210
        kernel_size=1,
        strides=1,
        use_bias=False,
        padding='same',
        kernel_initializer=self._kernel_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer)(
            x)
    x = self._norm(
        axis=bn_axis, momentum=norm_momentum, epsilon=norm_epsilon)(
            x)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
211
    endpoints[str(endpoint_level)] = tf_utils.get_activation(activation)(x)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
212
213
214
215

    super(EfficientNet, self).__init__(
        inputs=inputs, outputs=endpoints, **kwargs)

Fan Yang's avatar
Fan Yang committed
216
217
218
219
  def _block_group(self,
                   inputs: tf.Tensor,
                   specs: BlockSpec,
                   name: str = 'block_group'):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
220
221
222
    """Creates one group of blocks for the EfficientNet model.

    Args:
Fan Yang's avatar
Fan Yang committed
223
224
225
      inputs: A `tf.Tensor` of size `[batch, channels, height, width]`.
      specs: The specifications for one inverted bottleneck block group.
      name: A `str` name for the block.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
226
227

    Returns:
Fan Yang's avatar
Fan Yang committed
228
      The output `tf.Tensor` of the block layer.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
    """
    if specs.block_fn == 'mbconv':
      block_fn = nn_blocks.InvertedBottleneckBlock
    else:
      raise ValueError('Block func {} not supported.'.format(specs.block_fn))

    x = block_fn(
        in_filters=specs.in_filters,
        out_filters=specs.out_filters,
        expand_ratio=specs.expand_ratio,
        strides=specs.strides,
        kernel_size=specs.kernel_size,
        se_ratio=self._se_ratio,
        stochastic_depth_drop_rate=self._stochastic_depth_drop_rate,
        kernel_initializer=self._kernel_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer,
        activation=self._activation,
        use_sync_bn=self._use_sync_bn,
        norm_momentum=self._norm_momentum,
        norm_epsilon=self._norm_epsilon)(
            inputs)

    for _ in range(1, specs.block_repeats):
      x = block_fn(
          in_filters=specs.out_filters,  # Set 'in_filters' to 'out_filters'.
          out_filters=specs.out_filters,
          expand_ratio=specs.expand_ratio,
          strides=1,  # Fix strides to 1.
          kernel_size=specs.kernel_size,
          se_ratio=self._se_ratio,
          stochastic_depth_drop_rate=self._stochastic_depth_drop_rate,
          kernel_initializer=self._kernel_initializer,
          kernel_regularizer=self._kernel_regularizer,
          bias_regularizer=self._bias_regularizer,
          activation=self._activation,
          use_sync_bn=self._use_sync_bn,
          norm_momentum=self._norm_momentum,
          norm_epsilon=self._norm_epsilon)(
              x)

    return tf.identity(x, name=name)

  def get_config(self):
    config_dict = {
        'model_id': self._model_id,
        'se_ratio': self._se_ratio,
        'stochastic_depth_drop_rate': self._stochastic_depth_drop_rate,
        'kernel_initializer': self._kernel_initializer,
        'kernel_regularizer': self._kernel_regularizer,
        'bias_regularizer': self._bias_regularizer,
        'activation': self._activation,
        'use_sync_bn': self._use_sync_bn,
        'norm_momentum': self._norm_momentum,
        'norm_epsilon': self._norm_epsilon
    }
    return config_dict

  @classmethod
  def from_config(cls, config, custom_objects=None):
    return cls(**config)

  @property
  def output_specs(self):
    """A dict of {level: TensorShape} pairs for the model output."""
    return self._output_specs
Yeqing Li's avatar
Yeqing Li committed
295
296
297
298
299


@factory.register_backbone_builder('efficientnet')
def build_efficientnet(
    input_specs: tf.keras.layers.InputSpec,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
300
301
    backbone_config: hyperparams.Config,
    norm_activation_config: hyperparams.Config,
Yeqing Li's avatar
Yeqing Li committed
302
    l2_regularizer: tf.keras.regularizers.Regularizer = None) -> tf.keras.Model:
Fan Yang's avatar
Fan Yang committed
303
  """Builds EfficientNet backbone from a config."""
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
304
305
  backbone_type = backbone_config.type
  backbone_cfg = backbone_config.get()
Yeqing Li's avatar
Yeqing Li committed
306
307
308
309
310
311
312
313
314
315
316
317
318
  assert backbone_type == 'efficientnet', (f'Inconsistent backbone type '
                                           f'{backbone_type}')

  return EfficientNet(
      model_id=backbone_cfg.model_id,
      input_specs=input_specs,
      stochastic_depth_drop_rate=backbone_cfg.stochastic_depth_drop_rate,
      se_ratio=backbone_cfg.se_ratio,
      activation=norm_activation_config.activation,
      use_sync_bn=norm_activation_config.use_sync_bn,
      norm_momentum=norm_activation_config.norm_momentum,
      norm_epsilon=norm_activation_config.norm_epsilon,
      kernel_regularizer=l2_regularizer)