heads.py 48.3 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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
16
17
18
19
20
"""Classes to build various prediction heads in all supported models."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Yeqing Li's avatar
Yeqing Li committed
21
import functools
22
23

import numpy as np
24
import tensorflow as tf
25

26
from official.vision.detection.modeling.architecture import nn_ops
27
from official.vision.detection.ops import spatial_transform_ops
28
29


Yeqing Li's avatar
Yeqing Li committed
30
class RpnHead(tf.keras.layers.Layer):
31
32
  """Region Proposal Network head."""

Hongkun Yu's avatar
Hongkun Yu committed
33
34
35
36
37
38
39
40
41
42
43
  def __init__(
      self,
      min_level,
      max_level,
      anchors_per_location,
      num_convs=2,
      num_filters=256,
      use_separable_conv=False,
      activation='relu',
      use_batch_norm=True,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
44
45
46
47
48
49
50
    """Initialize params to build Region Proposal Network head.

    Args:
      min_level: `int` number of minimum feature level.
      max_level: `int` number of maximum feature level.
      anchors_per_location: `int` number of number of anchors per pixel
        location.
Yeqing Li's avatar
Yeqing Li committed
51
52
53
54
55
56
      num_convs: `int` number that represents the number of the intermediate
        conv layers before the prediction.
      num_filters: `int` number that represents the number of filters of the
        intermediate conv layers.
      use_separable_conv: `bool`, indicating whether the separable conv layers
        is used.
57
      activation: activation function. Support 'relu' and 'swish'.
Yeqing Li's avatar
Yeqing Li committed
58
      use_batch_norm: 'bool', indicating whether batchnorm layers are added.
Hongkun Yu's avatar
Hongkun Yu committed
59
60
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
61
    """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
62
63
    super().__init__(autocast=False)

64
65
66
    self._min_level = min_level
    self._max_level = max_level
    self._anchors_per_location = anchors_per_location
Pengchong Jin's avatar
Pengchong Jin committed
67
68
69
70
71
72
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))
Yeqing Li's avatar
Yeqing Li committed
73
74
75
76
77
78
79
80
81
82
83
84
85
    self._use_batch_norm = use_batch_norm

    if use_separable_conv:
      self._conv2d_op = functools.partial(
          tf.keras.layers.SeparableConv2D,
          depth_multiplier=1,
          bias_initializer=tf.zeros_initializer())
    else:
      self._conv2d_op = functools.partial(
          tf.keras.layers.Conv2D,
          kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
          bias_initializer=tf.zeros_initializer())

Yeqing Li's avatar
Yeqing Li committed
86
    self._rpn_conv = self._conv2d_op(
Yeqing Li's avatar
Yeqing Li committed
87
        num_filters,
88
89
        kernel_size=(3, 3),
        strides=(1, 1),
Pengchong Jin's avatar
Pengchong Jin committed
90
        activation=(None if self._use_batch_norm else self._activation_op),
91
92
        padding='same',
        name='rpn')
Yeqing Li's avatar
Yeqing Li committed
93
    self._rpn_class_conv = self._conv2d_op(
94
95
96
97
98
        anchors_per_location,
        kernel_size=(1, 1),
        strides=(1, 1),
        padding='valid',
        name='rpn-class')
Yeqing Li's avatar
Yeqing Li committed
99
    self._rpn_box_conv = self._conv2d_op(
100
101
102
103
104
        4 * anchors_per_location,
        kernel_size=(1, 1),
        strides=(1, 1),
        padding='valid',
        name='rpn-box')
Yeqing Li's avatar
Yeqing Li committed
105

Pengchong Jin's avatar
Pengchong Jin committed
106
    self._norm_activations = {}
Yeqing Li's avatar
Yeqing Li committed
107
108
    if self._use_batch_norm:
      for level in range(self._min_level, self._max_level + 1):
Pengchong Jin's avatar
Pengchong Jin committed
109
        self._norm_activations[level] = norm_activation(name='rpn-l%d-bn' %
Yeqing Li's avatar
Yeqing Li committed
110
                                                        level)
111
112
113
114
115

  def _shared_rpn_heads(self, features, anchors_per_location, level,
                        is_training):
    """Shared RPN heads."""
    features = self._rpn_conv(features)
Yeqing Li's avatar
Yeqing Li committed
116
117
    if self._use_batch_norm:
      # The batch normalization layers are not shared between levels.
Pengchong Jin's avatar
Pengchong Jin committed
118
      features = self._norm_activations[level](
Yeqing Li's avatar
Yeqing Li committed
119
          features, is_training=is_training)
120
121
122
123
124
125
126
    # Proposal classification scores
    scores = self._rpn_class_conv(features)
    # Proposal bbox regression deltas
    bboxes = self._rpn_box_conv(features)

    return scores, bboxes

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
127
  def call(self, features, is_training=None):
128
129
130
131

    scores_outputs = {}
    box_outputs = {}

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
132
    with tf.name_scope('rpn_head'):
133
134
135
136
137
138
139
140
      for level in range(self._min_level, self._max_level + 1):
        scores_output, box_output = self._shared_rpn_heads(
            features[level], self._anchors_per_location, level, is_training)
        scores_outputs[level] = scores_output
        box_outputs[level] = box_output
      return scores_outputs, box_outputs


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
class OlnRpnHead(tf.keras.layers.Layer):
  """Region Proposal Network for Object Localization Network (OLN)."""

  def __init__(
      self,
      min_level,
      max_level,
      anchors_per_location,
      num_convs=2,
      num_filters=256,
      use_separable_conv=False,
      activation='relu',
      use_batch_norm=True,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
    """Initialize params to build Region Proposal Network head.

    Args:
      min_level: `int` number of minimum feature level.
      max_level: `int` number of maximum feature level.
      anchors_per_location: `int` number of number of anchors per pixel
        location.
      num_convs: `int` number that represents the number of the intermediate
        conv layers before the prediction.
      num_filters: `int` number that represents the number of filters of the
        intermediate conv layers.
      use_separable_conv: `bool`, indicating whether the separable conv layers
        is used.
      activation: activation function. Support 'relu' and 'swish'.
      use_batch_norm: 'bool', indicating whether batchnorm layers are added.
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
    """
    self._min_level = min_level
    self._max_level = max_level
    self._anchors_per_location = anchors_per_location
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))
    self._use_batch_norm = use_batch_norm

    if use_separable_conv:
      self._conv2d_op = functools.partial(
          tf.keras.layers.SeparableConv2D,
          depth_multiplier=1,
          bias_initializer=tf.zeros_initializer())
    else:
      self._conv2d_op = functools.partial(
          tf.keras.layers.Conv2D,
          kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
          bias_initializer=tf.zeros_initializer())

    self._rpn_conv = self._conv2d_op(
        num_filters,
        kernel_size=(3, 3),
        strides=(1, 1),
        activation=(None if self._use_batch_norm else self._activation_op),
        padding='same',
        name='rpn')
    self._rpn_class_conv = self._conv2d_op(
        anchors_per_location,
        kernel_size=(1, 1),
        strides=(1, 1),
        padding='valid',
        name='rpn-class')
    self._rpn_box_conv = self._conv2d_op(
        4 * anchors_per_location,
        kernel_size=(1, 1),
        strides=(1, 1),
        padding='valid',
        name='rpn-box-lrtb')
    self._rpn_center_conv = self._conv2d_op(
        anchors_per_location,
        kernel_size=(1, 1),
        strides=(1, 1),
        padding='valid',
        name='rpn-centerness')

    self._norm_activations = {}
    if self._use_batch_norm:
      for level in range(self._min_level, self._max_level + 1):
        self._norm_activations[level] = norm_activation(name='rpn-l%d-bn' %
                                                        level)

  def _shared_rpn_heads(self, features, anchors_per_location, level,
                        is_training):
    """Shared RPN heads."""
    features = self._rpn_conv(features)
    if self._use_batch_norm:
      # The batch normalization layers are not shared between levels.
      features = self._norm_activations[level](
          features, is_training=is_training)
    # Feature L2 normalization for training stability
    features = tf.math.l2_normalize(
        features,
        axis=-1,
        name='rpn-norm',)
    # Proposal classification scores
    scores = self._rpn_class_conv(features)
    # Proposal bbox regression deltas
    bboxes = self._rpn_box_conv(features)
    # Proposal centerness scores
    centers = self._rpn_center_conv(features)

    return scores, bboxes, centers

  def __call__(self, features, is_training=None):

    scores_outputs = {}
    box_outputs = {}
    center_outputs = {}

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
255
    with tf.name_scope('rpn_head'):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
256
257
258
259
260
261
262
263
264
      for level in range(self._min_level, self._max_level + 1):
        scores_output, box_output, center_output = self._shared_rpn_heads(
            features[level], self._anchors_per_location, level, is_training)
        scores_outputs[level] = scores_output
        box_outputs[level] = box_output
        center_outputs[level] = center_output
      return scores_outputs, box_outputs, center_outputs


Yeqing Li's avatar
Yeqing Li committed
265
class FastrcnnHead(tf.keras.layers.Layer):
266
267
  """Fast R-CNN box head."""

Hongkun Yu's avatar
Hongkun Yu committed
268
269
270
271
272
273
274
275
276
277
278
  def __init__(
      self,
      num_classes,
      num_convs=0,
      num_filters=256,
      use_separable_conv=False,
      num_fcs=2,
      fc_dims=1024,
      activation='relu',
      use_batch_norm=True,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
279
280
281
282
    """Initialize params to build Fast R-CNN box head.

    Args:
      num_classes: a integer for the number of classes.
