yt8m_task.py 10.7 KB
Newer Older
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Hye Yoon's avatar
Hye Yoon committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14

Hye Yoon's avatar
Hye Yoon committed
15
16
"""Video classification task definition."""
from absl import logging
17
18
19
20
21
import tensorflow as tf

from official.core import base_task
from official.core import input_reader
from official.core import task_factory
Hye Yoon's avatar
Hye Yoon committed
22
from official.modeling import tf_utils
Yeqing Li's avatar
Yeqing Li committed
23
24
25
26
27
from official.projects.yt8m.configs import yt8m as yt8m_cfg
from official.projects.yt8m.dataloaders import yt8m_input
from official.projects.yt8m.eval_utils import eval_util
from official.projects.yt8m.modeling import yt8m_model_utils as utils
from official.projects.yt8m.modeling.yt8m_model import DbofModel
Hye Yoon's avatar
Hye Yoon committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42


@task_factory.register_task_cls(yt8m_cfg.YT8MTask)
class YT8MTask(base_task.Task):
  """A task for video classification."""

  def build_model(self):
    """Builds model for YT8M Task."""
    train_cfg = self.task_config.train_data
    common_input_shape = [None, sum(train_cfg.feature_sizes)]

    # [batch_size x num_frames x num_features]
    input_specs = tf.keras.layers.InputSpec(shape=[None] + common_input_shape)
    logging.info('Build model input %r', common_input_shape)

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
43
44
45
46
47
48
49
    l2_weight_decay = self.task_config.losses.l2_weight_decay
    # Divide weight decay by 2.0 to match the implementation of tf.nn.l2_loss.
    # (https://www.tensorflow.org/api_docs/python/tf/keras/regularizers/l2)
    # (https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss)
    l2_regularizer = (
        tf.keras.regularizers.l2(l2_weight_decay /
                                 2.0) if l2_weight_decay else None)
50
    # Model configuration.
Hye Yoon's avatar
Hye Yoon committed
51
    model_config = self.task_config.model
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
52
53
54
    norm_activation_config = model_config.norm_activation
    model = DbofModel(
        params=model_config,
55
56
        input_specs=input_specs,
        num_frames=train_cfg.num_frames,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
57
58
59
60
61
62
        num_classes=train_cfg.num_classes,
        activation=norm_activation_config.activation,
        use_sync_bn=norm_activation_config.use_sync_bn,
        norm_momentum=norm_activation_config.norm_momentum,
        norm_epsilon=norm_activation_config.norm_epsilon,
        kernel_regularizer=l2_regularizer)
Hye Yoon's avatar
Hye Yoon committed
63
64
65
66
    return model

  def build_inputs(self, params: yt8m_cfg.DataConfig, input_context=None):
    """Builds input.
67

Hye Yoon's avatar
Hye Yoon committed
68
69
    Args:
      params: configuration for input data
70
71
      input_context: indicates information about the compute replicas and input
        pipelines
Hye Yoon's avatar
Hye Yoon committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

    Returns:
      dataset: dataset fetched from reader
    """

    decoder = yt8m_input.Decoder(input_params=params)
    decoder_fn = decoder.decode
    parser = yt8m_input.Parser(input_params=params)
    parser_fn = parser.parse_fn(params.is_training)
    postprocess = yt8m_input.PostBatchProcessor(input_params=params)
    postprocess_fn = postprocess.post_fn
    transform_batch = yt8m_input.TransformBatcher(input_params=params)
    batch_fn = transform_batch.batch_fn

    reader = input_reader.InputReader(
        params,
        dataset_fn=tf.data.TFRecordDataset,
        decoder_fn=decoder_fn,
        parser_fn=parser_fn,
        postprocess_fn=postprocess_fn,
92
        transform_and_batch_fn=batch_fn)
Hye Yoon's avatar
Hye Yoon committed
93
94
95
96
97
98

    dataset = reader.read(input_context=input_context)

    return dataset

  def build_losses(self, labels, model_outputs, aux_losses=None):
