spec_builder.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. """Utils for building DRAGNN specs."""
  16. import tensorflow as tf
  17. from dragnn.protos import spec_pb2
  18. from dragnn.python import lexicon
  19. from syntaxnet.ops import gen_parser_ops
  20. from syntaxnet.util import check
  21. class ComponentSpecBuilder(object):
  22. """Wrapper to help construct SyntaxNetComponent specifications.
  23. This class will help make sure that ComponentSpec's are consistent with the
  24. expectations of the SyntaxNet Component backend. It contains defaults used to
  25. create LinkFeatureChannel specifications according to the network_unit and
  26. transition_system of the source compnent. It also encapsulates common recipes
  27. for hooking up FML and translators.
  28. Attributes:
  29. spec: The dragnn.ComponentSpec proto.
  30. """
  31. def __init__(self,
  32. name,
  33. builder='DynamicComponentBuilder',
  34. backend='SyntaxNetComponent'):
  35. """Initializes the ComponentSpec with some defaults for SyntaxNet.
  36. Args:
  37. name: The name of this Component in the pipeline.
  38. builder: The component builder type.
  39. backend: The component backend type.
  40. """
  41. self.spec = spec_pb2.ComponentSpec(
  42. name=name,
  43. backend=self.make_module(backend),
  44. component_builder=self.make_module(builder))
  45. def make_module(self, name, **kwargs):
  46. """Forwards kwargs to easily created a RegisteredModuleSpec.
  47. Note: all kwargs should be string-valued.
  48. Args:
  49. name: The registered name of the module.
  50. **kwargs: Proto fields to be specified in the module.
  51. Returns:
  52. Newly created RegisteredModuleSpec.
  53. """
  54. return spec_pb2.RegisteredModuleSpec(
  55. registered_name=name, parameters=kwargs)
  56. def default_source_layer(self):
  57. """Returns the default source_layer setting for this ComponentSpec.
  58. Usually links are intended for a specific layer in the network unit.
  59. For common network units, this returns the hidden layer intended
  60. to be read by recurrent and cross-component connections.
  61. Returns:
  62. String name of default network layer.
  63. Raises:
  64. ValueError: if no default is known for the given setup.
  65. """
  66. for network, default_layer in [('FeedForwardNetwork', 'layer_0'),
  67. ('LayerNormBasicLSTMNetwork', 'state_h_0'),
  68. ('LSTMNetwork', 'layer_0'),
  69. ('IdentityNetwork', 'input_embeddings')]:
  70. if self.spec.network_unit.registered_name.endswith(network):
  71. return default_layer
  72. raise ValueError('No default source for network unit: %s' %
  73. self.spec.network_unit)
  74. def default_token_translator(self):
  75. """Returns the default source_translator setting for token representations.
  76. Most links are token-based: given a target token index, retrieve a learned
  77. representation for that token from this component. This depends on the
  78. transition system; e.g. we should make sure that left-to-right sequence
  79. models reverse the incoming token index when looking up representations from
  80. a right-to-left model.
  81. Returns:
  82. String name of default translator for this transition system.
  83. Raises:
  84. ValueError: if no default is known for the given setup.
  85. """
  86. transition_spec = self.spec.transition_system
  87. if transition_spec.registered_name == 'arc-standard':
  88. return 'shift-reduce-step'
  89. if transition_spec.registered_name in ('shift-only', 'tagger'):
  90. if 'left_to_right' in transition_spec.parameters:
  91. if transition_spec.parameters['left_to_right'] == 'false':
  92. return 'reverse-token'
  93. return 'identity'
  94. raise ValueError('Invalid transition spec: %s' % str(transition_spec))
  95. def add_token_link(self, source=None, source_layer=None, **kwargs):
  96. """Adds a link to source's token representations using default settings.
  97. Constructs a LinkedFeatureChannel proto and adds it to the spec, using
  98. defaults to assign the name, component, translator, and layer of the
  99. channel. The user must provide fml and embedding_dim.
  100. Args:
  101. source: SyntaxComponentBuilder object to pull representations from.
  102. source_layer: Optional override for a source layer instead of the default.
  103. **kwargs: Forwarded arguments to the LinkedFeatureChannel proto.
  104. """
  105. if source_layer is None:
  106. source_layer = source.default_source_layer()
  107. self.spec.linked_feature.add(
  108. name=source.spec.name,
  109. source_component=source.spec.name,
  110. source_layer=source_layer,
  111. source_translator=source.default_token_translator(),
  112. **kwargs)
  113. def add_rnn_link(self, source_layer=None, **kwargs):
  114. """Adds a recurrent link to this component using default settings.
  115. This adds the connection to the previous time step only to the network. It
  116. constructs a LinkedFeatureChannel proto and adds it to the spec, using
  117. defaults to assign the name, component, translator, and layer of the
  118. channel. The user must provide the embedding_dim only.
  119. Args:
  120. source_layer: Optional override for a source layer instead of the default.
  121. **kwargs: Forwarded arguments to the LinkedFeatureChannel proto.
  122. """
  123. if source_layer is None:
  124. source_layer = self.default_source_layer()
  125. self.spec.linked_feature.add(
  126. name='rnn',
  127. source_layer=source_layer,
  128. source_component=self.spec.name,
  129. source_translator='history',
  130. fml='constant',
  131. **kwargs)
  132. def set_transition_system(self, *args, **kwargs):
  133. """Shorthand to set transition_system using kwargs."""
  134. self.spec.transition_system.CopyFrom(self.make_module(*args, **kwargs))
  135. def set_network_unit(self, *args, **kwargs):
  136. """Shorthand to set network_unit using kwargs."""
  137. self.spec.network_unit.CopyFrom(self.make_module(*args, **kwargs))
  138. def add_fixed_feature(self, **kwargs):
  139. """Shorthand to add a fixed_feature using kwargs."""
  140. self.spec.fixed_feature.add(**kwargs)
  141. def add_link(self, source, source_layer=None, source_translator='identity',
  142. name=None, **kwargs):
  143. """Add a link using default naming and layers only."""
  144. if source_layer is None:
  145. source_layer = source.default_source_layer()
  146. if name is None:
  147. name = source.spec.name
  148. self.spec.linked_feature.add(
  149. source_component=source.spec.name, source_layer=source_layer,
  150. name=name, source_translator=source_translator,
  151. **kwargs)
  152. def fill_from_resources(self, resource_path, tf_master=''):
  153. """Fills in feature sizes and vocabularies using SyntaxNet lexicon.
  154. Must be called before the spec is ready to be used to build TensorFlow
  155. graphs. Requires a SyntaxNet lexicon built at the resource_path. Using the
  156. lexicon, this will call the SyntaxNet custom ops to return the number of
  157. features and vocabulary sizes based on the FML specifications and the
  158. lexicons. It will also compute the number of actions of the transition
  159. system.
  160. This will often CHECK-fail if the spec doesn't correspond to a valid
  161. transition system or feature setup.
  162. Args:
  163. resource_path: Path to the lexicon.
  164. tf_master: TensorFlow master executor (string, defaults to '' to use the
  165. local instance).
  166. """
  167. check.IsTrue(
  168. self.spec.transition_system.registered_name,
  169. 'Set a transition system before calling fill_from_resources().')
  170. context = lexicon.create_lexicon_context(resource_path)
  171. for key, value in self.spec.transition_system.parameters.iteritems():
  172. context.parameter.add(name=key, value=value)
  173. context.parameter.add(
  174. name='brain_parser_embedding_dims',
  175. value=';'.join(
  176. [str(x.embedding_dim) for x in self.spec.fixed_feature]))
  177. context.parameter.add(
  178. name='brain_parser_features',
  179. value=';'.join([x.fml for x in self.spec.fixed_feature]))
  180. context.parameter.add(
  181. name='brain_parser_predicate_maps',
  182. value=';'.join(['' for x in self.spec.fixed_feature]))
  183. context.parameter.add(
  184. name='brain_parser_embedding_names',
  185. value=';'.join([x.name for x in self.spec.fixed_feature]))
  186. context.parameter.add(
  187. name='brain_parser_transition_system',
  188. value=self.spec.transition_system.registered_name)
  189. # Propagate information from SyntaxNet C++ backends into the DRAGNN
  190. # self.spec.
  191. with tf.Session(tf_master) as sess:
  192. feature_sizes, domain_sizes, _, num_actions = sess.run(
  193. gen_parser_ops.feature_size(task_context_str=str(context)))
  194. self.spec.num_actions = int(num_actions)
  195. for i in xrange(len(feature_sizes)):
  196. self.spec.fixed_feature[i].size = int(feature_sizes[i])
  197. self.spec.fixed_feature[i].vocabulary_size = int(domain_sizes[i])
  198. for i in xrange(len(self.spec.linked_feature)):
  199. self.spec.linked_feature[i].size = len(
  200. self.spec.linked_feature[i].fml.split(' '))
  201. for resource in context.input:
  202. self.spec.resource.add(name=resource.name).part.add(
  203. file_pattern=resource.part[0].file_pattern)
  204. def complete_master_spec(master_spec, lexicon_corpus, output_path,
  205. tf_master=''):
  206. """Finishes a MasterSpec that defines the network config.
  207. Given a MasterSpec that defines the DRAGNN architecture, completes the spec so
  208. that it can be used to build a DRAGNN graph and run training/inference.
  209. Args:
  210. master_spec: MasterSpec.
  211. lexicon_corpus: the corpus to be used with the LexiconBuilder.
  212. output_path: directory to save resources to.
  213. tf_master: TensorFlow master executor (string, defaults to '' to use the
  214. local instance).
  215. Returns:
  216. None, since the spec is changed in-place.
  217. """
  218. if lexicon_corpus:
  219. lexicon.build_lexicon(output_path, lexicon_corpus)
  220. # Use Syntaxnet builder to fill out specs.
  221. for i, spec in enumerate(master_spec.component):
  222. builder = ComponentSpecBuilder(spec.name)
  223. builder.spec = spec
  224. builder.fill_from_resources(output_path, tf_master=tf_master)
  225. master_spec.component[i].CopyFrom(builder.spec)
  226. def default_targets_from_spec(spec):
  227. """Constructs a default set of TrainTarget protos from a DRAGNN spec.
  228. For each component in the DRAGNN spec, it adds a training target for that
  229. component's oracle. It also stops unrolling the graph with that component. It
  230. skips any 'shift-only' transition systems which have no oracle. E.g.: if there
  231. are three components, a 'shift-only', a 'tagger', and a 'arc-standard', it
  232. will construct two training targets, one for the tagger and one for the
  233. arc-standard parser.
  234. Arguments:
  235. spec: DRAGNN spec.
  236. Returns:
  237. List of TrainTarget protos.
  238. """
  239. component_targets = [
  240. spec_pb2.TrainTarget(
  241. name=component.name,
  242. max_index=idx + 1,
  243. unroll_using_oracle=[False] * idx + [True])
  244. for idx, component in enumerate(spec.component)
  245. if not component.transition_system.registered_name.endswith('shift-only')
  246. ]
  247. return component_targets