Yeqing Li's avatar
Yeqing Li committed
283
284
285
286
287
288
289
290
291
292
      num_convs: `int` number that represents the number of the intermediate
        conv layers before the FC layers.
      num_filters: `int` number that represents the number of filters of the
        intermediate conv layers.
      use_separable_conv: `bool`, indicating whether the separable conv layers
        is used.
      num_fcs: `int` number that represents the number of FC layers before the
        predictions.
      fc_dims: `int` number that represents the number of dimension of the FC
        layers.
293
      activation: activation function. Support 'relu' and 'swish'.
Yeqing Li's avatar
Yeqing Li committed
294
      use_batch_norm: 'bool', indicating whether batchnorm layers are added.
Hongkun Yu's avatar
Hongkun Yu committed
295
296
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
297
    """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
298
299
    super(FastrcnnHead, self).__init__(autocast=False)

300
    self._num_classes = num_classes
Yeqing Li's avatar
Yeqing Li committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

    self._num_convs = num_convs
    self._num_filters = num_filters
    if use_separable_conv:
      self._conv2d_op = functools.partial(
          tf.keras.layers.SeparableConv2D,
          depth_multiplier=1,
          bias_initializer=tf.zeros_initializer())
    else:
      self._conv2d_op = functools.partial(
          tf.keras.layers.Conv2D,
          kernel_initializer=tf.keras.initializers.VarianceScaling(
              scale=2, mode='fan_out', distribution='untruncated_normal'),
          bias_initializer=tf.zeros_initializer())

    self._num_fcs = num_fcs
    self._fc_dims = fc_dims
Pengchong Jin's avatar
Pengchong Jin committed
318
319
320
321
322
323
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))
Yeqing Li's avatar
Yeqing Li committed
324
    self._use_batch_norm = use_batch_norm
Pengchong Jin's avatar
Pengchong Jin committed
325
    self._norm_activation = norm_activation
326

Yeqing Li's avatar
Yeqing Li committed
327
328
329
330
331
332
333
334
335
336
    self._conv_ops = []
    self._conv_bn_ops = []
    for i in range(self._num_convs):
      self._conv_ops.append(
          self._conv2d_op(
              self._num_filters,
              kernel_size=(3, 3),
              strides=(1, 1),
              padding='same',
              dilation_rate=(1, 1),
Hongkun Yu's avatar
Hongkun Yu committed
337
338
              activation=(None
                          if self._use_batch_norm else self._activation_op),
Yeqing Li's avatar
Yeqing Li committed
339
340
              name='conv_{}'.format(i)))
      if self._use_batch_norm:
Pengchong Jin's avatar
Pengchong Jin committed
341
        self._conv_bn_ops.append(self._norm_activation())
Yeqing Li's avatar
Yeqing Li committed
342
343
344
345
346
347
348

    self._fc_ops = []
    self._fc_bn_ops = []
    for i in range(self._num_fcs):
      self._fc_ops.append(
          tf.keras.layers.Dense(
              units=self._fc_dims,
Hongkun Yu's avatar
Hongkun Yu committed
349
350
              activation=(None
                          if self._use_batch_norm else self._activation_op),
Yeqing Li's avatar
Yeqing Li committed
351
352
              name='fc{}'.format(i)))
      if self._use_batch_norm:
Pengchong Jin's avatar
Pengchong Jin committed
353
        self._fc_bn_ops.append(self._norm_activation(fused=False))
Yeqing Li's avatar
Yeqing Li committed
354
355
356
357
358
359
360
361
362
363
364
365

    self._class_predict = tf.keras.layers.Dense(
        self._num_classes,
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
        bias_initializer=tf.zeros_initializer(),
        name='class-predict')
    self._box_predict = tf.keras.layers.Dense(
        self._num_classes * 4,
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.001),
        bias_initializer=tf.zeros_initializer(),
        name='box-predict')

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
366
  def call(self, roi_features, is_training=None):
367
368
369
    """Box and class branches for the Mask-RCNN model.

    Args:
Hongkun Yu's avatar
Hongkun Yu committed
370
371
      roi_features: A ROI feature tensor of shape [batch_size, num_rois,
        height_l, width_l, num_filters].
372
373
374
375
376
377
378
379
380
381
      is_training: `boolean`, if True if model is in training mode.

    Returns:
      class_outputs: a tensor with a shape of
        [batch_size, num_rois, num_classes], representing the class predictions.
      box_outputs: a tensor with a shape of
        [batch_size, num_rois, num_classes * 4], representing the box
        predictions.
    """

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
382
    with tf.name_scope(
383
        'fast_rcnn_head'):
384
385
      # reshape inputs beofre FC.
      _, num_rois, height, width, filters = roi_features.get_shape().as_list()
Yeqing Li's avatar
Yeqing Li committed
386
387
388

      net = tf.reshape(roi_features, [-1, height, width, filters])
      for i in range(self._num_convs):
Yeqing Li's avatar
Yeqing Li committed
389
        net = self._conv_ops[i](net)
Yeqing Li's avatar
Yeqing Li committed
390
        if self._use_batch_norm:
Yeqing Li's avatar
Yeqing Li committed
391
          net = self._conv_bn_ops[i](net, is_training=is_training)
Yeqing Li's avatar
Yeqing Li committed
392
393
394
395
396

      filters = self._num_filters if self._num_convs > 0 else filters
      net = tf.reshape(net, [-1, num_rois, height * width * filters])

      for i in range(self._num_fcs):
Yeqing Li's avatar
Yeqing Li committed
397
        net = self._fc_ops[i](net)
Yeqing Li's avatar
Yeqing Li committed
398
        if self._use_batch_norm:
Yeqing Li's avatar
Yeqing Li committed
399
          net = self._fc_bn_ops[i](net, is_training=is_training)
400

Yeqing Li's avatar
Yeqing Li committed
401
402
      class_outputs = self._class_predict(net)
      box_outputs = self._box_predict(net)
403
404
405
      return class_outputs, box_outputs


A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
class OlnBoxScoreHead(tf.keras.layers.Layer):
  """Box head of Object Localization Network (OLN)."""

  def __init__(
      self,
      num_classes,
      num_convs=0,
      num_filters=256,
      use_separable_conv=False,
      num_fcs=2,
      fc_dims=1024,
      activation='relu',
      use_batch_norm=True,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
    """Initialize params to build OLN box head.

    Args:
      num_classes: a integer for the number of classes.
      num_convs: `int` number that represents the number of the intermediate
        conv layers before the FC layers.
      num_filters: `int` number that represents the number of filters of the
        intermediate conv layers.
      use_separable_conv: `bool`, indicating whether the separable conv layers
        is used.
      num_fcs: `int` number that represents the number of FC layers before the
        predictions.
      fc_dims: `int` number that represents the number of dimension of the FC
        layers.
      activation: activation function. Support 'relu' and 'swish'.
      use_batch_norm: 'bool', indicating whether batchnorm layers are added.
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
    """
    self._num_classes = num_classes

    self._num_convs = num_convs
    self._num_filters = num_filters
    if use_separable_conv:
      self._conv2d_op = functools.partial(
          tf.keras.layers.SeparableConv2D,
          depth_multiplier=1,
          bias_initializer=tf.zeros_initializer())
    else:
      self._conv2d_op = functools.partial(
          tf.keras.layers.Conv2D,
          kernel_initializer=tf.keras.initializers.VarianceScaling(
              scale=2, mode='fan_out', distribution='untruncated_normal'),
          bias_initializer=tf.zeros_initializer())

    self._num_fcs = num_fcs
    self._fc_dims = fc_dims
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))
    self._use_batch_norm = use_batch_norm
    self._norm_activation = norm_activation

    self._conv_ops = []
    self._conv_bn_ops = []
    for i in range(self._num_convs):
      self._conv_ops.append(
          self._conv2d_op(
              self._num_filters,
              kernel_size=(3, 3),
              strides=(1, 1),
              padding='same',
              dilation_rate=(1, 1),
              activation=(None
                          if self._use_batch_norm else self._activation_op),
              name='conv_{}'.format(i)))
      if self._use_batch_norm:
        self._conv_bn_ops.append(self._norm_activation())

    self._fc_ops = []
    self._fc_bn_ops = []
    for i in range(self._num_fcs):
      self._fc_ops.append(
          tf.keras.layers.Dense(
              units=self._fc_dims,
              activation=(None
                          if self._use_batch_norm else self._activation_op),
              name='fc{}'.format(i)))
      if self._use_batch_norm:
        self._fc_bn_ops.append(self._norm_activation(fused=False))

    self._class_predict = tf.keras.layers.Dense(
        self._num_classes,
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
        bias_initializer=tf.zeros_initializer(),
        name='class-predict')
    self._box_predict = tf.keras.layers.Dense(
        self._num_classes * 4,
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.001),
        bias_initializer=tf.zeros_initializer(),
        name='box-predict')
    self._score_predict = tf.keras.layers.Dense(
        1,
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
        bias_initializer=tf.zeros_initializer(),
        name='score-predict')

  def __call__(self, roi_features, is_training=None):
    """Box and class branches for the Mask-RCNN model.

    Args:
      roi_features: A ROI feature tensor of shape [batch_size, num_rois,
        height_l, width_l, num_filters].
      is_training: `boolean`, if True if model is in training mode.

    Returns:
      class_outputs: a tensor with a shape of
        [batch_size, num_rois, num_classes], representing the class predictions.
      box_outputs: a tensor with a shape of
        [batch_size, num_rois, num_classes * 4], representing the box
        predictions.
    """

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
526
    with tf.name_scope('fast_rcnn_head'):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
      # reshape inputs beofre FC.
      _, num_rois, height, width, filters = roi_features.get_shape().as_list()

      net = tf.reshape(roi_features, [-1, height, width, filters])
      for i in range(self._num_convs):
        net = self._conv_ops[i](net)
        if self._use_batch_norm:
          net = self._conv_bn_ops[i](net, is_training=is_training)

      filters = self._num_filters if self._num_convs > 0 else filters
      net = tf.reshape(net, [-1, num_rois, height * width * filters])

      for i in range(self._num_fcs):
        net = self._fc_ops[i](net)
        if self._use_batch_norm:
          net = self._fc_bn_ops[i](net, is_training=is_training)

      class_outputs = self._class_predict(net)
      box_outputs = self._box_predict(net)
      score_outputs = self._score_predict(net)
      return class_outputs, box_outputs, score_outputs


Yeqing Li's avatar
Yeqing Li committed
550
class MaskrcnnHead(tf.keras.layers.Layer):
551
552
  """Mask R-CNN head."""

Hongkun Yu's avatar
Hongkun Yu committed
553
554
555
556
557
558
559
560
561
562
  def __init__(
      self,
      num_classes,
      mask_target_size,
      num_convs=4,
      num_filters=256,
      use_separable_conv=False,
      activation='relu',
      use_batch_norm=True,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
563
564
565
566
    """Initialize params to build Fast R-CNN head.

    Args:
      num_classes: a integer for the number of classes.
