graph_builder.py 28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2017 Google Inc. 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.
# ==============================================================================
Ivan Bogatyy's avatar
Ivan Bogatyy committed
15
16
"""Builds a DRAGNN graph for local training."""

17
import collections
Ivan Bogatyy's avatar
Ivan Bogatyy committed
18
import tensorflow as tf
19

Ivan Bogatyy's avatar
Ivan Bogatyy committed
20
21
22
23
24
25
26
27
28
29
30
from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.platform import tf_logging as logging

from dragnn.protos import spec_pb2
from dragnn.python import component
from dragnn.python import composite_optimizer
from dragnn.python import dragnn_ops
from syntaxnet.util import check

try:
  tf.NotDifferentiable('ExtractFixedFeatures')
Terry Koo's avatar
Terry Koo committed
31
except KeyError, e:
Ivan Bogatyy's avatar
Ivan Bogatyy committed
32
33
34
  logging.info(str(e))


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
def _validate_grid_point(hyperparams, is_sub_optimizer=False):
  """Validates that a grid point's configuration is reasonable.

  Args:
    hyperparams (spec_pb2.GridPoint): Grid point to validate.
    is_sub_optimizer (bool): Whether this optimizer is a sub-optimizer of
      a composite optimizer.

  Raises:
    ValueError: If the grid point is not valid.
  """
  valid_methods = ('gradient_descent', 'adam', 'lazyadam', 'momentum',
                   'composite')
  if hyperparams.learning_method not in valid_methods:
    raise ValueError('Unknown learning method (optimizer)')

  if is_sub_optimizer:
    for base_only_field in ('decay_steps', 'decay_base', 'decay_staircase'):
      if hyperparams.HasField(base_only_field):
        raise ValueError('Field {} is not valid for sub-optimizers of a '
                         'composite optimizer.'.format(base_only_field))

  if hyperparams.learning_method == 'composite':
    spec = hyperparams.composite_optimizer_spec
    if spec.switch_after_steps < 1:
      raise ValueError('switch_after_steps {} not valid for composite '
                       'optimizer!'.format(spec.switch_after_steps))
    for sub_optimizer in (spec.method1, spec.method2):
      _validate_grid_point(sub_optimizer, is_sub_optimizer=True)


Ivan Bogatyy's avatar
Ivan Bogatyy committed
66
67
68
69
70
71
72
73
def _create_learning_rate(hyperparams, step_var):
  """Creates learning rate var, with decay and switching for CompositeOptimizer.

  Args:
    hyperparams: a GridPoint proto containing optimizer spec, particularly
      learning_method to determine optimizer class to use.
    step_var: tf.Variable, global training step.

74
75
76
  Raises:
    ValueError: If the composite optimizer is set, but not correctly configured.

Ivan Bogatyy's avatar
Ivan Bogatyy committed
77
78
79
80
81
  Returns:
    a scalar `Tensor`, the learning rate based on current step and hyperparams.
  """
  if hyperparams.learning_method != 'composite':
    base_rate = hyperparams.learning_rate
82
    adjusted_steps = step_var
Ivan Bogatyy's avatar
Ivan Bogatyy committed
83
84
85
86
87
  else:
    spec = hyperparams.composite_optimizer_spec
    switch = tf.less(step_var, spec.switch_after_steps)
    base_rate = tf.cond(switch, lambda: tf.constant(spec.method1.learning_rate),
                        lambda: tf.constant(spec.method2.learning_rate))
88
89
90
91
92
93
    if spec.reset_learning_rate:
      adjusted_steps = tf.cond(switch, lambda: step_var,
                               lambda: step_var - spec.switch_after_steps)
    else:
      adjusted_steps = step_var

Ivan Bogatyy's avatar
Ivan Bogatyy committed
94
  return tf.train.exponential_decay(
95
96
97
98
      learning_rate=base_rate,
      global_step=adjusted_steps,
      decay_steps=hyperparams.decay_steps,
      decay_rate=hyperparams.decay_base,
Ivan Bogatyy's avatar
Ivan Bogatyy committed
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
      staircase=hyperparams.decay_staircase)


