biaffine_units.py 10 KB

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