99
100
    """Sigmoid Cross Entropy.

Hye Yoon's avatar
Hye Yoon committed
101
102
103
    Args:
      labels: tensor containing truth labels.
      model_outputs: output logits of the classifier.
104
105
      aux_losses: tensor containing auxiliarly loss tensors, i.e. `losses` in
        keras.Model.
Hye Yoon's avatar
Hye Yoon committed
106
107
108
109
110
111

    Returns:
      Tensors: The total loss, model loss tensors.
    """
    losses_config = self.task_config.losses
    model_loss = tf.keras.losses.binary_crossentropy(
112
113
114
115
        labels,
        model_outputs,
        from_logits=losses_config.from_logits,
        label_smoothing=losses_config.label_smoothing)
Hye Yoon's avatar
Hye Yoon committed
116
117
118
119
120
121
122
123
124
125

    model_loss = tf_utils.safe_mean(model_loss)
    total_loss = model_loss
    if aux_losses:
      total_loss += tf.add_n(aux_losses)

    return total_loss, model_loss

  def build_metrics(self, training=True):
    """Gets streaming metrics for training/validation.
126

Hye Yoon's avatar
Hye Yoon committed
127
128
129
130
131
132
       metric: mAP/gAP
       top_k: A positive integer specifying how many predictions are considered
        per video.
       top_n: A positive Integer specifying the average precision at n, or None
        to use all provided data points.
    Args:
133
      training: bool value, true for training mode, false for eval/validation.
Hye Yoon's avatar
Hye Yoon committed
134
135
136
137
138
139
140
141
142

    Returns:
      list of strings that indicate metrics to be used
    """
    metrics = []
    metric_names = ['total_loss', 'model_loss']
    for name in metric_names:
      metrics.append(tf.keras.metrics.Mean(name, dtype=tf.float32))

143
    if not training:  # Cannot run in train step.
Hye Yoon's avatar
Hye Yoon committed
144
145
146
147
      num_classes = self.task_config.validation_data.num_classes
      top_k = self.task_config.top_k
      top_n = self.task_config.top_n
      self.avg_prec_metric = eval_util.EvaluationMetrics(
148
          num_classes, top_k=top_k, top_n=top_n)
Hye Yoon's avatar
Hye Yoon committed
149
150
151
152
153

    return metrics

  def train_step(self, inputs, model, optimizer, metrics=None):
    """Does forward and backward.
154

Hye Yoon's avatar
Hye Yoon committed
155
    Args:
156
      inputs: a dictionary of input tensors. output_dict = {
Hye Yoon's avatar
Hye Yoon committed
157
158
159
          "video_ids": batch_video_ids,
          "video_matrix": batch_video_matrix,
          "labels": batch_labels,
160
          "num_frames": batch_frames, }
Hye Yoon's avatar
Hye Yoon committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
      model: the model, forward pass definition.
      optimizer: the optimizer for this training step.
      metrics: a nested structure of metrics objects.

    Returns:
      a dictionary of logs.
    """
    features, labels = inputs['video_matrix'], inputs['labels']
    num_frames = inputs['num_frames']

    # Normalize input features.
    feature_dim = len(features.shape) - 1
    features = tf.nn.l2_normalize(features, feature_dim)

    # sample random frames / random sequence
    num_frames = tf.cast(num_frames, tf.float32)
    sample_frames = self.task_config.train_data.num_frames
    if self.task_config.model.sample_random_frames:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
179
      features = utils.sample_random_frames(features, num_frames, sample_frames)
Hye Yoon's avatar
Hye Yoon committed
180
    else:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
181
182
      features = utils.sample_random_sequence(features, num_frames,
                                              sample_frames)
Hye Yoon's avatar
Hye Yoon committed
183
184
185
186
187
188
189
190
191
192

    num_replicas = tf.distribute.get_strategy().num_replicas_in_sync
    with tf.GradientTape() as tape:
      outputs = model(features, training=True)
      # Casting output layer as float32 is necessary when mixed_precision is
      # mixed_float16 or mixed_bfloat16 to ensure output is casted as float32.
      outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs)

      # Computes per-replica loss
      loss, model_loss = self.build_losses(
193
          model_outputs=outputs, labels=labels, aux_losses=model.losses)
Hye Yoon's avatar
Hye Yoon committed
194
195
196
197
198
199
      # Scales loss as the default gradients allreduce performs sum inside the
      # optimizer.
      scaled_loss = loss / num_replicas

      # For mixed_precision policy, when LossScaleOptimizer is used, loss is
      # scaled for numerical stability.
200
      if isinstance(optimizer,
201
                    tf.keras.mixed_precision.LossScaleOptimizer):
