Пример #1
0
    def test_spinenet_creation(self, model_id):
        """Test creation of SpineNet models."""
        input_size = 128
        min_level = 3
        max_level = 7

        input_specs = tf.keras.layers.InputSpec(
            shape=[None, input_size, input_size, 3])
        network = backbones.SpineNet(input_specs=input_specs,
                                     min_level=min_level,
                                     max_level=max_level,
                                     norm_momentum=0.99,
                                     norm_epsilon=1e-5)

        backbone_config = backbones_cfg.Backbone(
            type='spinenet',
            spinenet=backbones_cfg.SpineNet(model_id=model_id))
        norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99,
                                                           norm_epsilon=1e-5,
                                                           use_sync_bn=False)

        factory_network = factory.build_backbone(
            input_specs=tf.keras.layers.InputSpec(
                shape=[None, input_size, input_size, 3]),
            backbone_config=backbone_config,
            norm_activation_config=norm_activation_config)

        network_config = network.get_config()
        factory_network_config = factory_network.get_config()

        self.assertEqual(network_config, factory_network_config)
Пример #2
0
    def test_resnet_creation(self, model_id):
        """Test creation of ResNet models."""

        network = backbones.ResNet(model_id=model_id,
                                   se_ratio=0.0,
                                   norm_momentum=0.99,
                                   norm_epsilon=1e-5)

        backbone_config = backbones_cfg.Backbone(type='resnet',
                                                 resnet=backbones_cfg.ResNet(
                                                     model_id=model_id,
                                                     se_ratio=0.0))
        norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99,
                                                           norm_epsilon=1e-5,
                                                           use_sync_bn=False)
        model_config = retinanet_cfg.RetinaNet(
            backbone=backbone_config, norm_activation=norm_activation_config)

        factory_network = factory.build_backbone(
            input_specs=tf.keras.layers.InputSpec(shape=[None, None, None, 3]),
            model_config=model_config)

        network_config = network.get_config()
        factory_network_config = factory_network.get_config()

        self.assertEqual(network_config, factory_network_config)
Пример #3
0
    def test_efficientnet_creation(self, model_id, se_ratio):
        """Test creation of EfficientNet models."""

        network = backbones.EfficientNet(model_id=model_id,
                                         se_ratio=se_ratio,
                                         norm_momentum=0.99,
                                         norm_epsilon=1e-5)

        backbone_config = backbones_cfg.Backbone(
            type='efficientnet',
            efficientnet=backbones_cfg.EfficientNet(model_id=model_id,
                                                    se_ratio=se_ratio))
        norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99,
                                                           norm_epsilon=1e-5,
                                                           use_sync_bn=False)

        factory_network = factory.build_backbone(
            input_specs=tf.keras.layers.InputSpec(shape=[None, None, None, 3]),
            backbone_config=backbone_config,
            norm_activation_config=norm_activation_config)

        network_config = network.get_config()
        factory_network_config = factory_network.get_config()

        self.assertEqual(network_config, factory_network_config)
Пример #4
0
    def test_mobilenet_creation(self, model_id, filter_size_scale):
        """Test creation of Mobilenet models."""

        network = backbones.MobileNet(model_id=model_id,
                                      filter_size_scale=filter_size_scale,
                                      norm_momentum=0.99,
                                      norm_epsilon=1e-5)

        backbone_config = backbones_cfg.Backbone(
            type='mobilenet',
            mobilenet=backbones_cfg.MobileNet(
                model_id=model_id, filter_size_scale=filter_size_scale))
        norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99,
                                                           norm_epsilon=1e-5,
                                                           use_sync_bn=False)

        factory_network = factory.build_backbone(
            input_specs=tf.keras.layers.InputSpec(shape=[None, None, None, 3]),
            backbone_config=backbone_config,
            norm_activation_config=norm_activation_config)

        network_config = network.get_config()
        factory_network_config = factory_network.get_config()

        self.assertEqual(network_config, factory_network_config)
Пример #5
0
 def test_deeplabv3_builder(self, backbone_type, input_size, weight_decay):
     num_classes = 21
     input_specs = tf.keras.layers.InputSpec(
         shape=[None, input_size[0], input_size[1], 3])
     model_config = semantic_segmentation_cfg.SemanticSegmentationModel(
         num_classes=num_classes,
         backbone=backbones.Backbone(type=backbone_type,
                                     mobilenet=backbones.MobileNet(
                                         model_id='MobileNetV2',
                                         output_stride=16)),
         decoder=decoders.Decoder(type='aspp',
                                  aspp=decoders.ASPP(level=4,
                                                     num_filters=256,
                                                     dilation_rates=[],
                                                     spp_layer_version='v1',
                                                     output_tensor=True)),
         head=semantic_segmentation_cfg.SegmentationHead(
             level=4,
             low_level=2,
             num_convs=1,
             upsample_factor=2,
             use_depthwise_convolution=True))
     l2_regularizer = (tf.keras.regularizers.l2(weight_decay)
                       if weight_decay else None)
     model = factory.build_segmentation_model(input_specs=input_specs,
                                              model_config=model_config,
                                              l2_regularizer=l2_regularizer)
     quantization_config = common.Quantization()
     _ = qat_factory.build_qat_segmentation_model(
         model=model,
         quantization=quantization_config,
         input_specs=input_specs)
