image_classification.py 14.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
15

# Lint as: python3
Abdullah Rashwan's avatar
Abdullah Rashwan committed
16
"""Image classification configuration definition."""
17
import dataclasses
Abdullah Rashwan's avatar
Abdullah Rashwan committed
18
import os
Abdullah Rashwan's avatar
Abdullah Rashwan committed
19
from typing import List, Optional
Abdullah Rashwan's avatar
Abdullah Rashwan committed
20

21
from official.core import config_definitions as cfg
Abdullah Rashwan's avatar
Abdullah Rashwan committed
22
23
24
25
from official.core import exp_factory
from official.modeling import hyperparams
from official.modeling import optimization
from official.vision.beta.configs import common
Abdullah Rashwan's avatar
Abdullah Rashwan committed
26
from official.vision.beta.configs import backbones
Abdullah Rashwan's avatar
Abdullah Rashwan committed
27
28
29
30
31
32
33
34
35
36
37


@dataclasses.dataclass
class DataConfig(cfg.DataConfig):
  """Input config for training."""
  input_path: str = ''
  global_batch_size: int = 0
  is_training: bool = True
  dtype: str = 'float32'
  shuffle_buffer_size: int = 10000
  cycle_length: int = 10
Abdullah Rashwan's avatar
Abdullah Rashwan committed
38
  is_multilabel: bool = False
39
40
41
  aug_rand_hflip: bool = True
  aug_type: Optional[
      common.Augmentation] = None  # Choose from AutoAugment and RandAugment.
42
43
  color_jitter: float = 0.
  random_erasing: Optional[common.RandomErasing] = None
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
44
  file_type: str = 'tfrecord'
Fan Yang's avatar
Fan Yang committed
45
46
  image_field_key: str = 'image/encoded'
  label_field_key: str = 'image/class/label'
Abdullah Rashwan's avatar
Abdullah Rashwan committed
47
  decode_jpeg_only: bool = True
48
  mixup_and_cutmix: Optional[common.MixupAndCutmix] = None
49
  decoder: Optional[common.DataDecoder] = common.DataDecoder()
Abdullah Rashwan's avatar
Abdullah Rashwan committed
50

51
52
53
54
  # Keep for backward compatibility.
  aug_policy: Optional[str] = None  # None, 'autoaug', or 'randaug'.
  randaug_magnitude: Optional[int] = 10

Abdullah Rashwan's avatar
Abdullah Rashwan committed
55
56
57

@dataclasses.dataclass
class ImageClassificationModel(hyperparams.Config):
Pengchong Jin's avatar
Pengchong Jin committed
58
  """The model config."""
Abdullah Rashwan's avatar
Abdullah Rashwan committed
59
60
61
62
63
  num_classes: int = 0
  input_size: List[int] = dataclasses.field(default_factory=list)
  backbone: backbones.Backbone = backbones.Backbone(
      type='resnet', resnet=backbones.ResNet())
  dropout_rate: float = 0.0
Pengchong Jin's avatar
Pengchong Jin committed
64
65
  norm_activation: common.NormActivation = common.NormActivation(
      use_sync_bn=False)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
66
67
  # Adds a BatchNormalization layer pre-GlobalAveragePooling in classification
  add_head_batch_norm: bool = False
68
  kernel_initializer: str = 'random_uniform'
Abdullah Rashwan's avatar
Abdullah Rashwan committed
69
70
71
72


@dataclasses.dataclass
class Losses(hyperparams.Config):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
73
  loss_weight: float = 1.0
Abdullah Rashwan's avatar
Abdullah Rashwan committed
74
75
76
  one_hot: bool = True
  label_smoothing: float = 0.0
  l2_weight_decay: float = 0.0
77
  soft_labels: bool = False
Abdullah Rashwan's avatar
Abdullah Rashwan committed
78
79


Pengchong Jin's avatar
Pengchong Jin committed
80
81
82
83
84
@dataclasses.dataclass
class Evaluation(hyperparams.Config):
  top_k: int = 5


Abdullah Rashwan's avatar
Abdullah Rashwan committed
85
86
@dataclasses.dataclass
class ImageClassificationTask(cfg.TaskConfig):
Pengchong Jin's avatar
Pengchong Jin committed
87
  """The task config."""
Abdullah Rashwan's avatar
Abdullah Rashwan committed
88
89
90
91
  model: ImageClassificationModel = ImageClassificationModel()
  train_data: DataConfig = DataConfig(is_training=True)
  validation_data: DataConfig = DataConfig(is_training=False)
  losses: Losses = Losses()
Pengchong Jin's avatar
Pengchong Jin committed
92
  evaluation: Evaluation = Evaluation()
Abdullah Rashwan's avatar
Abdullah Rashwan committed
93
94
  init_checkpoint: Optional[str] = None
  init_checkpoint_modules: str = 'all'  # all or backbone
Fan Yang's avatar
Fan Yang committed
95
96
  model_output_keys: Optional[List[int]] = dataclasses.field(
      default_factory=list)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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


