multitask.py 5.81 KB
Newer Older
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Hongkun Yu's avatar
Hongkun Yu committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#
# 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
from official.modeling.multitask import configs
Frederick Liu's avatar
Frederick Liu committed
26
from official.modeling.privacy import configs as dp_configs
Hongkun Yu's avatar
Hongkun Yu committed
27

28
OptimizationConfig = optimization.OptimizationConfig
Hongkun Yu's avatar
Hongkun Yu committed
29
RuntimeConfig = config_definitions.RuntimeConfig
Frederick Liu's avatar
Frederick Liu committed
30
DifferentialPrivacyConfig = dp_configs.DifferentialPrivacyConfig
Hongkun Yu's avatar
Hongkun Yu committed
31
32
33
34
35
36
37


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
38
               task_weights: Optional[Dict[str, Union[float, int]]] = None,
Hongkun Yu's avatar
Hongkun Yu committed
39
40
41
42
43
44
               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
45
46
47
      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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
      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))
64
    self.task_eval_steps = task_eval_steps or {}
Hongkun Yu's avatar
Hongkun Yu committed
65
66
    self._task_weights = task_weights or {}
    self._task_weights = dict([
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
67
        (name, self._task_weights.get(name, 1.0)) for name in self.tasks
Hongkun Yu's avatar
Hongkun Yu committed
68
69
70
71
72
73
74
75
    ])

  @classmethod
  def from_config(cls, config: configs.MultiTaskConfig, logging_dir=None):
    tasks = {}
    task_eval_steps = {}
    task_weights = {}
    for task_routine in config.task_routines:
76
      task_name = task_routine.task_name or task_routine.task_config.name
Hongkun Yu's avatar
Hongkun Yu committed
77
      tasks[task_name] = task_factory.get_task(
78
          task_routine.task_config, logging_dir=logging_dir, name=task_name)
Hongkun Yu's avatar
Hongkun Yu committed
79
80
81
      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
82
        tasks, task_eval_steps=task_eval_steps, task_weights=task_weights)
Hongkun Yu's avatar
Hongkun Yu committed
83
84
85
86
87
88
89
90

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

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

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
91
92
93
94
  @property
  def task_weights(self):
    return self._task_weights

Hongkun Yu's avatar
Hongkun Yu committed
95
  @classmethod
96
97
  def create_optimizer(cls,
                       optimizer_config: OptimizationConfig,
Frederick Liu's avatar
Frederick Liu committed
98
99
                       runtime_config: Optional[RuntimeConfig] = None,
                       dp_config: Optional[DifferentialPrivacyConfig] = None):
100
    return base_task.Task.create_optimizer(
Frederick Liu's avatar
Frederick Liu committed
101
102
        optimizer_config=optimizer_config, runtime_config=runtime_config,
        dp_config=dp_config)
Hongkun Yu's avatar
Hongkun Yu committed
103

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

    Args:
      task_inputs: a dictionary of task names and per-task features.
Hongkun Yu's avatar
Hongkun Yu committed
112
      multi_task_model: a MultiTaskBaseModel instance.
Hongkun Yu's avatar
Hongkun Yu committed
113
114
      optimizer: a tf.optimizers.Optimizer.
      task_metrics: a dictionary of task names and per-task metrics.
Terry Huang's avatar
Terry Huang committed
115
      **kwargs: other arguments to pass through.
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
    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
Terry Huang's avatar
Terry Huang committed
138
139
        self.tasks[name].process_metrics(task_metrics[name], labels, outputs,
                                         **kwargs)
Hongkun Yu's avatar
Hongkun Yu committed
140
141
142
143
144
145
146
147
148
149

        # 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