Пример #6
0
 def test_builder(self, backbone_type, input_size, has_att_heads):
     num_classes = 2
     input_specs = tf.keras.layers.InputSpec(
         shape=[None, input_size[0], input_size[1], 3])
     if has_att_heads:
         attribute_heads_config = [
             retinanet_cfg.AttributeHead(name='att1'),
             retinanet_cfg.AttributeHead(name='att2',
                                         type='classification',
                                         size=2),
         ]
     else:
         attribute_heads_config = None
     model_config = retinanet_cfg.RetinaNet(
         num_classes=num_classes,
         backbone=backbones.Backbone(type=backbone_type),
         head=retinanet_cfg.RetinaNetHead(
             attribute_heads=attribute_heads_config))
     l2_regularizer = tf.keras.regularizers.l2(5e-5)
     _ = factory.build_retinanet(input_specs=input_specs,
                                 model_config=model_config,
                                 l2_regularizer=l2_regularizer)
     if has_att_heads:
         self.assertEqual(model_config.head.attribute_heads[0].as_dict(),
                          dict(name='att1', type='regression', size=1))
         self.assertEqual(model_config.head.attribute_heads[1].as_dict(),
                          dict(name='att2', type='classification', size=2))
class ImageClassificationModel(hyperparams.Config):
    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
    norm_activation: common.NormActivation = common.NormActivation()
    # Adds a BatchNormalization layer pre-GlobalAveragePooling in classification
    add_head_batch_norm: bool = False
Пример #8
0
class MultiHeadModel(hyperparams.Config):
    """Multi head multi task model config, similar to other models but 
  with input, backbone, activation and weight decay shared."""
    input_size: List[int] = dataclasses.field(default_factory=list)
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    norm_activation: common.NormActivation = common.NormActivation()
    heads: List[Submodel] = dataclasses.field(default_factory=list)
    l2_weight_decay: float = 0.0
Пример #9
0
class YoloModel(hyperparams.Config):
  num_classes: int = 0
  input_size: List[int] = dataclasses.field(default_factory=list)
  min_level: int = 3 # only for FPN or NASFPN
  max_level: int = 6 # only for FPN or NASFPN
  head: hyperparams.Config = YoloHead()
  backbone: backbones.Backbone = backbones.Backbone(
      type='resnet', resnet=backbones.ResNet())
  decoder: decoders.Decoder = decoders.Decoder(type='identity')
  norm_activation: common.NormActivation = common.NormActivation()
Пример #10
0
class SemanticSegmentationModel(hyperparams.Config):
    """Semantic segmentation model config."""
    num_classes: int = 0
    input_size: List[int] = dataclasses.field(default_factory=list)
    min_level: int = 3
    max_level: int = 6
    head: SegmentationHead = SegmentationHead()
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    decoder: decoders.Decoder = decoders.Decoder(type='identity')
    norm_activation: common.NormActivation = common.NormActivation()
Пример #11
0
 def test_builder(self, backbone_type, input_size):
     num_classes = 2
     input_specs = tf.keras.layers.InputSpec(
         shape=[None, input_size[0], input_size[1], 3])
     model_config = maskrcnn_cfg.MaskRCNN(
         num_classes=num_classes,
         backbone=backbones.Backbone(type=backbone_type))
     l2_regularizer = tf.keras.regularizers.l2(5e-5)
     _ = factory.build_maskrcnn(input_specs=input_specs,
                                model_config=model_config,
                                l2_regularizer=l2_regularizer)
Пример #12
0
class BASNetModel(hyperparams.Config):
  """BASNet model config."""
  num_classes: int = 0
  input_size: List[int] = dataclasses.field(default_factory=list)
  #min_level: int = 3
  #max_level: int = 6
  #head: BASNetHead = BASNetHead()
  backbone: backbones.Backbone = backbones.Backbone(
      type='basnet_en', basnet_en=backbones.BASNet_En())
  decoder: decoders.Decoder = decoders.Decoder(type='basnet_de')
  norm_activation: common.NormActivation = common.NormActivation()
Пример #13
0
 def test_builder(self, backbone_type, input_size, weight_decay):
     num_classes = 2
     input_specs = tf.keras.layers.InputSpec(
         shape=[None, input_size[0], input_size[1], 3])
     model_config = classification_cfg.ImageClassificationModel(
         num_classes=num_classes,
         backbone=backbones.Backbone(type=backbone_type))
     l2_regularizer = (tf.keras.regularizers.l2(weight_decay)
                       if weight_decay else None)
     _ = factory.build_classification_model(input_specs=input_specs,
                                            model_config=model_config,
                                            l2_regularizer=l2_regularizer)
Пример #14
0
class ImageClassificationModel(hyperparams.Config):
  """The model config."""
  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
  norm_activation: common.NormActivation = common.NormActivation(
      use_sync_bn=False)
  # Adds a BatchNormalization layer pre-GlobalAveragePooling in classification
  add_head_batch_norm: bool = False
  kernel_initializer: str = 'random_uniform'
