component.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. """Builds a DRAGNN graph for local training."""
  2. from abc import ABCMeta
  3. from abc import abstractmethod
  4. import tensorflow as tf
  5. from tensorflow.python.platform import tf_logging as logging
  6. from dragnn.python import dragnn_ops
  7. from dragnn.python import network_units
  8. from syntaxnet.util import check
  9. from syntaxnet.util import registry
  10. class NetworkState(object):
  11. """Simple utility to manage the state of a DRAGNN network.
  12. This class encapsulates the variables that are a specific to any
  13. particular instance of a DRAGNN stack, as constructed by the
  14. MasterBuilder below.
  15. Attributes:
  16. activations: Dictionary mapping layer names to StoredActivation objects.
  17. """
  18. def __init__(self):
  19. self.activations = {}
  20. class MasterState(object):
  21. """Simple utility to encapsulate tensors associated with the master state.
  22. Attributes:
  23. handle: string tensor handle to the underlying nlp_saft::dragnn::MasterState
  24. current_batch_size: int tensor containing the batch size following the most
  25. recent MasterState::Reset().
  26. """
  27. def __init__(self, handle, current_batch_size):
  28. self.handle = handle
  29. self.current_batch_size = current_batch_size
  30. @registry.RegisteredClass
  31. class ComponentBuilderBase(object):
  32. """Utility to build a single Component in a DRAGNN stack of models.
  33. This class handles converting a ComponentSpec proto into various TF
  34. sub-graphs. It will stitch together various neural units with dynamic
  35. unrolling inside a tf.while loop.
  36. All variables for parameters are created during the constructor within the
  37. scope of the component's name, e.g. 'tagger/embedding_matrix_0' for a
  38. component named 'tagger'.
  39. As part of the specification, ComponentBuilder will wrap an underlying
  40. NetworkUnit which generates the actual network layout.
  41. """
  42. __metaclass__ = ABCMeta # required for @abstractmethod
  43. def __init__(self, master, component_spec, attr_defaults=None):
  44. """Initializes the ComponentBuilder from specifications.
  45. Args:
  46. master: dragnn.MasterBuilder object.
  47. component_spec: dragnn.ComponentSpec proto to be built.
  48. attr_defaults: Optional dict of component attribute defaults. If not
  49. provided or if empty, attributes are not extracted.
  50. """
  51. self.master = master
  52. self.num_actions = component_spec.num_actions
  53. self.name = component_spec.name
  54. self.spec = component_spec
  55. self.moving_average = None
  56. # Determine if this component should apply self-normalization.
  57. self.eligible_for_self_norm = (
  58. not self.master.hyperparams.self_norm_components_filter or self.name in
  59. self.master.hyperparams.self_norm_components_filter.split(','))
  60. # Extract component attributes before make_network(), so the network unit
  61. # can access them.
  62. self._attrs = {}
  63. if attr_defaults:
  64. self._attrs = network_units.get_attrs_with_defaults(
  65. self.spec.component_builder.parameters, attr_defaults)
  66. with tf.variable_scope(self.name):
  67. self.training_beam_size = tf.constant(
  68. self.spec.training_beam_size, name='TrainingBeamSize')
  69. self.inference_beam_size = tf.constant(
  70. self.spec.inference_beam_size, name='InferenceBeamSize')
  71. self.locally_normalize = tf.constant(False, name='LocallyNormalize')
  72. self._step = tf.get_variable(
  73. 'step', [], initializer=tf.zeros_initializer(), dtype=tf.int32)
  74. self._total = tf.get_variable(
  75. 'total', [], initializer=tf.zeros_initializer(), dtype=tf.int32)
  76. # Construct network variables.
  77. self.network = self.make_network(self.spec.network_unit)
  78. # Construct moving average.
  79. if self.master.hyperparams.use_moving_average:
  80. self.moving_average = tf.train.ExponentialMovingAverage(
  81. decay=self.master.hyperparams.average_weight, num_updates=self._step)
  82. self.avg_ops = [self.moving_average.apply(self.network.params)]
  83. def make_network(self, network_unit):
  84. """Makes a NetworkUnitInterface object based on the network_unit spec.
  85. Components may override this method to exert control over the
  86. network unit construction, such as which network units are supported.
  87. Args:
  88. network_unit: RegisteredModuleSpec proto defining the network unit.
  89. Returns:
  90. An implementation of NetworkUnitInterface.
  91. Raises:
  92. ValueError: if the requested network unit is not found in the registry.
  93. """
  94. network_type = network_unit.registered_name
  95. with tf.variable_scope(self.name):
  96. # Raises ValueError if not found.
  97. return network_units.NetworkUnitInterface.Create(network_type, self)
  98. @abstractmethod
  99. def build_greedy_training(self, state, network_states):
  100. """Builds a training graph for this component.
  101. Two assumptions are made about the resulting graph:
  102. 1. An oracle will be used to unroll the state and compute the cost.
  103. 2. The graph will be differentiable when the cost is being minimized.
  104. Args:
  105. state: MasterState from the 'AdvanceMaster' op that advances the
  106. underlying master to this component.
  107. network_states: dictionary of component NetworkState objects.
  108. Returns:
  109. (state, cost, correct, total) -- These are TF ops corresponding to
  110. the final state after unrolling, the total cost, the total number of
  111. correctly predicted actions, and the total number of actions.
  112. """
  113. pass
  114. @abstractmethod
  115. def build_greedy_inference(self, state, network_states,
  116. during_training=False):
  117. """Builds an inference graph for this component.
  118. If this graph is being constructed 'during_training', then it needs to be
  119. differentiable even though it doesn't return an explicit cost.
  120. There may be other cases where the distinction between training and eval is
  121. important. The handling of dropout is an example of this.
  122. Args:
  123. state: MasterState from the 'AdvanceMaster' op that advances the
  124. underlying master to this component.
  125. network_states: dictionary of component NetworkState objects.
  126. during_training: whether the graph is being constructed during training
  127. Returns:
  128. Handle to the state once inference is complete for this Component.
  129. """
  130. pass
  131. def get_summaries(self):
  132. """Constructs a set of summaries for this component.
  133. Returns:
  134. List of Summary ops to get parameter norms, progress reports, and
  135. so forth for this component.
  136. """
  137. def combine_norm(matrices):
  138. # Handles None in cases where the optimizer or moving average slot is
  139. # not present.
  140. squares = [tf.reduce_sum(tf.square(m)) for m in matrices if m is not None]
  141. # Some components may not have any parameters, in which case we simply
  142. # return zero.
  143. if squares:
  144. return tf.sqrt(tf.add_n(squares))
  145. else:
  146. return tf.constant(0, tf.float32)
  147. summaries = []
  148. summaries.append(tf.summary.scalar('%s step' % self.name, self._step))
  149. summaries.append(tf.summary.scalar('%s total' % self.name, self._total))
  150. if self.network.params:
  151. summaries.append(
  152. tf.summary.scalar('%s parameter Norm' % self.name,
  153. combine_norm(self.network.params)))
  154. slot_names = self.master.optimizer.get_slot_names()
  155. for name in slot_names:
  156. slot_params = [
  157. self.master.optimizer.get_slot(p, name) for p in self.network.params
  158. ]
  159. summaries.append(
  160. tf.summary.scalar('%s %s Norm' % (self.name, name),
  161. combine_norm(slot_params)))
  162. # Construct moving average.
  163. if self.master.hyperparams.use_moving_average:
  164. summaries.append(
  165. tf.summary.scalar('%s avg Norm' % self.name,
  166. combine_norm([
  167. self.moving_average.average(p)
  168. for p in self.network.params
  169. ])))
  170. return summaries
  171. def get_variable(self, var_name=None, var_params=None):
  172. """Returns either the original or averaged version of a given variable.
  173. If the master.read_from_avg flag is set to True, and the
  174. ExponentialMovingAverage (EMA) object has been attached, then this will ask
  175. the EMA object for the given variable.
  176. This is to allow executing inference from the averaged version of
  177. parameters.
  178. Arguments:
  179. var_name: Name of the variable.
  180. var_params: tf.Variable for which to retrieve an average.
  181. Only one of |var_name| or |var_params| needs to be provided. If both are
  182. provided, |var_params| takes precedence.
  183. Returns:
  184. tf.Variable object corresponding to original or averaged version.
  185. """
  186. if var_params:
  187. var_name = var_params.name
  188. else:
  189. check.NotNone(var_name, 'specify at least one of var_name or var_params')
  190. var_params = tf.get_variable(var_name)
  191. if self.moving_average and self.master.read_from_avg:
  192. logging.info('Retrieving average for: %s', var_name)
  193. var_params = self.moving_average.average(var_params)
  194. assert var_params
  195. logging.info('Returning: %s', var_params.name)
  196. return var_params
  197. def advance_counters(self, total):
  198. """Returns ops to advance the per-component step and total counters.
  199. Args:
  200. total: Total number of actions to increment counters by.
  201. Returns:
  202. tf.Group op incrementing 'step' by 1 and 'total' by total.
  203. """
  204. update_total = tf.assign_add(self._total, total, use_locking=True)
  205. update_step = tf.assign_add(self._step, 1, use_locking=True)
  206. return tf.group(update_total, update_step)
  207. def add_regularizer(self, cost):
  208. """Adds L2 regularization for parameters which have it turned on.
  209. Args:
  210. cost: float cost before regularization.
  211. Returns:
  212. Updated cost optionally including regularization.
  213. """
  214. if self.network is None:
  215. return cost
  216. regularized_weights = self.network.get_l2_regularized_weights()
  217. if not regularized_weights:
  218. return cost
  219. l2_coeff = self.master.hyperparams.l2_regularization_coefficient
  220. if l2_coeff == 0.0:
  221. return cost
  222. tf.logging.info('[%s] Regularizing parameters: %s', self.name,
  223. [w.name for w in regularized_weights])
  224. l2_costs = [tf.nn.l2_loss(p) for p in regularized_weights]
  225. return tf.add(cost, l2_coeff * tf.add_n(l2_costs), name='regularizer')
  226. def build_post_restore_hook(self):
  227. """Builds a post restore graph for this component.
  228. This is a run-once graph that prepares any state necessary for the
  229. inference portion of the component. It is generally a no-op.
  230. Returns:
  231. A no-op state.
  232. """
  233. logging.info('Building default post restore hook for component: %s',
  234. self.spec.name)
  235. return tf.no_op(name='setup_%s' % self.spec.name)
  236. def attr(self, name):
  237. """Returns the value of the component attribute with the |name|."""
  238. return self._attrs[name]
  239. def update_tensor_arrays(network_tensors, arrays):
  240. """Updates a list of tensor arrays from the network's output tensors.
  241. Arguments:
  242. network_tensors: Output tensors from the underlying NN unit.
  243. arrays: TensorArrays to be updated.
  244. Returns:
  245. New list of TensorArrays after writing activations.
  246. """
  247. # TODO(googleuser): Only store activations that will be used later in linked
  248. # feature specifications.
  249. next_arrays = []
  250. for index, network_tensor in enumerate(network_tensors):
  251. array = arrays[index]
  252. size = array.size()
  253. array = array.write(size, network_tensor)
  254. next_arrays.append(array)
  255. return next_arrays
  256. class DynamicComponentBuilder(ComponentBuilderBase):
  257. """Component builder for recurrent DRAGNN networks.
  258. Feature extraction and annotation are done sequentially in a tf.while_loop
  259. so fixed and linked features can be recurrent.
  260. """
  261. def build_greedy_training(self, state, network_states):
  262. """Builds a training loop for this component.
  263. This loop repeatedly evaluates the network and computes the loss, but it
  264. does not advance using the predictions of the network. Instead, it advances
  265. using the oracle defined in the underlying transition system. The final
  266. state will always correspond to the gold annotation.
  267. Args:
  268. state: MasterState from the 'AdvanceMaster' op that advances the
  269. underlying master to this component.
  270. network_states: NetworkState object containing component TensorArrays.
  271. Returns:
  272. (state, cost, correct, total) -- These are TF ops corresponding to
  273. the final state after unrolling, the total cost, the total number of
  274. correctly predicted actions, and the total number of actions.
  275. """
  276. logging.info('Building component: %s', self.spec.name)
  277. stride = state.current_batch_size * self.training_beam_size
  278. cost = tf.constant(0.)
  279. correct = tf.constant(0)
  280. total = tf.constant(0)
  281. # Create the TensorArray's to store activations for downstream/recurrent
  282. # connections.
  283. def cond(handle, *_):
  284. all_final = dragnn_ops.emit_all_final(handle, component=self.name)
  285. return tf.logical_not(tf.reduce_all(all_final))
  286. def body(handle, cost, correct, total, *arrays):
  287. """Runs the network and advances the state by a step."""
  288. with tf.control_dependencies([handle, cost, correct, total] +
  289. [x.flow for x in arrays]):
  290. # Get a copy of the network inside this while loop.
  291. updated_state = MasterState(handle, state.current_batch_size)
  292. network_tensors = self._feedforward_unit(
  293. updated_state, arrays, network_states, stride, during_training=True)
  294. # Every layer is written to a TensorArray, so that it can be backprop'd.
  295. next_arrays = update_tensor_arrays(network_tensors, arrays)
  296. with tf.control_dependencies([x.flow for x in next_arrays]):
  297. with tf.name_scope('compute_loss'):
  298. # A gold label > -1 determines that the sentence is still
  299. # in a valid state. Otherwise, the sentence has ended.
  300. #
  301. # We add only the valid sentences to the loss, in the following way:
  302. # 1. We compute 'valid_ix', the indices in gold that contain
  303. # valid oracle actions.
  304. # 2. We compute the cost function by comparing logits and gold
  305. # only for the valid indices.
  306. gold = dragnn_ops.emit_oracle_labels(handle, component=self.name)
  307. gold.set_shape([None])
  308. valid = tf.greater(gold, -1)
  309. valid_ix = tf.reshape(tf.where(valid), [-1])
  310. gold = tf.gather(gold, valid_ix)
  311. logits = self.network.get_logits(network_tensors)
  312. logits = tf.gather(logits, valid_ix)
  313. cost += tf.reduce_sum(
  314. tf.nn.sparse_softmax_cross_entropy_with_logits(
  315. labels=tf.cast(gold, tf.int64), logits=logits))
  316. if (self.eligible_for_self_norm and
  317. self.master.hyperparams.self_norm_alpha > 0):
  318. log_z = tf.reduce_logsumexp(logits, [1])
  319. cost += (self.master.hyperparams.self_norm_alpha *
  320. tf.nn.l2_loss(log_z))
  321. correct += tf.reduce_sum(
  322. tf.to_int32(tf.nn.in_top_k(logits, gold, 1)))
  323. total += tf.size(gold)
  324. with tf.control_dependencies([cost, correct, total, gold]):
  325. handle = dragnn_ops.advance_from_oracle(handle, component=self.name)
  326. return [handle, cost, correct, total] + next_arrays
  327. with tf.name_scope(self.name + '/train_state'):
  328. init_arrays = []
  329. for layer in self.network.layers:
  330. init_arrays.append(layer.create_array(state.current_batch_size))
  331. output = tf.while_loop(
  332. cond,
  333. body, [state.handle, cost, correct, total] + init_arrays,
  334. name='train_%s' % self.name)
  335. # Saves completed arrays and return final state and cost.
  336. state.handle = output[0]
  337. correct = output[2]
  338. total = output[3]
  339. arrays = output[4:]
  340. cost = output[1]
  341. # Store handles to the final output for use in subsequent tasks.
  342. network_state = network_states[self.name]
  343. with tf.name_scope(self.name + '/stored_act'):
  344. for index, layer in enumerate(self.network.layers):
  345. network_state.activations[layer.name] = network_units.StoredActivations(
  346. array=arrays[index])
  347. # Normalize the objective by the total # of steps taken.
  348. with tf.control_dependencies([tf.assert_greater(total, 0)]):
  349. cost /= tf.to_float(total)
  350. # Adds regularization for the hidden weights.
  351. cost = self.add_regularizer(cost)
  352. with tf.control_dependencies([x.flow for x in arrays]):
  353. return tf.identity(state.handle), cost, correct, total
  354. def build_greedy_inference(self, state, network_states,
  355. during_training=False):
  356. """Builds an inference loop for this component.
  357. Repeatedly evaluates the network and advances the underlying state according
  358. to the predicted scores.
  359. Args:
  360. state: MasterState from the 'AdvanceMaster' op that advances the
  361. underlying master to this component.
  362. network_states: NetworkState object containing component TensorArrays.
  363. during_training: whether the graph is being constructed during training
  364. Returns:
  365. Handle to the state once inference is complete for this Component.
  366. """
  367. logging.info('Building component: %s', self.spec.name)
  368. if during_training:
  369. stride = state.current_batch_size * self.training_beam_size
  370. else:
  371. stride = state.current_batch_size * self.inference_beam_size
  372. def cond(handle, *_):
  373. all_final = dragnn_ops.emit_all_final(handle, component=self.name)
  374. return tf.logical_not(tf.reduce_all(all_final))
  375. def body(handle, *arrays):
  376. """Runs the network and advances the state by a step."""
  377. with tf.control_dependencies([handle] + [x.flow for x in arrays]):
  378. # Get a copy of the network inside this while loop.
  379. updated_state = MasterState(handle, state.current_batch_size)
  380. network_tensors = self._feedforward_unit(
  381. updated_state,
  382. arrays,
  383. network_states,
  384. stride,
  385. during_training=during_training)
  386. next_arrays = update_tensor_arrays(network_tensors, arrays)
  387. with tf.control_dependencies([x.flow for x in next_arrays]):
  388. logits = self.network.get_logits(network_tensors)
  389. logits = tf.cond(self.locally_normalize,
  390. lambda: tf.nn.log_softmax(logits), lambda: logits)
  391. handle = dragnn_ops.advance_from_prediction(
  392. handle, logits, component=self.name)
  393. return [handle] + next_arrays
  394. # Create the TensorArray's to store activations for downstream/recurrent
  395. # connections.
  396. with tf.name_scope(self.name + '/inference_state'):
  397. init_arrays = []
  398. for layer in self.network.layers:
  399. init_arrays.append(layer.create_array(stride))
  400. output = tf.while_loop(
  401. cond,
  402. body, [state.handle] + init_arrays,
  403. name='inference_%s' % self.name)
  404. # Saves completed arrays and returns final state.
  405. state.handle = output[0]
  406. arrays = output[1:]
  407. network_state = network_states[self.name]
  408. with tf.name_scope(self.name + '/stored_act'):
  409. for index, layer in enumerate(self.network.layers):
  410. network_state.activations[layer.name] = network_units.StoredActivations(
  411. array=arrays[index])
  412. with tf.control_dependencies([x.flow for x in arrays]):
  413. return tf.identity(state.handle)
  414. def _feedforward_unit(self, state, arrays, network_states, stride,
  415. during_training):
  416. """Constructs a single instance of a feed-forward cell.
  417. Given an input state and access to the arrays storing activations, this
  418. function encapsulates creation of a single network unit. This will *not*
  419. create new variables.
  420. Args:
  421. state: MasterState for the state that will be used to extract features.
  422. arrays: List of TensorArrays corresponding to network outputs from this
  423. component. These are used for recurrent link features; the arrays from
  424. other components are used for stack-prop style connections.
  425. network_states: NetworkState object containing the TensorArrays from
  426. *all* components.
  427. stride: int Tensor with the current beam * batch size.
  428. during_training: Whether to build a unit for training (vs inference).
  429. Returns:
  430. List of tensors generated by the underlying network implementation.
  431. """
  432. with tf.variable_scope(self.name, reuse=True):
  433. fixed_embeddings = []
  434. for channel_id, feature_spec in enumerate(self.spec.fixed_feature):
  435. fixed_embedding = network_units.fixed_feature_lookup(
  436. self, state, channel_id, stride)
  437. if feature_spec.is_constant:
  438. fixed_embedding.tensor = tf.stop_gradient(fixed_embedding.tensor)
  439. fixed_embeddings.append(fixed_embedding)
  440. linked_embeddings = []
  441. for channel_id, feature_spec in enumerate(self.spec.linked_feature):
  442. if feature_spec.source_component == self.name:
  443. # Recurrent feature: pull from the local arrays.
  444. index = self.network.get_layer_index(feature_spec.source_layer)
  445. source_array = arrays[index]
  446. source_layer_size = self.network.layers[index].dim
  447. linked_embeddings.append(
  448. network_units.activation_lookup_recurrent(
  449. self, state, channel_id, source_array, source_layer_size,
  450. stride))
  451. else:
  452. # Stackprop style feature: pull from another component's arrays.
  453. source = self.master.lookup_component[feature_spec.source_component]
  454. source_tensor = network_states[source.name].activations[
  455. feature_spec.source_layer]
  456. source_layer_size = source.network.get_layer_size(
  457. feature_spec.source_layer)
  458. linked_embeddings.append(
  459. network_units.activation_lookup_other(
  460. self, state, channel_id, source_tensor.dynamic_tensor,
  461. source_layer_size))
  462. context_tensor_arrays = []
  463. for context_layer in self.network.context_layers:
  464. index = self.network.get_layer_index(context_layer.name)
  465. context_tensor_arrays.append(arrays[index])
  466. if self.spec.attention_component:
  467. logging.info('%s component has attention over %s', self.name,
  468. self.spec.attention_component)
  469. source = self.master.lookup_component[self.spec.attention_component]
  470. network_state = network_states[self.spec.attention_component]
  471. with tf.control_dependencies(
  472. [tf.assert_equal(state.current_batch_size, 1)]):
  473. attention_tensor = tf.identity(
  474. network_state.activations['layer_0'].bulk_tensor)
  475. else:
  476. attention_tensor = None
  477. return self.network.create(fixed_embeddings, linked_embeddings,
  478. context_tensor_arrays, attention_tensor,
  479. during_training)