Pengchong Jin's avatar
Pengchong Jin committed
567
      mask_target_size: a integer that is the resolution of masks.
Yeqing Li's avatar
Yeqing Li committed
568
569
570
571
572
573
      num_convs: `int` number that represents the number of the intermediate
        conv layers before the prediction.
      num_filters: `int` number that represents the number of filters of the
        intermediate conv layers.
      use_separable_conv: `bool`, indicating whether the separable conv layers
        is used.
574
      activation: activation function. Support 'relu' and 'swish'.
Yeqing Li's avatar
Yeqing Li committed
575
      use_batch_norm: 'bool', indicating whether batchnorm layers are added.
Hongkun Yu's avatar
Hongkun Yu committed
576
577
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
578
    """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
579
    super(MaskrcnnHead, self).__init__(autocast=False)
580
    self._num_classes = num_classes
Pengchong Jin's avatar
Pengchong Jin committed
581
    self._mask_target_size = mask_target_size
Yeqing Li's avatar
Yeqing Li committed
582
583
584
585
586
587
588
589
590
591
592
593
594
595

    self._num_convs = num_convs
    self._num_filters = num_filters
    if use_separable_conv:
      self._conv2d_op = functools.partial(
          tf.keras.layers.SeparableConv2D,
          depth_multiplier=1,
          bias_initializer=tf.zeros_initializer())
    else:
      self._conv2d_op = functools.partial(
          tf.keras.layers.Conv2D,
          kernel_initializer=tf.keras.initializers.VarianceScaling(
              scale=2, mode='fan_out', distribution='untruncated_normal'),
          bias_initializer=tf.zeros_initializer())
Pengchong Jin's avatar
Pengchong Jin committed
596
597
598
599
600
601
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))
Yeqing Li's avatar
Yeqing Li committed
602
    self._use_batch_norm = use_batch_norm
Pengchong Jin's avatar
Pengchong Jin committed
603
    self._norm_activation = norm_activation
Yeqing Li's avatar
Yeqing Li committed
604
605
606
607
608
609
610
611
612
    self._conv2d_ops = []
    for i in range(self._num_convs):
      self._conv2d_ops.append(
          self._conv2d_op(
              self._num_filters,
              kernel_size=(3, 3),
              strides=(1, 1),
              padding='same',
              dilation_rate=(1, 1),
Hongkun Yu's avatar
Hongkun Yu committed
613
614
              activation=(None
                          if self._use_batch_norm else self._activation_op),
Yeqing Li's avatar
Yeqing Li committed
615
616
617
618
619
620
              name='mask-conv-l%d' % i))
    self._mask_conv_transpose = tf.keras.layers.Conv2DTranspose(
        self._num_filters,
        kernel_size=(2, 2),
        strides=(2, 2),
        padding='valid',
Pengchong Jin's avatar
Pengchong Jin committed
621
        activation=(None if self._use_batch_norm else self._activation_op),
Yeqing Li's avatar
Yeqing Li committed
622
623
624
625
        kernel_initializer=tf.keras.initializers.VarianceScaling(
            scale=2, mode='fan_out', distribution='untruncated_normal'),
        bias_initializer=tf.zeros_initializer(),
        name='conv5-mask')
626

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
627
628
629
630
631
632
633
634
635
    with tf.name_scope('mask_head'):
      self._mask_conv2d_op = self._conv2d_op(
          self._num_classes,
          kernel_size=(1, 1),
          strides=(1, 1),
          padding='valid',
          name='mask_fcn_logits')

  def call(self, roi_features, class_indices, is_training=None):
636
637
638
    """Mask branch for the Mask-RCNN model.

    Args:
Hongkun Yu's avatar
Hongkun Yu committed
639
640
641
642
      roi_features: A ROI feature tensor of shape [batch_size, num_rois,
        height_l, width_l, num_filters].
      class_indices: a Tensor of shape [batch_size, num_rois], indicating which
        class the ROI is.
643
      is_training: `boolean`, if True if model is in training mode.
Yeqing Li's avatar
Yeqing Li committed
644

645
646
647
648
649
650
651
652
653
654
655
    Returns:
      mask_outputs: a tensor with a shape of
        [batch_size, num_masks, mask_height, mask_width, num_classes],
        representing the mask predictions.
      fg_gather_indices: a tensor with a shape of [batch_size, num_masks, 2],
        representing the fg mask targets.
    Raises:
      ValueError: If boxes is not a rank-3 tensor or the last dimension of
        boxes is not 4.
    """

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
656
657
658
    with tf.name_scope('mask_head'):
      _, num_rois, height, width, filters = roi_features.get_shape().as_list()
      net = tf.reshape(roi_features, [-1, height, width, filters])
659

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
660
661
      for i in range(self._num_convs):
        net = self._conv2d_ops[i](net)
Yeqing Li's avatar
Yeqing Li committed
662
        if self._use_batch_norm:
Pengchong Jin's avatar
Pengchong Jin committed
663
          net = self._norm_activation()(net, is_training=is_training)
Yeqing Li's avatar
Yeqing Li committed
664

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
      net = self._mask_conv_transpose(net)
      if self._use_batch_norm:
        net = self._norm_activation()(net, is_training=is_training)

      mask_outputs = self._mask_conv2d_op(net)
      mask_outputs = tf.reshape(mask_outputs, [
          -1, num_rois, self._mask_target_size, self._mask_target_size,
          self._num_classes
      ])

      with tf.name_scope('masks_post_processing'):
        # TODO(pengchong): Figure out the way not to use the static inferred
        # batch size.
        batch_size, num_masks = class_indices.get_shape().as_list()
        mask_outputs = tf.transpose(a=mask_outputs, perm=[0, 1, 4, 2, 3])
        # Constructs indices for gather.
        batch_indices = tf.tile(
            tf.expand_dims(tf.range(batch_size), axis=1), [1, num_masks])
        mask_indices = tf.tile(
            tf.expand_dims(tf.range(num_masks), axis=0), [batch_size, 1])
        gather_indices = tf.stack(
            [batch_indices, mask_indices, class_indices], axis=2)
        mask_outputs = tf.gather_nd(mask_outputs, gather_indices)
688
689
690
691
692
693
      return mask_outputs


class RetinanetHead(object):
  """RetinaNet head."""

Hongkun Yu's avatar
Hongkun Yu committed
694
695
696
697
698
699
700
701
702
703
  def __init__(
      self,
      min_level,
      max_level,
      num_classes,
      anchors_per_location,
      num_convs=4,
      num_filters=256,
      use_separable_conv=False,
      norm_activation=nn_ops.norm_activation_builder(activation='relu')):
704
705
706
707
708
709
710
711
712
713
    """Initialize params to build RetinaNet head.

    Args:
      min_level: `int` number of minimum feature level.
      max_level: `int` number of maximum feature level.
      num_classes: `int` number of classification categories.
      anchors_per_location: `int` number of anchors per pixel location.
      num_convs: `int` number of stacked convolution before the last prediction
        layer.
      num_filters: `int` number of filters used in the head architecture.