Пример #15
0
class SimCLRModel(hyperparams.Config):
    """SimCLR model config."""
    input_size: List[int] = dataclasses.field(default_factory=list)
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    projection_head: ProjectionHead = ProjectionHead(proj_output_dim=128,
                                                     num_proj_layers=3,
                                                     ft_proj_idx=1)
    supervised_head: SupervisedHead = SupervisedHead(num_classes=1001)
    norm_activation: common.NormActivation = common.NormActivation(
        norm_momentum=0.9, norm_epsilon=1e-5, use_sync_bn=False)
    mode: str = simclr_model.PRETRAIN
    backbone_trainable: bool = True
Пример #16
0
class RetinaNet(hyperparams.Config):
    num_classes: int = 0
    input_size: List[int] = dataclasses.field(default_factory=list)
    min_level: int = 3
    max_level: int = 7
    anchor: Anchor = Anchor()
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    decoder: decoders.Decoder = decoders.Decoder(type='fpn',
                                                 fpn=decoders.FPN())
    head: RetinaNetHead = RetinaNetHead()
    detection_generator: DetectionGenerator = DetectionGenerator()
    norm_activation: common.NormActivation = common.NormActivation()
Пример #17
0
 def test_builder(self, backbone_type, input_size,
                  segmentation_backbone_type, segmentation_decoder_type,
                  fusion_type):
     num_classes = 2
     input_specs = tf.keras.layers.InputSpec(
         shape=[None, input_size[0], input_size[1], 3])
     segmentation_output_stride = 16
     level = int(np.math.log2(segmentation_output_stride))
     segmentation_model = semantic_segmentation.SemanticSegmentationModel(
         num_classes=2,
         backbone=backbones.Backbone(type=segmentation_backbone_type),
         decoder=decoders.Decoder(type=segmentation_decoder_type),
         head=semantic_segmentation.SegmentationHead(level=level))
     model_config = panoptic_maskrcnn_cfg.PanopticMaskRCNN(
         num_classes=num_classes,
         segmentation_model=segmentation_model,
         backbone=backbones.Backbone(type=backbone_type),
         shared_backbone=segmentation_backbone_type is None,
         shared_decoder=segmentation_decoder_type is None)
     l2_regularizer = tf.keras.regularizers.l2(5e-5)
     _ = factory.build_panoptic_maskrcnn(input_specs=input_specs,
                                         model_config=model_config,
                                         l2_regularizer=l2_regularizer)
Пример #18
0
class SimCLRMTModelConfig(hyperparams.Config):
    """Model config for multi-task SimCLR model."""
    input_size: List[int] = dataclasses.field(default_factory=list)
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    backbone_trainable: bool = True
    projection_head: simclr_configs.ProjectionHead = simclr_configs.ProjectionHead(
        proj_output_dim=128, num_proj_layers=3, ft_proj_idx=1)
    norm_activation: common.NormActivation = common.NormActivation(
        norm_momentum=0.9, norm_epsilon=1e-5, use_sync_bn=False)
    heads: Tuple[SimCLRMTHeadConfig, ...] = ()
    # L2 weight decay is used in the model, not in task.
    # Note that this can not be used together with lars optimizer.
    l2_weight_decay: float = 0.0
class AutosegEdgeTPUModelConfig(hyperparams.Config):
  """Autoseg-EdgeTPU segmentation model config."""
  num_classes: int = 0
  input_size: List[int] = dataclasses.field(default_factory=list)
  backbone: backbones.Backbone = backbones.Backbone()
  head: BiFPNHeadConfig = BiFPNHeadConfig()
  model_params: Mapping[str, Any] = dataclasses.field(
      default_factory=lambda: {  # pylint: disable=g-long-lambda
          'model_name': 'autoseg_edgetpu_backbone_s',
          'checkpoint_format': 'tf_checkpoint',
          'overrides': {
              'batch_norm': 'tpu',
              'rescale_input': False,
              'backbone_only': True,
              'resolution': 512
          }
      })
Пример #20
0
class MaskRCNN(hyperparams.Config):
    num_classes: int = 0
    input_size: List[int] = dataclasses.field(default_factory=list)
    min_level: int = 2
    max_level: int = 6
    anchor: Anchor = Anchor()
    include_mask: bool = True
    backbone: backbones.Backbone = backbones.Backbone(
        type='resnet', resnet=backbones.ResNet())
    decoder: decoders.Decoder = decoders.Decoder(type='fpn',
                                                 fpn=decoders.FPN())
    rpn_head: RPNHead = RPNHead()
    detection_head: DetectionHead = DetectionHead()
    roi_generator: ROIGenerator = ROIGenerator()
    roi_sampler: ROISampler = ROISampler()
    roi_aligner: ROIAligner = ROIAligner()
    detection_generator: DetectionGenerator = DetectionGenerator()
    mask_head: Optional[MaskHead] = MaskHead()
    mask_sampler: Optional[MaskSampler] = MaskSampler()
    mask_roi_aligner: Optional[MaskROIAligner] = MaskROIAligner()
    norm_activation: common.NormActivation = common.NormActivation(
        norm_momentum=0.997, norm_epsilon=0.0001, use_sync_bn=True)
