aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/estimator/python/estimator/multi_head.py
blob: 73bae5acf9c7c33a4c19a7eb1a5979ff7ff15ef0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
140
141
142
143
144
145
146
147
148
149
150
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
187
188
189
190
191
192
193
194
195
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# Copyright 2016 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.
# ==============================================================================
"""Abstractions for the head(s) of a model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import six

from tensorflow.python.estimator import model_fn
from tensorflow.python.estimator.canned import head as head_lib
from tensorflow.python.estimator.canned import metric_keys
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.summary import summary


_DEFAULT_SERVING_KEY = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY


def multi_head(heads, head_weights=None):
  """Creates a `_Head` for multi-objective learning.

  This class merges the output of multiple `_Head` objects.
  Specifically:
  * For training, sums losses of each head, calls `train_op_fn` with this
    final loss.
  * For eval, merges metrics by adding `head.name` suffix to the keys in eval
    metrics, such as `precision/head1`, `precision/head2`.
  * For prediction, merges predictions and updates keys in prediction dict to a
    2-tuple, `(head.name, prediction_key)`. Merges `export_outputs` such that
    by default the first head is served.

  Usage:

  ```python
  # In `input_fn` specify labels as a dict keyed by head name:
  def input_fn():
    features = ...
    labels1 = ...
    labels2 = ...
    return features, {'head1': labels1, 'head2': labels2}

  # In `model_fn`, specify logits as a dict keyed by head name:
  def model_fn(features, labels, mode):
    # Create simple heads and specify head name.
    head1 = multi_class_head(n_classes=3, name='head1')
    head2 = binary_classification_head(name='head2')
    # Create multi-head from two simple heads.
    head = multi_head([head1, head2])
    # Create logits for each head, and combine them into a dict.
    logits1, logits2 = logit_fn()
    logits = {'head1': logits1, 'head2': logits2}
    # Return the merged EstimatorSpec
    return head.create_estimator_spec(..., logits=logits, ...)

  # Create an estimator with this model_fn.
  estimator = tf.estimator.Estimator(model_fn=model_fn)
  estimator.train(input_fn=input_fn, steps=100)
  ```

  Also supports `logits` as a `Tensor` of shape
  `[D0, D1, ... DN, logits_dimension]`. It will split the `Tensor` along the
  last dimension and distribute it appropriately among the heads. E.g.:

  ```python
  def model_fn(features, labels, mode):
    # Create simple heads and specify head name.
    head1 = multi_class_head(n_classes=3, name='head1')
    head2 = binary_classification_head(name='head2')
    # Create multi-head from two simple heads.
    head = multi_head([head1, head2])
    # Create logits for the multihead.
    logits = logit_fn(logits_dimension=head.logits_dimension)
    # Return the merged EstimatorSpec
    return head.create_estimator_spec(..., logits=logits, ...)
  ```

  Args:
    heads: List or tuple of `_Head` instances. All heads must have `name`
      specified. The first head in the list is the default used at serving time.
    head_weights: Optional list of weights, same length as `heads`. Used when
      merging losses to calculate the weighted sum of losses from each head. If
      `None`, all losses are weighted equally.

  Returns:
    A instance of `_Head` that merges multiple heads.

  Raises:
    ValueError: If `heads` is empty.
    ValueError: If any of the `heads` does not have `name` specified.
    ValueError: If `heads` and `head_weights` have different size.
  """
  if head_weights:
    if len(head_weights) != len(heads):
      raise ValueError(
          'heads and head_weights must have the same size. '
          'Given len(heads): {}. Given len(head_weights): {}.'.format(
              len(heads), len(head_weights)))
  if not heads:
    raise ValueError('Must specify heads. Given: {}'.format(heads))
  for head in heads:
    if not head.name:
      raise ValueError(
          'All given heads must have name specified. '
          'Given: {}'.format(head))

  return _MultiHead(
      heads=tuple(heads),
      head_weights=tuple(head_weights) if head_weights else tuple())


def _no_op_train_fn(loss):
  del loss
  return control_flow_ops.no_op()


def _merge_losses(losses, head_weights=None):
  """Merges the given losses into one tensor."""
  losses = tuple(losses)
  with ops.name_scope(
      'merge_losses', values=losses + (head_weights or tuple())):
    if head_weights:
      weighted_losses = []
      for loss, weight in zip(losses, head_weights):
        weighted_losses.append(math_ops.multiply(loss, weight))
    else:
      weighted_losses = losses
    return math_ops.add_n(weighted_losses)


def _default_export_output(export_outputs, head_name):
  """Extracts the default export output from the given export_outputs dict."""
  if len(export_outputs) == 1:
    return next(six.itervalues(export_outputs))
  for k, v in six.iteritems(export_outputs):
    if k == _DEFAULT_SERVING_KEY:
      return v
  raise ValueError(
      '{} did not specify default export_outputs. '
      'Given: {} '
      'Suggested fix: Use one of the heads in tf.contrib.estimator, or include '
      'key {} in export_outputs.'.format(
          head_name, export_outputs, _DEFAULT_SERVING_KEY))


class _MultiHead(head_lib._Head):  # pylint:disable=protected-access
  """`_Head` for multi objective learning."""

  def __init__(self, heads, head_weights):
    self._logits_dimension = 0
    for head in heads:
      self._logits_dimension += head.logits_dimension

    self._heads = heads
    self._head_weights = head_weights

  @property
  def name(self):
    return '_'.join([h.name for h in self._heads])

  @property
  def logits_dimension(self):
    return self._logits_dimension

  def create_loss(self, features, mode, logits, labels):
    """See `Head`."""
    if isinstance(logits, dict):
      logits_dict = logits
    else:
      logits_dict = self._split_logits(logits)
    weighted_sum_losses = []
    example_weight_sums = []
    labels_by_head = {}
    for head in self._heads:
      (weighted_sum_loss,
       example_weight_sum, processed_labels) = head.create_loss(
           features, mode, logits_dict[head.name], labels[head.name])
      weighted_sum_losses.append(weighted_sum_loss)
      example_weight_sums.append(example_weight_sum)
      labels_by_head[head.name] = processed_labels

    weighted_sum_losses = tuple(weighted_sum_losses)
    with ops.name_scope('merge_losses',
                        values=weighted_sum_losses + (self._head_weights or
                                                      tuple())):
      if self._head_weights:
        head_weighted_losses = []
        head_weighted_example_weight_sums = []
        for loss, example_weight_sum, weight in zip(weighted_sum_losses,
                                                    example_weight_sums,
                                                    self._head_weights):
          head_weighted_losses.append(math_ops.multiply(loss, weight))
          head_weighted_example_weight_sums.append(math_ops.multiply(
              example_weight_sum, weight))
        merged_weighted_sum_loss = math_ops.add_n(head_weighted_losses)
        merged_example_weight_sum = math_ops.add_n(
            head_weighted_example_weight_sums)
      else:
        merged_weighted_sum_loss = math_ops.add_n(weighted_sum_losses)
        merged_example_weight_sum = math_ops.add_n(example_weight_sums)

    return head_lib.LossSpec(
        weighted_sum_loss=merged_weighted_sum_loss,
        example_weight_sum=merged_example_weight_sum,
        processed_labels=labels_by_head)

  def create_estimator_spec(
      self, features, mode, logits, labels=None, train_op_fn=None):
    """See `_Head`."""
    if isinstance(logits, dict):
      logits_dict = logits
    else:
      logits_dict = self._split_logits(logits)
    if labels and not isinstance(labels, dict):
      raise ValueError('labels must be a dict. Given: {}'.format(labels))

    all_estimator_spec = []
    for head in self._heads:
      head_name = head.name
      all_estimator_spec.append(
          head.create_estimator_spec(
              features=features,
              mode=mode,
              logits=logits_dict[head_name],
              labels=labels[head_name] if labels else None,
              train_op_fn=_no_op_train_fn))

    if mode == model_fn.ModeKeys.TRAIN:
      if train_op_fn is None:
        raise ValueError('train_op_fn can not be None in TRAIN mode.')
      spec = self._merge_train(all_estimator_spec, train_op_fn)
      with ops.name_scope(''):
        summary.scalar(metric_keys.MetricKeys.LOSS, spec.loss)
      return spec
    if mode == model_fn.ModeKeys.PREDICT:
      return self._merge_predict(all_estimator_spec)
    if mode == model_fn.ModeKeys.EVAL:
      return self._merge_eval(all_estimator_spec)
    raise ValueError('mode={} unrecognized'.format(mode))

  def _split_logits(self, logits):
    """Splits logits along the last dimension and returns a dict."""
    logits_dict = {}
    with ops.name_scope(None, 'split_logits', values=[logits]):
      logits = ops.convert_to_tensor(logits)
      batch_shape = array_ops.shape(logits)[:-1]
      zeros_like_batch_shape = array_ops.zeros_like(batch_shape)
      minus_ones_like_batch_shape = -1 * array_ops.ones_like(batch_shape)
      begin_idx = 0
      for head in self._heads:
        begin_tensor = array_ops.concat(
            [zeros_like_batch_shape, [begin_idx]], axis=0)
        size_tensor = array_ops.concat(
            [minus_ones_like_batch_shape, [head.logits_dimension]], axis=0)
        logits_dict[head.name] = array_ops.slice(
            logits, begin=begin_tensor, size=size_tensor)
        begin_idx += head.logits_dimension
    return logits_dict

  def _merge_train(self, all_estimator_spec, train_op_fn):
    """Merges list of `EstimatorSpec` for training.

    Args:
      all_estimator_spec: list of `EstimatorSpec` for the individual heads.
      train_op_fn: Function to create train op. See `create_estimator_spec`
        documentation for more details.

    Returns:
      `EstimatorSpec` that merges all heads for TRAIN.
    """
    losses = []
    metrics = {}
    for spec in all_estimator_spec:
      losses.append(spec.loss)
      # Metric keys already contain head.name.
      metrics.update(spec.eval_metric_ops or {})
    loss = _merge_losses(losses, self._head_weights)

    return model_fn.EstimatorSpec(
        mode=model_fn.ModeKeys.TRAIN,
        loss=loss,
        train_op=train_op_fn(loss),
        eval_metric_ops=metrics)

  def _merge_predict(self, all_estimator_spec):
    """Merges list of `EstimatorSpec` for prediction.

    Args:
      all_estimator_spec: list of `EstimatorSpec` for the individual heads.

    Returns:
      `EstimatorSpec` that merges all heads for PREDICT.
    """
    predictions = {}
    export_outputs = {
        _DEFAULT_SERVING_KEY: _default_export_output(
            all_estimator_spec[0].export_outputs,
            self._heads[0].name),
    }
    for head, spec in zip(self._heads, all_estimator_spec):
      head_name = head.name
      for k, v in six.iteritems(spec.export_outputs):
        if k == _DEFAULT_SERVING_KEY:
          key = head_name
        else:
          key = '%s/%s' % (k, head_name)
        export_outputs[key] = v
      for k, v in six.iteritems(spec.predictions):
        predictions[(head_name, k)] = v

    return model_fn.EstimatorSpec(
        mode=model_fn.ModeKeys.PREDICT,
        predictions=predictions,
        export_outputs=export_outputs)

  def _merge_eval(self, all_estimator_spec):
    """Merges list of `EstimatorSpec` for eval.

    Args:
      all_estimator_spec: list of `EstimatorSpec` for the individual heads.

    Returns:
      `EstimatorSpec` that merges all heads for EVAL.
    """
    predictions = {}
    metrics = {}
    losses = []
    for head, spec in zip(self._heads, all_estimator_spec):
      losses.append(spec.loss)
      head_name = head.name
      # Metric keys already contain head.name.
      metrics.update(spec.eval_metric_ops or {})
      for k, v in six.iteritems(spec.predictions):
        predictions[(head_name, k)] = v
    loss = _merge_losses(losses, self._head_weights)

    return model_fn.EstimatorSpec(
        mode=model_fn.ModeKeys.EVAL,
        predictions=predictions,
        loss=loss,
        eval_metric_ops=metrics)