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

# Lint as: python3
Abdullah Rashwan's avatar
Abdullah Rashwan committed
16
"""Image classification task definition."""
Abdullah Rashwan's avatar
Abdullah Rashwan committed
17
from absl import logging
Abdullah Rashwan's avatar
Abdullah Rashwan committed
18
import tensorflow as tf
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
19

20
from official.common import dataset_fn
Abdullah Rashwan's avatar
Abdullah Rashwan committed
21
22
23
24
25
from official.core import base_task
from official.core import task_factory
from official.modeling import tf_utils
from official.vision.beta.configs import image_classification as exp_cfg
from official.vision.beta.dataloaders import classification_input
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
26
from official.vision.beta.dataloaders import input_reader_factory
27
from official.vision.beta.dataloaders import tfds_classification_decoders
Abdullah Rashwan's avatar
Abdullah Rashwan committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from official.vision.beta.modeling import factory


@task_factory.register_task_cls(exp_cfg.ImageClassificationTask)
class ImageClassificationTask(base_task.Task):
  """A task for image classification."""

  def build_model(self):
    """Builds classification model."""
    input_specs = tf.keras.layers.InputSpec(
        shape=[None] + self.task_config.model.input_size)

    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)

    model = factory.build_classification_model(
        input_specs=input_specs,
        model_config=self.task_config.model,
        l2_regularizer=l2_regularizer)
    return model

Abdullah Rashwan's avatar
Abdullah Rashwan committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
  def initialize(self, model: tf.keras.Model):
    """Loading pretrained checkpoint."""
    if not self.task_config.init_checkpoint:
      return

    ckpt_dir_or_file = self.task_config.init_checkpoint
    if tf.io.gfile.isdir(ckpt_dir_or_file):
      ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)

    # Restoring checkpoint.
    if self.task_config.init_checkpoint_modules == 'all':
      ckpt = tf.train.Checkpoint(**model.checkpoint_items)
      status = ckpt.restore(ckpt_dir_or_file)
      status.assert_consumed()
    elif self.task_config.init_checkpoint_modules == 'backbone':
      ckpt = tf.train.Checkpoint(backbone=model.backbone)
      status = ckpt.restore(ckpt_dir_or_file)
      status.expect_partial().assert_existing_objects_matched()
    else:
Yeqing Li's avatar
Yeqing Li committed
72
73
      raise ValueError(
          "Only 'all' or 'backbone' can be used to initialize the model.")
Abdullah Rashwan's avatar
Abdullah Rashwan committed
74
75
76
77

    logging.info('Finished loading pretrained checkpoint from %s',
                 ckpt_dir_or_file)

Abdullah Rashwan's avatar
Abdullah Rashwan committed
78
79
80
81
82
83
  def build_inputs(self, params, input_context=None):
    """Builds classification input."""

    num_classes = self.task_config.model.num_classes
    input_size = self.task_config.model.input_size

84
85
86
87
88
89
90
91
92
    if params.tfds_name:
      if params.tfds_name in tfds_classification_decoders.TFDS_ID_TO_DECODER_MAP:
        decoder = tfds_classification_decoders.TFDS_ID_TO_DECODER_MAP[
            params.tfds_name]()
      else:
        raise ValueError('TFDS {} is not supported'.format(params.tfds_name))
    else:
      decoder = classification_input.Decoder()

Abdullah Rashwan's avatar
Abdullah Rashwan committed
93
94
95
    parser = classification_input.Parser(
        output_size=input_size[:2],
        num_classes=num_classes,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
96
        aug_policy=params.aug_policy,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
97
        randaug_magnitude=params.randaug_magnitude,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
98
99
        dtype=params.dtype)

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
100
    reader = input_reader_factory.input_reader_generator(
Abdullah Rashwan's avatar
Abdullah Rashwan committed
101
        params,
Rajagopal Ananthanarayanan's avatar
Rajagopal Ananthanarayanan committed
102
        dataset_fn=dataset_fn.pick_dataset_fn(params.file_type),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        decoder_fn=decoder.decode,
        parser_fn=parser.parse_fn(params.is_training))

    dataset = reader.read(input_context=input_context)

    return dataset

  def build_losses(self, labels, model_outputs, aux_losses=None):
    """Sparse categorical cross entropy loss.

    Args:
      labels: labels.
      model_outputs: Output logits of the classifier.
      aux_losses: auxiliarly loss tensors, i.e. `losses` in keras.Model.

    Returns:
      The total loss tensor.
    """
    losses_config = self.task_config.losses
    if losses_config.one_hot:
      total_loss = tf.keras.losses.categorical_crossentropy(
          labels,
          model_outputs,
          from_logits=True,
          label_smoothing=losses_config.label_smoothing)
    else:
      total_loss = tf.keras.losses.sparse_categorical_crossentropy(
          labels, model_outputs, from_logits=True)

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

    return total_loss

  def build_metrics(self, training=True):
    """Gets streaming metrics for training/validation."""
Pengchong Jin's avatar
Pengchong Jin committed
140
    k = self.task_config.evaluation.top_k
Abdullah Rashwan's avatar
Abdullah Rashwan committed
141
142
143
    if self.task_config.losses.one_hot:
      metrics = [
          tf.keras.metrics.CategoricalAccuracy(name='accuracy'),
Pengchong Jin's avatar
Pengchong Jin committed
144
145
          tf.keras.metrics.TopKCategoricalAccuracy(
              k=k, name='top_{}_accuracy'.format(k))]
Abdullah Rashwan's avatar
Abdullah Rashwan committed
146
147
148
149
    else:
      metrics = [
          tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
          tf.keras.metrics.SparseTopKCategoricalAccuracy(
Pengchong Jin's avatar
Pengchong Jin committed
150
              k=k, name='top_{}_accuracy'.format(k))]
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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
    return metrics

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

    Args:
      inputs: a dictionary of input tensors.
      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
    if self.task_config.losses.one_hot:
      labels = tf.one_hot(labels, self.task_config.model.num_classes)

    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 = self.build_losses(
          model_outputs=outputs, labels=labels, aux_losses=model.losses)
      # 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.
      if isinstance(
Pankaj Kanwar's avatar
Pankaj Kanwar committed
187
          optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
188
189
190
191
192
193
194
        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.
    if isinstance(
Pankaj Kanwar's avatar
Pankaj Kanwar committed
195
        optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
Abdullah Rashwan's avatar
Abdullah Rashwan committed
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
      grads = optimizer.get_unscaled_gradients(grads)
    optimizer.apply_gradients(list(zip(grads, tvars)))

    logs = {self.loss: loss}
    if metrics:
      self.process_metrics(metrics, labels, outputs)
    elif model.compiled_metrics:
      self.process_compiled_metrics(model.compiled_metrics, labels, outputs)
      logs.update({m.name: m.result() for m in model.metrics})
    return logs

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

    Args:
      inputs: a dictionary of input tensors.
      model: the keras.Model.
      metrics: a nested structure of metrics objects.

    Returns:
      A dictionary of logs.
    """
    features, labels = inputs
    if self.task_config.losses.one_hot:
      labels = tf.one_hot(labels, self.task_config.model.num_classes)

    outputs = self.inference_step(features, model)
    outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs)
    loss = self.build_losses(model_outputs=outputs, labels=labels,
                             aux_losses=model.losses)

    logs = {self.loss: loss}
    if metrics:
      self.process_metrics(metrics, labels, outputs)
    elif model.compiled_metrics:
      self.process_compiled_metrics(model.compiled_metrics, labels, outputs)
      logs.update({m.name: m.result() for m in model.metrics})
    return logs

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