BertModel.py 38 KB

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