multitask.py 5.6 KB
Newer Older
Hongkun Yu's avatar
Hongkun Yu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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.

"""Experimental MultiTask base class for multi-task training/evaluation."""
import abc
from typing import Dict, List, Optional, Text, Union

import tensorflow as tf
from official.core import base_task
from official.core import config_definitions
from official.core import task_factory
from official.modeling import optimization
Hongkun Yu's avatar
Hongkun Yu committed
24
from official.modeling.multitask import base_model
Hongkun Yu's avatar
Hongkun Yu committed
25
26
from official.modeling.multitask import configs

27
OptimizationConfig = optimization.OptimizationConfig
Hongkun Yu's avatar
Hongkun Yu committed
28
29
30
31
32
33
34
35
RuntimeConfig = config_definitions.RuntimeConfig


class MultiTask(tf.Module, metaclass=abc.ABCMeta):
  """A multi-task class to manage multiple tasks."""

  def __init__(self,
               tasks: Union[Dict[Text, base_task.Task], List[base_task.Task]],
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
36
               task_weights: Optional[Dict[str, Union[float, int]]] = None,
Hongkun Yu's avatar
Hongkun Yu committed
37
38
39
40
41
42
               task_eval_steps: Optional[Dict[str, int]] = None,
               name: Optional[str] = None):
    """MultiTask initialization.

    Args:
      tasks: a list or a flat dict of Task.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
43
44
45
      task_weights: a dict of (task, task weight), task weight can be applied
        directly during loss summation in a joint backward step, or it can be
        used to sample task among interleaved backward step.
Hongkun Yu's avatar
Hongkun Yu committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
      task_eval_steps: a dict of (task, eval steps).
      name: the instance name of a MultiTask object.
    """
    super().__init__(name=name)
    if isinstance(tasks, list):
      self._tasks = {}
      for task in tasks:
        if task.name in self._tasks:
          raise ValueError("Duplicated tasks found, task.name is %s" %
                           task.name)
        self._tasks[task.name] = task
    elif isinstance(tasks, dict):
      self._tasks = tasks
    else:
      raise ValueError("The tasks argument has an invalid type: %s" %
                       type(tasks))
    self._task_eval_steps = task_eval_steps or {}
    self._task_eval_steps = dict([
        (name, self._task_eval_steps.get(name, None)) for name in self.tasks
    ])
    self._task_weights = task_weights or {}
    self._task_weights = dict([
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
68
        (name, self._task_weights.get(name, 1.0)) for name in self.tasks
Hongkun Yu's avatar
Hongkun Yu committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    ])

  @classmethod
  def from_config(cls, config: configs.MultiTaskConfig, logging_dir=None):
    tasks = {}
    task_eval_steps = {}
    task_weights = {}
    for task_routine in config.task_routines:
      task_name = task_routine.task_name
      tasks[task_name] = task_factory.get_task(
          task_routine.task_config, logging_dir=logging_dir)
      task_eval_steps[task_name] = task_routine.eval_steps
      task_weights[task_name] = task_routine.task_weight
    return cls(
Hongkun Yu's avatar
Hongkun Yu committed
83
        tasks, task_eval_steps=task_eval_steps, task_weights=task_weights)
Hongkun Yu's avatar
Hongkun Yu committed
84
85
86
87
88
89
90
91
92
93
94

  @property
  def tasks(self):
    return self._tasks

  def task_eval_steps(self, task_name):
    return self._task_eval_steps[task_name]

  def task_weight(self, task_name):
    return self._task_weights[task_name]

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
95
96
97
98
  @property
  def task_weights(self):
    return self._task_weights

Hongkun Yu's avatar
Hongkun Yu committed
99
  @classmethod
100
101
  def create_optimizer(cls,
                       optimizer_config: OptimizationConfig,
Hongkun Yu's avatar
Hongkun Yu committed
102
                       runtime_config: Optional[RuntimeConfig] = None):
103
104
    return base_task.Task.create_optimizer(
        optimizer_config=optimizer_config, runtime_config=runtime_config)
Hongkun Yu's avatar
Hongkun Yu committed
105

Hongkun Yu's avatar
Hongkun Yu committed
106
107
108
  def joint_train_step(self, task_inputs,
                       multi_task_model: base_model.MultiTaskBaseModel,
                       optimizer: tf.keras.optimizers.Optimizer, task_metrics):
Hongkun Yu's avatar
Hongkun Yu committed
109
110
111
112
    """The joint train step.

    Args:
      task_inputs: a dictionary of task names and per-task features.
Hongkun Yu's avatar
Hongkun Yu committed
113
      multi_task_model: a MultiTaskBaseModel instance.
Hongkun Yu's avatar
Hongkun Yu committed
114
115
      optimizer: a tf.optimizers.Optimizer.
      task_metrics: a dictionary of task names and per-task metrics.
Hongkun Yu's avatar
Hongkun Yu committed
116

Hongkun Yu's avatar
Hongkun Yu committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    Returns:
      A dictionary of losses, inculding per-task losses and their weighted sum.
    """
    losses = {}
    with tf.GradientTape() as tape:
      total_loss = 0.0
      for name, model in multi_task_model.sub_tasks.items():
        inputs = task_inputs[name]
        if isinstance(inputs, tuple) and len(inputs) == 2:
          features, labels = inputs
        elif isinstance(inputs, dict):
          features, labels = inputs, inputs
        else:
          raise ValueError("The iterator output is neither a tuple nor a "
                           "dictionary. It is not implemented to support "
                           "such outputs.")
        outputs = model(features, training=True)
        task_loss = self.tasks[name].build_losses(labels, outputs)
        task_weight = self.task_weight(name)
        total_loss += task_weight * task_loss
        losses[name] = task_loss
        self.tasks[name].process_metrics(task_metrics[name], labels, outputs)

        # Scales loss as the default gradients allreduce performs sum inside
        # the optimizer.
        scaled_loss = total_loss / tf.distribute.get_strategy(
        ).num_replicas_in_sync
    tvars = multi_task_model.trainable_variables
    grads = tape.gradient(scaled_loss, tvars)
    optimizer.apply_gradients(list(zip(grads, tvars)))
    losses["total_loss"] = total_loss
    return losses