mock_task.py 3.15 KB
Newer Older
Hongkun Yu's avatar
Hongkun Yu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# 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.

Hongkun Yu's avatar
Hongkun Yu committed
15
16
17
"""Mock task for testing."""

import dataclasses
Hongkun Yu's avatar
Hongkun Yu committed
18

Hongkun Yu's avatar
Hongkun Yu committed
19
20
21
22
import numpy as np
import tensorflow as tf

from official.core import base_task
23
from official.core import config_definitions as cfg
Hongkun Yu's avatar
Hongkun Yu committed
24
from official.core import exp_factory
Hongkun Yu's avatar
Hongkun Yu committed
25
from official.modeling.hyperparams import base_config
Hongkun Yu's avatar
Hongkun Yu committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44


class MockModel(tf.keras.Model):

  def __init__(self, network):
    super().__init__()
    self.network = network

  def call(self, inputs):
    outputs = self.network(inputs)
    self.add_loss(tf.reduce_mean(outputs))
    return outputs


@dataclasses.dataclass
class MockTaskConfig(cfg.TaskConfig):
  pass


Hongkun Yu's avatar
Hongkun Yu committed
45
@base_config.bind(MockTaskConfig)
Hongkun Yu's avatar
Hongkun Yu committed
46
47
48
class MockTask(base_task.Task):
  """Mock task object for testing."""

Hongkun Yu's avatar
Hongkun Yu committed
49
50
  def __init__(self, params=None, logging_dir=None, name=None):
    super().__init__(params=params, logging_dir=logging_dir, name=name)
Hongkun Yu's avatar
Hongkun Yu committed
51
52
53

  def build_model(self, *arg, **kwargs):
    inputs = tf.keras.layers.Input(shape=(2,), name="random", dtype=tf.float32)
Hongkun Yu's avatar
Hongkun Yu committed
54
    outputs = tf.keras.layers.Dense(
Le Hou's avatar
Le Hou committed
55
        1, bias_initializer=tf.keras.initializers.Ones(), name="dense_0")(
Hongkun Yu's avatar
Hongkun Yu committed
56
            inputs)
Hongkun Yu's avatar
Hongkun Yu committed
57
58
59
60
61
62
63
    network = tf.keras.Model(inputs=inputs, outputs=outputs)
    return MockModel(network)

  def build_metrics(self, training: bool = True):
    del training
    return [tf.keras.metrics.Accuracy(name="acc")]

Hongkun Yu's avatar
Hongkun Yu committed
64
65
  def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
    logs = super().validation_step(inputs, model, metrics)
Scott Zhu's avatar
Scott Zhu committed
66
    logs["counter"] = tf.constant(1, dtype=tf.float32)
Hongkun Yu's avatar
Hongkun Yu committed
67
68
    return logs

Hongkun Yu's avatar
Hongkun Yu committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  def build_inputs(self, params):

    def generate_data(_):
      x = tf.zeros(shape=(2,), dtype=tf.float32)
      label = tf.zeros([1], dtype=tf.int32)
      return x, label

    dataset = tf.data.Dataset.range(1)
    dataset = dataset.repeat()
    dataset = dataset.map(
        generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
    return dataset.prefetch(buffer_size=1).batch(2, drop_remainder=True)

  def aggregate_logs(self, state, step_outputs):
    if state is None:
      state = {}
    for key, value in step_outputs.items():
      if key not in state:
        state[key] = []
      state[key].append(
          np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value]))
    return state

92
  def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
Hongkun Yu's avatar
Hongkun Yu committed
93
94
95
96
97
98
99
100
101
102
    for k, v in aggregated_logs.items():
      aggregated_logs[k] = np.sum(np.stack(v, axis=0))
    return aggregated_logs


@exp_factory.register_config_factory("mock")
def mock_experiment() -> cfg.ExperimentConfig:
  config = cfg.ExperimentConfig(
      task=MockTaskConfig(), trainer=cfg.TrainerConfig())
  return config