wrapped_units.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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 wrapping TensorFlows' tf.contrib.rnn cells.
  16. Please put all wrapping logic for tf.contrib.rnn in this module; this will help
  17. collect common subroutines that prove useful.
  18. """
  19. import abc
  20. import tensorflow as tf
  21. from dragnn.python import network_units as dragnn
  22. from syntaxnet.util import check
  23. class BaseLSTMNetwork(dragnn.NetworkUnitInterface):
  24. """Base class for wrapped LSTM networks.
  25. This LSTM network unit supports multiple layers with layer normalization.
  26. Because it is imported from tf.contrib.rnn, we need to capture the created
  27. variables during initialization time.
  28. Layers:
  29. ...subclass-specific layers...
  30. last_layer: Alias for the activations of the last hidden layer.
  31. logits: Logits associated with component actions.
  32. """
  33. def __init__(self, component, additional_attr_defaults=None):
  34. """Initializes the LSTM base class.
  35. Parameters used:
  36. hidden_layer_sizes: Comma-delimited number of hidden units for each layer.
  37. input_dropout_rate (-1.0): Input dropout rate for each layer. If < 0.0,
  38. use the global |dropout_rate| hyperparameter.
  39. recurrent_dropout_rate (0.8): Recurrent dropout rate. If < 0.0, use the
  40. global |recurrent_dropout_rate| hyperparameter.
  41. layer_norm (True): Whether or not to use layer norm.
  42. Hyperparameters used:
  43. dropout_rate: Input dropout rate.
  44. recurrent_dropout_rate: Recurrent dropout rate.
  45. Args:
  46. component: parent ComponentBuilderBase object.
  47. additional_attr_defaults: Additional attributes for use by derived class.
  48. """
  49. attr_defaults = additional_attr_defaults or {}
  50. attr_defaults.update({
  51. 'layer_norm': True,
  52. 'input_dropout_rate': -1.0,
  53. 'recurrent_dropout_rate': 0.8,
  54. 'hidden_layer_sizes': '256',
  55. })
  56. self._attrs = dragnn.get_attrs_with_defaults(
  57. component.spec.network_unit.parameters,
  58. defaults=attr_defaults)
  59. self._hidden_layer_sizes = map(int,
  60. self._attrs['hidden_layer_sizes'].split(','))
  61. self._input_dropout_rate = self._attrs['input_dropout_rate']
  62. if self._input_dropout_rate < 0.0:
  63. self._input_dropout_rate = component.master.hyperparams.dropout_rate
  64. self._recurrent_dropout_rate = self._attrs['recurrent_dropout_rate']
  65. if self._recurrent_dropout_rate < 0.0:
  66. self._recurrent_dropout_rate = (
  67. component.master.hyperparams.recurrent_dropout_rate)
  68. if self._recurrent_dropout_rate < 0.0:
  69. self._recurrent_dropout_rate = component.master.hyperparams.dropout_rate
  70. tf.logging.info('[%s] input_dropout_rate=%s recurrent_dropout_rate=%s',
  71. component.name, self._input_dropout_rate,
  72. self._recurrent_dropout_rate)
  73. layers, context_layers = self.create_hidden_layers(component,
  74. self._hidden_layer_sizes)
  75. last_layer_dim = layers[-1].dim
  76. layers.append(
  77. dragnn.Layer(component, name='last_layer', dim=last_layer_dim))
  78. layers.append(
  79. dragnn.Layer(component, name='logits', dim=component.num_actions))
  80. # Provide initial layers and context layers, so the base class constructor
  81. # can safely use accessors like get_layer_size().
  82. super(BaseLSTMNetwork, self).__init__(
  83. component, init_layers=layers, init_context_layers=context_layers)
  84. # Allocate parameters for the softmax.
  85. self._params.append(
  86. tf.get_variable(
  87. 'weights_softmax', [last_layer_dim, component.num_actions],
  88. initializer=tf.random_normal_initializer(stddev=1e-4)))
  89. self._params.append(
  90. tf.get_variable(
  91. 'bias_softmax', [component.num_actions],
  92. initializer=tf.zeros_initializer()))
  93. def get_logits(self, network_tensors):
  94. """Returns the logits for prediction."""
  95. return network_tensors[self.get_layer_index('logits')]
  96. @abc.abstractmethod
  97. def create_hidden_layers(self, component, hidden_layer_sizes):
  98. """Creates hidden network layers.
  99. Args:
  100. component: Parent ComponentBuilderBase object.
  101. hidden_layer_sizes: List of requested hidden layer activation sizes.
  102. Returns:
  103. layers: List of layers created by this network.
  104. context_layers: List of context layers created by this network.
  105. """
  106. pass
  107. def _append_base_layers(self, hidden_layers):
  108. """Appends layers defined by the base class to the |hidden_layers|."""
  109. last_layer = hidden_layers[-1]
  110. logits = tf.nn.xw_plus_b(last_layer,
  111. self._component.get_variable('weights_softmax'),
  112. self._component.get_variable('bias_softmax'))
  113. return hidden_layers + [last_layer, logits]
  114. def _create_cell(self, num_units, during_training):
  115. """Creates a single LSTM cell, possibly with dropout.
  116. Requires that BaseLSTMNetwork.__init__() was called.
  117. Args:
  118. num_units: Number of hidden units in the cell.
  119. during_training: Whether to create a cell for training (vs inference).
  120. Returns:
  121. A RNNCell of the requested size, possibly with dropout.
  122. """
  123. # No dropout in inference mode.
  124. if not during_training:
  125. return tf.contrib.rnn.LayerNormBasicLSTMCell(
  126. num_units, layer_norm=self._attrs['layer_norm'], reuse=True)
  127. # Otherwise, apply dropout to inputs and recurrences.
  128. cell = tf.contrib.rnn.LayerNormBasicLSTMCell(
  129. num_units,
  130. dropout_keep_prob=self._recurrent_dropout_rate,
  131. layer_norm=self._attrs['layer_norm'])
  132. cell = tf.contrib.rnn.DropoutWrapper(
  133. cell, input_keep_prob=self._input_dropout_rate)
  134. return cell
  135. def _create_train_cells(self):
  136. """Creates a list of LSTM cells for training."""
  137. return [
  138. self._create_cell(num_units, during_training=True)
  139. for num_units in self._hidden_layer_sizes
  140. ]
  141. def _create_inference_cells(self):
  142. """Creates a list of LSTM cells for inference."""
  143. return [
  144. self._create_cell(num_units, during_training=False)
  145. for num_units in self._hidden_layer_sizes
  146. ]
  147. def _capture_variables_as_params(self, function):
  148. """Captures variables created by a function in |self._params|.
  149. Args:
  150. function: Function whose variables should be captured. The function
  151. should take one argument, its enclosing variable scope.
  152. """
  153. created_vars = {}
  154. def _custom_getter(getter, *args, **kwargs):
  155. """Calls the real getter and captures its result in |created_vars|."""
  156. real_variable = getter(*args, **kwargs)
  157. created_vars[real_variable.name] = real_variable
  158. return real_variable
  159. with tf.variable_scope(
  160. 'cell', reuse=None, custom_getter=_custom_getter) as scope:
  161. function(scope)
  162. self._params.extend(created_vars.values())
  163. def _apply_with_captured_variables(self, function):
  164. """Applies a function using previously-captured variables.
  165. Args:
  166. function: Function to apply using captured variables. The function
  167. should take one argument, its enclosing variable scope.
  168. Returns:
  169. Results of function application.
  170. """
  171. def _custom_getter(getter, *args, **kwargs):
  172. """Retrieves the normal or moving-average variables."""
  173. return self._component.get_variable(var_params=getter(*args, **kwargs))
  174. with tf.variable_scope(
  175. 'cell', reuse=True, custom_getter=_custom_getter) as scope:
  176. return function(scope)
  177. class LayerNormBasicLSTMNetwork(BaseLSTMNetwork):
  178. """Wrapper around tf.contrib.rnn.LayerNormBasicLSTMCell.
  179. Features:
  180. All inputs are concatenated.
  181. Subclass-specific layers:
  182. state_c_<n>: Cell states for the <n>'th LSTM layer (0-origin).
  183. state_h_<n>: Hidden states for the <n>'th LSTM layer (0-origin).
  184. """
  185. def __init__(self, component):
  186. """Sets up context and output layers, as well as a final softmax."""
  187. super(LayerNormBasicLSTMNetwork, self).__init__(component)
  188. # Wrap lists of training and inference sub-cells into multi-layer RNN cells.
  189. # Note that a |MultiRNNCell| state is a tuple of per-layer sub-states.
  190. self._train_cell = tf.contrib.rnn.MultiRNNCell(self._create_train_cells())
  191. self._inference_cell = tf.contrib.rnn.MultiRNNCell(
  192. self._create_inference_cells())
  193. def _cell_closure(scope):
  194. """Applies the LSTM cell to placeholder inputs and state."""
  195. placeholder_inputs = tf.placeholder(
  196. dtype=tf.float32, shape=(1, self._concatenated_input_dim))
  197. placeholder_substates = []
  198. for num_units in self._hidden_layer_sizes:
  199. placeholder_substate = tf.contrib.rnn.LSTMStateTuple(
  200. tf.placeholder(dtype=tf.float32, shape=(1, num_units)),
  201. tf.placeholder(dtype=tf.float32, shape=(1, num_units)))
  202. placeholder_substates.append(placeholder_substate)
  203. placeholder_state = tuple(placeholder_substates)
  204. self._train_cell(
  205. inputs=placeholder_inputs, state=placeholder_state, scope=scope)
  206. self._capture_variables_as_params(_cell_closure)
  207. def create_hidden_layers(self, component, hidden_layer_sizes):
  208. """See base class."""
  209. # Construct the layer meta info for the DRAGNN builder. Note that the order
  210. # of h and c are reversed compared to the vanilla DRAGNN LSTM cell, as
  211. # this is the standard in tf.contrib.rnn.
  212. #
  213. # NB: The h activations of the last LSTM must be the last layer, in order
  214. # for _append_base_layers() to work.
  215. layers = []
  216. for index, num_units in enumerate(hidden_layer_sizes):
  217. layers.append(
  218. dragnn.Layer(component, name='state_c_%d' % index, dim=num_units))
  219. layers.append(
  220. dragnn.Layer(component, name='state_h_%d' % index, dim=num_units))
  221. context_layers = list(layers) # copy |layers|, don't alias it
  222. return layers, context_layers
  223. def create(self,
  224. fixed_embeddings,
  225. linked_embeddings,
  226. context_tensor_arrays,
  227. attention_tensor,
  228. during_training,
  229. stride=None):
  230. """See base class."""
  231. # NB: This cell pulls the lstm's h and c vectors from context_tensor_arrays
  232. # instead of through linked features.
  233. check.Eq(
  234. len(context_tensor_arrays), 2 * len(self._hidden_layer_sizes),
  235. 'require two context tensors per hidden layer')
  236. # Rearrange the context tensors into a tuple of LSTM sub-states.
  237. length = context_tensor_arrays[0].size()
  238. substates = []
  239. for index, num_units in enumerate(self._hidden_layer_sizes):
  240. state_c = context_tensor_arrays[2 * index].read(length - 1)
  241. state_h = context_tensor_arrays[2 * index + 1].read(length - 1)
  242. # Fix shapes that for some reason are not set properly for an unknown
  243. # reason. TODO(googleuser): Why are the shapes not set?
  244. state_c.set_shape([tf.Dimension(None), num_units])
  245. state_h.set_shape([tf.Dimension(None), num_units])
  246. substates.append(tf.contrib.rnn.LSTMStateTuple(state_c, state_h))
  247. state = tuple(substates)
  248. input_tensor = dragnn.get_input_tensor(fixed_embeddings, linked_embeddings)
  249. cell = self._train_cell if during_training else self._inference_cell
  250. def _cell_closure(scope):
  251. """Applies the LSTM cell to the current inputs and state."""
  252. return cell(input_tensor, state, scope)
  253. unused_h, state = self._apply_with_captured_variables(_cell_closure)
  254. # Return tensors to be put into the tensor arrays / used to compute
  255. # objective.
  256. output_tensors = []
  257. for new_substate in state:
  258. new_c, new_h = new_substate
  259. output_tensors.append(new_c)
  260. output_tensors.append(new_h)
  261. return self._append_base_layers(output_tensors)
  262. class BulkBiLSTMNetwork(BaseLSTMNetwork):
  263. """Bulk wrapper around tf.contrib.rnn.stack_bidirectional_dynamic_rnn().
  264. Features:
  265. lengths: [stride, 1] sequence lengths per batch item.
  266. All other features are concatenated into input activations.
  267. Subclass-specific layers:
  268. outputs: [stride * num_steps, self._output_dim] bi-LSTM activations.
  269. """
  270. def __init__(self, component):
  271. """Initializes the bulk bi-LSTM.
  272. Parameters used:
  273. parallel_iterations (1): Parallelism of the underlying tf.while_loop().
  274. Defaults to 1 thread to encourage deterministic behavior, but can be
  275. increased to trade memory for speed.
  276. Args:
  277. component: parent ComponentBuilderBase object.
  278. """
  279. super(BulkBiLSTMNetwork, self).__init__(
  280. component, additional_attr_defaults={'parallel_iterations': 1})
  281. check.In('lengths', self._linked_feature_dims,
  282. 'Missing required linked feature')
  283. check.Eq(self._linked_feature_dims['lengths'], 1,
  284. 'Wrong dimension for "lengths" feature')
  285. self._input_dim = self._concatenated_input_dim - 1 # exclude 'lengths'
  286. self._output_dim = self.get_layer_size('outputs')
  287. tf.logging.info('[%s] Bulk bi-LSTM with input_dim=%d output_dim=%d',
  288. component.name, self._input_dim, self._output_dim)
  289. # Create one training and inference cell per layer and direction.
  290. self._train_cells_forward = self._create_train_cells()
  291. self._train_cells_backward = self._create_train_cells()
  292. self._inference_cells_forward = self._create_inference_cells()
  293. self._inference_cells_backward = self._create_inference_cells()
  294. def _bilstm_closure(scope):
  295. """Applies the bi-LSTM to placeholder inputs and lengths."""
  296. # Use singleton |stride| and |steps| because their values don't affect the
  297. # weight variables.
  298. stride, steps = 1, 1
  299. placeholder_inputs = tf.placeholder(
  300. dtype=tf.float32, shape=[stride, steps, self._input_dim])
  301. placeholder_lengths = tf.placeholder(dtype=tf.int64, shape=[stride])
  302. # Omit the initial states and sequence lengths for simplicity; they don't
  303. # affect the weight variables.
  304. tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
  305. self._train_cells_forward,
  306. self._train_cells_backward,
  307. placeholder_inputs,
  308. dtype=tf.float32,
  309. sequence_length=placeholder_lengths,
  310. scope=scope)
  311. self._capture_variables_as_params(_bilstm_closure)
  312. # Allocate parameters for the initial states. Note that an LSTM state is a
  313. # tuple of two substates (c, h), so there are 4 variables per layer.
  314. for index, num_units in enumerate(self._hidden_layer_sizes):
  315. for direction in ['forward', 'backward']:
  316. for substate in ['c', 'h']:
  317. self._params.append(
  318. tf.get_variable(
  319. 'initial_state_%s_%s_%d' % (direction, substate, index),
  320. [1, num_units], # leading 1 for later batch-wise tiling
  321. dtype=tf.float32,
  322. initializer=tf.constant_initializer(0.0)))
  323. def create_hidden_layers(self, component, hidden_layer_sizes):
  324. """See base class."""
  325. dim = 2 * hidden_layer_sizes[-1]
  326. return [dragnn.Layer(component, name='outputs', dim=dim)], []
  327. def create(self,
  328. fixed_embeddings,
  329. linked_embeddings,
  330. context_tensor_arrays,
  331. attention_tensor,
  332. during_training,
  333. stride=None):
  334. """Requires |stride|; otherwise see base class."""
  335. check.NotNone(stride,
  336. 'BulkBiLSTMNetwork requires "stride" and must be called '
  337. 'in the bulk feature extractor component.')
  338. # Flatten the lengths into a vector.
  339. lengths = dragnn.lookup_named_tensor('lengths', linked_embeddings)
  340. lengths_s = tf.squeeze(lengths.tensor, [1])
  341. # Collect all other inputs into a batched tensor.
  342. linked_embeddings = [
  343. named_tensor for named_tensor in linked_embeddings
  344. if named_tensor.name != 'lengths'
  345. ]
  346. inputs_sxnxd = dragnn.get_input_tensor_with_stride(
  347. fixed_embeddings, linked_embeddings, stride)
  348. # Since get_input_tensor_with_stride() concatenates the input embeddings, it
  349. # obscures the static activation dimension, which the RNN library requires.
  350. # Restore it using set_shape(). Note that set_shape() merges into the known
  351. # shape, so only specify the activation dimension.
  352. inputs_sxnxd.set_shape(
  353. [tf.Dimension(None), tf.Dimension(None), self._input_dim])
  354. initial_states_forward, initial_states_backward = (
  355. self._create_initial_states(stride))
  356. if during_training:
  357. cells_forward = self._train_cells_forward
  358. cells_backward = self._train_cells_backward
  359. else:
  360. cells_forward = self._inference_cells_forward
  361. cells_backward = self._inference_cells_backward
  362. def _bilstm_closure(scope):
  363. """Applies the bi-LSTM to the current inputs."""
  364. outputs_sxnxd, _, _ = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
  365. cells_forward,
  366. cells_backward,
  367. inputs_sxnxd,
  368. initial_states_fw=initial_states_forward,
  369. initial_states_bw=initial_states_backward,
  370. sequence_length=lengths_s,
  371. parallel_iterations=self._attrs['parallel_iterations'],
  372. scope=scope)
  373. return outputs_sxnxd
  374. # Layer outputs are not batched; flatten out the batch dimension.
  375. outputs_sxnxd = self._apply_with_captured_variables(_bilstm_closure)
  376. outputs_snxd = tf.reshape(outputs_sxnxd, [-1, self._output_dim])
  377. return self._append_base_layers([outputs_snxd])
  378. def _create_initial_states(self, stride):
  379. """Returns stacked and batched initial states for the bi-LSTM."""
  380. initial_states_forward = []
  381. initial_states_backward = []
  382. for index in range(len(self._hidden_layer_sizes)):
  383. # Retrieve the initial states for this layer.
  384. states_sxd = []
  385. for direction in ['forward', 'backward']:
  386. for substate in ['c', 'h']:
  387. state_1xd = self._component.get_variable('initial_state_%s_%s_%d' %
  388. (direction, substate, index))
  389. state_sxd = tf.tile(state_1xd, [stride, 1]) # tile across the batch
  390. states_sxd.append(state_sxd)
  391. # Assemble and append forward and backward LSTM states.
  392. initial_states_forward.append(
  393. tf.contrib.rnn.LSTMStateTuple(states_sxd[0], states_sxd[1]))
  394. initial_states_backward.append(
  395. tf.contrib.rnn.LSTMStateTuple(states_sxd[2], states_sxd[3]))
  396. return initial_states_forward, initial_states_backward