Пример #21
0
    def test_builder(self, backbone_type, input_size, has_attribute_heads):
        num_classes = 2
        input_specs = tf.keras.layers.InputSpec(
            shape=[None, input_size[0], input_size[1], 3])
        if has_attribute_heads:
            attribute_heads_config = [
                retinanet_cfg.AttributeHead(name='att1'),
                retinanet_cfg.AttributeHead(name='att2',
                                            type='classification',
                                            size=2),
            ]
        else:
            attribute_heads_config = None
        model_config = retinanet_cfg.RetinaNet(
            num_classes=num_classes,
            backbone=backbones.Backbone(
                type=backbone_type,
                spinenet_mobile=backbones.SpineNetMobile(
                    model_id='49',
                    stochastic_depth_drop_rate=0.2,
                    min_level=3,
                    max_level=7,
                    use_keras_upsampling_2d=True)),
            head=retinanet_cfg.RetinaNetHead(
                attribute_heads=attribute_heads_config))
        l2_regularizer = tf.keras.regularizers.l2(5e-5)
        quantization_config = common.Quantization()
        model = factory.build_retinanet(input_specs=input_specs,
                                        model_config=model_config,
                                        l2_regularizer=l2_regularizer)

        _ = qat_factory.build_qat_retinanet(model=model,
                                            quantization=quantization_config,
                                            model_config=model_config)
        if has_attribute_heads:
            self.assertEqual(model_config.head.attribute_heads[0].as_dict(),
                             dict(name='att1', type='regression', size=1))
            self.assertEqual(model_config.head.attribute_heads[1].as_dict(),
                             dict(name='att2', type='classification', size=2))
Пример #22
0
def cascadercnn_spinenet_coco() -> cfg.ExperimentConfig:
  """COCO object detection with Cascade RCNN-RS with SpineNet backbone."""
  steps_per_epoch = 463
  coco_val_samples = 5000
  train_batch_size = 256
  eval_batch_size = 8

  config = cfg.ExperimentConfig(
      runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'),
      task=MaskRCNNTask(
          annotation_file=os.path.join(COCO_INPUT_PATH_BASE,
                                       'instances_val2017.json'),
          model=MaskRCNN(
              backbone=backbones.Backbone(
                  type='spinenet',
                  spinenet=backbones.SpineNet(
                      model_id='49',
                      min_level=3,
                      max_level=7,
                  )),
              decoder=decoders.Decoder(
                  type='identity', identity=decoders.Identity()),
              roi_sampler=ROISampler(cascade_iou_thresholds=[0.6, 0.7]),
              detection_head=DetectionHead(
                  class_agnostic_bbox_pred=True, cascade_class_ensemble=True),
              anchor=Anchor(anchor_size=3),
              norm_activation=common.NormActivation(
                  use_sync_bn=True, activation='swish'),
              num_classes=91,
              input_size=[640, 640, 3],
              min_level=3,
              max_level=7,
              include_mask=True),
          losses=Losses(l2_weight_decay=0.00004),
          train_data=DataConfig(
              input_path=os.path.join(COCO_INPUT_PATH_BASE, 'train*'),
              is_training=True,
              global_batch_size=train_batch_size,
              parser=Parser(
                  aug_rand_hflip=True, aug_scale_min=0.1, aug_scale_max=2.5)),
          validation_data=DataConfig(
              input_path=os.path.join(COCO_INPUT_PATH_BASE, 'val*'),
              is_training=False,
              global_batch_size=eval_batch_size,
              drop_remainder=False)),
      trainer=cfg.TrainerConfig(
          train_steps=steps_per_epoch * 500,
          validation_steps=coco_val_samples // eval_batch_size,
          validation_interval=steps_per_epoch,
          steps_per_loop=steps_per_epoch,
          summary_interval=steps_per_epoch,
          checkpoint_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'sgd',
                  'sgd': {
                      'momentum': 0.9
                  }
              },
              'learning_rate': {
                  'type': 'stepwise',
                  'stepwise': {
                      'boundaries': [
                          steps_per_epoch * 475, steps_per_epoch * 490
                      ],
                      'values': [0.32, 0.032, 0.0032],
                  }
              },
              'warmup': {
                  'type': 'linear',
                  'linear': {
                      'warmup_steps': 2000,
                      'warmup_learning_rate': 0.0067
                  }
              }
          })),
      restrictions=[
          'task.train_data.is_training != None',
          'task.validation_data.is_training != None',
          'task.model.min_level == task.model.backbone.spinenet.min_level',
          'task.model.max_level == task.model.backbone.spinenet.max_level',
      ])
  return config