def _create_optimizer(hyperparams, learning_rate_var, step_var=None):
  """Creates an optimizer object for a given spec, learning rate and step var.

  Args:
    hyperparams: a GridPoint proto containing optimizer spec, particularly
      learning_method to determine optimizer class to use.
    learning_rate_var: a `tf.Tensor`, the learning rate.
    step_var: a `tf.Variable`, global training step.

  Returns:
    a `tf.train.Optimizer` object that was built.
  """
  if hyperparams.learning_method == 'gradient_descent':
    return tf.train.GradientDescentOptimizer(
        learning_rate_var, use_locking=True)
  elif hyperparams.learning_method == 'adam':
    return tf.train.AdamOptimizer(
        learning_rate_var,
        beta1=hyperparams.adam_beta1,
        beta2=hyperparams.adam_beta2,
        epsilon=hyperparams.adam_eps,
        use_locking=True)
124
125
126
127
128
129
130
  elif hyperparams.learning_method == 'lazyadam':
    return tf.contrib.opt.LazyAdamOptimizer(
        learning_rate_var,
        beta1=hyperparams.adam_beta1,
        beta2=hyperparams.adam_beta2,
        epsilon=hyperparams.adam_eps,
        use_locking=True)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
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
  elif hyperparams.learning_method == 'momentum':
    return tf.train.MomentumOptimizer(
        learning_rate_var, hyperparams.momentum, use_locking=True)
  elif hyperparams.learning_method == 'composite':
    spec = hyperparams.composite_optimizer_spec
    optimizer1 = _create_optimizer(spec.method1, learning_rate_var, step_var)
    optimizer2 = _create_optimizer(spec.method2, learning_rate_var, step_var)
    if step_var is None:
      logging.fatal('step_var is required for CompositeOptimizer')
    switch = tf.less(step_var, spec.switch_after_steps)
    return composite_optimizer.CompositeOptimizer(
        optimizer1, optimizer2, switch, use_locking=True)
  else:
    logging.fatal('Unknown learning method (optimizer)')


class MasterBuilder(object):
  """A builder for a DRAGNN stack of models.

  This class is the major factory for all DRAGNN models. It provides
  common hooks to build training and evaluation targets from a single
  MasterSpec and hyperparameter configuration.

  The key concept is as follows: to execute a DRAGNN graph, one needs
  two stateful pieces:

    1. A handle to a C++ dragnn state, managed outside of TensorFlow and
       accesssed via the custom dragnn ops.
    2. A set of StoredActivations, one for each component, that contain network
       activations that can be used across components.

  TODO(googleuser): Update these comments to be accurate.
  Both of these can be handled automatically "under-the-hood" by the
  MasterBuilder API. For #1, the key consideration is that each C++
  ComputeSession is allocated statically, meaning memory is shared
  across different tensorflow::Session invocations. ComputeSessions are
  allocated from pools. The `pool_scope` identifies the pool, unique to this
  MasterBuilder, from which the ComputeSession is allocated. From there,
  GetSession takes care of handing out ComputeSessions with unique handles.
  Each ComputeSession can then be run concurrently.

  Attributes:
    spec: the MasterSpec proto.
    hyperparams: the GridPoint proto containing hyperparameters.
    pool_scope: string identifier for the ComputeSession pool to use.
    components: a list of ComponentBuilders in the order they are defined
      in the MasterSpec.
    lookup_component: a dictionary to lookup ComponentBuilders by name.
    optimizer: handle to the tf.train Optimizer object used to train this model.
    master_vars: dictionary of globally shared tf.Variable objects (e.g.
      the global training step and learning rate.)
Terry Koo's avatar
Terry Koo committed
182
183
    read_from_avg: Whether to use averaged params instead of normal params.
    build_runtime_graph: Whether to build a graph for use by the runtime.
Ivan Bogatyy's avatar
Ivan Bogatyy committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
  """

  def __init__(self, master_spec, hyperparam_config=None, pool_scope='shared'):
    """Initializes the MasterBuilder from specifications.

    During construction, all components are initialized along with their
    parameter tf.Variables.

    Args:
      master_spec: dragnn.MasterSpec proto.
      hyperparam_config: dragnn.GridPoint proto specifying hyperparameters.
        Defaults to empty specification.
      pool_scope: string identifier for the compute session pool to use.

    Raises:
      ValueError: if a component is not found in the registry.
    """
    self.spec = master_spec