714
715
      use_separable_conv: `bool` to indicate whether to use separable
        convoluation.
Hongkun Yu's avatar
Hongkun Yu committed
716
717
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
718
719
720
721
722
723
724
725
726
    """
    self._min_level = min_level
    self._max_level = max_level

    self._num_classes = num_classes
    self._anchors_per_location = anchors_per_location

    self._num_convs = num_convs
    self._num_filters = num_filters
727
    self._use_separable_conv = use_separable_conv
728
729
730
731
    with tf.name_scope('class_net') as scope_name:
      self._class_name_scope = tf.name_scope(scope_name)
    with tf.name_scope('box_net') as scope_name:
      self._box_name_scope = tf.name_scope(scope_name)
Pengchong Jin's avatar
Pengchong Jin committed
732
733
    self._build_class_net_layers(norm_activation)
    self._build_box_net_layers(norm_activation)
734
735
736
737
738
739
740

  def _class_net_batch_norm_name(self, i, level):
    return 'class-%d-%d' % (i, level)

  def _box_net_batch_norm_name(self, i, level):
    return 'box-%d-%d' % (i, level)

Pengchong Jin's avatar
Pengchong Jin committed
741
  def _build_class_net_layers(self, norm_activation):
742
    """Build re-usable layers for class prediction network."""
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
    if self._use_separable_conv:
      self._class_predict = tf.keras.layers.SeparableConv2D(
          self._num_classes * self._anchors_per_location,
          kernel_size=(3, 3),
          bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)),
          padding='same',
          name='class-predict')
    else:
      self._class_predict = tf.keras.layers.Conv2D(
          self._num_classes * self._anchors_per_location,
          kernel_size=(3, 3),
          bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)),
          kernel_initializer=tf.keras.initializers.RandomNormal(stddev=1e-5),
          padding='same',
          name='class-predict')
758
    self._class_conv = []
Pengchong Jin's avatar
Pengchong Jin committed
759
    self._class_norm_activation = {}
760
    for i in range(self._num_convs):
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
      if self._use_separable_conv:
        self._class_conv.append(
            tf.keras.layers.SeparableConv2D(
                self._num_filters,
                kernel_size=(3, 3),
                bias_initializer=tf.zeros_initializer(),
                activation=None,
                padding='same',
                name='class-' + str(i)))
      else:
        self._class_conv.append(
            tf.keras.layers.Conv2D(
                self._num_filters,
                kernel_size=(3, 3),
                bias_initializer=tf.zeros_initializer(),
                kernel_initializer=tf.keras.initializers.RandomNormal(
                    stddev=0.01),
                activation=None,
                padding='same',
                name='class-' + str(i)))
781
782
      for level in range(self._min_level, self._max_level + 1):
        name = self._class_net_batch_norm_name(i, level)
Pengchong Jin's avatar
Pengchong Jin committed
783
        self._class_norm_activation[name] = norm_activation(name=name)
784

Pengchong Jin's avatar
Pengchong Jin committed
785
  def _build_box_net_layers(self, norm_activation):
786
    """Build re-usable layers for box prediction network."""
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    if self._use_separable_conv:
      self._box_predict = tf.keras.layers.SeparableConv2D(
          4 * self._anchors_per_location,
          kernel_size=(3, 3),
          bias_initializer=tf.zeros_initializer(),
          padding='same',
          name='box-predict')
    else:
      self._box_predict = tf.keras.layers.Conv2D(
          4 * self._anchors_per_location,
          kernel_size=(3, 3),
          bias_initializer=tf.zeros_initializer(),
          kernel_initializer=tf.keras.initializers.RandomNormal(stddev=1e-5),
          padding='same',
          name='box-predict')
802
    self._box_conv = []
Pengchong Jin's avatar
Pengchong Jin committed
803
    self._box_norm_activation = {}
804
    for i in range(self._num_convs):
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
      if self._use_separable_conv:
        self._box_conv.append(
            tf.keras.layers.SeparableConv2D(
                self._num_filters,
                kernel_size=(3, 3),
                activation=None,
                bias_initializer=tf.zeros_initializer(),
                padding='same',
                name='box-' + str(i)))
      else:
        self._box_conv.append(
            tf.keras.layers.Conv2D(
                self._num_filters,
                kernel_size=(3, 3),
                activation=None,
                bias_initializer=tf.zeros_initializer(),
                kernel_initializer=tf.keras.initializers.RandomNormal(
                    stddev=0.01),
                padding='same',
                name='box-' + str(i)))
825
826
      for level in range(self._min_level, self._max_level + 1):
        name = self._box_net_batch_norm_name(i, level)
Pengchong Jin's avatar
Pengchong Jin committed
827
        self._box_norm_activation[name] = norm_activation(name=name)
828
829
830
831
832

  def __call__(self, fpn_features, is_training=None):
    """Returns outputs of RetinaNet head."""
    class_outputs = {}
    box_outputs = {}
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
833
    with tf.name_scope('retinanet_head'):
834
835
836
837
838
839
840
841
842
843
844
845
846
847
      for level in range(self._min_level, self._max_level + 1):
        features = fpn_features[level]

        class_outputs[level] = self.class_net(
            features, level, is_training=is_training)
        box_outputs[level] = self.box_net(
            features, level, is_training=is_training)
    return class_outputs, box_outputs

  def class_net(self, features, level, is_training):
    """Class prediction network for RetinaNet."""
    with self._class_name_scope:
      for i in range(self._num_convs):
        features = self._class_conv[i](features)
848
849
        # The convolution layers in the class net are shared among all levels,
        # but each level has its batch normlization to capture the statistical
850
851
        # difference among different levels.
        name = self._class_net_batch_norm_name(i, level)
Pengchong Jin's avatar
Pengchong Jin committed
852
        features = self._class_norm_activation[name](
853
854
855
856
857
858
859
860
861
862
863
864
865
866
            features, is_training=is_training)

      classes = self._class_predict(features)
    return classes

  def box_net(self, features, level, is_training=None):
    """Box regression network for RetinaNet."""
    with self._box_name_scope:
      for i in range(self._num_convs):
        features = self._box_conv[i](features)
        # The convolution layers in the box net are shared among all levels, but
        # each level has its batch normlization to capture the statistical
        # difference among different levels.
        name = self._box_net_batch_norm_name(i, level)
Pengchong Jin's avatar
Pengchong Jin committed
867
        features = self._box_norm_activation[name](
868
869
870
871
872
873
874
875
876
877
            features, is_training=is_training)

      boxes = self._box_predict(features)
    return boxes


# TODO(yeqing): Refactor this class when it is ready for var_scope reuse.
class ShapemaskPriorHead(object):
  """ShapeMask Prior head."""

Hongkun Yu's avatar
Hongkun Yu committed
878
879
  def __init__(self, num_classes, num_downsample_channels, mask_crop_size,
               use_category_for_mask, shape_prior_path):
880
881
882
883
884
885
886
887
888
    """Initialize params to build RetinaNet head.

    Args:
      num_classes: Number of output classes.
      num_downsample_channels: number of channels in mask branch.
      mask_crop_size: feature crop size.
      use_category_for_mask: use class information in mask branch.
      shape_prior_path: the path to load shape priors.
    """
889
    self._mask_num_classes = num_classes if use_category_for_mask else 1
890
891
892
    self._num_downsample_channels = num_downsample_channels
    self._mask_crop_size = mask_crop_size
    self._shape_prior_path = shape_prior_path
893
894
895
896
    self._use_category_for_mask = use_category_for_mask

    self._shape_prior_fc = tf.keras.layers.Dense(
        self._num_downsample_channels, name='shape-prior-fc')
897

898
  def __call__(self, fpn_features, boxes, outer_boxes, classes, is_training):
899
900
901
902
903
904
905
    """Generate the detection priors from the box detections and FPN features.

    This corresponds to the Fig. 4 of the ShapeMask paper at
    https://arxiv.org/pdf/1904.03239.pdf

    Args:
      fpn_features: a dictionary of FPN features.