Пример #23
0
def maskrcnn_spinenet_coco() -> cfg.ExperimentConfig:
    """COCO object detection with Mask R-CNN with SpineNet backbone."""
    steps_per_epoch = 463
    coco_val_samples = 5000

    config = cfg.ExperimentConfig(
        runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'),
        task=MaskRCNNTask(
            annotation_file=os.path.join(COCO_INPUT_PATH_BASE,
                                         'instances_val2017.json'),
            model=MaskRCNN(
                backbone=backbones.Backbone(
                    type='spinenet',
                    spinenet=backbones.SpineNet(model_id='49')),
                decoder=decoders.Decoder(type='identity',
                                         identity=decoders.Identity()),
                anchor=Anchor(anchor_size=3),
                norm_activation=common.NormActivation(use_sync_bn=True),
                num_classes=91,
                input_size=[640, 640, 3],
                min_level=3,
                max_level=7,
                include_mask=True),
            losses=Losses(l2_weight_decay=0.00004),
            train_data=DataConfig(input_path=os.path.join(
                COCO_INPUT_PATH_BASE, 'train*'),
                                  is_training=True,
                                  global_batch_size=256,
                                  parser=Parser(aug_rand_hflip=True,
                                                aug_scale_min=0.5,
                                                aug_scale_max=2.0)),
            validation_data=DataConfig(input_path=os.path.join(
                COCO_INPUT_PATH_BASE, 'val*'),
                                       is_training=False,
                                       global_batch_size=8)),
        trainer=cfg.TrainerConfig(
            train_steps=steps_per_epoch * 350,
            validation_steps=coco_val_samples // 8,
            validation_interval=steps_per_epoch,
            steps_per_loop=steps_per_epoch,
            summary_interval=steps_per_epoch,
            checkpoint_interval=steps_per_epoch,
            optimizer_config=optimization.OptimizationConfig({
                'optimizer': {
                    'type': 'sgd',
                    'sgd': {
                        'momentum': 0.9
                    }
                },
                'learning_rate': {
                    'type': 'stepwise',
                    'stepwise': {
                        'boundaries':
                        [steps_per_epoch * 320, steps_per_epoch * 340],
                        'values': [0.28, 0.028, 0.0028],
                    }
                },
                'warmup': {
                    'type': 'linear',
                    'linear': {
                        'warmup_steps': 2000,
                        'warmup_learning_rate': 0.0067
                    }
                }
            })),
        restrictions=[
            'task.train_data.is_training != None',
            'task.validation_data.is_training != None'
        ])
    return config
Пример #24
0
def seg_deeplabv3plus_cityscapes() -> cfg.ExperimentConfig:
    """Image segmentation on imagenet with resnet deeplabv3+."""
    train_batch_size = 16
    eval_batch_size = 16
    steps_per_epoch = CITYSCAPES_TRAIN_EXAMPLES // train_batch_size
    output_stride = 16
    aspp_dilation_rates = [6, 12, 18]
    multigrid = [1, 2, 4]
    stem_type = 'v1'
    level = int(np.math.log2(output_stride))
    config = cfg.ExperimentConfig(
        task=SemanticSegmentationTask(
            model=SemanticSegmentationModel(
                # Cityscapes uses only 19 semantic classes for train/evaluation.
                # The void (background) class is ignored in train and evaluation.
                num_classes=19,
                input_size=[None, None, 3],
                backbone=backbones.Backbone(
                    type='dilated_resnet',
                    dilated_resnet=backbones.DilatedResNet(
                        model_id=101,
                        output_stride=output_stride,
                        stem_type=stem_type,
                        multigrid=multigrid)),
                decoder=decoders.Decoder(
                    type='aspp',
                    aspp=decoders.ASPP(level=level,
                                       dilation_rates=aspp_dilation_rates,
                                       pool_kernel_size=[512, 1024])),
                head=SegmentationHead(level=level,
                                      num_convs=2,
                                      feature_fusion='deeplabv3plus',
                                      low_level=2,
                                      low_level_num_filters=48),
                norm_activation=common.NormActivation(activation='swish',
                                                      norm_momentum=0.99,
                                                      norm_epsilon=1e-3,
                                                      use_sync_bn=True)),
            losses=Losses(l2_weight_decay=1e-4),
            train_data=DataConfig(input_path=os.path.join(
                CITYSCAPES_INPUT_PATH_BASE, 'train_fine**'),
                                  crop_size=[512, 1024],
                                  output_size=[1024, 2048],
                                  is_training=True,
                                  global_batch_size=train_batch_size,
                                  aug_scale_min=0.5,
                                  aug_scale_max=2.0),
            validation_data=DataConfig(input_path=os.path.join(
                CITYSCAPES_INPUT_PATH_BASE, 'val_fine*'),
                                       output_size=[1024, 2048],
                                       is_training=False,
                                       global_batch_size=eval_batch_size,
                                       resize_eval_groundtruth=True,
                                       drop_remainder=False),
            # resnet101
            init_checkpoint=
            'gs://cloud-tpu-checkpoints/vision-2.0/deeplab/deeplab_resnet101_imagenet/ckpt-62400',
            init_checkpoint_modules='backbone'),
        trainer=cfg.TrainerConfig(
            steps_per_loop=steps_per_epoch,
            summary_interval=steps_per_epoch,
            checkpoint_interval=steps_per_epoch,
            train_steps=500 * steps_per_epoch,
            validation_steps=CITYSCAPES_VAL_EXAMPLES // eval_batch_size,
            validation_interval=steps_per_epoch,
            optimizer_config=optimization.OptimizationConfig({
                'optimizer': {
                    'type': 'sgd',
                    'sgd': {
                        'momentum': 0.9
                    }
                },
                'learning_rate': {
                    'type': 'polynomial',
                    'polynomial': {
                        'initial_learning_rate': 0.01,
                        'decay_steps': 500 * steps_per_epoch,
                        'end_learning_rate': 0.0,
                        'power': 0.9
                    }
                },
                '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
Пример #25
0
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(
                  norm_momentum=0.9, norm_epsilon=1e-5, use_sync_bn=False),
              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
Пример #26
0
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(
                  norm_momentum=0.0,
                  norm_epsilon=1e-5,
                  use_sync_bn=False,
                  activation='swish')),
          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,
              aug_type=common.Augmentation(
                  type='randaug', randaug=common.RandAugment(magnitude=10))),
          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=350 * 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
                  }
              },
              'ema': {
                  'average_decay': 0.9999,
                  'trainable_weights_only': False,
              },
              'learning_rate': {
                  'type': 'cosine',
                  'cosine': {
                      'initial_learning_rate': 1.6,
                      'decay_steps': 350 * steps_per_epoch
                  }
              },
              '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