Terry Koo's avatar
Terry Koo committed
202
203
204
    self.hyperparams = (
        spec_pb2.GridPoint()
        if hyperparam_config is None else hyperparam_config)
205
    _validate_grid_point(self.hyperparams)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
206
207
    self.pool_scope = pool_scope

208
209
    # Set the graph-level random seed before creating the Components so the ops
    # they create will use this seed.
Terry Koo's avatar
Terry Koo committed
210
    tf.set_random_seed(self.hyperparams.seed)
211

Ivan Bogatyy's avatar
Ivan Bogatyy committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    # Construct all utility class and variables for each Component.
    self.components = []
    self.lookup_component = {}
    for component_spec in master_spec.component:
      component_type = component_spec.component_builder.registered_name

      # Raises ValueError if not found.
      comp = component.ComponentBuilderBase.Create(component_type, self,
                                                   component_spec)

      self.lookup_component[comp.name] = comp
      self.components.append(comp)

    self.master_vars = {}
    with tf.variable_scope('master', reuse=False):
Terry Koo's avatar
Terry Koo committed
227
      # Add global step variable.
Ivan Bogatyy's avatar
Ivan Bogatyy committed
228
229
      self.master_vars['step'] = tf.get_variable(
          'step', [], initializer=tf.zeros_initializer(), dtype=tf.int32)
Terry Koo's avatar
Terry Koo committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

      # Add learning rate. If the learning rate is optimized externally, then
      # just create an assign op.
      if self.hyperparams.pbt_optimize_learning_rate:
        self.master_vars['learning_rate'] = tf.get_variable(
            'learning_rate',
            initializer=tf.constant(
                self.hyperparams.learning_rate, dtype=tf.float32))
        lr_assign_input = tf.placeholder(tf.float32, [],
                                         'pbt/assign/learning_rate/Value')
        tf.assign(
            self.master_vars['learning_rate'],
            value=lr_assign_input,
            name='pbt/assign/learning_rate')
      else:
        self.master_vars['learning_rate'] = _create_learning_rate(
            self.hyperparams, self.master_vars['step'])
Ivan Bogatyy's avatar
Ivan Bogatyy committed
247
248
249
250
251
252

    # Construct optimizer.
    self.optimizer = _create_optimizer(self.hyperparams,
                                       self.master_vars['learning_rate'],
                                       self.master_vars['step'])

Terry Koo's avatar
Terry Koo committed
253
254
255
    self.read_from_avg = False
    self.build_runtime_graph = False

Ivan Bogatyy's avatar
Ivan Bogatyy committed
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
  @property
  def component_names(self):
    return tuple(c.name for c in self.components)

  def _get_compute_session(self):
    """Returns a new ComputeSession handle."""
    return dragnn_ops.get_session(
        self.pool_scope,
        master_spec=self.spec.SerializeToString(),
        grid_point=self.hyperparams.SerializeToString(),
        name='GetSession')

  def _get_session_with_reader(self, enable_tracing):
    """Utility to create ComputeSession management ops.

    Creates a new ComputeSession handle and provides the following
    named nodes:

    ComputeSession/InputBatch -- a placeholder for attaching a string
      specification for AttachReader.
    ComputeSession/AttachReader -- the AttachReader op.

    Args:
      enable_tracing: bool, whether to enable tracing before attaching the data.

    Returns:
      handle: handle to a new ComputeSession returned by the AttachReader op.
      input_batch: InputBatch placeholder.
    """
    with tf.name_scope('ComputeSession'):
      input_batch = tf.placeholder(
          dtype=tf.string, shape=[None], name='InputBatch')

      # Get the ComputeSession and chain some essential ops.
      handle = self._get_compute_session()
      if enable_tracing:
        handle = dragnn_ops.set_tracing(handle, True)
      handle = dragnn_ops.attach_data_reader(
          handle, input_batch, name='AttachReader')

    return handle, input_batch

  def _outputs_with_release(self, handle, inputs, outputs):
    """Ensures ComputeSession is released before outputs are returned.

    Args:
      handle: Handle to ComputeSession on which all computation until now has
          depended. It will be released and assigned to the output 'run'.
      inputs: list of nodes we want to pass through without any dependencies.
      outputs: list of nodes whose access should ensure the ComputeSession is
          safely released.

    Returns:
      A dictionary of both input and output nodes.
    """
    with tf.control_dependencies(outputs.values()):
      with tf.name_scope('ComputeSession'):
        release_op = dragnn_ops.release_session(handle)
      run_op = tf.group(release_op, name='run')
      for output in outputs:
        with tf.control_dependencies([release_op]):
          outputs[output] = tf.identity(outputs[output], name=output)
    all_nodes = inputs.copy()
    all_nodes.update(outputs)

    # Add an alias for simply running without collecting outputs.
    # Common, for instance, with training.
    all_nodes['run'] = run_op
    return all_nodes