Hongkun Yu's avatar
Hongkun Yu committed
906
907
      boxes: a float tensor of shape [batch_size, num_instances, 4] representing
        the tight gt boxes from dataloader/detection.
908
909
      outer_boxes: a float tensor of shape [batch_size, num_instances, 4]
        representing the loose gt boxes from dataloader/detection.
Hongkun Yu's avatar
Hongkun Yu committed
910
911
      classes: a int Tensor of shape [batch_size, num_instances] of instance
        classes.
912
913
914
      is_training: training mode or not.

    Returns:
915
      instance_features: a float Tensor of shape [batch_size * num_instances,
916
917
918
919
920
          mask_crop_size, mask_crop_size, num_downsample_channels]. This is the
          instance feature crop.
      detection_priors: A float Tensor of shape [batch_size * num_instances,
        mask_size, mask_size, 1].
    """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
921
    with tf.name_scope('prior_mask'):
922
923
924
925
926
927
928
929
930
931
      batch_size, num_instances, _ = boxes.get_shape().as_list()
      outer_boxes = tf.cast(outer_boxes, tf.float32)
      boxes = tf.cast(boxes, tf.float32)
      instance_features = spatial_transform_ops.multilevel_crop_and_resize(
          fpn_features, outer_boxes, output_size=self._mask_crop_size)
      instance_features = self._shape_prior_fc(instance_features)

      shape_priors = self._get_priors()

      # Get uniform priors for each outer box.
Hongkun Yu's avatar
Hongkun Yu committed
932
933
934
      uniform_priors = tf.ones([
          batch_size, num_instances, self._mask_crop_size, self._mask_crop_size
      ])
935
      uniform_priors = spatial_transform_ops.crop_mask_in_target_box(
936
937
938
939
940
941
942
          uniform_priors, boxes, outer_boxes, self._mask_crop_size)

      # Classify shape priors using uniform priors + instance features.
      prior_distribution = self._classify_shape_priors(
          tf.cast(instance_features, tf.float32), uniform_priors, classes)

      instance_priors = tf.gather(shape_priors, classes)
Hongkun Yu's avatar
Hongkun Yu committed
943
944
945
      instance_priors *= tf.expand_dims(
          tf.expand_dims(tf.cast(prior_distribution, tf.float32), axis=-1),
          axis=-1)
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
      instance_priors = tf.reduce_sum(instance_priors, axis=2)
      detection_priors = spatial_transform_ops.crop_mask_in_target_box(
          instance_priors, boxes, outer_boxes, self._mask_crop_size)

      return instance_features, detection_priors

  def _get_priors(self):
    """Load shape priors from file."""
    # loads class specific or agnostic shape priors
    if self._shape_prior_path:
      # Priors are loaded into shape [mask_num_classes, num_clusters, 32, 32].
      priors = np.load(tf.io.gfile.GFile(self._shape_prior_path, 'rb'))
      priors = tf.convert_to_tensor(priors, dtype=tf.float32)
      self._num_clusters = priors.get_shape().as_list()[1]
    else:
      # If prior path does not exist, do not use priors, i.e., pirors equal to
      # uniform empty 32x32 patch.
      self._num_clusters = 1
Hongkun Yu's avatar
Hongkun Yu committed
964
965
966
967
      priors = tf.zeros([
          self._mask_num_classes, self._num_clusters, self._mask_crop_size,
          self._mask_crop_size
      ])
968
969
970
    return priors

  def _classify_shape_priors(self, features, uniform_priors, classes):
971
972
973
974
975
976
    """Classify the uniform prior by predicting the shape modes.

    Classify the object crop features into K modes of the clusters for each
    category.

    Args:
Hongkun Yu's avatar
Hongkun Yu committed
977
978
      features: A float Tensor of shape [batch_size, num_instances, mask_size,
        mask_size, num_channels].
979
980
      uniform_priors: A float Tensor of shape [batch_size, num_instances,
        mask_size, mask_size] representing the uniform detection priors.
Hongkun Yu's avatar
Hongkun Yu committed
981
982
      classes: A int Tensor of shape [batch_size, num_instances] of detection
        class ids.
983
984

    Returns:
985
986
      prior_distribution: A float Tensor of shape
        [batch_size, num_instances, num_clusters] representing the classifier