Пример #27
0
def retinanet_spinenet_mobile_coco() -> cfg.ExperimentConfig:
    """COCO object detection with RetinaNet using Mobile SpineNet backbone."""
    train_batch_size = 256
    eval_batch_size = 8
    steps_per_epoch = COCO_TRAIN_EXAMPLES // train_batch_size
    input_size = 384

    config = cfg.ExperimentConfig(
        runtime=cfg.RuntimeConfig(mixed_precision_dtype='float32'),
        task=RetinaNetTask(
            annotation_file=os.path.join(COCO_INPUT_PATH_BASE,
                                         'instances_val2017.json'),
            model=RetinaNet(
                backbone=backbones.Backbone(
                    type='spinenet_mobile',
                    spinenet_mobile=backbones.SpineNetMobile(
                        model_id='49',
                        stochastic_depth_drop_rate=0.2,
                        min_level=3,
                        max_level=7)),
                decoder=decoders.Decoder(type='identity',
                                         identity=decoders.Identity()),
                head=RetinaNetHead(num_filters=48, use_separable_conv=True),
                anchor=Anchor(anchor_size=3),
                norm_activation=common.NormActivation(use_sync_bn=True,
                                                      activation='swish'),
                num_classes=91,
                input_size=[input_size, input_size, 3],
                min_level=3,
                max_level=7),
            losses=Losses(l2_weight_decay=3e-5),
            train_data=DataConfig(input_path=os.path.join(
                COCO_INPUT_PATH_BASE, 'train*'),
                                  is_training=True,
                                  global_batch_size=train_batch_size,
                                  parser=Parser(aug_rand_hflip=True,
                                                aug_scale_min=0.1,
                                                aug_scale_max=2.0)),
            validation_data=DataConfig(input_path=os.path.join(
                COCO_INPUT_PATH_BASE, 'val*'),
                                       is_training=False,
                                       global_batch_size=eval_batch_size)),
        trainer=cfg.TrainerConfig(
            train_steps=600 * steps_per_epoch,
            validation_steps=COCO_VAL_EXAMPLES // eval_batch_size,
            validation_interval=steps_per_epoch,
            steps_per_loop=steps_per_epoch,
            summary_interval=steps_per_epoch,
            checkpoint_interval=steps_per_epoch,
            optimizer_config=optimization.OptimizationConfig({
                'optimizer': {
                    'type': 'sgd',
                    'sgd': {
                        'momentum': 0.9
                    }
                },
                'learning_rate': {
                    'type': 'stepwise',
                    'stepwise': {
                        'boundaries':
                        [575 * steps_per_epoch, 590 * steps_per_epoch],
                        'values': [
                            0.32 * train_batch_size / 256.0,
                            0.032 * train_batch_size / 256.0,
                            0.0032 * train_batch_size / 256.0
                        ],
                    }
                },
                'warmup': {
                    'type': 'linear',
                    'linear': {
                        'warmup_steps': 2000,
                        'warmup_learning_rate': 0.0067
                    }
                }
            })),
        restrictions=[
            'task.train_data.is_training != None',
            'task.validation_data.is_training != None',
            'task.model.min_level == task.model.backbone.spinenet_mobile.min_level',
            'task.model.max_level == task.model.backbone.spinenet_mobile.max_level',
        ])

    return config