Hye Yoon's avatar
Hye Yoon committed
202
203
204
205
206
207
        scaled_loss = optimizer.get_scaled_loss(scaled_loss)

    tvars = model.trainable_variables
    grads = tape.gradient(scaled_loss, tvars)
    # Scales back gradient before apply_gradients when LossScaleOptimizer is
    # used.
208
    if isinstance(optimizer,
209
                  tf.keras.mixed_precision.LossScaleOptimizer):
Hye Yoon's avatar
Hye Yoon committed
210
211
212
213
      grads = optimizer.get_unscaled_gradients(grads)

    # Apply gradient clipping.
    if self.task_config.gradient_clip_norm > 0:
214
215
      grads, _ = tf.clip_by_global_norm(grads,
                                        self.task_config.gradient_clip_norm)
Hye Yoon's avatar
Hye Yoon committed
216
217
218
219
    optimizer.apply_gradients(list(zip(grads, tvars)))

    logs = {self.loss: loss}

220
    all_losses = {'total_loss': loss, 'model_loss': model_loss}
Hye Yoon's avatar
Hye Yoon committed
221
222
223
224
225
226
227
228
229
230
231
232

    if metrics:
      for m in metrics:
        m.update_state(all_losses[m.name])
        logs.update({m.name: m.result()})

    return logs

  def validation_step(self, inputs, model, metrics=None):
    """Validatation step.

    Args:
233
      inputs: a dictionary of input tensors. output_dict = {
Hye Yoon's avatar
Hye Yoon committed
234
235
236
        "video_ids": batch_video_ids,
        "video_matrix": batch_video_matrix,
        "labels": batch_labels,
237
        "num_frames": batch_frames, }
Hye Yoon's avatar
Hye Yoon committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
      model: the model, forward definition
      metrics: a nested structure of metrics objects.

    Returns:
      a dictionary of logs.
    """
    features, labels = inputs['video_matrix'], inputs['labels']
    num_frames = inputs['num_frames']

    # Normalize input features.
    feature_dim = len(features.shape) - 1
    features = tf.nn.l2_normalize(features, feature_dim)

    # sample random frames (None, 5, 1152) -> (None, 30, 1152)
    sample_frames = self.task_config.validation_data.num_frames
    if self.task_config.model.sample_random_frames:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
254
      features = utils.sample_random_frames(features, num_frames, sample_frames)
Hye Yoon's avatar
Hye Yoon committed
255
    else:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
256
257
      features = utils.sample_random_sequence(features, num_frames,
                                              sample_frames)
Hye Yoon's avatar
Hye Yoon committed
258
259
260
261
262
263
264
265
266

    outputs = self.inference_step(features, model)
    outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs)
    if self.task_config.validation_data.segment_labels:
      # workaround to ignore the unrated labels.
      outputs *= inputs['label_weights']
      # remove padding
      outputs = outputs[~tf.reduce_all(labels == -1, axis=1)]
      labels = labels[~tf.reduce_all(labels == -1, axis=1)]
267
268
    loss, model_loss = self.build_losses(
        model_outputs=outputs, labels=labels, aux_losses=model.losses)
Hye Yoon's avatar
Hye Yoon committed
269
270
271

    logs = {self.loss: loss}

272
    all_losses = {'total_loss': loss, 'model_loss': model_loss}
Hye Yoon's avatar
Hye Yoon committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

    logs.update({self.avg_prec_metric.name: (labels, outputs)})

    if metrics:
      for m in metrics:
        m.update_state(all_losses[m.name])
        logs.update({m.name: m.result()})
    return logs

  def inference_step(self, inputs, model):
    """Performs the forward step."""
    return model(inputs, training=False)

  def aggregate_logs(self, state=None, step_logs=None):
    if state is None:
      state = self.avg_prec_metric
    self.avg_prec_metric.accumulate(
290
291
        labels=step_logs[self.avg_prec_metric.name][0],
        predictions=step_logs[self.avg_prec_metric.name][1])
Hye Yoon's avatar
Hye Yoon committed
292
293
    return state

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
294
  def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
Hye Yoon's avatar
Hye Yoon committed
295
296
297
    avg_prec_metrics = self.avg_prec_metric.get()
    self.avg_prec_metric.clear()
    return avg_prec_metrics