987
988
989
        output probability over all possible shapes.
    """

990
991
992
993
994
995
996
    batch_size, num_instances, _, _, _ = features.get_shape().as_list()
    features *= tf.expand_dims(uniform_priors, axis=-1)
    # Reduce spatial dimension of features. The features have shape
    # [batch_size, num_instances, num_channels].
    features = tf.reduce_mean(features, axis=(2, 3))
    logits = tf.keras.layers.Dense(
        self._mask_num_classes * self._num_clusters,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
997
998
        kernel_initializer=tf.random_normal_initializer(stddev=0.01),
        name='classify-shape-prior-fc')(features)
Hongkun Yu's avatar
Hongkun Yu committed
999
1000
1001
    logits = tf.reshape(
        logits,
        [batch_size, num_instances, self._mask_num_classes, self._num_clusters])
1002
    if self._use_category_for_mask:
1003
1004
      logits = tf.gather(logits, tf.expand_dims(classes, axis=-1), batch_dims=2)
      logits = tf.squeeze(logits, axis=2)
1005
    else:
1006
1007
1008
1009
      logits = logits[:, :, 0, :]

    distribution = tf.nn.softmax(logits, name='shape_prior_weights')
    return distribution
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019


class ShapemaskCoarsemaskHead(object):
  """ShapemaskCoarsemaskHead head."""

  def __init__(self,
               num_classes,
               num_downsample_channels,
               mask_crop_size,
               use_category_for_mask,
1020
1021
               num_convs,
               norm_activation=nn_ops.norm_activation_builder()):
1022
1023
1024
1025
1026
1027
1028
1029
1030
    """Initialize params to build ShapeMask coarse and fine prediction head.

    Args:
      num_classes: `int` number of mask classification categories.
      num_downsample_channels: `int` number of filters at mask head.
      mask_crop_size: feature crop size.
      use_category_for_mask: use class information in mask branch.
      num_convs: `int` number of stacked convolution before the last prediction
        layer.
Hongkun Yu's avatar
Hongkun Yu committed
1031
1032
      norm_activation: an operation that includes a normalization layer followed
        by an optional activation layer.
1033
    """
1034
1035
    self._mask_num_classes = num_classes if use_category_for_mask else 1
    self._use_category_for_mask = use_category_for_mask
1036
1037
1038
    self._num_downsample_channels = num_downsample_channels
    self._mask_crop_size = mask_crop_size
    self._num_convs = num_convs
1039
1040
1041
1042
1043
1044
1045
1046
1047
    self._norm_activation = norm_activation

    self._coarse_mask_fc = tf.keras.layers.Dense(
        self._num_downsample_channels, name='coarse-mask-fc')

    self._class_conv = []
    self._class_norm_activation = []

    for i in range(self._num_convs):
Hongkun Yu's avatar
Hongkun Yu committed
1048
1049
1050
1051
1052
1053
1054
1055
1056
      self._class_conv.append(
          tf.keras.layers.Conv2D(
              self._num_downsample_channels,
              kernel_size=(3, 3),
              bias_initializer=tf.zeros_initializer(),
              kernel_initializer=tf.keras.initializers.RandomNormal(
                  stddev=0.01),
              padding='same',
              name='coarse-mask-class-%d' % i))
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070

      self._class_norm_activation.append(
          norm_activation(name='coarse-mask-class-%d-bn' % i))

    self._class_predict = tf.keras.layers.Conv2D(
        self._mask_num_classes,
        kernel_size=(1, 1),
        # Focal loss bias initialization to have foreground 0.01 probability.
        bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)),
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
        padding='same',
        name='coarse-mask-class-predict')

  def __call__(self, features, detection_priors, classes, is_training):
1071
1072
1073
1074
1075
1076
    """Generate instance masks from FPN features and detection priors.

    This corresponds to the Fig. 5-6 of the ShapeMask paper at
    https://arxiv.org/pdf/1904.03239.pdf

    Args:
1077
      features: a float Tensor of shape [batch_size, num_instances,
1078
1079
        mask_crop_size, mask_crop_size, num_downsample_channels]. This is the
        instance feature crop.
1080
      detection_priors: a float Tensor of shape [batch_size, num_instances,
Hongkun Yu's avatar
Hongkun Yu committed
1081
1082
1083
1084
        mask_crop_size, mask_crop_size, 1]. This is the detection prior for the
        instance.
      classes: a int Tensor of shape [batch_size, num_instances] of instance
        classes.
1085
1086
1087
1088
      is_training: a bool indicating whether in training mode.

    Returns:
      mask_outputs: instance mask prediction as a float Tensor of shape
1089
        [batch_size, num_instances, mask_size, mask_size].
1090
    """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1091
    with tf.name_scope('coarse_mask'):
1092
1093
1094
1095
1096
1097
1098
1099
1100
      # Transform detection priors to have the same dimension as features.
      detection_priors = tf.expand_dims(detection_priors, axis=-1)
      detection_priors = self._coarse_mask_fc(detection_priors)

      features += detection_priors
      mask_logits = self.decoder_net(features, is_training)
      # Gather the logits with right input class.
      if self._use_category_for_mask:
        mask_logits = tf.transpose(mask_logits, [0, 1, 4, 2, 3])
Hongkun Yu's avatar
Hongkun Yu committed
1101
1102
        mask_logits = tf.gather(
            mask_logits, tf.expand_dims(classes, -1), batch_dims=2)
1103
1104
1105
        mask_logits = tf.squeeze(mask_logits, axis=2)
      else:
        mask_logits = mask_logits[..., 0]
1106

1107
      return mask_logits
1108

1109
  def decoder_net(self, features, is_training=False):
1110
1111
1112
    """Coarse mask decoder network architecture.

    Args:
1113
      features: A tensor of size [batch, height_in, width_in, channels_in].
1114
      is_training: Whether batch_norm layers are in training mode.
1115

1116
1117
1118
1119
    Returns:
      images: A feature tensor of size [batch, output_size, output_size,
        num_channels]
    """
1120
1121
    (batch_size, num_instances, height, width,
     num_channels) = features.get_shape().as_list()
Hongkun Yu's avatar
Hongkun Yu committed
1122
1123
    features = tf.reshape(
        features, [batch_size * num_instances, height, width, num_channels])
1124
    for i in range(self._num_convs):
1125
      features = self._class_conv[i](features)
Hongkun Yu's avatar
Hongkun Yu committed
1126
1127
      features = self._class_norm_activation[i](
          features, is_training=is_training)
1128

1129
    mask_logits = self._class_predict(features)
Hongkun Yu's avatar
Hongkun Yu committed
1130
1131
1132
    mask_logits = tf.reshape(
        mask_logits,
        [batch_size, num_instances, height, width, self._mask_num_classes])
1133
    return mask_logits
1134
1135
1136
1137
1138
1139
1140
1141
1142


class ShapemaskFinemaskHead(object):
  """ShapemaskFinemaskHead head."""

  def __init__(self,
               num_classes,
               num_downsample_channels,
               mask_crop_size,
1143
               use_category_for_mask,
1144
               num_convs,
1145
               upsample_factor,
Pengchong Jin's avatar
Pengchong Jin committed
1146
               norm_activation=nn_ops.norm_activation_builder()):
1147
1148
1149
1150
1151
1152
    """Initialize params to build ShapeMask coarse and fine prediction head.

    Args:
      num_classes: `int` number of mask classification categories.
      num_downsample_channels: `int` number of filters at mask head.
      mask_crop_size: feature crop size.