Пример #28
0
def multitask_vision() -> multi_cfg.MultiTaskExperimentConfig:
    """
  Vision task with single backbone and multiple heads.
  Each head can be a segmenter, detector or classifier.
  TODO: use same num_class and input_size in both task and model definition

  multi_cfg.MultiTaskConfig:
    - Retains each task_name, entire task, eval_steps and weights,
        - Entire_task used in respective multitask trainers for train_step
        - Weights used in task_sampler
  
  multi_cfg.MultiTaskTrainerConfig:
    - trainer_type and task_sampler used to configure task sampling in train_lib
    - Normal multi_cfg.TrainerConfig params used directly in train_lib
  """
    input_path_segmentation = ''
    input_path_classification = ''
    input_path_yolo = ''
    steps_per_epoch = 6915 + 2486 + 600
    train_batch_size = 1
    eval_batch_size = 1
    validation_steps = 1021 + 621 + 600

    segmentation_routine = multi_cfg.TaskRoutine(
        task_name='segmentation',
        task_config=SemanticSegmentationSubtask(
            model=SemanticSegmentationModelSpecs(num_classes=19,
                                                 input_size=[256, 256, 3]),
            losses=SegmentationLosses(ignore_label=250,
                                      top_k_percent_pixels=0.3),
            train_data=SegmentationDataConfig(
                output_size=[256, 256],
                input_path=input_path_segmentation,
                global_batch_size=train_batch_size,
                is_training=True,
                aug_scale_min=0.5,
                aug_scale_max=2.0,
                preserve_aspect_ratio=False,
                aug_policy='randaug',
                randaug_magnitude=5,
                randaug_available_ops=[
                    'AutoContrast', 'Equalize', 'Invert', 'Rotate',
                    'Posterize', 'Solarize', 'Color', 'Contrast', 'Brightness',
                    'Sharpness', 'Cutout', 'SolarizeAdd'
                ]),
            validation_data=SegmentationDataConfig(
                output_size=[256, 256],
                input_path=input_path_segmentation,
                global_batch_size=eval_batch_size,
                is_training=False,
                resize_eval_groundtruth=True,
                drop_remainder=False)),
        eval_steps=603,  # check where eval steps is used
        task_weight=1.0)
    classification_routine = multi_cfg.TaskRoutine(
        task_name='classification',
        task_config=ImageClassificationSubtask(
            model=ImageClassificationModelSpecs(num_classes=4,
                                                input_size=[256, 256, 3]),
            losses=ClassificationLosses(label_smoothing=0.1),
            train_data=ClassificationDataConfig(
                input_path=input_path_classification,
                is_training=True,
                global_batch_size=train_batch_size,
                aug_policy='randaug',
                randaug_magnitude=5),
            validation_data=ClassificationDataConfig(
                input_path=input_path_classification,
                is_training=False,
                global_batch_size=eval_batch_size,
                drop_remainder=False)),
        eval_steps=621,  # check where eval steps is used
        task_weight=1.0)
    yolo_routine = multi_cfg.TaskRoutine(
        task_name='yolo',
        task_config=YoloSubtask(
            model=YoloModelSpecs(num_classes=4,
                                 input_size=[256, 256, 3],
                                 head=YoloHead(anchor_per_scale=3,
                                               strides=[16, 32, 64],
                                               anchors=[
                                                   12, 16, 19, 36, 40, 28, 36,
                                                   75, 76, 55, 72, 146, 142,
                                                   110, 192, 243, 459, 401
                                               ],
                                               xy_scale=[1.2, 1.1, 1.05])),
            losses=YoloLosses(l2_weight_decay=1e-4, iou_loss_thres=0.5),
            train_data=YoloDataConfig(input_path=input_path_yolo,
                                      is_training=True,
                                      global_batch_size=train_batch_size,
                                      aug_policy='randaug',
                                      randaug_magnitude=5),
            validation_data=YoloDataConfig(input_path=input_path_yolo,
                                           is_training=False,
                                           global_batch_size=eval_batch_size,
                                           drop_remainder=False)),
        eval_steps=600,  # check where eval steps is used
        task_weight=1.0)

    model_config = MultiHeadModel(
        input_size=[256, 256, 3],
        backbone=backbones.Backbone(type='hardnet',
                                    hardnet=backbones.HardNet(model_id=70)),
        norm_activation=common.NormActivation(activation='relu',
                                              norm_momentum=0.9997,
                                              norm_epsilon=0.001,
                                              use_sync_bn=True),
        heads=[
            Submodel(
                name='classification',
                num_classes=4,
                head=ImageClassificationHead(
                    level=0,  # decoder is identity function
                    num_convs=2,
                    num_filters=256,
                    add_head_batch_norm=False,
                    dropout_rate=0.2)),
            Submodel(name='segmentation',
                     num_classes=19,
                     decoder=decoders.Decoder(
                         type='hardnet',
                         hardnet=decoders.HardNet(model_id=70)),
                     head=SegmentationHead(level=0,
                                           num_convs=0,
                                           feature_fusion=None,
                                           low_level=0,
                                           low_level_num_filters=0)),
            Submodel(name='yolo',
                     num_classes=4,
                     decoder=decoders.Decoder(type='pan',
                                              pan=decoders.PAN(levels=3)),
                     head=YoloHead(anchor_per_scale=3,
                                   strides=[16, 32, 64],
                                   anchors=[
                                       12, 16, 19, 36, 40, 28, 36, 75, 76, 55,
                                       72, 146, 142, 110, 192, 243, 459, 401
                                   ],
                                   xy_scale=[1.2, 1.1, 1.05]))
        ],
        l2_weight_decay=1e-4)

    return multi_cfg.MultiTaskExperimentConfig(
        task=multi_cfg.MultiTaskConfig(model=model_config,
                                       init_checkpoint=None,
                                       task_routines=(segmentation_routine,
                                                      classification_routine,
                                                      yolo_routine)),
        trainer=multi_cfg.MultiTaskTrainerConfig(
            trainer_type="interleaving",
            task_sampler=multi_cfg.TaskSamplingConfig(
                type="proportional",
                proportional=multi_cfg.ProportionalSampleConfig(
                    alpha=1.0)),  # uniform, proportional or annealing
            steps_per_loop=steps_per_epoch,
            summary_interval=steps_per_epoch,
            checkpoint_interval=steps_per_epoch,
            train_steps=45 * steps_per_epoch,
            validation_steps=validation_steps,
            validation_interval=steps_per_epoch,
            best_checkpoint_eval_metric='mean_iou',
            continuous_eval_timeout=3600,
            max_to_keep=5,
            optimizer_config=optimization.OptimizationConfig({
                'optimizer': {
                    'type': 'sgd',
                    'sgd': {
                        'momentum': 0.9
                    }
                },
                'learning_rate': {
                    'type': 'polynomial',
                    'polynomial': {
                        'initial_learning_rate': 0.007,
                        'decay_steps': 45 * steps_per_epoch,
                        'end_learning_rate': 0.0,
                        'power': 0.9
                    }
                },
                'warmup': {
                    'type': 'linear',
                    'linear': {
                        'warmup_steps': 5 * steps_per_epoch,
                        'warmup_learning_rate': 0
                    }
                }
            })))