326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
  def build_warmup_graph(self, asset_dir):
    """Builds a warmup graph.

    This graph performs a MasterSpec asset location rewrite via
    SetAssetDirectory, then grabs a ComputeSession and immediately returns it.
    By grabbing a session, we cause the underlying transition systems to cache
    their static data reads.

    Args:
      asset_dir: The base directory to append to all resources.

    Returns:
      A single op suitable for passing to the legacy_init_op of the ModelSaver.
    """
    with tf.control_dependencies([dragnn_ops.set_asset_directory(asset_dir)]):
      session = self._get_compute_session()
      release_op = dragnn_ops.release_session(session)
    return tf.group(release_op, name='run')

Ivan Bogatyy's avatar
Ivan Bogatyy committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
  def build_training(self,
                     handle,
                     compute_gradients=True,
                     use_moving_average=False,
                     advance_counters=True,
                     component_weights=None,
                     unroll_using_oracle=None,
                     max_index=-1):
    """Builds a training pipeline.

    Args:
      handle: Handle tensor for the ComputeSession.
      compute_gradients: Whether to generate gradients and an optimizer op.
        When False, build_training will return a 'dry run' training op,
        used normally only for oracle tracing.
      use_moving_average: Whether or not to read from the moving
        average variables instead of the true parameters. Note: it is not
        possible to make gradient updates when this is True.
      advance_counters: Whether or not this loop should increment the
        per-component step counters.
      component_weights: If set, this is a list of relative weights
        each component's cost should get in the pipeline. Defaults to 1.0 for
        each component.
      unroll_using_oracle: If set, this is a list of booleans indicating
        whether or not to use the gold decodings for each component. Defaults
        to True for each component.
      max_index: Training will use only the first max_index components,
        or -1 for all components.

    Returns:
      handle: to the ComputeSession, conditioned on completing training step.
      outputs: a dictionary of useful training tensors.

    Raises:
      IndexError: if max_index is positive but out of bounds.
    """
    check.IsFalse(compute_gradients and use_moving_average,
                  'It is not possible to make gradient updates when reading '
                  'from the moving average variables.')

    self.read_from_avg = use_moving_average
    if max_index < 0:
      max_index = len(self.components)
    else:
      if not 0 < max_index <= len(self.components):
Terry Koo's avatar
Terry Koo committed
390
391
392
        raise IndexError(
            'Invalid max_index {} for components {}; handle {}'.format(
                max_index, self.component_names, handle.name))
Ivan Bogatyy's avatar
Ivan Bogatyy committed
393
394
395
396
397
398
399

    # By default, we train every component supervised.
    if not component_weights:
      component_weights = [1] * max_index
    if not unroll_using_oracle:
      unroll_using_oracle = [True] * max_index

Terry Koo's avatar
Terry Koo committed
400
401
402
403
404
    if not max_index <= len(unroll_using_oracle):
      raise IndexError(('Invalid max_index {} for unroll_using_oracle {}; '
                        'handle {}').format(max_index, unroll_using_oracle,
                                            handle.name))

Ivan Bogatyy's avatar
Ivan Bogatyy committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    component_weights = component_weights[:max_index]
    total_weight = (float)(sum(component_weights))
    component_weights = [w / total_weight for w in component_weights]

    unroll_using_oracle = unroll_using_oracle[:max_index]

    logging.info('Creating training target:')
    logging.info('\tWeights: %s', component_weights)
    logging.info('\tOracle: %s', unroll_using_oracle)

    metrics_list = []
    cost = tf.constant(0.)
    effective_batch = tf.constant(0)

    avg_ops = []
    params_to_train = []

    network_states = {}
    for component_index in range(0, max_index):
      comp = self.components[component_index]
      network_states[comp.name] = component.NetworkState()

      logging.info('Initializing data for component "%s"', comp.name)
      handle = dragnn_ops.init_component_data(
          handle, beam_size=comp.training_beam_size, component=comp.name)
      # TODO(googleuser): Phase out component.MasterState.
      master_state = component.MasterState(handle,
                                           dragnn_ops.batch_size(
                                               handle, component=comp.name))
      with tf.control_dependencies([handle, cost]):