1153
      use_category_for_mask: use class information in mask branch.
1154
1155
      num_convs: `int` number of stacked convolution before the last prediction
        layer.
1156
      upsample_factor: `int` number of fine mask upsampling factor.
Pengchong Jin's avatar
Pengchong Jin committed
1157
      norm_activation: an operation that includes a batch normalization layer
1158
1159
        followed by a relu layer(optional).
    """
1160
1161
    self._use_category_for_mask = use_category_for_mask
    self._mask_num_classes = num_classes if use_category_for_mask else 1
1162
1163
1164
    self._num_downsample_channels = num_downsample_channels
    self._mask_crop_size = mask_crop_size
    self._num_convs = num_convs
1165
1166
1167
1168
    self.up_sample_factor = upsample_factor

    self._fine_mask_fc = tf.keras.layers.Dense(
        self._num_downsample_channels, name='fine-mask-fc')
1169
1170

    self._upsample_conv = tf.keras.layers.Conv2DTranspose(
1171
1172
1173
1174
1175
        self._num_downsample_channels,
        (self.up_sample_factor, self.up_sample_factor),
        (self.up_sample_factor, self.up_sample_factor),
        name='fine-mask-conv2d-tran')

1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
    self._fine_class_conv = []
    self._fine_class_bn = []
    for i in range(self._num_convs):
      self._fine_class_conv.append(
          tf.keras.layers.Conv2D(
              self._num_downsample_channels,
              kernel_size=(3, 3),
              bias_initializer=tf.zeros_initializer(),
              kernel_initializer=tf.keras.initializers.RandomNormal(
                  stddev=0.01),
              activation=None,
              padding='same',
1188
              name='fine-mask-class-%d' % i))
Hongkun Yu's avatar
Hongkun Yu committed
1189
1190
      self._fine_class_bn.append(
          norm_activation(name='fine-mask-class-%d-bn' % i))
1191
1192
1193
1194
1195
1196
1197
1198
1199

    self._class_predict_conv = tf.keras.layers.Conv2D(
        self._mask_num_classes,
        kernel_size=(1, 1),
        # Focal loss bias initialization to have foreground 0.01 probability.
        bias_initializer=tf.constant_initializer(-np.log((1 - 0.01) / 0.01)),
        kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
        padding='same',
        name='fine-mask-class-predict')
1200

1201
  def __call__(self, features, mask_logits, classes, is_training):
1202
1203
1204
1205
1206
1207
    """Generate instance masks from FPN features and detection priors.

    This corresponds to the Fig. 5-6 of the ShapeMask paper at
    https://arxiv.org/pdf/1904.03239.pdf

    Args:
Hongkun Yu's avatar
Hongkun Yu committed
1208
1209
1210
1211
1212
1213
1214
      features: a float Tensor of shape [batch_size, num_instances,
        mask_crop_size, mask_crop_size, num_downsample_channels]. This is the
        instance feature crop.
      mask_logits: a float Tensor of shape [batch_size, num_instances,
        mask_crop_size, mask_crop_size] indicating predicted mask logits.
      classes: a int Tensor of shape [batch_size, num_instances] of instance
        classes.
1215
1216
1217
1218
      is_training: a bool indicating whether in training mode.

    Returns:
      mask_outputs: instance mask prediction as a float Tensor of shape
1219
        [batch_size, num_instances, mask_size, mask_size].
1220
    """
1221
1222
    # Extract the foreground mean features
    # with tf.variable_scope('fine_mask', reuse=tf.AUTO_REUSE):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1223
    with tf.name_scope('fine_mask'):
1224
1225
1226
      mask_probs = tf.nn.sigmoid(mask_logits)
      # Compute instance embedding for hard average.
      binary_mask = tf.cast(tf.greater(mask_probs, 0.5), features.dtype)
1227
      instance_embedding = tf.reduce_sum(
1228
1229
1230
          features * tf.expand_dims(binary_mask, axis=-1), axis=(2, 3))
      instance_embedding /= tf.expand_dims(
          tf.reduce_sum(binary_mask, axis=(2, 3)) + 1e-20, axis=-1)
1231
      # Take the difference between crop features and mean instance features.
1232
1233
      features -= tf.expand_dims(
          tf.expand_dims(instance_embedding, axis=2), axis=2)
1234

1235
      features += self._fine_mask_fc(tf.expand_dims(mask_probs, axis=-1))
1236

1237
1238
1239
1240
      # Decoder to generate upsampled segmentation mask.
      mask_logits = self.decoder_net(features, is_training)
      if self._use_category_for_mask:
        mask_logits = tf.transpose(mask_logits, [0, 1, 4, 2, 3])
Hongkun Yu's avatar
Hongkun Yu committed
1241
1242
        mask_logits = tf.gather(
            mask_logits, tf.expand_dims(classes, -1), batch_dims=2)
1243
1244
1245
        mask_logits = tf.squeeze(mask_logits, axis=2)
      else:
        mask_logits = mask_logits[..., 0]
1246

1247
    return mask_logits
1248

1249
  def decoder_net(self, features, is_training=False):
1250
1251
1252
    """Fine mask decoder network architecture.

    Args:
1253
      features: A tensor of size [batch, height_in, width_in, channels_in].
1254
1255
1256
1257
1258
1259
1260
      is_training: Whether batch_norm layers are in training mode.

    Returns:
      images: A feature tensor of size [batch, output_size, output_size,
        num_channels], where output size is self._gt_upsample_scale times
        that of input.
    """
1261
1262
    (batch_size, num_instances, height, width,
     num_channels) = features.get_shape().as_list()
Hongkun Yu's avatar
Hongkun Yu committed
1263
1264
    features = tf.reshape(
        features, [batch_size * num_instances, height, width, num_channels])
1265
    for i in range(self._num_convs):
1266
1267
1268
1269
1270
      features = self._fine_class_conv[i](features)
      features = self._fine_class_bn[i](features, is_training=is_training)

    if self.up_sample_factor > 1:
      features = self._upsample_conv(features)
1271

1272
1273
    # Predict per-class instance masks.
    mask_logits = self._class_predict_conv(features)
1274

Hongkun Yu's avatar
Hongkun Yu committed
1275
1276
1277
1278
    mask_logits = tf.reshape(mask_logits, [
        batch_size, num_instances, height * self.up_sample_factor,
        width * self.up_sample_factor, self._mask_num_classes
    ])
1279
    return mask_logits