Пример #29
0
def image_classification_imagenet_mobilenet() -> cfg.ExperimentConfig:
  """Image classification on imagenet with mobilenet."""
  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,
              dropout_rate=0.2,
              input_size=[224, 224, 3],
              backbone=backbones.Backbone(
                  type='mobilenet',
                  mobilenet=backbones.MobileNet(
                      model_id='MobileNetV2', filter_size_scale=1.0)),
              norm_activation=common.NormActivation(
                  norm_momentum=0.997, norm_epsilon=1e-3, use_sync_bn=False)),
          losses=Losses(l2_weight_decay=1e-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),
          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=500 * steps_per_epoch,
          validation_steps=IMAGENET_VAL_EXAMPLES // eval_batch_size,
          validation_interval=steps_per_epoch,
          optimizer_config=optimization.OptimizationConfig({
              'optimizer': {
                  'type': 'rmsprop',
                  'rmsprop': {
                      'rho': 0.9,
                      'momentum': 0.9,
                      'epsilon': 0.002,
                  }
              },
              'learning_rate': {
                  'type': 'exponential',
                  'exponential': {
                      'initial_learning_rate':
                          0.008 * (train_batch_size // 128),
                      'decay_steps':
                          int(2.5 * steps_per_epoch),
                      'decay_rate':
                          0.98,
                      'staircase':
                          True
                  }
              },
              '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
Пример #30
0
def seg_resnetfpn_pascal() -> cfg.ExperimentConfig:
    """Image segmentation on imagenet with resnet-fpn."""
    train_batch_size = 256
    eval_batch_size = 32
    steps_per_epoch = PASCAL_TRAIN_EXAMPLES // train_batch_size
    config = cfg.ExperimentConfig(
        task=SemanticSegmentationTask(
            model=SemanticSegmentationModel(
                num_classes=21,
                input_size=[512, 512, 3],
                min_level=3,
                max_level=7,
                backbone=backbones.Backbone(
                    type='resnet', resnet=backbones.ResNet(model_id=50)),
                decoder=decoders.Decoder(type='fpn', fpn=decoders.FPN()),
                head=SegmentationHead(level=3, num_convs=3),
                norm_activation=common.NormActivation(activation='swish',
                                                      use_sync_bn=True)),
            losses=Losses(l2_weight_decay=1e-4),
            train_data=DataConfig(input_path=os.path.join(
                PASCAL_INPUT_PATH_BASE, 'train_aug*'),
                                  is_training=True,
                                  global_batch_size=train_batch_size,
                                  aug_scale_min=0.2,
                                  aug_scale_max=1.5),
            validation_data=DataConfig(input_path=os.path.join(
                PASCAL_INPUT_PATH_BASE, 'val*'),
                                       is_training=False,
                                       global_batch_size=eval_batch_size,
                                       resize_eval_groundtruth=False,
                                       groundtruth_padded_size=[512, 512],
                                       drop_remainder=False),
        ),
        trainer=cfg.TrainerConfig(
            steps_per_loop=steps_per_epoch,
            summary_interval=steps_per_epoch,
            checkpoint_interval=steps_per_epoch,
            train_steps=450 * steps_per_epoch,
            validation_steps=PASCAL_VAL_EXAMPLES // eval_batch_size,
            validation_interval=steps_per_epoch,
            optimizer_config=optimization.OptimizationConfig({
                'optimizer': {
                    'type': 'sgd',
                    'sgd': {
                        'momentum': 0.9
                    }
                },
                'learning_rate': {
                    'type': 'polynomial',
                    'polynomial': {
                        'initial_learning_rate': 0.007,
                        'decay_steps': 450 * steps_per_epoch,
                        'end_learning_rate': 0.0,
                        'power': 0.9
                    }
                },
                '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