@exp_factory.register_config_factory('image_classification')
def image_classification() -> cfg.ExperimentConfig:
  """Image classification general."""
  return cfg.ExperimentConfig(
      task=ImageClassificationTask(),
      trainer=cfg.TrainerConfig(),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None'
      ])


IMAGENET_TRAIN_EXAMPLES = 1281167
IMAGENET_VAL_EXAMPLES = 50000
IMAGENET_INPUT_PATH_BASE = 'imagenet-2012-tfrecord'


@exp_factory.register_config_factory('resnet_imagenet')
def image_classification_imagenet() -> cfg.ExperimentConfig:
  """Image classification on imagenet with resnet."""
  train_batch_size = 4096
  eval_batch_size = 4096
  steps_per_epoch = IMAGENET_TRAIN_EXAMPLES // train_batch_size
  config = cfg.ExperimentConfig(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
123
      runtime=cfg.RuntimeConfig(enable_xla=True),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
124
125
126
127
      task=ImageClassificationTask(
          model=ImageClassificationModel(
              num_classes=1001,
              input_size=[224, 224, 3],
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
128
129
              backbone=backbones.Backbone(
                  type='resnet', resnet=backbones.ResNet(model_id=50)),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
130
              norm_activation=common.NormActivation(
Pengchong Jin's avatar
Pengchong Jin committed
131
                  norm_momentum=0.9, norm_epsilon=1e-5, use_sync_bn=False)),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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
          losses=Losses(l2_weight_decay=1e-4),
          train_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'train*'),
              is_training=True,
              global_batch_size=train_batch_size),
          validation_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'valid*'),
              is_training=False,
              global_batch_size=eval_batch_size)),
      trainer=cfg.TrainerConfig(
          steps_per_loop=steps_per_epoch,
          summary_interval=steps_per_epoch,
          checkpoint_interval=steps_per_epoch,
          train_steps=90 * steps_per_epoch,
          validation_steps=IMAGENET_VAL_EXAMPLES // eval_batch_size,
          validation_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'sgd',
                  'sgd': {
                      'momentum': 0.9
                  }
              },
              'learning_rate': {
                  'type': 'stepwise',
                  'stepwise': {
                      'boundaries': [
                          30 * steps_per_epoch, 60 * steps_per_epoch,
                          80 * steps_per_epoch
                      ],
                      'values': [
163
164
165
166
                          0.1 * train_batch_size / 256,
                          0.01 * train_batch_size / 256,
                          0.001 * train_batch_size / 256,
                          0.0001 * train_batch_size / 256,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
                      ]
                  }
              },
              'warmup': {
                  'type': 'linear',
                  'linear': {
                      'warmup_steps': 5 * steps_per_epoch,
                      'warmup_learning_rate': 0
                  }
              }
          })),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None'
      ])

  return config


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@exp_factory.register_config_factory('resnet_rs_imagenet')
def image_classification_imagenet_resnetrs() -> cfg.ExperimentConfig:
  """Image classification on imagenet with resnet-rs."""
  train_batch_size = 4096
  eval_batch_size = 4096
  steps_per_epoch = IMAGENET_TRAIN_EXAMPLES // train_batch_size
  config = cfg.ExperimentConfig(
      task=ImageClassificationTask(
          model=ImageClassificationModel(
              num_classes=1001,
              input_size=[160, 160, 3],
              backbone=backbones.Backbone(
                  type='resnet',
                  resnet=backbones.ResNet(
                      model_id=50,
                      stem_type='v1',
                      resnetd_shortcut=True,
                      replace_stem_max_pool=True,
                      se_ratio=0.25,
                      stochastic_depth_drop_rate=0.0)),
              dropout_rate=0.25,
              norm_activation=common.NormActivation(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
208
209
210
211
                  norm_momentum=0.0,
                  norm_epsilon=1e-5,
                  use_sync_bn=False,
                  activation='swish')),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
212
213
214
215
216
          losses=Losses(l2_weight_decay=4e-5, label_smoothing=0.1),
          train_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'train*'),
              is_training=True,
              global_batch_size=train_batch_size,
217
218
              aug_type=common.Augmentation(
                  type='randaug', randaug=common.RandAugment(magnitude=10))),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
219
220
221
222
223
224
225
226
          validation_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'valid*'),
              is_training=False,
              global_batch_size=eval_batch_size)),
      trainer=cfg.TrainerConfig(
          steps_per_loop=steps_per_epoch,
          summary_interval=steps_per_epoch,
          checkpoint_interval=steps_per_epoch,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
227
          train_steps=350 * steps_per_epoch,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
228
229
230
231
232
233
234
235
236
237
          validation_steps=IMAGENET_VAL_EXAMPLES // eval_batch_size,
          validation_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'sgd',
                  'sgd': {
                      'momentum': 0.9
                  }
              },
              'ema': {
Abdullah Rashwan's avatar
Abdullah Rashwan committed
238
239
                  'average_decay': 0.9999,
                  'trainable_weights_only': False,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
240
241
242
243
              },
              'learning_rate': {
                  'type': 'cosine',
                  'cosine': {
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
244
245
                      'initial_learning_rate': 1.6,
                      'decay_steps': 350 * steps_per_epoch
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
                  }
              },
              'warmup': {
                  'type': 'linear',
                  'linear': {
                      'warmup_steps': 5 * steps_per_epoch,
                      'warmup_learning_rate': 0
                  }
              }
          })),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None'
      ])
  return config


