biaffine_units.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. """Network units used in the Dozat and Manning (2017) biaffine parser."""
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. import tensorflow as tf
  6. from dragnn.python import digraph_ops
  7. from dragnn.python import network_units
  8. from syntaxnet.util import check
  9. class BiaffineDigraphNetwork(network_units.NetworkUnitInterface):
  10. """Network unit that computes biaffine digraph scores.
  11. The D&M parser uses two MLPs to create two activation vectors for each token,
  12. which represent the token when it it used as the source or target of an arc.
  13. Arcs are scored using a "biaffine" function that includes a bilinear and
  14. linear term:
  15. sources[s] * arc_weights * targets[t] + sources[s] * source_weights
  16. The digraph is "unlabeled" in that there is at most one arc between any pair
  17. of tokens. If labels are required, the BiaffineLabelNetwork can be used to
  18. label a set of selected arcs.
  19. Note that in the typical use case where the source and target activations are
  20. the same dimension and are produced by single-layer MLPs, it is arithmetically
  21. equivalent to produce the source and target activations using a single MLP of
  22. twice the size, and then split those activations in half. The |SplitNetwork|
  23. can be used for this purpose.
  24. Parameters:
  25. None.
  26. Features:
  27. sources: [B * N, S] matrix of batched activations for source tokens.
  28. targets: [B * N, T] matrix of batched activations for target tokens.
  29. Layers:
  30. adjacency: [B * N, N] matrix where entry b*N+s,t is the score of the arc
  31. from s to t in batch b, if s != t, or the score for selecting t
  32. as a root, if s == t.
  33. """
  34. def __init__(self, component):
  35. """Initializes weights and layers.
  36. Args:
  37. component: Parent ComponentBuilderBase object.
  38. """
  39. super(BiaffineDigraphNetwork, self).__init__(component)
  40. check.Eq(len(self._fixed_feature_dims.items()), 0,
  41. 'Expected no fixed features')
  42. check.Eq(len(self._linked_feature_dims.items()), 2,
  43. 'Expected two linked features')
  44. check.In('sources', self._linked_feature_dims,
  45. 'Missing required linked feature')
  46. check.In('targets', self._linked_feature_dims,
  47. 'Missing required linked feature')
  48. self._source_dim = self._linked_feature_dims['sources']
  49. self._target_dim = self._linked_feature_dims['targets']
  50. # TODO(googleuser): Make parameter initialization configurable.
  51. self._weights = []
  52. self._weights.append(tf.get_variable(
  53. 'weights_arc', [self._source_dim, self._target_dim], tf.float32,
  54. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  55. self._weights.append(tf.get_variable(
  56. 'weights_source', [self._source_dim], tf.float32,
  57. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  58. self._weights.append(tf.get_variable(
  59. 'root', [self._source_dim], tf.float32,
  60. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  61. self._params.extend(self._weights)
  62. self._regularized_weights.extend(self._weights)
  63. # Negative Layer.dim indicates that the dimension is dynamic.
  64. self._layers.append(network_units.Layer(self, 'adjacency', -1))
  65. def create(self,
  66. fixed_embeddings,
  67. linked_embeddings,
  68. context_tensor_arrays,
  69. attention_tensor,
  70. during_training,
  71. stride=None):
  72. """Requires |stride|; otherwise see base class."""
  73. check.NotNone(stride,
  74. 'BiaffineDigraphNetwork requires "stride" and must be called '
  75. 'in the bulk feature extractor component.')
  76. # TODO(googleuser): Add dropout during training.
  77. del during_training
  78. # Retrieve (possibly averaged) weights.
  79. weights_arc = self._component.get_variable('weights_arc')
  80. weights_source = self._component.get_variable('weights_source')
  81. root = self._component.get_variable('root')
  82. # Extract the source and target token activations. Use |stride| to collapse
  83. # batch and beam into a single dimension.
  84. sources = network_units.lookup_named_tensor('sources', linked_embeddings)
  85. targets = network_units.lookup_named_tensor('targets', linked_embeddings)
  86. source_tokens_bxnxs = tf.reshape(sources.tensor,
  87. [stride, -1, self._source_dim])
  88. target_tokens_bxnxt = tf.reshape(targets.tensor,
  89. [stride, -1, self._target_dim])
  90. num_tokens = tf.shape(source_tokens_bxnxs)[1]
  91. # Compute the arc, source, and root potentials.
  92. arcs_bxnxn = digraph_ops.ArcPotentialsFromTokens(
  93. source_tokens_bxnxs, target_tokens_bxnxt, weights_arc)
  94. sources_bxnxn = digraph_ops.ArcSourcePotentialsFromTokens(
  95. source_tokens_bxnxs, weights_source)
  96. roots_bxn = digraph_ops.RootPotentialsFromTokens(
  97. root, target_tokens_bxnxt, weights_arc)
  98. # Combine them into a single matrix with the roots on the diagonal.
  99. adjacency_bxnxn = digraph_ops.CombineArcAndRootPotentials(
  100. arcs_bxnxn + sources_bxnxn, roots_bxn)
  101. return [tf.reshape(adjacency_bxnxn, [-1, num_tokens])]
  102. class BiaffineLabelNetwork(network_units.NetworkUnitInterface):
  103. """Network unit that computes biaffine label scores.
  104. D&M parser uses a slightly modified version of the arc scoring function to
  105. score labels. The differences are:
  106. 1. Each label has its own source and target MLPs and biaffine weights.
  107. 2. A linear term for the target token is added.
  108. 3. A bias term is added.
  109. Parameters:
  110. num_labels: The number of dependency labels, L.
  111. Features:
  112. sources: [B * N, S] matrix of batched activations for source tokens.
  113. targets: [B * N, T] matrix of batched activations for target tokens.
  114. Layers:
  115. labels: [B * N, L] matrix where entry b*N+t,l is the score of the label of
  116. the inbound arc for token t in batch b.
  117. """
  118. def __init__(self, component):
  119. """Initializes weights and layers.
  120. Args:
  121. component: Parent ComponentBuilderBase object.
  122. """
  123. super(BiaffineLabelNetwork, self).__init__(component)
  124. parameters = component.spec.network_unit.parameters
  125. self._num_labels = int(parameters['num_labels'])
  126. check.Gt(self._num_labels, 0, 'Expected some labels')
  127. check.Eq(len(self._fixed_feature_dims.items()), 0,
  128. 'Expected no fixed features')
  129. check.Eq(len(self._linked_feature_dims.items()), 2,
  130. 'Expected two linked features')
  131. check.In('sources', self._linked_feature_dims,
  132. 'Missing required linked feature')
  133. check.In('targets', self._linked_feature_dims,
  134. 'Missing required linked feature')
  135. self._source_dim = self._linked_feature_dims['sources']
  136. self._target_dim = self._linked_feature_dims['targets']
  137. # TODO(googleuser): Make parameter initialization configurable.
  138. self._weights = []
  139. self._weights.append(tf.get_variable(
  140. 'weights_pair', [self._num_labels, self._source_dim, self._target_dim],
  141. tf.float32, tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  142. self._weights.append(tf.get_variable(
  143. 'weights_source', [self._num_labels, self._source_dim], tf.float32,
  144. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  145. self._weights.append(tf.get_variable(
  146. 'weights_target', [self._num_labels, self._target_dim], tf.float32,
  147. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  148. self._biases = []
  149. self._biases.append(tf.get_variable(
  150. 'biases', [self._num_labels], tf.float32,
  151. tf.random_normal_initializer(stddev=1e-4, seed=self._seed)))
  152. self._params.extend(self._weights + self._biases)
  153. self._regularized_weights.extend(self._weights)
  154. self._layers.append(network_units.Layer(self, 'labels', self._num_labels))
  155. def create(self,
  156. fixed_embeddings,
  157. linked_embeddings,
  158. context_tensor_arrays,
  159. attention_tensor,
  160. during_training,
  161. stride=None):
  162. """Requires |stride|; otherwise see base class."""
  163. check.NotNone(stride,
  164. 'BiaffineLabelNetwork requires "stride" and must be called '
  165. 'in the bulk feature extractor component.')
  166. # TODO(googleuser): Add dropout during training.
  167. del during_training
  168. # Retrieve (possibly averaged) weights.
  169. weights_pair = self._component.get_variable('weights_pair')
  170. weights_source = self._component.get_variable('weights_source')
  171. weights_target = self._component.get_variable('weights_target')
  172. biases = self._component.get_variable('biases')
  173. # Extract and shape the source and target token activations. Use |stride|
  174. # to collapse batch and beam into a single dimension.
  175. sources = network_units.lookup_named_tensor('sources', linked_embeddings)
  176. targets = network_units.lookup_named_tensor('targets', linked_embeddings)
  177. sources_bxnxs = tf.reshape(sources.tensor, [stride, -1, self._source_dim])
  178. targets_bxnxt = tf.reshape(targets.tensor, [stride, -1, self._target_dim])
  179. # Compute the pair, source, and target potentials.
  180. pairs_bxnxl = digraph_ops.LabelPotentialsFromTokenPairs(sources_bxnxs,
  181. targets_bxnxt,
  182. weights_pair)
  183. sources_bxnxl = digraph_ops.LabelPotentialsFromTokens(sources_bxnxs,
  184. weights_source)
  185. targets_bxnxl = digraph_ops.LabelPotentialsFromTokens(targets_bxnxt,
  186. weights_target)
  187. # Combine them with the biases.
  188. labels_bxnxl = pairs_bxnxl + sources_bxnxl + targets_bxnxl + biases
  189. # Flatten out the batch dimension.
  190. return [tf.reshape(labels_bxnxl, [-1, self._num_labels])]