435
        args = (master_state, network_states)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
436
        if unroll_using_oracle[component_index]:
437

Terry Koo's avatar
Terry Koo committed
438
439
440
441
          handle, component_cost, component_correct, component_total = (
              tf.cond(comp.training_beam_size > 1,
                      lambda: comp.build_structured_training(*args),
                      lambda: comp.build_greedy_training(*args)))
442

Ivan Bogatyy's avatar
Ivan Bogatyy committed
443
        else:
444
445
446
          handle = comp.build_greedy_inference(*args, during_training=True)
          component_cost = tf.constant(0.)
          component_correct, component_total = tf.constant(0), tf.constant(0)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

        weighted_component_cost = tf.multiply(
            component_cost,
            tf.constant((float)(component_weights[component_index])),
            name='weighted_component_cost')

        cost += weighted_component_cost
        effective_batch += component_total
        metrics_list += [[component_total], [component_correct]]

        if advance_counters:
          with tf.control_dependencies(
              [comp.advance_counters(component_total)]):
            cost = tf.identity(cost)

        # Keep track of which parameters will be trained, and any moving
        # average updates to apply for these parameters.
        params_to_train += comp.network.params
        if self.hyperparams.use_moving_average:
          avg_ops += comp.avg_ops

    # Concatenate evaluation results
    metrics = tf.concat(metrics_list, 0)

    # If gradient computation is requested, then:
    # 1. compute the gradients,
    # 2. add an optimizer to update the parameters using the gradients,
    # 3. make the ComputeSession handle depend on the optimizer.
Terry Koo's avatar
Terry Koo committed
475
    gradient_norm = tf.constant(0.)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
476
477
478
479
480
481
482
    if compute_gradients:
      logging.info('Creating train op with %d variables:\n\t%s',
                   len(params_to_train),
                   '\n\t'.join([x.name for x in params_to_train]))

      grads_and_vars = self.optimizer.compute_gradients(
          cost, var_list=params_to_train)
Terry Koo's avatar
Terry Koo committed
483
484
485
486
487
      clipped_gradients = [
          (self._clip_gradients(g), v) for g, v in grads_and_vars
      ]
      gradient_norm = tf.global_norm(list(zip(*clipped_gradients))[0])

Ivan Bogatyy's avatar
Ivan Bogatyy committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
      minimize_op = self.optimizer.apply_gradients(
          clipped_gradients, global_step=self.master_vars['step'])

      if self.hyperparams.use_moving_average:
        with tf.control_dependencies([minimize_op]):
          minimize_op = tf.group(*avg_ops)

      # Make sure all the side-effectful minimizations ops finish before
      # proceeding.
      with tf.control_dependencies([minimize_op]):
        handle = tf.identity(handle)

    # Restore that subsequent builds don't use average by default.
    self.read_from_avg = False

503
504
    cost = tf.check_numerics(cost, message='Cost is not finite.')

Ivan Bogatyy's avatar
Ivan Bogatyy committed
505
506
507
    # Returns named access to common outputs.
    outputs = {
        'cost': cost,
Terry Koo's avatar
Terry Koo committed
508
        'gradient_norm': gradient_norm,
Ivan Bogatyy's avatar
Ivan Bogatyy committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        'batch': effective_batch,
        'metrics': metrics,
    }
    return handle, outputs

  def _clip_gradients(self, grad):
    """Clips gradients if the hyperparameter `gradient_clip_norm` requires it.

    Sparse tensors, in the form of IndexedSlices returned for the
    gradients of embeddings, require special handling.

    Args:
      grad: Gradient Tensor, IndexedSlices, or None.

    Returns:
      Optionally clipped gradient.
    """
    if grad is not None and self.hyperparams.gradient_clip_norm > 0:
      logging.info('Clipping gradient %s', grad)
      if isinstance(grad, tf.IndexedSlices):
        tmp = tf.clip_by_norm(grad.values, self.hyperparams.gradient_clip_norm)
        return tf.IndexedSlices(tmp, grad.indices, grad.dense_shape)
      else:
        return tf.clip_by_norm(grad, self.hyperparams.gradient_clip_norm)
    else:
      return grad

  def build_post_restore_hook(self):
    """Builds a graph that should be executed after the restore op.

    This graph is intended to be run once, before the inference pipeline is
    run.

    Returns:
      setup_op - An op that, when run, guarantees all setup ops will run.
    """
