Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

modeling.py 37 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...