modeling.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """The main BERT model and related functions."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import collections
  20. import copy
  21. import json
  22. import math
  23. import re
  24. import numpy as np
  25. import six
  26. import tensorflow as tf
  27. from gpu_environment import get_custom_getter
  28. class BertConfig(object):
  29. """Configuration for `BertModel`."""
  30. def __init__(self,
  31. vocab_size,
  32. hidden_size=768,
  33. num_hidden_layers=12,
  34. num_attention_heads=12,
  35. intermediate_size=3072,
  36. hidden_act="gelu",
  37. hidden_dropout_prob=0.1,
  38. attention_probs_dropout_prob=0.1,
  39. max_position_embeddings=512,
  40. type_vocab_size=16,
  41. initializer_range=0.02):
  42. """Constructs BertConfig.
  43. Args:
  44. vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
  45. hidden_size: Size of the encoder layers and the pooler layer.
  46. num_hidden_layers: Number of hidden layers in the Transformer encoder.
  47. num_attention_heads: Number of attention heads for each attention layer in
  48. the Transformer encoder.
  49. intermediate_size: The size of the "intermediate" (i.e., feed-forward)
  50. layer in the Transformer encoder.
  51. hidden_act: The non-linear activation function (function or string) in the
  52. encoder and pooler.
  53. hidden_dropout_prob: The dropout probability for all fully connected
  54. layers in the embeddings, encoder, and pooler.
  55. attention_probs_dropout_prob: The dropout ratio for the attention
  56. probabilities.
  57. max_position_embeddings: The maximum sequence length that this model might
  58. ever be used with. Typically set this to something large just in case
  59. (e.g., 512 or 1024 or 2048).
  60. type_vocab_size: The vocabulary size of the `token_type_ids` passed into
  61. `BertModel`.
  62. initializer_range: The stdev of the truncated_normal_initializer for
  63. initializing all weight matrices.
  64. """
  65. self.vocab_size = vocab_size
  66. self.hidden_size = hidden_size
  67. self.num_hidden_layers = num_hidden_layers
  68. self.num_attention_heads = num_attention_heads
  69. self.hidden_act = hidden_act
  70. self.intermediate_size = intermediate_size
  71. self.hidden_dropout_prob = hidden_dropout_prob
  72. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  73. self.max_position_embeddings = max_position_embeddings
  74. self.type_vocab_size = type_vocab_size
  75. self.initializer_range = initializer_range
  76. @classmethod
  77. def from_dict(cls, json_object):
  78. """Constructs a `BertConfig` from a Python dictionary of parameters."""
  79. config = BertConfig(vocab_size=None)
  80. for (key, value) in six.iteritems(json_object):
  81. config.__dict__[key] = value
  82. return config
  83. @classmethod
  84. def from_json_file(cls, json_file):
  85. """Constructs a `BertConfig` from a json file of parameters."""
  86. with tf.io.gfile.GFile(json_file, "r") as reader:
  87. text = reader.read()
  88. return cls.from_dict(json.loads(text))
  89. def to_dict(self):
  90. """Serializes this instance to a Python dictionary."""
  91. output = copy.deepcopy(self.__dict__)
  92. return output
  93. def to_json_string(self):
  94. """Serializes this instance to a JSON string."""
  95. return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
  96. class BertModel(object):
  97. """BERT model ("Bidirectional Encoder Representations from Transformers").
  98. Example usage:
  99. ```python
  100. # Already been converted into WordPiece token ids
  101. input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
  102. input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
  103. token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])
  104. config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
  105. num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
  106. model = modeling.BertModel(config=config, is_training=True,
  107. input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
  108. label_embeddings = tf.get_variable(...)
  109. pooled_output = model.get_pooled_output()
  110. logits = tf.matmul(pooled_output, label_embeddings)
  111. ...
  112. ```
  113. """
  114. def __init__(self,
  115. config,
  116. is_training,
  117. input_ids,
  118. input_mask=None,
  119. token_type_ids=None,
  120. use_one_hot_embeddings=False,
  121. scope=None,
  122. compute_type=tf.float32):
  123. """Constructor for BertModel.
  124. Args:
  125. config: `BertConfig` instance.
  126. is_training: bool. true for training model, false for eval model. Controls
  127. whether dropout will be applied.
  128. input_ids: int32 Tensor of shape [batch_size, seq_length].
  129. input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].
  130. token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
  131. use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
  132. embeddings or tf.embedding_lookup() for the word embeddings. On the TPU,
  133. it is much faster if this is True, on the CPU or GPU, it is faster if
  134. this is False.
  135. scope: (optional) variable scope. Defaults to "bert".
  136. compute_type: (optional) either float32 or float16. Only applies to GPUs.
  137. Raises:
  138. ValueError: The config is invalid or one of the input tensor shapes
  139. is invalid.
  140. """
  141. config = copy.deepcopy(config)
  142. if not is_training:
  143. config.hidden_dropout_prob = 0.0
  144. config.attention_probs_dropout_prob = 0.0
  145. input_shape = get_shape_list(input_ids, expected_rank=2)
  146. batch_size = input_shape[0]
  147. seq_length = input_shape[1]
  148. if input_mask is None:
  149. input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)
  150. if token_type_ids is None:
  151. token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)
  152. with tf.variable_scope(scope, default_name="bert", custom_getter=get_custom_getter(compute_type)):
  153. with tf.variable_scope("embeddings"):
  154. # For good convergence with mixed precision training,
  155. # it is important that the embedding codes remain fp32.
  156. # Perform embedding lookup on the word ids.
  157. (self.embedding_output, self.embedding_table) = embedding_lookup(
  158. input_ids=input_ids,
  159. vocab_size=config.vocab_size,
  160. embedding_size=config.hidden_size,
  161. initializer_range=config.initializer_range,
  162. word_embedding_name="word_embeddings",
  163. use_one_hot_embeddings=use_one_hot_embeddings)
  164. # Add positional embeddings and token type embeddings, then layer
  165. # normalize and perform dropout.
  166. self.embedding_output = embedding_postprocessor(
  167. input_tensor=self.embedding_output,
  168. use_token_type=True,
  169. token_type_ids=token_type_ids,
  170. token_type_vocab_size=config.type_vocab_size,
  171. token_type_embedding_name="token_type_embeddings",
  172. use_position_embeddings=True,
  173. position_embedding_name="position_embeddings",
  174. initializer_range=config.initializer_range,
  175. max_position_embeddings=config.max_position_embeddings,
  176. dropout_prob=config.hidden_dropout_prob,
  177. use_one_hot_embeddings=use_one_hot_embeddings)
  178. with tf.variable_scope("encoder"):
  179. # This converts a 2D mask of shape [batch_size, seq_length] to a 3D
  180. # mask of shape [batch_size, seq_length, seq_length] which is used
  181. # for the attention scores.
  182. attention_mask = create_attention_mask_from_input_mask(
  183. input_ids, input_mask)
  184. # Run the stacked transformer.
  185. # `sequence_output` shape = [batch_size, seq_length, hidden_size].
  186. self.all_encoder_layers = transformer_model(
  187. input_tensor=tf.saturate_cast(self.embedding_output, compute_type),
  188. attention_mask=attention_mask,
  189. hidden_size=config.hidden_size,
  190. num_hidden_layers=config.num_hidden_layers,
  191. num_attention_heads=config.num_attention_heads,
  192. intermediate_size=config.intermediate_size,
  193. intermediate_act_fn=get_activation(config.hidden_act),
  194. hidden_dropout_prob=config.hidden_dropout_prob,
  195. attention_probs_dropout_prob=config.attention_probs_dropout_prob,
  196. initializer_range=config.initializer_range,
  197. do_return_all_layers=True)
  198. self.sequence_output = tf.cast(self.all_encoder_layers[-1], tf.float32)
  199. # The "pooler" converts the encoded sequence tensor of shape
  200. # [batch_size, seq_length, hidden_size] to a tensor of shape
  201. # [batch_size, hidden_size]. This is necessary for segment-level
  202. # (or segment-pair-level) classification tasks where we need a fixed
  203. # dimensional representation of the segment.
  204. with tf.variable_scope("pooler"):
  205. # We "pool" the model by simply taking the hidden state corresponding
  206. # to the first token. We assume that this has been pre-trained
  207. first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
  208. self.pooled_output = tf.layers.dense(
  209. first_token_tensor,
  210. config.hidden_size,
  211. activation=tf.tanh,
  212. kernel_initializer=create_initializer(config.initializer_range))
  213. def get_pooled_output(self):
  214. return self.pooled_output
  215. def get_sequence_output(self):
  216. """Gets final hidden layer of encoder.
  217. Returns:
  218. float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
  219. to the final hidden of the transformer encoder.
  220. """
  221. return self.sequence_output
  222. def get_all_encoder_layers(self):
  223. return self.all_encoder_layers
  224. def get_embedding_output(self):
  225. """Gets output of the embedding lookup (i.e., input to the transformer).
  226. Returns:
  227. float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
  228. to the output of the embedding layer, after summing the word
  229. embeddings with the positional embeddings and the token type embeddings,
  230. then performing layer normalization. This is the input to the transformer.
  231. """
  232. return self.embedding_output
  233. def get_embedding_table(self):
  234. return self.embedding_table
  235. def gelu(x):
  236. """Gaussian Error Linear Unit.
  237. This is a smoother version of the RELU.
  238. Original paper: https://arxiv.org/abs/1606.08415
  239. Args:
  240. x: float Tensor to perform activation.
  241. Returns:
  242. `x` with the GELU activation applied.
  243. """
  244. cdf = 0.5 * (1.0 + tf.tanh(
  245. (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
  246. return x * cdf
  247. def get_activation(activation_string):
  248. """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
  249. Args:
  250. activation_string: String name of the activation function.
  251. Returns:
  252. A Python function corresponding to the activation function. If
  253. `activation_string` is None, empty, or "linear", this will return None.
  254. If `activation_string` is not a string, it will return `activation_string`.
  255. Raises:
  256. ValueError: The `activation_string` does not correspond to a known
  257. activation.
  258. """
  259. # We assume that anything that"s not a string is already an activation
  260. # function, so we just return it.
  261. if not isinstance(activation_string, six.string_types):
  262. return activation_string
  263. if not activation_string:
  264. return None
  265. act = activation_string.lower()
  266. if act == "linear":
  267. return None
  268. elif act == "relu":
  269. return tf.nn.relu
  270. elif act == "gelu":
  271. return gelu
  272. elif act == "tanh":
  273. return tf.tanh
  274. else:
  275. raise ValueError("Unsupported activation: %s" % act)
  276. def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
  277. """Compute the union of the current variables and checkpoint variables."""
  278. assignment_map = {}
  279. initialized_variable_names = {}
  280. name_to_variable = collections.OrderedDict()
  281. for var in tvars:
  282. name = var.name
  283. m = re.match("^(.*):\\d+$", name)
  284. if m is not None:
  285. name = m.group(1)
  286. name_to_variable[name] = var
  287. init_vars = tf.train.list_variables(init_checkpoint)
  288. assignment_map = collections.OrderedDict()
  289. for x in init_vars:
  290. (name, var) = (x[0], x[1])
  291. if name not in name_to_variable:
  292. continue
  293. assignment_map[name] = name
  294. initialized_variable_names[name] = 1
  295. initialized_variable_names[name + ":0"] = 1
  296. return (assignment_map, initialized_variable_names)
  297. def dropout(input_tensor, dropout_prob):
  298. """Perform dropout.
  299. Args:
  300. input_tensor: float Tensor.
  301. dropout_prob: Python float. The probability of dropping out a value (NOT of
  302. *keeping* a dimension as in `tf.nn.dropout`).
  303. Returns:
  304. A version of `input_tensor` with dropout applied.
  305. """
  306. if dropout_prob is None or dropout_prob == 0.0:
  307. return input_tensor
  308. output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
  309. return output
  310. def layer_norm(input_tensor, name=None):
  311. """Run layer normalization on the last dimension of the tensor."""
  312. if input_tensor.dtype == tf.float16:
  313. try:
  314. from fused_layer_norm import fused_layer_norm
  315. return fused_layer_norm(
  316. inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name,
  317. use_fused_batch_norm=True)
  318. except ImportError:
  319. return tf.contrib.layers.layer_norm(
  320. inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
  321. else:
  322. return tf.contrib.layers.layer_norm(
  323. inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
  324. def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
  325. """Runs layer normalization followed by dropout."""
  326. output_tensor = layer_norm(input_tensor, name)
  327. output_tensor = dropout(output_tensor, dropout_prob)
  328. return output_tensor
  329. def create_initializer(initializer_range=0.02):
  330. """Creates a `truncated_normal_initializer` with the given range."""
  331. return tf.truncated_normal_initializer(stddev=initializer_range)
  332. def embedding_lookup(input_ids,
  333. vocab_size,
  334. embedding_size=128,
  335. initializer_range=0.02,
  336. word_embedding_name="word_embeddings",
  337. use_one_hot_embeddings=False):
  338. """Looks up words embeddings for id tensor.
  339. Args:
  340. input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
  341. ids.
  342. vocab_size: int. Size of the embedding vocabulary.
  343. embedding_size: int. Width of the word embeddings.
  344. initializer_range: float. Embedding initialization range.
  345. word_embedding_name: string. Name of the embedding table.
  346. use_one_hot_embeddings: bool. If True, use one-hot method for word
  347. embeddings. If False, use `tf.gather()`.
  348. Returns:
  349. float Tensor of shape [batch_size, seq_length, embedding_size].
  350. """
  351. # This function assumes that the input is of shape [batch_size, seq_length,
  352. # num_inputs].
  353. #
  354. # If the input is a 2D tensor of shape [batch_size, seq_length], we
  355. # reshape to [batch_size, seq_length, 1].
  356. if input_ids.shape.ndims == 2:
  357. input_ids = tf.expand_dims(input_ids, axis=[-1])
  358. embedding_table = tf.get_variable(
  359. name=word_embedding_name,
  360. shape=[vocab_size, embedding_size],
  361. initializer=create_initializer(initializer_range))
  362. flat_input_ids = tf.reshape(input_ids, [-1])
  363. if use_one_hot_embeddings:
  364. one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
  365. output = tf.matmul(one_hot_input_ids, embedding_table)
  366. else:
  367. output = tf.gather(embedding_table, flat_input_ids)
  368. input_shape = get_shape_list(input_ids)
  369. output = tf.reshape(output,
  370. input_shape[0:-1] + [input_shape[-1] * embedding_size])
  371. return (output, embedding_table)
  372. def embedding_postprocessor(input_tensor,
  373. use_token_type=False,
  374. token_type_ids=None,
  375. token_type_vocab_size=16,
  376. token_type_embedding_name="token_type_embeddings",
  377. use_position_embeddings=True,
  378. position_embedding_name="position_embeddings",
  379. initializer_range=0.02,
  380. max_position_embeddings=512,
  381. dropout_prob=0.1,
  382. use_one_hot_embeddings=False):
  383. """Performs various post-processing on a word embedding tensor.
  384. Args:
  385. input_tensor: float Tensor of shape [batch_size, seq_length,
  386. embedding_size].
  387. use_token_type: bool. Whether to add embeddings for `token_type_ids`.
  388. token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
  389. Must be specified if `use_token_type` is True.
  390. token_type_vocab_size: int. The vocabulary size of `token_type_ids`.
  391. token_type_embedding_name: string. The name of the embedding table variable
  392. for token type ids.
  393. use_position_embeddings: bool. Whether to add position embeddings for the
  394. position of each token in the sequence.
  395. position_embedding_name: string. The name of the embedding table variable
  396. for positional embeddings.
  397. initializer_range: float. Range of the weight initialization.
  398. max_position_embeddings: int. Maximum sequence length that might ever be
  399. used with this model. This can be longer than the sequence length of
  400. input_tensor, but cannot be shorter.
  401. dropout_prob: float. Dropout probability applied to the final output tensor.
  402. use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
  403. embeddings or tf.embedding_lookup() for the word embeddings.
  404. Returns:
  405. float tensor with same shape as `input_tensor`.
  406. Raises:
  407. ValueError: One of the tensor shapes or input values is invalid.
  408. """
  409. input_shape = get_shape_list(input_tensor, expected_rank=3)
  410. batch_size = input_shape[0]
  411. seq_length = input_shape[1]
  412. width = input_shape[2]
  413. output = input_tensor
  414. if use_token_type:
  415. if token_type_ids is None:
  416. raise ValueError("`token_type_ids` must be specified if"
  417. "`use_token_type` is True.")
  418. token_type_table = tf.get_variable(
  419. name=token_type_embedding_name,
  420. shape=[token_type_vocab_size, width],
  421. initializer=create_initializer(initializer_range))
  422. flat_token_type_ids = tf.reshape(token_type_ids, [-1])
  423. if use_one_hot_embeddings:
  424. # This vocab will be small so we always do one-hot here, since it is
  425. # always faster for a small vocabulary.
  426. one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
  427. token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
  428. else:
  429. token_type_embeddings = tf.gather(token_type_table, flat_token_type_ids)
  430. token_type_embeddings = tf.reshape(token_type_embeddings,
  431. [batch_size, seq_length, width])
  432. output += token_type_embeddings
  433. if use_position_embeddings:
  434. full_position_embeddings = tf.get_variable(
  435. name=position_embedding_name,
  436. shape=[max_position_embeddings, width],
  437. initializer=create_initializer(initializer_range))
  438. # Since the position embedding table is a learned variable, we create it
  439. # using a (long) sequence length `max_position_embeddings`. The actual
  440. # sequence length might be shorter than this, for faster training of
  441. # tasks that do not have long sequences.
  442. #
  443. # So `full_position_embeddings` is effectively an embedding table
  444. # for position [0, 1, 2, ..., max_position_embeddings-1], and the current
  445. # sequence has positions [0, 1, 2, ... seq_length-1], so we can just
  446. # perform a slice.
  447. position_embeddings = tf.slice(full_position_embeddings, [0, 0],
  448. [seq_length, width])
  449. num_dims = len(output.shape.as_list())
  450. # Only the last two dimensions are relevant (`seq_length` and `width`), so
  451. # we broadcast among the first dimensions, which is typically just
  452. # the batch size.
  453. position_broadcast_shape = []
  454. for _ in range(num_dims - 2):
  455. position_broadcast_shape.append(1)
  456. position_broadcast_shape.extend([seq_length, width])
  457. position_embeddings = tf.reshape(position_embeddings,
  458. position_broadcast_shape)
  459. output += position_embeddings
  460. output = layer_norm_and_dropout(output, dropout_prob)
  461. return output
  462. def create_attention_mask_from_input_mask(from_tensor, to_mask):
  463. """Create 3D attention mask from a 2D tensor mask.
  464. Args:
  465. from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
  466. to_mask: int32 Tensor of shape [batch_size, to_seq_length].
  467. Returns:
  468. float Tensor of shape [batch_size, from_seq_length, to_seq_length].
  469. """
  470. to_mask = tf.cast(to_mask, dtype=tf.float32)
  471. from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
  472. batch_size = from_shape[0]
  473. to_shape = get_shape_list(to_mask, expected_rank=2)
  474. to_seq_length = to_shape[1]
  475. to_mask = tf.reshape(to_mask, [batch_size, 1, to_seq_length])
  476. # The mask will be automatically broadcasted to
  477. # [batch_size, from_seq_length, to_seq_length] when it is used in the
  478. # attention layer.
  479. return to_mask
  480. def attention_layer(from_tensor,
  481. to_tensor,
  482. attention_mask=None,
  483. num_attention_heads=1,
  484. size_per_head=512,
  485. query_act=None,
  486. key_act=None,
  487. value_act=None,
  488. attention_probs_dropout_prob=0.0,
  489. initializer_range=0.02,
  490. do_return_2d_tensor=False,
  491. batch_size=None,
  492. from_seq_length=None,
  493. to_seq_length=None):
  494. """Performs multi-headed attention from `from_tensor` to `to_tensor`.
  495. This is an implementation of multi-headed attention based on "Attention
  496. is all you Need". If `from_tensor` and `to_tensor` are the same, then
  497. this is self-attention. Each timestep in `from_tensor` attends to the
  498. corresponding sequence in `to_tensor`, and returns a fixed-with vector.
  499. This function first projects `from_tensor` into a "query" tensor and
  500. `to_tensor` into "key" and "value" tensors. These are (effectively) a list
  501. of tensors of length `num_attention_heads`, where each tensor is of shape
  502. [batch_size, seq_length, size_per_head].
  503. Then, the query and key tensors are dot-producted and scaled. These are
  504. softmaxed to obtain attention probabilities. The value tensors are then
  505. interpolated by these probabilities, then concatenated back to a single
  506. tensor and returned.
  507. In practice, the multi-headed attention are done with transposes and
  508. reshapes rather than actual separate tensors.
  509. Args:
  510. from_tensor: float Tensor of shape [batch_size, from_seq_length,
  511. from_width].
  512. to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
  513. attention_mask: (optional) int32 Tensor of shape [batch_size,
  514. from_seq_length, to_seq_length]. The values should be 1 or 0. The
  515. attention scores will effectively be set to -infinity for any positions in
  516. the mask that are 0, and will be unchanged for positions that are 1.
  517. num_attention_heads: int. Number of attention heads.
  518. size_per_head: int. Size of each attention head.
  519. query_act: (optional) Activation function for the query transform.
  520. key_act: (optional) Activation function for the key transform.
  521. value_act: (optional) Activation function for the value transform.
  522. attention_probs_dropout_prob: (optional) float. Dropout probability of the
  523. attention probabilities.
  524. initializer_range: float. Range of the weight initializer.
  525. do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
  526. * from_seq_length, num_attention_heads * size_per_head]. If False, the
  527. output will be of shape [batch_size, from_seq_length, num_attention_heads
  528. * size_per_head].
  529. batch_size: (Optional) int. If the input is 2D, this might be the batch size
  530. of the 3D version of the `from_tensor` and `to_tensor`.
  531. from_seq_length: (Optional) If the input is 2D, this might be the seq length
  532. of the 3D version of the `from_tensor`.
  533. to_seq_length: (Optional) If the input is 2D, this might be the seq length
  534. of the 3D version of the `to_tensor`.
  535. Returns:
  536. float Tensor of shape [batch_size, from_seq_length,
  537. num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
  538. true, this will be of shape [batch_size * from_seq_length,
  539. num_attention_heads * size_per_head]).
  540. Raises:
  541. ValueError: Any of the arguments or tensor shapes are invalid.
  542. """
  543. def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
  544. seq_length, width):
  545. output_tensor = tf.reshape(
  546. input_tensor, [batch_size, seq_length, num_attention_heads, width])
  547. output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
  548. return output_tensor
  549. from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
  550. to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
  551. if len(from_shape) != len(to_shape):
  552. raise ValueError(
  553. "The rank of `from_tensor` must match the rank of `to_tensor`.")
  554. if len(from_shape) == 3:
  555. batch_size = from_shape[0]
  556. from_seq_length = from_shape[1]
  557. to_seq_length = to_shape[1]
  558. elif len(from_shape) == 2:
  559. if (batch_size is None or from_seq_length is None or to_seq_length is None):
  560. raise ValueError(
  561. "When passing in rank 2 tensors to attention_layer, the values "
  562. "for `batch_size`, `from_seq_length`, and `to_seq_length` "
  563. "must all be specified.")
  564. # Scalar dimensions referenced here:
  565. # B = batch size (number of sequences)
  566. # F = `from_tensor` sequence length
  567. # T = `to_tensor` sequence length
  568. # N = `num_attention_heads`
  569. # H = `size_per_head`
  570. from_tensor_2d = reshape_to_matrix(from_tensor)
  571. to_tensor_2d = reshape_to_matrix(to_tensor)
  572. # `query_layer` = [B*F, N*H]
  573. query_layer = tf.layers.dense(
  574. from_tensor_2d,
  575. num_attention_heads * size_per_head,
  576. activation=query_act,
  577. name="query",
  578. kernel_initializer=create_initializer(initializer_range))
  579. # `key_layer` = [B*T, N*H]
  580. key_layer = tf.layers.dense(
  581. to_tensor_2d,
  582. num_attention_heads * size_per_head,
  583. activation=key_act,
  584. name="key",
  585. kernel_initializer=create_initializer(initializer_range))
  586. # `value_layer` = [B*T, N*H]
  587. value_layer = tf.layers.dense(
  588. to_tensor_2d,
  589. num_attention_heads * size_per_head,
  590. activation=value_act,
  591. name="value",
  592. kernel_initializer=create_initializer(initializer_range))
  593. # `query_layer` = [B, N, F, H]
  594. query_layer = transpose_for_scores(query_layer, batch_size,
  595. num_attention_heads, from_seq_length,
  596. size_per_head)
  597. # `key_layer` = [B, N, T, H]
  598. key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
  599. to_seq_length, size_per_head)
  600. # Take the dot product between "query" and "key" to get the raw
  601. # attention scores.
  602. # `attention_scores` = [B, N, F, T]
  603. attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
  604. attention_scores = tf.multiply(attention_scores,
  605. 1.0 / math.sqrt(float(size_per_head)))
  606. if attention_mask is not None:
  607. # `attention_mask` = [B, 1, F, T]
  608. attention_mask = tf.expand_dims(attention_mask, axis=[1])
  609. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  610. # masked positions, this operation will create a tensor which is 0.0 for
  611. # positions we want to attend and -10000.0 for masked positions.
  612. adder = (1.0 - tf.cast(attention_mask, attention_scores.dtype)) * -10000.0
  613. # Since we are adding it to the raw scores before the softmax, this is
  614. # effectively the same as removing these entirely.
  615. attention_scores += adder
  616. # Normalize the attention scores to probabilities.
  617. # `attention_probs` = [B, N, F, T]
  618. attention_probs = tf.nn.softmax(attention_scores)
  619. # This is actually dropping out entire tokens to attend to, which might
  620. # seem a bit unusual, but is taken from the original Transformer paper.
  621. attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
  622. # `value_layer` = [B, T, N, H]
  623. value_layer = tf.reshape(
  624. value_layer,
  625. [batch_size, to_seq_length, num_attention_heads, size_per_head])
  626. # `value_layer` = [B, N, T, H]
  627. value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
  628. # `context_layer` = [B, N, F, H]
  629. context_layer = tf.matmul(attention_probs, value_layer)
  630. # `context_layer` = [B, F, N, H]
  631. context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
  632. if do_return_2d_tensor:
  633. # `context_layer` = [B*F, N*H]
  634. context_layer = tf.reshape(
  635. context_layer,
  636. [batch_size * from_seq_length, num_attention_heads * size_per_head])
  637. else:
  638. # `context_layer` = [B, F, N*H]
  639. context_layer = tf.reshape(
  640. context_layer,
  641. [batch_size, from_seq_length, num_attention_heads * size_per_head])
  642. return context_layer
  643. def transformer_model(input_tensor,
  644. attention_mask=None,
  645. hidden_size=768,
  646. num_hidden_layers=12,
  647. num_attention_heads=12,
  648. intermediate_size=3072,
  649. intermediate_act_fn=gelu,
  650. hidden_dropout_prob=0.1,
  651. attention_probs_dropout_prob=0.1,
  652. initializer_range=0.02,
  653. do_return_all_layers=False):
  654. """Multi-headed, multi-layer Transformer from "Attention is All You Need".
  655. This is almost an exact implementation of the original Transformer encoder.
  656. See the original paper:
  657. https://arxiv.org/abs/1706.03762
  658. Also see:
  659. https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
  660. Args:
  661. input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
  662. attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
  663. seq_length], with 1 for positions that can be attended to and 0 in
  664. positions that should not be.
  665. hidden_size: int. Hidden size of the Transformer.
  666. num_hidden_layers: int. Number of layers (blocks) in the Transformer.
  667. num_attention_heads: int. Number of attention heads in the Transformer.
  668. intermediate_size: int. The size of the "intermediate" (a.k.a., feed
  669. forward) layer.
  670. intermediate_act_fn: function. The non-linear activation function to apply
  671. to the output of the intermediate/feed-forward layer.
  672. hidden_dropout_prob: float. Dropout probability for the hidden layers.
  673. attention_probs_dropout_prob: float. Dropout probability of the attention
  674. probabilities.
  675. initializer_range: float. Range of the initializer (stddev of truncated
  676. normal).
  677. do_return_all_layers: Whether to also return all layers or just the final
  678. layer.
  679. Returns:
  680. float Tensor of shape [batch_size, seq_length, hidden_size], the final
  681. hidden layer of the Transformer.
  682. Raises:
  683. ValueError: A Tensor shape or parameter is invalid.
  684. """
  685. if hidden_size % num_attention_heads != 0:
  686. raise ValueError(
  687. "The hidden size (%d) is not a multiple of the number of attention "
  688. "heads (%d)" % (hidden_size, num_attention_heads))
  689. attention_head_size = int(hidden_size / num_attention_heads)
  690. input_shape = get_shape_list(input_tensor, expected_rank=3)
  691. batch_size = input_shape[0]
  692. seq_length = input_shape[1]
  693. input_width = input_shape[2]
  694. # The Transformer performs sum residuals on all layers so the input needs
  695. # to be the same as the hidden size.
  696. if input_width != hidden_size:
  697. raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
  698. (input_width, hidden_size))
  699. # We keep the representation as a 2D tensor to avoid re-shaping it back and
  700. # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
  701. # the GPU/CPU but may not be free on the TPU, so we want to minimize them to
  702. # help the optimizer.
  703. prev_output = reshape_to_matrix(input_tensor)
  704. all_layer_outputs = []
  705. for layer_idx in range(num_hidden_layers):
  706. with tf.variable_scope("layer_%d" % layer_idx):
  707. layer_input = prev_output
  708. with tf.variable_scope("attention"):
  709. attention_heads = []
  710. with tf.variable_scope("self"):
  711. attention_head = attention_layer(
  712. from_tensor=layer_input,
  713. to_tensor=layer_input,
  714. attention_mask=attention_mask,
  715. num_attention_heads=num_attention_heads,
  716. size_per_head=attention_head_size,
  717. attention_probs_dropout_prob=attention_probs_dropout_prob,
  718. initializer_range=initializer_range,
  719. do_return_2d_tensor=True,
  720. batch_size=batch_size,
  721. from_seq_length=seq_length,
  722. to_seq_length=seq_length)
  723. attention_heads.append(attention_head)
  724. attention_output = None
  725. if len(attention_heads) == 1:
  726. attention_output = attention_heads[0]
  727. else:
  728. # In the case where we have other sequences, we just concatenate
  729. # them to the self-attention head before the projection.
  730. attention_output = tf.concat(attention_heads, axis=-1)
  731. # Run a linear projection of `hidden_size` then add a residual
  732. # with `layer_input`.
  733. with tf.variable_scope("output"):
  734. attention_output = tf.layers.dense(
  735. attention_output,
  736. hidden_size,
  737. kernel_initializer=create_initializer(initializer_range))
  738. attention_output = dropout(attention_output, hidden_dropout_prob)
  739. attention_output = layer_norm(attention_output + layer_input)
  740. # The activation is only applied to the "intermediate" hidden layer.
  741. with tf.variable_scope("intermediate"):
  742. intermediate_output = tf.layers.dense(
  743. attention_output,
  744. intermediate_size,
  745. activation=intermediate_act_fn,
  746. kernel_initializer=create_initializer(initializer_range))
  747. # Down-project back to `hidden_size` then add the residual.
  748. with tf.variable_scope("output"):
  749. layer_output = tf.layers.dense(
  750. intermediate_output,
  751. hidden_size,
  752. kernel_initializer=create_initializer(initializer_range))
  753. layer_output = dropout(layer_output, hidden_dropout_prob)
  754. layer_output = layer_norm(layer_output + attention_output)
  755. prev_output = layer_output
  756. all_layer_outputs.append(layer_output)
  757. if do_return_all_layers:
  758. final_outputs = []
  759. for layer_output in all_layer_outputs:
  760. final_output = reshape_from_matrix(layer_output, input_shape)
  761. final_outputs.append(final_output)
  762. return final_outputs
  763. else:
  764. final_output = reshape_from_matrix(prev_output, input_shape)
  765. return final_output
  766. def get_shape_list(tensor, expected_rank=None, name=None):
  767. """Returns a list of the shape of tensor, preferring static dimensions.
  768. Args:
  769. tensor: A tf.Tensor object to find the shape of.
  770. expected_rank: (optional) int. The expected rank of `tensor`. If this is
  771. specified and the `tensor` has a different rank, and exception will be
  772. thrown.
  773. name: Optional name of the tensor for the error message.
  774. Returns:
  775. A list of dimensions of the shape of tensor. All static dimensions will
  776. be returned as python integers, and dynamic dimensions will be returned
  777. as tf.Tensor scalars.
  778. """
  779. if name is None:
  780. name = tensor.name
  781. if expected_rank is not None:
  782. assert_rank(tensor, expected_rank, name)
  783. shape = tensor.shape.as_list()
  784. non_static_indexes = []
  785. for (index, dim) in enumerate(shape):
  786. if dim is None:
  787. non_static_indexes.append(index)
  788. if not non_static_indexes:
  789. return shape
  790. dyn_shape = tf.shape(tensor)
  791. for index in non_static_indexes:
  792. shape[index] = dyn_shape[index]
  793. return shape
  794. def reshape_to_matrix(input_tensor):
  795. """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
  796. ndims = input_tensor.shape.ndims
  797. if ndims < 2:
  798. raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
  799. (input_tensor.shape))
  800. if ndims == 2:
  801. return input_tensor
  802. width = input_tensor.shape[-1]
  803. output_tensor = tf.reshape(input_tensor, [-1, width])
  804. return output_tensor
  805. def reshape_from_matrix(output_tensor, orig_shape_list):
  806. """Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
  807. if len(orig_shape_list) == 2:
  808. return output_tensor
  809. output_shape = get_shape_list(output_tensor)
  810. orig_dims = orig_shape_list[0:-1]
  811. width = output_shape[-1]
  812. return tf.reshape(output_tensor, orig_dims + [width])
  813. def assert_rank(tensor, expected_rank, name=None):
  814. """Raises an exception if the tensor rank is not of the expected rank.
  815. Args:
  816. tensor: A tf.Tensor to check the rank of.
  817. expected_rank: Python integer or list of integers, expected rank.
  818. name: Optional name of the tensor for the error message.
  819. Raises:
  820. ValueError: If the expected shape doesn't match the actual shape.
  821. """
  822. if name is None:
  823. name = tensor.name
  824. expected_rank_dict = {}
  825. if isinstance(expected_rank, six.integer_types):
  826. expected_rank_dict[expected_rank] = True
  827. else:
  828. for x in expected_rank:
  829. expected_rank_dict[x] = True
  830. actual_rank = tensor.shape.ndims
  831. if actual_rank not in expected_rank_dict:
  832. scope_name = tf.get_variable_scope().name
  833. raise ValueError(
  834. "For the tensor `%s` in scope `%s`, the actual rank "
  835. "`%d` (shape = %s) is not equal to the expected rank `%s`" %
  836. (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))