545
546
547
548
549
550
551
552
    control_ops = []
    for comp in self.components:
      hook = comp.build_post_restore_hook()
      if isinstance(hook, collections.Iterable):
        control_ops.extend(hook)
      else:
        control_ops.append(hook)
    with tf.control_dependencies(control_ops):
Ivan Bogatyy's avatar
Ivan Bogatyy committed
553
554
      return tf.no_op(name='post_restore_hook_master')

Terry Koo's avatar
Terry Koo committed
555
556
557
558
  def build_inference(self,
                      handle,
                      use_moving_average=False,
                      build_runtime_graph=False):
Ivan Bogatyy's avatar
Ivan Bogatyy committed
559
560
561
562
563
564
565
566
567
    """Builds an inference pipeline.

    This always uses the whole pipeline.

    Args:
      handle: Handle tensor for the ComputeSession.
      use_moving_average: Whether or not to read from the moving
        average variables instead of the true parameters. Note: it is not
        possible to make gradient updates when this is True.
Terry Koo's avatar
Terry Koo committed
568
      build_runtime_graph: Whether to build a graph for use by the runtime.
Ivan Bogatyy's avatar
Ivan Bogatyy committed
569
570
571
572
573

    Returns:
      handle: Handle after annotation.
    """
    self.read_from_avg = use_moving_average
Terry Koo's avatar
Terry Koo committed
574
    self.build_runtime_graph = build_runtime_graph
Ivan Bogatyy's avatar
Ivan Bogatyy committed
575
576
577
578
579
580
    network_states = {}

    for comp in self.components:
      network_states[comp.name] = component.NetworkState()
      handle = dragnn_ops.init_component_data(
          handle, beam_size=comp.inference_beam_size, component=comp.name)
Terry Koo's avatar
Terry Koo committed
581
582
583
584
585
      if build_runtime_graph:
        batch_size = 1  # runtime uses singleton batches
      else:
        batch_size = dragnn_ops.batch_size(handle, component=comp.name)
      master_state = component.MasterState(handle, batch_size)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
586
587
588
589
590
      with tf.control_dependencies([handle]):
        handle = comp.build_greedy_inference(master_state, network_states)
      handle = dragnn_ops.write_annotations(handle, component=comp.name)

    self.read_from_avg = False
Terry Koo's avatar
Terry Koo committed
591
    self.build_runtime_graph = False
Ivan Bogatyy's avatar
Ivan Bogatyy committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
    return handle

  def add_training_from_config(self,
                               target_config,
                               prefix='train-',
                               trace_only=False,
                               **kwargs):
    """Constructs a training pipeline from a TrainTarget proto.

    This constructs a separately managed pipeline for a given target:
    it has its own ComputeSession, InputSpec placeholder, etc. The ops
    are given standardized names to allow access from the C++ API. It
    passes the values in target_config to build_training() above.

    For the default prefix ('train-'), and a target named 'target', this will
    construct the following targets in the graph:

      train-target/ComputeSession/* (the standard ComputeSession controls)
      train-target/run (handle to a completed training step)
      train-target/metrics (per-decision metrics from gold oracles)
      train-target/cost (total cost across all components)

    Enabling `trace_only` effectively creates a graph that is a 'dry run'.
    There will be no side affects. In addition, the gradients won't be computed
    and the model parameters will not be updated.

    Args:
      target_config: the TrainTarget proto.
      prefix: Preprends target_config.name with this to construct
        a unique identifier.
      trace_only: Enabling this will result in:
          1. Tracing will be enabled for the ComputeSession..
          2. A 'traces' node will be added to the outputs.
          3. Gradients will not be computed.
      **kwargs: Passed on to build_training() above.

    Returns:
      Dictionary of training targets.
    """
    logging.info('Creating new training target '
                 '%s'
                 ' from config: %s', target_config.name, str(target_config))
    scope_id = prefix + target_config.name
    with tf.name_scope(scope_id):
      # Construct training targets. Disable tracing during training.
      handle, input_batch = self._get_session_with_reader(trace_only)