Abdullah Rashwan's avatar
Abdullah Rashwan committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
@exp_factory.register_config_factory('revnet_imagenet')
def image_classification_imagenet_revnet() -> cfg.ExperimentConfig:
  """Returns a revnet config for image classification on imagenet."""
  train_batch_size = 4096
  eval_batch_size = 4096
  steps_per_epoch = IMAGENET_TRAIN_EXAMPLES // train_batch_size

  config = cfg.ExperimentConfig(
      task=ImageClassificationTask(
          model=ImageClassificationModel(
              num_classes=1001,
              input_size=[224, 224, 3],
              backbone=backbones.Backbone(
                  type='revnet', revnet=backbones.RevNet(model_id=56)),
              norm_activation=common.NormActivation(
Pengchong Jin's avatar
Pengchong Jin committed
278
                  norm_momentum=0.9, norm_epsilon=1e-5, use_sync_bn=False),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
              add_head_batch_norm=True),
          losses=Losses(l2_weight_decay=1e-4),
          train_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'train*'),
              is_training=True,
              global_batch_size=train_batch_size),
          validation_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'valid*'),
              is_training=False,
              global_batch_size=eval_batch_size)),
      trainer=cfg.TrainerConfig(
          steps_per_loop=steps_per_epoch,
          summary_interval=steps_per_epoch,
          checkpoint_interval=steps_per_epoch,
          train_steps=90 * steps_per_epoch,
          validation_steps=IMAGENET_VAL_EXAMPLES // eval_batch_size,
          validation_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'sgd',
                  'sgd': {
                      'momentum': 0.9
                  }
              },
              'learning_rate': {
                  'type': 'stepwise',
                  'stepwise': {
                      'boundaries': [
                          30 * steps_per_epoch, 60 * steps_per_epoch,
                          80 * steps_per_epoch
                      ],
                      'values': [0.8, 0.08, 0.008, 0.0008]
                  }
              },
              'warmup': {
                  'type': 'linear',
                  'linear': {
                      'warmup_steps': 5 * steps_per_epoch,
                      'warmup_learning_rate': 0
                  }
              }
          })),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None'
      ])

  return config
327
328
329
330
331


@exp_factory.register_config_factory('mobilenet_imagenet')
def image_classification_imagenet_mobilenet() -> cfg.ExperimentConfig:
  """Image classification on imagenet with mobilenet."""
332
333
  train_batch_size = 4096
  eval_batch_size = 4096
334
335
336
337
338
339
340
341
342
343
  steps_per_epoch = IMAGENET_TRAIN_EXAMPLES // train_batch_size
  config = cfg.ExperimentConfig(
      task=ImageClassificationTask(
          model=ImageClassificationModel(
              num_classes=1001,
              dropout_rate=0.2,
              input_size=[224, 224, 3],
              backbone=backbones.Backbone(
                  type='mobilenet',
                  mobilenet=backbones.MobileNet(
344
                      model_id='MobileNetV2', filter_size_scale=1.0)),
345
              norm_activation=common.NormActivation(
Pengchong Jin's avatar
Pengchong Jin committed
346
                  norm_momentum=0.997, norm_epsilon=1e-3, use_sync_bn=False)),
347
          losses=Losses(l2_weight_decay=1e-5, label_smoothing=0.1),
348
349
350
351
352
353
354
355
356
357
358
359
          train_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'train*'),
              is_training=True,
              global_batch_size=train_batch_size),
          validation_data=DataConfig(
              input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'valid*'),
              is_training=False,
              global_batch_size=eval_batch_size)),
      trainer=cfg.TrainerConfig(
          steps_per_loop=steps_per_epoch,
          summary_interval=steps_per_epoch,
          checkpoint_interval=steps_per_epoch,
360
          train_steps=500 * steps_per_epoch,
361
362
363
364
365
366
          validation_steps=IMAGENET_VAL_EXAMPLES // eval_batch_size,
          validation_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'rmsprop',
                  'rmsprop': {
367
                      'rho': 0.9,
368
369
370
371
372
373
374
                      'momentum': 0.9,
                      'epsilon': 0.002,
                  }
              },
              'learning_rate': {
                  'type': 'exponential',
                  'exponential': {
375
376
377
378
379
380
381
382
                      'initial_learning_rate':
                          0.008 * (train_batch_size // 128),
                      'decay_steps':
                          int(2.5 * steps_per_epoch),
                      'decay_rate':
                          0.98,
                      'staircase':
                          True
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
                  }
              },
              'warmup': {
                  'type': 'linear',
                  'linear': {
                      'warmup_steps': 5 * steps_per_epoch,
                      'warmup_learning_rate': 0
                  }
              },
          })),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None'
      ])

  return config