638
639
640
641
642
643
644
645
646
647
648
649

      # If `trace_only` is True, the training graph shouldn't have any
      # side effects. Otherwise, the standard training scenario should
      # generate gradients and update counters.
      handle, outputs = self.build_training(
          handle,
          compute_gradients=not trace_only,
          advance_counters=not trace_only,
          component_weights=target_config.component_weights,
          unroll_using_oracle=target_config.unroll_using_oracle,
          max_index=target_config.max_index,
          **kwargs)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
650
651
652
653
      if trace_only:
        outputs['traces'] = dragnn_ops.get_component_trace(
            handle, component=self.spec.component[-1].name)
      else:
654
        # Standard training keeps track of the number of training steps.
Ivan Bogatyy's avatar
Ivan Bogatyy committed
655
656
657
658
659
660
661
662
663
664
665
666
667
        outputs['target_step'] = tf.get_variable(
            scope_id + '/TargetStep', [],
            initializer=tf.zeros_initializer(),
            dtype=tf.int32)
        increment_target_step = tf.assign_add(
            outputs['target_step'], 1, use_locking=True)

        with tf.control_dependencies([increment_target_step]):
          handle = tf.identity(handle)

      return self._outputs_with_release(handle, {'input_batch': input_batch},
                                        outputs)

Terry Koo's avatar
Terry Koo committed
668
669
670
671
  def add_annotation(self,
                     name_scope='annotation',
                     enable_tracing=False,
                     build_runtime_graph=False):
Ivan Bogatyy's avatar
Ivan Bogatyy committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
    """Adds an annotation pipeline to the graph.

    This will create the following additional named targets by default, for use
    in C++ annotation code (as well as regular ComputeSession targets):
      annotation/ComputeSession/session_id (placeholder for giving unique id)
      annotation/EmitAnnotations (get annotated data)
      annotation/GetComponentTrace (get trace data)
      annotation/SetTracing (sets tracing based on annotation/tracing_on)

    Args:
      name_scope: Scope for the annotation pipeline.
      enable_tracing: Enabling this will result in two things:
          1. Tracing will be enabled during inference.
          2. A 'traces' node will be added to the outputs.
Terry Koo's avatar
Terry Koo committed
686
      build_runtime_graph: Whether to build a graph for use by the runtime.
Ivan Bogatyy's avatar
Ivan Bogatyy committed
687
688
689
690
691
692

    Returns:
      A dictionary of input and output nodes.
    """
    with tf.name_scope(name_scope):
      handle, input_batch = self._get_session_with_reader(enable_tracing)
Terry Koo's avatar
Terry Koo committed
693
694
695
696
      handle = self.build_inference(
          handle,
          use_moving_average=True,
          build_runtime_graph=build_runtime_graph)
Ivan Bogatyy's avatar
Ivan Bogatyy committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715

      annotations = dragnn_ops.emit_annotations(
          handle, component=self.spec.component[-1].name)
      outputs = {'annotations': annotations}

      if enable_tracing:
        outputs['traces'] = dragnn_ops.get_component_trace(
            handle, component=self.spec.component[-1].name)

      return self._outputs_with_release(handle, {'input_batch': input_batch},
                                        outputs)

  def add_post_restore_hook(self, name_scope):
    """Adds the post restore ops."""
    with tf.name_scope(name_scope):
      return self.build_post_restore_hook()

  def add_saver(self):
    """Adds a Saver for all variables in the graph."""
Terry Koo's avatar
Terry Koo committed
716
    logging.info('Generating op to save variables:\n\t%s',
717
                 '\n\t'.join([x.name for x in tf.global_variables()]))
Ivan Bogatyy's avatar
Ivan Bogatyy committed
718
    self.saver = tf.train.Saver(
719
        var_list=[x for x in tf.global_variables()],
Ivan Bogatyy's avatar
Ivan Bogatyy committed
720
        write_version=saver_pb2.SaverDef.V1)